albumsmodel.cpp 8.02 KB
Newer Older
camilo higuita's avatar
camilo higuita committed
1 2
#include "albumsmodel.h"
#include "db/collectionDB.h"
3 4
#include "utils/brain.h"
#include <QtConcurrent>
camilo higuita's avatar
camilo higuita committed
5 6 7 8 9

AlbumsModel::AlbumsModel(QObject *parent) : BaseList(parent)
{
    this->db = CollectionDB::getInstance();
    connect(this, &AlbumsModel::queryChanged, this, &AlbumsModel::setList);
camilo higuita's avatar
camilo higuita committed
10 11
}

12
AlbumsModel::~AlbumsModel() {}
camilo higuita's avatar
camilo higuita committed
13 14 15 16 17 18

FMH::MODEL_LIST AlbumsModel::items() const
{
    return this->list;
}

19
void AlbumsModel::setQuery(const QUERY &query)
camilo higuita's avatar
camilo higuita committed
20 21 22 23 24 25 26 27
{
    if(this->query == query)
        return;

    this->query = query;
    emit this->queryChanged();
}

28
AlbumsModel::QUERY AlbumsModel::getQuery() const
camilo higuita's avatar
camilo higuita committed
29 30 31 32 33 34 35 36 37 38 39
{
    return this->query;
}

void AlbumsModel::setSortBy(const SORTBY &sort)
{
    if(this->sort == sort)
        return;

    this->sort = sort;

40
    emit this->preListChanged();
camilo higuita's avatar
camilo higuita committed
41
    this->sortList();
42
    emit this->postListChanged();
camilo higuita's avatar
camilo higuita committed
43 44 45 46 47 48 49 50 51 52 53 54
    emit this->sortByChanged();
}

AlbumsModel::SORTBY AlbumsModel::getSortBy() const
{
    return this->sort;
}

void AlbumsModel::sortList()
{
    const auto key = static_cast<FMH::MODEL_KEY>(this->sort);
    qDebug()<< "SORTING LIST BY"<< this->sort;
55
    std::sort(this->list.begin(), this->list.end(), [key](const FMH::MODEL &e1, const FMH::MODEL &e2) -> bool
camilo higuita's avatar
camilo higuita committed
56
    {
57
        const auto role = key;
camilo higuita's avatar
camilo higuita committed
58 59 60 61 62 63 64 65 66 67 68
        switch(role)
        {
        case FMH::MODEL_KEY::RELEASEDATE:
        {
            if(e1[role].toDouble() > e2[role].toDouble())
                return true;
            break;
        }

        case FMH::MODEL_KEY::ADDDATE:
        {
69 70
            const auto date1 = QDateTime::fromString(e1[role], Qt::TextDate);
            const auto date2 = QDateTime::fromString(e2[role], Qt::TextDate);
camilo higuita's avatar
camilo higuita committed
71

72
            if(date1.secsTo(QDateTime::currentDateTime()) <  date2.secsTo(QDateTime::currentDateTime()))
camilo higuita's avatar
camilo higuita committed
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
                return true;
            break;
        }

        case FMH::MODEL_KEY::ARTIST:
        case FMH::MODEL_KEY::ALBUM:
        {
            const auto str1 = QString(e1[role]).toLower();
            const auto str2 = QString(e2[role]).toLower();

            if(str1 < str2)
                return true;
            break;
        }

        default:
            if(e1[role] < e2[role])
                return true;
        }

        return false;
    });
}

void AlbumsModel::setList()
{
    emit this->preListChanged();

101 102 103 104 105 106
    QString m_Query;
    if(this->query == AlbumsModel::QUERY::ALBUMS)
        m_Query = "select * from albums order by album asc";
    else if(this->query == AlbumsModel::QUERY::ARTISTS)
        m_Query = "select * from artists order by artist asc";

camilo higuita's avatar
camilo higuita committed
107
    //get albums data with modifier for missing images for artworks
camilo higuita's avatar
camilo higuita committed
108
    this->list = this->db->getDBData(m_Query, [&](FMH::MODEL &item)
109
    {
110 111 112 113 114 115 116 117
            if(!item[FMH::MODEL_KEY::ARTWORK].isEmpty() && !FMH::fileExists(item[FMH::MODEL_KEY::ARTWORK]))
    {
        this->db->removeArtwork(FMH::MODEL_NAME[static_cast<FMH::MODEL_KEY>(this->query)], FM::toMap(item));
        item[FMH::MODEL_KEY::ARTWORK] = "";
    }
});
this->sortList();
emit this->postListChanged();
118 119
}

