collectionDB.cpp 30.6 KB
Newer Older
Camilo Higuita's avatar
Camilo Higuita committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
/*
   Babe - tiny music player
   Copyright (C) 2017  Camilo Higuita
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software Foundation,
   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA

   */


#include "collectionDB.h"
#include <QUuid>
#include <QString>
#include <QStringList>

using namespace BAE;

CollectionDB::CollectionDB(QObject *parent) : QObject(parent)
{
    this->name = QUuid::createUuid().toString();
    if(!BAE::fileExists(BAE::CollectionDBPath + BAE::DBName))
    {
        this->openDB(this->name);
        qDebug()<<"Collection doesn't exists, trying to create it" << BAE::CollectionDBPath + BAE::DBName;
        this->prepareCollectionDB();
    }else this->openDB(this->name);
}

CollectionDB::~CollectionDB()
{
    this->m_db.close();
}

Camilo Higuita's avatar
Camilo Higuita committed
42 43 44 45 46
void CollectionDB::test()
{
    qDebug()<<"call form qml";
}

Camilo Higuita's avatar
Camilo Higuita committed
47 48 49 50 51 52 53 54 55
void CollectionDB::closeConnection()
{
    qDebug()<<"CLOSING COLLECTIONDB";
}

void CollectionDB::prepareCollectionDB() const
{
    QSqlQuery query(this->m_db);

Camilo Higuita's avatar
Camilo Higuita committed
56
    QFile file(":/db/script.sql");
Camilo Higuita's avatar
Camilo Higuita committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212

    if (!file.exists())
    {
        QString log = QStringLiteral("Fatal error on build database. The file '");
        log.append(file.fileName() + QStringLiteral("' for database and tables creation query cannot be not found!"));
        qDebug()<<log;
        return;
    }

    if (!file.open(QIODevice::ReadOnly))
    {
        qDebug()<<QStringLiteral("Fatal error on try to create database! The file with sql queries for database creation cannot be opened!");
        return;
    }

    bool hasText;
    QString line;
    QByteArray readLine;
    QString cleanedLine;
    QStringList strings;

    while (!file.atEnd())
    {
        hasText     = false;
        line        = "";
        readLine    = "";
        cleanedLine = "";
        strings.clear();
        while (!hasText)
        {
            readLine    = file.readLine();
            cleanedLine = readLine.trimmed();
            strings     = cleanedLine.split("--");
            cleanedLine = strings.at(0);
            if (!cleanedLine.startsWith("--") && !cleanedLine.startsWith("DROP") && !cleanedLine.isEmpty())
                line += cleanedLine;
            if (cleanedLine.endsWith(";"))
                break;
            if (cleanedLine.startsWith("COMMIT"))
                hasText = true;
        }
        if (!line.isEmpty())
        {
            if (!query.exec(line))
            {
                qDebug()<<"exec failed"<<query.lastQuery()<<query.lastError();
            }

        } else qDebug()<<"exec wrong"<<query.lastError();
    }
    file.close();
}

bool CollectionDB::check_existance(const QString &tableName, const QString &searchId,const QString &search)
{
    auto queryStr = QString("SELECT %1 FROM %2 WHERE %3 = \"%4\"").arg(searchId, tableName, searchId, search);
    auto query = this->getQuery(queryStr);

    if (query.exec())
    {
        if (query.next()) return true;
    }else qDebug()<<query.lastError().text();

    return false;
}

bool CollectionDB::insert(const QString &tableName, const QVariantMap &insertData)
{
    if (tableName.isEmpty())
    {
        qDebug()<<QStringLiteral("Fatal error on insert! The table name is empty!");
        return false;

    } else if (insertData.isEmpty())
    {
        qDebug()<<QStringLiteral("Fatal error on insert! The insertData is empty!");
        return false;
    }

    QStringList strValues;
    QStringList fields = insertData.keys();
    QVariantList values = insertData.values();
    int totalFields = fields.size();
    for (int i = 0; i < totalFields; ++i)
        strValues.append("?");

    QString sqlQueryString = "INSERT INTO " + tableName + " (" + QString(fields.join(",")) + ") VALUES(" + QString(strValues.join(",")) + ")";
    QSqlQuery query(this->m_db);
    query.prepare(sqlQueryString);

    int k = 0;
    foreach (const QVariant &value, values)
        query.bindValue(k++, value);

    return query.exec();
}

bool CollectionDB::update(const QString &tableName, const BAE::DB &updateData, const QVariantMap &where)
{
    if (tableName.isEmpty())
    {
        qDebug()<<QStringLiteral("Fatal error on insert! The table name is empty!");
        return false;
    } else if (updateData.isEmpty())
    {
        qDebug()<<QStringLiteral("Fatal error on insert! The insertData is empty!");
        return false;
    }

    QStringList set;
    for (auto key : updateData.keys())
        set.append(KEYMAP[key]+" = '"+updateData[key]+"'");

    QStringList condition;
    for (auto key : where.keys())
        condition.append(key+" = '"+where[key].toString()+"'");

    QString sqlQueryString = "UPDATE " + tableName + " SET " + QString(set.join(",")) + " WHERE " + QString(condition.join(",")) ;
    auto query = this->getQuery(sqlQueryString);
    qDebug()<<sqlQueryString;
    return query.exec();
}

