1 package org.varienaja.util.coverart;
2
3 import java.io.IOException;
4 import java.io.InputStreamReader;
5 import java.net.URI;
6 import java.net.URISyntaxException;
7 import java.util.LinkedList;
8 import java.util.List;
9
10 import org.apache.log4j.Logger;
11
12
13
14
15 public class YahooCoverArtFinder extends AbstractCoverArtFinder {
16 private static final Logger log = Logger.getLogger(YahooCoverArtFinder.class);
17 private int _spot;
18
19 @Override
20 public URI constructSearchURI(String band, String albumtitle) throws URISyntaxException {
21 return new URI("http",null,"images.search.yahoo.com/search/images",-1,null,
22 "ei=UTF-8&fr=sfp&p="+band+" "+albumtitle,null);
23 }
24
25
26
27
28
29
30
31
32
33
34
35
36
37 @Override
38 public List<CoverArtSearchResult> procesSearchResult(InputStreamReader in) throws IOException {
39 log.debug("Processing Yahoo-imagesearch response");
40 List<CoverArtSearchResult> results = new LinkedList<CoverArtSearchResult>();
41 StringBuilder sb = new StringBuilder();
42 char[] read = new char[255];
43 int count;
44 while ((count = in.read(read))!=-1) {
45 sb.append(read,0,count);
46 }
47
48
49 _spot = 1;
50 while ((_spot = sb.indexOf("http://rds.yahoo.com/"))>=0) {
51 CoverArtSearchResult casr = extractData(sb);
52 sb.delete(0,_spot+1);
53 if (casr!=null) {
54 results.add(casr);
55 }
56 }
57
58 return results;
59 }
60
61 private CoverArtSearchResult extractData(StringBuilder sb) {
62 CoverArtSearchResult casr = null;
63 try {
64 int start = sb.indexOf("imgurl=",_spot);
65 int end = sb.indexOf("rurl=",_spot);
66 if (start==-1 || end==-1) return casr;
67
68 String picurl = sb.substring(start+7,end-3);
69 picurl = "http://"+picurl.replaceAll("%252F","/").replaceAll("%252520","%20");
70
71
72 int width = 0;
73 int height = 0;
74 int size = 0;
75 try {
76 start = sb.indexOf("\"em\":\"",end);
77 end = sb.indexOf("\"",start+6);
78 String whs = sb.substring(start+6,end-1);
79 String[] parts = whs.split(" ");
80
81 width = Integer.parseInt(parts[0]);
82 height = Integer.parseInt(parts[2]);
83
84 String sze = parts[4].replaceAll("\\.","");
85 size = (1024*Integer.parseInt(sze));
86
87 } catch (IndexOutOfBoundsException e) {
88
89 } catch (NumberFormatException e) {
90
91 }
92
93 casr = new CoverArtSearchResult(picurl,width,height,size);
94 _spot = end;
95 log.debug("Image extracted: "+casr);
96 } catch (Exception e) {
97
98 log.error("Error extracting coverart-data: "+e);
99 }
100 return casr;
101 }
102
103
104
105
106
107 @Override
108 protected Logger getLogger() {
109 return log;
110 }
111
112 }