summaryrefslogtreecommitdiffstats
path: root/kaffeine/src/input/audiobrowser/googlefetcher.cpp
blob: f12d232fa7b9977c6cc362eb60238de77c7a5b21 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/*
 * googlefetcher.cpp
 *
 * Copyright (C) 2004 Nathan Toone <nathan@toonetown.com>
 * Copyright (C) 2006 Christophe Thommeret <hftom@free.fr>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include <dom/html_document.h>
#include <dom/html_misc.h>
#include <dom/html_table.h>
#include <dom/dom_exception.h>
#include <dom/dom2_traversal.h>

#include <tdehtml_part.h>

#include <klocale.h>
#include <kinputdialog.h>
#include <kurl.h>
#include <tdeio/netaccess.h>

#include "googlefetcher.h"
#include "googlefetcherdialog.h"

GoogleImage::GoogleImage(TQString thumbURL, TQString size)
{
    // thumbURL is in the following format - and we can regex the imageURL
    // images?q=tbn:hKSEWNB8aNcJ:www.styxnet.com/deyoung/styx/stygians/cp_portrait.jpg
    m_thumbURL = thumbURL.replace("\"","");
    m_imageURL = thumbURL.remove(TQRegExp("^.*q=tbn:[^:]*:")).replace("\"","");
    m_size = size.replace("pixels - ", "\n(") + ")";
}


GoogleFetcher::GoogleFetcher( TQString artist, TQString album, bool gallery )
{
  m_artist = artist;
  m_album = album;
  m_searchString = artist+" "+album;
  encoding = 0;
  galleryImage=galleryPage=0;
  galleryMode = gallery;
}

void GoogleFetcher::slotLoadImageURLs(GoogleFetcher::ImageSize size)
{
    if(m_loadedQuery == m_searchString && m_loadedSize == size)
        return;

    m_imageList.clear();

    KURL url("http://images.google.com/images");
    if ( encoding )
    	url.addQueryItem("q", m_searchString,encoding);
    else
    	url.addQueryItem("q", m_searchString);

    switch (size) {
        case XLarge:
            url.addQueryItem("imgsz", "xlarge|xxlarge");
            break;
        case Large:
            url.addQueryItem("imgsz", "large");
            break;
        case Medium:
            url.addQueryItem("imgsz", "medium");
            break;
        case Small:
            url.addQueryItem("imgsz", "small");
            break;
        case Icon:
            url.addQueryItem("imgsz", "icon");
            break;
        default:
            break;
    }

    m_loadedQuery = m_searchString;
    m_loadedSize = size;

    // We don't normally like exceptions but missing DOMException will kill
    // JuK rather abruptly whether we like it or not so we don't really have a
    // choice if we're going to screen-scrape Google.
    try {

    TDEHTMLPart part;

    // Create empty document.

    part.begin();
    part.end();

    DOM::Document search = part.document();
    search.setAsync(false); // Grab the document before proceeding.

    kdDebug() << "Performing Google Search: " << url << endl;

    search.load(url.url()+TQString("&start=%1&sa=N").arg(galleryPage*20) );

    TQString text = search.toString().string();

    if ( !hasImageResults(text) ) {
	kdDebug() << "Search returned no results.\n";
        emit signalNewSearch(m_imageList);
        return;
    }

    // Go through each of the top (table) nodes

    int pos = text.find("/imgres?imgurl");
    int tpos;
    TQString s, c;
    while ( pos>-1 ) {
        text = text.right( text.length()-pos-14 );
        tpos = text.find("&h=");
        text = text.right( text.length()-tpos-3 );
        tpos = text.find("&w=");
        c = "pixels - " + text.left( tpos );
        text = text.right( text.length()-tpos-3 );
        tpos = text.find("&sz=");
        c = c + "x" + text.left( tpos );
        tpos = text.find("src=");
        text = text.right( text.length()-tpos-4 );
        if ( (tpos=text.find("width="))==-1 )
        	break;
        s = text.left( tpos-1 );
        text = text.right( text.length()-tpos );
        if ( (tpos=text.find("></a>"))==-1 )
        	break;
	m_imageList.append(GoogleImage(s, c));
	pos = text.find("/imgres?imgurl");
    }
    } // try
    catch (DOM::DOMException &e)
    {
	kdError() << "Caught DOM Exception: " << e.code << endl;
    }
    catch (...)
    {
	kdError() << "Caught unknown exception.\n";
    }

    emit signalNewSearch(m_imageList);
}

TQImage GoogleFetcher::galleryNext( bool &end )
{
    TQString file;
    TQImage image;
    m_loadedSize = All;
    int tries = 0;
    end = false;

    while ( tries<3 ) {
    	if( m_imageList.isEmpty() ) {
    		if ( tries==0 ) {
    			encoding = 0;
    			m_loadedQuery = "";
    			++tries;
    			displayWaitMessage();
    		}
    		else if ( tries==1 ) {
    			encoding = 4; // try iso8859-1
    		    	m_loadedQuery = "";
    		    	++tries;
    		    	kdDebug() << "Trying iso8859-1" << endl;
        		displayWaitMessage();
       		 }
     		else {
        		end = true;
        		return TQImage();
        	}
    	}
    	else {
		if(TDEIO::NetAccess::download( m_imageList[galleryImage].imageURL(), file, 0))
        		image = TQImage(file);
        	else
        		image = TQImage();
        	++galleryImage;
        	if ( galleryImage==(int)m_imageList.count() ) {
        		m_imageList.clear();
        		galleryImage = 0;
        		++galleryPage;
        	}
        	TDEIO::NetAccess::removeTempFile(file);
        	return image;
    	}
    }
    return TQImage();
}

TQPixmap GoogleFetcher::pixmap( bool forceFetch )
{
    bool chosen = false;
    m_loadedSize = All;
    int tries = 0;

    encoding = 0;
    displayWaitMessage();

    TQPixmap pixmap;

    while(!chosen) {

        if(m_imageList.isEmpty())
            switch(tries) {
              case 0:
              	encoding = 4; // try iso8859-1
              	m_loadedQuery = "";
              	++tries;
              	kdDebug() << "Trying iso8859-1" << endl;
              	displayWaitMessage();
              	break;
              default :
		if ( forceFetch == true )
	              	chosen = !requestNewSearchTerms(true);
		else
			chosen = true;
            }
        else {
            GoogleFetcherDialog dialog("google", m_imageList, m_artist, m_album, 0);
            connect(&dialog, TQT_SIGNAL(sizeChanged(GoogleFetcher::ImageSize)),
                    this, TQT_SLOT(slotLoadImageURLs(GoogleFetcher::ImageSize)));
            connect(this, TQT_SIGNAL(signalNewSearch(GoogleImageList &)),
                    &dialog, TQT_SLOT(refreshScreen(GoogleImageList &)));
            dialog.exec();
            pixmap = dialog.result();
            chosen = dialog.takeIt();

            if(dialog.newSearch())
                requestNewSearchTerms();
        }
    }
    return pixmap;
}

void GoogleFetcher::displayWaitMessage()
{
    //KStatusBar *statusBar = static_cast<KMainWindow *>(kapp->mainWidget())->statusBar();
    //statusBar->message(i18n("Searching for Images. Please Wait..."));
    slotLoadImageURLs();
    //statusBar->clear();*/
}

bool GoogleFetcher::requestNewSearchTerms(bool noResults)
{
    bool ok;
    m_searchString = KInputDialog::getText(i18n("Cover Downloader"),
                                           noResults ?
                                             i18n("No matching images found, please enter new search terms:") :
                                             i18n("Enter new search terms:"),
                                           m_searchString, &ok);
    if(ok && !m_searchString.isEmpty())
        displayWaitMessage();
    else
        m_searchString = m_loadedQuery;

    return ok;
}

bool GoogleFetcher::hasImageResults( TQString &doc )
{
    if ( !doc.contains( "/imgres?imgurl" ) )
    	return false;

    return true;
}

#include "googlefetcher.moc"