camilo higuita's avatar
fixes  
camilo higuita committed
120
void AlbumsModel::fetchInformation()
121
{
camilo higuita's avatar
fixes  
camilo higuita committed
122
    qDebug() << "RNUNGING BRAIN EFFORRTS";
123
    QFutureWatcher<void> *watcher = new QFutureWatcher<void>;
camilo higuita's avatar
camilo higuita committed
124 125
    QObject::connect(watcher, &QFutureWatcher<void>::finished,
                     watcher, &QFutureWatcher<void>::deleteLater);
126

127 128 129
    //    QObject::connect(this, &AlbumsModel::destroyed, watcher, &QFutureWatcher<void>::waitForFinished);

    auto func = [&, stop = bool()]() mutable
130
    {
131
        stop = false;
132 133
        QList<PULPO::REQUEST> requests;
        int index = -1;
camilo higuita's avatar
camilo higuita committed
134
        for(auto album : this->list)
135 136 137 138 139 140 141
        {
            index++;
            if(!album[FMH::MODEL_KEY::ARTWORK].isEmpty())
                continue;

            if(BAE::artworkCache(album, FMH::MODEL_KEY::ALBUM))
            {
142
                this->db->insertArtwork(album);
143
                emit this->updateModel(index, {FMH::MODEL_KEY::ARTWORK});
144 145 146 147 148
                continue;
            }

            PULPO::REQUEST request;
            request.track = album;
camilo higuita's avatar
fixes  
camilo higuita committed
149
            request.ontology = this->query == AlbumsModel::QUERY::ALBUMS ? PULPO::ONTOLOGY::ALBUM : PULPO::ONTOLOGY::ARTIST;
150 151
            request.services = {PULPO::SERVICES::LastFm, PULPO::SERVICES::Spotify, PULPO::SERVICES::MusicBrainz};
            request.info = {PULPO::INFO::ARTWORK};
camilo higuita's avatar
camilo higuita committed
152
            request.callback = [&, index](PULPO::REQUEST request, PULPO::RESPONSES responses)
153 154 155 156 157 158 159 160 161
            {
                qDebug() << "DONE WITH " << request.track ;

                for(const auto &res : responses)
                {
                    if(res.context == PULPO::CONTEXT::IMAGE && !res.value.toString().isEmpty())
                    {
                        qDebug()<<"SAVING ARTWORK FOR: " << request.track[FMH::MODEL_KEY::ALBUM];
                        auto downloader = new FMH::Downloader;
camilo higuita's avatar
camilo higuita committed
162
                        QObject::connect(downloader, &FMH::Downloader::fileSaved, [&, index, request, downloader = std::move(downloader)](QString path)
163 164 165 166
                        {
                            qDebug()<< "Saving artwork file to" << path;
                            FMH::MODEL newTrack = request.track;
                            newTrack[FMH::MODEL_KEY::ARTWORK] = path;
camilo higuita's avatar
camilo higuita committed
167
                            this->db->insertArtwork(newTrack);
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
                            this->updateArtwork(index, path);
                            downloader->deleteLater();
                        });

                        QStringList filePathList = res.value.toString().split('/');
                        const auto format = "." + filePathList.at(filePathList.count() - 1).split(".").last();
                        QString name = !request.track[FMH::MODEL_KEY::ALBUM].isEmpty() ? request.track[FMH::MODEL_KEY::ARTIST] + "_" + request.track[FMH::MODEL_KEY::ALBUM] : request.track[FMH::MODEL_KEY::ARTIST];
                        name.replace("/", "-");
                        name.replace("&", "-");
                        downloader->setFile(res.value.toString(),  BAE::CachePath + name + format);
                    }
                }
            };

            requests << request;
        }

        Pulpo pulpo;
        QEventLoop loop;
        QObject::connect(&pulpo, &Pulpo::finished, &loop, &QEventLoop::quit);
188

189 190 191 192 193
        QObject::connect(this, &AlbumsModel::destroyed, [&stop]()
        {
            qDebug()<< stop << &stop;
            stop = true;
            qDebug()<< stop << &stop;
194

195
        });
196

197
        for(const auto &req : requests)
198
        {
camilo higuita's avatar
camilo higuita committed
199
            pulpo.request(req);
200 201
            if(stop)
            {
202 203 204 205 206 207 208 209 210 211
                qDebug()<< "TRYING EXITING THREAD LOADINFO" << loop.isRunning();

                if(loop.isRunning())
                    loop.quit();

                qDebug()<< "EXITING THREAD LOADINFO" << loop.isRunning();
                break;
            }else {
                loop.exec();

212
            }
213 214 215
        }
    };

camilo higuita's avatar
camilo higuita committed
216
    QFuture<void> t1 = QtConcurrent::run(func);
217 218 219 220 221 222 223 224 225 226
    watcher->setFuture(t1);
}

void AlbumsModel::updateArtwork(const int index, const QString &artwork)
{
    if(index >= this->list.size() || index < 0)
        return;

    this->list[index][FMH::MODEL_KEY::ARTWORK] = artwork;
    emit this->updateModel(index, {FMH::MODEL_KEY::ARTWORK});
camilo higuita's avatar
camilo higuita committed
227 228 229 230 231 232
}

QVariantMap AlbumsModel::get(const int &index) const
{
    if(index >= this->list.size() || index < 0)
        return QVariantMap();
233
    return FM::toMap(this->list.at(index));
camilo higuita's avatar
camilo higuita committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
}

void AlbumsModel::append(const QVariantMap &item)
{
    if(item.isEmpty())
        return;

    emit this->preItemAppended();

    FMH::MODEL model;
    for(auto key : item.keys())
        model.insert(FMH::MODEL_NAME_KEY[key], item[key].toString());

    this->list << model;

    emit this->postItemAppended();
}

void AlbumsModel::append(const QVariantMap &item, const int &at)
{
    if(item.isEmpty())
        return;

    if(at > this->list.size() || at < 0)
        return;

    qDebug()<< "trying to append at" << at << item["title"];

    emit this->preItemAppendedAt(at);

    FMH::MODEL model;
    for(auto key : item.keys())
        model.insert(FMH::MODEL_NAME_KEY[key], item[key].toString());

    this->list.insert(at, model);

    emit this->postItemAppended();
}

Camilo higuita's avatar
Camilo higuita committed
273 274 275 276
void AlbumsModel::refresh()
{
    this->setList();
}