scrobbler.cpp 9.03 KB
Newer Older
1 2
/**
 * Copyright (C) 2012 Martin Sandsmark <martin.sandsmark@kde.org>
3
 * Copyright (C) 2014 Arnold Dumas <contact@arnolddumas.fr>
4 5 6 7 8 9 10 11 12 13 14 15 16
 *
 * 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, see <http://www.gnu.org/licenses/>.
 */
17

18
#include "scrobbler.h"
19

20
#include <QCryptographicHash>
21
#include <QDir>
22 23 24 25
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QDomDocument>
26
#include <QByteArray>
27 28 29 30 31 32 33

#include <kglobal.h>
#include <kconfiggroup.h>
#include <KDebug>
#include <KSharedConfig>
#include <KSharedPtr>

34 35
#include "tag.h"

36 37
Scrobbler::Scrobbler(QObject* parent)
    : QObject(parent)
38
    , m_networkAccessManager(0)
39
    , m_wallet(0)
40
{
41
    QByteArray sessionKey;
42

43 44 45 46 47 48 49 50 51 52 53
    m_wallet = Scrobbler::openKWallet();

    if (m_wallet) {

        m_wallet->readEntry("SessionKey", sessionKey);

    } else {

        KConfigGroup config(KGlobal::config(), "Scrobbling");
        sessionKey.append(config.readEntry("SessionKey", ""));
    }
54 55

    if(sessionKey.isEmpty())
56 57 58 59 60
        getAuthToken();
}

Scrobbler::~Scrobbler()
{
61
    delete m_wallet;
62 63
}

64 65
bool Scrobbler::isScrobblingEnabled()
{
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
    QString username, password;

    if (KWallet::Wallet::folderDoesNotExist(KWallet::Wallet::LocalWallet(), "JuK")) {

        KConfigGroup config(KGlobal::config(), "Scrobbling");

        username = config.readEntry("Username", "");
        password = config.readEntry("Password", "");

    } else {

        KWallet::Wallet* wallet = Scrobbler::openKWallet();

        if (wallet) {

            QMap<QString, QString> scrobblingCredentials;
            wallet->readMap("Scrobbling", scrobblingCredentials);
83

84 85 86 87 88 89 90 91 92
            if (scrobblingCredentials.contains("Username") && scrobblingCredentials.contains("Password")) {

                username = scrobblingCredentials["Username"];
                password = scrobblingCredentials["Password"];
            }

            delete wallet;
        }
    }
93 94 95 96

    return (!username.isEmpty() && !password.isEmpty());
}

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
KWallet::Wallet* Scrobbler::openKWallet() // static
{
    const QString walletFolderName = "JuK";

    KWallet::Wallet* wallet = KWallet::Wallet::openWallet(KWallet::Wallet::LocalWallet(), 0);

    if (wallet) {

        if (!wallet->hasFolder(walletFolderName)) {

            if (!wallet->createFolder(walletFolderName)) {

                delete wallet;
                return 0;
            }
        }

        if (!wallet->setFolder(walletFolderName)) {

            delete wallet;
            return 0;
        }
    }

    return wallet;
}

124 125
QByteArray Scrobbler::md5(QByteArray data)
{
126 127
    return QCryptographicHash::hash(data, QCryptographicHash::Md5)
        .toHex().rightJustified(32, '0').toLower();
128 129 130 131
}

void Scrobbler::sign(QMap< QString, QString >& params)
{
132 133
    params["api_key"] = "3e6ecbd7284883089e8f2b5b53b0aecd";

134
    QString s;
135 136 137
    QMapIterator<QString, QString> i(params);

    while(i.hasNext()) {
138 139 140
        i.next();
        s += i.key() + i.value();
    }
141

142
    s += "2cab3957b1f70d485e9815ac1ac94096"; //shared secret
143

144 145 146
    params["api_sig"] = md5(s.toUtf8());
}

147 148
void Scrobbler::getAuthToken(QString username, QString password)
{
149 150
    kDebug() << "Getting new auth token for user:" << username;

151
    QByteArray authToken = md5((username + md5(password.toUtf8())).toUtf8());
152

153 154
    QMap<QString, QString> params;
    params["method"]    = "auth.getMobileSession";
155
    params["authToken"] = authToken;
156 157
    params["username"]  = username;

158
    QUrl url("http://ws.audioscrobbler.com/2.0/?");
159

160
    sign(params);
161

162 163 164 165
    foreach(QString key, params.keys()) {
        url.addQueryItem(key, params[key]);
    }

166 167 168
    if (!m_networkAccessManager)
        m_networkAccessManager = new QNetworkAccessManager(this);

169
    QNetworkReply *reply = m_networkAccessManager->get(QNetworkRequest(url));
170 171 172
    connect(reply, SIGNAL(finished()), this, SLOT(handleAuthenticationReply()));
}

173
void Scrobbler::getAuthToken()
174
{
175 176 177 178 179 180 181 182
    QString username, password;

    if (m_wallet) {

        QMap<QString, QString> scrobblingCredentials;
        m_wallet->readMap("Scrobbling", scrobblingCredentials);

        if (scrobblingCredentials.contains("Username") && scrobblingCredentials.contains("Password")) {
183

184 185 186 187 188 189 190 191 192 193
            username = scrobblingCredentials["Username"];
            password = scrobblingCredentials["Password"];
        }

    } else {

        KConfigGroup config(KGlobal::config(), "Scrobbling");
        username = config.readEntry("Username", "");
        password = config.readEntry("Password", "");
    }
194 195

    if(username.isEmpty() || password.isEmpty())
196
        return;
197

198 199 200
    getAuthToken(username, password);
}