bool CollectionDB::update(const QString &table, const QString &column, const QVariant &newValue, const QVariant &op, const QString &id)
{
    auto queryStr = QString("UPDATE %1 SET %2 = \"%3\" WHERE %4 = \"%5\"").arg(table, column, newValue.toString().replace("\"","\"\""), op.toString(), id);
    auto query = this->getQuery(queryStr);
    return query.exec();
}

bool CollectionDB::execQuery(QSqlQuery &query) const
{
    if(query.exec()) return true;
    qDebug()<<"ERROR ON EXEC QUERY";
    qDebug()<<query.lastError()<<query.lastQuery();
    return false;
}

bool CollectionDB::execQuery(const QString &queryTxt)
{
    auto query = this->getQuery(queryTxt);
    return query.exec();
}

void CollectionDB::openDB(const QString &name)
{
    if(!QSqlDatabase::contains(name))
    {
        this->m_db = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), name);
        this->m_db.setDatabaseName(BAE::CollectionDBPath + BAE::DBName);
    }

    if (!this->m_db.isOpen())
    {
        if(!this->m_db.open())
            qDebug()<<"ERROR OPENING DB"<<this->m_db.lastError().text()<<m_db.connectionName();
213 214 215
    }else
    {
        this->execQuery("PRAGMA journal_mode=WAL");
Camilo Higuita's avatar
Camilo Higuita committed
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    }
}

void CollectionDB::addTrack(const DB &track)
{
    auto query = this->getQuery("PRAGMA synchronous=OFF");
    if(query.exec())
    {
        auto url = track[KEY::URL];
        auto title = track[KEY::TITLE];
        auto artist = track[KEY::ARTIST];
        auto album = track[KEY::ALBUM];
        auto genre = track[KEY::GENRE];
        auto year = track[KEY::RELEASE_DATE];
        auto sourceUrl = track[KEY::SOURCES_URL];
        auto duration = track[KEY::DURATION];
        auto babe = track[KEY::BABE];
        auto trackNumber = track[KEY::TRACK];

        auto artwork = track[KEY::ARTWORK].isEmpty()? "" : track[KEY::ARTWORK];

        qDebug()<< "writting to db: "<<title<<artist;
        /* first needs to insert album and artist*/
        QVariantMap sourceMap {{KEYMAP[KEY::URL],sourceUrl},
                               {KEYMAP[KEY::SOURCE_TYPE], sourceType(url)}};

        insert(TABLEMAP[TABLE::SOURCES],sourceMap);

        QVariantMap artistMap {{KEYMAP[KEY::ARTIST], artist},
                               {KEYMAP[KEY::ARTWORK], ""},
                               {KEYMAP[KEY::WIKI],""}};

        insert(TABLEMAP[TABLE::ARTISTS],artistMap);

        QVariantMap albumMap {{KEYMAP[KEY::ALBUM], album},
                              {KEYMAP[KEY::ARTIST], artist},
                              {KEYMAP[KEY::ARTWORK], artwork},
                              {KEYMAP[KEY::WIKI],""}};
        insert(TABLEMAP[TABLE::ALBUMS],albumMap);

        QVariantMap trackMap {{KEYMAP[KEY::URL], url},
                              {KEYMAP[KEY::SOURCES_URL], sourceUrl},
                              {KEYMAP[KEY::TRACK], trackNumber},
                              {KEYMAP[KEY::TITLE], title},
                              {KEYMAP[KEY::ARTIST], artist},
                              {KEYMAP[KEY::ALBUM], album},
                              {KEYMAP[KEY::DURATION], duration},
                              {KEYMAP[KEY::PLAYED], 0},
                              {KEYMAP[KEY::BABE], babe},
                              {KEYMAP[KEY::STARS], 0},
                              {KEYMAP[KEY::RELEASE_DATE], year},
                              {KEYMAP[KEY::ADD_DATE], QDateTime::currentDateTime()},
                              {KEYMAP[KEY::LYRICS],""},
                              {KEYMAP[KEY::GENRE], genre},
                              {KEYMAP[KEY::ART], ""},
                              {KEYMAP[KEY::WIKI], ""},
                              {KEYMAP[KEY::COMMENT], ""}};

        insert(TABLEMAP[TABLE::TRACKS],trackMap);
    }else
    {
        qDebug()<< "Failed to insert async";
    }

    emit trackInserted();
}

