Media.cpp 15.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
#include <algorithm>
24
#include <cassert>
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
25 26
#include <cstdlib>
#include <cstring>
27
#include <ctime>
28

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
29
#include "Album.h"
30
#include "AlbumTrack.h"
31
#include "Artist.h"
32
#include "AudioTrack.h"
33
#include "Media.h"
34
#include "File.h"
35
#include "Folder.h"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
36
#include "Label.h"
37
#include "logging/Logger.h"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
38
#include "Movie.h"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
39
#include "ShowEpisode.h"
40
#include "database/SqliteTools.h"
41
#include "VideoTrack.h"
42
#include "filesystem/IFile.h"
43 44
#include "filesystem/IDirectory.h"
#include "filesystem/IDevice.h"
45
#include "utils/Filename.h"
46

47
const std::string policy::MediaTable::Name = "Media";
48
const std::string policy::MediaTable::PrimaryKeyColumn = "id_media";
49
unsigned int Media::* const policy::MediaTable::PrimaryKey = &Media::m_id;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
50

51 52
Media::Media( MediaLibraryPtr ml, sqlite::Row& row )
    : m_ml( ml )
53
    , m_changed( false )
54
{
55 56
    row >> m_id
        >> m_type
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
57
        >> m_subType
58 59
        >> m_duration
        >> m_playCount
60
        >> m_lastPlayedDate
61 62
        >> m_progress
        >> m_rating
63
        >> m_insertionDate
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
64
        >> m_thumbnail
65
        >> m_title
66 67
        >> m_isFavorite
        >> m_isPresent;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
68 69
}

70 71 72
Media::Media( MediaLibraryPtr ml, const std::string& title, Type type )
    : m_ml( ml )
    , m_id( 0 )
73
    , m_type( type )
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
74
    , m_subType( SubType::Unknown )
75
    , m_duration( -1 )
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
76
    , m_playCount( 0 )
77
    , m_lastPlayedDate( 0 )
78 79
    , m_progress( .0f )
    , m_rating( -1 )
80
    , m_insertionDate( time( nullptr ) )
81
    , m_title( title )
82
    , m_isFavorite( false )
83
    , m_changed( false )
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
84
{
85 86
}

87
std::shared_ptr<Media> Media::create( MediaLibraryPtr ml, Type type, const fs::IFile& file )
88
{
89
    auto self = std::make_shared<Media>( ml, file.name(), type );
90
    static const std::string req = "INSERT INTO " + policy::MediaTable::Name +
91
            "(type, insertion_date, title) VALUES(?, ?, ?)";
92

93
    if ( insert( ml, self, req, type, self->m_insertionDate, self->m_title ) == false )
94
        return nullptr;
95
    return self;
96 97
}

98
AlbumTrackPtr Media::albumTrack() const
99
{
100 101
    if ( m_subType != SubType::AlbumTrack )
        return nullptr;
102 103
    auto lock = m_albumTrack.lock();

104
    if ( m_albumTrack.isCached() == false )
105
        m_albumTrack = AlbumTrack::fromMedia( m_ml, m_id );
106
    return m_albumTrack.get();
107 108
}

109
void Media::setAlbumTrack( AlbumTrackPtr albumTrack )
110
{
111
    auto lock = m_albumTrack.lock();
112
    m_albumTrack = albumTrack;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
113 114
    m_subType = SubType::AlbumTrack;
    m_changed = true;
115 116
}

117
int64_t Media::duration() const
118 119 120 121
{
    return m_duration;
}

122
void Media::setDuration( int64_t duration )
123
{
124 125
    if ( m_duration == duration )
        return;
126
    m_duration = duration;
127
    m_changed = true;
128 129
}

130
ShowEpisodePtr Media::showEpisode() const
131
{
132 133
    if ( m_subType != SubType::ShowEpisode )
        return nullptr;
134

135 136
    auto lock = m_showEpisode.lock();
    if ( m_showEpisode.isCached() == false )
137
        m_showEpisode = ShowEpisode::fromMedia( m_ml, m_id );
138
    return m_showEpisode.get();
139 140
}

141
void Media::setShowEpisode( ShowEpisodePtr episode )
142
{
143 144
    auto lock = m_showEpisode.lock();
    m_showEpisode = episode;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
145 146
    m_subType = SubType::ShowEpisode;
    m_changed = true;
147 148
}

149
std::vector<LabelPtr> Media::labels()
150
{
151
    static const std::string req = "SELECT l.* FROM " + policy::LabelTable::Name + " l "
152
            "INNER JOIN LabelFileRelation lfr ON lfr.label_id = l.id_label "
153
            "WHERE lfr.media_id = ?";
154
    return Label::fetchAll<ILabel>( m_ml, req, m_id );
155 156
}

157
int Media::playCount() const
158
{
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
159
    return m_playCount;
160 161
}

162
bool Media::increasePlayCount()
163
{
164 165 166 167 168
    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;
169
    m_playCount++;
170 171
    m_lastPlayedDate = lastPlayedDate;
    return true;
172 173
}

