Add Deezer support

This commit is contained in:
Jonas Kvinge
2018-10-14 00:08:33 +02:00
parent 4aad44cb62
commit 0a81fa99fc
78 changed files with 5309 additions and 630 deletions

329
src/deezer/deezersearch.cpp Normal file
View File

@@ -0,0 +1,329 @@
/*
* Strawberry Music Player
* This code was part of Clementine (GlobalSearch)
* Copyright 2010, David Sansome <me@davidsansome.com>
* 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 <QObject>
#include <QList>
#include <QMap>
#include <QString>
#include <QStringList>
#include <QStringBuilder>
#include <QUrl>
#include <QImage>
#include <QPixmap>
#include <QIcon>
#include <QPainter>
#include <QTimerEvent>
#include <QSettings>
#include "core/application.h"
#include "core/logging.h"
#include "core/closure.h"
#include "core/iconloader.h"
#include "covermanager/albumcoverloader.h"
#include "internet/internetsongmimedata.h"
#include "playlist/songmimedata.h"
#include "deezersearch.h"
#include "deezerservice.h"
#include "settings/deezersettingspage.h"
const int DeezerSearch::kDelayedSearchTimeoutMs = 200;
const int DeezerSearch::kMaxResultsPerEmission = 2000;
const int DeezerSearch::kArtHeight = 32;
DeezerSearch::DeezerSearch(Application *app, QObject *parent)
: QObject(parent),
app_(app),
service_(app->internet_model()->Service<DeezerService>()),
name_("Deezer"),
id_("deezer"),
icon_(IconLoader::Load("deezer")),
searches_next_id_(1),
art_searches_next_id_(1) {
cover_loader_options_.desired_height_ = kArtHeight;
cover_loader_options_.pad_output_image_ = true;
cover_loader_options_.scale_output_image_ = true;
connect(app_->album_cover_loader(), SIGNAL(ImageLoaded(quint64, QImage)), SLOT(AlbumArtLoaded(quint64, QImage)));
connect(this, SIGNAL(SearchAsyncSig(int, QString, DeezerSettingsPage::SearchBy)), this, SLOT(DoSearchAsync(int, QString, DeezerSettingsPage::SearchBy)));
connect(this, SIGNAL(ResultsAvailable(int, DeezerSearch::ResultList)), SLOT(ResultsAvailableSlot(int, DeezerSearch::ResultList)));
connect(this, SIGNAL(ArtLoaded(int, QImage)), SLOT(ArtLoadedSlot(int, QImage)));
connect(service_, SIGNAL(UpdateStatus(QString)), SLOT(UpdateStatusSlot(QString)));
connect(service_, SIGNAL(ProgressSetMaximum(int)), SLOT(ProgressSetMaximumSlot(int)));
connect(service_, SIGNAL(UpdateProgress(int)), SLOT(UpdateProgressSlot(int)));
connect(service_, SIGNAL(SearchResults(int, SongList)), SLOT(SearchDone(int, SongList)));
connect(service_, SIGNAL(SearchError(int, QString)), SLOT(HandleError(int, QString)));
icon_as_image_ = QImage(icon_.pixmap(48, 48).toImage());
}
DeezerSearch::~DeezerSearch() {}
QStringList DeezerSearch::TokenizeQuery(const QString &query) {
QStringList tokens(query.split(QRegExp("\\s+")));
for (QStringList::iterator it = tokens.begin(); it != tokens.end(); ++it) {
(*it).remove('(');
(*it).remove(')');
(*it).remove('"');
const int colon = (*it).indexOf(":");
if (colon != -1) {
(*it).remove(0, colon + 1);
}
}
return tokens;
}
bool DeezerSearch::Matches(const QStringList &tokens, const QString &string) {
for (const QString &token : tokens) {
if (!string.contains(token, Qt::CaseInsensitive)) {
return false;
}
}
return true;
}
int DeezerSearch::SearchAsync(const QString &query, DeezerSettingsPage::SearchBy searchby) {
const int id = searches_next_id_++;
emit SearchAsyncSig(id, query, searchby);
return id;
}
void DeezerSearch::SearchAsync(int id, const QString &query, DeezerSettingsPage::SearchBy searchby) {
const int service_id = service_->Search(query, searchby);
pending_searches_[service_id] = PendingState(id, TokenizeQuery(query));
}
void DeezerSearch::DoSearchAsync(int id, const QString &query, DeezerSettingsPage::SearchBy searchby) {
int timer_id = startTimer(kDelayedSearchTimeoutMs);
delayed_searches_[timer_id].id_ = id;
delayed_searches_[timer_id].query_ = query;
delayed_searches_[timer_id].searchby_ = searchby;
}
void DeezerSearch::SearchDone(int service_id, const SongList &songs) {
// Map back to the original id.
const PendingState state = pending_searches_.take(service_id);
const int search_id = state.orig_id_;
ResultList ret;
for (const Song &song : songs) {
Result result;
result.metadata_ = song;
ret << result;
}
emit ResultsAvailable(search_id, ret);
MaybeSearchFinished(search_id);
}
void DeezerSearch::HandleError(const int id, const QString error) {
emit SearchError(id, error);
}
void DeezerSearch::MaybeSearchFinished(int id) {
if (pending_searches_.keys(PendingState(id, QStringList())).isEmpty()) {
emit SearchFinished(id);
}
}
void DeezerSearch::CancelSearch(int id) {
QMap<int, DelayedSearch>::iterator it;
for (it = delayed_searches_.begin(); it != delayed_searches_.end(); ++it) {
if (it.value().id_ == id) {
killTimer(it.key());
delayed_searches_.erase(it);
return;
}
}
service_->CancelSearch();
}
void DeezerSearch::timerEvent(QTimerEvent *e) {
QMap<int, DelayedSearch>::iterator it = delayed_searches_.find(e->timerId());
if (it != delayed_searches_.end()) {
SearchAsync(it.value().id_, it.value().query_, it.value().searchby_);
delayed_searches_.erase(it);
return;
}
QObject::timerEvent(e);
}
void DeezerSearch::ResultsAvailableSlot(int id, DeezerSearch::ResultList results) {
if (results.isEmpty()) return;
// Limit the number of results that are used from each emission.
if (results.count() > kMaxResultsPerEmission) {
DeezerSearch::ResultList::iterator begin = results.begin();
std::advance(begin, kMaxResultsPerEmission);
results.erase(begin, results.end());
}
// Load cached pixmaps into the results
for (DeezerSearch::ResultList::iterator it = results.begin(); it != results.end(); ++it) {
it->pixmap_cache_key_ = PixmapCacheKey(*it);
}
emit AddResults(id, results);
}
QString DeezerSearch::PixmapCacheKey(const DeezerSearch::Result &result) const {
return "deezer:" % result.metadata_.url().toString();
}
bool DeezerSearch::FindCachedPixmap(const DeezerSearch::Result &result, QPixmap *pixmap) const {
return pixmap_cache_.find(result.pixmap_cache_key_, pixmap);
}
int DeezerSearch::LoadArtAsync(const DeezerSearch::Result &result) {
const int id = art_searches_next_id_++;
pending_art_searches_[id] = result.pixmap_cache_key_;
quint64 loader_id = app_->album_cover_loader()->LoadImageAsync(cover_loader_options_, result.metadata_);
cover_loader_tasks_[loader_id] = id;
return id;
}
void DeezerSearch::ArtLoadedSlot(int id, const QImage &image) {
HandleLoadedArt(id, image);
}
void DeezerSearch::AlbumArtLoaded(quint64 id, const QImage &image) {
if (!cover_loader_tasks_.contains(id)) return;
int orig_id = cover_loader_tasks_.take(id);
HandleLoadedArt(orig_id, image);
}
void DeezerSearch::HandleLoadedArt(int id, const QImage &image) {
const QString key = pending_art_searches_.take(id);
QPixmap pixmap = QPixmap::fromImage(image);
pixmap_cache_.insert(key, pixmap);
emit ArtLoaded(id, pixmap);
}
QImage DeezerSearch::ScaleAndPad(const QImage &image) {
if (image.isNull()) return QImage();
const QSize target_size = QSize(kArtHeight, kArtHeight);
if (image.size() == target_size) return image;
// Scale the image down
QImage copy;
copy = image.scaled(target_size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
// Pad the image to kHeight x kHeight
if (copy.size() == target_size) return copy;
QImage padded_image(kArtHeight, kArtHeight, QImage::Format_ARGB32);
padded_image.fill(0);
QPainter p(&padded_image);
p.drawImage((kArtHeight - copy.width()) / 2, (kArtHeight - copy.height()) / 2, copy);
p.end();
return padded_image;
}
MimeData *DeezerSearch::LoadTracks(const ResultList &results) {
if (results.isEmpty()) {
return nullptr;
}
ResultList results_copy;
for (const Result &result : results) {
results_copy << result;
}
SongList songs;
for (const Result &result : results) {
songs << result.metadata_;
}
InternetSongMimeData *internet_song_mime_data = new InternetSongMimeData(service_);
internet_song_mime_data->songs = songs;
MimeData *mime_data = internet_song_mime_data;
QList<QUrl> urls;
for (const Result &result : results) {
urls << result.metadata_.url();
}
mime_data->setUrls(urls);
return mime_data;
}
void DeezerSearch::UpdateStatusSlot(QString text) {
emit UpdateStatus(text);
}
void DeezerSearch::ProgressSetMaximumSlot(int max) {
emit ProgressSetMaximum(max);
}
void DeezerSearch::UpdateProgressSlot(int progress) {
emit UpdateProgress(progress);
}

164
src/deezer/deezersearch.h Normal file
View File

@@ -0,0 +1,164 @@
/*
* Strawberry Music Player
* This code was part of Clementine (GlobalSearch)
* Copyright 2010, David Sansome <me@davidsansome.com>
* 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 DEEZERSEARCH_H
#define DEEZERSEARCH_H
#include "config.h"
#include <QObject>
#include <QFuture>
#include <QIcon>
#include <QMetaType>
#include <QPixmapCache>
#include "core/song.h"
#include "covermanager/albumcoverloaderoptions.h"
#include "settings/deezersettingspage.h"
class Application;
class MimeData;
class AlbumCoverLoader;
class InternetService;
class DeezerService;
class DeezerSearch : public QObject {
Q_OBJECT
public:
DeezerSearch(Application *app, QObject *parent = nullptr);
~DeezerSearch();
struct Result {
Song metadata_;
QString pixmap_cache_key_;
};
typedef QList<Result> ResultList;
static const int kDelayedSearchTimeoutMs;
static const int kMaxResultsPerEmission;
Application *application() const { return app_; }
DeezerService *service() const { return service_; }
int SearchAsync(const QString &query, DeezerSettingsPage::SearchBy searchby);
int LoadArtAsync(const DeezerSearch::Result &result);
void CancelSearch(int id);
void CancelArt(int id);
// Loads tracks for results that were previously emitted by ResultsAvailable.
// The implementation creates a SongMimeData with one Song for each Result.
MimeData *LoadTracks(const ResultList &results);
signals:
void SearchAsyncSig(int id, const QString &query, DeezerSettingsPage::SearchBy searchby);
void ResultsAvailable(int id, const DeezerSearch::ResultList &results);
void AddResults(int id, const DeezerSearch::ResultList &results);
void SearchError(const int id, const QString error);
void SearchFinished(int id);
void UpdateStatus(QString text);
void ProgressSetMaximum(int progress);
void UpdateProgress(int max);
void ArtLoaded(int id, const QPixmap &pixmap);
void ArtLoaded(int id, const QImage &image);
protected:
struct PendingState {
PendingState() : orig_id_(-1) {}
PendingState(int orig_id, QStringList tokens)
: orig_id_(orig_id), tokens_(tokens) {}
int orig_id_;
QStringList tokens_;
bool operator<(const PendingState &b) const {
return orig_id_ < b.orig_id_;
}
bool operator==(const PendingState &b) const {
return orig_id_ == b.orig_id_;
}
};
void timerEvent(QTimerEvent *e);
// These functions treat queries in the same way as LibraryQuery.
// They're useful for figuring out whether you got a result because it matched in the song title or the artist/album name.
static QStringList TokenizeQuery(const QString &query);
static bool Matches(const QStringList &tokens, const QString &string);
private slots:
void DoSearchAsync(int id, const QString &query, DeezerSettingsPage::SearchBy searchby);
void SearchDone(int id, const SongList &songs);
void HandleError(const int id, const QString error);
void ResultsAvailableSlot(int id, DeezerSearch::ResultList results);
void ArtLoadedSlot(int id, const QImage &image);
void AlbumArtLoaded(quint64 id, const QImage &image);
void UpdateStatusSlot(QString text);
void ProgressSetMaximumSlot(int progress);
void UpdateProgressSlot(int max);
private:
void SearchAsync(int id, const QString &query, DeezerSettingsPage::SearchBy searchby);
void HandleLoadedArt(int id, const QImage &image);
bool FindCachedPixmap(const DeezerSearch::Result &result, QPixmap *pixmap) const;
QString PixmapCacheKey(const DeezerSearch::Result &result) const;
void MaybeSearchFinished(int id);
void ShowConfig() {}
static QImage ScaleAndPad(const QImage &image);
private:
struct DelayedSearch {
int id_;
QString query_;
DeezerSettingsPage::SearchBy searchby_;
};
static const int kArtHeight;
Application *app_;
DeezerService *service_;
Song::Source source_;
QString name_;
QString id_;
QIcon icon_;
QImage icon_as_image_;
int searches_next_id_;
int art_searches_next_id_;
QMap<int, DelayedSearch> delayed_searches_;
QMap<int, QString> pending_art_searches_;
QPixmapCache pixmap_cache_;
AlbumCoverLoaderOptions cover_loader_options_;
QMap<quint64, int> cover_loader_tasks_;
QMap<int, PendingState> pending_searches_;
};
Q_DECLARE_METATYPE(DeezerSearch::Result)
Q_DECLARE_METATYPE(DeezerSearch::ResultList)
#endif // DEEZERSEARCH_H

View File

@@ -0,0 +1,35 @@
/*
* Strawberry Music Player
* This code was part of Clementine (GlobalSearch)
* Copyright 2012, David Sansome <me@davidsansome.com>
*
* 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 <QPainter>
#include <QStyleOptionViewItem>
#include "deezersearchitemdelegate.h"
#include "deezersearchview.h"
DeezerSearchItemDelegate::DeezerSearchItemDelegate(DeezerSearchView* view)
: CollectionItemDelegate(view), view_(view) {}
void DeezerSearchItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
// Tell the view we painted this item so it can lazy load some art.
const_cast<DeezerSearchView*>(view_)->LazyLoadArt(index);
CollectionItemDelegate::paint(painter, option, index);
}

View File

@@ -0,0 +1,41 @@
/*
* Strawberry Music Player
* This code was part of Clementine (GlobalSearch)
* Copyright 2012, David Sansome <me@davidsansome.com>
*
* 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 DEEZERSEARCHITEMDELEGATE_H
#define DEEZERSEARCHITEMDELEGATE_H
#include <QPainter>
#include <QStyleOptionViewItem>
#include "collection/collectionview.h"
class DeezerSearchView;
class DeezerSearchItemDelegate : public CollectionItemDelegate {
public:
DeezerSearchItemDelegate(DeezerSearchView *view);
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
private:
DeezerSearchView* view_;
};
#endif // DEEZERSEARCHITEMDELEGATE_H

View File

@@ -0,0 +1,319 @@
/*
* Strawberry Music Player
* This code was part of Clementine (GlobalSearch)
* Copyright 2012, David Sansome <me@davidsansome.com>
*
* 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 <QStandardItem>
#include <QStandardItemModel>
#include <QList>
#include <QSet>
#include <QVariant>
#include <QString>
#include <QPixmap>
#include <QMimeData>
#include "core/mimedata.h"
#include "core/iconloader.h"
#include "core/logging.h"
#include "deezersearch.h"
#include "deezersearchmodel.h"
DeezerSearchModel::DeezerSearchModel(DeezerSearch *engine, QObject *parent)
: QStandardItemModel(parent),
engine_(engine),
proxy_(nullptr),
use_pretty_covers_(true),
artist_icon_(IconLoader::Load("folder-sound")) {
group_by_[0] = CollectionModel::GroupBy_Artist;
group_by_[1] = CollectionModel::GroupBy_Album;
group_by_[2] = CollectionModel::GroupBy_None;
QIcon nocover = IconLoader::Load("cdcase");
no_cover_icon_ = nocover.pixmap(nocover.availableSizes().last()).scaled(CollectionModel::kPrettyCoverSize, CollectionModel::kPrettyCoverSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
//no_cover_icon_ = QPixmap(":/pictures/noalbumart.png").scaled(CollectionModel::kPrettyCoverSize, CollectionModel::kPrettyCoverSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
album_icon_ = no_cover_icon_;
}
void DeezerSearchModel::AddResults(const DeezerSearch::ResultList &results) {
int sort_index = 0;
for (const DeezerSearch::Result &result : results) {
QStandardItem *parent = invisibleRootItem();
// Find (or create) the container nodes for this result if we can.
ContainerKey key;
key.provider_index_ = sort_index;
parent = BuildContainers(result.metadata_, parent, &key);
// Create the item
QStandardItem *item = new QStandardItem;
item->setText(result.metadata_.TitleWithCompilationArtist());
item->setData(QVariant::fromValue(result), Role_Result);
item->setData(sort_index, Role_ProviderIndex);
parent->appendRow(item);
}
}
QStandardItem *DeezerSearchModel::BuildContainers(const Song &s, QStandardItem *parent, ContainerKey *key, int level) {
if (level >= 3) {
return parent;
}
bool has_artist_icon = false;
bool has_album_icon = false;
QString display_text;
QString sort_text;
int unique_tag = -1;
int year = 0;
switch (group_by_[level]) {
case CollectionModel::GroupBy_Artist:
if (s.is_compilation()) {
display_text = tr("Various artists");
sort_text = "aaaaaa";
}
else {
display_text = CollectionModel::TextOrUnknown(s.artist());
sort_text = CollectionModel::SortTextForArtist(s.artist());
}
has_artist_icon = true;
break;
case CollectionModel::GroupBy_YearAlbum:
year = qMax(0, s.year());
display_text = CollectionModel::PrettyYearAlbum(year, s.album());
sort_text = CollectionModel::SortTextForNumber(year) + s.album();
unique_tag = s.album_id();
has_album_icon = true;
break;
case CollectionModel::GroupBy_OriginalYearAlbum:
year = qMax(0, s.effective_originalyear());
display_text = CollectionModel::PrettyYearAlbum(year, s.album());
sort_text = CollectionModel::SortTextForNumber(year) + s.album();
unique_tag = s.album_id();
has_album_icon = true;
break;
case CollectionModel::GroupBy_Year:
year = qMax(0, s.year());
display_text = QString::number(year);
sort_text = CollectionModel::SortTextForNumber(year) + " ";
break;
case CollectionModel::GroupBy_OriginalYear:
year = qMax(0, s.effective_originalyear());
display_text = QString::number(year);
sort_text = CollectionModel::SortTextForNumber(year) + " ";
break;
case CollectionModel::GroupBy_Composer:
display_text = s.composer();
case CollectionModel::GroupBy_Performer:
display_text = s.performer();
case CollectionModel::GroupBy_Disc:
display_text = s.disc();
case CollectionModel::GroupBy_Grouping:
display_text = s.grouping();
case CollectionModel::GroupBy_Genre:
if (display_text.isNull()) display_text = s.genre();
case CollectionModel::GroupBy_Album:
unique_tag = s.album_id();
if (display_text.isNull()) {
display_text = s.album();
}
// fallthrough
case CollectionModel::GroupBy_AlbumArtist:
if (display_text.isNull()) display_text = s.effective_albumartist();
display_text = CollectionModel::TextOrUnknown(display_text);
sort_text = CollectionModel::SortTextForArtist(display_text);
has_album_icon = true;
break;
case CollectionModel::GroupBy_FileType:
display_text = s.TextForFiletype();
sort_text = display_text;
break;
case CollectionModel::GroupBy_Bitrate:
display_text = QString(s.bitrate(), 1);
sort_text = display_text;
break;
case CollectionModel::GroupBy_Samplerate:
display_text = QString(s.samplerate(), 1);
sort_text = display_text;
break;
case CollectionModel::GroupBy_Bitdepth:
display_text = QString(s.bitdepth(), 1);
sort_text = display_text;
break;
case CollectionModel::GroupBy_None:
return parent;
}
// Find a container for this level
key->group_[level] = display_text + QString::number(unique_tag);
QStandardItem *container = containers_[*key];
if (!container) {
container = new QStandardItem(display_text);
container->setData(key->provider_index_, Role_ProviderIndex);
container->setData(sort_text, CollectionModel::Role_SortText);
container->setData(group_by_[level], CollectionModel::Role_ContainerType);
if (has_artist_icon) {
container->setIcon(artist_icon_);
}
else if (has_album_icon) {
if (use_pretty_covers_) {
container->setData(no_cover_icon_, Qt::DecorationRole);
}
else {
container->setIcon(album_icon_);
}
}
parent->appendRow(container);
containers_[*key] = container;
}
// Create the container for the next level.
return BuildContainers(s, container, key, level + 1);
}
void DeezerSearchModel::Clear() {
containers_.clear();
clear();
}
DeezerSearch::ResultList DeezerSearchModel::GetChildResults(const QModelIndexList &indexes) const {
QList<QStandardItem*> items;
for (const QModelIndex &index : indexes) {
items << itemFromIndex(index);
}
return GetChildResults(items);
}
DeezerSearch::ResultList DeezerSearchModel::GetChildResults(const QList<QStandardItem*> &items) const {
DeezerSearch::ResultList results;
QSet<const QStandardItem*> visited;
for (QStandardItem *item : items) {
GetChildResults(item, &results, &visited);
}
return results;
}
void DeezerSearchModel::GetChildResults(const QStandardItem *item, DeezerSearch::ResultList *results, QSet<const QStandardItem*> *visited) const {
if (visited->contains(item)) {
return;
}
visited->insert(item);
// Does this item have children?
if (item->rowCount()) {
const QModelIndex parent_proxy_index = proxy_->mapFromSource(item->index());
// Yes - visit all the children, but do so through the proxy so we get them
// in the right order.
for (int i = 0; i < item->rowCount(); ++i) {
const QModelIndex proxy_index = parent_proxy_index.child(i, 0);
const QModelIndex index = proxy_->mapToSource(proxy_index);
GetChildResults(itemFromIndex(index), results, visited);
}
}
else {
// No - maybe it's a song, add its result if valid
QVariant result = item->data(Role_Result);
if (result.isValid()) {
results->append(result.value<DeezerSearch::Result>());
}
else {
// Maybe it's a provider then?
bool is_provider;
const int sort_index = item->data(Role_ProviderIndex).toInt(&is_provider);
if (is_provider) {
// Go through all the items (through the proxy to keep them ordered) and add the ones belonging to this provider to our list
for (int i = 0; i < proxy_->rowCount(invisibleRootItem()->index()); ++i) {
QModelIndex child_index = proxy_->index(i, 0, invisibleRootItem()->index());
const QStandardItem *child_item = itemFromIndex(proxy_->mapToSource(child_index));
if (child_item->data(Role_ProviderIndex).toInt() == sort_index) {
GetChildResults(child_item, results, visited);
}
}
}
}
}
}
QMimeData *DeezerSearchModel::mimeData(const QModelIndexList &indexes) const {
return engine_->LoadTracks(GetChildResults(indexes));
}
namespace {
void GatherResults(const QStandardItem *parent, DeezerSearch::ResultList *results) {
QVariant result_variant = parent->data(DeezerSearchModel::Role_Result);
if (result_variant.isValid()) {
DeezerSearch::Result result = result_variant.value<DeezerSearch::Result>();
(*results).append(result);
}
for (int i = 0; i < parent->rowCount(); ++i) {
GatherResults(parent->child(i), results);
}
}
}
void DeezerSearchModel::SetGroupBy(const CollectionModel::Grouping &grouping, bool regroup_now) {
const CollectionModel::Grouping old_group_by = group_by_;
group_by_ = grouping;
if (regroup_now && group_by_ != old_group_by) {
// Walk the tree gathering the results we have already
DeezerSearch::ResultList results;
GatherResults(invisibleRootItem(), &results);
// Reset the model and re-add all the results using the new grouping.
Clear();
AddResults(results);
}
}

View File

@@ -0,0 +1,109 @@
/*
* Strawberry Music Player
* This code was part of Clementine (GlobalSearch)
* Copyright 2012, David Sansome <me@davidsansome.com>
*
* 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 DEEZERSEARCHMODEL_H
#define DEEZERSEARCHMODEL_H
#include "config.h"
#include <QtGlobal>
#include <QObject>
#include <QMimeData>
#include <QStandardItemModel>
#include <QStandardItem>
#include <QSortFilterProxyModel>
#include <QMap>
#include <QSet>
#include <QList>
#include <QString>
#include <QStringList>
#include <QIcon>
#include <QPixmap>
#include "collection/collectionmodel.h"
#include "deezersearch.h"
class DeezerSearchModel : public QStandardItemModel {
Q_OBJECT
public:
DeezerSearchModel(DeezerSearch *engine, QObject *parent = nullptr);
enum Role {
Role_Result = CollectionModel::LastRole,
Role_LazyLoadingArt,
Role_ProviderIndex,
LastRole
};
struct ContainerKey {
int provider_index_;
QString group_[3];
};
void set_proxy(QSortFilterProxyModel *proxy) { proxy_ = proxy; }
void set_use_pretty_covers(bool pretty) { use_pretty_covers_ = pretty; }
void SetGroupBy(const CollectionModel::Grouping &grouping, bool regroup_now);
void Clear();
DeezerSearch::ResultList GetChildResults(const QModelIndexList &indexes) const;
DeezerSearch::ResultList GetChildResults(const QList<QStandardItem*> &items) const;
QMimeData *mimeData(const QModelIndexList &indexes) const;
public slots:
void AddResults(const DeezerSearch::ResultList &results);
private:
QStandardItem *BuildContainers(const Song &metadata, QStandardItem *parent, ContainerKey *key, int level = 0);
void GetChildResults(const QStandardItem *item, DeezerSearch::ResultList *results, QSet<const QStandardItem*> *visited) const;
private:
DeezerSearch *engine_;
QSortFilterProxyModel *proxy_;
bool use_pretty_covers_;
QIcon artist_icon_;
QPixmap no_cover_icon_;
QIcon album_icon_;
CollectionModel::Grouping group_by_;
QMap<ContainerKey, QStandardItem*> containers_;
};
inline uint qHash(const DeezerSearchModel::ContainerKey &key) {
return qHash(key.provider_index_) ^ qHash(key.group_[0]) ^ qHash(key.group_[1]) ^ qHash(key.group_[2]);
}
inline bool operator<(const DeezerSearchModel::ContainerKey &left, const DeezerSearchModel::ContainerKey &right) {
#define CMP(field) \
if (left.field < right.field) return true; \
if (left.field > right.field) return false
CMP(provider_index_);
CMP(group_[0]);
CMP(group_[1]);
CMP(group_[2]);
return false;
#undef CMP
}
#endif // DEEZERSEARCHMODEL_H

View File

@@ -0,0 +1,79 @@
/*
* Strawberry Music Player
* This code was part of Clementine (GlobalSearch)
* Copyright 2010, David Sansome <me@davidsansome.com>
*
* 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 <QSortFilterProxyModel>
#include <QString>
#include "core/logging.h"
#include "deezersearchmodel.h"
#include "deezersearchsortmodel.h"
DeezerSearchSortModel::DeezerSearchSortModel(QObject *parent)
: QSortFilterProxyModel(parent) {}
bool DeezerSearchSortModel::lessThan(const QModelIndex &left, const QModelIndex &right) const {
// Compare the provider sort index first.
const int index_left = left.data(DeezerSearchModel::Role_ProviderIndex).toInt();
const int index_right = right.data(DeezerSearchModel::Role_ProviderIndex).toInt();
if (index_left < index_right) return true;
if (index_left > index_right) return false;
// Dividers always go first
if (left.data(CollectionModel::Role_IsDivider).toBool()) return true;
if (right.data(CollectionModel::Role_IsDivider).toBool()) return false;
// Containers go before songs if they're at the same level
const bool left_is_container = left.data(CollectionModel::Role_ContainerType).isValid();
const bool right_is_container = right.data(CollectionModel::Role_ContainerType).isValid();
if (left_is_container && !right_is_container) return true;
if (right_is_container && !left_is_container) return false;
// Containers get sorted on their sort text.
if (left_is_container) {
return QString::localeAwareCompare(left.data(CollectionModel::Role_SortText).toString(), right.data(CollectionModel::Role_SortText).toString()) < 0;
}
// Otherwise we're comparing songs. Sort by disc, track, then title.
const DeezerSearch::Result r1 = left.data(DeezerSearchModel::Role_Result).value<DeezerSearch::Result>();
const DeezerSearch::Result r2 = right.data(DeezerSearchModel::Role_Result).value<DeezerSearch::Result>();
#define CompareInt(field) \
if (r1.metadata_.field() < r2.metadata_.field()) return true; \
if (r1.metadata_.field() > r2.metadata_.field()) return false
int ret = 0;
#define CompareString(field) \
ret = QString::localeAwareCompare(r1.metadata_.field(), r2.metadata_.field()); \
if (ret < 0) return true; \
if (ret > 0) return false
CompareInt(disc);
CompareInt(track);
CompareString(title);
return false;
#undef CompareInt
#undef CompareString
}

View File

@@ -0,0 +1,35 @@
/*
* Strawberry Music Player
* This code was part of Clementine (GlobalSearch)
* Copyright 2010, David Sansome <me@davidsansome.com>
*
* 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 DEEZERSEARCHSORTMODEL_H
#define DEEZERSEARCHSORTMODEL_H
#include <QObject>
#include <QSortFilterProxyModel>
class DeezerSearchSortModel : public QSortFilterProxyModel {
public:
DeezerSearchSortModel(QObject *parent = nullptr);
protected:
bool lessThan(const QModelIndex &left, const QModelIndex &right) const;
};
#endif // DEEZERSEARCHSORTMODEL_H

View File

@@ -0,0 +1,574 @@
/*
* Strawberry Music Player
* This code was part of Clementine (GlobalSearch)
* Copyright 2012, David Sansome <me@davidsansome.com>
* 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 <functional>
#include <QtGlobal>
#include <QWidget>
#include <QTimer>
#include <QList>
#include <QString>
#include <QStringList>
#include <QPixmap>
#include <QPalette>
#include <QColor>
#include <QFont>
#include <QMenu>
#include <QSortFilterProxyModel>
#include <QStandardItem>
#include <QSettings>
#include <QAction>
#include <QtEvents>
#include "core/application.h"
#include "core/logging.h"
#include "core/mimedata.h"
#include "core/timeconstants.h"
#include "core/iconloader.h"
#include "internet/internetsongmimedata.h"
#include "collection/collectionfilterwidget.h"
#include "collection/collectionmodel.h"
#include "collection/groupbydialog.h"
#include "playlist/songmimedata.h"
#include "deezersearch.h"
#include "deezersearchitemdelegate.h"
#include "deezersearchmodel.h"
#include "deezersearchsortmodel.h"
#include "deezersearchview.h"
#include "ui_deezersearchview.h"
#include "settings/deezersettingspage.h"
using std::placeholders::_1;
using std::placeholders::_2;
using std::swap;
const int DeezerSearchView::kSwapModelsTimeoutMsec = 250;
DeezerSearchView::DeezerSearchView(Application *app, QWidget *parent)
: QWidget(parent),
app_(app),
engine_(app_->deezer_search()),
ui_(new Ui_DeezerSearchView),
context_menu_(nullptr),
last_search_id_(0),
front_model_(new DeezerSearchModel(engine_, this)),
back_model_(new DeezerSearchModel(engine_, this)),
current_model_(front_model_),
front_proxy_(new DeezerSearchSortModel(this)),
back_proxy_(new DeezerSearchSortModel(this)),
current_proxy_(front_proxy_),
swap_models_timer_(new QTimer(this)),
search_icon_(IconLoader::Load("search")),
warning_icon_(IconLoader::Load("dialog-warning")),
error_(false) {
ui_->setupUi(this);
ui_->progressbar->hide();
ui_->progressbar->reset();
front_model_->set_proxy(front_proxy_);
back_model_->set_proxy(back_proxy_);
ui_->search->installEventFilter(this);
ui_->results_stack->installEventFilter(this);
ui_->settings->setIcon(IconLoader::Load("configure"));
// Must be a queued connection to ensure the DeezerSearch handles it first.
connect(app_, SIGNAL(SettingsChanged()), SLOT(ReloadSettings()), Qt::QueuedConnection);
connect(ui_->search, SIGNAL(textChanged(QString)), SLOT(TextEdited(QString)));
connect(ui_->results, SIGNAL(AddToPlaylistSignal(QMimeData*)), SIGNAL(AddToPlaylist(QMimeData*)));
connect(ui_->results, SIGNAL(FocusOnFilterSignal(QKeyEvent*)), SLOT(FocusOnFilter(QKeyEvent*)));
// Set the appearance of the results list
ui_->results->setItemDelegate(new DeezerSearchItemDelegate(this));
ui_->results->setAttribute(Qt::WA_MacShowFocusRect, false);
ui_->results->setStyleSheet("QTreeView::item{padding-top:1px;}");
// Show the help page initially
ui_->results_stack->setCurrentWidget(ui_->help_page);
ui_->help_frame->setBackgroundRole(QPalette::Base);
// Set the colour of the help text to the disabled window text colour
QPalette help_palette = ui_->label_helptext->palette();
const QColor help_color = help_palette.color(QPalette::Disabled, QPalette::WindowText);
help_palette.setColor(QPalette::Normal, QPalette::WindowText, help_color);
help_palette.setColor(QPalette::Inactive, QPalette::WindowText, help_color);
ui_->label_helptext->setPalette(help_palette);
// Make it bold
QFont help_font = ui_->label_helptext->font();
help_font.setBold(true);
ui_->label_helptext->setFont(help_font);
// Set up the sorting proxy model
front_proxy_->setSourceModel(front_model_);
front_proxy_->setDynamicSortFilter(true);
front_proxy_->sort(0);
back_proxy_->setSourceModel(back_model_);
back_proxy_->setDynamicSortFilter(true);
back_proxy_->sort(0);
swap_models_timer_->setSingleShot(true);
swap_models_timer_->setInterval(kSwapModelsTimeoutMsec);
connect(swap_models_timer_, SIGNAL(timeout()), SLOT(SwapModels()));
// Add actions to the settings menu
group_by_actions_ = CollectionFilterWidget::CreateGroupByActions(this);
QMenu *settings_menu = new QMenu(this);
settings_menu->addActions(group_by_actions_->actions());
settings_menu->addSeparator();
settings_menu->addAction(IconLoader::Load("configure"), tr("Configure Deezer..."), this, SLOT(OpenSettingsDialog()));
ui_->settings->setMenu(settings_menu);
connect(ui_->radiobutton_searchbyalbums, SIGNAL(clicked(bool)), SLOT(SearchByAlbumsClicked(bool)));
connect(ui_->radiobutton_searchbysongs, SIGNAL(clicked(bool)), SLOT(SearchBySongsClicked(bool)));
connect(group_by_actions_, SIGNAL(triggered(QAction*)), SLOT(GroupByClicked(QAction*)));
// These have to be queued connections because they may get emitted before our call to Search() (or whatever) returns and we add the ID to the map.
connect(engine_, SIGNAL(UpdateStatus(QString)), SLOT(UpdateStatus(QString)));
connect(engine_, SIGNAL(ProgressSetMaximum(int)), SLOT(ProgressSetMaximum(int)), Qt::QueuedConnection);
connect(engine_, SIGNAL(UpdateProgress(int)), SLOT(UpdateProgress(int)), Qt::QueuedConnection);
connect(engine_, SIGNAL(AddResults(int, DeezerSearch::ResultList)), SLOT(AddResults(int, DeezerSearch::ResultList)), Qt::QueuedConnection);
connect(engine_, SIGNAL(SearchError(int, QString)), SLOT(SearchError(int, QString)), Qt::QueuedConnection);
connect(engine_, SIGNAL(ArtLoaded(int, QPixmap)), SLOT(ArtLoaded(int, QPixmap)), Qt::QueuedConnection);
ReloadSettings();
}
DeezerSearchView::~DeezerSearchView() { delete ui_; }
void DeezerSearchView::ReloadSettings() {
QSettings s;
// Collection settings
s.beginGroup(DeezerSettingsPage::kSettingsGroup);
const bool pretty = s.value("pretty_covers", true).toBool();
front_model_->set_use_pretty_covers(pretty);
back_model_->set_use_pretty_covers(pretty);
s.endGroup();
// Deezer search settings
s.beginGroup(DeezerSettingsPage::kSettingsGroup);
searchby_ = DeezerSettingsPage::SearchBy(s.value("searchby", int(DeezerSettingsPage::SearchBy_Songs)).toInt());
switch (searchby_) {
case DeezerSettingsPage::SearchBy_Songs:
ui_->radiobutton_searchbysongs->setChecked(true);
break;
case DeezerSettingsPage::SearchBy_Albums:
ui_->radiobutton_searchbyalbums->setChecked(true);
break;
}
SetGroupBy(CollectionModel::Grouping(
CollectionModel::GroupBy(s.value("group_by1", int(CollectionModel::GroupBy_Artist)).toInt()),
CollectionModel::GroupBy(s.value("group_by2", int(CollectionModel::GroupBy_Album)).toInt()),
CollectionModel::GroupBy(s.value("group_by3", int(CollectionModel::GroupBy_None)).toInt())));
s.endGroup();
}
void DeezerSearchView::StartSearch(const QString &query) {
ui_->search->setText(query);
TextEdited(query);
// Swap models immediately
swap_models_timer_->stop();
SwapModels();
}
void DeezerSearchView::TextEdited(const QString &text) {
const QString trimmed(text.trimmed());
error_ = false;
// Add results to the back model, switch models after some delay.
back_model_->Clear();
current_model_ = back_model_;
current_proxy_ = back_proxy_;
swap_models_timer_->start();
// Cancel the last search (if any) and start the new one.
engine_->CancelSearch(last_search_id_);
// If text query is empty, don't start a new search
if (trimmed.isEmpty()) {
last_search_id_ = -1;
ui_->label_helptext->setText("Enter search terms above to find music");
ui_->label_status->clear();
ui_->progressbar->hide();
ui_->progressbar->reset();
}
else {
ui_->progressbar->reset();
last_search_id_ = engine_->SearchAsync(trimmed, searchby_);
}
}
void DeezerSearchView::AddResults(int id, const DeezerSearch::ResultList &results) {
if (id != last_search_id_) return;
if (results.isEmpty()) return;
ui_->label_status->clear();
ui_->progressbar->reset();
ui_->progressbar->hide();
current_model_->AddResults(results);
}
void DeezerSearchView::SearchError(const int id, const QString error) {
error_ = true;
ui_->label_helptext->setText(error);
ui_->label_status->clear();
ui_->progressbar->reset();
ui_->progressbar->hide();
ui_->results_stack->setCurrentWidget(ui_->help_page);
}
void DeezerSearchView::SwapModels() {
art_requests_.clear();
std::swap(front_model_, back_model_);
std::swap(front_proxy_, back_proxy_);
ui_->results->setModel(front_proxy_);
if (ui_->search->text().trimmed().isEmpty() || error_) {
ui_->results_stack->setCurrentWidget(ui_->help_page);
}
else {
ui_->results_stack->setCurrentWidget(ui_->results_page);
}
}
void DeezerSearchView::LazyLoadArt(const QModelIndex &proxy_index) {
if (!proxy_index.isValid() || proxy_index.model() != front_proxy_) {
return;
}
// Already loading art for this item?
if (proxy_index.data(DeezerSearchModel::Role_LazyLoadingArt).isValid()) {
return;
}
// Should we even load art at all?
if (!app_->collection_model()->use_pretty_covers()) {
return;
}
// Is this an album?
const CollectionModel::GroupBy container_type = CollectionModel::GroupBy(proxy_index.data(CollectionModel::Role_ContainerType).toInt());
if (container_type != CollectionModel::GroupBy_Album &&
container_type != CollectionModel::GroupBy_AlbumArtist &&
container_type != CollectionModel::GroupBy_YearAlbum &&
container_type != CollectionModel::GroupBy_OriginalYearAlbum) {
return;
}
// Mark the item as loading art
const QModelIndex source_index = front_proxy_->mapToSource(proxy_index);
QStandardItem *item = front_model_->itemFromIndex(source_index);
item->setData(true, DeezerSearchModel::Role_LazyLoadingArt);
// Walk down the item's children until we find a track
while (item->rowCount()) {
item = item->child(0);
}
// Get the track's Result
const DeezerSearch::Result result = item->data(DeezerSearchModel::Role_Result).value<DeezerSearch::Result>();
// Load the art.
int id = engine_->LoadArtAsync(result);
art_requests_[id] = source_index;
}
void DeezerSearchView::ArtLoaded(int id, const QPixmap &pixmap) {
if (!art_requests_.contains(id)) return;
QModelIndex index = art_requests_.take(id);
if (!pixmap.isNull()) {
front_model_->itemFromIndex(index)->setData(pixmap, Qt::DecorationRole);
}
}
MimeData *DeezerSearchView::SelectedMimeData() {
if (!ui_->results->selectionModel()) return nullptr;
// Get all selected model indexes
QModelIndexList indexes = ui_->results->selectionModel()->selectedRows();
if (indexes.isEmpty()) {
// There's nothing selected - take the first thing in the model that isn't a divider.
for (int i = 0; i < front_proxy_->rowCount(); ++i) {
QModelIndex index = front_proxy_->index(i, 0);
if (!index.data(CollectionModel::Role_IsDivider).toBool()) {
indexes << index;
ui_->results->setCurrentIndex(index);
break;
}
}
}
// Still got nothing? Give up.
if (indexes.isEmpty()) {
return nullptr;
}
// Get items for these indexes
QList<QStandardItem*> items;
for (const QModelIndex &index : indexes) {
items << (front_model_->itemFromIndex(front_proxy_->mapToSource(index)));
}
// Get a MimeData for these items
return engine_->LoadTracks(front_model_->GetChildResults(items));
}
bool DeezerSearchView::eventFilter(QObject *object, QEvent *event) {
if (object == ui_->search && event->type() == QEvent::KeyRelease) {
if (SearchKeyEvent(static_cast<QKeyEvent*>(event))) {
return true;
}
}
else if (object == ui_->results_stack && event->type() == QEvent::ContextMenu) {
if (ResultsContextMenuEvent(static_cast<QContextMenuEvent*>(event))) {
return true;
}
}
return QWidget::eventFilter(object, event);
}
bool DeezerSearchView::SearchKeyEvent(QKeyEvent *event) {
switch (event->key()) {
case Qt::Key_Up:
ui_->results->UpAndFocus();
break;
case Qt::Key_Down:
ui_->results->DownAndFocus();
break;
case Qt::Key_Escape:
ui_->search->clear();
break;
case Qt::Key_Return:
TextEdited(ui_->search->text());
break;
default:
return false;
}
event->accept();
return true;
}
bool DeezerSearchView::ResultsContextMenuEvent(QContextMenuEvent *event) {
context_menu_ = new QMenu(this);
context_actions_ << context_menu_->addAction( IconLoader::Load("media-play"), tr("Append to current playlist"), this, SLOT(AddSelectedToPlaylist()));
context_actions_ << context_menu_->addAction( IconLoader::Load("media-play"), tr("Replace current playlist"), this, SLOT(LoadSelected()));
context_actions_ << context_menu_->addAction( IconLoader::Load("document-new"), tr("Open in new playlist"), this, SLOT(OpenSelectedInNewPlaylist()));
context_menu_->addSeparator();
context_actions_ << context_menu_->addAction(IconLoader::Load("go-next"), tr("Queue track"), this, SLOT(AddSelectedToPlaylistEnqueue()));
context_menu_->addSeparator();
if (ui_->results->selectionModel() && ui_->results->selectionModel()->selectedRows().length() == 1) {
context_actions_ << context_menu_->addAction(IconLoader::Load("search"), tr("Search for this"), this, SLOT(SearchForThis()));
}
context_menu_->addSeparator();
context_menu_->addMenu(tr("Group by"))->addActions(group_by_actions_->actions());
context_menu_->addAction(IconLoader::Load("configure"), tr("Configure Deezer..."), this, SLOT(OpenSettingsDialog()));
const bool enable_context_actions = ui_->results->selectionModel() && ui_->results->selectionModel()->hasSelection();
for (QAction *action : context_actions_) {
action->setEnabled(enable_context_actions);
}
context_menu_->popup(event->globalPos());
return true;
}
void DeezerSearchView::AddSelectedToPlaylist() {
emit AddToPlaylist(SelectedMimeData());
}
void DeezerSearchView::LoadSelected() {
MimeData *data = SelectedMimeData();
if (!data) return;
data->clear_first_ = true;
emit AddToPlaylist(data);
}
void DeezerSearchView::AddSelectedToPlaylistEnqueue() {
MimeData *data = SelectedMimeData();
if (!data) return;
data->enqueue_now_ = true;
emit AddToPlaylist(data);
}
void DeezerSearchView::OpenSelectedInNewPlaylist() {
MimeData *data = SelectedMimeData();
if (!data) return;
data->open_in_new_playlist_ = true;
emit AddToPlaylist(data);
}
void DeezerSearchView::SearchForThis() {
StartSearch(ui_->results->selectionModel()->selectedRows().first().data().toString());
}
void DeezerSearchView::showEvent(QShowEvent *e) {
QWidget::showEvent(e);
FocusSearchField();
}
void DeezerSearchView::FocusSearchField() {
ui_->search->setFocus();
ui_->search->selectAll();
}
void DeezerSearchView::hideEvent(QHideEvent *e) {
QWidget::hideEvent(e);
}
void DeezerSearchView::FocusOnFilter(QKeyEvent *event) {
ui_->search->setFocus();
QApplication::sendEvent(ui_->search, event);
}
void DeezerSearchView::OpenSettingsDialog() {
app_->OpenSettingsDialogAtPage(SettingsDialog::Page_Deezer);
}
void DeezerSearchView::GroupByClicked(QAction *action) {
if (action->property("group_by").isNull()) {
if (!group_by_dialog_) {
group_by_dialog_.reset(new GroupByDialog);
connect(group_by_dialog_.data(), SIGNAL(Accepted(CollectionModel::Grouping)), SLOT(SetGroupBy(CollectionModel::Grouping)));
}
group_by_dialog_->show();
return;
}
SetGroupBy(action->property("group_by").value<CollectionModel::Grouping>());
}
void DeezerSearchView::SetGroupBy(const CollectionModel::Grouping &g) {
// Clear requests: changing "group by" on the models will cause all the items to be removed/added again,
// so all the QModelIndex here will become invalid. New requests will be created for those
// songs when they will be displayed again anyway (when DeezerSearchItemDelegate::paint will call LazyLoadArt)
art_requests_.clear();
// Update the models
front_model_->SetGroupBy(g, true);
back_model_->SetGroupBy(g, false);
// Save the setting
QSettings s;
s.beginGroup(DeezerSettingsPage::kSettingsGroup);
s.setValue("group_by1", int(g.first));
s.setValue("group_by2", int(g.second));
s.setValue("group_by3", int(g.third));
s.endGroup();
// Make sure the correct action is checked.
for (QAction *action : group_by_actions_->actions()) {
if (action->property("group_by").isNull()) continue;
if (g == action->property("group_by").value<CollectionModel::Grouping>()) {
action->setChecked(true);
return;
}
}
// Check the advanced action
group_by_actions_->actions().last()->setChecked(true);
}
void DeezerSearchView::SearchBySongsClicked(bool checked) {
SetSearchBy(DeezerSettingsPage::SearchBy_Songs);
}
void DeezerSearchView::SearchByAlbumsClicked(bool checked) {
SetSearchBy(DeezerSettingsPage::SearchBy_Albums);
}
void DeezerSearchView::SetSearchBy(DeezerSettingsPage::SearchBy searchby) {
searchby_ = searchby;
QSettings s;
s.beginGroup(DeezerSettingsPage::kSettingsGroup);
s.setValue("searchby", int(searchby));
s.endGroup();
TextEdited(ui_->search->text());
}
void DeezerSearchView::UpdateStatus(QString text) {
ui_->progressbar->show();
ui_->label_status->setText(text);
}
void DeezerSearchView::ProgressSetMaximum(int max) {
ui_->progressbar->setMaximum(max);
}
void DeezerSearchView::UpdateProgress(int progress) {
ui_->progressbar->setValue(progress);
}

View File

@@ -0,0 +1,142 @@
/*
* Strawberry Music Player
* This code was part of Clementine (GlobalSearch)
* Copyright 2012, David Sansome <me@davidsansome.com>
* 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 DEEZERSEARCHVIEW_H
#define DEEZERSEARCHVIEW_H
#include "config.h"
#include <QWidget>
#include <QObject>
#include <QTimer>
#include <QMap>
#include <QList>
#include <QString>
#include <QIcon>
#include <QPixmap>
#include <QMimeData>
#include <QMenu>
#include <QSortFilterProxyModel>
#include <QAction>
#include <QActionGroup>
#include <QtEvents>
#include "collection/collectionmodel.h"
#include "settings/settingsdialog.h"
#include "playlist/playlistmanager.h"
#include "deezersearch.h"
#include "settings/deezersettingspage.h"
class Application;
class GroupByDialog;
class DeezerSearchModel;
class Ui_DeezerSearchView;
class DeezerSearchView : public QWidget {
Q_OBJECT
public:
DeezerSearchView(Application *app, QWidget *parent = nullptr);
~DeezerSearchView();
static const int kSwapModelsTimeoutMsec;
void LazyLoadArt(const QModelIndex &index);
void showEvent(QShowEvent *e);
void hideEvent(QHideEvent *e);
bool eventFilter(QObject *object, QEvent *event);
public slots:
void ReloadSettings();
void StartSearch(const QString &query);
void FocusSearchField();
void OpenSettingsDialog();
signals:
void AddToPlaylist(QMimeData *data);
private slots:
void SwapModels();
void TextEdited(const QString &text);
void UpdateStatus(QString text);
void ProgressSetMaximum(int progress);
void UpdateProgress(int max);
void AddResults(int id, const DeezerSearch::ResultList &results);
void SearchError(const int id, const QString error);
void ArtLoaded(int id, const QPixmap &pixmap);
void FocusOnFilter(QKeyEvent *event);
void AddSelectedToPlaylist();
void LoadSelected();
void OpenSelectedInNewPlaylist();
void AddSelectedToPlaylistEnqueue();
void SearchForThis();
void SearchBySongsClicked(bool);
void SearchByAlbumsClicked(bool);
void GroupByClicked(QAction *action);
void SetSearchBy(DeezerSettingsPage::SearchBy searchby);
void SetGroupBy(const CollectionModel::Grouping &g);
private:
MimeData *SelectedMimeData();
bool SearchKeyEvent(QKeyEvent *event);
bool ResultsContextMenuEvent(QContextMenuEvent *event);
Application *app_;
DeezerSearch *engine_;
Ui_DeezerSearchView *ui_;
QScopedPointer<GroupByDialog> group_by_dialog_;
QMenu *context_menu_;
QList<QAction*> context_actions_;
QActionGroup *group_by_actions_;
int last_search_id_;
// Like graphics APIs have a front buffer and a back buffer, there's a front model and a back model
// The front model is the one that's shown in the UI and the back model is the one that lies in wait.
// current_model_ will point to either the front or the back model.
DeezerSearchModel *front_model_;
DeezerSearchModel *back_model_;
DeezerSearchModel *current_model_;
QSortFilterProxyModel *front_proxy_;
QSortFilterProxyModel *back_proxy_;
QSortFilterProxyModel *current_proxy_;
QMap<int, QModelIndex> art_requests_;
QTimer *swap_models_timer_;
QIcon search_icon_;
QIcon warning_icon_;
DeezerSettingsPage::SearchBy searchby_;
bool error_;
};
#endif // DEEZERSEARCHVIEW_H

View File

@@ -0,0 +1,283 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>DeezerSearchView</class>
<widget class="QWidget" name="DeezerSearchView">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>660</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QWidget" name="widget_search" native="true">
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="spacing">
<number>0</number>
</property>
<item>
<layout class="QVBoxLayout" name="layout_top" stretch="0,0,0">
<item>
<layout class="QHBoxLayout" name="layout_search">
<item>
<widget class="QSearchField" name="search" native="true">
<property name="placeholderText" stdset="0">
<string>Search for anything</string>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="settings">
<property name="minimumSize">
<size>
<width>20</width>
<height>0</height>
</size>
</property>
<property name="popupMode">
<enum>QToolButton::InstantPopup</enum>
</property>
<property name="autoRaise">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout_searchby">
<property name="sizeConstraint">
<enum>QLayout::SetFixedSize</enum>
</property>
<item>
<widget class="QLabel" name="label_searchby">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string>Search by</string>
</property>
<property name="margin">
<number>10</number>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radiobutton_searchbyalbums">
<property name="text">
<string>a&amp;lbums</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radiobutton_searchbysongs">
<property name="text">
<string>son&amp;gs</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="layout_progress">
<item>
<widget class="QLabel" name="label_status">
<property name="text">
<string/>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QProgressBar" name="progressbar">
<property name="value">
<number>0</number>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QStackedWidget" name="results_stack">
<property name="currentIndex">
<number>1</number>
</property>
<widget class="QWidget" name="results_page">
<layout class="QVBoxLayout" name="verticalLayout_3">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="AutoExpandingTreeView" name="results">
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
<property name="dragEnabled">
<bool>true</bool>
</property>
<property name="dragDropMode">
<enum>QAbstractItemView::DragOnly</enum>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::ExtendedSelection</enum>
</property>
<property name="allColumnsShowFocus">
<bool>true</bool>
</property>
<attribute name="headerVisible">
<bool>false</bool>
</attribute>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="help_page">
<layout class="QVBoxLayout" name="verticalLayout_6">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QScrollArea" name="help_frame">
<property name="horizontalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="widgetResizable">
<bool>true</bool>
</property>
<widget class="QWidget" name="help_frame_contents">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>398</width>
<height>502</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout_5">
<item>
<widget class="QWidget" name="widget" native="true">
<layout class="QVBoxLayout" name="verticalLayout_4">
<property name="leftMargin">
<number>32</number>
</property>
<property name="topMargin">
<number>16</number>
</property>
<property name="rightMargin">
<number>32</number>
</property>
<property name="bottomMargin">
<number>64</number>
</property>
<item>
<widget class="QLabel" name="label_helptext">
<property name="text">
<string>Enter search terms above to find music</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<spacer name="spacer_helptext">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>QSearchField</class>
<extends>QWidget</extends>
<header>3rdparty/qocoa/qsearchfield.h</header>
</customwidget>
<customwidget>
<class>AutoExpandingTreeView</class>
<extends>QTreeView</extends>
<header>widgets/autoexpandingtreeview.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>

View File

@@ -0,0 +1,823 @@
/*
* 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"
#ifdef HAVE_DZMEDIA
# include <dzmedia.h>
#endif
#include <QObject>
#include <QByteArray>
#include <QList>
#include <QVector>
#include <QPair>
#include <QString>
#include <QUrl>
#include <QUrlQuery>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QTimer>
#include <QJsonParseError>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QMenu>
#include <QDesktopServices>
#include <QSettings>
#include "core/application.h"
#include "core/player.h"
#include "core/closure.h"
#include "core/logging.h"
#include "core/mergedproxymodel.h"
#include "core/network.h"
#include "core/song.h"
#include "core/iconloader.h"
#include "core/taskmanager.h"
#include "core/timeconstants.h"
#include "core/utilities.h"
#include "internet/internetmodel.h"
#include "internet/localredirectserver.h"
#include "deezerservice.h"
#include "deezersearch.h"
#include "deezerurlhandler.h"
#include "settings/deezersettingspage.h"
const Song::Source DeezerService::kSource = Song::Source_Deezer;
const char *DeezerService::kApiUrl = "https://api.deezer.com";
const char *DeezerService::kOAuthUrl = "https://connect.deezer.com/oauth/auth.php";
const char *DeezerService::kOAuthAccessTokenUrl = "https://connect.deezer.com/oauth/access_token.php";
const char *DeezerService::kOAuthRedirectUrl = "https://oauth.strawbs.net";
const int DeezerService::kAppID = 303684;
const char *DeezerService::kSecretKey = "06911976010b9ddd7256769adf2b2e56";
typedef QPair<QString, QString> Param;
DeezerService::DeezerService(Application *app, InternetModel *parent)
: InternetService(Song::Source_Deezer, "Deezer", "dzmedia", app, parent, parent),
network_(new NetworkAccessManager(this)),
url_handler_(new DeezerUrlHandler(app, this)),
#ifdef HAVE_DZMEDIA
dzmedia_(new DZMedia(this)),
#endif
timer_searchdelay_(new QTimer(this)),
searchdelay_(1500),
albumssearchlimit_(1),
songssearchlimit_(1),
fetchalbums_(false),
preview_(false),
pending_search_id_(0),
next_pending_search_id_(1),
search_id_(0),
albums_requested_(0),
albums_received_(0)
{
timer_searchdelay_->setSingleShot(true);
connect(timer_searchdelay_, SIGNAL(timeout()), SLOT(StartSearch()));
connect(this, SIGNAL(Authenticated()), app->player(), SLOT(HandleAuthentication()));
app->player()->RegisterUrlHandler(url_handler_);
ReloadSettings();
LoadAccessToken();
#ifdef HAVE_DZMEDIA
connect(dzmedia_, SIGNAL(StreamURLReceived(QUrl, QUrl, DZMedia::FileType)), this, SLOT(GetStreamURLFinished(QUrl, QUrl, DZMedia::FileType)));
#endif
}
DeezerService::~DeezerService() {}
void DeezerService::ShowConfig() {
app_->OpenSettingsDialogAtPage(SettingsDialog::Page_Deezer);
}
void DeezerService::ReloadSettings() {
QSettings s;
s.beginGroup(DeezerSettingsPage::kSettingsGroup);
quality_ = s.value("quality", "FLAC").toString();
searchdelay_ = s.value("searchdelay", 1500).toInt();
albumssearchlimit_ = s.value("albumssearchlimit", 100).toInt();
songssearchlimit_ = s.value("songssearchlimit", 100).toInt();
fetchalbums_ = s.value("fetchalbums", false).toBool();
coversize_ = s.value("coversize", "cover_big").toString();
preview_ = s.value("preview", false).toBool();
s.endGroup();
}
void DeezerService::LoadAccessToken() {
QSettings s;
s.beginGroup(DeezerSettingsPage::kSettingsGroup);
if (s.contains("access_token") && s.contains("expiry_time")) {
access_token_ = s.value("access_token").toString();
expiry_time_ = s.value("expiry_time").toDateTime();
}
s.endGroup();
}
void DeezerService::Logout() {
}
void DeezerService::StartAuthorisation() {
LocalRedirectServer *server = new LocalRedirectServer(this);
server->Listen();
QUrl url = QUrl(kOAuthUrl);
QUrlQuery url_query;
//url_query.addQueryItem("response_type", "token");
url_query.addQueryItem("response_type", "code");
url_query.addQueryItem("app_id", QString::number(kAppID));
QUrl redirect_url;
QUrlQuery redirect_url_query;
const QString port = QString::number(server->url().port());
redirect_url = QUrl(kOAuthRedirectUrl);
redirect_url_query.addQueryItem("port", port);
redirect_url.setQuery(redirect_url_query);
url_query.addQueryItem("redirect_uri", redirect_url.toString());
url.setQuery(url_query);
NewClosure(server, SIGNAL(Finished()), this, &DeezerService::RedirectArrived, server, redirect_url);
QDesktopServices::openUrl(url);
}
void DeezerService::RedirectArrived(LocalRedirectServer *server, QUrl url) {
server->deleteLater();
QUrl request_url = server->request_url();
RequestAccessToken(QUrlQuery(request_url).queryItemValue("code").toUtf8());
}
void DeezerService::RequestAccessToken(const QByteArray &code) {
typedef QPair<QString, QString> Arg;
typedef QList<Arg> ArgList;
typedef QPair<QByteArray, QByteArray> EncodedArg;
typedef QList<EncodedArg> EncodedArgList;
ArgList args = ArgList() << Arg("app_id", QString::number(kAppID))
<< Arg("secret", kSecretKey)
<< Arg("code", code);
QUrlQuery url_query;
for (const Arg &arg : args) {
EncodedArg encoded_arg(QUrl::toPercentEncoding(arg.first), QUrl::toPercentEncoding(arg.second));
url_query.addQueryItem(encoded_arg.first, encoded_arg.second);
}
QUrl url(kOAuthAccessTokenUrl);
QNetworkRequest request = QNetworkRequest(url);
QNetworkReply *reply = network_->post(request, url_query.toString(QUrl::FullyEncoded).toUtf8());
NewClosure(reply, SIGNAL(finished()), this, SLOT(FetchAccessTokenFinished(QNetworkReply*)), reply);
}
void DeezerService::FetchAccessTokenFinished(QNetworkReply *reply) {
reply->deleteLater();
if (reply->error() != QNetworkReply::NoError) {
Error(QString("%1 (%2)").arg(reply->errorString()).arg(reply->error()));
return;
}
forever {
QByteArray line = reply->readLine();
QString str(line);
QStringList args = str.split("&");
for (QString arg : args) {
QStringList params = arg.split("=");
if (params.count() < 2) continue;
QString param1 = params.first();
QString param2 = params[1];
if (param1 == "access_token") access_token_ = param2;
else if (param1 == "expires") SetExpiryTime(param2.toInt());
}
if (reply->atEnd()) break;
}
QSettings s;
s.beginGroup(DeezerSettingsPage::kSettingsGroup);
s.setValue("access_token", access_token_);
s.setValue("expiry_time", expiry_time_);
s.endGroup();
emit Authenticated();
emit LoginSuccess();
}
void DeezerService::SetExpiryTime(int expires_in_seconds) {
// Set the expiry time with two minutes' grace.
expiry_time_ = QDateTime::currentDateTime().addSecs(expires_in_seconds - 120);
qLog(Debug) << "Current oauth access token expires at:" << expiry_time_;
}
QNetworkReply *DeezerService::CreateRequest(const QString &ressource_name, const QList<Param> &params) {
typedef QPair<QString, QString> Arg;
typedef QList<Arg> ArgList;
typedef QPair<QByteArray, QByteArray> EncodedArg;
typedef QList<EncodedArg> EncodedArgList;
ArgList args = ArgList() << Arg("access_token", access_token_)
<< Arg("output", "json")
<< params;
QUrlQuery url_query;
for (const Arg& arg : args) {
EncodedArg encoded_arg(QUrl::toPercentEncoding(arg.first), QUrl::toPercentEncoding(arg.second));
url_query.addQueryItem(encoded_arg.first, encoded_arg.second);
}
QUrl url(kApiUrl + QString("/") + ressource_name);
url.setQuery(url_query);
QNetworkRequest req(url);
QNetworkReply *reply = network_->get(req);
//qLog(Debug) << "Deezer: Sending request" << url;
return reply;
}
QByteArray DeezerService::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 failure_reason = QString("%1 (%2)").arg(reply->errorString()).arg(reply->error());
Error(failure_reason);
}
else {
// See if there is Json data containing "error" - 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")) {
QJsonValue json_value_error = json_obj["error"];
if (json_value_error.isObject()) {
QJsonObject json_error = json_value_error.toObject();
int code = json_error["code"].toInt();
if (code == 300) access_token_.clear();
QString message = json_error["message"].toString();
QString type = json_error["type"].toString();
failure_reason = QString("%1 (%2)").arg(message).arg(code);
}
else { failure_reason = QString("%1 (%2)").arg(reply->errorString()).arg(reply->error()); }
}
else {
failure_reason = QString("%1 (%2)").arg(reply->errorString()).arg(reply->error());
}
}
else {
failure_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(failure_reason);
}
else if (reply->error() == QNetworkReply::ContentNotFoundError) { // Ignore this error
Error(failure_reason);
}
else { // Fail
Error(failure_reason);
}
}
return QByteArray();
}
return data;
}
QJsonObject DeezerService::ExtractJsonObj(QByteArray &data) {
QJsonParseError error;
QJsonDocument json_doc = QJsonDocument::fromJson(data, &error);
//qLog(Debug) << json_doc;
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();
}
//qLog(Debug) << json_obj;
return json_obj;
}
QJsonValue DeezerService::ExtractData(QByteArray &data) {
QJsonObject json_obj = ExtractJsonObj(data);
if (json_obj.isEmpty()) return QJsonObject();
if (json_obj.contains("error")) {
QJsonValue json_value_error = json_obj["error"];
if (!json_value_error.isObject()) {
Error("Error missing object", json_obj);
return QJsonValue();
}
QJsonObject json_error = json_value_error.toObject();
int code = json_error["code"].toInt();
if (code == 300) access_token_.clear();
QString message = json_error["message"].toString();
QString type = json_error["type"].toString();
Error(QString("%1 (%2)").arg(message).arg(code));
return QJsonValue();
}
if (!json_obj.contains("data") && !json_obj.contains("DATA")) {
Error("Json reply is missing data.", json_obj);
return QJsonValue();
}
QJsonValue json_data;
if (json_obj.contains("data")) json_data = json_obj["data"];
else json_data = json_obj["DATA"];
return json_data;
}
int DeezerService::Search(const QString &text, DeezerSettingsPage::SearchBy searchby) {
pending_search_id_ = next_pending_search_id_;
pending_search_text_ = text;
pending_searchby_ = searchby;
next_pending_search_id_++;
if (text.isEmpty()) {
timer_searchdelay_->stop();
return pending_search_id_;
}
timer_searchdelay_->setInterval(searchdelay_);
timer_searchdelay_->start();
return pending_search_id_;
}
void DeezerService::StartSearch() {
if (access_token_.isEmpty()) {
emit SearchError(pending_search_id_, "Not authenticated.");
next_pending_search_id_ = 1;
ShowConfig();
return;
}
ClearSearch();
search_id_ = pending_search_id_;
search_text_ = pending_search_text_;
SendSearch();
}
void DeezerService::CancelSearch() {
ClearSearch();
}
void DeezerService::ClearSearch() {
search_id_ = 0;
search_text_.clear();
search_error_.clear();
albums_requested_ = 0;
albums_received_ = 0;
requests_album_.clear();
requests_song_.clear();
songs_.clear();
}
void DeezerService::SendSearch() {
emit UpdateStatus("Searching...");
QList<Param> parameters;
parameters << Param("q", search_text_);
QString searchparam;
switch (pending_searchby_) {
case DeezerSettingsPage::SearchBy_Songs:
searchparam = "search/track";
parameters << Param("limit", QString::number(songssearchlimit_));
break;
case DeezerSettingsPage::SearchBy_Albums:
default:
searchparam = "search/album";
parameters << Param("limit", QString::number(albumssearchlimit_));
break;
}
QNetworkReply *reply = CreateRequest(searchparam, parameters);
NewClosure(reply, SIGNAL(finished()), this, SLOT(SearchFinished(QNetworkReply*, int)), reply, search_id_);
}
void DeezerService::SearchFinished(QNetworkReply *reply, int id) {
reply->deleteLater();
if (id != search_id_) return;
QByteArray data = GetReplyData(reply);
if (data.isEmpty()) {
CheckFinish();
return;
}
QJsonValue json_value = ExtractData(data);
if (!json_value.isArray()) {
CheckFinish();
return;
}
QJsonArray json_data = json_value.toArray();
if (json_data.isEmpty()) {
Error("No match.");
CheckFinish();
return;
}
//qLog(Debug) << json_data;
for (const QJsonValue &value : json_data) {
//qLog(Debug) << value;
if (!value.isObject()) {
Error("Invalid Json reply, data is not an object.", value);
continue;
}
QJsonObject json_obj = value.toObject();
//qLog(Debug) << json_obj;
if (!json_obj.contains("id") || !json_obj.contains("type")) {
Error("Invalid Json reply, item is missing ID or type.", json_obj);
continue;
}
//int id = json_obj["id"].toInt();
QString type = json_obj["type"].toString();
if (!json_obj.contains("artist")) {
Error("Invalid Json reply, item missing artist.", json_obj);
continue;
}
QJsonValue json_value_artist = json_obj["artist"];
if (!json_value_artist.isObject()) {
Error("Invalid Json reply, item artist is not a object.", json_value_artist);
continue;
}
QJsonObject json_artist = json_value_artist.toObject();
if (!json_artist.contains("name")) {
Error("Invalid Json reply, artist data missing name.", json_artist);
continue;
}
QString artist = json_artist["name"].toString();
int album_id(0);
QString album;
QString cover;
if (type == "album") {
album_id = json_obj["id"].toInt();
album = json_obj["title"].toString();
cover = json_obj[coversize_].toString();
}
else if (type == "track") {
if (!json_obj.contains("album")) {
Error("Invalid Json reply, missing album data.", json_obj);
continue;
}
QJsonValue json_value_album = json_obj["album"];
if (!json_value_album.isObject()) {
Error("Invalid Json reply, album data is not an object.", json_value_album);
continue;
}
QJsonObject json_album = json_value_album.toObject();
if (!json_album.contains("id") || !json_album.contains("title")) {
Error("Invalid Json reply, album data is missing ID or title.", json_album);
continue;
}
album_id = json_album["id"].toInt();
album = json_album["title"].toString();
cover = json_album[coversize_].toString();
if (!fetchalbums_) {
Song song = ParseSong(album_id, album, cover, value);
songs_ << song;
continue;
}
}
DeezerAlbumContext *album_ctx;
if (requests_album_.contains(album_id)) {
album_ctx = requests_album_.value(album_id);
album_ctx->search_id = search_id_;
continue;
}
album_ctx = CreateAlbum(album_id, artist, album, cover);
GetAlbum(album_ctx);
albums_requested_++;
if (albums_requested_ >= albumssearchlimit_) break;
}
if (albums_requested_ > 0) {
emit UpdateStatus(QString("Retriving %1 album%2...").arg(albums_requested_).arg(albums_requested_ == 1 ? "" : "s"));
emit ProgressSetMaximum(albums_requested_);
emit UpdateProgress(0);
}
CheckFinish();
}
DeezerAlbumContext *DeezerService::CreateAlbum(const int album_id, const QString &artist, const QString &album, const QString &cover) {
DeezerAlbumContext *album_ctx = new DeezerAlbumContext;
album_ctx->id = album_id;
album_ctx->artist = artist;
album_ctx->album = album;
album_ctx->cover = cover;
album_ctx->cover_url.setUrl(cover);
requests_album_.insert(album_id, album_ctx);
return album_ctx;
}
void DeezerService::GetAlbum(const DeezerAlbumContext *album_ctx) {
QList<Param> parameters;
QNetworkReply *reply = CreateRequest(QString("album/%1/tracks").arg(album_ctx->id), parameters);
NewClosure(reply, SIGNAL(finished()), this, SLOT(GetAlbumFinished(QNetworkReply*, int, int)), reply, search_id_, album_ctx->id);
}
void DeezerService::GetAlbumFinished(QNetworkReply *reply, int search_id, int album_id) {
reply->deleteLater();
if (!requests_album_.contains(album_id)) {
qLog(Error) << "Deezer: Got reply for cancelled album request: " << album_id;
CheckFinish();
return;
}
DeezerAlbumContext *album_ctx = requests_album_.value(album_id);
if (search_id != search_id_) {
if (album_ctx->search_id == search_id) delete requests_album_.take(album_ctx->id);
return;
}
albums_received_++;
emit UpdateProgress(albums_received_);
QByteArray data = GetReplyData(reply);
if (data.isEmpty()) {
CheckFinish();
return;
}
QJsonValue json_value = ExtractData(data);
if (!json_value.isArray()) {
delete requests_album_.take(album_ctx->id);
CheckFinish();
return;
}
QJsonArray json_data = json_value.toArray();
if (json_data.isEmpty()) {
delete requests_album_.take(album_ctx->id);
CheckFinish();
return;
}
bool compilation = false;
bool multidisc = false;
Song first_song;
SongList songs;
for (const QJsonValue &value : json_data) {
Song song = ParseSong(album_ctx->id, album_ctx->album, album_ctx->cover, value);
if (!song.is_valid()) continue;
if (song.disc() >= 2) multidisc = true;
if (song.is_compilation() || (first_song.is_valid() && song.artist() != first_song.artist())) compilation = true;
if (!first_song.is_valid()) first_song = song;
songs << song;
}
for (Song &song : songs) {
if (compilation) song.set_compilation_detected(true);
if (multidisc) {
QString album_full(QString("%1 - (Disc %2)").arg(song.album()).arg(song.disc()));
song.set_album(album_full);
}
songs_ << song;
}
delete requests_album_.take(album_ctx->id);
CheckFinish();
}
Song DeezerService::ParseSong(const int album_id, const QString &album, const QString &album_cover, const QJsonValue &value) {
if (!value.isObject()) {
Error("Invalid Json reply, track is not an object.", value);
return Song();
}
QJsonObject json_obj = value.toObject();
//qLog(Debug) << json_obj;
if (
!json_obj.contains("id") ||
!json_obj.contains("title") ||
!json_obj.contains("artist") ||
!json_obj.contains("duration") ||
!json_obj.contains("preview")
) {
Error("Invalid Json reply, track is missing one or more values.", json_obj);
return Song();
}
int song_id = json_obj["id"].toInt();
QString title = json_obj["title"].toString();
QJsonValue json_value_artist = json_obj["artist"];
QVariant q_duration = json_obj["duration"].toVariant();
int track(0);
if (json_obj.contains("track_position")) track = json_obj["track_position"].toInt();
int disc(0);
if (json_obj.contains("disk_number")) disc = json_obj["disk_number"].toInt();
QString preview = json_obj["preview"].toString();
if (!json_value_artist.isObject()) {
Error("Invalid Json reply, track artist is not an object.", json_value_artist);
return Song();
}
QJsonObject json_artist = json_value_artist.toObject();
if (!json_artist.contains("name")) {
Error("Invalid Json reply, track artist is missing name.", json_artist);
return Song();
}
QString artist = json_artist["name"].toString();
Song song;
song.set_source(Song::Source_Deezer);
song.set_id(song_id);
song.set_album_id(album_id);
song.set_artist(artist);
song.set_album(album);
song.set_title(title);
song.set_disc(disc);
song.set_track(track);
song.set_art_automatic(album_cover);
QUrl url;
if (preview_) {
url.setUrl(preview);
quint64 duration = (30 * kNsecPerSec);
song.set_length_nanosec(duration);
}
else {
url.setScheme(url_handler_->scheme());
url.setPath(QString("track/%1").arg(QString::number(song_id)));
if (q_duration.isValid()) {
quint64 duration = q_duration.toULongLong() * kNsecPerSec;
song.set_length_nanosec(duration);
}
}
song.set_url(url);
song.set_valid(true);
return song;
}
void DeezerService::GetStreamURL(const QUrl &original_url) {
#ifdef HAVE_DZMEDIA
stream_request_url_ = original_url;
dzmedia_->GetStreamURL(original_url);
#else
stream_request_url_ = QUrl();
emit StreamURLReceived(original_url, original_url, Song::FileType_Stream);
#endif
}
#ifdef HAVE_DZMEDIA
void DeezerService::GetStreamURLFinished(const QUrl original_url, const QUrl media_url, const DZMedia::FileType dzmedia_filetype) {
Song::FileType filetype(Song::FileType_Unknown);
switch (dzmedia_filetype) {
case DZMedia::FileType_FLAC:
filetype = Song::FileType_FLAC;
break;
case DZMedia::FileType_MPEG:
filetype = Song::FileType_MPEG;
break;
case DZMedia::FileType_Stream:
filetype = Song::FileType_Stream;
break;
default:
filetype = Song::FileType_Unknown;
break;
}
stream_request_url_ = QUrl();
emit StreamURLReceived(original_url, media_url, filetype);
}
#endif
void DeezerService::CheckFinish() {
if (search_id_ == 0) return;
if (albums_requested_ <= albums_received_) {
if (songs_.isEmpty()) {
if (search_error_.isEmpty()) emit SearchError(search_id_, "Unknown error");
else emit SearchError(search_id_, search_error_);
}
else emit SearchResults(search_id_, songs_);
ClearSearch();
}
}
void DeezerService::Error(QString error, QVariant debug) {
qLog(Error) << "Deezer:" << error;
if (!debug.isValid()) qLog(Debug) << debug;
if (search_id_ != 0) {
if (!error.isEmpty()) {
search_error_ += error;
search_error_ += "<br />";
}
CheckFinish();
}
if (!stream_request_url_.isEmpty()) {
emit StreamURLReceived(stream_request_url_, stream_request_url_, Song::FileType_Stream);
stream_request_url_ = QUrl();
}
}

163
src/deezer/deezerservice.h Normal file
View File

@@ -0,0 +1,163 @@
/*
* 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 DEEZERSERVICE_H
#define DEEZERSERVICE_H
#include "config.h"
#ifdef HAVE_DZMEDIA
# include <dzmedia.h>
#endif
#include <QtGlobal>
#include <QObject>
#include <QHash>
#include <QString>
#include <QUrl>
#include <QNetworkReply>
#include <QTimer>
#include <QDateTime>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include "core/song.h"
#include "internet/internetmodel.h"
#include "internet/internetservice.h"
#include "settings/deezersettingspage.h"
class NetworkAccessManager;
class LocalRedirectServer;
class DeezerUrlHandler;
struct DeezerAlbumContext {
int id;
int search_id;
QString artist;
QString album;
QString cover;
QUrl cover_url;
};
Q_DECLARE_METATYPE(DeezerAlbumContext);
class DeezerService : public InternetService {
Q_OBJECT
public:
DeezerService(Application *app, InternetModel *parent);
~DeezerService();
static const Song::Source kSource;
static const int kAppID;
void ReloadSettings();
void Logout();
int Search(const QString &query, DeezerSettingsPage::SearchBy searchby);
void CancelSearch();
const bool app_id() { return kAppID; }
const bool authenticated() { return !access_token_.isEmpty(); }
void GetStreamURL(const QUrl &url);
signals:
void Login();
void LoginSuccess();
void LoginFailure(QString failure_reason);
void Authenticated();
void SearchResults(int id, SongList songs);
void SearchError(int id, QString message);
void UpdateStatus(QString text);
void ProgressSetMaximum(int max);
void UpdateProgress(int max);
void StreamURLReceived(const QUrl original_url, const QUrl media_url, const Song::FileType filetype);
public slots:
void ShowConfig();
private slots:
void StartAuthorisation();
void FetchAccessTokenFinished(QNetworkReply *reply);
void StartSearch();
void SearchFinished(QNetworkReply *reply, int search_id);
void GetAlbumFinished(QNetworkReply *reply, int search_id, int album_id);
#ifdef HAVE_DZMEDIA
void GetStreamURLFinished(const QUrl original_url, const QUrl media_url, const DZMedia::FileType dzmedia_filetype);
#endif
private:
void LoadAccessToken();
void RedirectArrived(LocalRedirectServer *server, QUrl url);
void RequestAccessToken(const QByteArray &code);
void SetExpiryTime(int expires_in_seconds);
void ClearSearch();
QNetworkReply *CreateRequest(const QString &ressource_name, const QList<QPair<QString, QString>> &params);
QByteArray GetReplyData(QNetworkReply *reply);
QJsonObject ExtractJsonObj(QByteArray &data);
QJsonValue ExtractData(QByteArray &data);
void SendSearch();
DeezerAlbumContext *CreateAlbum(const int album_id, const QString &artist, const QString &album, const QString &cover);
void GetAlbum(const DeezerAlbumContext *album_ctx);
Song ParseSong(const int album_id, const QString &album, const QString &album_cover, const QJsonValue &value);
void CheckFinish();
void Error(QString error, QVariant debug = QString());
static const char *kApiUrl;
static const char *kOAuthUrl;
static const char *kOAuthAccessTokenUrl;
static const char *kOAuthRedirectUrl;
static const char *kSecretKey;
NetworkAccessManager *network_;
DeezerUrlHandler *url_handler_;
#ifdef HAVE_DZMEDIA
DZMedia *dzmedia_;
#endif
QTimer *timer_searchdelay_;
QString quality_;
int searchdelay_;
int albumssearchlimit_;
int songssearchlimit_;
bool fetchalbums_;
QString coversize_;
bool preview_;
QString access_token_;
QDateTime expiry_time_;
int pending_search_id_;
int next_pending_search_id_;
QString pending_search_text_;
DeezerSettingsPage::SearchBy pending_searchby_;
int search_id_;
QString search_text_;
QHash<int, DeezerAlbumContext*> requests_album_;
QHash<int, QUrl> requests_song_;
int albums_requested_;
int albums_received_;
SongList songs_;
QString search_error_;
QUrl stream_request_url_;
};
#endif // DEEZERSERVICE_H

View File

@@ -0,0 +1,65 @@
/*
* 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 <QObject>
#include <QString>
#include <QUrl>
#include "core/application.h"
#include "core/taskmanager.h"
#include "core/iconloader.h"
#include "core/logging.h"
#include "core/song.h"
#include "deezer/deezerservice.h"
#include "deezerurlhandler.h"
DeezerUrlHandler::DeezerUrlHandler(
Application *app, DeezerService *service)
: UrlHandler(service), app_(app), service_(service), task_id_(-1) {
connect(service, SIGNAL(StreamURLReceived(QUrl, QUrl, Song::FileType)), this, SLOT(GetStreamURLFinished(QUrl, QUrl, Song::FileType)));
}
UrlHandler::LoadResult DeezerUrlHandler::StartLoading(const QUrl &url) {
LoadResult ret(url);
if (task_id_ != -1) return ret;
last_original_url_ = url;
task_id_ = app_->task_manager()->StartTask(QString("Loading %1 stream...").arg(url.scheme()));
service_->GetStreamURL(url);
ret.type_ = LoadResult::WillLoadAsynchronously;
return ret;
}
void DeezerUrlHandler::GetStreamURLFinished(QUrl original_url, QUrl media_url, Song::FileType filetype) {
if (task_id_ == -1) return;
CancelTask();
emit AsyncLoadComplete(LoadResult(original_url, LoadResult::TrackAvailable, media_url, filetype));
}
void DeezerUrlHandler::CancelTask() {
app_->task_manager()->SetTaskFinished(task_id_);
task_id_ = -1;
}

View File

@@ -0,0 +1,56 @@
/*
* 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 DEEZERURLHANDLER_H
#define DEEZERURLHANDLER_H
#include <QObject>
#include <QString>
#include <QUrl>
#include "core/urlhandler.h"
#include "core/song.h"
#include "deezer/deezerservice.h"
class Application;
class DeezerService;
class DeezerUrlHandler : public UrlHandler {
Q_OBJECT
public:
DeezerUrlHandler(Application *app, DeezerService *service);
QString scheme() const { return service_->url_scheme(); }
LoadResult StartLoading(const QUrl &url);
void CancelTask();
private slots:
void GetStreamURLFinished(QUrl original_url, QUrl media_url, Song::FileType filetype);
private:
Application *app_;
DeezerService *service_;
int task_id_;
QUrl last_original_url_;
};
#endif