Media.cpp 24.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

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

52 53 54
namespace medialibrary
{

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

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

61 62
Media::Media( MediaLibraryPtr ml, sqlite::Row& row )
    : m_ml( ml )
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_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 std::string& fileName )
103
{
104
    auto self = std::make_shared<Media>( ml, fileName, 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
bool Media::isFavorite() const
{
    return m_isFavorite;
}

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

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

217
MoviePtr Media::movie() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
218
{
219 220 221
    if ( m_subType != SubType::Movie )
        return nullptr;

222 223
    auto lock = m_movie.lock();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

464 465

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

501 502 503 504 505 506 507 508 509
std::vector<MediaPtr> Media::listAll( MediaLibraryPtr ml, IMedia::Type type,
                                      SortingCriteria sort, bool desc )
{
    std::string req = "SELECT m.* FROM " + policy::MediaTable::Name + " m INNER JOIN "
            + policy::FileTable::Name + " f ON m.id_media = f.media_id"
            " WHERE m.type = ?"
            " AND f.type = ?"
            " AND f.is_present != 0";
    req += sortRequest( sort, desc );
510
    return fetchAll<IMedia>( ml, req, type, File::Type::Main );
511 512
}

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

518
IMedia::Type Media::type()
519 520 521 522
{
    return m_type;
}

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

528
void Media::setType( Type type )
529
{
530
    if ( m_type == type )
531
        return;
532
    m_type = type;
533
    m_changed = true;
534 535
}

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

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

557 558 559 560
    m_title = title;
    return true;
}

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

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

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

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

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

    sqlite::Tools::executeRequest( connection, indexReq );
645 646 647 648 649
    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 );
650
}
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
651

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

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

712 713
std::vector<MediaPtr> Media::search( MediaLibraryPtr ml, const std::string& title,
                                     SortingCriteria sort, bool desc )
714
{
715
    std::string req = "SELECT m.* FROM " + policy::MediaTable::Name + " m "
716 717 718
            " 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"
719
            " WHERE " + policy::MediaTable::Name + "Fts MATCH '*' || ? || '*')"
720 721
            " AND f.is_present = 1"
            " AND f.type = ?";
722
    req += sortRequest( sort, desc );
723
    return Media::fetchAll<IMedia>( ml, req, title, File::Type::Main );
724
}
725

726
std::vector<MediaPtr> Media::fetchHistory( MediaLibraryPtr ml )
727 728 729
{
    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";
730
    return fetchAll<IMedia>( ml, req );
731
}
732

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

749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
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;
}

764 765 766 767 768 769
void Media::MediaMetadata::set( const std::string& value )
{
    m_value = value;
    m_isSet = true;
}

770
}