ktrm.cpp 15.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/***************************************************************************
    copyright            : (C) 2004 by Scott Wheeler
    email                : wheeler@kde.org
 ***************************************************************************/

/***************************************************************************
 *   This library is free software; you can redistribute it and/or modify  *
 *   it  under the terms of the GNU Lesser General Public License version  *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   This library 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     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
18
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
19 20 21 22
 *   USA                                                                   *
 ***************************************************************************/

#include "ktrm.h"
23
#include <config-juk.h>
Tim Beaulen's avatar
Tim Beaulen committed
24
#ifdef HAVE_TUNEPIMP //Silence warning about HAVE_TUNEPIMP not being defined.
25
#if HAVE_TUNEPIMP
26 27

#include <kapplication.h>
28
#include <kresolver.h>
29 30 31 32 33
#include <kprotocolmanager.h>
#include <kurl.h>
#include <kdebug.h>

#include <qmutex.h>
34
#include <QRegExp>
35
#include <qevent.h>
36
#include <QObject>
37
#include <QFile>
Laurent Montel's avatar
Laurent Montel committed
38
#include <QCustomEvent>
39 40

#include <tunepimp/tp_c.h>
Stephan Kulow's avatar
Stephan Kulow committed
41
#include <fixx11h.h>
42 43 44 45 46

class KTRMLookup;

extern "C"
{
47
#if HAVE_TUNEPIMP >= 4
48 49
    static void TRMNotifyCallback(tunepimp_t pimp, void *data, TPCallbackEnum type, int fileId, TPFileStatus status);
#else
50
    static void TRMNotifyCallback(tunepimp_t pimp, void *data, TPCallbackEnum type, int fileId);
51
#endif
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
}

/**
 * This represents the main TunePimp instance and handles incoming requests.
 */

class KTRMRequestHandler
{
public:
    static KTRMRequestHandler *instance()
    {
        static QMutex mutex;
        mutex.lock();
        static KTRMRequestHandler handler;
        mutex.unlock();
        return &handler;
    }

70
    int startLookup(KTRMLookup *lookup)
71
    {
72 73 74
        int id;

        if(!m_fileMap.contains(lookup->file())) {
75
#if HAVE_TUNEPIMP >= 4
76 77
            id = tp_AddFile(m_pimp, QFile::encodeName(lookup->file()), 0);
#else
78
            id = tp_AddFile(m_pimp, QFile::encodeName(lookup->file()));
79
#endif
80 81 82 83 84 85
            m_fileMap.insert(lookup->file(), id);
        }
        else {
            id = m_fileMap[lookup->file()];
            tp_IdentifyAgain(m_pimp, id);
        }
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
        m_lookupMap[id] = lookup;
        return id;
    }

    void endLookup(KTRMLookup *lookup)
    {
        tp_ReleaseTrack(m_pimp, tp_GetTrack(m_pimp, lookup->fileId()));
        tp_Remove(m_pimp, lookup->fileId());
        m_lookupMap.remove(lookup->fileId());
    }

    bool lookupMapContains(int fileId) const
    {
        m_lookupMapMutex.lock();
        bool contains = m_lookupMap.contains(fileId);
        m_lookupMapMutex.unlock();
        return contains;
    }

    KTRMLookup *lookup(int fileId) const
    {
        m_lookupMapMutex.lock();
        KTRMLookup *l = m_lookupMap[fileId];
        m_lookupMapMutex.unlock();
        return l;
    }

    void removeFromLookupMap(int fileId)
    {
        m_lookupMapMutex.lock();
        m_lookupMap.remove(fileId);
        m_lookupMapMutex.unlock();
    }