174 175 176 177 178
float Media::progress() const
{
    return m_progress;
}

179
bool Media::setProgress( float progress )
180
{
181
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET progress = ? WHERE id_media = ?";
182
    if ( progress == m_progress || progress < 0 || progress > 1.0 )
183 184 185
        return true;
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, progress, m_id ) == false )
        return false;
186
    m_progress = progress;
187
    return true;
188 189 190 191 192 193 194
}

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

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

206 207 208 209 210
bool Media::isFavorite() const
{
    return m_isFavorite;
}

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

222
const std::vector<FilePtr>& Media::files() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
223
{
224 225 226 227 228
    auto lock = m_files.lock();
    if ( m_files.isCached() == false )
    {
        static const std::string req = "SELECT * FROM " + policy::FileTable::Name
                + " WHERE media_id = ?";
229
        m_files = File::fetchAll<IFile>( m_ml, req, m_id );
230 231
    }
    return m_files;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
232 233
}

234
MoviePtr Media::movie() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
235
{
236 237 238
    if ( m_subType != SubType::Movie )
        return nullptr;

239 240
    auto lock = m_movie.lock();

241
    if ( m_movie.isCached() == false )
242
        m_movie = Movie::fromMedia( m_ml, m_id );
243
    return m_movie.get();
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
244 245
}

246
void Media::setMovie(MoviePtr movie)
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
247
{
248
    auto lock = m_movie.lock();
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
249
    m_movie = movie;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
250 251
    m_subType = SubType::Movie;
    m_changed = true;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
252 253
}

254
bool Media::addVideoTrack(const std::string& codec, unsigned int width, unsigned int height, float fps)
255
{
256
    return VideoTrack::create( m_ml, codec, width, height, fps, m_id ) != nullptr;
257 258
}

259
std::vector<VideoTrackPtr> Media::videoTracks()
260
{
261 262
    static const std::string req = "SELECT * FROM " + policy::VideoTrackTable::Name +
            " WHERE media_id = ?";
263
    return VideoTrack::fetchAll<IVideoTrack>( m_ml, req, m_id );
264 265
}

266
bool Media::addAudioTrack( const std::string& codec, unsigned int bitrate,
267 268
                          unsigned int sampleRate, unsigned int nbChannels,
                          const std::string& language, const std::string& desc )
269
{
270
    return AudioTrack::create( m_ml, codec, bitrate, sampleRate, nbChannels, language, desc, m_id ) != nullptr;
271 272
}

273
std::vector<AudioTrackPtr> Media::audioTracks()
274
{
275 276
    static const std::string req = "SELECT * FROM " + policy::AudioTrackTable::Name +
            " WHERE media_id = ?";
277
    return AudioTrack::fetchAll<IAudioTrack>( m_ml, req, m_id );
278 279
}

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
280
const std::string &Media::thumbnail()
281
{
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
282
    return m_thumbnail;
283 284
}

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

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
290
void Media::setThumbnail(const std::string& thumbnail )
291
{
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
292
    if ( m_thumbnail == thumbnail )
293
        return;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
294
    m_thumbnail = thumbnail;
295 296 297 298 299 300
    m_changed = true;
}

bool Media::save()
{
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET "
301 302
            "type = ?, subtype = ?, duration = ?, progress = ?,"
            "thumbnail = ?, title = ? WHERE id_media = ?";
303 304
    if ( m_changed == false )
        return true;
305 306
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, m_type, m_subType, m_duration,
                                       m_progress, m_thumbnail, m_title, m_id ) == false )
307 308 309 310
    {
        return false;
    }
    m_changed = false;
311 312 313
    return true;
}

314
std::shared_ptr<File> Media::addFile( const fs::IFile& fileFs, Folder& parentFolder, fs::IDirectory& parentFolderFs, IFile::Type type )
315
{
316
    auto file = File::create( m_ml, m_id, type, fileFs, parentFolder.id(), parentFolderFs.device()->isRemovable() );
317 318 319 320 321 322
    if ( file == nullptr )
        return nullptr;
    auto lock = m_files.lock();
    if ( m_files.isCached() )
        m_files.get().push_back( file );
    return file;
323 324
}

325
void Media::removeFile( File& file )
326
{
327 328 329
    file.destroy();
    auto lock = m_files.lock();
    if ( m_files.isCached() == false )
330
        return;
331 332 333
    m_files.get().erase( std::remove_if( begin( m_files.get() ), end( m_files.get() ), [&file]( const FilePtr& f ) {
        return f->id() == file.id();
    }));
334 335
}

336
unsigned int Media::id() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
337 338 339 340
{
    return m_id;
}

341
IMedia::Type Media::type()
342 343 344 345
{
    return m_type;
}

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
346 347 348 349 350
IMedia::SubType Media::subType() const
{
    return m_subType;
}

351
void Media::setType( Type type )
352
{
353 354
    if ( m_type != type )
        return;
355
    m_type = type;
356
    m_changed = true;
357 358
}

