summaryrefslogtreecommitdiffstats
path: root/juk/webimagefetcher.cpp
blob: f8445bc3f850defd9123c02065a988c0db4a706a (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
/***************************************************************************
    copyright            : (C) 2004 Nathan Toone <[email protected]>
    copyright            : (C) 2007 Michael Pyne <[email protected]>
***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include <tqhttp.h>
#include <tqdom.h>
#include <tqwaitcondition.h>

#include <kapplication.h>
#include <kstatusbar.h>
#include <kdebug.h>
#include <kmainwindow.h>
#include <klocale.h>
#include <kinputdialog.h>
#include <kurl.h>

#include "covermanager.h"
#include "webimagefetcher.h"
#include "webimagefetcherdialog.h"
#include "tag.h"

WebImage::WebImage()
{
}

WebImage::WebImage(const TQString &imageURL, const TQString &thumbURL,
                         int width, int height) :
    m_imageURL(imageURL),
    m_thumbURL(thumbURL),
    m_size(TQString("\n%1 x %2").tqarg(width).tqarg(height))
{
}


WebImageFetcher::WebImageFetcher(TQObject *tqparent)
    : TQObject(tqparent),
      m_connection(new TQHttp(this)),
      m_connectionId(-1),
      m_dialog(0)
{
    connect(m_connection, TQT_SIGNAL(requestFinished(int,bool)), TQT_SLOT(slotWebRequestFinished(int,bool)));
}

WebImageFetcher::~WebImageFetcher()
{
    delete m_dialog;
}

void WebImageFetcher::setFile(const FileHandle &file)
{
    m_file = file;
    m_searchString = TQString(file.tag()->artist() + ' ' + file.tag()->album());

    if(m_dialog)
	m_dialog->setFile(file);
}

void WebImageFetcher::abortSearch()
{
    m_connection->abort();
}

void WebImageFetcher::chooseCover()
{
    slotLoadImageURLs();
}

void WebImageFetcher::slotLoadImageURLs()
{
    m_imageList.clear();

    KURL url("http://search.yahooapis.com/ImageSearchService/V1/imageSearch");
    url.addQueryItem("appid", "org.kde.juk/kde3");
    url.addQueryItem("query", m_searchString);
    url.addQueryItem("results", "25");

    kdDebug(65432) << "Using request " << url.encodedPathAndQuery() << endl;

    m_connection->setHost(url.host());
    m_connectionId = m_connection->get(url.encodedPathAndQuery());

    // Wait for the results...
}

void WebImageFetcher::slotWebRequestFinished(int id, bool error)
{
    if(id != m_connectionId)
	return;

    if(error) {
	kdError(65432) << "Error reading image results from Yahoo!\n";
	kdError(65432) << m_connection->errorString() << endl;
	return;
    }

    TQDomDocument results("ResultSet");

    TQString errorStr;
    int errorCol, errorLine;
    if(!results.setContent(m_connection->readAll(), &errorStr, &errorLine, &errorCol)) {
	kdError(65432) << "Unable to create XML document from Yahoo results.\n";
	kdError(65432) << "Line " << errorLine << ", " << errorStr << endl;
	return;
    }

    TQDomNode n = results.documentElement();

    bool hasNoResults = false;

    if(n.isNull()) {
	kdDebug(65432) << "No document root in XML results??\n";
	hasNoResults = true;
    }
    else {
	TQDomElement result = n.toElement();
	if(result.attribute("totalResultsReturned").toInt() == 0)
	    kdDebug(65432) << "Search returned " << result.attribute("totalResultsAvailable") << " results.\n";

	if(result.isNull() || !result.hasAttribute("totalResultsReturned") ||
	    result.attribute("totalResultsReturned").toInt() == 0)
	{
	    hasNoResults = true;
	}
    }

    if(hasNoResults)
    {
	kdDebug(65432) << "Search returned no results.\n";
	requestNewSearchTerms(true /* no results */);
        return;
    }

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

    n = n.firstChild();
    while(!n.isNull()) {
	TQDomNode resultUrl = n.namedItem("Url");
	TQDomNode thumbnail = n.namedItem("Thumbnail");
	TQDomNode height = n.namedItem("Height");
	TQDomNode width = n.namedItem("Width");

	// We have the necessary info, move to next node before we forget.
	n = n.nextSibling();

	if(resultUrl.isNull() || thumbnail.isNull() || height.isNull() || width.isNull()) {
	    kdError(65432) << "Invalid result returned, skipping.\n";
	    continue;
	}

	m_imageList.append(
	    WebImage(
	        resultUrl.toElement().text(),
		thumbnail.namedItem("Url").toElement().text(),
		width.toElement().text().toInt(),
		height.toElement().text().toInt()
	    )
	);
    }

    // Have results, show them and pick one.

    if(!m_dialog) {
        m_dialog = new WebImageFetcherDialog(m_imageList, m_file, 0);
	m_dialog->setModal(true);

	connect(m_dialog, TQT_SIGNAL(coverSelected()), TQT_SLOT(slotCoverChosen()));
	connect(m_dialog, TQT_SIGNAL(newSearchRequested()), TQT_SLOT(slotNewSearch()));
    }

    m_dialog->refreshScreen(m_imageList);
    m_dialog->show();
}

void WebImageFetcher::slotCoverChosen()
{
    TQPixmap pixmap = m_dialog->result();
    if(pixmap.isNull()) {
	kdError(65432) << "Selected pixmap is null for some reason.\n";
	return;
    }

    kdDebug(65432) << "Adding new cover for " << m_file.tag()->fileName() << endl;
    coverKey newId = CoverManager::addCover(pixmap, m_file.tag()->artist(), m_file.tag()->album());
    emit signalCoverChanged(newId);
}

void WebImageFetcher::slotNewSearch()
{
    requestNewSearchTerms();
}

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

void WebImageFetcher::requestNewSearchTerms(bool noResults)
{
    bool ok;
    TQString search = 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 && !search.isEmpty()) {
	m_searchString = search;
        displayWaitMessage(); // This kicks off the new search.
    }
}

#include "webimagefetcher.moc"