    const tunepimp_t &tunePimp() const
    {
        return m_pimp;
    }

protected:
    KTRMRequestHandler()
    {
        m_pimp = tp_New("KTRM", "0.1");
129
        //tp_SetDebug(m_pimp, true);
130 131 132 133
        tp_SetTRMCollisionThreshold(m_pimp, 100);
        tp_SetAutoSaveThreshold(m_pimp, -1);
        tp_SetMoveFiles(m_pimp, false);
        tp_SetRenameFiles(m_pimp, false);
134
#if HAVE_TUNEPIMP >= 4
135 136
        tp_SetFileNameEncoding(m_pimp, "UTF-8");
#else
137
        tp_SetUseUTF8(m_pimp, true);
138
#endif
139 140
        tp_SetNotifyCallback(m_pimp, TRMNotifyCallback, 0);

141 142 143
        // Re-read proxy config.
        KProtocolManager::reparseConfiguration();

144
        if(KProtocolManager::useProxy()) {
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
            // split code copied from kcm_kio.
            QString noProxiesFor = KProtocolManager::noProxyFor();
            QStringList noProxies = QStringList::split(QRegExp("[',''\t'' ']"), noProxiesFor);
            bool useProxy = true;

            // Host that libtunepimp will contact.
            QString tunepimpHost = "www.musicbrainz.org";
            QString tunepimpHostWithPort = "www.musicbrainz.org:80";

            // Check what hosts are allowed to proceed without being proxied,
            // or is using reversed proxy, what hosts must be proxied.
            for(QStringList::ConstIterator it = noProxies.constBegin(); it != noProxies.constEnd(); ++it) {
                QString normalizedHost = KNetwork::KResolver::normalizeDomain(*it);

                if(normalizedHost == tunepimpHost ||
160
                   tunepimpHost.endsWith('.' + normalizedHost))
161 162 163 164 165 166 167 168
                {
                    useProxy = false;
                    break;
                }

                // KDE's proxy mechanism also supports exempting a specific
                // host/port combo, check that also.
                if(normalizedHost == tunepimpHostWithPort ||
169
                   tunepimpHostWithPort.endsWith('.' + normalizedHost))
170 171 172 173 174 175 176 177 178 179 180
                {
                    useProxy = false;
                    break;
                }
            }

            // KDE supports a reverse proxy mechanism.  Uh, yay.
            if(KProtocolManager::useReverseProxy())
                useProxy = !useProxy;

            if(useProxy) {
181
                KUrl proxy = KProtocolManager::proxyFor("http");
182 183
                QString proxyHost = proxy.host();

Scott Wheeler's avatar
Scott Wheeler committed
184
                kDebug(65432) << "Using proxy server " << proxyHost << " for www.musicbrainz.org.\n";
Dirk Mueller's avatar
Dirk Mueller committed
185
                tp_SetProxy(m_pimp, proxyHost.toAscii(), short(proxy.port()));
186
            }
187 188 189 190 191 192 193 194 195 196
        }
    }

    ~KTRMRequestHandler()
    {
        tp_Delete(m_pimp);
    }

private:
    tunepimp_t m_pimp;
197 198
    QMap<int, KTRMLookup *> m_lookupMap;
    QMap<QString, int> m_fileMap;
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
    mutable QMutex m_lookupMapMutex;
};


/**
 * A custom event type used for signalling that a TRM lookup is finished.
 */

class KTRMEvent : public QCustomEvent
{
public:
    enum Status {
        Recognized,
        Unrecognized,
        Collision,
        Error
    };

    KTRMEvent(int fileId, Status status) :
        QCustomEvent(id),
        m_fileId(fileId),
        m_status(status) {}

    int fileId() const
    {
        return m_fileId;
    }

    Status status() const
    {
        return m_status;
    }

    static const int id = User + 1984; // random, unique, event id

private:
    int m_fileId;
    Status m_status;
};

/**
 * A helper class to intercept KTRMQueryEvents and call recognized() (from the GUI
 * thread) for the lookup.
 */

class KTRMEventHandler : public QObject
{
public:
    static void send(int fileId, KTRMEvent::Status status)
    {
        KApplication::postEvent(instance(), new KTRMEvent(fileId, status));
    }

protected:
    KTRMEventHandler() : QObject() {}

    static KTRMEventHandler *instance()
    {
        static QMutex mutex;
        mutex.lock();
        static KTRMEventHandler handler;
        mutex.unlock();
        return &handler;
    }

    virtual void customEvent(QCustomEvent *event)
    {
        if(!event->type() == KTRMEvent::id)
            return;

        KTRMEvent *e = static_cast<KTRMEvent *>(event);

        static QMutex mutex;
        mutex.lock();

        if(!KTRMRequestHandler::instance()->lookupMapContains(e->fileId())) {
            mutex.unlock();
            return;
        }

        KTRMLookup *lookup = KTRMRequestHandler::instance()->lookup(e->fileId());
280
#if HAVE_TUNEPIMP >= 4
281 282 283
        if ( e->status() != KTRMEvent::Unrecognized)
#endif
            KTRMRequestHandler::instance()->removeFromLookupMap(e->fileId());
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304

        mutex.unlock();

        switch(e->status()) {
        case KTRMEvent::Recognized:
            lookup->recognized();
            break;
        case KTRMEvent::Unrecognized:
            lookup->unrecognized();
            break;
        case KTRMEvent::Collision:
            lookup->collision();
            break;
        case KTRMEvent::Error:
            lookup->error();
            break;
        }
    }
};

/**
305
 * Callback function for TunePimp lookup events.
306
 */
