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

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

92
    if ( insert( ml, self, req, type, self->m_insertionDate, self->m_title ) == false )
93
        return nullptr;
94
    self->m_ml = ml;
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 163 164
void Media::increasePlayCount()
{
    m_playCount++;
165
    m_lastPlayedDate = time( nullptr );
166 167 168
    m_changed = true;
}

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
float Media::progress() const
{
    return m_progress;
}

void Media::setProgress( float progress )
{
    if ( progress == m_progress || progress < 0 || progress > 1.0 )
        return;
    m_progress = progress;
    m_changed = true;
}

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

void Media::setRating( int rating )
{
    if ( m_rating == rating )
        return;
    m_rating = rating;
    m_changed = true;
}

195 196 197 198 199 200 201 202 203 204 205 206 207
bool Media::isFavorite() const
{
    return m_isFavorite;
}

void Media::setFavorite( bool favorite )
{
    if ( m_isFavorite == favorite )
        return;
    m_isFavorite = favorite;
    m_changed = true;
}

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

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

225 226
    auto lock = m_movie.lock();

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

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

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

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

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

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

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
266
const std::string &Media::thumbnail()
267
{
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
268
    return m_thumbnail;
269 270
}

271 272 273 274 275
unsigned int Media::insertionDate() const
{
    return m_insertionDate;
}

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
276
void Media::setThumbnail(const std::string& thumbnail )
277
{
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
278
    if ( m_thumbnail == thumbnail )
279
        return;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
280
    m_thumbnail = thumbnail;
281 282 283 284 285 286
    m_changed = true;
}

bool Media::save()
{
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET "
287
            "type = ?, subtype = ?, duration = ?, play_count = ?, last_played_date = ?, progress = ?, rating = ?,"
288
            "thumbnail = ?, title = ?, is_favorite = ? WHERE id_media = ?";
289 290
    if ( m_changed == false )
        return true;
291
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, m_type, m_subType, m_duration, m_playCount,
292 293
                                       m_lastPlayedDate, m_progress, m_rating, m_thumbnail, m_title,
                                       m_isFavorite, m_id ) == false )
294 295 296 297
    {
        return false;
    }
    m_changed = false;
298 299 300
    return true;
}

301
std::shared_ptr<File> Media::addFile( const fs::IFile& fileFs, Folder& parentFolder, fs::IDirectory& parentFolderFs, IFile::Type type )
302
{
303
    auto file = File::create( m_ml, m_id, type, fileFs, parentFolder.id(), parentFolderFs.device()->isRemovable() );
304 305 306 307 308 309
    if ( file == nullptr )
        return nullptr;
    auto lock = m_files.lock();
    if ( m_files.isCached() )
        m_files.get().push_back( file );
    return file;
310 311
}

312
void Media::removeFile( File& file )
313
{
314 315 316
    file.destroy();
    auto lock = m_files.lock();
    if ( m_files.isCached() == false )
317
        return;
318 319 320
    m_files.get().erase( std::remove_if( begin( m_files.get() ), end( m_files.get() ), [&file]( const FilePtr& f ) {
        return f->id() == file.id();
    }));
321 322
}

323
unsigned int Media::id() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
324 325 326 327
{
    return m_id;
}

328
IMedia::Type Media::type()
329 330 331 332
{
    return m_type;
}

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
333 334 335 336 337
IMedia::SubType Media::subType() const
{
    return m_subType;
}

338
void Media::setType( Type type )
339
{
340 341
    if ( m_type != type )
        return;
342
    m_type = type;
343
    m_changed = true;
344 345
}

346
const std::string &Media::title() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
347
{
348
    return m_title;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
349 350
}

351
void Media::setTitle( const std::string &title )
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
352
{
353 354
    if ( m_title == title )
        return;
355
    m_title = title;
356
    m_changed = true;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
357 358
}

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

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;";
404 405 406 407

    static const std::string vtableInsertTrigger = "CREATE TRIGGER IF NOT EXISTS insert_media_fts"
            " AFTER INSERT ON " + policy::MediaTable::Name +
            " BEGIN"
408
            " INSERT INTO " + policy::MediaTable::Name + "Fts(rowid,title,labels) VALUES(new.id_media, new.title, '');"
409 410
            " 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
411
            " BEFORE DELETE ON " + policy::MediaTable::Name +
412 413 414 415 416 417 418 419
            " 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";
420
    return sqlite::Tools::executeRequest( connection, triggerReq ) &&
421 422 423 424
            sqlite::Tools::executeRequest( connection, triggerReq2 ) &&
            sqlite::Tools::executeRequest( connection, vtableInsertTrigger ) &&
            sqlite::Tools::executeRequest( connection, vtableDeleteTrigger ) &&
            sqlite::Tools::executeRequest( connection, vtableUpdateTitleTrigger2 );
425
}
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
426

427
bool Media::addLabel( LabelPtr label )
428
{
429
    if ( m_id == 0 || label->id() == 0 )
430
    {
431
        LOG_ERROR( "Both file & label need to be inserted in database before being linked together" );
432 433 434
        return false;
    }
    const char* req = "INSERT INTO LabelFileRelation VALUES(?, ?)";
435
    if ( sqlite::Tools::insert( m_ml->getConn(), req, label->id(), m_id ) == 0 )
436 437 438
        return false;
    const std::string reqFts = "UPDATE " + policy::MediaTable::Name + "Fts "
        "SET labels = labels || ' ' || ? WHERE rowid = ?";
439
    return sqlite::Tools::executeUpdate( m_ml->getConn(), reqFts, label->name(), m_id );
440 441
}

442
bool Media::removeLabel( LabelPtr label )
443
{
444
    if ( m_id == 0 || label->id() == 0 )
445
    {
446
        LOG_ERROR( "Can't unlink a label/file not inserted in database" );
447 448
        return false;
    }
449
    const char* req = "DELETE FROM LabelFileRelation WHERE label_id = ? AND media_id = ?";
450
    if ( sqlite::Tools::executeDelete( m_ml->getConn(), req, label->id(), m_id ) == false )
451 452 453
        return false;
    const std::string reqFts = "UPDATE " + policy::MediaTable::Name + "Fts "
            "SET labels = TRIM(REPLACE(labels, ?, '')) WHERE rowid = ?";
454
    return sqlite::Tools::executeUpdate( m_ml->getConn(), reqFts, label->name(), m_id );
455
}
456 457


458
std::vector<MediaPtr> Media::search( MediaLibraryPtr ml, const std::string& title )
459 460 461
{
    static const std::string req = "SELECT * FROM " + policy::MediaTable::Name + " WHERE"
            " id_media IN (SELECT rowid FROM " + policy::MediaTable::Name + "Fts"
462 463
            " WHERE " + policy::MediaTable::Name + "Fts MATCH ?)"
            "AND is_present = 1";
464
    return Media::fetchAll<IMedia>( ml, req, title + "*" );
465
}
466

467
std::vector<MediaPtr> Media::fetchHistory( MediaLibraryPtr ml )
468 469 470
{
    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";
471
    return fetchAll<IMedia>( ml, req );
472
}