Media.cpp 24.7 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
MoviePtr Media::movie() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
219
{
220 221 222
    if ( m_subType != SubType::Movie )
        return nullptr;

223 224
    auto lock = m_movie.lock();

225
    if ( m_movie.isCached() == false )
226
        m_movie = Movie::fromMedia( m_ml, m_id );
227
    return m_movie.get();
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
228 229
}

230
void Media::setMovie(MoviePtr movie)
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
231
{
232
    auto lock = m_movie.lock();
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
233
    m_movie = movie;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
234 235
    m_subType = SubType::Movie;
    m_changed = true;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
236 237
}

238 239
bool Media::addVideoTrack(const std::string& codec, unsigned int width, unsigned int height, float fps,
                          const std::string& language, const std::string& description )
240
{
241
    return VideoTrack::create( m_ml, codec, width, height, fps, m_id, language, description ) != nullptr;
242 243
}

244
Query<IVideoTrack> Media::videoTracks()
245
{
246
    static const std::string req = "FROM " + policy::VideoTrackTable::Name +
247
            " WHERE media_id = ?";
248
    return make_query<VideoTrack, IVideoTrack>( m_ml, "*", req, m_id );
249 250
}

251
bool Media::addAudioTrack( const std::string& codec, unsigned int bitrate,
252 253
                          unsigned int sampleRate, unsigned int nbChannels,
                          const std::string& language, const std::string& desc )
254
{
255
    return AudioTrack::create( m_ml, codec, bitrate, sampleRate, nbChannels, language, desc, m_id ) != nullptr;
256 257
}

258
Query<IAudioTrack> Media::audioTracks()
259
{
260
    static const std::string req = "FROM " + policy::AudioTrackTable::Name +
261
            " WHERE media_id = ?";
262
    return make_query<AudioTrack, IAudioTrack>( m_ml, "*", req, m_id );
263 264
}

265
const std::string& Media::thumbnail()
266
{
267
    if ( m_thumbnailId == 0 || m_thumbnailGenerated == false )
268 269
        return Thumbnail::EmptyMrl;

270 271
    auto lock = m_thumbnail.lock();
    if ( m_thumbnail.isCached() == false )
272 273 274 275 276 277
    {
        auto thumbnail = Thumbnail::fetch( m_ml, m_thumbnailId );
        if ( thumbnail == nullptr )
            return Thumbnail::EmptyMrl;
        m_thumbnail = std::move( thumbnail );
    }
278 279 280 281 282 283
    return m_thumbnail.get()->mrl();
}

bool Media::isThumbnailGenerated() const
{
    return m_thumbnailGenerated;
284 285
}

286 287
unsigned int Media::insertionDate() const
{
288
    return static_cast<unsigned int>( m_insertionDate );
289 290
}

291 292 293 294 295
unsigned int Media::releaseDate() const
{
    return m_releaseDate;
}

296 297 298 299 300 301
const IMediaMetadata& Media::metadata( IMedia::MetadataType type ) const
{
    auto lock = m_metadata.lock();
    if ( m_metadata.isCached() == false )
    {
        std::vector<MediaMetadata> res;
302 303 304 305 306
        // 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 );
307 308
        static const std::string req = "SELECT * FROM " + policy::MediaMetadataTable::Name +
                " WHERE id_media = ?";
309 310
        auto conn = m_ml->getConn();
        auto ctx = conn->acquireReadContext();
311
        sqlite::Statement stmt( conn->handle(), req );
312 313 314 315 316 317 318
        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 ) );
        }
319
        m_metadata = std::move( res );
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    }
    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() ) )
342
                (*it).set( value );
343 344 345 346
            else
                m_metadata.get().emplace_back( type, value );
        }
    }
347 348 349 350 351 352 353 354 355 356 357
    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;
    }
358 359 360 361 362 363 364 365
}

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

366 367 368 369 370 371 372 373
void Media::setReleaseDate( unsigned int date )
{
    if ( m_releaseDate == date )
        return;
    m_releaseDate = date;
    m_changed = true;
}

374
bool Media::setThumbnail( const std::string& thumbnailMrl, Thumbnail::Origin origin )
375
{
376
    if ( m_thumbnailId != 0 )
377
        return Thumbnail::setMrlFromPrimaryKey( m_ml, m_thumbnail, m_thumbnailId,
378
                                                thumbnailMrl, origin );
379

380 381 382 383
    std::unique_ptr<sqlite::Transaction> t;
    if ( sqlite::Transaction::transactionInProgress() == false )
        t = m_ml->getConn()->newTransaction();
    auto lock = m_thumbnail.lock();
384 385
    auto thumbnail = Thumbnail::create( m_ml, thumbnailMrl, origin );
    if ( thumbnail == nullptr )
386
        return false;
387

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

400 401 402 403 404
bool Media::setThumbnail( const std::string& thumbnailMrl )
{
    return setThumbnail( thumbnailMrl, Thumbnail::Origin::UserProvided );
}

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

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

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

446 447 448 449 450 451 452 453
    if ( file == nullptr )
        return nullptr;
    auto lock = m_files.lock();
    if ( m_files.isCached() )
        m_files.get().push_back( file );
    return file;
}

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