307
#if HAVE_TUNEPIMP >= 4
308
static void TRMNotifyCallback(tunepimp_t /*pimp*/, void * /*data*/, TPCallbackEnum type, int fileId, TPFileStatus status)
309 310 311
#else
static void TRMNotifyCallback(tunepimp_t pimp, void *data, TPCallbackEnum type, int fileId)
#endif
312 313 314 315
{
    if(type != tpFileChanged)
        return;

316
#if HAVE_TUNEPIMP < 4
317
    track_t track = tp_GetTrack(pimp, fileId);
318
    TPFileStatus status = tr_GetStatus(track);
319
#endif
320 321 322 323 324 325 326 327 328

    switch(status) {
    case eRecognized:
        KTRMEventHandler::send(fileId, KTRMEvent::Recognized);
        break;
    case eUnrecognized:
        KTRMEventHandler::send(fileId, KTRMEvent::Unrecognized);
        break;
    case eTRMCollision:
329
#if HAVE_TUNEPIMP >= 4
330 331
    case eUserSelection:
#endif
332 333 334 335 336 337 338 339
        KTRMEventHandler::send(fileId, KTRMEvent::Collision);
        break;
    case eError:
        KTRMEventHandler::send(fileId, KTRMEvent::Error);
        break;
    default:
        break;
    }
340
#if HAVE_TUNEPIMP < 4
341 342
    tp_ReleaseTrack(pimp, track);
#endif
343 344
}

Scott Wheeler's avatar
Scott Wheeler committed
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
////////////////////////////////////////////////////////////////////////////////
// KTRMResult implementation
////////////////////////////////////////////////////////////////////////////////

class KTRMResult::KTRMResultPrivate
{
public:
    KTRMResultPrivate() : track(0), year(0), relevance(0) {}
    QString title;
    QString artist;
    QString album;
    int track;
    int year;
    int relevance;
};

////////////////////////////////////////////////////////////////////////////////
// KTRMResult public methods
////////////////////////////////////////////////////////////////////////////////

KTRMResult::KTRMResult()
{
    d = new KTRMResultPrivate;
}

KTRMResult::KTRMResult(const KTRMResult &result)
{
    d = new KTRMResultPrivate(*result.d);
}

KTRMResult::~KTRMResult()
{
    delete d;
}

QString KTRMResult::title() const
{
    return d->title;
}

QString KTRMResult::artist() const
{
    return d->artist;
}

QString KTRMResult::album() const
{
    return d->album;
}

int KTRMResult::track() const
{
    return d->track;
}

int KTRMResult::year() const
{
    return d->year;
}

bool KTRMResult::operator<(const KTRMResult &r) const
{
    return r.d->relevance < d->relevance;
}

bool KTRMResult::operator>(const KTRMResult &r) const
{
    return r.d->relevance > d->relevance;
}

bool KTRMResult::isEmpty() const
{
    return d->title.isEmpty() && d->artist.isEmpty() && d->album.isEmpty() &&
        d->track == 0 && d->year == 0;
}

////////////////////////////////////////////////////////////////////////////////
// KTRMLookup implementation
////////////////////////////////////////////////////////////////////////////////

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
class KTRMLookup::KTRMLookupPrivate
{
public:
    KTRMLookupPrivate() :
        fileId(-1) {}
    QString file;
    KTRMResultList results;
    int fileId;
    bool autoDelete;
};

////////////////////////////////////////////////////////////////////////////////
// KTRMLookup public methods
////////////////////////////////////////////////////////////////////////////////

KTRMLookup::KTRMLookup(const QString &file, bool autoDelete)
{
    d = new KTRMLookupPrivate;
    d->file = file;
    d->autoDelete = autoDelete;
    d->fileId = KTRMRequestHandler::instance()->startLookup(this);
}

KTRMLookup::~KTRMLookup()
{
    KTRMRequestHandler::instance()->endLookup(this);
    delete d;
}

QString KTRMLookup::file() const
{
    return d->file;
}

int KTRMLookup::fileId() const
{
    return d->fileId;
}

void KTRMLookup::recognized()
{
Scott Wheeler's avatar
Scott Wheeler committed
466
    kDebug() << k_funcinfo << d->file << endl;
467 468 469 470 471

    d->results.clear();

    metadata_t *metaData = md_New();
    track_t track = tp_GetTrack(KTRMRequestHandler::instance()->tunePimp(), d->fileId);
472
    tr_Lock(track);
473 474 475 476
    tr_GetServerMetadata(track, metaData);

    KTRMResult result;

Scott Wheeler's avatar
Scott Wheeler committed
477 478 479 480 481
    result.d->title = QString::fromUtf8(metaData->track);
    result.d->artist = QString::fromUtf8(metaData->artist);
    result.d->album = QString::fromUtf8(metaData->album);
    result.d->track = metaData->trackNum;
    result.d->year = metaData->releaseYear;
482 483 484 485

    d->results.append(result);

    md_Delete(metaData);
486
    tr_Unlock(track);
487 488 489 490 491
    finished();
}