bool CollectionDB::updateTrack(const DB &track)
{
    if(this->check_existance(TABLEMAP[TABLE::TRACKS], KEYMAP[KEY::URL], track[KEY::URL]))
    {
        QVariantMap artistMap {{KEYMAP[KEY::ARTIST], track[KEY::ARTIST]},
                               {KEYMAP[KEY::ARTWORK], ""},
                               {KEYMAP[KEY::WIKI],""}};

        insert(TABLEMAP[TABLE::ARTISTS],artistMap);

        QVariantMap albumMap {{KEYMAP[KEY::ALBUM], track[KEY::ALBUM]},
                              {KEYMAP[KEY::ARTIST], track[KEY::ARTIST]},
                              {KEYMAP[KEY::ARTWORK], ""},
                              {KEYMAP[KEY::WIKI],""}};
        insert(TABLEMAP[TABLE::ALBUMS],albumMap);

        QVariantMap condition {{KEYMAP[KEY::URL], track[KEY::URL]}};

        if(this->update(TABLEMAP[TABLE::TRACKS], track, condition))
            if(cleanAlbums()) cleanArtists();

        return true;
    }

    return false;
}

bool CollectionDB::rateTrack(const QString &path, const int &value)
{
    if(update(TABLEMAP[TABLE::TRACKS],
              KEYMAP[KEY::STARS],
              value,
              KEYMAP[KEY::URL],
              path)) return true;
    return false;
}


321
bool CollectionDB::colorTagTrack(const QString &path, const QString &value)
Camilo Higuita's avatar
Camilo Higuita committed
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
{
    if(update(TABLEMAP[TABLE::TRACKS],
              KEYMAP[KEY::ART],
              value,
              KEYMAP[KEY::URL],
              path)) return true;
    return false;
}

bool CollectionDB::lyricsTrack(const DB &track, const QString &value)
{
    if(update(TABLEMAP[TABLE::TRACKS],
              KEYMAP[KEY::LYRICS],
              value,
              KEYMAP[KEY::URL],
              track[KEY::URL])) return true;
    return false;
}

bool CollectionDB::tagsTrack(const DB &track, const QString &value, const QString &context)
{
    auto url = track[KEY::URL];

    qDebug()<<"INSERTIN TRACK TAG"<<value<<context<<url;

    QVariantMap tagMap {{KEYMAP[KEY::TAG],value},{KEYMAP[KEY::CONTEXT],context}};

    QVariantMap trackTagMap {{KEYMAP[KEY::TAG],value},
                             {KEYMAP[KEY::CONTEXT],context},
                             {KEYMAP[KEY::URL],url}};

    insert(TABLEMAP[TABLE::TAGS],tagMap);
    insert(TABLEMAP[TABLE::TRACKS_TAGS],trackTagMap);
    return true;
}

bool CollectionDB::albumTrack(const DB &track, const QString &value)
{
    auto album = track[KEY::ALBUM];
    auto artist = track[KEY::ARTIST];
    auto url = track[KEY::URL];

    auto queryTxt = QString("SELECT * %1 WHERE %2 = %3 AND %4 = %5").arg(TABLEMAP[TABLE::ALBUMS],
            KEYMAP[KEY::ALBUM],album, KEYMAP[KEY::ARTIST], artist);

    auto result = this->getDBData(queryTxt);
    if(result.isEmpty())  return false;

    auto oldAlbum = result.first();
    QVariantMap albumMap {{KEYMAP[KEY::ALBUM],value},
                          {KEYMAP[KEY::ARTIST],oldAlbum[KEY::ARTIST]},
                          {KEYMAP[KEY::ARTWORK],oldAlbum[KEY::ARTWORK]},
                          {KEYMAP[KEY::WIKI],oldAlbum[KEY::WIKI]}};

    if (!insert(TABLEMAP[TABLE::ALBUMS],albumMap)) return false;

    // update albums SET album = "newalbumname" WHERE album = "albumname" NAD artist = "aretist name";
    queryTxt = QString("UPDATE %1 SET %2 = %3 AND %4 = %5 WHERE %2 = %6 AND %4 = %5").arg(TABLEMAP[TABLE::TRACKS],
            KEYMAP[KEY::ALBUM],value,
            KEYMAP[KEY::ARTIST], oldAlbum[KEY::ARTIST],oldAlbum[KEY::ALBUM]);
    auto query = this->getQuery(queryTxt);

    if(!execQuery(query)) return false;

    queryTxt = QString("DELETE FROM %1 WHERE %2 = %3 AND %4 = %5").arg(TABLEMAP[TABLE::ALBUMS],
            KEYMAP[KEY::ALBUM],oldAlbum[KEY::ALBUM], KEYMAP[KEY::ARTIST], artist);
    query.prepare(queryTxt);

    if(!execQuery(query)) return false;

    return true;
}