359
const std::string &Media::title() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
360
{
361
    return m_title;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
362 363
}

364
void Media::setTitle( const std::string &title )
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
365
{
366 367
    if ( m_title == title )
        return;
368
    m_title = title;
369
    m_changed = true;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
370 371
}

372
bool Media::createTable( DBConnection connection )
373
{
374 375
    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
376
            "type INTEGER,"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
377
            "subtype INTEGER,"
378
            "duration INTEGER DEFAULT -1,"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
379
            "play_count UNSIGNED INTEGER,"
380
            "last_played_date UNSIGNED INTEGER,"
381 382
            "progress REAL,"
            "rating INTEGER DEFAULT -1,"
383
            "insertion_date UNSIGNED INTEGER,"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
384
            "thumbnail TEXT,"
385
            "title TEXT,"
386
            "is_favorite BOOLEAN NOT NULL DEFAULT 0,"
387
            "is_present BOOLEAN NOT NULL DEFAULT 1"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
388
            ")";
389 390
    static const std::string indexReq = "CREATE INDEX IF NOT EXISTS index_last_played_date ON "
            + policy::MediaTable::Name + "(last_played_date DESC)";
391 392
    static const std::string vtableReq = "CREATE VIRTUAL TABLE IF NOT EXISTS "
                + policy::MediaTable::Name + "Fts USING FTS3("
393 394
                "title,"
                "labels"
395 396
            ")";
    return sqlite::Tools::executeRequest( connection, req ) &&
397
            sqlite::Tools::executeRequest( connection, indexReq ) &&
398
            sqlite::Tools::executeRequest( connection, vtableReq );
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
}

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;";
417 418 419 420

    static const std::string vtableInsertTrigger = "CREATE TRIGGER IF NOT EXISTS insert_media_fts"
            " AFTER INSERT ON " + policy::MediaTable::Name +
            " BEGIN"
421
            " INSERT INTO " + policy::MediaTable::Name + "Fts(rowid,title,labels) VALUES(new.id_media, new.title, '');"
422 423
            " 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
424
            " BEFORE DELETE ON " + policy::MediaTable::Name +
425 426 427 428 429 430 431 432
            " 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";
433
    return sqlite::Tools::executeRequest( connection, triggerReq ) &&
434 435 436 437
            sqlite::Tools::executeRequest( connection, triggerReq2 ) &&
            sqlite::Tools::executeRequest( connection, vtableInsertTrigger ) &&
            sqlite::Tools::executeRequest( connection, vtableDeleteTrigger ) &&
            sqlite::Tools::executeRequest( connection, vtableUpdateTitleTrigger2 );
438
}
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
439

440
bool Media::addLabel( LabelPtr label )
441
{
442
    if ( m_id == 0 || label->id() == 0 )
443
    {
444
        LOG_ERROR( "Both file & label need to be inserted in database before being linked together" );
445 446 447
        return false;
    }
    const char* req = "INSERT INTO LabelFileRelation VALUES(?, ?)";
448
    if ( sqlite::Tools::insert( m_ml->getConn(), req, label->id(), m_id ) == 0 )
449 450 451
        return false;
    const std::string reqFts = "UPDATE " + policy::MediaTable::Name + "Fts "
        "SET labels = labels || ' ' || ? WHERE rowid = ?";
452
    return sqlite::Tools::executeUpdate( m_ml->getConn(), reqFts, label->name(), m_id );
453 454
}

455
bool Media::removeLabel( LabelPtr label )
456
{
457
    if ( m_id == 0 || label->id() == 0 )
458
    {
459
        LOG_ERROR( "Can't unlink a label/file not inserted in database" );
460 461
        return false;
    }
462
    const char* req = "DELETE FROM LabelFileRelation WHERE label_id = ? AND media_id = ?";
463
    if ( sqlite::Tools::executeDelete( m_ml->getConn(), req, label->id(), m_id ) == false )
464 465 466
        return false;
    const std::string reqFts = "UPDATE " + policy::MediaTable::Name + "Fts "
            "SET labels = TRIM(REPLACE(labels, ?, '')) WHERE rowid = ?";
467
    return sqlite::Tools::executeUpdate( m_ml->getConn(), reqFts, label->name(), m_id );
468
}
469 470


471
std::vector<MediaPtr> Media::search( MediaLibraryPtr ml, const std::string& title )
472 473 474
{
    static const std::string req = "SELECT * FROM " + policy::MediaTable::Name + " WHERE"
            " id_media IN (SELECT rowid FROM " + policy::MediaTable::Name + "Fts"
475 476
            " WHERE " + policy::MediaTable::Name + "Fts MATCH ?)"
            "AND is_present = 1";
477
    return Media::fetchAll<IMedia>( ml, req, title + "*" );
478
}
479

480
std::vector<MediaPtr> Media::fetchHistory( MediaLibraryPtr ml )
481 482 483
{
    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";
484
    return fetchAll<IMedia>( ml, req );
485
}