Add scrobbler with support for Last.fm, Libre.fm and ListenBrainz
This commit is contained in:
173
src/scrobbler/audioscrobbler.cpp
Normal file
173
src/scrobbler/audioscrobbler.cpp
Normal file
@@ -0,0 +1,173 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include <QtGlobal>
|
||||
#include <QDesktopServices>
|
||||
#include <QUrlQuery>
|
||||
#include <QCryptographicHash>
|
||||
#include <QMenu>
|
||||
#include <QMessageBox>
|
||||
#include <QSettings>
|
||||
#include <QNetworkRequest>
|
||||
#include <QNetworkReply>
|
||||
#include <QJsonParseError>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonValue>
|
||||
|
||||
#include "core/application.h"
|
||||
#include "core/closure.h"
|
||||
#include "core/logging.h"
|
||||
#include "core/network.h"
|
||||
#include "core/player.h"
|
||||
#include "core/song.h"
|
||||
#include "core/taskmanager.h"
|
||||
#include "core/iconloader.h"
|
||||
#include "settings/settingsdialog.h"
|
||||
#include "settings/scrobblersettingspage.h"
|
||||
|
||||
#include "audioscrobbler.h"
|
||||
#include "scrobblerservices.h"
|
||||
#include "scrobblerservice.h"
|
||||
#include "lastfmscrobbler.h"
|
||||
#include "librefmscrobbler.h"
|
||||
#include "listenbrainzscrobbler.h"
|
||||
|
||||
AudioScrobbler::AudioScrobbler(Application *app, QObject *parent) :
|
||||
QObject(parent),
|
||||
app_(app),
|
||||
scrobbler_services_(new ScrobblerServices(this)),
|
||||
enabled_(false),
|
||||
offline_(false),
|
||||
scrobble_button_(false) {
|
||||
|
||||
scrobbler_services_->AddService(new LastFMScrobbler(app_, scrobbler_services_));
|
||||
scrobbler_services_->AddService(new LibreFMScrobbler(app_, scrobbler_services_));
|
||||
scrobbler_services_->AddService(new ListenBrainzScrobbler(app_, scrobbler_services_));
|
||||
|
||||
ReloadSettings();
|
||||
|
||||
}
|
||||
|
||||
AudioScrobbler::~AudioScrobbler() {}
|
||||
|
||||
void AudioScrobbler::ReloadSettings() {
|
||||
|
||||
QSettings s;
|
||||
s.beginGroup(ScrobblerSettingsPage::kSettingsGroup);
|
||||
enabled_ = s.value("enabled", false).toBool();
|
||||
offline_ = s.value("offline", false).toBool();
|
||||
scrobble_button_ = s.value("scrobble_button", false).toBool();
|
||||
s.endGroup();
|
||||
|
||||
emit ScrobblingEnabledChanged(enabled_);
|
||||
emit ScrobbleButtonVisibilityChanged(scrobble_button_);
|
||||
|
||||
for (ScrobblerService *service : scrobbler_services_->List()) {
|
||||
service->ReloadSettings();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void AudioScrobbler::ToggleScrobbling() {
|
||||
|
||||
bool enabled_old_ = enabled_;
|
||||
enabled_ = !enabled_;
|
||||
|
||||
QSettings s;
|
||||
s.beginGroup(ScrobblerSettingsPage::kSettingsGroup);
|
||||
s.setValue("enabled", enabled_);
|
||||
s.endGroup();
|
||||
|
||||
if (enabled_ != enabled_old_) emit ScrobblingEnabledChanged(enabled_);
|
||||
if (enabled_ && !offline_) { Submit(); }
|
||||
|
||||
}
|
||||
|
||||
void AudioScrobbler::ToggleOffline() {
|
||||
|
||||
bool offline_old_ = offline_;
|
||||
offline_ = !offline_;
|
||||
|
||||
QSettings s;
|
||||
s.beginGroup(ScrobblerSettingsPage::kSettingsGroup);
|
||||
s.setValue("offline", offline_);
|
||||
s.endGroup();
|
||||
|
||||
if (offline_ != offline_old_) { emit ScrobblingOfflineChanged(offline_); }
|
||||
if (enabled_ && !offline_) { Submit(); }
|
||||
|
||||
}
|
||||
|
||||
void AudioScrobbler::ShowConfig() {
|
||||
app_->OpenSettingsDialogAtPage(SettingsDialog::Page_Scrobbler);
|
||||
}
|
||||
|
||||
void AudioScrobbler::UpdateNowPlaying(const Song &song) {
|
||||
qLog(Debug) << "Sending now playing for song" << song.title();
|
||||
for (ScrobblerService *service : scrobbler_services_->List()) {
|
||||
if (!service->IsEnabled()) continue;
|
||||
service->UpdateNowPlaying(song);
|
||||
}
|
||||
}
|
||||
|
||||
void AudioScrobbler::Scrobble(const Song &song, const int scrobble_point) {
|
||||
qLog(Debug) << "Scrobbling song" << QString("") + song.title() + QString("") << "at" << scrobble_point;
|
||||
for (ScrobblerService *service : scrobbler_services_->List()) {
|
||||
if (!service->IsEnabled()) continue;
|
||||
service->Scrobble(song);
|
||||
}
|
||||
}
|
||||
|
||||
void AudioScrobbler::Love(const Song &song) {
|
||||
for (ScrobblerService *service : scrobbler_services_->List()) {
|
||||
if (!service->IsEnabled() || !service->IsAuthenticated()) continue;
|
||||
service->Love(song);
|
||||
}
|
||||
}
|
||||
|
||||
void AudioScrobbler::Submit() {
|
||||
for (ScrobblerService *service : scrobbler_services_->List()) {
|
||||
if (!service->IsEnabled() || !service->IsAuthenticated() || service->IsSubmitted()) continue;
|
||||
service->Submitted();
|
||||
DoInAMinuteOrSo(service, SLOT(Submit()));
|
||||
}
|
||||
}
|
||||
|
||||
void AudioScrobbler::WriteCache() {
|
||||
for (ScrobblerService *service : scrobbler_services_->List()) {
|
||||
if (!service->IsEnabled()) continue;
|
||||
service->WriteCache();
|
||||
}
|
||||
}
|
||||
|
||||
void AudioScrobbler::ConnectError() {
|
||||
for (ScrobblerService *service : scrobbler_services_->List()) {
|
||||
connect(service, SIGNAL(ErrorMessage(QString)), SLOT(ErrorReceived(QString)));
|
||||
}
|
||||
}
|
||||
|
||||
void AudioScrobbler::ErrorReceived(QString error) {
|
||||
emit ErrorMessage(error);
|
||||
}
|
||||
88
src/scrobbler/audioscrobbler.h
Normal file
88
src/scrobbler/audioscrobbler.h
Normal file
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef AUDIOSCROBBLER_H
|
||||
#define AUDIOSCROBBLER_H
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include <QtGlobal>
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
|
||||
#include "scrobblerservices.h"
|
||||
|
||||
class Application;
|
||||
class Song;
|
||||
class NetworkAccessManager;
|
||||
class ScrobblerService;
|
||||
|
||||
class AudioScrobbler : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit AudioScrobbler(Application *app, QObject *parent = nullptr);
|
||||
~AudioScrobbler();
|
||||
|
||||
void ReloadSettings();
|
||||
|
||||
bool IsEnabled() const { return enabled_; }
|
||||
bool IsOffline() const { return offline_; }
|
||||
bool ScrobbleButton() const { return scrobble_button_; }
|
||||
|
||||
void UpdateNowPlaying(const Song &song);
|
||||
void Scrobble(const Song &song, const int scrobble_point);
|
||||
void Love(const Song &song);
|
||||
void ShowConfig();
|
||||
void ConnectError();
|
||||
|
||||
ScrobblerService *ServiceByName(const QString &name) const { return scrobbler_services_->ServiceByName(name); }
|
||||
|
||||
template <typename T>
|
||||
T *Service() {
|
||||
return static_cast<T*>(this->ServiceByName(T::kName));
|
||||
}
|
||||
|
||||
public slots:
|
||||
void ToggleScrobbling();
|
||||
void ToggleOffline();
|
||||
void Submit();
|
||||
void WriteCache();
|
||||
void ErrorReceived(QString);
|
||||
|
||||
signals:
|
||||
void ErrorMessage(QString);
|
||||
void ScrobblingEnabledChanged(bool value);
|
||||
void ScrobblingOfflineChanged(bool value);
|
||||
void ScrobbleButtonVisibilityChanged(bool value);
|
||||
|
||||
private:
|
||||
|
||||
Application *app_;
|
||||
ScrobblerServices *scrobbler_services_;
|
||||
|
||||
bool enabled_;
|
||||
bool offline_;
|
||||
bool scrobble_button_;
|
||||
|
||||
};
|
||||
|
||||
#endif // AUDIOSCROBBLER_H
|
||||
82
src/scrobbler/lastfmscrobbler.cpp
Normal file
82
src/scrobbler/lastfmscrobbler.cpp
Normal file
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include <QtGlobal>
|
||||
#include <QDesktopServices>
|
||||
#include <QVariant>
|
||||
#include <QByteArray>
|
||||
#include <QString>
|
||||
#include <QUrl>
|
||||
#include <QUrlQuery>
|
||||
#include <QDateTime>
|
||||
#include <QCryptographicHash>
|
||||
#include <QMenu>
|
||||
#include <QMessageBox>
|
||||
#include <QSettings>
|
||||
#include <QNetworkRequest>
|
||||
#include <QNetworkReply>
|
||||
#include <QJsonParseError>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonValue>
|
||||
|
||||
#include "core/application.h"
|
||||
#include "core/player.h"
|
||||
#include "core/closure.h"
|
||||
#include "core/network.h"
|
||||
#include "core/song.h"
|
||||
#include "core/timeconstants.h"
|
||||
#include "core/logging.h"
|
||||
#include "internet/localredirectserver.h"
|
||||
#include "settings/settingsdialog.h"
|
||||
#include "settings/scrobblersettingspage.h"
|
||||
|
||||
#include "audioscrobbler.h"
|
||||
#include "scrobblerservices.h"
|
||||
#include "scrobblercache.h"
|
||||
#include "scrobblingapi20.h"
|
||||
#include "lastfmscrobbler.h"
|
||||
|
||||
const char *LastFMScrobbler::kName = "Last.fm";
|
||||
const char *LastFMScrobbler::kSettingsGroup = "LastFM";
|
||||
const char *LastFMScrobbler::kAuthUrl = "https://www.last.fm/api/auth/";
|
||||
const char *LastFMScrobbler::kApiUrl = "https://ws.audioscrobbler.com/2.0/";
|
||||
const char *LastFMScrobbler::kCacheFile = "lastfmscrobbler.cache";
|
||||
|
||||
LastFMScrobbler::LastFMScrobbler(Application *app, QObject *parent) : ScrobblingAPI20(kName, kSettingsGroup, kAuthUrl, kApiUrl, true, app, parent),
|
||||
auth_url_(kAuthUrl),
|
||||
api_url_(kApiUrl),
|
||||
app_(app),
|
||||
network_(new NetworkAccessManager(this)),
|
||||
cache_(new ScrobblerCache(kCacheFile, this)),
|
||||
enabled_(false),
|
||||
subscriber_(false),
|
||||
submitted_(false) {
|
||||
|
||||
ReloadSettings();
|
||||
LoadSession();
|
||||
|
||||
}
|
||||
|
||||
LastFMScrobbler::~LastFMScrobbler() {}
|
||||
82
src/scrobbler/lastfmscrobbler.h
Normal file
82
src/scrobbler/lastfmscrobbler.h
Normal file
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef LASTFMSCROBBLER_H
|
||||
#define LASTFMSCROBBLER_H
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include <QtGlobal>
|
||||
#include <QObject>
|
||||
#include <QNetworkReply>
|
||||
#include <QPair>
|
||||
#include <QList>
|
||||
#include <QVariant>
|
||||
#include <QByteArray>
|
||||
#include <QString>
|
||||
#include <QJsonObject>
|
||||
|
||||
#include "core/song.h"
|
||||
#include "scrobblerservice.h"
|
||||
#include "scrobblingapi20.h"
|
||||
|
||||
class Application;
|
||||
class NetworkAccessManager;
|
||||
class LocalRedirectServer;
|
||||
class ScrobblerCache;
|
||||
|
||||
class LastFMScrobbler : public ScrobblingAPI20 {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit LastFMScrobbler(Application *app, QObject *parent = nullptr);
|
||||
~LastFMScrobbler();
|
||||
|
||||
static const char *kName;
|
||||
static const char *kSettingsGroup;
|
||||
|
||||
NetworkAccessManager *network() { return network_; }
|
||||
ScrobblerCache *cache() { return cache_; }
|
||||
|
||||
private:
|
||||
static const char *kAuthUrl;
|
||||
static const char *kApiUrl;
|
||||
static const char *kCacheFile;
|
||||
|
||||
QString settings_group_;
|
||||
QString auth_url_;
|
||||
QString api_url_;
|
||||
QString api_key_;
|
||||
QString secret_;
|
||||
Application *app_;
|
||||
NetworkAccessManager *network_;
|
||||
ScrobblerCache *cache_;
|
||||
bool enabled_;
|
||||
bool subscriber_;
|
||||
QString username_;
|
||||
QString session_key_;
|
||||
bool submitted_;
|
||||
Song song_playing_;
|
||||
quint64 timestamp_;
|
||||
|
||||
};
|
||||
|
||||
#endif // LASTFMSCROBBLER_H
|
||||
82
src/scrobbler/librefmscrobbler.cpp
Normal file
82
src/scrobbler/librefmscrobbler.cpp
Normal file
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include <QtGlobal>
|
||||
#include <QDesktopServices>
|
||||
#include <QVariant>
|
||||
#include <QByteArray>
|
||||
#include <QString>
|
||||
#include <QUrl>
|
||||
#include <QUrlQuery>
|
||||
#include <QDateTime>
|
||||
#include <QCryptographicHash>
|
||||
#include <QMenu>
|
||||
#include <QMessageBox>
|
||||
#include <QSettings>
|
||||
#include <QNetworkRequest>
|
||||
#include <QNetworkReply>
|
||||
#include <QJsonParseError>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonValue>
|
||||
|
||||
#include "core/application.h"
|
||||
#include "core/player.h"
|
||||
#include "core/closure.h"
|
||||
#include "core/network.h"
|
||||
#include "core/song.h"
|
||||
#include "core/timeconstants.h"
|
||||
#include "core/logging.h"
|
||||
#include "internet/localredirectserver.h"
|
||||
#include "settings/settingsdialog.h"
|
||||
#include "settings/scrobblersettingspage.h"
|
||||
|
||||
#include "audioscrobbler.h"
|
||||
#include "scrobblerservices.h"
|
||||
#include "scrobblercache.h"
|
||||
#include "scrobblingapi20.h"
|
||||
#include "librefmscrobbler.h"
|
||||
|
||||
const char *LibreFMScrobbler::kName = "Libre.fm";
|
||||
const char *LibreFMScrobbler::kSettingsGroup = "LibreFM";
|
||||
const char *LibreFMScrobbler::kAuthUrl = "https://www.libre.fm/api/auth/";
|
||||
const char *LibreFMScrobbler::kApiUrl = "https://libre.fm/2.0/";
|
||||
const char *LibreFMScrobbler::kCacheFile = "librefmscrobbler.cache";
|
||||
|
||||
LibreFMScrobbler::LibreFMScrobbler(Application *app, QObject *parent) : ScrobblingAPI20(kName, kSettingsGroup, kAuthUrl, kApiUrl, false, app, parent),
|
||||
auth_url_(kAuthUrl),
|
||||
api_url_(kApiUrl),
|
||||
app_(app),
|
||||
network_(new NetworkAccessManager(this)),
|
||||
cache_(new ScrobblerCache(kCacheFile, this)),
|
||||
enabled_(false),
|
||||
subscriber_(false),
|
||||
submitted_(false) {
|
||||
|
||||
ReloadSettings();
|
||||
LoadSession();
|
||||
|
||||
}
|
||||
|
||||
LibreFMScrobbler::~LibreFMScrobbler() {}
|
||||
82
src/scrobbler/librefmscrobbler.h
Normal file
82
src/scrobbler/librefmscrobbler.h
Normal file
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef LIBREFMSCROBBLER_H
|
||||
#define LIBREFMSCROBBLER_H
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include <QtGlobal>
|
||||
#include <QObject>
|
||||
#include <QNetworkReply>
|
||||
#include <QPair>
|
||||
#include <QList>
|
||||
#include <QVariant>
|
||||
#include <QByteArray>
|
||||
#include <QString>
|
||||
#include <QJsonObject>
|
||||
|
||||
#include "core/song.h"
|
||||
#include "scrobblerservice.h"
|
||||
#include "scrobblingapi20.h"
|
||||
|
||||
class Application;
|
||||
class NetworkAccessManager;
|
||||
class LocalRedirectServer;
|
||||
class ScrobblerCache;
|
||||
|
||||
class LibreFMScrobbler : public ScrobblingAPI20 {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit LibreFMScrobbler(Application *app, QObject *parent = nullptr);
|
||||
~LibreFMScrobbler();
|
||||
|
||||
static const char *kName;
|
||||
static const char *kSettingsGroup;
|
||||
|
||||
NetworkAccessManager *network() { return network_; }
|
||||
ScrobblerCache *cache() { return cache_; }
|
||||
|
||||
private:
|
||||
static const char *kAuthUrl;
|
||||
static const char *kApiUrl;
|
||||
static const char *kCacheFile;
|
||||
|
||||
QString settings_group_;
|
||||
QString auth_url_;
|
||||
QString api_url_;
|
||||
QString api_key_;
|
||||
QString secret_;
|
||||
Application *app_;
|
||||
NetworkAccessManager *network_;
|
||||
ScrobblerCache *cache_;
|
||||
bool enabled_;
|
||||
bool subscriber_;
|
||||
QString username_;
|
||||
QString session_key_;
|
||||
bool submitted_;
|
||||
Song song_playing_;
|
||||
quint64 timestamp_;
|
||||
|
||||
};
|
||||
|
||||
#endif // LIBREFMSCROBBLER_H
|
||||
482
src/scrobbler/listenbrainzscrobbler.cpp
Normal file
482
src/scrobbler/listenbrainzscrobbler.cpp
Normal file
@@ -0,0 +1,482 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include <QtGlobal>
|
||||
#include <QDesktopServices>
|
||||
#include <QVariant>
|
||||
#include <QByteArray>
|
||||
#include <QString>
|
||||
#include <QUrl>
|
||||
#include <QUrlQuery>
|
||||
#include <QDateTime>
|
||||
#include <QCryptographicHash>
|
||||
#include <QMenu>
|
||||
#include <QMessageBox>
|
||||
#include <QSettings>
|
||||
#include <QNetworkRequest>
|
||||
#include <QNetworkReply>
|
||||
#include <QJsonParseError>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonValue>
|
||||
|
||||
#include "core/application.h"
|
||||
#include "core/player.h"
|
||||
#include "core/closure.h"
|
||||
#include "core/network.h"
|
||||
#include "core/song.h"
|
||||
#include "core/timeconstants.h"
|
||||
#include "core/logging.h"
|
||||
#include "internet/localredirectserver.h"
|
||||
#include "settings/settingsdialog.h"
|
||||
#include "settings/scrobblersettingspage.h"
|
||||
|
||||
#include "audioscrobbler.h"
|
||||
#include "scrobblerservices.h"
|
||||
#include "scrobblerservice.h"
|
||||
#include "scrobblercache.h"
|
||||
#include "scrobblercacheitem.h"
|
||||
#include "listenbrainzscrobbler.h"
|
||||
|
||||
const char *ListenBrainzScrobbler::kName = "ListenBrainz";
|
||||
const char *ListenBrainzScrobbler::kSettingsGroup = "ListenBrainz";
|
||||
const char *ListenBrainzScrobbler::kAuthUrl = "https://musicbrainz.org/oauth2/authorize";
|
||||
const char *ListenBrainzScrobbler::kAuthTokenUrl = "https://musicbrainz.org/oauth2/token";
|
||||
const char *ListenBrainzScrobbler::kRedirectUrl = "http://localhost";
|
||||
const char *ListenBrainzScrobbler::kApiUrl = "https://api.listenbrainz.org";
|
||||
const char *ListenBrainzScrobbler::kClientID = "oeAUNwqSQer0er09Fiqi0Q";
|
||||
const char *ListenBrainzScrobbler::kClientSecret = "ROFghkeQ3F3oPyEhqiyWPA";
|
||||
const char *ListenBrainzScrobbler::kCacheFile = "listenbrainzscrobbler.cache";
|
||||
const int ListenBrainzScrobbler::kScrobblesPerRequest = 10;
|
||||
|
||||
ListenBrainzScrobbler::ListenBrainzScrobbler(Application *app, QObject *parent) : ScrobblerService(kName, app, parent),
|
||||
app_(app),
|
||||
network_(new NetworkAccessManager(this)),
|
||||
cache_(new ScrobblerCache(kCacheFile, this)),
|
||||
enabled_(false),
|
||||
expires_in_(-1),
|
||||
submitted_(false) {
|
||||
|
||||
ReloadSettings();
|
||||
LoadSession();
|
||||
|
||||
}
|
||||
|
||||
ListenBrainzScrobbler::~ListenBrainzScrobbler() {}
|
||||
|
||||
void ListenBrainzScrobbler::ReloadSettings() {
|
||||
|
||||
QSettings s;
|
||||
s.beginGroup(kSettingsGroup);
|
||||
enabled_ = s.value("enabled", false).toBool();
|
||||
user_token_ = s.value("user_token").toString();
|
||||
s.endGroup();
|
||||
|
||||
}
|
||||
|
||||
void ListenBrainzScrobbler::LoadSession() {
|
||||
|
||||
QSettings s;
|
||||
s.beginGroup(kSettingsGroup);
|
||||
access_token_ = s.value("access_token").toString();
|
||||
expires_in_ = s.value("expires_in", -1).toInt();
|
||||
token_type_ = s.value("token_type").toString();
|
||||
refresh_token_ = s.value("refresh_token").toString();
|
||||
s.endGroup();
|
||||
|
||||
}
|
||||
|
||||
void ListenBrainzScrobbler::Logout() {
|
||||
|
||||
access_token_.clear();
|
||||
expires_in_ = -1;
|
||||
token_type_.clear();
|
||||
refresh_token_.clear();
|
||||
|
||||
QSettings settings;
|
||||
settings.beginGroup(kSettingsGroup);
|
||||
settings.remove("access_token");
|
||||
settings.remove("expires_in");
|
||||
settings.remove("token_type");
|
||||
settings.remove("refresh_token");
|
||||
settings.endGroup();
|
||||
|
||||
}
|
||||
|
||||
void ListenBrainzScrobbler::Authenticate() {
|
||||
|
||||
QUrl url(kAuthUrl);
|
||||
|
||||
LocalRedirectServer *server = new LocalRedirectServer(this);
|
||||
server->Listen();
|
||||
NewClosure(server, SIGNAL(Finished()), this, &ListenBrainzScrobbler::RedirectArrived, server);
|
||||
|
||||
QUrl redirect_url(kRedirectUrl);
|
||||
redirect_url.setPort(server->url().port());
|
||||
|
||||
QUrlQuery url_query;
|
||||
url_query.addQueryItem("response_type", "code");
|
||||
url_query.addQueryItem("client_id", kClientID);
|
||||
url_query.addQueryItem("redirect_uri", redirect_url.toString());
|
||||
url_query.addQueryItem("scope", "profile;email;tag;rating;collection;submit_isrc;submit_barcode");
|
||||
url.setQuery(url_query);
|
||||
|
||||
bool result = QDesktopServices::openUrl(url);
|
||||
if (!result) {
|
||||
QMessageBox box(QMessageBox::NoIcon, "Scrobbler Authentication", QString("Please open this URL in your browser: <a href=\"%1\">%1</a>").arg(url.toString()), QMessageBox::Ok);
|
||||
box.setTextFormat(Qt::RichText);
|
||||
qLog(Debug) << "Scrobbler authentication URL: " << url.toString();
|
||||
box.exec();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void ListenBrainzScrobbler::RedirectArrived(LocalRedirectServer *server) {
|
||||
|
||||
server->deleteLater();
|
||||
|
||||
QUrl url = server->request_url();
|
||||
if (!QUrlQuery(url).queryItemValue("error").isEmpty()) {
|
||||
AuthError(QUrlQuery(url).queryItemValue("error"));
|
||||
return;
|
||||
}
|
||||
if (QUrlQuery(url).queryItemValue("code").isEmpty()) {
|
||||
AuthError("Redirect missing token code!");
|
||||
return;
|
||||
}
|
||||
|
||||
RequestSession(url, QUrlQuery(url).queryItemValue("code").toUtf8());
|
||||
|
||||
}
|
||||
|
||||
void ListenBrainzScrobbler::RequestSession(QUrl url, QString token) {
|
||||
|
||||
QUrl session_url(kAuthTokenUrl);
|
||||
QUrlQuery url_query;
|
||||
url_query.addQueryItem("grant_type", "authorization_code");
|
||||
url_query.addQueryItem("code", token);
|
||||
url_query.addQueryItem("client_id", kClientID);
|
||||
url_query.addQueryItem("client_secret", kClientSecret);
|
||||
url_query.addQueryItem("redirect_uri", url.toString());
|
||||
|
||||
QNetworkRequest req(session_url);
|
||||
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
|
||||
QByteArray query = url_query.toString(QUrl::FullyEncoded).toUtf8();
|
||||
QNetworkReply *reply = network_->post(req, query);
|
||||
NewClosure(reply, SIGNAL(finished()), this, SLOT(AuthenticateReplyFinished(QNetworkReply*)), reply);
|
||||
|
||||
}
|
||||
|
||||
void ListenBrainzScrobbler::AuthenticateReplyFinished(QNetworkReply *reply) {
|
||||
|
||||
reply->deleteLater();
|
||||
|
||||
QByteArray data;
|
||||
|
||||
if (reply->error() == QNetworkReply::NoError && reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 200) {
|
||||
data = reply->readAll();
|
||||
}
|
||||
else {
|
||||
if (reply->error() < 200) {
|
||||
// This is a network error, there is nothing more to do.
|
||||
QString failure_reason = QString("%1 (%2)").arg(reply->errorString()).arg(reply->error());
|
||||
AuthError(failure_reason);
|
||||
}
|
||||
else {
|
||||
// See if there is Json data containing "error" and "error_description" - then use that instead.
|
||||
data = reply->readAll();
|
||||
QJsonParseError error;
|
||||
QJsonDocument json_doc = QJsonDocument::fromJson(data, &error);
|
||||
QString failure_reason;
|
||||
if (error.error == QJsonParseError::NoError && !json_doc.isNull() && !json_doc.isEmpty() && json_doc.isObject()) {
|
||||
QJsonObject json_obj = json_doc.object();
|
||||
if (json_obj.contains("error") && json_obj.contains("error_description")) {
|
||||
QString error = json_obj["error"].toString();
|
||||
failure_reason = json_obj["error_description"].toString();
|
||||
}
|
||||
else {
|
||||
failure_reason = QString("%1 (%2)").arg(reply->errorString()).arg(reply->error());
|
||||
}
|
||||
}
|
||||
else {
|
||||
failure_reason = QString("%1 (%2)").arg(reply->errorString()).arg(reply->error());
|
||||
}
|
||||
AuthError(failure_reason);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonObject json_obj = ExtractJsonObj(data);
|
||||
if (json_obj.isEmpty()) {
|
||||
AuthError("Json document from server was empty.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (json_obj.contains("error") && json_obj.contains("error_description")) {
|
||||
QString error = json_obj["error"].toString();
|
||||
QString failure_reason = json_obj["error_description"].toString();
|
||||
AuthError(failure_reason);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!json_obj.contains("access_token") || !json_obj.contains("expires_in") || !json_obj.contains("token_type") || !json_obj.contains("refresh_token")) {
|
||||
AuthError("Json session object is missing values.");
|
||||
return;
|
||||
}
|
||||
|
||||
access_token_ = json_obj["access_token"].toString();
|
||||
expires_in_ = json_obj["expires_in"].toInt();
|
||||
token_type_ = json_obj["token_type"].toString();
|
||||
refresh_token_ = json_obj["refresh_token"].toString();
|
||||
|
||||
QSettings s;
|
||||
s.beginGroup(kSettingsGroup);
|
||||
s.setValue("access_token", access_token_);
|
||||
s.setValue("expires_in", expires_in_);
|
||||
s.setValue("token_type", token_type_);
|
||||
s.setValue("refresh_token", refresh_token_);
|
||||
s.endGroup();
|
||||
|
||||
emit AuthenticationComplete(true);
|
||||
|
||||
}
|
||||
|
||||
QNetworkReply *ListenBrainzScrobbler::CreateRequest(const QUrl &url, const QJsonDocument &json_doc) {
|
||||
|
||||
QNetworkRequest req(url);
|
||||
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
req.setRawHeader("Authorization", QString("Token %1").arg(user_token_).toUtf8());
|
||||
QNetworkReply *reply = network_->post(req, json_doc.toJson());
|
||||
|
||||
//qLog(Debug) << "ListenBrainz: Sending request" << json_doc.toJson();
|
||||
|
||||
return reply;
|
||||
|
||||
}
|
||||
|
||||
QByteArray ListenBrainzScrobbler::GetReplyData(QNetworkReply *reply) {
|
||||
|
||||
QByteArray data;
|
||||
|
||||
if (reply->error() == QNetworkReply::NoError && reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 200) {
|
||||
data = reply->readAll();
|
||||
}
|
||||
else {
|
||||
if (reply->error() < 200) {
|
||||
// This is a network error, there is nothing more to do.
|
||||
QString error_reason = QString("%1 (%2)").arg(reply->errorString()).arg(reply->error());
|
||||
Error(error_reason);
|
||||
}
|
||||
else {
|
||||
// See if there is Json data containing "error" and "error_description" - then use that instead.
|
||||
data = reply->readAll();
|
||||
QJsonParseError error;
|
||||
QJsonDocument json_doc = QJsonDocument::fromJson(data, &error);
|
||||
int error_code = -1;
|
||||
QString error_reason;
|
||||
if (error.error == QJsonParseError::NoError && !json_doc.isNull() && !json_doc.isEmpty() && json_doc.isObject()) {
|
||||
QJsonObject json_obj = json_doc.object();
|
||||
if (json_obj.contains("code") && json_obj.contains("error")) {
|
||||
error_code = json_obj["code"].toInt();
|
||||
QString message = json_obj["error"].toString();
|
||||
error_reason = QString("%1 (%2)").arg(message).arg(error_code);
|
||||
}
|
||||
else {
|
||||
error_reason = QString("%1 (%2)").arg(reply->errorString()).arg(reply->error());
|
||||
}
|
||||
}
|
||||
else {
|
||||
error_reason = QString("%1 (%2)").arg(reply->errorString()).arg(reply->error());
|
||||
}
|
||||
if (reply->error() == QNetworkReply::ContentAccessDenied || reply->error() == QNetworkReply::ContentOperationNotPermittedError || reply->error() == QNetworkReply::AuthenticationRequiredError) {
|
||||
// Session is probably expired
|
||||
Logout();
|
||||
Error(error_reason);
|
||||
}
|
||||
else if (reply->error() == QNetworkReply::ContentNotFoundError) { // Ignore this error
|
||||
Error(error_reason);
|
||||
}
|
||||
else { // Fail
|
||||
Error(error_reason);
|
||||
}
|
||||
}
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
}
|
||||
|
||||
void ListenBrainzScrobbler::UpdateNowPlaying(const Song &song) {
|
||||
|
||||
song_playing_ = song;
|
||||
timestamp_ = QDateTime::currentDateTime().toTime_t();
|
||||
|
||||
if (!song.is_metadata_good()) return;
|
||||
|
||||
// FIXME: This does not work: BAD REQUEST (302)
|
||||
return;
|
||||
|
||||
QJsonObject object_listen;
|
||||
object_listen.insert("listened_at", QJsonValue::fromVariant(timestamp_));
|
||||
QJsonObject object_track_metadata;
|
||||
object_track_metadata.insert("artist_name", QJsonValue::fromVariant(song.artist()));
|
||||
object_track_metadata.insert("release_name", QJsonValue::fromVariant(song.album()));
|
||||
object_track_metadata.insert("track_name", QJsonValue::fromVariant(song.title()));
|
||||
object_listen.insert("track_metadata", object_track_metadata);
|
||||
|
||||
QJsonArray array_payload;
|
||||
array_payload.append(object_listen);
|
||||
|
||||
QJsonObject object;
|
||||
object.insert("listen_type", "playing_now");
|
||||
object.insert("payload", array_payload);
|
||||
QJsonDocument doc(object);
|
||||
|
||||
QUrl url(QString("%1/1/submit-listens").arg(kApiUrl));
|
||||
QNetworkReply *reply = CreateRequest(url, doc);
|
||||
NewClosure(reply, SIGNAL(finished()), this, SLOT(UpdateNowPlayingRequestFinished(QNetworkReply*)), reply);
|
||||
|
||||
}
|
||||
|
||||
void ListenBrainzScrobbler::UpdateNowPlayingRequestFinished(QNetworkReply *reply) {
|
||||
|
||||
reply->deleteLater();
|
||||
|
||||
QByteArray data = GetReplyData(reply);
|
||||
if (data.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
qLog(Debug) << data;
|
||||
|
||||
// TODO
|
||||
|
||||
}
|
||||
|
||||
void ListenBrainzScrobbler::Scrobble(const Song &song) {
|
||||
|
||||
if (song.id() != song_playing_.id() || song.url() != song_playing_.url() || !song.is_metadata_good()) return;
|
||||
|
||||
cache_->Add(song, timestamp_);
|
||||
|
||||
if (app_->scrobbler()->IsOffline()) return;
|
||||
|
||||
if (!IsAuthenticated()) {
|
||||
emit ErrorMessage("ListenBrainz is not authenticated!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!submitted_) {
|
||||
DoInAMinuteOrSo(this, SLOT(Submit()));
|
||||
submitted_ = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void ListenBrainzScrobbler::Submit() {
|
||||
|
||||
qLog(Debug) << __PRETTY_FUNCTION__;
|
||||
|
||||
submitted_ = false;
|
||||
|
||||
if (!IsEnabled() || !IsAuthenticated() || app_->scrobbler()->IsOffline()) return;
|
||||
|
||||
QJsonArray array;
|
||||
int i(0);
|
||||
QList<quint64> list;
|
||||
for (ScrobblerCacheItem *item : cache_->List()) {
|
||||
if (item->sent_) continue;
|
||||
item->sent_ = true;
|
||||
i++;
|
||||
list << item->timestamp_;
|
||||
QJsonObject object_listen;
|
||||
object_listen.insert("listened_at", QJsonValue::fromVariant(item->timestamp_));
|
||||
QJsonObject object_track_metadata;
|
||||
object_track_metadata.insert("artist_name", QJsonValue::fromVariant(item->artist_));
|
||||
object_track_metadata.insert("release_name", QJsonValue::fromVariant(item->album_));
|
||||
object_track_metadata.insert("track_name", QJsonValue::fromVariant(item->song_));
|
||||
object_listen.insert("track_metadata", object_track_metadata);
|
||||
array.append(QJsonValue::fromVariant(object_listen));
|
||||
if (i >= kScrobblesPerRequest) break;
|
||||
}
|
||||
|
||||
if (i <= 0) return;
|
||||
|
||||
QJsonObject object;
|
||||
object.insert("listen_type", "import");
|
||||
object.insert("payload", array);
|
||||
QJsonDocument doc(object);
|
||||
|
||||
QUrl url(QString("%1/1/submit-listens").arg(kApiUrl));
|
||||
QNetworkReply *reply = CreateRequest(url, doc);
|
||||
NewClosure(reply, SIGNAL(finished()), this, SLOT(ScrobbleRequestFinished(QNetworkReply*, QList<quint64>)), reply, list);
|
||||
|
||||
}
|
||||
|
||||
void ListenBrainzScrobbler::ScrobbleRequestFinished(QNetworkReply *reply, QList<quint64> list) {
|
||||
|
||||
reply->deleteLater();
|
||||
|
||||
QByteArray data = GetReplyData(reply);
|
||||
if (data.isEmpty()) {
|
||||
cache_->ClearSent(list);
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonObject json_obj = ExtractJsonObj(data);
|
||||
if (json_obj.isEmpty()) {
|
||||
cache_->ClearSent(list);
|
||||
return;
|
||||
}
|
||||
|
||||
if (json_obj.contains("error") && json_obj.contains("error_description")) {
|
||||
QString error_code = json_obj["error"].toString();
|
||||
QString error_desc = json_obj["error_description"].toString();
|
||||
Error(error_desc);
|
||||
cache_->ClearSent(list);
|
||||
return;
|
||||
}
|
||||
|
||||
if (json_obj.contains("status")) {
|
||||
QString status = json_obj["status"].toString();
|
||||
qLog(Debug) << "MusicBrainz: Received scrobble status:" << status;
|
||||
}
|
||||
|
||||
cache_->Flush(list);
|
||||
|
||||
}
|
||||
|
||||
void ListenBrainzScrobbler::Love(const Song &song) {}
|
||||
|
||||
void ListenBrainzScrobbler::AuthError(QString error) {
|
||||
emit AuthenticationComplete(false, error);
|
||||
}
|
||||
|
||||
void ListenBrainzScrobbler::Error(QString error, QVariant debug) {
|
||||
|
||||
qLog(Error) << "ListenBrainz:" << error;
|
||||
if (debug.isValid()) qLog(Debug) << debug;
|
||||
|
||||
}
|
||||
|
||||
117
src/scrobbler/listenbrainzscrobbler.h
Normal file
117
src/scrobbler/listenbrainzscrobbler.h
Normal file
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef LISTENBRAINZSCROBBLER_H
|
||||
#define LISTENBRAINZSCROBBLER_H
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include <QtGlobal>
|
||||
#include <QObject>
|
||||
#include <QNetworkReply>
|
||||
#include <QPair>
|
||||
#include <QList>
|
||||
#include <QVariant>
|
||||
#include <QByteArray>
|
||||
#include <QString>
|
||||
#include <QJsonObject>
|
||||
|
||||
#include "core/song.h"
|
||||
#include "scrobblerservice.h"
|
||||
#include "scrobblercache.h"
|
||||
|
||||
class Application;
|
||||
class NetworkAccessManager;
|
||||
class LocalRedirectServer;
|
||||
class ScrobblerCacheItem;
|
||||
|
||||
class ListenBrainzScrobbler : public ScrobblerService {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit ListenBrainzScrobbler(Application *app, QObject *parent = nullptr);
|
||||
~ListenBrainzScrobbler();
|
||||
|
||||
static const char *kName;
|
||||
static const char *kSettingsGroup;
|
||||
|
||||
void ReloadSettings();
|
||||
void LoadSession();
|
||||
|
||||
bool IsEnabled() const { return enabled_; }
|
||||
bool IsAuthenticated() const { return !access_token_.isEmpty() && !user_token_.isEmpty(); }
|
||||
bool IsSubmitted() const { return submitted_; }
|
||||
void Submitted() { submitted_ = true; }
|
||||
QString user_token() const { return user_token_; }
|
||||
|
||||
void Authenticate();
|
||||
void Logout();
|
||||
void ShowConfig();
|
||||
void Submit();
|
||||
void UpdateNowPlaying(const Song &song);
|
||||
void Scrobble(const Song &song);
|
||||
void Love(const Song &song);
|
||||
|
||||
signals:
|
||||
void AuthenticationComplete(bool success, QString error = QString());
|
||||
|
||||
public slots:
|
||||
void WriteCache() { cache_->WriteCache(); }
|
||||
|
||||
private slots:
|
||||
void RedirectArrived(LocalRedirectServer *server);
|
||||
void AuthenticateReplyFinished(QNetworkReply *reply);
|
||||
void UpdateNowPlayingRequestFinished(QNetworkReply *reply);
|
||||
void ScrobbleRequestFinished(QNetworkReply *reply, QList<quint64>);
|
||||
|
||||
private:
|
||||
QNetworkReply *CreateRequest(const QUrl &url, const QJsonDocument &json_doc);
|
||||
QByteArray GetReplyData(QNetworkReply *reply);
|
||||
|
||||
void RequestSession(QUrl url, QString token);
|
||||
void AuthError(QString error);
|
||||
void Error(QString error, QVariant debug = QVariant());
|
||||
|
||||
static const char *kAuthUrl;
|
||||
static const char *kAuthTokenUrl;
|
||||
static const char *kApiUrl;
|
||||
static const char *kClientID;
|
||||
static const char *kClientSecret;
|
||||
static const char *kCacheFile;
|
||||
static const char *kRedirectUrl;
|
||||
static const int kScrobblesPerRequest;
|
||||
|
||||
Application *app_;
|
||||
NetworkAccessManager *network_;
|
||||
ScrobblerCache *cache_;
|
||||
bool enabled_;
|
||||
QString user_token_;
|
||||
QString access_token_;
|
||||
qint64 expires_in_;
|
||||
QString token_type_;
|
||||
QString refresh_token_;
|
||||
bool submitted_;
|
||||
Song song_playing_;
|
||||
quint64 timestamp_;
|
||||
|
||||
};
|
||||
|
||||
#endif // LISTENBRAINZSCROBBLER_H
|
||||
230
src/scrobbler/scrobblercache.cpp
Normal file
230
src/scrobbler/scrobblercache.cpp
Normal file
@@ -0,0 +1,230 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <QObject>
|
||||
#include <QStandardPaths>
|
||||
#include <QString>
|
||||
#include <QFile>
|
||||
#include <QIODevice>
|
||||
#include <QTextStream>
|
||||
#include <QDateTime>
|
||||
#include <QMultiHash>
|
||||
#include <QJsonValue>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonParseError>
|
||||
|
||||
#include "core/song.h"
|
||||
#include "core/logging.h"
|
||||
#include "core/closure.h"
|
||||
|
||||
#include "scrobblercache.h"
|
||||
#include "scrobblercacheitem.h"
|
||||
|
||||
ScrobblerCache::ScrobblerCache(const QString &filename, QObject *parent) :
|
||||
QObject(parent),
|
||||
filename_(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/" + filename),
|
||||
loaded_(false) {
|
||||
ReadCache();
|
||||
loaded_ = true;
|
||||
}
|
||||
|
||||
ScrobblerCache::~ScrobblerCache() {}
|
||||
|
||||
void ScrobblerCache::ReadCache() {
|
||||
|
||||
QFile file(filename_);
|
||||
bool result = file.open(QIODevice::ReadOnly | QIODevice::Text);
|
||||
if (!result) return;
|
||||
|
||||
QTextStream stream(&file);
|
||||
stream.setCodec("UTF-8");
|
||||
QString data = stream.readAll();
|
||||
file.close();
|
||||
|
||||
if (data.isEmpty()) return;
|
||||
|
||||
QJsonParseError error;
|
||||
QJsonDocument json_doc = QJsonDocument::fromJson(data.toUtf8(), &error);
|
||||
if (error.error != QJsonParseError::NoError) {
|
||||
qLog(Error) << "Scrobbler cache is missing JSON data.";
|
||||
return;
|
||||
}
|
||||
if (json_doc.isNull() || json_doc.isEmpty()) {
|
||||
qLog(Error) << "Scrobbler cache has empty JSON document.";
|
||||
return;
|
||||
}
|
||||
if (!json_doc.isObject()) {
|
||||
qLog(Error) << "Scrobbler cache JSON document is not an object.";
|
||||
return;
|
||||
}
|
||||
QJsonObject json_obj = json_doc.object();
|
||||
if (json_obj.isEmpty()) {
|
||||
qLog(Error) << "Scrobbler cache has empty JSON object.";
|
||||
return;
|
||||
}
|
||||
if (!json_obj.contains("tracks")) {
|
||||
qLog(Error) << "Scrobbler cache is missing JSON tracks.";
|
||||
return;
|
||||
}
|
||||
QJsonValue json_tracks = json_obj["tracks"];
|
||||
if (!json_tracks.isArray()) {
|
||||
qLog(Error) << "Scrobbler cache JSON tracks is not an array.";
|
||||
return;
|
||||
}
|
||||
QJsonArray json_array = json_tracks.toArray();
|
||||
if (json_array.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const QJsonValue &value : json_array) {
|
||||
if (!value.isObject()) {
|
||||
qLog(Error) << "Scrobbler cache JSON tracks array value is not an object.";
|
||||
qLog(Debug) << value;
|
||||
continue;
|
||||
}
|
||||
QJsonObject json_obj_track = value.toObject();
|
||||
if (
|
||||
!json_obj_track.contains("timestamp") ||
|
||||
!json_obj_track.contains("song") ||
|
||||
!json_obj_track.contains("album") ||
|
||||
!json_obj_track.contains("artist") ||
|
||||
!json_obj_track.contains("albumartist") ||
|
||||
!json_obj_track.contains("track") ||
|
||||
!json_obj_track.contains("duration")
|
||||
) {
|
||||
qLog(Error) << "Scrobbler cache JSON tracks array value is missing data.";
|
||||
qLog(Debug) << value;
|
||||
continue;
|
||||
}
|
||||
|
||||
quint64 timestamp = json_obj_track["timestamp"].toVariant().toULongLong();
|
||||
QString artist = json_obj_track["artist"].toString();
|
||||
QString album = json_obj_track["album"].toString();
|
||||
QString song = json_obj_track["song"].toString();
|
||||
QString albumartist = json_obj_track["albumartist"].toString();
|
||||
int track = json_obj_track["track"].toInt();
|
||||
qint64 duration = json_obj_track["duration"].toVariant().toLongLong();
|
||||
|
||||
if (timestamp <= 0 || artist.isEmpty() || album.isEmpty() || song.isEmpty() || duration <= 0) {
|
||||
qLog(Error) << "Invalid cache data" << "for song" << song;
|
||||
continue;
|
||||
}
|
||||
if (scrobbler_cache_.contains(timestamp)) continue;
|
||||
ScrobblerCacheItem *item = new ScrobblerCacheItem(artist, album, song, albumartist, track, duration, timestamp);
|
||||
scrobbler_cache_.insert(timestamp, item);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void ScrobblerCache::WriteCache() {
|
||||
|
||||
if (!loaded_) return;
|
||||
|
||||
qLog(Debug) << "Writing scrobbler cache file" << filename_;
|
||||
|
||||
QJsonArray array;
|
||||
|
||||
QMultiHash <quint64, ScrobblerCacheItem*> ::iterator i;
|
||||
for (i = scrobbler_cache_.begin() ; i != scrobbler_cache_.end() ; ++i) {
|
||||
ScrobblerCacheItem *item = i.value();
|
||||
QJsonObject object;
|
||||
object.insert("timestamp", QJsonValue::fromVariant(item->timestamp_));
|
||||
object.insert("artist", QJsonValue::fromVariant(item->artist_));
|
||||
object.insert("album", QJsonValue::fromVariant(item->album_));
|
||||
object.insert("song", QJsonValue::fromVariant(item->song_));
|
||||
object.insert("albumartist", QJsonValue::fromVariant(item->albumartist_));
|
||||
object.insert("track", QJsonValue::fromVariant(item->track_));
|
||||
object.insert("duration", QJsonValue::fromVariant(item->duration_));
|
||||
array.append(QJsonValue::fromVariant(object));
|
||||
}
|
||||
|
||||
QJsonObject object;
|
||||
object.insert("tracks", array);
|
||||
QJsonDocument doc(object);
|
||||
|
||||
QFile file(filename_);
|
||||
bool result = file.open(QIODevice::WriteOnly | QIODevice::Text);
|
||||
if (!result) {
|
||||
qLog(Error) << "Unable to open scrobbler cache file" << filename_;
|
||||
return;
|
||||
}
|
||||
QTextStream stream(&file);
|
||||
stream.setCodec("UTF-8");
|
||||
stream << doc.toJson();
|
||||
file.close();
|
||||
|
||||
}
|
||||
|
||||
ScrobblerCacheItem *ScrobblerCache::Add(const Song &song, const quint64 ×tamp) {
|
||||
|
||||
if (scrobbler_cache_.contains(timestamp)) return nullptr;
|
||||
|
||||
ScrobblerCacheItem *item = new ScrobblerCacheItem(song.artist(), song.album(), song.title(), song.albumartist(), song.track(), song.length_nanosec(), timestamp);
|
||||
scrobbler_cache_.insert(timestamp, item);
|
||||
|
||||
if (loaded_) DoInAMinuteOrSo(this, SLOT(WriteCache()));
|
||||
|
||||
return item;
|
||||
|
||||
}
|
||||
|
||||
ScrobblerCacheItem *ScrobblerCache::Get(const quint64 hash) {
|
||||
|
||||
if (scrobbler_cache_.contains(hash)) { return scrobbler_cache_.value(hash); }
|
||||
else return nullptr;
|
||||
|
||||
}
|
||||
|
||||
void ScrobblerCache::Remove(const quint64 hash) {
|
||||
|
||||
if (!scrobbler_cache_.contains(hash)) {
|
||||
qLog(Error) << "Tried to remove non-existing hash" << hash;
|
||||
return;
|
||||
}
|
||||
|
||||
delete scrobbler_cache_.take(hash);
|
||||
|
||||
}
|
||||
|
||||
void ScrobblerCache::Remove(ScrobblerCacheItem &item) {
|
||||
delete scrobbler_cache_.take(item.timestamp_);
|
||||
}
|
||||
|
||||
void ScrobblerCache::ClearSent(const QList<quint64> list) {
|
||||
for (quint64 timestamp : list) {
|
||||
if (!scrobbler_cache_.contains(timestamp)) continue;
|
||||
ScrobblerCacheItem *item = scrobbler_cache_.take(timestamp);
|
||||
item->sent_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
void ScrobblerCache::Flush(const QList<quint64> list) {
|
||||
|
||||
for (quint64 timestamp : list) {
|
||||
if (!scrobbler_cache_.contains(timestamp)) continue;
|
||||
delete scrobbler_cache_.take(timestamp);
|
||||
}
|
||||
DoInAMinuteOrSo(this, SLOT(WriteCache()));
|
||||
|
||||
}
|
||||
64
src/scrobbler/scrobblercache.h
Normal file
64
src/scrobbler/scrobblercache.h
Normal file
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef SCROBBLERCACHE_H
|
||||
#define SCROBBLERCACHE_H
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
#include <QObject>
|
||||
#include <QList>
|
||||
#include <QHash>
|
||||
#include <QString>
|
||||
#include <QDateTime>
|
||||
|
||||
class Application;
|
||||
class Song;
|
||||
class ScrobblerCacheItem;
|
||||
|
||||
class ScrobblerCache : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit ScrobblerCache(const QString &filename, QObject *parent);
|
||||
~ScrobblerCache();
|
||||
|
||||
void ReadCache();
|
||||
|
||||
ScrobblerCacheItem *Add(const Song &song, const quint64 ×tamp);
|
||||
ScrobblerCacheItem *Get(const quint64 hash);
|
||||
void Remove(const quint64 hash);
|
||||
void Remove(ScrobblerCacheItem &item);
|
||||
QList<ScrobblerCacheItem*> List() const { return scrobbler_cache_.values(); }
|
||||
void ClearSent(const QList<quint64> list);
|
||||
void Flush(const QList<quint64> list);
|
||||
|
||||
public slots:
|
||||
void WriteCache();
|
||||
|
||||
private:
|
||||
QString filename_;
|
||||
bool loaded_;
|
||||
QHash <quint64, ScrobblerCacheItem*> scrobbler_cache_;
|
||||
|
||||
};
|
||||
|
||||
#endif // SCROBBLERCACHE_H
|
||||
39
src/scrobbler/scrobblercacheitem.cpp
Normal file
39
src/scrobbler/scrobblercacheitem.cpp
Normal file
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <QObject>
|
||||
#include <QtGlobal>
|
||||
#include <QString>
|
||||
#include <QHash>
|
||||
|
||||
#include "scrobblercacheitem.h"
|
||||
|
||||
ScrobblerCacheItem::ScrobblerCacheItem(const QString &artist, const QString &album, const QString &song, const QString &albumartist, const int track, const qint64 duration, const quint64 ×tamp) :
|
||||
artist_(artist),
|
||||
album_(album),
|
||||
song_(song),
|
||||
albumartist_(albumartist),
|
||||
track_(track),
|
||||
duration_(duration),
|
||||
timestamp_(timestamp),
|
||||
sent_(false) {}
|
||||
|
||||
ScrobblerCacheItem::~ScrobblerCacheItem() {}
|
||||
48
src/scrobbler/scrobblercacheitem.h
Normal file
48
src/scrobbler/scrobblercacheitem.h
Normal file
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef SCROBBLERCACHEITEM_H
|
||||
#define SCROBBLERCACHEITEM_H
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <QtGlobal>
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
|
||||
class ScrobblerCacheItem : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit ScrobblerCacheItem(const QString &artist, const QString &album, const QString &song, const QString &albumartist, const int track, const qint64 duration, const quint64 ×tamp);
|
||||
~ScrobblerCacheItem();
|
||||
|
||||
public:
|
||||
QString artist_;
|
||||
QString album_;
|
||||
QString song_;
|
||||
QString albumartist_;
|
||||
int track_;
|
||||
qint64 duration_;
|
||||
quint64 timestamp_;
|
||||
bool sent_;
|
||||
|
||||
};
|
||||
|
||||
#endif // SCROBBLERCACHEITEM_H
|
||||
57
src/scrobbler/scrobblerservice.cpp
Normal file
57
src/scrobbler/scrobblerservice.cpp
Normal file
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
#include <QByteArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
|
||||
#include "scrobblerservice.h"
|
||||
|
||||
ScrobblerService::ScrobblerService(const QString &name, Application *app, QObject *parent) : QObject(parent), name_(name) {}
|
||||
|
||||
QJsonObject ScrobblerService::ExtractJsonObj(const QByteArray &data) {
|
||||
|
||||
QJsonParseError error;
|
||||
QJsonDocument json_doc = QJsonDocument::fromJson(data, &error);
|
||||
|
||||
if (error.error != QJsonParseError::NoError) {
|
||||
Error("Reply from server missing Json data.", data);
|
||||
return QJsonObject();
|
||||
}
|
||||
if (json_doc.isNull() || json_doc.isEmpty()) {
|
||||
Error("Received empty Json document.", json_doc);
|
||||
return QJsonObject();
|
||||
}
|
||||
if (!json_doc.isObject()) {
|
||||
Error("Json document is not an object.", json_doc);
|
||||
return QJsonObject();
|
||||
}
|
||||
QJsonObject json_obj = json_doc.object();
|
||||
if (json_obj.isEmpty()) {
|
||||
Error("Received empty Json object.", json_doc);
|
||||
return QJsonObject();
|
||||
}
|
||||
|
||||
return json_obj;
|
||||
|
||||
}
|
||||
76
src/scrobbler/scrobblerservice.h
Normal file
76
src/scrobbler/scrobblerservice.h
Normal file
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef SCROBBLERSERVICE_H
|
||||
#define SCROBBLERSERVICE_H
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
#include <QVariant>
|
||||
#include <QByteArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
|
||||
class Application;
|
||||
class Song;
|
||||
|
||||
class ScrobblerService : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit ScrobblerService(const QString &name, Application *app, QObject *parent);
|
||||
|
||||
QString name() const { return name_; }
|
||||
|
||||
virtual void ReloadSettings() = 0;
|
||||
|
||||
virtual bool IsEnabled() const { return false; }
|
||||
virtual bool IsAuthenticated() const { return false; }
|
||||
|
||||
virtual void UpdateNowPlaying(const Song &song) = 0;
|
||||
virtual void Scrobble(const Song &song) = 0;
|
||||
virtual void Love(const Song &song) = 0;
|
||||
virtual void Error(QString error, QVariant debug = QVariant()) = 0;
|
||||
|
||||
virtual void Submitted() = 0;
|
||||
virtual bool IsSubmitted() const { return false; }
|
||||
|
||||
typedef QPair<QString, QString> Param;
|
||||
typedef QPair<QByteArray, QByteArray> EncodedParam;
|
||||
typedef QList<Param> ParamList;
|
||||
|
||||
QJsonObject ExtractJsonObj(const QByteArray &data);
|
||||
|
||||
public slots:
|
||||
virtual void Submit() = 0;
|
||||
virtual void WriteCache() = 0;
|
||||
|
||||
signals:
|
||||
void ErrorMessage(QString);
|
||||
|
||||
private:
|
||||
QString name_;
|
||||
|
||||
};
|
||||
|
||||
#endif // SCROBBLERSERVICE_H
|
||||
77
src/scrobbler/scrobblerservices.cpp
Normal file
77
src/scrobbler/scrobblerservices.cpp
Normal file
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <QObject>
|
||||
#include <QMutexLocker>
|
||||
#include <QString>
|
||||
#include <QtDebug>
|
||||
|
||||
#include "core/application.h"
|
||||
#include "core/logging.h"
|
||||
|
||||
#include "scrobblerservices.h"
|
||||
#include "scrobblerservice.h"
|
||||
|
||||
ScrobblerServices::ScrobblerServices(QObject *parent) : QObject(parent) {}
|
||||
|
||||
ScrobblerServices::~ScrobblerServices() {}
|
||||
|
||||
void ScrobblerServices::AddService(ScrobblerService *service) {
|
||||
|
||||
{
|
||||
QMutexLocker locker(&mutex_);
|
||||
scrobbler_services_.insert(service->name(), service);
|
||||
connect(service, SIGNAL(destroyed()), SLOT(ServiceDestroyed()));
|
||||
}
|
||||
|
||||
qLog(Debug) << "Registered scrobbler service" << service->name();
|
||||
|
||||
}
|
||||
|
||||
void ScrobblerServices::RemoveService(ScrobblerService *service) {
|
||||
|
||||
if (!service || !scrobbler_services_.contains(service->name())) return;
|
||||
|
||||
{
|
||||
QMutexLocker locker(&mutex_);
|
||||
scrobbler_services_.remove(service->name());
|
||||
disconnect(service, 0, this, 0);
|
||||
}
|
||||
|
||||
qLog(Debug) << "Unregistered scrobbler service" << service->name();
|
||||
|
||||
}
|
||||
|
||||
void ScrobblerServices::ServiceDestroyed() {
|
||||
|
||||
ScrobblerService *service = static_cast<ScrobblerService*>(sender());
|
||||
RemoveService(service);
|
||||
|
||||
}
|
||||
|
||||
int ScrobblerServices::NextId() { return next_id_.fetchAndAddRelaxed(1); }
|
||||
|
||||
ScrobblerService *ScrobblerServices::ServiceByName(const QString &name) {
|
||||
|
||||
if (scrobbler_services_.contains(name)) return scrobbler_services_.value(name);
|
||||
return nullptr;
|
||||
|
||||
}
|
||||
70
src/scrobbler/scrobblerservices.h
Normal file
70
src/scrobbler/scrobblerservices.h
Normal file
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef SCROBBLERSERVICES_H
|
||||
#define SCROBBLERSERVICES_H
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
#include <QtGlobal>
|
||||
#include <QObject>
|
||||
#include <QMutex>
|
||||
#include <QList>
|
||||
#include <QMap>
|
||||
#include <QString>
|
||||
#include <QAtomicInt>
|
||||
|
||||
class Application;
|
||||
class ScrobblerService;
|
||||
|
||||
class ScrobblerServices : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit ScrobblerServices(QObject *parent = nullptr);
|
||||
~ScrobblerServices();
|
||||
|
||||
void AddService(ScrobblerService *service);
|
||||
void RemoveService(ScrobblerService *service);
|
||||
QList<ScrobblerService*> List() const { return scrobbler_services_.values(); }
|
||||
bool HasAnyServices() const { return !scrobbler_services_.isEmpty(); }
|
||||
int NextId();
|
||||
|
||||
ScrobblerService *ServiceByName(const QString &name);
|
||||
template <typename T>
|
||||
T *Service() {
|
||||
return static_cast<T*>(this->ServiceByName(T::kName));
|
||||
}
|
||||
|
||||
private slots:
|
||||
void ServiceDestroyed();
|
||||
|
||||
private:
|
||||
Q_DISABLE_COPY(ScrobblerServices);
|
||||
|
||||
QMap<QString, ScrobblerService *> scrobbler_services_;
|
||||
QMutex mutex_;
|
||||
|
||||
QAtomicInt next_id_;
|
||||
|
||||
};
|
||||
|
||||
#endif // SCROBBLERSERVICES_H
|
||||
740
src/scrobbler/scrobblingapi20.cpp
Normal file
740
src/scrobbler/scrobblingapi20.cpp
Normal file
@@ -0,0 +1,740 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include <QtGlobal>
|
||||
#include <QDesktopServices>
|
||||
#include <QVariant>
|
||||
#include <QByteArray>
|
||||
#include <QString>
|
||||
#include <QUrl>
|
||||
#include <QUrlQuery>
|
||||
#include <QDateTime>
|
||||
#include <QCryptographicHash>
|
||||
#include <QMenu>
|
||||
#include <QMessageBox>
|
||||
#include <QSettings>
|
||||
#include <QNetworkRequest>
|
||||
#include <QNetworkReply>
|
||||
#include <QJsonParseError>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonValue>
|
||||
|
||||
#include "core/application.h"
|
||||
#include "core/player.h"
|
||||
#include "core/closure.h"
|
||||
#include "core/network.h"
|
||||
#include "core/song.h"
|
||||
#include "core/timeconstants.h"
|
||||
#include "core/logging.h"
|
||||
#include "internet/localredirectserver.h"
|
||||
#include "settings/settingsdialog.h"
|
||||
#include "settings/scrobblersettingspage.h"
|
||||
|
||||
#include "audioscrobbler.h"
|
||||
#include "scrobblerservices.h"
|
||||
#include "scrobblingapi20.h"
|
||||
#include "scrobblercache.h"
|
||||
#include "scrobblercacheitem.h"
|
||||
|
||||
const char *ScrobblingAPI20::kApiKey = "211990b4c96782c05d1536e7219eb56e";
|
||||
const char *ScrobblingAPI20::kSecret = "80fd738f49596e9709b1bf9319c444a8";
|
||||
const char *ScrobblingAPI20::kRedirectUrl = "https://oauth.strawbs.net";
|
||||
const int ScrobblingAPI20::kScrobblesPerRequest = 50;
|
||||
|
||||
ScrobblingAPI20::ScrobblingAPI20(const QString &name, const QString &settings_group, const QString &auth_url, const QString &api_url, const bool batch, Application *app, QObject *parent) :
|
||||
ScrobblerService(name, app, parent),
|
||||
name_(name),
|
||||
settings_group_(settings_group),
|
||||
auth_url_(auth_url),
|
||||
api_url_(api_url),
|
||||
batch_(batch),
|
||||
app_(app),
|
||||
enabled_(false),
|
||||
subscriber_(false),
|
||||
submitted_(false) {}
|
||||
|
||||
ScrobblingAPI20::~ScrobblingAPI20() {}
|
||||
|
||||
void ScrobblingAPI20::ReloadSettings() {
|
||||
|
||||
QSettings s;
|
||||
s.beginGroup(settings_group_);
|
||||
enabled_ = s.value("enabled", false).toBool();
|
||||
s.endGroup();
|
||||
|
||||
}
|
||||
|
||||
void ScrobblingAPI20::LoadSession() {
|
||||
|
||||
QSettings s;
|
||||
s.beginGroup(settings_group_);
|
||||
subscriber_ = s.value("subscriber", false).toBool();
|
||||
username_ = s.value("username").toString();
|
||||
session_key_ = s.value("session_key").toString();
|
||||
s.endGroup();
|
||||
|
||||
}
|
||||
|
||||
void ScrobblingAPI20::Logout() {
|
||||
|
||||
subscriber_ = false;
|
||||
username_.clear();
|
||||
session_key_.clear();
|
||||
|
||||
QSettings settings;
|
||||
settings.beginGroup(settings_group_);
|
||||
settings.remove("subscriber");
|
||||
settings.remove("username");
|
||||
settings.remove("session_key");
|
||||
settings.endGroup();
|
||||
|
||||
}
|
||||
|
||||
void ScrobblingAPI20::Authenticate() {
|
||||
|
||||
QUrl url(auth_url_);
|
||||
|
||||
LocalRedirectServer *server = new LocalRedirectServer(this);
|
||||
server->Listen();
|
||||
NewClosure(server, SIGNAL(Finished()), this, &ScrobblingAPI20::RedirectArrived, server);
|
||||
|
||||
QUrl redirect_url(kRedirectUrl);
|
||||
QUrlQuery redirect_url_query;
|
||||
const QString port = QString::number(server->url().port());
|
||||
redirect_url_query.addQueryItem("port", port);
|
||||
redirect_url.setQuery(redirect_url_query);
|
||||
|
||||
QUrlQuery url_query;
|
||||
url_query.addQueryItem("api_key", kApiKey);
|
||||
url_query.addQueryItem("cb", redirect_url.toString());
|
||||
url.setQuery(url_query);
|
||||
|
||||
bool result = QDesktopServices::openUrl(url);
|
||||
if (!result) {
|
||||
QMessageBox box(QMessageBox::NoIcon, "Scrobbler Authentication", QString("Please open this URL in your browser: <a href=\"%1\">%1</a>").arg(url.toString()), QMessageBox::Ok);
|
||||
box.setTextFormat(Qt::RichText);
|
||||
qLog(Debug) << "Scrobbler authentication URL: " << url.toString();
|
||||
box.exec();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void ScrobblingAPI20::RedirectArrived(LocalRedirectServer *server) {
|
||||
|
||||
server->deleteLater();
|
||||
|
||||
QUrl url = server->request_url();
|
||||
RequestSession(QUrlQuery(url).queryItemValue("token").toUtf8());
|
||||
|
||||
}
|
||||
|
||||
void ScrobblingAPI20::RequestSession(QString token) {
|
||||
|
||||
QUrl session_url(api_url_);
|
||||
QUrlQuery session_url_query;
|
||||
session_url_query.addQueryItem("api_key", kApiKey);
|
||||
session_url_query.addQueryItem("method", "auth.getSession");
|
||||
session_url_query.addQueryItem("token", token);
|
||||
QString data_to_sign;
|
||||
for (QPair<QString, QString> param : session_url_query.queryItems()) {
|
||||
data_to_sign += param.first + param.second;
|
||||
}
|
||||
data_to_sign += kSecret;
|
||||
QByteArray const digest = QCryptographicHash::hash(data_to_sign.toUtf8(), QCryptographicHash::Md5);
|
||||
QString signature = QString::fromLatin1(digest.toHex()).rightJustified(32, '0').toLower();
|
||||
session_url_query.addQueryItem("api_sig", signature);
|
||||
session_url_query.addQueryItem(QUrl::toPercentEncoding("format"), QUrl::toPercentEncoding("json"));
|
||||
session_url.setQuery(session_url_query);
|
||||
|
||||
QNetworkRequest req(session_url);
|
||||
QNetworkReply *reply = network()->get(req);
|
||||
NewClosure(reply, SIGNAL(finished()), this, SLOT(AuthenticateReplyFinished(QNetworkReply*)), reply);
|
||||
|
||||
}
|
||||
|
||||
void ScrobblingAPI20::AuthenticateReplyFinished(QNetworkReply *reply) {
|
||||
|
||||
reply->deleteLater();
|
||||
|
||||
QByteArray data;
|
||||
|
||||
if (reply->error() == QNetworkReply::NoError && reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 200) {
|
||||
data = reply->readAll();
|
||||
}
|
||||
else {
|
||||
if (reply->error() < 200) {
|
||||
// This is a network error, there is nothing more to do.
|
||||
QString failure_reason = QString("%1 (%2)").arg(reply->errorString()).arg(reply->error());
|
||||
AuthError(failure_reason);
|
||||
}
|
||||
else {
|
||||
// See if there is Json data containing "error" and "message" - then use that instead.
|
||||
data = reply->readAll();
|
||||
QJsonParseError error;
|
||||
QJsonDocument json_doc = QJsonDocument::fromJson(data, &error);
|
||||
QString failure_reason;
|
||||
if (error.error == QJsonParseError::NoError && !json_doc.isNull() && !json_doc.isEmpty() && json_doc.isObject()) {
|
||||
QJsonObject json_obj = json_doc.object();
|
||||
if (json_obj.contains("error") && json_obj.contains("message")) {
|
||||
int error = json_obj["error"].toInt();
|
||||
QString message = json_obj["message"].toString();
|
||||
failure_reason = "Error: " + QString::number(error) + ": " + message;
|
||||
}
|
||||
else {
|
||||
failure_reason = QString("%1 (%2)").arg(reply->errorString()).arg(reply->error());
|
||||
}
|
||||
}
|
||||
else {
|
||||
failure_reason = QString("%1 (%2)").arg(reply->errorString()).arg(reply->error());
|
||||
}
|
||||
AuthError(failure_reason);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonObject json_obj = ExtractJsonObj(data);
|
||||
if (json_obj.isEmpty()) {
|
||||
AuthError("Json document from server was empty.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (json_obj.contains("error") && json_obj.contains("message")) {
|
||||
int error = json_obj["error"].toInt();
|
||||
QString message = json_obj["message"].toString();
|
||||
QString failure_reason = "Error: " + QString::number(error) + ": " + message;
|
||||
AuthError(failure_reason);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!json_obj.contains("session")) {
|
||||
AuthError("Json reply from server is missing session.");
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonValue json_session = json_obj["session"];
|
||||
if (!json_session.isObject()) {
|
||||
AuthError("Json session is not an object.");
|
||||
return;
|
||||
}
|
||||
json_obj = json_session.toObject();
|
||||
if (json_obj.isEmpty()) {
|
||||
AuthError("Json session object is empty.");
|
||||
return;
|
||||
}
|
||||
if (!json_obj.contains("subscriber") || !json_obj.contains("name") || !json_obj.contains("key")) {
|
||||
AuthError("Json session object is missing values.");
|
||||
return;
|
||||
}
|
||||
|
||||
subscriber_ = json_obj["subscriber"].toBool();
|
||||
username_ = json_obj["name"].toString();
|
||||
session_key_ = json_obj["key"].toString();
|
||||
|
||||
QSettings s;
|
||||
s.beginGroup(settings_group_);
|
||||
s.setValue("subscriber", subscriber_);
|
||||
s.setValue("username", username_);
|
||||
s.setValue("session_key", session_key_);
|
||||
s.endGroup();
|
||||
|
||||
emit AuthenticationComplete(true);
|
||||
|
||||
}
|
||||
|
||||
QNetworkReply *ScrobblingAPI20::CreateRequest(const ParamList &request_params) {
|
||||
|
||||
ParamList params = ParamList()
|
||||
<< Param("api_key", kApiKey)
|
||||
<< Param("sk", session_key_)
|
||||
<< Param("lang", QLocale().name().left(2).toLower())
|
||||
<< request_params;
|
||||
|
||||
std::sort(params.begin(), params.end());
|
||||
|
||||
QUrlQuery url_query;
|
||||
QString data_to_sign;
|
||||
for (const Param ¶m : params) {
|
||||
EncodedParam encoded_param(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second));
|
||||
url_query.addQueryItem(encoded_param.first, encoded_param.second);
|
||||
data_to_sign += param.first + param.second;
|
||||
}
|
||||
data_to_sign += kSecret;
|
||||
|
||||
QByteArray const digest = QCryptographicHash::hash(data_to_sign.toUtf8(), QCryptographicHash::Md5);
|
||||
QString signature = QString::fromLatin1(digest.toHex()).rightJustified(32, '0').toLower();
|
||||
|
||||
url_query.addQueryItem("api_sig", QUrl::toPercentEncoding(signature));
|
||||
url_query.addQueryItem("format", QUrl::toPercentEncoding("json"));
|
||||
|
||||
QUrl url(api_url_);
|
||||
QNetworkRequest req(url);
|
||||
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
|
||||
QByteArray query = url_query.toString(QUrl::FullyEncoded).toUtf8();
|
||||
QNetworkReply *reply = network()->post(req, query);
|
||||
|
||||
//qLog(Debug) << name_ << "Sending request" << query;
|
||||
|
||||
return reply;
|
||||
|
||||
}
|
||||
|
||||
QByteArray ScrobblingAPI20::GetReplyData(QNetworkReply *reply) {
|
||||
|
||||
QByteArray data;
|
||||
|
||||
if (reply->error() == QNetworkReply::NoError && reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 200) {
|
||||
data = reply->readAll();
|
||||
}
|
||||
else {
|
||||
if (reply->error() < 200) {
|
||||
// This is a network error, there is nothing more to do.
|
||||
QString error_reason = QString("%1 (%2)").arg(reply->errorString()).arg(reply->error());
|
||||
Error(error_reason);
|
||||
}
|
||||
else {
|
||||
// See if there is Json data containing "error" and "message" - then use that instead.
|
||||
data = reply->readAll();
|
||||
QJsonParseError error;
|
||||
QJsonDocument json_doc = QJsonDocument::fromJson(data, &error);
|
||||
int error_code = -1;
|
||||
QString error_reason;
|
||||
if (error.error == QJsonParseError::NoError && !json_doc.isNull() && !json_doc.isEmpty() && json_doc.isObject()) {
|
||||
QJsonObject json_obj = json_doc.object();
|
||||
if (json_obj.contains("error") && json_obj.contains("message")) {
|
||||
error_code = json_obj["error"].toInt();
|
||||
QString message = json_obj["message"].toString();
|
||||
error_reason = QString("%1 (%2)").arg(message).arg(error_code);
|
||||
}
|
||||
else {
|
||||
error_reason = QString("%1 (%2)").arg(reply->errorString()).arg(reply->error());
|
||||
}
|
||||
}
|
||||
else {
|
||||
error_reason = QString("%1 (%2)").arg(reply->errorString()).arg(reply->error());
|
||||
}
|
||||
if (reply->error() == QNetworkReply::ContentAccessDenied ||
|
||||
reply->error() == QNetworkReply::ContentOperationNotPermittedError ||
|
||||
reply->error() == QNetworkReply::AuthenticationRequiredError ||
|
||||
error_code == ScrobbleErrorCode::InvalidSessionKey ||
|
||||
error_code == ScrobbleErrorCode::AuthenticationFailed
|
||||
){
|
||||
// Session is probably expired
|
||||
Logout();
|
||||
Error(error_reason);
|
||||
}
|
||||
else if (reply->error() == QNetworkReply::ContentNotFoundError) { // Ignore this error
|
||||
Error(error_reason);
|
||||
}
|
||||
else { // Fail
|
||||
Error(error_reason);
|
||||
}
|
||||
}
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
}
|
||||
|
||||
void ScrobblingAPI20::UpdateNowPlaying(const Song &song) {
|
||||
|
||||
song_playing_ = song;
|
||||
timestamp_ = QDateTime::currentDateTime().toTime_t();
|
||||
|
||||
if (!IsAuthenticated() || !song.is_metadata_good()) return;
|
||||
|
||||
ParamList params = ParamList()
|
||||
<< Param("method", "track.updateNowPlaying")
|
||||
<< Param("artist", song.artist())
|
||||
<< Param("track", song.title())
|
||||
<< Param("album", song.album());
|
||||
|
||||
QNetworkReply *reply = CreateRequest(params);
|
||||
NewClosure(reply, SIGNAL(finished()), this, SLOT(UpdateNowPlayingRequestFinished(QNetworkReply*)), reply);
|
||||
|
||||
}
|
||||
|
||||
void ScrobblingAPI20::UpdateNowPlayingRequestFinished(QNetworkReply *reply) {
|
||||
|
||||
reply->deleteLater();
|
||||
|
||||
QByteArray data = GetReplyData(reply);
|
||||
if (data.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO
|
||||
|
||||
}
|
||||
|
||||
void ScrobblingAPI20::Scrobble(const Song &song) {
|
||||
|
||||
if (song.id() != song_playing_.id() || song.url() != song_playing_.url() || !song.is_metadata_good()) return;
|
||||
|
||||
cache()->Add(song, timestamp_);
|
||||
|
||||
if (app_->scrobbler()->IsOffline()) return;
|
||||
|
||||
if (!IsAuthenticated()) {
|
||||
emit ErrorMessage(QString("Scrobbler %1 is not authenticated!").arg(name_));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!submitted_) {
|
||||
DoInAMinuteOrSo(this, SLOT(Submit()));
|
||||
submitted_ = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void ScrobblingAPI20::Submit() {
|
||||
|
||||
qLog(Debug) << __PRETTY_FUNCTION__ << name_;
|
||||
|
||||
submitted_ = false;
|
||||
|
||||
if (!IsEnabled() || !IsAuthenticated() || app_->scrobbler()->IsOffline()) return;
|
||||
|
||||
ParamList params = ParamList()
|
||||
<< Param("method", "track.scrobble");
|
||||
|
||||
int i(0);
|
||||
QList<quint64> list;
|
||||
for (ScrobblerCacheItem *item : cache()->List()) {
|
||||
if (item->sent_) continue;
|
||||
item->sent_ = true;
|
||||
if (!batch_) { SendSingleScrobble(item); continue; }
|
||||
i++;
|
||||
list << item->timestamp_;
|
||||
params << Param(QString("%1[%2]").arg("artist").arg(i), item->artist_);
|
||||
params << Param(QString("%1[%2]").arg("album").arg(i), item->album_);
|
||||
params << Param(QString("%1[%2]").arg("track").arg(i), item->song_);
|
||||
params << Param(QString("%1[%2]").arg("timestamp").arg(i), QString::number(item->timestamp_));
|
||||
params << Param(QString("%1[%2]").arg("duration").arg(i), QString::number(item->duration_ / kNsecPerSec));
|
||||
if (!item->albumartist_.isEmpty()) params << Param(QString("%1[%2]").arg("albumArtist").arg(i), item->albumartist_);
|
||||
if (item->track_ > 0) params << Param(QString("%1[%2]").arg(i).arg("trackNumber"), QString::number(item->track_));
|
||||
if (i >= kScrobblesPerRequest) break;
|
||||
}
|
||||
|
||||
if (!batch_ || i <= 0) return;
|
||||
|
||||
QNetworkReply *reply = CreateRequest(params);
|
||||
NewClosure(reply, SIGNAL(finished()), this, SLOT(ScrobbleRequestFinished(QNetworkReply*, QList<quint64>)), reply, list);
|
||||
|
||||
}
|
||||
|
||||
void ScrobblingAPI20::ScrobbleRequestFinished(QNetworkReply *reply, QList<quint64> list) {
|
||||
|
||||
reply->deleteLater();
|
||||
|
||||
QByteArray data = GetReplyData(reply);
|
||||
if (data.isEmpty()) {
|
||||
cache()->ClearSent(list);
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonObject json_obj = ExtractJsonObj(data);
|
||||
if (json_obj.isEmpty()) {
|
||||
cache()->ClearSent(list);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!json_obj.contains("scrobbles")) {
|
||||
if (json_obj.contains("error")) {
|
||||
int error = json_obj["error"].toInt();
|
||||
Error(QString("Error: %1: %2").arg(QString::number(error)).arg(error));
|
||||
}
|
||||
Error("Json reply from server is missing session.");
|
||||
cache()->ClearSent(list);
|
||||
return;
|
||||
}
|
||||
|
||||
cache()->Flush(list);
|
||||
|
||||
QJsonValue json_scrobbles = json_obj["scrobbles"];
|
||||
if (!json_scrobbles.isObject()) {
|
||||
Error("Json scrobbles is not an object.", json_obj);
|
||||
return;
|
||||
}
|
||||
json_obj = json_scrobbles.toObject();
|
||||
if (json_obj.isEmpty()) {
|
||||
Error("Json scrobbles object is empty.", json_scrobbles);
|
||||
return;
|
||||
}
|
||||
if (!json_obj.contains("@attr") || !json_obj.contains("scrobble")) {
|
||||
Error("Json scrobbles object is missing values.", json_obj);
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonValue json_attr = json_obj["@attr"];
|
||||
if (!json_attr.isObject()) {
|
||||
Error("Json scrobbles attr is not an object.", json_attr);
|
||||
return;
|
||||
}
|
||||
QJsonObject json_obj_attr = json_attr.toObject();
|
||||
if (json_obj_attr.isEmpty()) {
|
||||
Error("Json scrobbles attr is empty.", json_attr);
|
||||
return;
|
||||
}
|
||||
if (!json_obj_attr.contains("accepted") || !json_obj_attr.contains("ignored")) {
|
||||
Error("Json scrobbles attr is missing values.", json_obj_attr);
|
||||
return;
|
||||
}
|
||||
int accepted = json_obj_attr["accepted"].toInt();
|
||||
int ignored = json_obj_attr["ignored"].toInt();
|
||||
qLog(Debug) << name_ << "Scrobbles accepted:" << accepted << "ignored:" << ignored;
|
||||
|
||||
QJsonValue json_scrobble = json_obj["scrobble"];
|
||||
if (!json_scrobble.isArray()) {
|
||||
Error("Json scrobbles scrobble is not array.", json_scrobble);
|
||||
return;
|
||||
}
|
||||
QJsonArray json_array_scrobble = json_scrobble.toArray();
|
||||
if (json_array_scrobble.isEmpty()) {
|
||||
Error("Json scrobbles scrobble array is empty.", json_scrobble);
|
||||
return;
|
||||
}
|
||||
|
||||
for (const QJsonValue &value : json_array_scrobble) {
|
||||
|
||||
if (!value.isObject()) {
|
||||
Error("Json scrobbles scrobble array value is not an object.", value);
|
||||
continue;
|
||||
}
|
||||
QJsonObject json_track = value.toObject();
|
||||
if (json_track.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!json_track.contains("artist") ||
|
||||
!json_track.contains("album") ||
|
||||
!json_track.contains("albumArtist") ||
|
||||
!json_track.contains("track") ||
|
||||
!json_track.contains("timestamp") ||
|
||||
!json_track.contains("ignoredMessage")
|
||||
) {
|
||||
Error("Json scrobbles scrobble is missing values.", json_track);
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonValue json_value_artist = json_track["artist"];
|
||||
QJsonValue json_value_album = json_track["album"];
|
||||
QJsonValue json_value_song = json_track["track"];
|
||||
//quint64 timestamp = json_track["timestamp"].toVariant().toULongLong();
|
||||
|
||||
if (!json_value_artist.isObject() || !json_value_album.isObject() || !json_value_song.isObject()) {
|
||||
Error("Json scrobbles scrobble values are not objects.", json_track);
|
||||
continue;
|
||||
}
|
||||
|
||||
QJsonObject json_obj_artist = json_value_artist.toObject();
|
||||
QJsonObject json_obj_album = json_value_album.toObject();
|
||||
QJsonObject json_obj_song = json_value_song.toObject();
|
||||
|
||||
if (json_obj_artist.isEmpty() || json_obj_album.isEmpty() || json_obj_song.isEmpty()) {
|
||||
Error("Json scrobbles scrobble values objects are empty.", json_track);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!json_obj_artist.contains("#text") || !json_obj_album.contains("#text") || !json_obj_song.contains("#text")) {
|
||||
Error("Json scrobbles scrobble values objects are empty.", json_track);
|
||||
continue;
|
||||
}
|
||||
|
||||
// TODO
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void ScrobblingAPI20::SendSingleScrobble(ScrobblerCacheItem *item) {
|
||||
|
||||
ParamList params = ParamList()
|
||||
<< Param("method", "track.scrobble")
|
||||
<< Param("artist", item->artist_)
|
||||
<< Param("album", item->album_)
|
||||
<< Param("track", item->song_)
|
||||
<< Param("timestamp", QString::number(item->timestamp_))
|
||||
<< Param("duration", QString::number(item->duration_ / kNsecPerSec));
|
||||
|
||||
if (!item->albumartist_.isEmpty()) params << Param("albumArtist", item->albumartist_);
|
||||
if (item->track_ > 0) params << Param("trackNumber", QString::number(item->track_));
|
||||
|
||||
QNetworkReply *reply = CreateRequest(params);
|
||||
NewClosure(reply, SIGNAL(finished()), this, SLOT(SingleScrobbleRequestFinished(QNetworkReply*, quint64)), reply, item->timestamp_);
|
||||
|
||||
}
|
||||
|
||||
void ScrobblingAPI20::SingleScrobbleRequestFinished(QNetworkReply *reply, quint64 timestamp) {
|
||||
|
||||
reply->deleteLater();
|
||||
|
||||
ScrobblerCacheItem *item = cache()->Get(timestamp);
|
||||
if (!item) {
|
||||
Error(QString("Received reply for non-existing cache entry %1.").arg(timestamp));
|
||||
return;
|
||||
}
|
||||
|
||||
QByteArray data = GetReplyData(reply);
|
||||
if (data.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonObject json_obj = ExtractJsonObj(data);
|
||||
if (json_obj.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!json_obj.contains("scrobbles")) {
|
||||
if (json_obj.contains("error")) {
|
||||
int error = json_obj["error"].toInt();
|
||||
Error(QString("Error: %1: %2").arg(QString::number(error)).arg(error));
|
||||
}
|
||||
Error("Json reply from server is missing session.");
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonValue json_scrobbles = json_obj["scrobbles"];
|
||||
if (!json_scrobbles.isObject()) {
|
||||
Error("Json scrobbles is not an object.", json_obj);
|
||||
return;
|
||||
}
|
||||
json_obj = json_scrobbles.toObject();
|
||||
if (json_obj.isEmpty()) {
|
||||
Error("Json scrobbles object is empty.", json_scrobbles);
|
||||
return;
|
||||
}
|
||||
if (!json_obj.contains("@attr") || !json_obj.contains("scrobble")) {
|
||||
Error("Json scrobbles object is missing values.", json_obj);
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonValue json_attr = json_obj["@attr"];
|
||||
if (!json_attr.isObject()) {
|
||||
Error("Json scrobbles attr is not an object.", json_attr);
|
||||
return;
|
||||
}
|
||||
QJsonObject json_obj_attr = json_attr.toObject();
|
||||
if (json_obj_attr.isEmpty()) {
|
||||
Error("Json scrobbles attr is empty.", json_attr);
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonValue json_scrobble = json_obj["scrobble"];
|
||||
if (!json_scrobble.isObject()) {
|
||||
Error("Json scrobbles scrobble is not an object.", json_scrobble);
|
||||
return;
|
||||
}
|
||||
QJsonObject json_obj_scrobble = json_scrobble.toObject();
|
||||
if (json_obj_scrobble.isEmpty()) {
|
||||
Error("Json scrobbles scrobble is empty.", json_scrobble);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!json_obj_attr.contains("accepted") || !json_obj_attr.contains("ignored")) {
|
||||
Error("Json scrobbles attr is missing values.", json_obj_attr);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!json_obj_scrobble.contains("artist") || !json_obj_scrobble.contains("album") || !json_obj_scrobble.contains("albumArtist") || !json_obj_scrobble.contains("track") || !json_obj_scrobble.contains("timestamp")) {
|
||||
Error("Json scrobbles scrobble is missing values.", json_obj_scrobble);
|
||||
return;
|
||||
}
|
||||
|
||||
int accepted = json_obj_attr["accepted"].toVariant().toInt();
|
||||
if (accepted == 1) {
|
||||
qLog(Debug) << name_ << "Scrobble for" << item->song_ << "accepted";
|
||||
}
|
||||
else {
|
||||
Error(QString("Scrobble for \"%1\" not accepted").arg(item->song_));
|
||||
qLog(Debug) << name_ << json_obj_attr["accepted"];
|
||||
}
|
||||
|
||||
cache()->Remove(timestamp);
|
||||
|
||||
}
|
||||
|
||||
void ScrobblingAPI20::Love(const Song &song) {
|
||||
|
||||
if (!IsAuthenticated()) app_->scrobbler()->ShowConfig();
|
||||
|
||||
ParamList params = ParamList()
|
||||
<< Param("method", "track.love")
|
||||
<< Param("artist", song.artist())
|
||||
<< Param("track", song.title())
|
||||
<< Param("album", song.album());
|
||||
|
||||
QNetworkReply *reply = CreateRequest(params);
|
||||
NewClosure(reply, SIGNAL(finished()), this, SLOT(RequestFinished(QNetworkReply*)), reply);
|
||||
|
||||
}
|
||||
|
||||
void ScrobblingAPI20::AuthError(QString error) {
|
||||
emit AuthenticationComplete(false, error);
|
||||
}
|
||||
|
||||
void ScrobblingAPI20::Error(QString error, QVariant debug) {
|
||||
|
||||
qLog(Error) << name_ << error;
|
||||
if (debug.isValid()) qLog(Debug) << debug;
|
||||
|
||||
}
|
||||
|
||||
QString ScrobblingAPI20::ErrorString(ScrobbleErrorCode error) const {
|
||||
|
||||
switch (error) {
|
||||
case ScrobbleErrorCode::InvalidService:
|
||||
return QString("Invalid service - This service does not exist");
|
||||
case ScrobbleErrorCode::InvalidMethod:
|
||||
return QString("Invalid Method - No method with that name in this package");
|
||||
case ScrobbleErrorCode::AuthenticationFailed:
|
||||
return QString("Authentication Failed - You do not have permissions to access the service");
|
||||
case ScrobbleErrorCode::InvalidFormat:
|
||||
return QString("Invalid format - This service doesn't exist in that format");
|
||||
case ScrobbleErrorCode::InvalidParameters:
|
||||
return QString("Invalid parameters - Your request is missing a required parameter");
|
||||
case ScrobbleErrorCode::InvalidResourceSpecified:
|
||||
return QString("Invalid resource specified");
|
||||
case ScrobbleErrorCode::OperationFailed:
|
||||
return QString("Operation failed - Something else went wrong");
|
||||
case ScrobbleErrorCode::InvalidSessionKey:
|
||||
return QString("Invalid session key - Please re-authenticate");
|
||||
case ScrobbleErrorCode::InvalidApiKey:
|
||||
return QString("Invalid API key - You must be granted a valid key by last.fm");
|
||||
case ScrobbleErrorCode::ServiceOffline:
|
||||
return QString("Service Offline - This service is temporarily offline. Try again later.");
|
||||
case ScrobbleErrorCode::InvalidMethodSignature:
|
||||
return QString("Invalid method signature supplied");
|
||||
case ScrobbleErrorCode::TempError:
|
||||
return QString("There was a temporary error processing your request. Please try again");
|
||||
case ScrobbleErrorCode::SuspendedAPIKey:
|
||||
return QString("Suspended API key - Access for your account has been suspended, please contact Last.fm");
|
||||
case ScrobbleErrorCode::RateLimitExceeded:
|
||||
return QString("Rate limit exceeded - Your IP has made too many requests in a short period");
|
||||
default:
|
||||
return QString("Unknown error");
|
||||
}
|
||||
|
||||
}
|
||||
158
src/scrobbler/scrobblingapi20.h
Normal file
158
src/scrobbler/scrobblingapi20.h
Normal file
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* Strawberry Music Player
|
||||
* Copyright 2018, Jonas Kvinge <jonas@jkvinge.net>
|
||||
*
|
||||
* Strawberry 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 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef SCROBBLINGAPI20_H
|
||||
#define SCROBBLINGAPI20_H
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include <QtGlobal>
|
||||
#include <QObject>
|
||||
#include <QNetworkReply>
|
||||
#include <QPair>
|
||||
#include <QList>
|
||||
#include <QVariant>
|
||||
#include <QByteArray>
|
||||
#include <QString>
|
||||
#include <QJsonObject>
|
||||
|
||||
#include "core/song.h"
|
||||
#include "scrobblerservice.h"
|
||||
#include "scrobblercache.h"
|
||||
|
||||
class Application;
|
||||
class NetworkAccessManager;
|
||||
class LocalRedirectServer;
|
||||
class ScrobblerService;
|
||||
class ScrobblerCache;
|
||||
class ScrobblerCacheItem;
|
||||
|
||||
class ScrobblingAPI20 : public ScrobblerService {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit ScrobblingAPI20(const QString &name, const QString &settings_group, const QString &auth_url, const QString &api_url, const bool batch, Application *app, QObject *parent = nullptr);
|
||||
~ScrobblingAPI20();
|
||||
|
||||
static const char *kRedirectUrl;
|
||||
|
||||
void ReloadSettings();
|
||||
void LoadSession();
|
||||
|
||||
virtual NetworkAccessManager *network() = 0;
|
||||
virtual ScrobblerCache *cache() = 0;
|
||||
|
||||
bool IsEnabled() const { return enabled_; }
|
||||
bool IsAuthenticated() const { return !username_.isEmpty() && !session_key_.isEmpty(); }
|
||||
bool IsSubscriber() const { return subscriber_; }
|
||||
bool IsSubmitted() const { return submitted_; }
|
||||
void Submitted() { submitted_ = true; }
|
||||
QString username() const { return username_; }
|
||||
|
||||
void Authenticate();
|
||||
void Logout();
|
||||
void UpdateNowPlaying(const Song &song);
|
||||
void Scrobble(const Song &song);
|
||||
void Submit();
|
||||
void Love(const Song &song);
|
||||
|
||||
signals:
|
||||
void AuthenticationComplete(bool success, QString error = QString());
|
||||
|
||||
public slots:
|
||||
void WriteCache() { cache()->WriteCache(); }
|
||||
|
||||
private slots:
|
||||
void RedirectArrived(LocalRedirectServer *server);
|
||||
void AuthenticateReplyFinished(QNetworkReply *reply);
|
||||
void UpdateNowPlayingRequestFinished(QNetworkReply *reply);
|
||||
void ScrobbleRequestFinished(QNetworkReply *reply, QList<quint64>);
|
||||
void SingleScrobbleRequestFinished(QNetworkReply *reply, quint64 timestamp);
|
||||
|
||||
private:
|
||||
|
||||
enum ScrobbleErrorCode {
|
||||
Unknown = 0,
|
||||
NoError = 1,
|
||||
InvalidService = 2,
|
||||
InvalidMethod = 3,
|
||||
AuthenticationFailed = 4,
|
||||
InvalidFormat = 5,
|
||||
InvalidParameters = 6,
|
||||
InvalidResourceSpecified = 7,
|
||||
OperationFailed = 8,
|
||||
InvalidSessionKey = 9,
|
||||
InvalidApiKey = 10,
|
||||
ServiceOffline = 11,
|
||||
Reserved12 = 12,
|
||||
InvalidMethodSignature = 13,
|
||||
Reserved14 = 14,
|
||||
Reserved15 = 15,
|
||||
TempError = 16,
|
||||
Reserved17 = 17,
|
||||
Reserved18 = 18,
|
||||
Reserved19 = 19,
|
||||
Reserved20 = 20,
|
||||
Reserved21 = 21,
|
||||
Reserved22 = 22,
|
||||
Reserved23 = 23,
|
||||
Reserved24 = 24,
|
||||
Reserved25 = 25,
|
||||
SuspendedAPIKey = 26,
|
||||
Reserved27 = 27,
|
||||
Reserved28 = 28,
|
||||
RateLimitExceeded = 29,
|
||||
};
|
||||
|
||||
static const char *kApiKey;
|
||||
static const char *kSecret;
|
||||
static const int kScrobblesPerRequest;
|
||||
|
||||
QNetworkReply *CreateRequest(const ParamList &request_params);
|
||||
QByteArray GetReplyData(QNetworkReply *reply);
|
||||
|
||||
void RequestSession(QString token);
|
||||
void AuthError(QString error);
|
||||
void SendSingleScrobble(ScrobblerCacheItem *item);
|
||||
void Error(QString error, QVariant debug = QVariant());
|
||||
QString ErrorString(ScrobbleErrorCode error) const;
|
||||
|
||||
QString name_;
|
||||
QString settings_group_;
|
||||
QString auth_url_;
|
||||
QString api_url_;
|
||||
bool batch_;
|
||||
|
||||
Application *app_;
|
||||
|
||||
bool enabled_;
|
||||
|
||||
bool subscriber_;
|
||||
QString username_;
|
||||
QString session_key_;
|
||||
|
||||
bool submitted_;
|
||||
Song song_playing_;
|
||||
quint64 timestamp_;
|
||||
|
||||
};
|
||||
|
||||
#endif // SCROBBLINGAPI20_H
|
||||
Reference in New Issue
Block a user