bool CollectionDB::playedTrack(const QString &url, const int &increment)
{
    auto queryTxt = QString("UPDATE %1 SET %2 = %2 + %3 WHERE %4 = \"%5\"").arg(TABLEMAP[TABLE::TRACKS],
            KEYMAP[KEY::PLAYED], QString::number(increment), KEYMAP[KEY::URL],url);

    auto query = this->getQuery(queryTxt);

    if(query.exec())
        return true;

    return false;
}

bool CollectionDB::wikiTrack(const DB &track, const QString &value)
{
    auto url = track[KEY::URL];

    if(update(TABLEMAP[TABLE::TRACKS],
              KEYMAP[KEY::WIKI],
              value,
              KEYMAP[KEY::URL],
              url)) return true;

    return false;
}

bool CollectionDB::wikiArtist(const DB &track, const QString &value)
{
    auto artist = track[KEY::ARTIST];

    if(update(TABLEMAP[TABLE::ARTISTS],
              KEYMAP[KEY::WIKI],
              value,
              KEYMAP[KEY::ARTIST],
              artist)) return true;
    return false;
}

bool CollectionDB::tagsArtist(const DB &track, const QString &value, const QString &context)
{
    auto artist = track[KEY::ARTIST];

    QVariantMap tagMap {{KEYMAP[KEY::TAG],value},{KEYMAP[KEY::CONTEXT],context}};

    QVariantMap artistTagMap {{KEYMAP[KEY::TAG],value},
                              {KEYMAP[KEY::CONTEXT],context},
                              {KEYMAP[KEY::ARTIST],artist}};

    insert(TABLEMAP[TABLE::TAGS],tagMap);
    insert(TABLEMAP[TABLE::ARTISTS_TAGS],artistTagMap);

    return true;

}

bool CollectionDB::wikiAlbum(const DB &track,  QString value)
{
    auto artist = track[KEY::ARTIST];
    auto album = track[KEY::ALBUM];

    auto queryStr = QString("UPDATE %1 SET %2 = \"%3\" WHERE %4 = \"%5\" AND %6 = \"%7\"").arg(
                TABLEMAP[TABLE::ALBUMS],
            KEYMAP[KEY::WIKI], value.replace("\"","\"\""),
            KEYMAP[KEY::ALBUM],
            album,KEYMAP[KEY::ARTIST], artist);


    qDebug()<<queryStr;
    auto query = this->getQuery(queryStr);
    return query.exec();
}

bool CollectionDB::tagsAlbum(const DB &track, const QString &value, const QString &context)
{
    auto artist = track[KEY::ARTIST];
    auto album = track[KEY::ALBUM];

    QVariantMap tagMap {{KEYMAP[KEY::TAG],value},{KEYMAP[KEY::CONTEXT],context}};

    QVariantMap albumsTagMap {{KEYMAP[KEY::TAG],value},
                              {KEYMAP[KEY::CONTEXT],context},
                              {KEYMAP[KEY::ARTIST],artist},
                              {KEYMAP[KEY::ALBUM],album}};

    insert(TABLEMAP[TABLE::TAGS],tagMap);
    insert(TABLEMAP[TABLE::ALBUMS_TAGS],albumsTagMap);
    return true;
}

bool CollectionDB::addPlaylist(const QString &title)
{
    if(!title.isEmpty())
    {
        QVariantMap playlist {{KEYMAP[KEY::PLAYLIST],title},
489
                              {KEYMAP[KEY::ADD_DATE],QDateTime::currentDateTime()}};
Camilo Higuita's avatar
Camilo Higuita committed
490 491 492 493 494 495 496 497

        if(insert(TABLEMAP[TABLE::PLAYLISTS],playlist))
            return true;
    }

    return false;
}

Camilo Higuita's avatar
fixes  
Camilo Higuita committed
498 499 500
bool CollectionDB::addFolder(const QString &url)
{
    QVariantMap map {{KEYMAP[KEY::URL],url},
501
                     {KEYMAP[KEY::ADD_DATE],QDateTime::currentDateTime()}};
Camilo Higuita's avatar
fixes  
Camilo Higuita committed
502 503 504 505 506 507 508

    if(insert(TABLEMAP[TABLE::FOLDERS],map))
        return true;

    return false;
}

Camilo Higuita's avatar
Camilo Higuita committed
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547

DB_LIST CollectionDB::getDBData(const QStringList &urls)
{
    DB_LIST mapList;

    for(auto url : urls)
    {
        auto queryTxt = QString("SELECT * FROM %1 WHERE %2 = \"%3\"").arg(TABLEMAP[TABLE::TRACKS],
                KEYMAP[KEY::URL],url);

        mapList << this->getDBData(queryTxt);
    }

    return mapList;
}

DB_LIST CollectionDB::getDBData(const QString &queryTxt)
{
    DB_LIST mapList;

    auto query = this->getQuery(queryTxt);

    if(query.exec())
    {
        while(query.next())
        {
            DB data;
            for(auto key : KEYMAP.keys())
                if(query.record().indexOf(KEYMAP[key])>-1)
                    data.insert(key, query.value(KEYMAP[key]).toString());

            mapList<< data;
        }

    }else qDebug()<< query.lastError()<< query.lastQuery();

    return mapList;
}

