Media.cpp 20.3 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
#include "database/SqliteTools.h"
45
#include "VideoTrack.h"
46
#include "filesystem/IFile.h"
47 48
#include "filesystem/IDirectory.h"
#include "filesystem/IDevice.h"
49
#include "utils/Filename.h"
50

51 52 53
namespace medialibrary
{

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

58 59
const std::string policy::MediaMetadataTable::Name = "MediaMetadata";

60 61
Media::Media( MediaLibraryPtr ml, sqlite::Row& row )
    : m_ml( ml )
62
    , m_changed( false )
63
{
64 65
    row >> m_id
        >> m_type
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
66
        >> m_subType
67 68
        >> m_duration
        >> m_playCount
69
        >> m_lastPlayedDate
70 71
        >> m_progress
        >> m_rating
72
        >> m_insertionDate
73
        >> m_releaseDate
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
74
        >> m_thumbnail
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 90
    , m_progress( .0f )
    , m_rating( -1 )
91
    , m_insertionDate( time( nullptr ) )
92
    , m_releaseDate( 0 )
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_changed( false )
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
99
{
100 101
}

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

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

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

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

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

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

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

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

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

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

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

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

177
bool Media::increasePlayCount()
178
{
179 180 181 182 183
    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;
184
    m_playCount++;
185 186
    m_lastPlayedDate = lastPlayedDate;
    return true;
187 188
}

189 190 191 192 193
float Media::progress() const
{
    return m_progress;
}

194
bool Media::setProgress( float progress )
195
{
196
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET progress = ? WHERE id_media = ?";
197
    if ( progress == m_progress || progress < 0 || progress > 1.0 )
198 199 200
        return true;
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, progress, m_id ) == false )
        return false;
201
    m_progress = progress;
202
    return true;
203 204 205 206 207 208 209
}

int Media::rating() const
{
    return m_rating;
}

210
bool Media::setRating( int rating )
211
{
212
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET rating = ? WHERE id_media = ?";
213
    if ( m_rating == rating )
214 215 216
        return true;
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, rating, m_id ) == false )
        return false;
217
    m_rating = rating;
218
    return true;
219 220
}

221 222 223 224 225
bool Media::isFavorite() const
{
    return m_isFavorite;
}

226
bool Media::setFavorite( bool favorite )
227
{
228
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET is_favorite = ? WHERE id_media = ?";
229
    if ( m_isFavorite == favorite )
230 231 232
        return true;
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, favorite, m_id ) == false )
        return false;
233
    m_isFavorite = favorite;
234
    return true;
235 236
}

237
const std::vector<FilePtr>& Media::files() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
238
{
239 240 241 242 243
    auto lock = m_files.lock();
    if ( m_files.isCached() == false )
    {
        static const std::string req = "SELECT * FROM " + policy::FileTable::Name
                + " WHERE media_id = ?";
244
        m_files = File::fetchAll<IFile>( m_ml, req, m_id );
245 246
    }
    return m_files;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
247 248
}

249
MoviePtr Media::movie() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
250
{
251 252 253
    if ( m_subType != SubType::Movie )
        return nullptr;

254 255
    auto lock = m_movie.lock();

256
    if ( m_movie.isCached() == false )
257
        m_movie = Movie::fromMedia( m_ml, m_id );
258
    return m_movie.get();
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
259 260
}

261
void Media::setMovie(MoviePtr movie)
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
262
{
263
    auto lock = m_movie.lock();
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
264
    m_movie = movie;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
265 266
    m_subType = SubType::Movie;
    m_changed = true;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
267 268
}

269 270
bool Media::addVideoTrack(const std::string& codec, unsigned int width, unsigned int height, float fps,
                          const std::string& language, const std::string& description )
271
{
272
    return VideoTrack::create( m_ml, codec, width, height, fps, m_id, language, description ) != nullptr;
273 274
}

275
std::vector<VideoTrackPtr> Media::videoTracks()
276
{
277 278
    static const std::string req = "SELECT * FROM " + policy::VideoTrackTable::Name +
            " WHERE media_id = ?";
279
    return VideoTrack::fetchAll<IVideoTrack>( m_ml, req, m_id );
280 281
}

282
bool Media::addAudioTrack( const std::string& codec, unsigned int bitrate,
283 284
                          unsigned int sampleRate, unsigned int nbChannels,
                          const std::string& language, const std::string& desc )
285
{
286
    return AudioTrack::create( m_ml, codec, bitrate, sampleRate, nbChannels, language, desc, m_id ) != nullptr;
287 288
}

289
std::vector<AudioTrackPtr> Media::audioTracks()
290
{
291 292
    static const std::string req = "SELECT * FROM " + policy::AudioTrackTable::Name +
            " WHERE media_id = ?";
293
    return AudioTrack::fetchAll<IAudioTrack>( m_ml, req, m_id );
294 295
}

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
296
const std::string &Media::thumbnail()
297
{
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
298
    return m_thumbnail;
299 300
}

301 302 303 304 305
unsigned int Media::insertionDate() const
{
    return m_insertionDate;
}

306 307 308 309 310
unsigned int Media::releaseDate() const
{
    return m_releaseDate;
}

311 312 313 314 315 316 317 318 319 320 321 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
const IMediaMetadata& Media::metadata( IMedia::MetadataType type ) const
{
    auto lock = m_metadata.lock();
    if ( m_metadata.isCached() == false )
    {
        std::vector<MediaMetadata> res;
        static const std::string req = "SELECT * FROM " + policy::MediaMetadataTable::Name +
                " WHERE id_media = ?";
        sqlite::Statement stmt( m_ml->getConn()->getConn(), req );
        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 ) );
        }
        m_metadata = res;
    }
    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() ) )
                (*it).m_value = value;
            else
                m_metadata.get().emplace_back( type, value );
        }
    }
    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 );
}

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;
}

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
374
void Media::setThumbnail(const std::string& thumbnail )
375
{
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
376
    if ( m_thumbnail == thumbnail )
377
        return;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
378
    m_thumbnail = thumbnail;
379 380 381 382 383 384
    m_changed = true;
}

bool Media::save()
{
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET "
385
            "type = ?, subtype = ?, duration = ?, progress = ?, release_date = ?,"
386
            "thumbnail = ?, title = ? WHERE id_media = ?";
387 388
    if ( m_changed == false )
        return true;
389
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, m_type, m_subType, m_duration,
390
                                       m_progress, m_releaseDate, m_thumbnail, m_title, m_id ) == false )
391 392 393 394
    {
        return false;
    }
    m_changed = false;
395 396 397
    return true;
}

398
std::shared_ptr<File> Media::addFile( const fs::IFile& fileFs, Folder& parentFolder, fs::IDirectory& parentFolderFs, IFile::Type type )
399
{
400
    auto file = File::create( m_ml, m_id, type, fileFs, parentFolder.id(), parentFolderFs.device()->isRemovable() );
401 402 403 404 405 406
    if ( file == nullptr )
        return nullptr;
    auto lock = m_files.lock();
    if ( m_files.isCached() )
        m_files.get().push_back( file );
    return file;
407 408
}

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

420
std::vector<MediaPtr> Media::listAll( MediaLibraryPtr ml, IMedia::Type type, SortingCriteria sort, bool desc )
421
{
422
    std::string req;
423
    if ( sort == SortingCriteria::LastModificationDate || sort == SortingCriteria::FileSize )
424 425 426 427
    {
        req = "SELECT m.* FROM " + policy::MediaTable::Name + " m INNER JOIN "
                + policy::FileTable::Name + " f ON m.id_media = f.media_id"
                " WHERE m.type = ?"
428 429 430 431 432
                " AND ( f.type = ? OR f.type = ? )";
        if ( sort == SortingCriteria::LastModificationDate )
            req += " ORDER BY f.last_modification_date";
        else
            req += " ORDER BY f.size";
433 434 435 436 437 438 439
        if ( desc == true )
            req += " DESC";
        return fetchAll<IMedia>( ml, req, type, File::Type::Entire, File::Type::Main );
    }
    req = "SELECT * FROM " + policy::MediaTable::Name + " WHERE type = ? AND is_present = 1 ORDER BY ";
    switch ( sort )
    {
440
    case SortingCriteria::Duration:
441 442
        req += "duration";
        break;
443
    case SortingCriteria::InsertionDate:
444 445
        req += "insertion_date";
        break;
446
    case SortingCriteria::ReleaseDate:
447 448 449
        req += "release_date";
        break;
    default:
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
450
        req += "title";
451 452 453 454 455 456
        break;
    }
    if ( desc == true )
        req += " DESC";

    return fetchAll<IMedia>( ml, req, type );
457 458
}

459
int64_t Media::id() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
460 461 462 463
{
    return m_id;
}

464
IMedia::Type Media::type()
465 466 467 468
{
    return m_type;
}

469
IMedia::SubType Media::subType() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
470 471 472 473
{
    return m_subType;
}

474
void Media::setType( Type type )
475
{
476
    if ( m_type == type )
477
        return;
478
    m_type = type;
479
    m_changed = true;
480 481
}

482
const std::string &Media::title() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
483
{
484
    return m_title;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
485 486
}

487
void Media::setTitle( const std::string &title )
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
488
{
489 490
    if ( m_title == title )
        return;
491
    m_title = title;
492
    m_changed = true;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
493 494
}

495
bool Media::createTable( DBConnection connection )
496
{
497 498
    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
499
            "type INTEGER,"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
500
            "subtype INTEGER,"
501
            "duration INTEGER DEFAULT -1,"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
502
            "play_count UNSIGNED INTEGER,"
503
            "last_played_date UNSIGNED INTEGER,"
504 505
            "progress REAL,"
            "rating INTEGER DEFAULT -1,"
506
            "insertion_date UNSIGNED INTEGER,"
507
            "release_date UNSIGNED INTEGER,"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
508
            "thumbnail TEXT,"
509
            "title TEXT COLLATE NOCASE,"
510
            "filename TEXT,"
511
            "is_favorite BOOLEAN NOT NULL DEFAULT 0,"
512
            "is_present BOOLEAN NOT NULL DEFAULT 1"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
513
            ")";
514
    const std::string indexReq = "CREATE INDEX IF NOT EXISTS index_last_played_date ON "
515
            + policy::MediaTable::Name + "(last_played_date DESC)";
516
    const std::string vtableReq = "CREATE VIRTUAL TABLE IF NOT EXISTS "
517
                + policy::MediaTable::Name + "Fts USING FTS3("
518 519
                "title,"
                "labels"
520
            ")";
521 522 523 524 525 526
    const std::string metadataReq = "CREATE TABLE IF NOT EXISTS " + policy::MediaMetadataTable::Name + "("
            "id_media INTEGER,"
            "type INTEGER,"
            "value TEXT,"
            "PRIMARY KEY (id_media, type)"
            ")";
527
    return sqlite::Tools::executeRequest( connection, req ) &&
528
            sqlite::Tools::executeRequest( connection, indexReq ) &&
529 530
            sqlite::Tools::executeRequest( connection, vtableReq ) &&
            sqlite::Tools::executeRequest( connection, metadataReq );
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
}

bool Media::createTriggers( DBConnection connection )
{
    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="
                "(SELECT COUNT(id_file) FROM " + policy::FileTable::Name + " WHERE media_id=new.media_id AND is_present=1) "
                "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;";
549 550 551 552

    static const std::string vtableInsertTrigger = "CREATE TRIGGER IF NOT EXISTS insert_media_fts"
            " AFTER INSERT ON " + policy::MediaTable::Name +
            " BEGIN"
553
            " INSERT INTO " + policy::MediaTable::Name + "Fts(rowid,title,labels) VALUES(new.id_media, new.title, '');"
554 555
            " 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
556
            " BEFORE DELETE ON " + policy::MediaTable::Name +
557 558 559 560 561 562 563 564
            " 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";
565
    return sqlite::Tools::executeRequest( connection, triggerReq ) &&
566 567 568 569
            sqlite::Tools::executeRequest( connection, triggerReq2 ) &&
            sqlite::Tools::executeRequest( connection, vtableInsertTrigger ) &&
            sqlite::Tools::executeRequest( connection, vtableDeleteTrigger ) &&
            sqlite::Tools::executeRequest( connection, vtableUpdateTitleTrigger2 );
570
}
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
571

572
bool Media::addLabel( LabelPtr label )
573
{
574
    if ( m_id == 0 || label->id() == 0 )
575
    {
576
        LOG_ERROR( "Both file & label need to be inserted in database before being linked together" );
577 578 579
        return false;
    }
    const char* req = "INSERT INTO LabelFileRelation VALUES(?, ?)";
580
    if ( sqlite::Tools::executeInsert( m_ml->getConn(), req, label->id(), m_id ) == 0 )
581 582 583
        return false;
    const std::string reqFts = "UPDATE " + policy::MediaTable::Name + "Fts "
        "SET labels = labels || ' ' || ? WHERE rowid = ?";
584
    return sqlite::Tools::executeUpdate( m_ml->getConn(), reqFts, label->name(), m_id );
585 586
}

587
bool Media::removeLabel( LabelPtr label )
588
{
589
    if ( m_id == 0 || label->id() == 0 )
590
    {
591
        LOG_ERROR( "Can't unlink a label/file not inserted in database" );
592 593
        return false;
    }
594
    const char* req = "DELETE FROM LabelFileRelation WHERE label_id = ? AND media_id = ?";
595
    if ( sqlite::Tools::executeDelete( m_ml->getConn(), req, label->id(), m_id ) == false )
596 597 598
        return false;
    const std::string reqFts = "UPDATE " + policy::MediaTable::Name + "Fts "
            "SET labels = TRIM(REPLACE(labels, ?, '')) WHERE rowid = ?";
599
    return sqlite::Tools::executeUpdate( m_ml->getConn(), reqFts, label->name(), m_id );
600
}
601 602


603
std::vector<MediaPtr> Media::search( MediaLibraryPtr ml, const std::string& title )
604 605 606
{
    static const std::string req = "SELECT * FROM " + policy::MediaTable::Name + " WHERE"
            " id_media IN (SELECT rowid FROM " + policy::MediaTable::Name + "Fts"
607
            " WHERE " + policy::MediaTable::Name + "Fts MATCH '*' || ? || '*')"
608
            "AND is_present = 1";
609
    return Media::fetchAll<IMedia>( ml, req, title );
610
}
611

612
std::vector<MediaPtr> Media::fetchHistory( MediaLibraryPtr ml )
613 614 615
{
    static const std::string req = "SELECT * FROM " + policy::MediaTable::Name + " WHERE last_played_date IS NOT NULL"
            " ORDER BY last_played_date DESC LIMIT 100";
616
    return fetchAll<IMedia>( ml, req );
617
}
618

619
void Media::clearHistory( MediaLibraryPtr ml )
620 621 622 623 624 625 626 627
{
    auto dbConn = ml->getConn();
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET "
            "play_count = 0,"
            "last_played_date = NULL,"
            "progress = 0";
    // Clear the entire cache since quite a few items are now containing invalid info.
    clear();
628
    sqlite::Tools::executeUpdate( dbConn, req );
629 630
}

631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
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;
}

646
}