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 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
|
/**
* Copyright (C) 2012 Martin Sandsmark <martin.sandsmark@kde.org>
* Copyright (C) 2014 Arnold Dumas <contact@arnolddumas.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, see <http://www.gnu.org/licenses/>.
*/
#include "scrobbler.h"
#include <QByteArray>
#include <QCryptographicHash>
#include <QDomDocument>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QUrl>
#include <QUrlQuery>
#include <kconfiggroup.h>
#include <KSharedConfig>
#include <memory>
#include "juktag.h"
#include "juk.h"
#include "juk_debug.h"
Scrobbler::Scrobbler(QObject* parent)
: QObject(parent)
, m_networkAccessManager(new QNetworkAccessManager(this))
, m_wallet(Scrobbler::openKWallet())
{
QByteArray sessionKey;
if (m_wallet) {
m_wallet->readEntry("SessionKey", sessionKey);
} else {
KConfigGroup config(KSharedConfig::openConfig(), "Scrobbling");
sessionKey.append(config.readEntry("SessionKey", "").toLatin1());
}
if(sessionKey.isEmpty())
getAuthToken();
}
bool Scrobbler::isScrobblingEnabled() // static
{
QString username, password;
// checks without prompting to open the wallet
if (Wallet::folderDoesNotExist(Wallet::LocalWallet(), "JuK")) {
KConfigGroup config(KSharedConfig::openConfig(), "Scrobbling");
username = config.readEntry("Username", "");
password = config.readEntry("Password", "");
} else {
auto wallet = Scrobbler::openKWallet();
if (wallet) {
QMap<QString, QString> scrobblingCredentials;
wallet->readMap("Scrobbling", scrobblingCredentials);
if (scrobblingCredentials.contains("Username") && scrobblingCredentials.contains("Password")) {
username = scrobblingCredentials["Username"];
password = scrobblingCredentials["Password"];
}
}
}
return (!username.isEmpty() && !password.isEmpty());
}
std::unique_ptr<KWallet::Wallet> Scrobbler::openKWallet() // static
{
using KWallet::Wallet;
const QString walletFolderName(QStringLiteral("JuK"));
const auto walletName = Wallet::LocalWallet();
// checks without prompting to open the wallet
if (Wallet::folderDoesNotExist(walletName, walletFolderName)) {
return nullptr;
}
std::unique_ptr<Wallet> wallet(
Wallet::openWallet(walletName, JuK::JuKInstance()->winId()));
if(!wallet ||
(!wallet->hasFolder(walletFolderName) &&
!wallet->createFolder(walletFolderName)) ||
!wallet->setFolder(walletFolderName))
{
return nullptr;
}
return wallet;
}
QByteArray Scrobbler::md5(QByteArray data)
{
return QCryptographicHash::hash(data, QCryptographicHash::Md5)
.toHex().rightJustified(32, '0').toLower();
}
void Scrobbler::sign(QMap< QString, QString >& params)
{
params["api_key"] = "3e6ecbd7284883089e8f2b5b53b0aecd";
QString s;
QMapIterator<QString, QString> i(params);
while(i.hasNext()) {
i.next();
s += i.key() + i.value();
}
s += "2cab3957b1f70d485e9815ac1ac94096"; //shared secret
params["api_sig"] = md5(s.toUtf8());
}
void Scrobbler::getAuthToken(QString username, QString password)
{
qCDebug(JUK_LOG) << "Getting new auth token for user:" << username;
QByteArray authToken = md5((username + md5(password.toUtf8())).toUtf8());
QMap<QString, QString> params;
params["method"] = "auth.getMobileSession";
params["authToken"] = authToken;
params["username"] = username;
QUrl url("https://ws.audioscrobbler.com/2.0/?");
sign(params);
QUrlQuery urlQuery;
const auto paramKeys = params.keys();
for(const auto &key : paramKeys) {
urlQuery.addQueryItem(key, params[key]);
}
url.setQuery(urlQuery);
QNetworkReply *reply = m_networkAccessManager->get(QNetworkRequest(url));
connect(reply, SIGNAL(finished()), this, SLOT(handleAuthenticationReply()));
}
void Scrobbler::getAuthToken()
{
QString username, password;
if (m_wallet) {
QMap<QString, QString> scrobblingCredentials;
m_wallet->readMap("Scrobbling", scrobblingCredentials);
if (scrobblingCredentials.contains("Username") && scrobblingCredentials.contains("Password")) {
username = scrobblingCredentials["Username"];
password = scrobblingCredentials["Password"];
}
} else {
KConfigGroup config(KSharedConfig::openConfig(), "Scrobbling");
username = config.readEntry("Username", "");
password = config.readEntry("Password", "");
}
if(username.isEmpty() || password.isEmpty())
return;
getAuthToken(username, password);
}
void Scrobbler::handleAuthenticationReply()
{
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
qCDebug(JUK_LOG) << "got authentication reply";
if (reply->error() != QNetworkReply::NoError) {
emit invalidAuth();
qCWarning(JUK_LOG) << "Error while getting authentication reply" << reply->errorString();
return;
}
QDomDocument doc;
QByteArray data = reply->readAll();
doc.setContent(data);
QString sessionKey = doc.documentElement()
.firstChildElement("session")
.firstChildElement("key").text();
if(sessionKey.isEmpty()) {
emit invalidAuth();
qCWarning(JUK_LOG) << "Unable to get session key" << data;
return;
}
if (m_wallet) {
m_wallet->writeEntry("SessionKey", sessionKey.toUtf8());
} else {
KConfigGroup config(KSharedConfig::openConfig(), "Scrobbling");
config.writeEntry("SessionKey", sessionKey);
}
emit validAuth();
}
void Scrobbler::nowPlaying(const FileHandle& file)
{
QString sessionKey;
if (m_wallet) {
QByteArray sessionKeyByteArray;
m_wallet->readEntry("SessionKey", sessionKeyByteArray);
sessionKey = QString::fromLatin1(sessionKeyByteArray);
} else {
KConfigGroup config(KSharedConfig::openConfig(), "Scrobbling");
sessionKey = config.readEntry("SessionKey", "");
}
if (!m_file.isNull()) {
scrobble(); // Update time-played info for last track
}
QMap<QString, QString> params;
params["method"] = "track.updateNowPlaying";
params["sk"] = sessionKey;
params["track"] = file.tag()->title();
params["artist"] = file.tag()->artist();
params["album"] = file.tag()->album();
params["trackNumber"] = QString::number(file.tag()->track());
params["duration"] = QString::number(file.tag()->seconds());
sign(params);
post(params);
m_file = file; // May be empty FileHandle
m_playbackTimer = QDateTime::currentDateTime();
}
void Scrobbler::scrobble()
{
QString sessionKey;
if (m_wallet) {
QByteArray sessionKeyByteArray;
m_wallet->readEntry("SessionKey", sessionKeyByteArray);
sessionKey = QString::fromLatin1(sessionKeyByteArray);
} else {
KConfigGroup config(KSharedConfig::openConfig(), "Scrobbling");
sessionKey = config.readEntry("SessionKey", "");
}
if(sessionKey.isEmpty()) {
getAuthToken();
return;
}
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
}
qCDebug(JUK_LOG) << "Scrobbling" << m_file.tag()->title();
QMap<QString, QString> params;
params["method"] = "track.scrobble";
params["sk"] = sessionKey;
params["track"] = m_file.tag()->title();
params["artist"] = m_file.tag()->artist();
params["album"] = m_file.tag()->album();
params["timestamp"] = QString::number(m_playbackTimer.toSecsSinceEpoch());
params["trackNumber"] = QString::number(m_file.tag()->track());
params["duration"] = QString::number(m_file.tag()->seconds());
sign(params);
post(params);
}
void Scrobbler::post(QMap<QString, QString> ¶ms)
{
QUrl url("https://ws.audioscrobbler.com/2.0/");
QByteArray data;
const auto paramKeys = params.keys();
for(const auto &key : paramKeys) {
data += QUrl::toPercentEncoding(key) + '=' + QUrl::toPercentEncoding(params[key]) + '&';
}
QNetworkRequest req(url);
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QNetworkReply *reply = m_networkAccessManager->post(req, data);
connect(reply, SIGNAL(finished()), this, SLOT(handleResults()));
}
void Scrobbler::handleResults()
{
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
QByteArray data = reply->readAll();
if(data.contains("code=\"9\"")) // We need a new token
getAuthToken();
}
|