548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
QVariantList CollectionDB::getDBDataQML(const QString &queryTxt)
{
    QVariantList mapList;

    auto query = this->getQuery(queryTxt);

    if(query.exec())
    {
        while(query.next())
        {
            QVariantMap data;
            for(auto key : KEYMAP.keys())
                if(query.record().indexOf(KEYMAP[key])>-1)
                    data[BAE::KEYMAP[key]] = query.value(KEYMAP[key]).toString();

            mapList<< data;
        }

    }else qDebug()<< query.lastError()<< query.lastQuery();

    return mapList;
}

Camilo Higuita's avatar
Camilo Higuita committed
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609

DB_LIST CollectionDB::getAlbumTracks(const QString &album, const QString &artist, const KEY &orderBy, const BAE::W &order)
{
    auto queryTxt = QString("SELECT * FROM %1 WHERE %2 = \"%3\" AND %4 = \"%5\" ORDER by %6 %7").arg(TABLEMAP[TABLE::TRACKS],
            KEYMAP[KEY::ARTIST],artist,KEYMAP[KEY::ALBUM],album,KEYMAP[orderBy], SLANG[order]);

    return this->getDBData(queryTxt);
}

DB_LIST CollectionDB::getArtistTracks(const QString &artist, const KEY &orderBy, const BAE::W &order)
{
    auto queryTxt = QString("SELECT * FROM %1 WHERE %2 = \"%3\" ORDER by %4 %5, %6 %5").arg(TABLEMAP[TABLE::TRACKS],
            KEYMAP[KEY::ARTIST],artist,KEYMAP[orderBy],SLANG[order],KEYMAP[KEY::TRACK]);

    return this->getDBData(queryTxt);
}

QStringList CollectionDB::getArtistAlbums(const QString &artist)
{
    QStringList albums;

    auto queryTxt = QString("SELECT %4 FROM %1 WHERE %2 = \"%3\" ORDER BY %4 ASC").arg(TABLEMAP[TABLE::ALBUMS],
            KEYMAP[KEY::ARTIST],artist,KEYMAP[KEY::ALBUM]);
    auto query = this->getDBData(queryTxt);

    for(auto track : query)
        albums << track[KEY::ALBUM];

    return albums;
}

DB_LIST CollectionDB::getBabedTracks(const KEY &orderBy, const BAE::W &order)
{
    auto queryTxt = QString("SELECT * FROM %1 WHERE %2 = 1 ORDER by %3 %4").arg(TABLEMAP[TABLE::TRACKS],
            KEYMAP[KEY::BABE],
            KEYMAP[orderBy], SLANG[order]);
    return this->getDBData(queryTxt);
}

610
QVariantList CollectionDB::getSearchedTracks(const KEY &where, const QString &search)
Camilo Higuita's avatar
Camilo Higuita committed
611 612 613 614
{
    QString queryTxt;

    if(where == KEY::PLAYED || where == KEY::STARS || where == KEY::BABE)
615
        queryTxt = QString("SELECT t.*, al.artwork FROM %1 t inner join albums al on al.album = t.album and t.artist = al.artist WHERE %2 = \"%3\"").arg(TABLEMAP[TABLE::TRACKS],
Camilo Higuita's avatar
Camilo Higuita committed
616 617 618 619
                KEYMAP[where],
                search);
    else if(where == KEY::WIKI)

620
        queryTxt = QString("SELECT DISTINCT t.*, al.artwork FROM %1 t INNER JOIN %2 al ON t.%3 = al.%3 INNER JOIN %4 ar ON t.%5 = ar.%5 WHERE al.%6 LIKE \"%%7%\" OR ar.%6 LIKE \"%%7%\" COLLATE NOCASE").arg(TABLEMAP[TABLE::TRACKS],
Camilo Higuita's avatar
Camilo Higuita committed
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
                TABLEMAP[TABLE::ALBUMS],KEYMAP[KEY::ALBUM],
                TABLEMAP[TABLE::ARTISTS],KEYMAP[KEY::ARTIST],
                KEYMAP[where],
                search);


    else if(where == KEY::PLAYLIST)

        queryTxt = QString("SELECT t.* FROM %1 t INNER JOIN %2 tp ON t.%3 = tp.%3 WHERE tp.%4 = \"%5\"").arg(TABLEMAP[TABLE::TRACKS],
                TABLEMAP[TABLE::TRACKS_PLAYLISTS],KEYMAP[KEY::URL],
                KEYMAP[where],
                search);


    else if(where == KEY::TAG)

        queryTxt = QString("SELECT t.* FROM %1 t INNER JOIN %2 tt ON t.%3 = tt.%3 WHERE tt.%4 = \"%5\" COLLATE NOCASE "
                           "UNION "
                           "SELECT t.* FROM %1 t INNER JOIN %6 at ON t.%7 = at.%7 AND t.%8 = at.%8 WHERE at.%4 = \"%5\" COLLATE NOCASE "
                           "UNION "
                           "SELECT t.* FROM %1 t INNER JOIN %9 art ON t.%8 = art.%8 WHERE art.%4 LIKE \"%%5%\" COLLATE NOCASE "
                           "UNION "
                           "SELECT DISTINCT t.* FROM %1 t INNER JOIN %9 at ON t.%8 = at.%4 WHERE at.%8 LIKE \"%%5%\" COLLATE NOCASE").arg(
                    TABLEMAP[TABLE::TRACKS],
                TABLEMAP[TABLE::TRACKS_TAGS],
                KEYMAP[KEY::URL],
                KEYMAP[where],
                search,
                TABLEMAP[TABLE::ALBUMS_TAGS],
                KEYMAP[KEY::ALBUM],
                KEYMAP[KEY::ARTIST],
                TABLEMAP[TABLE::ARTISTS_TAGS]);

    else
655
        queryTxt = QString("SELECT t.*, al.artwork FROM %1 t inner join albums al on al.album = t.album and t.artist = al.artist WHERE %2 LIKE \"%%3%\"").arg(TABLEMAP[TABLE::TRACKS],
Camilo Higuita's avatar
Camilo Higuita committed
656 657 658 659 660
                KEYMAP[where],
                search);

    qDebug()<<"SEARCH QUERY:"<<queryTxt;

661
    return this->getDBDataQML(queryTxt);
Camilo Higuita's avatar
Camilo Higuita committed
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709

}

