Media.cpp 22.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser 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.
 *****************************************************************************/

23 24 25 26
#if HAVE_CONFIG_H
# include "config.h"
#endif

27
#include <algorithm>
28
#include <cassert>
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
29 30
#include <cstdlib>
#include <cstring>
31
#include <ctime>
32

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
33
#include "Album.h"
34
#include "AlbumTrack.h"
35
#include "Artist.h"
36
#include "AudioTrack.h"
37
#include "Media.h"
38
#include "File.h"
39
#include "Folder.h"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
40
#include "Label.h"
41
#include "logging/Logger.h"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
42
#include "Movie.h"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
43
#include "ShowEpisode.h"
44

45
#include "database/SqliteTools.h"
46
#include "database/SqliteQuery.h"
47
#include "VideoTrack.h"
48 49 50
#include "medialibrary/filesystem/IFile.h"
#include "medialibrary/filesystem/IDirectory.h"
#include "medialibrary/filesystem/IDevice.h"
51
#include "utils/Filename.h"
52

53 54 55
namespace medialibrary
{

56
const std::string policy::MediaTable::Name = "Media";
57
const std::string policy::MediaTable::PrimaryKeyColumn = "id_media";
58
int64_t Media::* const policy::MediaTable::PrimaryKey = &Media::m_id;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
59

60 61
Media::Media( MediaLibraryPtr ml, sqlite::Row& row )
    : m_ml( ml )
62
    , m_metadata( m_ml, IMetadata::EntityType::Media )
63
    , m_changed( false )
64
{
65 66
    row >> m_id
        >> m_type
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
67
        >> m_subType
68 69
        >> m_duration
        >> m_playCount
70
        >> m_lastPlayedDate
71
        >> m_insertionDate
72
        >> m_releaseDate
73 74
        >> m_thumbnailId
        >> m_thumbnailGenerated
75
        >> m_title
76
        >> m_filename
77 78
        >> m_isFavorite
        >> m_isPresent;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
79 80
}

81 82 83
Media::Media( MediaLibraryPtr ml, const std::string& title, Type type )
    : m_ml( ml )
    , m_id( 0 )
84
    , m_type( type )
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
85
    , m_subType( SubType::Unknown )
86
    , m_duration( -1 )
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
87
    , m_playCount( 0 )
88
    , m_lastPlayedDate( 0 )
89
    , m_insertionDate( time( nullptr ) )
90
    , m_releaseDate( 0 )
91 92
    , m_thumbnailId( 0 )
    , m_thumbnailGenerated( false )
93
    , m_title( title )
94 95
    // When creating a Media, meta aren't parsed, and therefor, is the filename
    , m_filename( title )
96
    , m_isFavorite( false )
97
    , m_isPresent( true )
98
    , m_metadata( m_ml, IMetadata::EntityType::Media )
99
    , m_changed( false )
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
100
{
101 102
}

103
std::shared_ptr<Media> Media::create( MediaLibraryPtr ml, Type type, const std::string& fileName )
104
{
105
    auto self = std::make_shared<Media>( ml, fileName, type );
106
    static const std::string req = "INSERT INTO " + policy::MediaTable::Name +
107
            "(type, insertion_date, title, filename) VALUES(?, ?, ?, ?)";
108

109
    if ( insert( ml, self, req, type, self->m_insertionDate, self->m_title, self->m_filename ) == false )
110
        return nullptr;
111
    return self;
112 113
}

114
AlbumTrackPtr Media::albumTrack() const
115
{
116 117
    if ( m_subType != SubType::AlbumTrack )
        return nullptr;
118 119
    auto lock = m_albumTrack.lock();

120
    if ( m_albumTrack.isCached() == false )
121
        m_albumTrack = AlbumTrack::fromMedia( m_ml, m_id );
122
    return m_albumTrack.get();
123 124
}

125
void Media::setAlbumTrack( AlbumTrackPtr albumTrack )
126
{
127
    auto lock = m_albumTrack.lock();
128
    m_albumTrack = albumTrack;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
129 130
    m_subType = SubType::AlbumTrack;
    m_changed = true;
131 132
}

133
int64_t Media::duration() const
134 135 136 137
{
    return m_duration;
}

138
void Media::setDuration( int64_t duration )
139
{
140 141
    if ( m_duration == duration )
        return;
142
    m_duration = duration;
143
    m_changed = true;
144 145
}

146
ShowEpisodePtr Media::showEpisode() const
147
{
148 149
    if ( m_subType != SubType::ShowEpisode )
        return nullptr;
150

151 152
    auto lock = m_showEpisode.lock();
    if ( m_showEpisode.isCached() == false )
153
        m_showEpisode = ShowEpisode::fromMedia( m_ml, m_id );
154
    return m_showEpisode.get();
155 156
}

157
void Media::setShowEpisode( ShowEpisodePtr episode )
158
{
159 160
    auto lock = m_showEpisode.lock();
    m_showEpisode = episode;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
161 162
    m_subType = SubType::ShowEpisode;
    m_changed = true;
163 164
}

165
Query<ILabel> Media::labels() const
166
{
167
    static const std::string req = "FROM " + policy::LabelTable::Name + " l "
168
            "INNER JOIN LabelFileRelation lfr ON lfr.label_id = l.id_label "
169
            "WHERE lfr.media_id = ?";
170
    return make_query<Label, ILabel>( m_ml, "l.*", req, m_id );
171 172
}

173
int Media::playCount() const
174
{
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
175
    return m_playCount;
176 177
}

178
bool Media::increasePlayCount()
179
{
180 181 182 183 184
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET "
            "play_count = ?, last_played_date = ? WHERE id_media = ?";
    auto lastPlayedDate = time( nullptr );
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, m_playCount + 1, lastPlayedDate, m_id ) == false )
        return false;