201 202 203
void Scrobbler::handleAuthenticationReply()
{
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
204

205
    kDebug() << "got authentication reply";
206
    if(reply->error() != QNetworkReply::NoError) {
207 208
        emit invalidAuth();
        kWarning() << "Error while getting authentication reply" << reply->errorString();
209 210
        return;
    }
211

212 213 214
    QDomDocument doc;
    QByteArray data = reply->readAll();
    doc.setContent(data);
215 216 217 218 219 220

    QString sessionKey = doc.documentElement()
        .firstChildElement("session")
            .firstChildElement("key").text();

    if(sessionKey.isEmpty()) {
221 222 223 224
        emit invalidAuth();
        kWarning() << "Unable to get session key" << data;
        return;
    }
225

226 227 228 229 230 231 232 233 234 235
    if (m_wallet) {

        m_wallet->writeEntry("SessionKey", sessionKey.toUtf8());

    } else {

        KConfigGroup config(KGlobal::config(), "Scrobbling");
        config.writeEntry("SessionKey", sessionKey);
    }

236
    emit validAuth();
237 238 239 240
}

void Scrobbler::nowPlaying(const FileHandle& file)
{
241
    QString sessionKey;
242

243 244 245 246 247 248 249 250 251 252
    if (m_wallet) {

        QByteArray sessionKeyByteArray;
        m_wallet->readEntry("SessionKey", sessionKeyByteArray);
        sessionKey = QString::fromLatin1(sessionKeyByteArray);

    } else {

        KConfigGroup config(KGlobal::config(), "Scrobbling");
        sessionKey = config.readEntry("SessionKey", "");
253
    }
254

255 256 257 258
    if (!m_file.isNull()) {
        scrobble(); // Update time-played info for last track
    }

259 260
    QMap<QString, QString> params;
    params["method"] = "track.updateNowPlaying";
261 262
    params["sk"]     = sessionKey;
    params["track"]  = file.tag()->title();
263
    params["artist"] = file.tag()->artist();
264
    params["album"]  = file.tag()->album();
265
    params["trackNumber"] = QString::number(file.tag()->track());
266 267
    params["duration"]    = QString::number(file.tag()->seconds());

268 269
    sign(params);
    post(params);
270

271 272
    m_file = file; // May be FileHandle::null()
    m_playbackTimer = QDateTime::currentDateTime();
273 274 275 276
}

void Scrobbler::scrobble()
{
277 278 279
    QString sessionKey;

    if (m_wallet) {
280

281 282 283 284 285 286 287 288 289
        QByteArray sessionKeyByteArray;
        m_wallet->readEntry("SessionKey", sessionKeyByteArray);
        sessionKey = QString::fromLatin1(sessionKeyByteArray);

    } else {

        KConfigGroup config(KGlobal::config(), "Scrobbling");
        sessionKey = config.readEntry("SessionKey", "");
    }
290 291

    if(sessionKey.isEmpty()) {
292 293 294
        getAuthToken();
        return;
    }
295

296 297 298 299 300 301 302
    int halfDuration = m_file.tag()->seconds() / 2;
    int timeElapsed = m_playbackTimer.secsTo(QDateTime::currentDateTime());

    if (timeElapsed < 30 || timeElapsed < halfDuration) {
        return; // API says not to scrobble if the user didn't play long enough
    }

303
    kDebug() << "Scrobbling" << m_file.tag()->title();
304

305 306
    QMap<QString, QString> params;
    params["method"] = "track.scrobble";
307 308
    params["sk"]     = sessionKey;
    params["track"]  = m_file.tag()->title();
309
    params["artist"] = m_file.tag()->artist();
310
    params["album"]  = m_file.tag()->album();
311
    params["timestamp"]   = QString::number(m_playbackTimer.toTime_t());
312
    params["trackNumber"] = QString::number(m_file.tag()->track());
313 314
    params["duration"]    = QString::number(m_file.tag()->seconds());

315 316 317 318 319 320
    sign(params);
    post(params);
}

void Scrobbler::post(QMap<QString, QString> &params)
{
321 322 323 324
    if(!m_networkAccessManager) {
        return;
    }

325
    QUrl url("http://ws.audioscrobbler.com/2.0/");
326

327 328
    QByteArray data;
    foreach(QString key, params.keys()) {
Shubham Chaudhary's avatar
Shubham Chaudhary committed
329
        data += QUrl::toPercentEncoding(key) + '=' + QUrl::toPercentEncoding(params[key]) + '&';
330 331 332 333
    }

    QNetworkRequest req(url);
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
334
    QNetworkReply *reply = m_networkAccessManager->post(req, data);
335 336 337 338 339 340 341
    connect(reply, SIGNAL(finished()), this, SLOT(handleResults()));
}

void Scrobbler::handleResults()
{
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
    QByteArray data = reply->readAll();
342
    if(data.contains("code=\"9\"")) // We need a new token
343 344
        getAuthToken();
}