DB_LIST CollectionDB::getPlaylistTracks(const QString &playlist, const KEY &orderBy, const BAE::W &order)
{
    auto queryTxt= QString("SELECT t.* FROM %1 t INNER JOIN %2 tp ON t.%3 = tp.%3 WHERE tp.%4 = '%5' ORDER BY tp.%6 %7").arg(TABLEMAP[TABLE::TRACKS],
            TABLEMAP[TABLE::TRACKS_PLAYLISTS], KEYMAP[KEY::URL],
            KEYMAP[KEY::PLAYLIST],
            playlist, KEYMAP[orderBy], SLANG[order]);

    return this->getDBData(queryTxt);
}

DB_LIST CollectionDB::getFavTracks(const int &stars, const int &limit, const KEY &orderBy, const BAE::W &order)
{
    auto queryTxt= QString("SELECT * FROM %1 WHERE %2 >= %3 ORDER BY %4 %5 LIMIT %6" ).arg(TABLEMAP[TABLE::TRACKS],
            KEYMAP[KEY::STARS], QString::number(stars),
            KEYMAP[orderBy],SLANG[order],QString::number(limit));

    return this->getDBData(queryTxt);
}

DB_LIST CollectionDB::getRecentTracks(const int &limit, const KEY &orderBy, const BAE::W &order)
{
    auto queryTxt= QString("SELECT * FROM %1 ORDER BY strftime(\"%s\",%2) %3 LIMIT %4" ).arg(TABLEMAP[TABLE::TRACKS],
            KEYMAP[orderBy],SLANG[order],QString::number(limit));

    return this->getDBData(queryTxt);
}

DB_LIST CollectionDB::getOnlineTracks(const KEY &orderBy, const BAE::W &order)
{
    auto queryTxt= QString("SELECT * FROM %1 WHERE %2 LIKE \"%3%\" ORDER BY %4 %5" ).arg(TABLEMAP[TABLE::TRACKS],
            KEYMAP[KEY::URL],YoutubeCachePath,KEYMAP[orderBy],SLANG[order]);

    return this->getDBData(queryTxt);
}

DB_LIST CollectionDB::getMostPlayedTracks(const int &greaterThan, const int &limit, const KEY &orderBy, const BAE::W &order)
{
    auto queryTxt = QString("SELECT * FROM %1 WHERE %2 > %3 ORDER BY %4 %5 LIMIT %6" ).arg(TABLEMAP[TABLE::TRACKS],
            KEYMAP[KEY::PLAYED], QString::number(greaterThan),
            KEYMAP[orderBy],SLANG[order],QString::number(limit));

    return this->getDBData(queryTxt);
}


710
QString CollectionDB::trackColorTag(const QString &path)
Camilo Higuita's avatar
Camilo Higuita committed
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
{
    QString color;
    auto query = this->getDBData(QString("SELECT %1 FROM %2 WHERE %3 = \"%4\"").arg(KEYMAP[KEY::ART],
                                 TABLEMAP[TABLE::TRACKS],
            KEYMAP[KEY::URL],path));

    for(auto track : query)
        color = track[KEY::ART];

    return color;
}