185
    m_playCount++;
186 187
    m_lastPlayedDate = lastPlayedDate;
    return true;
188 189
}

190 191 192 193 194
bool Media::isFavorite() const
{
    return m_isFavorite;
}

195
bool Media::setFavorite( bool favorite )
196
{
197
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET is_favorite = ? WHERE id_media = ?";
198
    if ( m_isFavorite == favorite )
199 200 201
        return true;
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, favorite, m_id ) == false )
        return false;
202
    m_isFavorite = favorite;
203
    return true;
204 205
}

206
const std::vector<FilePtr>& Media::files() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
207
{
208 209 210 211 212
    auto lock = m_files.lock();
    if ( m_files.isCached() == false )
    {
        static const std::string req = "SELECT * FROM " + policy::FileTable::Name
                + " WHERE media_id = ?";
213
        m_files = File::fetchAll<IFile>( m_ml, req, m_id );
214 215
    }
    return m_files;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
216 217
}

218 219 220 221 222
const std::string& Media::fileName() const
{
    return m_filename;
}

223
MoviePtr Media::movie() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
224
{
225 226 227
    if ( m_subType != SubType::Movie )
        return nullptr;

228 229
    auto lock = m_movie.lock();

230
    if ( m_movie.isCached() == false )
231
        m_movie = Movie::fromMedia( m_ml, m_id );
232
    return m_movie.get();
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
233 234
}

235
void Media::setMovie(MoviePtr movie)
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
236
{
237
    auto lock = m_movie.lock();
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
238
    m_movie = movie;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
239 240
    m_subType = SubType::Movie;
    m_changed = true;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
241 242
}

243 244
bool Media::addVideoTrack(const std::string& codec, unsigned int width, unsigned int height, float fps,
                          const std::string& language, const std::string& description )
245
{
246
    return VideoTrack::create( m_ml, codec, width, height, fps, m_id, language, description ) != nullptr;
247 248
}

249
Query<IVideoTrack> Media::videoTracks()
250
{
251
    static const std::string req = "FROM " + policy::VideoTrackTable::Name +
252
            " WHERE media_id = ?";
253
    return make_query<VideoTrack, IVideoTrack>( m_ml, "*", req, m_id );
254 255
}

256
bool Media::addAudioTrack( const std::string& codec, unsigned int bitrate,
257 258
                          unsigned int sampleRate, unsigned int nbChannels,
                          const std::string& language, const std::string& desc )
259
{
260
    return AudioTrack::create( m_ml, codec, bitrate, sampleRate, nbChannels, language, desc, m_id ) != nullptr;
261 262
}

263
Query<IAudioTrack> Media::audioTracks()
264
{
265
    static const std::string req = "FROM " + policy::AudioTrackTable::Name +
266
            " WHERE media_id = ?";
267
    return make_query<AudioTrack, IAudioTrack>( m_ml, "*", req, m_id );
268 269
}

270
const std::string& Media::thumbnail() const
271
{
272
    if ( m_thumbnailId == 0 || m_thumbnailGenerated == false )
273 274
        return Thumbnail::EmptyMrl;

275 276
    auto lock = m_thumbnail.lock();
    if ( m_thumbnail.isCached() == false )
277 278 279 280 281 282
    {
        auto thumbnail = Thumbnail::fetch( m_ml, m_thumbnailId );
        if ( thumbnail == nullptr )
            return Thumbnail::EmptyMrl;
        m_thumbnail = std::move( thumbnail );
    }
283 284 285 286 287 288
    return m_thumbnail.get()->mrl();
}

bool Media::isThumbnailGenerated() const
{
    return m_thumbnailGenerated;
289 290
}

291 292
unsigned int Media::insertionDate() const
{
293
    return static_cast<unsigned int>( m_insertionDate );
294 295
}

296 297 298 299 300
unsigned int Media::releaseDate() const
{
    return m_releaseDate;
}

301
const IMetadata& Media::metadata( IMedia::MetadataType type ) const
302
{
303
    using MDType = typename std::underlying_type<IMedia::MetadataType>::type;
304 305
    if ( m_metadata.isReady() == false )
        m_metadata.init( m_id, IMedia::NbMeta );
306
    return m_metadata.get( static_cast<MDType>( type ) );
307 308 309 310
}

bool Media::setMetadata( IMedia::MetadataType type, const std::string& value )
{
311
    using MDType = typename std::underlying_type<IMedia::MetadataType>::type;
312 313
    if ( m_metadata.isReady() == false )
        m_metadata.init( m_id, IMedia::NbMeta );
314
    return m_metadata.set( static_cast<MDType>( type ), value );
315 316 317 318
}

bool Media::setMetadata( IMedia::MetadataType type, int64_t value )
{
319
    using MDType = typename std::underlying_type<IMedia::MetadataType>::type;
320 321
    if ( m_metadata.isReady() == false )
        m_metadata.init( m_id, IMedia::NbMeta );
322
    return m_metadata.set( static_cast<MDType>( type ), value );
323 324
}

325 326 327 328 329 330 331 332
void Media::setReleaseDate( unsigned int date )
{
    if ( m_releaseDate == date )
        return;
    m_releaseDate = date;
    m_changed = true;
}

333
bool Media::setThumbnail( const std::string& thumbnailMrl, Thumbnail::Origin origin )
334
{
335
    if ( m_thumbnailId != 0 )
336
        return Thumbnail::setMrlFromPrimaryKey( m_ml, m_thumbnail, m_thumbnailId,
337
                                                thumbnailMrl, origin );
338

339 340 341 342
    std::unique_ptr<sqlite::Transaction> t;
    if ( sqlite::Transaction::transactionInProgress() == false )
        t = m_ml->getConn()->newTransaction();
    auto lock = m_thumbnail.lock();
343 344
    auto thumbnail = Thumbnail::create( m_ml, thumbnailMrl, origin );
    if ( thumbnail == nullptr )
345
        return false;
346

347
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET "
348
            "thumbnail_id = ?, thumbnail_generated = 1 WHERE id_media = ?";
349
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, thumbnail->id(), m_id ) == false )
350
        return false;
351
    m_thumbnailId = thumbnail->id();
352
    m_thumbnailGenerated = true;
353
    m_thumbnail = std::move( thumbnail );
354 355
    if ( t != nullptr )
        t->commit();
356 357 358
    return true;
}

359 360 361 362 363
bool Media::setThumbnail( const std::string& thumbnailMrl )
{
    return setThumbnail( thumbnailMrl, Thumbnail::Origin::UserProvided );
}

364 365 366
bool Media::save()
{
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET "
367
            "type = ?, subtype = ?, duration = ?, release_date = ?,"
368
            "title = ? WHERE id_media = ?";
369 370
    if ( m_changed == false )
        return true;
371
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, m_type, m_subType, m_duration,
372
                                       m_releaseDate, m_title, m_id ) == false )
373 374 375 376
    {
        return false;
    }
    m_changed = false;
377 378 379
    return true;
}

380 381
std::shared_ptr<File> Media::addFile( const fs::IFile& fileFs, int64_t parentFolderId,
                                      bool isFolderFsRemovable, IFile::Type type )
382
{
383
    auto file = File::createFromMedia( m_ml, m_id, type, fileFs, parentFolderId, isFolderFsRemovable);
384 385 386 387 388 389
    if ( file == nullptr )
        return nullptr;
    auto lock = m_files.lock();
    if ( m_files.isCached() )
        m_files.get().push_back( file );
    return file;
390 391
}

392
FilePtr Media::addExternalMrl( const std::string& mrl , IFile::Type type )
393
{
394 395 396
    FilePtr file;
    try
    {
397
        file = File::createFromMedia( m_ml, m_id, type, mrl );
398 399 400 401 402 403 404
    }
    catch ( const sqlite::errors::Generic& ex )
    {
        LOG_ERROR( "Failed to add media external MRL: ", ex.what() );
        return nullptr;
    }

405 406 407 408 409 410 411 412
    if ( file == nullptr )
        return nullptr;
    auto lock = m_files.lock();
    if ( m_files.isCached() )
        m_files.get().push_back( file );
    return file;
}

413
void Media::removeFile( File& file )
414
{
415 416 417
    file.destroy();
    auto lock = m_files.lock();
    if ( m_files.isCached() == false )
418
        return;
419
    m_files.get().erase( std::remove_if( begin( m_files.get() ), end( m_files.get() ), [&file]( const FilePtr& f ) {
420 421
        return f->id() == file.id();
    }));
422 423
}

424
std::string Media::sortRequest( const QueryParameters* params )
425
{
426
    std::string req = " ORDER BY ";
427

428 429
    auto sort = params != nullptr ? params->sort : SortingCriteria::Default;
    auto desc = params != nullptr ? params->desc : false;
430 431
    switch ( sort )
    {
432
    case SortingCriteria::Duration:
433
        req += "m.duration";
434
        break;
435
    case SortingCriteria::InsertionDate:
436
        req += "m.insertion_date";
437
        break;
438
    case SortingCriteria::ReleaseDate:
439
        req += "m.release_date";
440
        break;
441
    case SortingCriteria::PlayCount:
442
        req += "m.play_count";
443 444
        desc = !desc; // Make decreasing order default for play count sorting
        break;
445
    case SortingCriteria::Filename:
446 447 448 449 450 451 452
        req += "m.filename";
        break;
    case SortingCriteria::LastModificationDate:
        req += "f.last_modification_date";
        break;
    case SortingCriteria::FileSize:
        req += "f.size";
453
        break;
454
    default:
455
        req += "m.title";
456 457 458 459
        break;
    }
    if ( desc == true )
        req += " DESC";
460 461
    return req;
}
462

463
Query<IMedia> Media::listAll( MediaLibraryPtr ml, IMedia::Type type,
464
                              const QueryParameters* params )
465
{
466
    std::string req = "FROM " + policy::MediaTable::Name + " m INNER JOIN "
467 468 469 470
            + policy::FileTable::Name + " f ON m.id_media = f.media_id"
            " WHERE m.type = ?"
            " AND f.type = ?"
            " AND f.is_present != 0";
471

472
    req += sortRequest( params );
473 474
    return make_query<Media, IMedia>( ml, "m.*", std::move( req ),
                                      type, IFile::Type::Main );
475 476
}

477
int64_t Media::id() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
478 479 480 481
{
    return m_id;
}

482
IMedia::Type Media::type() const
483 484 485 486
{
    return m_type;
}

487
IMedia::SubType Media::subType() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
488 489 490 491
{
    return m_subType;
}

492
void Media::setType( Type type )
493
{
494
    if ( m_type == type )
495
        return;
496
    m_type = type;
497
    m_changed = true;
498 499
}

500
const std::string& Media::title() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
501
{
502
    return m_title;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
503 504
}

505 506 507 508 509
bool Media::setTitle( const std::string& title )
{
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET title = ? WHERE id_media = ?";
    if ( m_title == title )
        return true;
510 511 512 513 514 515 516 517
    try
    {
        if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, title, m_id ) == false )
            return false;
    }
    catch ( const sqlite::errors::Generic& ex )
    {
        LOG_ERROR( "Failed to set media title: ", ex.what() );
518
        return false;
519 520
    }

521 522 523 524
    m_title = title;
    return true;
}

525
void Media::setTitleBuffered( const std::string& title )
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
526
{
527 528
    if ( m_title == title )
        return;
529
    m_title = title;
530
    m_changed = true;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
531 532
}

533
void Media::createTable( sqlite::Connection* connection )
534
{
535 536
    std::string req = "CREATE TABLE IF NOT EXISTS " + policy::MediaTable::Name + "("
            "id_media INTEGER PRIMARY KEY AUTOINCREMENT,"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
537
            "type INTEGER,"
538 539 540
            "subtype INTEGER NOT NULL DEFAULT " +
                std::to_string( static_cast<typename std::underlying_type<IMedia::SubType>::type>(
                                    IMedia::SubType::Unknown ) ) + ","
541
            "duration INTEGER DEFAULT -1,"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
542
            "play_count UNSIGNED INTEGER,"
543
            "last_played_date UNSIGNED INTEGER,"
544
            "insertion_date UNSIGNED INTEGER,"
545
            "release_date UNSIGNED INTEGER,"
546 547
            "thumbnail_id INTEGER,"
            "thumbnail_generated BOOLEAN NOT NULL DEFAULT 0,"
548
            "title TEXT COLLATE NOCASE,"
549
            "filename TEXT,"
550
            "is_favorite BOOLEAN NOT NULL DEFAULT 0,"
551 552 553
            "is_present BOOLEAN NOT NULL DEFAULT 1,"
            "FOREIGN KEY(thumbnail_id) REFERENCES " + policy::ThumbnailTable::Name
            + "(id_thumbnail)"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
554
            ")";
555

556
    const std::string vtableReq = "CREATE VIRTUAL TABLE IF NOT EXISTS "
557
                + policy::MediaTable::Name + "Fts USING FTS3("
558 559
                "title,"
                "labels"
560
            ")";
561 562
    sqlite::Tools::executeRequest( connection, req );
    sqlite::Tools::executeRequest( connection, vtableReq );
563 564
}

565
void Media::createTriggers( sqlite::Connection* connection )
566
{
567 568
    const std::string indexReq = "CREATE INDEX IF NOT EXISTS index_last_played_date ON "
            + policy::MediaTable::Name + "(last_played_date DESC)";
569 570 571 572
    static const std::string triggerReq = "CREATE TRIGGER IF NOT EXISTS has_files_present AFTER UPDATE OF "
            "is_present ON " + policy::FileTable::Name +
            " BEGIN "
            " UPDATE " + policy::MediaTable::Name + " SET is_present="
573 574
                "(SELECT EXISTS("
                    "SELECT id_file FROM " + policy::FileTable::Name +
575
                    " WHERE media_id=new.media_id AND is_present != 0 LIMIT 1"
576
                ") )"
577 578 579 580 581 582 583 584 585
                "WHERE id_media=new.media_id;"
            " END;";
    static const std::string triggerReq2 = "CREATE TRIGGER IF NOT EXISTS cascade_file_deletion AFTER DELETE ON "
            + policy::FileTable::Name +
            " BEGIN "
            " DELETE FROM " + policy::MediaTable::Name + " WHERE "
                "(SELECT COUNT(id_file) FROM " + policy::FileTable::Name + " WHERE media_id=old.media_id) = 0"
                " AND id_media=old.media_id;"
            " END;";
586 587 588 589

    static const std::string vtableInsertTrigger = "CREATE TRIGGER IF NOT EXISTS insert_media_fts"
            " AFTER INSERT ON " + policy::MediaTable::Name +
            " BEGIN"
590
            " INSERT INTO " + policy::MediaTable::Name + "Fts(rowid,title,labels) VALUES(new.id_media, new.title, '');"
591 592
            " END";
    static const std::string vtableDeleteTrigger = "CREATE TRIGGER IF NOT EXISTS delete_media_fts"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
593
            " BEFORE DELETE ON " + policy::MediaTable::Name +
594 595 596 597 598 599 600 601
            " BEGIN"
            " DELETE FROM " + policy::MediaTable::Name + "Fts WHERE rowid = old.id_media;"
            " END";
    static const std::string vtableUpdateTitleTrigger2 = "CREATE TRIGGER IF NOT EXISTS update_media_title_fts"
              " AFTER UPDATE OF title ON " + policy::MediaTable::Name +
              " BEGIN"
              " UPDATE " + policy::MediaTable::Name + "Fts SET title = new.title WHERE rowid = new.id_media;"
              " END";
602 603

    sqlite::Tools::executeRequest( connection, indexReq );
604 605 606 607 608
    sqlite::Tools::executeRequest( connection, triggerReq );
    sqlite::Tools::executeRequest( connection, triggerReq2 );
    sqlite::Tools::executeRequest( connection, vtableInsertTrigger );
    sqlite::Tools::executeRequest( connection, vtableDeleteTrigger );
    sqlite::Tools::executeRequest( connection, vtableUpdateTitleTrigger2 );
609
}
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
610

611
bool Media::addLabel( LabelPtr label )
612
{
613
    if ( m_id == 0 || label->id() == 0 )
614
    {
615
        LOG_ERROR( "Both file & label need to be inserted in database before being linked together" );
616 617
        return false;
    }
618 619
    try
    {
620 621 622 623 624 625 626 627 628 629 630 631 632
        return sqlite::Tools::withRetries( 3, [this]( LabelPtr label ) {
            auto t = m_ml->getConn()->newTransaction();

            const char* req = "INSERT INTO LabelFileRelation VALUES(?, ?)";
            if ( sqlite::Tools::executeInsert( m_ml->getConn(), req, label->id(), m_id ) == 0 )
                return false;
            const std::string reqFts = "UPDATE " + policy::MediaTable::Name + "Fts "
                "SET labels = labels || ' ' || ? WHERE rowid = ?";
            if ( sqlite::Tools::executeUpdate( m_ml->getConn(), reqFts, label->name(), m_id ) == false )
                return false;
            t->commit();
            return true;
        }, std::move( label ) );
633 634 635 636
    }
    catch ( const sqlite::errors::Generic& ex )
    {
        LOG_ERROR( "Failed to add label: ", ex.what() );
637
        return false;
638
    }
639 640
}

641
bool Media::removeLabel( LabelPtr label )
642
{
643
    if ( m_id == 0 || label->id() == 0 )
644
    {
645
        LOG_ERROR( "Can't unlink a label/file not inserted in database" );
646 647
        return false;
    }
648 649
    try
    {
650 651 652 653 654 655 656 657 658 659 660 661 662
        return sqlite::Tools::withRetries( 3, [this]( LabelPtr label ) {
            auto t = m_ml->getConn()->newTransaction();

            const char* req = "DELETE FROM LabelFileRelation WHERE label_id = ? AND media_id = ?";
            if ( sqlite::Tools::executeDelete( m_ml->getConn(), req, label->id(), m_id ) == false )
                return false;
            const std::string reqFts = "UPDATE " + policy::MediaTable::Name + "Fts "
                    "SET labels = TRIM(REPLACE(labels, ?, '')) WHERE rowid = ?";
            if ( sqlite::Tools::executeUpdate( m_ml->getConn(), reqFts, label->name(), m_id ) == false )
                return false;
            t->commit();
            return true;
        }, std::move( label ) );
663 664 665 666
    }
    catch ( const sqlite::errors::Generic& ex )
    {
        LOG_ERROR( "Failed to remove label: ", ex.what() );
667
        return false;
668
    }
669
}
670

671
Query<IMedia> Media::search( MediaLibraryPtr ml, const std::string& title,
672
                             Media::SubType subType, const QueryParameters* params )
673
{
674
    std::string req = "FROM " + policy::MediaTable::Name + " m "
675 676 677
            " INNER JOIN " + policy::FileTable::Name + " f ON m.id_media = f.media_id"
            " WHERE"
            " m.id_media IN (SELECT rowid FROM " + policy::MediaTable::Name + "Fts"
678
            " WHERE " + policy::MediaTable::Name + "Fts MATCH '*' || ? || '*')"
679
            " AND f.is_present = 1"
680 681
            " AND f.type = ?"
            " AND m.subtype = ?";
682
    req += sortRequest( params );
683
    return make_query<Media, IMedia>( ml, "m.*", req, title, File::Type::Main, subType );
684
}
685

686
Query<IMedia> Media::fetchHistory( MediaLibraryPtr ml )
687
{
688
    static const std::string req = "FROM " + policy::MediaTable::Name + " WHERE last_played_date IS NOT NULL"
689
            " ORDER BY last_played_date DESC LIMIT 100";
690
    return make_query<Media, IMedia>( ml, "*", req );
691
}
692

693
void Media::clearHistory( MediaLibraryPtr ml )
694 695
{
    auto dbConn = ml->getConn();
696 697
    // There should already be an active transaction, from MediaLibrary::clearHistory
    assert( sqlite::Transaction::transactionInProgress() == true );
698 699
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET "
            "play_count = 0,"
700
            "last_played_date = NULL";
701 702
    // Clear the entire cache since quite a few items are now containing invalid info.
    clear();
703 704 705 706 707

    using MDType = typename std::underlying_type<IMedia::MetadataType>::type;
    Metadata::unset( dbConn, IMetadata::EntityType::Media,
                     static_cast<MDType>( IMedia::MetadataType::Progress ) );

708
    sqlite::Tools::executeUpdate( dbConn, req );
709 710
}

711
}