package net.pms.util; import java.io.IOException; import java.net.URLEncoder; import java.util.HashMap; import net.pms.network.HTTPResource; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CoverUtil extends HTTPResource { private static final Logger logger = LoggerFactory.getLogger(CoverUtil.class); private static CoverUtil instance; private static byte[] lock = null; static { lock = new byte[0]; } public static CoverUtil get() { if (instance == null) { synchronized (lock) { if (instance == null) { instance = new CoverUtil(); } } } return instance; } private CoverUtil() { covers = new HashMap(); } private HashMap covers; public static final int AUDIO_DISCOGS = 0; public static final int AUDIO_AMAZON = 1; public synchronized byte[] getThumbnailFromArtistAlbum(int backend, String... info) throws IOException { if (info.length >= 2 && StringUtils.isNotBlank(info[0]) && StringUtils.isNotBlank(info[1])) { String artist = URLEncoder.encode(info[0], "UTF-8"); String album = URLEncoder.encode(info[1], "UTF-8"); if (covers.get(artist + album) != null) { byte data[] = covers.get(artist + album); if (data.length == 0) { return null; } else { return data; } } if (backend == AUDIO_DISCOGS) { String url = "http://www.discogs.com/advanced_search?artist=" + artist + "&release_title=" + album + "&btn=Search+Releases"; byte data[] = downloadAndSendBinary(url); if (data != null) { try { String html = new String(data, "UTF-8"); int firstItem = html.indexOf("
  • -1) { String detailUrl = html.substring(html.indexOf("", firstItem)); data = downloadAndSendBinary("http://www.discogs.com/" + detailUrl); html = new String(data, "UTF-8"); firstItem = html.indexOf(" -1) { String imageUrl = html.substring(html.indexOf(" -1) { int imageUrlPos = html.indexOf("src=\"", firstItem) + 5; String imageUrl = html.substring(imageUrlPos, html.indexOf("\" class", imageUrlPos)); data = downloadAndSendBinary(imageUrl); if (data != null) { covers.put(artist + album, data); } else { covers.put(artist + album, new byte[0]); } return data; } } catch (Exception e) { logger.error("Error while retrieving cover for " + artist + album, e); } } } covers.put(artist + album, new byte[0]); } return null; } }