Debian Codegraph @

src/context/engines/labels/LabelsEngine.cpp

raw
1 /****************************************************************************************
2 * Copyright (c) 2009 Simon Esneault <[email protected]> *
3 * Copyright (c) 2010 Daniel Faust <[email protected]> *
4 * *
5 * This program is free software; you can redistribute it and/or modify it under *
6 * the terms of the GNU General Public License as published by the Free Software *
7 * Foundation; either version 2 of the License, or (at your option) any later *
8 * version. *
9 * *
10 * This program is distributed in the hope that it will be useful, but WITHOUT ANY *
11 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
12 * PARTICULAR PURPOSE. See the GNU General Public License for more details. *
13 * *
14 * You should have received a copy of the GNU General Public License along with *
15 * this program. If not, see <http://www.gnu.org/licenses/>. *
16 ****************************************************************************************/
17
18 #define DEBUG_PREFIX "LabelsEngine"
19
20 #include "LabelsEngine.h"
21
22 #include "EngineController.h"
23 #include "context/ContextObserver.h"
24 #include "context/ContextView.h"
25 #include "core/collections/Collection.h"
26 #include "core/collections/QueryMaker.h"
27 #include "core/meta/Meta.h"
28 #include "core/support/Debug.h"
29 #include "core-impl/collections/support/CollectionManager.h"
30
31 #include <KIO/Job>
32 #include <KLocalizedString>
33
34 #include <QDomDocument>
35
36 using namespace Context;
37
38 LabelsEngine::LabelsEngine( QObject *parent, const QList<QVariant> &args )
39 : DataEngine( parent )
40 , ContextObserver( ContextView::self() )
41 {
42 Q_UNUSED( args )
43 m_sources << "lastfm" ;
44
45 m_timeoutTimer.setInterval( 10000 );
46 m_timeoutTimer.setSingleShot( true );
47 connect( &m_timeoutTimer, SIGNAL(timeout()), this, SLOT(timeout()) );
48
49 EngineController *engine = The::engineController();
50
51 connect( engine, SIGNAL(trackChanged(Meta::TrackPtr)),
52 this, SLOT(update()) );
53 connect( engine, SIGNAL(trackMetadataChanged(Meta::TrackPtr)),
54 this, SLOT(update()) );
55 }
56
57 LabelsEngine::~LabelsEngine()
58 {
59 DEBUG_BLOCK
60 }
61
62 QStringList
63 LabelsEngine::sources() const
64 {
65 return m_sources;
66 }
67
68 bool
69 LabelsEngine::sourceRequestEvent( const QString &name )
70 {
71 DEBUG_BLOCK
72
73 Collections::Collection *coll = CollectionManager::instance()->primaryCollection();
74 if( coll )
75 {
76 Collections::QueryMaker *qm = coll->queryMaker();
77 qm->setAutoDelete( true );
78 qm->setQueryType( Collections::QueryMaker::Label );
79 m_allLabels.clear();
80
81 connect( qm, SIGNAL(newResultReady(Meta::LabelList)),
82 SLOT(resultReady(Meta::LabelList)), Qt::QueuedConnection );
83 connect( qm, SIGNAL(queryDone()), SLOT(dataQueryDone()) );
84
85 qm->run();
86 }
87
88 update( name == "reload" );
89
90 return true;
91 }
92
93 void
94 LabelsEngine::resultReady( const Meta::LabelList &labels )
95 {
96 for( const Meta::LabelPtr &label : labels )
97 {
98 if( !label->name().isEmpty() )
99 m_allLabels << label->name();
100 }
101 }
102
103 void
104 LabelsEngine::dataQueryDone()
105 {
106 DEBUG_BLOCK
107 QVariant varAll;
108 varAll.setValue< QStringList >( m_allLabels );
109 setData( "labels", "all", varAll );
110 }
111
112 void
113 LabelsEngine::update( bool reload )
114 {
115 Meta::TrackPtr track = The::engineController()->currentTrack();
116
117 if( !track )
118 {
119 removeAllData( "labels" );
120 m_artist.clear();
121 m_title.clear();
122 m_album.clear();
123 m_userLabels.clear();
124 m_webLabels.clear();
125 setData( "labels", "state", "stopped" );
126 return;
127 }
128
129 const QString title = track->name();
130 Meta::ArtistPtr artist = track->artist();
131 if( !artist )
132 {
133 setData( "labels", "message", i18n( "No labels found on Last.fm" ) );
134 debug() << "track has no artist, returning";
135 return;
136 }
137
138 QStringList userLabels;
139
140 for( const Meta::LabelPtr &label : track->labels() )
141 userLabels += label->name();
142
143 userLabels.sort();
144 m_userLabels.sort();
145
146 // check what changed
147 if( !reload && artist->name() == m_artist && title == m_title && userLabels == m_userLabels )
148 {
149 // nothing important changed
150 return;
151 }
152 else if( !reload && artist->name() == m_artist && title == m_title )
153 {
154 // only the labels changed - no download necessary
155 debug() << "only the labels changed - no download necessary";
156 QVariant varUser;
157 varUser.setValue< QStringList >( userLabels );
158 setData( "labels", "user", varUser );
159 m_userLabels = userLabels;
160 return;
161 }
162
163 removeAllData( "labels" );
164 setData( "labels", "state", "started" );
165
166 m_artist = artist->name();
167 m_title = title;
168 if( track->album() )
169 m_album = track->album()->name();
170 else
171 m_album.clear();
172
173 m_userLabels = userLabels;
174 m_webLabels.clear();
175
176 QVariant varUser;
177 varUser.setValue< QStringList >( m_userLabels );
178 setData( "labels", "user", varUser );
179
180 m_try = 0;
181 fetchLastFm();
182 }
183
184 void
185 LabelsEngine::fetchLastFm()
186 {
187 QStringList separators;
188 QString currentArtist;
189 QString currentTitle;
190
191 if( m_title.isEmpty() || m_artist.isEmpty() )
192 {
193 // stop timeout timer
194 m_timeoutTimer.stop();
195 setData( "labels", "message", i18n( "No labels found on Last.fm" ) );
196 debug() << "current track is invalid, returning";
197 return;
198 }
199
200 if( m_try == 0 )
201 {
202 currentArtist = m_artist;
203 currentTitle = m_title;
204 m_timeoutTimer.start();
205 }
206 else if( m_try == 1 )
207 {
208 currentArtist = m_artist;
209 currentTitle = m_title;
210 separators.clear();
211 separators << " (" << " [" << " - " << " featuring " << " feat. " << " feat " << " ft. " << " ft " << "/";
212 for( const QString &separator : separators )
213 {
214 if( m_title.contains(separator,Qt::CaseInsensitive) )
215 {
216 currentTitle = m_title.left( m_title.indexOf(separator,0,Qt::CaseInsensitive) );
217 break;
218 }
219 }
220 if ( currentTitle == m_title )
221 {
222 debug() << "try 2: title is the same, retrying";
223 m_try++;
224 fetchLastFm();
225 return;
226 }
227 }
228 else if( m_try == 2 )
229 {
230 currentArtist = m_artist;
231 currentTitle = m_title;
232 separators.clear();
233 separators << " vs. " << " vs " << " featuring " << " feat. " << " feat " << " ft. " << " ft " << ", " << " and " << " & " << "/";
234 for( const QString &separator : separators )
235 {
236 if( m_artist.contains(separator,Qt::CaseInsensitive) )
237 {
238 currentArtist = m_artist.left( m_artist.indexOf(separator,0,Qt::CaseInsensitive) );
239 break;
240 }
241 }
242 separators.clear();
243 separators << " (" << " [" << " - " << " featuring " << " feat. " << " feat " << " ft. " << " ft " << "/";
244 for( const QString &separator : separators )
245 {
246 if( m_title.contains(separator,Qt::CaseInsensitive) )
247 {
248 currentTitle = m_title.left( m_title.indexOf(separator,0,Qt::CaseInsensitive) );
249 break;
250 }
251 }
252 if( currentArtist == m_artist ) // the title got modified the same way as on the last try
253 {
254 // stop timeout timer
255 m_timeoutTimer.stop();
256 setData( "labels", "message", i18n( "No labels found on Last.fm" ) );
257 debug() << "try 3: artist and title are the same, returning";
258 return;
259 }
260 }
261 else
262 {
263 // shouldn't happen
264 // stop timeout timer
265 m_timeoutTimer.stop();
266 setData( "labels", "message", i18n( "No labels found on Last.fm" ) );
267 debug() << "try > 2, returning";
268 return;
269 }
270
271 if( !currentArtist.isEmpty() && !currentTitle.isEmpty() )
272 {
273 setData( "labels", "message", "fetching");
274 // send the artist and title actually used for searching labels
275 setData( "labels", "artist", currentArtist );
276 setData( "labels", "title", currentTitle );
277 setData( "labels", "album", m_album );
278
279 // Query lastfm
280 QUrl lastFmUrl;
281 lastFmUrl.setScheme( "http" );
282 lastFmUrl.setHost( "ws.audioscrobbler.com" );
283 lastFmUrl.setPath( "/2.0/" );
284 lastFmUrl.addQueryItem( "method", "track.gettoptags" );
285 lastFmUrl.addQueryItem( "api_key", "402d3ca8e9bc9d3cf9b85e1202944ca5" );
286 lastFmUrl.addQueryItem( "artist", currentArtist.toLocal8Bit() );
287 lastFmUrl.addQueryItem( "track", currentTitle.toLocal8Bit() );
288 m_lastFmUrl = lastFmUrl;
289
290 QNetworkRequest req( lastFmUrl );
291 // req.setAttribute( QNetworkRequest::ConnectionEncryptedAttribute, QNetworkRequest::AlwaysNetwork );
292 The::networkAccessManager()->get( req );
293 The::networkAccessManager()->getData( lastFmUrl, this,
294 SLOT(resultLastFm(QUrl,QByteArray,NetworkAccessManagerProxy::Error)) );
295 }
296 else
297 {
298 // stop timeout timer
299 m_timeoutTimer.stop();
300 setData( "labels", "message", i18n( "No labels found on Last.fm" ) );
301 debug() << "artist or track empty";
302 }
303 }
304
305 void LabelsEngine::resultLastFm( const QUrl &url, QByteArray data, NetworkAccessManagerProxy::Error e )
306 {
307 DEBUG_BLOCK;
308
309 if( m_lastFmUrl != url )
310 {
311 debug() << "urls not matching, returning";
312 return;
313 }
314
315 if( e.code != QNetworkReply::NoError )
316 {
317 // stop timeout timer
318 m_timeoutTimer.stop();
319 setData( "labels", "message", i18n( "Unable to retrieve from Last.fm" ) );
320 debug() << "Unable to retrieve last.fm information: " << e.description;
321 return;
322 }
323
324 QDomDocument xmlDoc;
325 xmlDoc.setContent( data );
326 const QDomElement topElement = xmlDoc.elementsByTagName("toptags").at(0).toElement();
327 const QDomNodeList xmlNodeList = topElement.elementsByTagName( "tag" );
328
329 for( uint i = 0; i < xmlNodeList.length(); i++ )
330 {
331 // Get all the information
332 const QDomElement nd = xmlNodeList.at( i ).toElement();
333 const QDomElement nameElement = nd.elementsByTagName("name").at(0).toElement();
334 const QString name = nameElement.text().toLower();
335 const QDomElement countElement = nd.elementsByTagName("count").at(0).toElement();
336 const int count = countElement.text().toInt();
337 m_webLabels.insert( name, count );
338 }
339
340 if( m_webLabels.isEmpty() )
341 {
342 if( m_try < 2 )
343 {
344 m_try++;
345 fetchLastFm();
346 }
347 else
348 {
349 // stop timeout timer
350 m_timeoutTimer.stop();
351 setData( "labels", "message", i18n( "No labels found on Last.fm" ) );
352 }
353 }
354 else
355 {
356 // remove previous message
357 removeData( "labels", "message" );
358 // stop timeout timer
359 m_timeoutTimer.stop();
360
361 QVariant varWeb;
362 varWeb.setValue< QMap< QString, QVariant > > ( m_webLabels );
363 setData( "labels", "web", varWeb );
364 }
365 }
366
367 void LabelsEngine::timeout()
368 {
369 setData( "labels", "message", i18n( "No connection to Last.fm" ) );
370 }
371
372
373