QStringList CollectionDB::getTrackTags(const QString &path)
{
    Q_UNUSED(path);
    return {};
}

int CollectionDB::getTrackStars(const QString &path)
{
    int stars = 0;
    auto query = this->getDBData(QString("SELECT %1 FROM %2 WHERE %3 = \"%4\"").arg(KEYMAP[KEY::STARS],
                                 TABLEMAP[TABLE::TRACKS],
            KEYMAP[KEY::URL],path));

    for(auto track : query)
        stars = track[KEY::STARS].toInt();

    return stars;
}

//QStringList CollectionDB::getArtistTags(const QString &artist)
//{
//    QStringList tags;

//    auto queryStr = QString("SELECT at.%1 FROM %2 at "
//                            "INNER JOIN %3 ta ON ta.%1 = at.%1 "
//                            "WHERE ta.%4 = '%5' "
//                            "AND at.%6 = \"%7\"").arg(KEYMAP[KEY::TAG],
//            TABLEMAP[TABLE::ARTISTS_TAGS],
//            TABLEMAP[TABLE::TAGS],
//            KEYMAP[KEY::CONTEXT],
//            PULPO::CONTEXT_MAP[PULPO::CONTEXT::ARTIST_SIMILAR],
//            KEYMAP[KEY::ARTIST],artist);
//    auto query = this->getDBData(queryStr);
//    for(auto track : query)
//        tags << track[KEY::TAG];

//    return tags;
//}


//QStringList CollectionDB::getAlbumTags(const QString &album, const QString &artist)
//{
//    QStringList tags;

//    auto queryStr = QString("SELECT at.%1 FROM %2 at "
//                            "INNER JOIN %3 ta ON ta.%1 = at.%1 "
//                            "WHERE ta.%4 = '%5' AND at.%6 = \"%7\" AND at.%8 = \"%9\"").arg(KEYMAP[KEY::TAG],
//            TABLEMAP[TABLE::ALBUMS_TAGS],
//            TABLEMAP[TABLE::TAGS],
//            KEYMAP[KEY::CONTEXT],
//            PULPO::CONTEXT_MAP[PULPO::CONTEXT::TAG],
//            KEYMAP[KEY::ALBUM],album,
//            KEYMAP[KEY::ARTIST],artist);

//    auto query = this->getDBData(queryStr);

//    for(auto track : query)
//        tags << track[KEY::TAG];

//    return tags;
//}

QStringList CollectionDB::getPlaylists()
{
    QStringList playlists;
    auto queryTxt = QString("SELECT %1, %2 FROM %3 ORDER BY %2 DESC").arg(KEYMAP[KEY::PLAYLIST], KEYMAP[KEY::ADD_DATE],TABLEMAP[TABLE::PLAYLISTS]);

    for(auto data : this->getDBData(queryTxt))
        playlists << data[KEY::PLAYLIST];

    return playlists;
}

bool CollectionDB::removeTrack(const QString &path)
{
    auto queryTxt = QString("DELETE FROM %1 WHERE %2 =  \"%3\"").arg(TABLEMAP[TABLE::TRACKS],
            KEYMAP[KEY::URL],path);
    auto query = this->getQuery(queryTxt);
    if(query.exec())
    {
        if(cleanAlbums()) cleanArtists();
        return true;
    }
    return false;
}

QSqlQuery CollectionDB::getQuery(const QString &queryTxt)
810
{    
Camilo Higuita's avatar
Camilo Higuita committed
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
    QSqlQuery query(queryTxt, this->m_db);
    return query;
}

bool CollectionDB::removeSource(const QString &path)
{
    auto queryTxt = QString("DELETE FROM %1 WHERE %2 LIKE \"%3%\"").arg(TABLEMAP[TABLE::TRACKS],
            KEYMAP[KEY::SOURCES_URL],path);
    qDebug() << queryTxt;
    auto query = this->getQuery(queryTxt);
    if(query.exec())
    {
        queryTxt = QString("DELETE FROM %1 WHERE %2 LIKE \"%3%\"").arg(TABLEMAP[TABLE::SOURCES],
                KEYMAP[KEY::URL],path);
        query.prepare(queryTxt);
        if(query.exec())
        {
            if(cleanAlbums()) cleanArtists();
            return true;
        }
    }
    return false;
}

sourceTypes CollectionDB::sourceType(const QString &url)
{
    /*for now*/
    Q_UNUSED(url);
    return sourceTypes::LOCAL;
}


/*******************OLD STUFF********************/

void CollectionDB::insertArtwork(const DB &track)
{
    auto artist = track[KEY::ARTIST];
    auto album =track[KEY::ALBUM];
    auto path = track[KEY::ARTWORK];

    switch(albumType(track))
    {
853 854 855 856 857 858 859 860 861 862 863 864 865
    case TABLE::ALBUMS :
    {
        auto queryStr = QString("UPDATE %1 SET %2 = \"%3\" WHERE %4 = \"%5\" AND %6 = \"%7\"").arg(TABLEMAP[TABLE::ALBUMS],
                KEYMAP[KEY::ARTWORK],
                path.isEmpty() ? SLANG[W::NONE] : path,
                                                  KEYMAP[KEY::ALBUM],
                                                  album,
                                                  KEYMAP[KEY::ARTIST],
                                                  artist);

        auto query = this->getQuery(queryStr);
        if(!query.exec())qDebug()<<"COULDNT Artwork[cover] inerted into DB"<<artist<<album;
        break;
Camilo Higuita's avatar
Camilo Higuita committed
866

867 868 869 870 871 872 873 874 875 876
    }
    case TABLE::ARTISTS:
    {
        auto queryStr = QString("UPDATE %1 SET %2 = \"%3\" WHERE %4 = \"%5\"").arg(TABLEMAP[TABLE::ARTISTS],
                KEYMAP[KEY::ARTWORK],
                path.isEmpty() ? SLANG[W::NONE] : path,
                                                  KEYMAP[KEY::ARTIST],
                                                  artist);
        auto query = this->getQuery(queryStr);
        if(!query.exec())qDebug()<<"COULDNT Artwork[head] inerted into DB"<<artist;
Camilo Higuita's avatar
Camilo Higuita committed
877

878
        break;
Camilo Higuita's avatar
Camilo Higuita committed
879

880 881
    }
    default: return;
Camilo Higuita's avatar
Camilo Higuita committed
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
    }

    emit artworkInserted(track);
}


bool CollectionDB::removePlaylistTrack(const QString &url, const QString &playlist)
{
    auto queryTxt = QString("DELETE FROM %1 WHERE %2 = \"%3\" AND %4 = \"%5\"").arg(TABLEMAP[TABLE::TRACKS_PLAYLISTS],
            KEYMAP[KEY::PLAYLIST],playlist,KEYMAP[KEY::URL],url);
    auto query = this->getQuery(queryTxt);
    return query.exec();
}

bool CollectionDB::removePlaylist(const QString &playlist)
{
    QString queryTxt;
    queryTxt = QString("DELETE FROM %1 WHERE %2 = \"%3\"").arg(TABLEMAP[TABLE::TRACKS_PLAYLISTS],
            KEYMAP[KEY::PLAYLIST],playlist);

    auto query = this->getQuery(queryTxt);
    if(!query.exec()) return false;

    queryTxt = QString("DELETE FROM %1 WHERE %2 = \"%3\"").arg(TABLEMAP[TABLE::PLAYLISTS],
            KEYMAP[KEY::PLAYLIST],playlist);

    query.prepare(queryTxt);
    return query.exec();
}

bool CollectionDB::removeArtist(const QString &artist)
{
    auto queryTxt = QString("DELETE FROM %1 WHERE %2 = \"%3\" ").arg(TABLEMAP[TABLE::ARTISTS],
            KEYMAP[KEY::ARTIST],artist);
    auto query = this->getQuery(queryTxt);

    return query.exec();
}

bool CollectionDB::cleanArtists()
{
    //    delete from artists where artist in (select artist from artists except select distinct artist from tracks);
    auto queryTxt=QString("DELETE FROM %1 WHERE %2 IN (SELECT %2 FROM %1 EXCEPT SELECT DISTINCT %2 FROM %3)").arg(
                TABLEMAP[TABLE::ARTISTS],
            KEYMAP[KEY::ARTIST],
            TABLEMAP[TABLE::TRACKS]
            );
    qDebug()<<queryTxt;

    auto query = this->getQuery(queryTxt);
    emit this->artistsCleaned(query.numRowsAffected());
    return query.exec();
}

bool CollectionDB::removeAlbum(const QString &album, const QString &artist)
{
    auto queryTxt = QString("DELETE FROM %1 WHERE %2 = \"%3\" AND %4 = \"%5\"").arg(TABLEMAP[TABLE::ALBUMS],
            KEYMAP[KEY::ALBUM],album,KEYMAP[KEY::ARTIST],artist);
    auto query = this->getQuery(queryTxt);
    return query.exec();
}

bool CollectionDB::cleanAlbums()
{
    //    delete from albums where (album, artist) in (select a.album, a.artist from albums a except select distinct album, artist from tracks);
    auto queryTxt=QString("DELETE FROM %1 WHERE (%2, %3) IN (SELECT %2, %3 FROM %1 EXCEPT SELECT DISTINCT %2, %3  FROM %4)").arg(
                TABLEMAP[TABLE::ALBUMS],
            KEYMAP[KEY::ALBUM],
            KEYMAP[KEY::ARTIST],
            TABLEMAP[TABLE::TRACKS]
            );
    qDebug()<<queryTxt;
    auto query = this->getQuery(queryTxt);
    emit albumsCleaned(query.numRowsAffected());
    return query.exec();
}