strawberry-audio-player-win.../src/tidal/tidalservice.cpp

1041 lines
37 KiB
C++
Raw Normal View History

2020-04-13 19:04:06 +02:00
/*
* Strawberry Music Player
2021-03-20 21:14:47 +01:00
* Copyright 2018-2021, Jonas Kvinge <jonas@jkvinge.net>
2020-04-13 19:04:06 +02:00
*
* 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 <memory>
#include <chrono>
2020-04-13 19:04:06 +02:00
#include <QObject>
#include <QDesktopServices>
#include <QCryptographicHash>
#include <QByteArray>
#include <QList>
#include <QString>
#include <QChar>
#include <QUrl>
#include <QUrlQuery>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QSslError>
#include <QTimer>
#include <QJsonValue>
#include <QJsonDocument>
#include <QJsonObject>
#include <QSettings>
#include <QSortFilterProxyModel>
#include "core/application.h"
#include "core/player.h"
#include "core/logging.h"
2021-01-11 16:48:46 +01:00
#include "core/networkaccessmanager.h"
2020-04-13 19:04:06 +02:00
#include "core/database.h"
#include "core/song.h"
#include "core/utilities.h"
2020-05-13 21:56:11 +02:00
#include "core/timeconstants.h"
2020-04-13 19:04:06 +02:00
#include "internet/internetsearchview.h"
#include "collection/collectionbackend.h"
#include "collection/collectionmodel.h"
#include "tidalservice.h"
#include "tidalurlhandler.h"
#include "tidalbaserequest.h"
#include "tidalrequest.h"
#include "tidalfavoriterequest.h"
#include "tidalstreamurlrequest.h"
#include "settings/settingsdialog.h"
#include "settings/tidalsettingspage.h"
2022-11-27 03:11:57 +01:00
const Song::Source TidalService::kSource = Song::Source_Tidal;
const char TidalService::kApiUrl[] = "https://api.tidalhifi.com/v1";
const char TidalService::kResourcesUrl[] = "https://resources.tidal.com";
2022-10-31 06:12:02 +01:00
constexpr char TidalService::kOAuthUrl[] = "https://login.tidal.com/authorize";
constexpr char TidalService::kOAuthAccessTokenUrl[] = "https://login.tidal.com/oauth2/token";
constexpr char TidalService::kOAuthRedirectUrl[] = "tidal://login/auth";
constexpr char TidalService::kAuthUrl[] = "https://api.tidalhifi.com/v1/login/username";
2022-11-27 03:11:57 +01:00
const int TidalService::kLoginAttempts = 2;
2022-10-31 06:12:02 +01:00
constexpr int TidalService::kTimeResetLoginAttempts = 60000;
constexpr char TidalService::kArtistsSongsTable[] = "tidal_artists_songs";
constexpr char TidalService::kAlbumsSongsTable[] = "tidal_albums_songs";
constexpr char TidalService::kSongsTable[] = "tidal_songs";
constexpr char TidalService::kArtistsSongsFtsTable[] = "tidal_artists_songs_fts";
constexpr char TidalService::kAlbumsSongsFtsTable[] = "tidal_albums_songs_fts";
constexpr char TidalService::kSongsFtsTable[] = "tidal_songs_fts";
2020-04-13 19:04:06 +02:00
using namespace std::chrono_literals;
2020-04-13 19:04:06 +02:00
TidalService::TidalService(Application *app, QObject *parent)
: InternetService(Song::Source_Tidal, "Tidal", "tidal", TidalSettingsPage::kSettingsGroup, SettingsDialog::Page_Tidal, app, parent),
app_(app),
network_(new NetworkAccessManager(this)),
url_handler_(new TidalUrlHandler(app, this)),
artists_collection_backend_(nullptr),
albums_collection_backend_(nullptr),
songs_collection_backend_(nullptr),
artists_collection_model_(nullptr),
albums_collection_model_(nullptr),
songs_collection_model_(nullptr),
artists_collection_sort_model_(new QSortFilterProxyModel(this)),
albums_collection_sort_model_(new QSortFilterProxyModel(this)),
songs_collection_sort_model_(new QSortFilterProxyModel(this)),
timer_search_delay_(new QTimer(this)),
timer_login_attempt_(new QTimer(this)),
2020-05-13 21:56:11 +02:00
timer_refresh_login_(new QTimer(this)),
2020-04-13 19:04:06 +02:00
favorite_request_(new TidalFavoriteRequest(this, network_, this)),
2020-05-13 21:56:11 +02:00
enabled_(false),
oauth_(false),
2020-04-13 19:04:06 +02:00
user_id_(0),
artistssearchlimit_(1),
albumssearchlimit_(1),
songssearchlimit_(1),
fetchalbums_(true),
download_album_covers_(true),
2021-06-20 23:53:28 +02:00
stream_url_method_(TidalSettingsPage::StreamUrlMethod_StreamUrl),
album_explicit_(false),
2020-05-13 21:56:11 +02:00
expires_in_(0),
login_time_(0),
2020-04-13 19:04:06 +02:00
pending_search_id_(0),
next_pending_search_id_(1),
2021-06-20 23:53:28 +02:00
pending_search_type_(InternetSearchView::SearchType_Artists),
2020-04-13 19:04:06 +02:00
search_id_(0),
login_sent_(false),
login_attempts_(0),
next_stream_url_request_id_(0) {
2020-04-13 19:04:06 +02:00
app->player()->RegisterUrlHandler(url_handler_);
// Backends
artists_collection_backend_ = new CollectionBackend();
artists_collection_backend_->moveToThread(app_->database()->thread());
artists_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source_Tidal, kArtistsSongsTable, kArtistsSongsFtsTable);
2020-04-13 19:04:06 +02:00
albums_collection_backend_ = new CollectionBackend();
albums_collection_backend_->moveToThread(app_->database()->thread());
albums_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source_Tidal, kAlbumsSongsTable, kAlbumsSongsFtsTable);
2020-04-13 19:04:06 +02:00
songs_collection_backend_ = new CollectionBackend();
songs_collection_backend_->moveToThread(app_->database()->thread());
songs_collection_backend_->Init(app_->database(), app->task_manager(), Song::Source_Tidal, kSongsTable, kSongsFtsTable);
2020-04-13 19:04:06 +02:00
artists_collection_model_ = new CollectionModel(artists_collection_backend_, app_, this);
albums_collection_model_ = new CollectionModel(albums_collection_backend_, app_, this);
songs_collection_model_ = new CollectionModel(songs_collection_backend_, app_, this);
artists_collection_sort_model_->setSourceModel(artists_collection_model_);
artists_collection_sort_model_->setSortRole(CollectionModel::Role_SortText);
artists_collection_sort_model_->setDynamicSortFilter(true);
artists_collection_sort_model_->setSortLocaleAware(true);
artists_collection_sort_model_->sort(0);
albums_collection_sort_model_->setSourceModel(albums_collection_model_);
albums_collection_sort_model_->setSortRole(CollectionModel::Role_SortText);
albums_collection_sort_model_->setDynamicSortFilter(true);
albums_collection_sort_model_->setSortLocaleAware(true);
albums_collection_sort_model_->sort(0);
songs_collection_sort_model_->setSourceModel(songs_collection_model_);
songs_collection_sort_model_->setSortRole(CollectionModel::Role_SortText);
songs_collection_sort_model_->setDynamicSortFilter(true);
songs_collection_sort_model_->setSortLocaleAware(true);
songs_collection_sort_model_->sort(0);
// Search
timer_search_delay_->setSingleShot(true);
2021-01-26 16:48:04 +01:00
QObject::connect(timer_search_delay_, &QTimer::timeout, this, &TidalService::StartSearch);
2020-04-13 19:04:06 +02:00
timer_login_attempt_->setSingleShot(true);
2020-05-13 21:56:11 +02:00
timer_login_attempt_->setInterval(kTimeResetLoginAttempts);
2021-01-26 16:48:04 +01:00
QObject::connect(timer_login_attempt_, &QTimer::timeout, this, &TidalService::ResetLoginAttempts);
2020-04-13 19:04:06 +02:00
2020-05-13 21:56:11 +02:00
timer_refresh_login_->setSingleShot(true);
2021-01-26 16:48:04 +01:00
QObject::connect(timer_refresh_login_, &QTimer::timeout, this, &TidalService::RequestNewAccessToken);
2020-05-13 21:56:11 +02:00
2021-03-21 18:53:02 +01:00
QObject::connect(this, &TidalService::RequestLogin, this, &TidalService::SendLogin);
2021-01-26 16:48:04 +01:00
QObject::connect(this, &TidalService::LoginWithCredentials, this, &TidalService::SendLoginWithCredentials);
2020-04-13 19:04:06 +02:00
2021-01-26 16:48:04 +01:00
QObject::connect(this, &TidalService::AddArtists, favorite_request_, &TidalFavoriteRequest::AddArtists);
QObject::connect(this, &TidalService::AddAlbums, favorite_request_, &TidalFavoriteRequest::AddAlbums);
QObject::connect(this, &TidalService::AddSongs, favorite_request_, QOverload<const SongList&>::of(&TidalFavoriteRequest::AddSongs));
2020-04-13 19:04:06 +02:00
2021-01-26 16:48:04 +01:00
QObject::connect(this, &TidalService::RemoveArtists, favorite_request_, &TidalFavoriteRequest::RemoveArtists);
QObject::connect(this, &TidalService::RemoveAlbums, favorite_request_, &TidalFavoriteRequest::RemoveAlbums);
2021-11-09 17:42:18 +01:00
QObject::connect(this, &TidalService::RemoveSongsByList, favorite_request_, QOverload<const SongList&>::of(&TidalFavoriteRequest::RemoveSongs));
QObject::connect(this, &TidalService::RemoveSongsByMap, favorite_request_, QOverload<const SongMap&>::of(&TidalFavoriteRequest::RemoveSongs));
2020-04-13 19:04:06 +02:00
QObject::connect(favorite_request_, &TidalFavoriteRequest::RequestLogin, this, &TidalService::SendLogin);
2021-01-26 16:48:04 +01:00
QObject::connect(favorite_request_, &TidalFavoriteRequest::ArtistsAdded, artists_collection_backend_, &CollectionBackend::AddOrUpdateSongs);
QObject::connect(favorite_request_, &TidalFavoriteRequest::AlbumsAdded, albums_collection_backend_, &CollectionBackend::AddOrUpdateSongs);
QObject::connect(favorite_request_, &TidalFavoriteRequest::SongsAdded, songs_collection_backend_, &CollectionBackend::AddOrUpdateSongs);
2020-04-13 19:04:06 +02:00
2021-01-26 16:48:04 +01:00
QObject::connect(favorite_request_, &TidalFavoriteRequest::ArtistsRemoved, artists_collection_backend_, &CollectionBackend::DeleteSongs);
QObject::connect(favorite_request_, &TidalFavoriteRequest::AlbumsRemoved, albums_collection_backend_, &CollectionBackend::DeleteSongs);
QObject::connect(favorite_request_, &TidalFavoriteRequest::SongsRemoved, songs_collection_backend_, &CollectionBackend::DeleteSongs);
2020-04-13 19:04:06 +02:00
2021-03-21 04:47:11 +01:00
TidalService::ReloadSettings();
2020-05-13 21:56:11 +02:00
LoadSession();
2020-04-13 19:04:06 +02:00
}
TidalService::~TidalService() {
while (!replies_.isEmpty()) {
QNetworkReply *reply = replies_.takeFirst();
2021-01-26 16:48:04 +01:00
QObject::disconnect(reply, nullptr, this, nullptr);
reply->abort();
reply->deleteLater();
}
2020-04-13 19:04:06 +02:00
while (!stream_url_requests_.isEmpty()) {
std::shared_ptr<TidalStreamURLRequest> stream_url_req = stream_url_requests_.take(stream_url_requests_.firstKey());
QObject::disconnect(stream_url_req.get(), nullptr, this, nullptr);
2020-04-13 19:04:06 +02:00
}
artists_collection_backend_->deleteLater();
albums_collection_backend_->deleteLater();
songs_collection_backend_->deleteLater();
}
void TidalService::Exit() {
wait_for_exit_ << artists_collection_backend_ << albums_collection_backend_ << songs_collection_backend_;
2021-01-26 16:48:04 +01:00
QObject::connect(artists_collection_backend_, &CollectionBackend::ExitFinished, this, &TidalService::ExitReceived);
QObject::connect(albums_collection_backend_, &CollectionBackend::ExitFinished, this, &TidalService::ExitReceived);
QObject::connect(songs_collection_backend_, &CollectionBackend::ExitFinished, this, &TidalService::ExitReceived);
2020-04-13 19:04:06 +02:00
artists_collection_backend_->ExitAsync();
albums_collection_backend_->ExitAsync();
songs_collection_backend_->ExitAsync();
}
void TidalService::ExitReceived() {
2021-06-20 19:04:08 +02:00
QObject *obj = sender();
2021-01-26 16:48:04 +01:00
QObject::disconnect(obj, nullptr, this, nullptr);
2020-04-13 19:04:06 +02:00
qLog(Debug) << obj << "successfully exited.";
wait_for_exit_.removeAll(obj);
if (wait_for_exit_.isEmpty()) emit ExitFinished();
}
void TidalService::ShowConfig() {
app_->OpenSettingsDialogAtPage(SettingsDialog::Page_Tidal);
}
2020-05-13 21:56:11 +02:00
void TidalService::LoadSession() {
QSettings s;
s.beginGroup(TidalSettingsPage::kSettingsGroup);
user_id_ = s.value("user_id").toInt();
country_code_ = s.value("country_code", "US").toString();
access_token_ = s.value("access_token").toString();
refresh_token_ = s.value("refresh_token").toString();
session_id_ = s.value("session_id").toString();
expires_in_ = s.value("expires_in").toLongLong();
login_time_ = s.value("login_time").toLongLong();
s.endGroup();
if (!refresh_token_.isEmpty()) {
2021-10-30 02:21:29 +02:00
qint64 time = static_cast<qint64>(expires_in_) - (QDateTime::currentDateTime().toSecsSinceEpoch() - static_cast<qint64>(login_time_));
if (time <= 0) {
timer_refresh_login_->setInterval(200ms);
}
else {
timer_refresh_login_->setInterval(static_cast<int>(time * kMsecPerSec));
}
2020-05-13 21:56:11 +02:00
timer_refresh_login_->start();
}
}
2020-04-13 19:04:06 +02:00
void TidalService::ReloadSettings() {
QSettings s;
s.beginGroup(TidalSettingsPage::kSettingsGroup);
2020-05-13 21:56:11 +02:00
enabled_ = s.value("enabled", false).toBool();
2020-09-17 17:07:54 +02:00
oauth_ = s.value("oauth", true).toBool();
2020-04-13 19:04:06 +02:00
client_id_ = s.value("client_id").toString();
api_token_ = s.value("api_token").toString();
username_ = s.value("username").toString();
QByteArray password = s.value("password").toByteArray();
if (password.isEmpty()) password_.clear();
else password_ = QString::fromUtf8(QByteArray::fromBase64(password));
quality_ = s.value("quality", "LOSSLESS").toString();
2020-05-13 21:56:11 +02:00
quint64 search_delay = s.value("searchdelay", 1500).toInt();
2020-04-13 19:04:06 +02:00
artistssearchlimit_ = s.value("artistssearchlimit", 4).toInt();
albumssearchlimit_ = s.value("albumssearchlimit", 10).toInt();
songssearchlimit_ = s.value("songssearchlimit", 10).toInt();
fetchalbums_ = s.value("fetchalbums", false).toBool();
2020-09-17 17:07:54 +02:00
coversize_ = s.value("coversize", "640x640").toString();
2020-04-13 19:04:06 +02:00
download_album_covers_ = s.value("downloadalbumcovers", true).toBool();
stream_url_method_ = static_cast<TidalSettingsPage::StreamUrlMethod>(s.value("streamurl").toInt());
album_explicit_ = s.value("album_explicit").toBool();
2020-04-13 19:04:06 +02:00
s.endGroup();
2021-10-30 02:21:29 +02:00
timer_search_delay_->setInterval(static_cast<int>(search_delay));
2020-05-13 21:56:11 +02:00
2020-04-13 19:04:06 +02:00
}
2021-06-20 19:04:08 +02:00
void TidalService::StartAuthorization(const QString &client_id) {
2020-04-13 19:04:06 +02:00
2020-05-13 21:56:11 +02:00
client_id_ = client_id;
2020-04-13 19:04:06 +02:00
code_verifier_ = Utilities::CryptographicRandomString(44);
code_challenge_ = QString(QCryptographicHash::hash(code_verifier_.toUtf8(), QCryptographicHash::Sha256).toBase64(QByteArray::Base64UrlEncoding));
if (code_challenge_.lastIndexOf(QChar('=')) == code_challenge_.length() - 1) {
code_challenge_.chop(1);
}
const ParamList params = ParamList() << Param("response_type", "code")
<< Param("code_challenge", code_challenge_)
<< Param("code_challenge_method", "S256")
<< Param("redirect_uri", kOAuthRedirectUrl)
<< Param("client_id", client_id_)
<< Param("scope", "r_usr w_usr");
QUrlQuery url_query;
for (const Param &param : params) {
2020-04-23 21:05:57 +02:00
url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second));
2020-04-13 19:04:06 +02:00
}
QUrl url = QUrl(kOAuthUrl);
url.setQuery(url_query);
QDesktopServices::openUrl(url);
}
2020-05-13 21:56:11 +02:00
void TidalService::AuthorizationUrlReceived(const QUrl &url) {
2020-04-13 19:04:06 +02:00
2020-05-13 21:56:11 +02:00
qLog(Debug) << "Tidal: Authorization URL Received" << url;
2020-04-13 19:04:06 +02:00
QUrlQuery url_query(url);
if (url_query.hasQueryItem("token_type") && url_query.hasQueryItem("expires_in") && url_query.hasQueryItem("access_token")) {
access_token_ = url_query.queryItemValue("access_token").toUtf8();
2020-05-13 21:56:11 +02:00
if (url_query.hasQueryItem("refresh_token")) {
refresh_token_ = url_query.queryItemValue("refresh_token").toUtf8();
}
expires_in_ = url_query.queryItemValue("expires_in").toInt();
login_time_ = QDateTime::currentDateTime().toSecsSinceEpoch();
2020-04-13 19:04:06 +02:00
session_id_.clear();
QSettings s;
s.beginGroup(TidalSettingsPage::kSettingsGroup);
s.setValue("access_token", access_token_);
2020-05-13 21:56:11 +02:00
s.setValue("refresh_token", refresh_token_);
s.setValue("expires_in", expires_in_);
s.setValue("login_time", login_time_);
2020-04-13 19:04:06 +02:00
s.remove("session_id");
s.endGroup();
emit LoginComplete(true);
emit LoginSuccess();
}
else if (url_query.hasQueryItem("code") && url_query.hasQueryItem("state")) {
QString code = url_query.queryItemValue("code");
2020-05-13 21:56:11 +02:00
RequestAccessToken(code);
2020-04-13 19:04:06 +02:00
2020-05-13 21:56:11 +02:00
}
2020-04-13 19:04:06 +02:00
2020-05-13 21:56:11 +02:00
else {
LoginError(tr("Reply from Tidal is missing query items."));
return;
}
2020-04-13 19:04:06 +02:00
2020-05-13 21:56:11 +02:00
}
2020-04-13 19:04:06 +02:00
2020-05-13 21:56:11 +02:00
void TidalService::RequestAccessToken(const QString &code) {
timer_refresh_login_->stop();
2020-04-13 19:04:06 +02:00
2020-05-13 21:56:11 +02:00
ParamList params = ParamList() << Param("client_id", client_id_);
if (!code.isEmpty()) {
params << Param("grant_type", "authorization_code");
params << Param("code", code);
params << Param("code_verifier", code_verifier_);
params << Param("redirect_uri", kOAuthRedirectUrl);
params << Param("scope", "r_usr w_usr");
}
else if (!refresh_token_.isEmpty() && enabled_ && oauth_) {
params << Param("grant_type", "refresh_token");
params << Param("refresh_token", refresh_token_);
}
2020-04-13 19:04:06 +02:00
else {
return;
}
2020-05-13 21:56:11 +02:00
QUrlQuery url_query;
for (const Param &param : params) {
url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second));
}
QUrl url(kOAuthAccessTokenUrl);
QNetworkRequest req(url);
req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
2020-05-13 21:56:11 +02:00
QByteArray query = url_query.toString(QUrl::FullyEncoded).toUtf8();
login_errors_.clear();
QNetworkReply *reply = network_->post(req, query);
2020-05-13 21:56:11 +02:00
replies_ << reply;
2021-01-26 16:48:04 +01:00
QObject::connect(reply, &QNetworkReply::sslErrors, this, &TidalService::HandleLoginSSLErrors);
2021-03-21 00:37:17 +01:00
QObject::connect(reply, &QNetworkReply::finished, this, [this, reply]() { AccessTokenRequestFinished(reply); });
2020-05-13 21:56:11 +02:00
2020-04-13 19:04:06 +02:00
}
2021-06-20 19:04:08 +02:00
void TidalService::HandleLoginSSLErrors(const QList<QSslError> &ssl_errors) {
2020-04-13 19:04:06 +02:00
2021-06-20 19:04:08 +02:00
for (const QSslError &ssl_error : ssl_errors) {
2020-04-13 19:04:06 +02:00
login_errors_ += ssl_error.errorString();
}
}
void TidalService::AccessTokenRequestFinished(QNetworkReply *reply) {
if (!replies_.contains(reply)) return;
replies_.removeAll(reply);
2021-01-26 16:48:04 +01:00
QObject::disconnect(reply, nullptr, this, nullptr);
2020-04-13 19:04:06 +02:00
reply->deleteLater();
if (reply->error() != QNetworkReply::NoError || reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != 200) {
if (reply->error() != QNetworkReply::NoError && reply->error() < 200) {
// This is a network error, there is nothing more to do.
LoginError(QString("%1 (%2)").arg(reply->errorString()).arg(reply->error()));
return;
}
else {
// See if there is Json data containing "status" and "userMessage" then use that instead.
QByteArray data(reply->readAll());
QJsonParseError json_error;
QJsonDocument json_doc = QJsonDocument::fromJson(data, &json_error);
2020-10-02 19:27:47 +02:00
if (json_error.error == QJsonParseError::NoError && !json_doc.isEmpty() && json_doc.isObject()) {
2020-04-13 19:04:06 +02:00
QJsonObject json_obj = json_doc.object();
if (!json_obj.isEmpty() && json_obj.contains("status") && json_obj.contains("userMessage")) {
int status = json_obj["status"].toInt();
int sub_status = json_obj["subStatus"].toInt();
QString user_message = json_obj["userMessage"].toString();
login_errors_ << QString("Authentication failure: %1 (%2) (%3)").arg(user_message).arg(status).arg(sub_status);
}
}
if (login_errors_.isEmpty()) {
if (reply->error() != QNetworkReply::NoError) {
login_errors_ << QString("%1 (%2)").arg(reply->errorString()).arg(reply->error());
}
else {
login_errors_ << QString("Received HTTP code %1").arg(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt());
}
}
LoginError();
return;
}
}
QByteArray data(reply->readAll());
QJsonParseError json_error;
QJsonDocument json_doc = QJsonDocument::fromJson(data, &json_error);
if (json_error.error != QJsonParseError::NoError) {
LoginError("Authentication reply from server missing Json data.");
return;
}
2020-04-23 21:05:57 +02:00
if (json_doc.isEmpty()) {
2020-04-13 19:04:06 +02:00
LoginError("Authentication reply from server has empty Json document.");
return;
}
if (!json_doc.isObject()) {
LoginError("Authentication reply from server has Json document that is not an object.", json_doc);
return;
}
QJsonObject json_obj = json_doc.object();
if (json_obj.isEmpty()) {
LoginError("Authentication reply from server has empty Json object.", json_doc);
return;
}
2020-05-13 21:56:11 +02:00
if (!json_obj.contains("access_token") || !json_obj.contains("expires_in")) {
LoginError("Authentication reply from server is missing access_token or expires_in", json_obj);
2020-04-13 19:04:06 +02:00
return;
}
access_token_ = json_obj["access_token"].toString();
2020-05-13 21:56:11 +02:00
expires_in_ = json_obj["expires_in"].toInt();
if (json_obj.contains("refresh_token")) {
refresh_token_ = json_obj["refresh_token"].toString();
2020-04-13 19:04:06 +02:00
}
login_time_ = QDateTime::currentDateTime().toSecsSinceEpoch();
2020-05-13 21:56:11 +02:00
if (json_obj.contains("user") && json_obj["user"].isObject()) {
QJsonObject obj_user = json_obj["user"].toObject();
if (obj_user.contains("countryCode") && obj_user.contains("userId")) {
country_code_ = obj_user["countryCode"].toString();
user_id_ = obj_user["userId"].toInt();
}
2020-04-13 19:04:06 +02:00
}
session_id_.clear();
QSettings s;
s.beginGroup(TidalSettingsPage::kSettingsGroup);
s.setValue("access_token", access_token_);
s.setValue("refresh_token", refresh_token_);
2020-05-13 21:56:11 +02:00
s.setValue("expires_in", expires_in_);
s.setValue("login_time", login_time_);
2020-04-13 19:04:06 +02:00
s.setValue("country_code", country_code_);
s.setValue("user_id", user_id_);
s.remove("session_id");
s.endGroup();
2020-05-13 21:56:11 +02:00
if (expires_in_ > 0) {
2021-03-21 18:53:02 +01:00
timer_refresh_login_->setInterval(static_cast<int>(expires_in_ * kMsecPerSec));
2020-05-13 21:56:11 +02:00
timer_refresh_login_->start();
}
2020-04-13 19:04:06 +02:00
2021-06-04 00:15:35 +02:00
qLog(Debug) << "Tidal: Login successful" << "user id" << user_id_;
2020-04-13 19:04:06 +02:00
emit LoginComplete(true);
emit LoginSuccess();
}
void TidalService::SendLogin() {
2021-01-26 16:48:04 +01:00
SendLoginWithCredentials(api_token_, username_, password_);
2020-04-13 19:04:06 +02:00
}
2021-01-26 16:48:04 +01:00
void TidalService::SendLoginWithCredentials(const QString &api_token, const QString &username, const QString &password) {
2020-04-13 19:04:06 +02:00
login_sent_ = true;
++login_attempts_;
timer_login_attempt_->start();
2020-05-13 21:56:11 +02:00
timer_refresh_login_->stop();
2020-04-13 19:04:06 +02:00
const ParamList params = ParamList() << Param("token", (api_token.isEmpty() ? api_token_ : api_token))
<< Param("username", username)
<< Param("password", password)
<< Param("clientVersion", "2.2.1--7");
QUrlQuery url_query;
for (const Param &param : params) {
2020-04-23 21:05:57 +02:00
url_query.addQueryItem(QUrl::toPercentEncoding(param.first), QUrl::toPercentEncoding(param.second));
2020-04-13 19:04:06 +02:00
}
QUrl url(kAuthUrl);
QNetworkRequest req(url);
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
req.setRawHeader("X-Tidal-Token", (api_token.isEmpty() ? api_token_.toUtf8() : api_token.toUtf8()));
QByteArray query = url_query.toString(QUrl::FullyEncoded).toUtf8();
QNetworkReply *reply = network_->post(req, query);
2021-01-26 16:48:04 +01:00
QObject::connect(reply, &QNetworkReply::sslErrors, this, &TidalService::HandleLoginSSLErrors);
2021-03-21 00:37:17 +01:00
QObject::connect(reply, &QNetworkReply::finished, this, [this, reply]() { HandleAuthReply(reply); });
replies_ << reply;
2020-04-13 19:04:06 +02:00
//qLog(Debug) << "Tidal: Sending request" << url << query;
}
void TidalService::HandleAuthReply(QNetworkReply *reply) {
if (!replies_.contains(reply)) return;
replies_.removeAll(reply);
2021-01-26 16:48:04 +01:00
QObject::disconnect(reply, nullptr, this, nullptr);
2020-04-13 19:04:06 +02:00
reply->deleteLater();
login_sent_ = false;
if (reply->error() != QNetworkReply::NoError || reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != 200) {
if (reply->error() != QNetworkReply::NoError && reply->error() < 200) {
// This is a network error, there is nothing more to do.
LoginError(QString("%1 (%2)").arg(reply->errorString()).arg(reply->error()));
login_errors_.clear();
return;
}
else {
// See if there is Json data containing "status" and "userMessage" - then use that instead.
QByteArray data(reply->readAll());
QJsonParseError json_error;
QJsonDocument json_doc = QJsonDocument::fromJson(data, &json_error);
2020-10-02 19:27:47 +02:00
if (json_error.error == QJsonParseError::NoError && !json_doc.isEmpty() && json_doc.isObject()) {
2020-04-13 19:04:06 +02:00
QJsonObject json_obj = json_doc.object();
if (!json_obj.isEmpty() && json_obj.contains("status") && json_obj.contains("userMessage")) {
int status = json_obj["status"].toInt();
int sub_status = json_obj["subStatus"].toInt();
QString user_message = json_obj["userMessage"].toString();
login_errors_ << QString("Authentication failure: %1 (%2) (%3)").arg(user_message).arg(status).arg(sub_status);
}
}
if (login_errors_.isEmpty()) {
if (reply->error() != QNetworkReply::NoError) {
login_errors_ << QString("%1 (%2)").arg(reply->errorString()).arg(reply->error());
}
else {
login_errors_ << QString("Received HTTP code %1").arg(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt());
}
}
LoginError();
login_errors_.clear();
return;
}
}
login_errors_.clear();
QByteArray data(reply->readAll());
QJsonParseError json_error;
QJsonDocument json_doc = QJsonDocument::fromJson(data, &json_error);
if (json_error.error != QJsonParseError::NoError) {
LoginError("Authentication reply from server missing Json data.");
return;
}
2020-10-02 19:27:47 +02:00
if (json_doc.isEmpty()) {
2020-04-13 19:04:06 +02:00
LoginError("Authentication reply from server has empty Json document.");
return;
}
if (!json_doc.isObject()) {
LoginError("Authentication reply from server has Json document that is not an object.", json_doc);
return;
}
QJsonObject json_obj = json_doc.object();
if (json_obj.isEmpty()) {
LoginError("Authentication reply from server has empty Json object.", json_doc);
return;
}
2021-07-11 09:49:38 +02:00
if (!json_obj.contains("userId") || !json_obj.contains("sessionId") || !json_obj.contains("countryCode")) {
2020-04-13 19:04:06 +02:00
LoginError("Authentication reply from server is missing userId, sessionId or countryCode", json_obj);
return;
}
country_code_ = json_obj["countryCode"].toString();
session_id_ = json_obj["sessionId"].toString();
user_id_ = json_obj["userId"].toInt();
access_token_.clear();
refresh_token_.clear();
QSettings s;
s.beginGroup(TidalSettingsPage::kSettingsGroup);
s.remove("access_token");
s.remove("refresh_token");
2020-05-13 21:56:11 +02:00
s.remove("expires_in");
s.remove("login_time");
2020-04-13 19:04:06 +02:00
s.setValue("user_id", user_id_);
s.setValue("session_id", session_id_);
s.setValue("country_code", country_code_);
s.endGroup();
qLog(Debug) << "Tidal: Login successful" << "user id" << user_id_ << "session id" << session_id_ << "country code" << country_code_;
login_attempts_ = 0;
2020-05-13 21:56:11 +02:00
timer_login_attempt_->stop();
2020-04-13 19:04:06 +02:00
emit LoginComplete(true);
emit LoginSuccess();
}
void TidalService::Logout() {
2020-05-13 21:56:11 +02:00
user_id_ = 0;
country_code_.clear();
2020-04-13 19:04:06 +02:00
access_token_.clear();
session_id_.clear();
2020-05-13 21:56:11 +02:00
expires_in_ = 0;
login_time_ = 0;
2020-04-13 19:04:06 +02:00
QSettings s;
s.beginGroup(TidalSettingsPage::kSettingsGroup);
s.remove("user_id");
s.remove("country_code");
s.remove("access_token");
s.remove("session_id");
2020-05-13 21:56:11 +02:00
s.remove("expires_in");
s.remove("login_time");
2020-04-13 19:04:06 +02:00
s.endGroup();
2020-05-13 21:56:11 +02:00
timer_refresh_login_->stop();
2020-04-13 19:04:06 +02:00
}
void TidalService::ResetLoginAttempts() {
login_attempts_ = 0;
}
void TidalService::TryLogin() {
if (authenticated() || login_sent_) return;
if (api_token_.isEmpty()) {
emit LoginComplete(false, tr("Missing Tidal API token."));
return;
}
if (username_.isEmpty()) {
emit LoginComplete(false, tr("Missing Tidal username."));
return;
}
if (password_.isEmpty()) {
emit LoginComplete(false, tr("Missing Tidal password."));
return;
}
if (login_attempts_ >= kLoginAttempts) {
emit LoginComplete(false, tr("Not authenticated with Tidal and reached maximum number of login attempts."));
return;
}
2021-03-21 18:53:02 +01:00
emit RequestLogin();
2020-04-13 19:04:06 +02:00
}
void TidalService::ResetArtistsRequest() {
2021-06-22 14:02:37 +02:00
if (artists_request_) {
2021-01-26 16:48:04 +01:00
QObject::disconnect(artists_request_.get(), nullptr, this, nullptr);
QObject::disconnect(this, nullptr, artists_request_.get(), nullptr);
2020-04-13 19:04:06 +02:00
artists_request_.reset();
}
}
void TidalService::GetArtists() {
if (!authenticated()) {
if (oauth_) {
emit ArtistsResults(SongMap(), tr("Not authenticated with Tidal."));
2020-04-13 19:04:06 +02:00
ShowConfig();
return;
}
else if (api_token_.isEmpty() || username_.isEmpty() || password_.isEmpty()) {
emit ArtistsResults(SongMap(), tr("Missing Tidal API token, username or password."));
2020-04-13 19:04:06 +02:00
ShowConfig();
return;
}
}
ResetArtistsRequest();
artists_request_.reset(new TidalRequest(this, url_handler_, app_, network_, TidalBaseRequest::QueryType_Artists, this), [](TidalRequest *request) { request->deleteLater(); });
QObject::connect(artists_request_.get(), &TidalRequest::RequestLogin, this, &TidalService::SendLogin);
2021-01-26 16:48:04 +01:00
QObject::connect(artists_request_.get(), &TidalRequest::Results, this, &TidalService::ArtistsResultsReceived);
QObject::connect(artists_request_.get(), &TidalRequest::UpdateStatus, this, &TidalService::ArtistsUpdateStatusReceived);
QObject::connect(artists_request_.get(), &TidalRequest::UpdateProgress, this, &TidalService::ArtistsUpdateProgressReceived);
QObject::connect(this, &TidalService::LoginComplete, artists_request_.get(), &TidalRequest::LoginComplete);
2020-04-13 19:04:06 +02:00
artists_request_->Process();
}
void TidalService::ArtistsResultsReceived(const int id, const SongMap &songs, const QString &error) {
2020-04-13 19:04:06 +02:00
Q_UNUSED(id);
emit ArtistsResults(songs, error);
ResetArtistsRequest();
2020-04-13 19:04:06 +02:00
}
void TidalService::ArtistsUpdateStatusReceived(const int id, const QString &text) {
Q_UNUSED(id);
emit ArtistsUpdateStatus(text);
}
void TidalService::ArtistsUpdateProgressReceived(const int id, const int progress) {
Q_UNUSED(id);
emit ArtistsUpdateProgress(progress);
}
void TidalService::ResetAlbumsRequest() {
2021-06-22 14:02:37 +02:00
if (albums_request_) {
2021-01-26 16:48:04 +01:00
QObject::disconnect(albums_request_.get(), nullptr, this, nullptr);
QObject::disconnect(this, nullptr, albums_request_.get(), nullptr);
2020-04-13 19:04:06 +02:00
albums_request_.reset();
}
}
void TidalService::GetAlbums() {
if (!authenticated()) {
if (oauth_) {
emit AlbumsResults(SongMap(), tr("Not authenticated with Tidal."));
2020-04-13 19:04:06 +02:00
ShowConfig();
return;
}
else if (api_token_.isEmpty() || username_.isEmpty() || password_.isEmpty()) {
emit AlbumsResults(SongMap(), tr("Missing Tidal API token, username or password."));
2020-04-13 19:04:06 +02:00
ShowConfig();
return;
}
}
ResetAlbumsRequest();
albums_request_.reset(new TidalRequest(this, url_handler_, app_, network_, TidalBaseRequest::QueryType_Albums, this), [](TidalRequest *request) { request->deleteLater(); });
QObject::connect(albums_request_.get(), &TidalRequest::RequestLogin, this, &TidalService::SendLogin);
2021-01-26 16:48:04 +01:00
QObject::connect(albums_request_.get(), &TidalRequest::Results, this, &TidalService::AlbumsResultsReceived);
QObject::connect(albums_request_.get(), &TidalRequest::UpdateStatus, this, &TidalService::AlbumsUpdateStatusReceived);
QObject::connect(albums_request_.get(), &TidalRequest::UpdateProgress, this, &TidalService::AlbumsUpdateProgressReceived);
QObject::connect(this, &TidalService::LoginComplete, albums_request_.get(), &TidalRequest::LoginComplete);
2020-04-13 19:04:06 +02:00
albums_request_->Process();
}
void TidalService::AlbumsResultsReceived(const int id, const SongMap &songs, const QString &error) {
2020-04-13 19:04:06 +02:00
Q_UNUSED(id);
emit AlbumsResults(songs, error);
ResetAlbumsRequest();
2020-04-13 19:04:06 +02:00
}
void TidalService::AlbumsUpdateStatusReceived(const int id, const QString &text) {
Q_UNUSED(id);
emit AlbumsUpdateStatus(text);
}
void TidalService::AlbumsUpdateProgressReceived(const int id, const int progress) {
Q_UNUSED(id);
emit AlbumsUpdateProgress(progress);
}
void TidalService::ResetSongsRequest() {
2021-06-22 14:02:37 +02:00
if (songs_request_) {
2021-01-26 16:48:04 +01:00
QObject::disconnect(songs_request_.get(), nullptr, this, nullptr);
QObject::disconnect(this, nullptr, songs_request_.get(), nullptr);
2020-04-13 19:04:06 +02:00
songs_request_.reset();
}
}
void TidalService::GetSongs() {
if (!authenticated()) {
if (oauth_) {
emit SongsResults(SongMap(), tr("Not authenticated with Tidal."));
2020-04-13 19:04:06 +02:00
ShowConfig();
return;
}
else if (api_token_.isEmpty() || username_.isEmpty() || password_.isEmpty()) {
emit SongsResults(SongMap(), tr("Missing Tidal API token, username or password."));
2020-04-13 19:04:06 +02:00
ShowConfig();
return;
}
}
ResetSongsRequest();
songs_request_.reset(new TidalRequest(this, url_handler_, app_, network_, TidalBaseRequest::QueryType_Songs, this), [](TidalRequest *request) { request->deleteLater(); });
QObject::connect(songs_request_.get(), &TidalRequest::RequestLogin, this, &TidalService::SendLogin);
2021-01-26 16:48:04 +01:00
QObject::connect(songs_request_.get(), &TidalRequest::Results, this, &TidalService::SongsResultsReceived);
QObject::connect(songs_request_.get(), &TidalRequest::UpdateStatus, this, &TidalService::SongsUpdateStatusReceived);
QObject::connect(songs_request_.get(), &TidalRequest::UpdateProgress, this, &TidalService::SongsUpdateProgressReceived);
QObject::connect(this, &TidalService::LoginComplete, songs_request_.get(), &TidalRequest::LoginComplete);
2020-04-13 19:04:06 +02:00
songs_request_->Process();
}
void TidalService::SongsResultsReceived(const int id, const SongMap &songs, const QString &error) {
2020-04-13 19:04:06 +02:00
Q_UNUSED(id);
emit SongsResults(songs, error);
ResetSongsRequest();
2020-04-13 19:04:06 +02:00
}
void TidalService::SongsUpdateStatusReceived(const int id, const QString &text) {
Q_UNUSED(id);
emit SongsUpdateStatus(text);
}
void TidalService::SongsUpdateProgressReceived(const int id, const int progress) {
Q_UNUSED(id);
emit SongsUpdateProgress(progress);
}
int TidalService::Search(const QString &text, InternetSearchView::SearchType type) {
pending_search_id_ = next_pending_search_id_;
pending_search_text_ = text;
pending_search_type_ = type;
next_pending_search_id_++;
if (text.isEmpty()) {
timer_search_delay_->stop();
return pending_search_id_;
}
timer_search_delay_->start();
return pending_search_id_;
}
void TidalService::StartSearch() {
if (!authenticated()) {
if (oauth_) {
emit SearchResults(pending_search_id_, SongMap(), tr("Not authenticated with Tidal."));
2020-04-13 19:04:06 +02:00
ShowConfig();
return;
}
else if (api_token_.isEmpty() || username_.isEmpty() || password_.isEmpty()) {
emit SearchResults(pending_search_id_, SongMap(), tr("Missing Tidal API token, username or password."));
2020-04-13 19:04:06 +02:00
ShowConfig();
return;
}
}
search_id_ = pending_search_id_;
search_text_ = pending_search_text_;
SendSearch();
}
void TidalService::CancelSearch() {
}
void TidalService::SendSearch() {
2021-03-26 21:30:13 +01:00
TidalBaseRequest::QueryType type = TidalBaseRequest::QueryType_None;
2020-04-13 19:04:06 +02:00
switch (pending_search_type_) {
case InternetSearchView::SearchType_Artists:
type = TidalBaseRequest::QueryType_SearchArtists;
break;
case InternetSearchView::SearchType_Albums:
type = TidalBaseRequest::QueryType_SearchAlbums;
break;
case InternetSearchView::SearchType_Songs:
type = TidalBaseRequest::QueryType_SearchSongs;
break;
default:
//Error("Invalid search type.");
return;
}
search_request_.reset(new TidalRequest(this, url_handler_, app_, network_, type, this), [](TidalRequest *request) { request->deleteLater(); });
2020-04-13 19:04:06 +02:00
QObject::connect(search_request_.get(), &TidalRequest::RequestLogin, this, &TidalService::SendLogin);
2021-01-26 16:48:04 +01:00
QObject::connect(search_request_.get(), &TidalRequest::Results, this, &TidalService::SearchResultsReceived);
QObject::connect(search_request_.get(), &TidalRequest::UpdateStatus, this, &TidalService::SearchUpdateStatus);
QObject::connect(search_request_.get(), &TidalRequest::UpdateProgress, this, &TidalService::SearchUpdateProgress);
QObject::connect(this, &TidalService::LoginComplete, search_request_.get(), &TidalRequest::LoginComplete);
2020-04-13 19:04:06 +02:00
search_request_->Search(search_id_, search_text_);
search_request_->Process();
}
void TidalService::SearchResultsReceived(const int id, const SongMap &songs, const QString &error) {
2020-04-13 19:04:06 +02:00
emit SearchResults(id, songs, error);
search_request_.reset();
2020-04-13 19:04:06 +02:00
}
uint TidalService::GetStreamURL(const QUrl &url, QString &error) {
2020-04-13 19:04:06 +02:00
if (!authenticated()) {
if (oauth_) {
error = tr("Not authenticated with Tidal.");
return 0;
2020-04-13 19:04:06 +02:00
}
else if (api_token_.isEmpty() || username_.isEmpty() || password_.isEmpty()) {
error = tr("Missing Tidal API token, username or password.");
return 0;
2020-04-13 19:04:06 +02:00
}
}
uint id = 0;
while (id == 0) id = ++next_stream_url_request_id_;
std::shared_ptr<TidalStreamURLRequest> stream_url_req;
stream_url_req.reset(new TidalStreamURLRequest(this, network_, url, id), [](TidalStreamURLRequest *request) { request->deleteLater(); });
stream_url_requests_.insert(id, stream_url_req);
2020-04-13 19:04:06 +02:00
QObject::connect(stream_url_req.get(), &TidalStreamURLRequest::TryLogin, this, &TidalService::TryLogin);
QObject::connect(stream_url_req.get(), &TidalStreamURLRequest::StreamURLFailure, this, &TidalService::HandleStreamURLFailure);
QObject::connect(stream_url_req.get(), &TidalStreamURLRequest::StreamURLSuccess, this, &TidalService::HandleStreamURLSuccess);
QObject::connect(this, &TidalService::LoginComplete, stream_url_req.get(), &TidalStreamURLRequest::LoginComplete);
2020-04-13 19:04:06 +02:00
stream_url_req->Process();
return id;
}
void TidalService::HandleStreamURLFailure(const uint id, const QUrl &original_url, const QString &error) {
if (!stream_url_requests_.contains(id)) return;
stream_url_requests_.remove(id);
emit StreamURLFailure(id, original_url, error);
2020-04-13 19:04:06 +02:00
}
void TidalService::HandleStreamURLSuccess(const uint id, const QUrl &original_url, const QUrl &stream_url, const Song::FileType filetype, const int samplerate, const int bit_depth, const qint64 duration) {
2020-04-13 19:04:06 +02:00
if (!stream_url_requests_.contains(id)) return;
stream_url_requests_.remove(id);
2020-04-13 19:04:06 +02:00
emit StreamURLSuccess(id, original_url, stream_url, filetype, samplerate, bit_depth, duration);
2020-04-13 19:04:06 +02:00
}
void TidalService::LoginError(const QString &error, const QVariant &debug) {
if (!error.isEmpty()) login_errors_ << error;
QString error_html;
2020-04-23 21:05:57 +02:00
for (const QString &e : login_errors_) {
qLog(Error) << "Tidal:" << e;
error_html += e + "<br />";
2020-04-13 19:04:06 +02:00
}
if (debug.isValid()) qLog(Debug) << debug;
emit LoginFailure(error_html);
emit LoginComplete(false, error_html);
login_errors_.clear();
}