void KTRMLookup::unrecognized()
{
Scott Wheeler's avatar
Scott Wheeler committed
492
    kDebug() << k_funcinfo << d->file << endl;
493
#if HAVE_TUNEPIMP >= 4
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
    char trm[255];
    bool finish = false;
    trm[0] = 0;
    track_t track = tp_GetTrack(KTRMRequestHandler::instance()->tunePimp(), d->fileId);
    tr_Lock(track);
    tr_GetTRM(track, trm, 255);
    if ( !trm[0] ) {
        tr_SetStatus(track, ePending);
        tp_Wake(KTRMRequestHandler::instance()->tunePimp(), track);
    }
    else
        finish = true;
    tr_Unlock(track);
    tp_ReleaseTrack(KTRMRequestHandler::instance()->tunePimp(), track);
    if ( !finish )
       return;
#endif
511 512 513 514 515 516
    d->results.clear();
    finished();
}

void KTRMLookup::collision()
{
Scott Wheeler's avatar
Scott Wheeler committed
517
    kDebug() << k_funcinfo << d->file << endl;
518 519 520 521

    track_t track = tp_GetTrack(KTRMRequestHandler::instance()->tunePimp(), d->fileId);

    if(track <= 0) {
Scott Wheeler's avatar
Scott Wheeler committed
522
        kDebug() << "invalid track number" << endl;
523 524 525 526 527 528
        return;
    }

    tr_Lock(track);
    int resultCount = tr_GetNumResults(track);

529
    if(resultCount > 0) {
530 531 532 533 534 535
        TPResultType type;
        result_t *results = new result_t[resultCount];
        tr_GetResults(track, &type, results, &resultCount);

        switch(type) {
        case eNone:
Scott Wheeler's avatar
Scott Wheeler committed
536
            kDebug() << k_funcinfo << "eNone" << endl;
537 538
            break;
        case eArtistList:
Scott Wheeler's avatar
Scott Wheeler committed
539
            kDebug() << "eArtistList" << endl;
540 541
            break;
        case eAlbumList:
Scott Wheeler's avatar
Scott Wheeler committed
542
            kDebug() << "eAlbumList" << endl;
543 544 545
            break;
        case eTrackList:
        {
Scott Wheeler's avatar
Scott Wheeler committed
546
            kDebug() << "eTrackList" << endl;
547 548 549 550 551 552
            albumtrackresult_t **tracks = (albumtrackresult_t **) results;
            d->results.clear();

            for(int i = 0; i < resultCount; i++) {
                KTRMResult result;

Scott Wheeler's avatar
Scott Wheeler committed
553
                result.d->title = QString::fromUtf8(tracks[i]->name);
554
#if HAVE_TUNEPIMP >= 4
555 556 557
                result.d->artist = QString::fromUtf8(tracks[i]->artist.name);
                result.d->album = QString::fromUtf8(tracks[i]->album.name);
                result.d->year = tracks[i]->album.releaseYear;
558
#else
Scott Wheeler's avatar
Scott Wheeler committed
559 560 561
                result.d->artist = QString::fromUtf8(tracks[i]->artist->name);
                result.d->album = QString::fromUtf8(tracks[i]->album->name);
                result.d->year = tracks[i]->album->releaseYear;
562 563
#endif
                result.d->track = tracks[i]->trackNum;
Scott Wheeler's avatar
Scott Wheeler committed
564
                result.d->relevance = tracks[i]->relevance;
565 566 567 568 569 570

                d->results.append(result);
            }
            break;
        }
        case eMatchedTrack:
Scott Wheeler's avatar
Scott Wheeler committed
571
            kDebug() << k_funcinfo << "eMatchedTrack" << endl;
572 573 574 575 576 577 578 579 580 581 582 583 584
            break;
        }

        delete [] results;
    }

    tr_Unlock(track);

    finished();
}

void KTRMLookup::error()
{
Scott Wheeler's avatar
Scott Wheeler committed
585
    kDebug() << k_funcinfo << d->file << endl;
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605

    d->results.clear();
    finished();
}

KTRMResultList KTRMLookup::results() const
{
    return d->results;
}

////////////////////////////////////////////////////////////////////////////////
// KTRMLookup protected methods
////////////////////////////////////////////////////////////////////////////////

void KTRMLookup::finished()
{
    if(d->autoDelete)
        delete this;
}

Tim Beaulen's avatar
Tim Beaulen committed
606
#endif
607
#endif
608

609
// vim: set et sw=4 tw=0 sta: