Media.cpp 24.9 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
const std::string policy::MediaMetadataTable::Name = "MediaMetadata";

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

82 83 84
Media::Media( MediaLibraryPtr ml, const std::string& title, Type type )
    : m_ml( ml )
    , m_id( 0 )
85
    , m_type( type )
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
86
    , m_subType( SubType::Unknown )
87
    , m_duration( -1 )
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
88
    , m_playCount( 0 )
89
    , m_lastPlayedDate( 0 )
90
    , m_insertionDate( time( nullptr ) )
91
    , m_releaseDate( 0 )
92 93
    , m_thumbnailId( 0 )
    , m_thumbnailGenerated( false )
94
    , m_title( title )
95 96
    // When creating a Media, meta aren't parsed, and therefor, is the filename
    , m_filename( title )
97
    , m_isFavorite( false )
98
    , m_isPresent( true )
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()
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()
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 302 303 304 305 306
const IMediaMetadata& Media::metadata( IMedia::MetadataType type ) const
{
    auto lock = m_metadata.lock();
    if ( m_metadata.isCached() == false )
    {
        std::vector<MediaMetadata> res;
307 308 309 310 311
        // Reserve the space for all meta to avoid a race condition where 2 threads
        // would cache different meta, invalidating the potential reference
        // to another IMediaMetadata held by another thread.
        // This guarantees the vector will not grow afterward.
        res.reserve( IMedia::NbMeta );
312 313
        static const std::string req = "SELECT * FROM " + policy::MediaMetadataTable::Name +
                " WHERE id_media = ?";
314 315
        auto conn = m_ml->getConn();
        auto ctx = conn->acquireReadContext();
316
        sqlite::Statement stmt( conn->handle(), req );
317 318 319 320 321 322 323
        stmt.execute( m_id );
        for ( sqlite::Row row = stmt.row(); row != nullptr; row = stmt.row() )
        {
            assert( row.load<int64_t>( 0 ) == m_id );
            res.emplace_back( row.load<decltype(MediaMetadata::m_type)>( 1 ),
                              row.load<decltype(MediaMetadata::m_value)>( 2 ) );
        }
324
        m_metadata = std::move( res );
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    }
    auto it = std::find_if( begin( m_metadata.get() ), end( m_metadata.get() ), [type](const MediaMetadata& m ) {
        return m.m_type == type;
    });
    if ( it == end( m_metadata.get() ) )
    {
        m_metadata.get().emplace_back( type );
        return *m_metadata.get().rbegin();
    }
    return (*it);
}

bool Media::setMetadata( IMedia::MetadataType type, const std::string& value )
{
    {
        auto lock = m_metadata.lock();
        if ( m_metadata.isCached() == true )
        {
            auto it = std::find_if( begin( m_metadata.get() ), end( m_metadata.get() ), [type](const MediaMetadata& m ) {
                return m.m_type == type;
            });
            if ( it != end( m_metadata.get() ) )
347
                (*it).set( value );
348 349 350 351
            else
                m_metadata.get().emplace_back( type, value );
        }
    }
352 353 354 355 356 357 358 359 360 361 362
    try
    {
        static const std::string req = "INSERT OR REPLACE INTO " + policy::MediaMetadataTable::Name +
                "(id_media, type, value) VALUES(?, ?, ?)";
        return sqlite::Tools::executeInsert( m_ml->getConn(), req, m_id, type, value );
    }
    catch ( const sqlite::errors::Generic& ex )
    {
        LOG_ERROR( "Failed to update media metadata: ", ex.what() );
        return false;
    }
363 364 365 366 367 368 369 370
}

bool Media::setMetadata( IMedia::MetadataType type, int64_t value )
{
    auto str = std::to_string( value );
    return setMetadata( type, str );
}

371 372 373 374 375 376 377 378
void Media::setReleaseDate( unsigned int date )
{
    if ( m_releaseDate == date )
        return;
    m_releaseDate = date;
    m_changed = true;
}

379
bool Media::setThumbnail( const std::string& thumbnailMrl, Thumbnail::Origin origin )
380
{
381
    if ( m_thumbnailId != 0 )
382
        return Thumbnail::setMrlFromPrimaryKey( m_ml, m_thumbnail, m_thumbnailId,
383
                                                thumbnailMrl, origin );
384

385 386 387 388
    std::unique_ptr<sqlite::Transaction> t;
    if ( sqlite::Transaction::transactionInProgress() == false )
        t = m_ml->getConn()->newTransaction();
    auto lock = m_thumbnail.lock();
389 390
    auto thumbnail = Thumbnail::create( m_ml, thumbnailMrl, origin );
    if ( thumbnail == nullptr )
391
        return false;
392

393
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET "
394
            "thumbnail_id = ?, thumbnail_generated = 1 WHERE id_media = ?";
395
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, thumbnail->id(), m_id ) == false )
396
        return false;
397
    m_thumbnailId = thumbnail->id();
398
    m_thumbnailGenerated = true;
399
    m_thumbnail = std::move( thumbnail );
400 401
    if ( t != nullptr )
        t->commit();
402 403 404
    return true;
}

405 406 407 408 409
bool Media::setThumbnail( const std::string& thumbnailMrl )
{
    return setThumbnail( thumbnailMrl, Thumbnail::Origin::UserProvided );
}

410 411 412
bool Media::save()
{
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET "
413
            "type = ?, subtype = ?, duration = ?, release_date = ?,"
414
            "title = ? WHERE id_media = ?";
415 416
    if ( m_changed == false )
        return true;
417
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, m_type, m_subType, m_duration,
418
                                       m_releaseDate, m_title, m_id ) == false )
419 420 421 422
    {
        return false;
    }
    m_changed = false;
423 424 425
    return true;
}

426 427
std::shared_ptr<File> Media::addFile( const fs::IFile& fileFs, int64_t parentFolderId,
                                      bool isFolderFsRemovable, IFile::Type type )
428
{
429
    auto file = File::createFromMedia( m_ml, m_id, type, fileFs, parentFolderId, isFolderFsRemovable);
430 431 432 433 434 435
    if ( file == nullptr )
        return nullptr;
    auto lock = m_files.lock();
    if ( m_files.isCached() )
        m_files.get().push_back( file );
    return file;
436 437
}

438
FilePtr Media::addExternalMrl( const std::string& mrl , IFile::Type type )
439
{
440 441 442
    FilePtr file;
    try
    {
443
        file = File::createFromMedia( m_ml, m_id, type, mrl );
444 445 446 447 448 449 450
    }
    catch ( const sqlite::errors::Generic& ex )
    {
        LOG_ERROR( "Failed to add media external MRL: ", ex.what() );
        return nullptr;
    }

451 452 453 454 455 456 457 458
    if ( file == nullptr )
        return nullptr;
    auto lock = m_files.lock();
    if ( m_files.isCached() )
        m_files.get().push_back( file );
    return file;
}

459
void Media::removeFile( File& file )
460
{
461 462 463
    file.destroy();
    auto lock = m_files.lock();
    if ( m_files.isCached() == false )
464
        return;
465
    m_files.get().erase( std::remove_if( begin( m_files.get() ), end( m_files.get() ), [&file]( const FilePtr& f ) {
466 467
        return f->id() == file.id();
    }));
468 469
}

470
std::string Media::sortRequest( const QueryParameters* params )
471
{
472
    std::string req = " ORDER BY ";
473

474 475
    auto sort = params != nullptr ? params->sort : SortingCriteria::Default;
    auto desc = params != nullptr ? params->desc : false;
476 477
    switch ( sort )
    {
478
    case SortingCriteria::Duration:
479
        req += "m.duration";
480
        break;
481
    case SortingCriteria::InsertionDate:
482
        req += "m.insertion_date";
483
        break;
484
    case SortingCriteria::ReleaseDate:
485
        req += "m.release_date";
486
        break;
487
    case SortingCriteria::PlayCount:
488
        req += "m.play_count";
489 490
        desc = !desc; // Make decreasing order default for play count sorting
        break;
491
    case SortingCriteria::Filename:
492 493 494 495 496 497 498
        req += "m.filename";
        break;
    case SortingCriteria::LastModificationDate:
        req += "f.last_modification_date";
        break;
    case SortingCriteria::FileSize:
        req += "f.size";
499
        break;
500
    default:
501
        req += "m.title";
502 503 504 505
        break;
    }
    if ( desc == true )
        req += " DESC";
506 507
    return req;
}
508

509
Query<IMedia> Media::listAll( MediaLibraryPtr ml, IMedia::Type type,
510
                              const QueryParameters* params )
511
{
512
    std::string req = "FROM " + policy::MediaTable::Name + " m INNER JOIN "
513 514 515 516
            + policy::FileTable::Name + " f ON m.id_media = f.media_id"
            " WHERE m.type = ?"
            " AND f.type = ?"
            " AND f.is_present != 0";
517

518
    req += sortRequest( params );
519 520
    return make_query<Media, IMedia>( ml, "m.*", std::move( req ),
                                      type, IFile::Type::Main );
521 522
}

523
int64_t Media::id() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
524 525 526 527
{
    return m_id;
}

528
IMedia::Type Media::type() const
529 530 531 532
{
    return m_type;
}

533
IMedia::SubType Media::subType() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
534 535 536 537
{
    return m_subType;
}

538
void Media::setType( Type type )
539
{
540
    if ( m_type == type )
541
        return;
542
    m_type = type;
543
    m_changed = true;
544 545
}

546
const std::string& Media::title() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
547
{
548
    return m_title;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
549 550
}

551 552 553 554 555
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;
556 557 558 559 560 561 562 563
    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() );
564
        return false;
565 566
    }

567 568 569 570
    m_title = title;
    return true;
}

571
void Media::setTitleBuffered( const std::string& title )
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
572
{
573 574
    if ( m_title == title )
        return;
575
    m_title = title;
576
    m_changed = true;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
577 578
}

579
void Media::createTable( sqlite::Connection* connection )
580
{
581 582
    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
583
            "type INTEGER,"
584 585 586
            "subtype INTEGER NOT NULL DEFAULT " +
                std::to_string( static_cast<typename std::underlying_type<IMedia::SubType>::type>(
                                    IMedia::SubType::Unknown ) ) + ","
587
            "duration INTEGER DEFAULT -1,"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
588
            "play_count UNSIGNED INTEGER,"
589
            "last_played_date UNSIGNED INTEGER,"
590
            "insertion_date UNSIGNED INTEGER,"
591
            "release_date UNSIGNED INTEGER,"
592 593
            "thumbnail_id INTEGER,"
            "thumbnail_generated BOOLEAN NOT NULL DEFAULT 0,"
594
            "title TEXT COLLATE NOCASE,"
595
            "filename TEXT,"
596
            "is_favorite BOOLEAN NOT NULL DEFAULT 0,"
597 598 599
            "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
600
            ")";
601

602
    const std::string vtableReq = "CREATE VIRTUAL TABLE IF NOT EXISTS "
603
                + policy::MediaTable::Name + "Fts USING FTS3("
604 605
                "title,"
                "labels"
606
            ")";
607 608 609 610 611 612
    const std::string metadataReq = "CREATE TABLE IF NOT EXISTS " + policy::MediaMetadataTable::Name + "("
            "id_media INTEGER,"
            "type INTEGER,"
            "value TEXT,"
            "PRIMARY KEY (id_media, type)"
            ")";
613 614 615
    sqlite::Tools::executeRequest( connection, req );
    sqlite::Tools::executeRequest( connection, vtableReq );
    sqlite::Tools::executeRequest( connection, metadataReq );
616 617
}

618
void Media::createTriggers( sqlite::Connection* connection )
619
{
620 621
    const std::string indexReq = "CREATE INDEX IF NOT EXISTS index_last_played_date ON "
            + policy::MediaTable::Name + "(last_played_date DESC)";
622 623 624 625
    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="
626 627
                "(SELECT EXISTS("
                    "SELECT id_file FROM " + policy::FileTable::Name +
628
                    " WHERE media_id=new.media_id AND is_present != 0 LIMIT 1"
629
                ") )"
630 631 632 633 634 635 636 637 638
                "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;";
639 640 641 642

    static const std::string vtableInsertTrigger = "CREATE TRIGGER IF NOT EXISTS insert_media_fts"
            " AFTER INSERT ON " + policy::MediaTable::Name +
            " BEGIN"
643
            " INSERT INTO " + policy::MediaTable::Name + "Fts(rowid,title,labels) VALUES(new.id_media, new.title, '');"
644 645
            " 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
646
            " BEFORE DELETE ON " + policy::MediaTable::Name +
647 648 649 650 651 652 653 654
            " 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";
655 656

    sqlite::Tools::executeRequest( connection, indexReq );
657 658 659 660 661
    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 );
662
}
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
663

664
bool Media::addLabel( LabelPtr label )
665
{
666
    if ( m_id == 0 || label->id() == 0 )
667
    {
668
        LOG_ERROR( "Both file & label need to be inserted in database before being linked together" );
669 670
        return false;
    }
671 672
    try
    {
673 674 675 676 677 678 679 680 681 682 683 684 685
        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 ) );
686 687 688 689
    }
    catch ( const sqlite::errors::Generic& ex )
    {
        LOG_ERROR( "Failed to add label: ", ex.what() );
690
        return false;
691
    }
692 693
}

694
bool Media::removeLabel( LabelPtr label )
695
{
696
    if ( m_id == 0 || label->id() == 0 )
697
    {
698
        LOG_ERROR( "Can't unlink a label/file not inserted in database" );
699 700
        return false;
    }
701 702
    try
    {
703 704 705 706 707 708 709 710 711 712 713 714 715
        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 ) );
716 717 718 719
    }
    catch ( const sqlite::errors::Generic& ex )
    {
        LOG_ERROR( "Failed to remove label: ", ex.what() );
720
        return false;
721
    }
722
}
723

724
Query<IMedia> Media::search( MediaLibraryPtr ml, const std::string& title,
725
                             Media::SubType subType, const QueryParameters* params )
726
{
727
    std::string req = "FROM " + policy::MediaTable::Name + " m "
728 729 730
            " 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"
731
            " WHERE " + policy::MediaTable::Name + "Fts MATCH '*' || ? || '*')"
732
            " AND f.is_present = 1"
733 734
            " AND f.type = ?"
            " AND m.subtype = ?";
735
    req += sortRequest( params );
736
    return make_query<Media, IMedia>( ml, "m.*", req, title, File::Type::Main, subType );
737
}
738

739
Query<IMedia> Media::fetchHistory( MediaLibraryPtr ml )
740
{
741
    static const std::string req = "FROM " + policy::MediaTable::Name + " WHERE last_played_date IS NOT NULL"
742
            " ORDER BY last_played_date DESC LIMIT 100";
743
    return make_query<Media, IMedia>( ml, "*", req );
744
}
745

746
void Media::clearHistory( MediaLibraryPtr ml )
747 748
{
    auto dbConn = ml->getConn();
749 750
    // There should already be an active transaction, from MediaLibrary::clearHistory
    assert( sqlite::Transaction::transactionInProgress() == true );
751 752
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET "
            "play_count = 0,"
753 754 755
            "last_played_date = NULL";
    static const std::string flushProgress = "DELETE FROM " + policy::MediaMetadataTable::Name +
            " WHERE type = ?";
756 757
    // Clear the entire cache since quite a few items are now containing invalid info.
    clear();
758
    sqlite::Tools::executeUpdate( dbConn, req );
759
    sqlite::Tools::executeDelete( dbConn, flushProgress, IMedia::MetadataType::Progress );
760 761
}

762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
bool Media::MediaMetadata::isSet() const
{
    return m_isSet;
}

int64_t Media::MediaMetadata::integer() const
{
    return atoll( m_value.c_str() );
}

const std::string& Media::MediaMetadata::str() const
{
    return m_value;
}

777 778 779 780 781 782
void Media::MediaMetadata::set( const std::string& value )
{
    m_value = value;
    m_isSet = true;
}

783
}