465
std::string Media::sortRequest( SortingCriteria sort, bool desc )
466
{
467
    std::string req = " ORDER BY ";
468

469 470
    switch ( sort )
    {
471
    case SortingCriteria::Duration:
472
        req += "m.duration";
473
        break;
474
    case SortingCriteria::InsertionDate:
475
        req += "m.insertion_date";
476
        break;
477
    case SortingCriteria::ReleaseDate:
478
        req += "m.release_date";
479
        break;
480
    case SortingCriteria::PlayCount:
481
        req += "m.play_count";
482 483
        desc = !desc; // Make decreasing order default for play count sorting
        break;
484
    case SortingCriteria::Filename:
485 486 487 488 489 490 491
        req += "m.filename";
        break;
    case SortingCriteria::LastModificationDate:
        req += "f.last_modification_date";
        break;
    case SortingCriteria::FileSize:
        req += "f.size";
492
        break;
493
    default:
494
        req += "m.title";
495 496 497 498
        break;
    }
    if ( desc == true )
        req += " DESC";
499 500
    return req;
}
501

502
Query<IMedia> Media::listAll( MediaLibraryPtr ml, IMedia::Type type,
503 504
                                      SortingCriteria sort, bool desc )
{
505
    std::string req = "FROM " + policy::MediaTable::Name + " m INNER JOIN "
506 507 508 509
            + policy::FileTable::Name + " f ON m.id_media = f.media_id"
            " WHERE m.type = ?"
            " AND f.type = ?"
            " AND f.is_present != 0";
510

511
    req += sortRequest( sort, desc );
512 513
    return make_query<Media, IMedia>( ml, "m.*", std::move( req ),
                                      type, IFile::Type::Main );
514 515
}

516
int64_t Media::id() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
517 518 519 520
{
    return m_id;
}

521
IMedia::Type Media::type()
522 523 524 525
{
    return m_type;
}

526
IMedia::SubType Media::subType() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
527 528 529 530
{
    return m_subType;
}

531
void Media::setType( Type type )
532
{
533
    if ( m_type == type )
534
        return;
535
    m_type = type;
536
    m_changed = true;
537 538
}

539
const std::string& Media::title() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
540
{
541
    return m_title;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
542 543
}

544 545 546 547 548
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;
549 550 551 552 553 554 555 556
    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() );
557
        return false;
558 559
    }

560 561 562 563
    m_title = title;
    return true;
}

564
void Media::setTitleBuffered( const std::string& title )
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
565
{
566 567
    if ( m_title == title )
        return;
568
    m_title = title;
569
    m_changed = true;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
570 571
}

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

595
    const std::string vtableReq = "CREATE VIRTUAL TABLE IF NOT EXISTS "
596
                + policy::MediaTable::Name + "Fts USING FTS3("
597 598
                "title,"
                "labels"
599
            ")";
600 601 602 603 604 605
    const std::string metadataReq = "CREATE TABLE IF NOT EXISTS " + policy::MediaMetadataTable::Name + "("
            "id_media INTEGER,"
            "type INTEGER,"
            "value TEXT,"
            "PRIMARY KEY (id_media, type)"
            ")";
606 607 608
    sqlite::Tools::executeRequest( connection, req );
    sqlite::Tools::executeRequest( connection, vtableReq );
    sqlite::Tools::executeRequest( connection, metadataReq );
609 610
}

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

    static const std::string vtableInsertTrigger = "CREATE TRIGGER IF NOT EXISTS insert_media_fts"
            " AFTER INSERT ON " + policy::MediaTable::Name +
            " BEGIN"
636
            " INSERT INTO " + policy::MediaTable::Name + "Fts(rowid,title,labels) VALUES(new.id_media, new.title, '');"
637 638
            " 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
639
            " BEFORE DELETE ON " + policy::MediaTable::Name +
640 641 642 643 644 645 646 647
            " 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";
648 649

    sqlite::Tools::executeRequest( connection, indexReq );
650 651 652 653 654
    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 );
655
}
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
656

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

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

717 718
Query<IMedia> Media::search( MediaLibraryPtr ml, const std::string& title,
                             Media::SubType subType, SortingCriteria sort, bool desc )
719
{
720
    std::string req = "FROM " + policy::MediaTable::Name + " m "
721 722 723
            " 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"
724
            " WHERE " + policy::MediaTable::Name + "Fts MATCH '*' || ? || '*')"
725
            " AND f.is_present = 1"
726 727
            " AND f.type = ?"
            " AND m.subtype = ?";
728
    req += sortRequest( sort, desc );
729
    return make_query<Media, IMedia>( ml, "m.*", req, title, File::Type::Main, subType );
730
}
731

732
Query<IMedia> Media::fetchHistory( MediaLibraryPtr ml )
733
{
734
    static const std::string req = "FROM " + policy::MediaTable::Name + " WHERE last_played_date IS NOT NULL"
735
            " ORDER BY last_played_date DESC LIMIT 100";
736
    return make_query<Media, IMedia>( ml, "*", req );
737
}
738

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

755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
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;
}

770 771 772 773 774 775
void Media::MediaMetadata::set( const std::string& value )
{
    m_value = value;
    m_isSet = true;
}

776
}