Media.cpp 13.9 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
Media::Media( DBConnection dbConnection, sqlite::Row& row )
52
    : m_dbConnection( dbConnection )
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 61
        >> m_progress
        >> m_rating
62
        >> m_insertionDate
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
63
        >> m_thumbnail
64
        >> m_title
65 66
        >> m_isFavorite
        >> m_isPresent;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
67 68
}

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

84
std::shared_ptr<Media> Media::create( DBConnection dbConnection, Type type, const fs::IFile* file )
85
{
86
    auto self = std::make_shared<Media>( file->name(), type );
87
    static const std::string req = "INSERT INTO " + policy::MediaTable::Name +
88
            "(type, insertion_date, title) VALUES(?, ?, ?)";
89

90
    if ( insert( dbConnection, self, req, type, self->m_insertionDate, self->m_title ) == false )
91
        return nullptr;
92 93
    self->m_dbConnection = dbConnection;
    return self;
94 95
}

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

102
    if ( m_albumTrack.isCached() == false )
103 104
        m_albumTrack = AlbumTrack::fromMedia( m_dbConnection, m_id );
    return m_albumTrack.get();
105 106
}

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

115
int64_t Media::duration() const
116 117 118 119
{
    return m_duration;
}

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

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

133 134
    auto lock = m_showEpisode.lock();
    if ( m_showEpisode.isCached() == false )
135 136
        m_showEpisode = ShowEpisode::fromMedia( m_dbConnection, m_id );
    return m_showEpisode.get();
137 138
}

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

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

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

160 161 162 163 164 165
void Media::increasePlayCount()
{
    m_playCount++;
    m_changed = true;
}

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
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;
}

192 193 194 195 196 197 198 199 200 201 202 203 204
bool Media::isFavorite() const
{
    return m_isFavorite;
}

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

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 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 = ?";
        m_files = File::fetchAll<IFile>( m_dbConnection, req, m_id );
    }
    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 226
        m_movie = Movie::fromMedia( m_dbConnection, m_id );
    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
bool Media::addVideoTrack(const std::string& codec, unsigned int width, unsigned int height, float fps)
238
{
239
    return VideoTrack::create( m_dbConnection, codec, width, height, fps, m_id ) != nullptr;
240 241
}

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

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

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

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

268 269 270 271 272
unsigned int Media::insertionDate() const
{
    return m_insertionDate;
}

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

bool Media::save()
{
    static const std::string req = "UPDATE " + policy::MediaTable::Name + " SET "
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
284
            "type = ?, subtype = ?, duration = ?, play_count = ?, progress = ?, rating = ?,"
285
            "thumbnail = ?, title = ?, is_favorite = ? WHERE id_media = ?";
286 287
    if ( m_changed == false )
        return true;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
288
    if ( sqlite::Tools::executeUpdate( m_dbConnection, req, m_type, m_subType, m_duration, m_playCount,
289
                                       m_progress, m_rating, m_thumbnail, m_title, m_isFavorite, m_id ) == false )
290 291 292 293
    {
        return false;
    }
    m_changed = false;
294 295 296
    return true;
}

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

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

319
unsigned int Media::id() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
320 321 322 323
{
    return m_id;
}

324
IMedia::Type Media::type()
325 326 327 328
{
    return m_type;
}

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
329 330 331 332 333
IMedia::SubType Media::subType() const
{
    return m_subType;
}

334
void Media::setType( Type type )
335
{
336 337
    if ( m_type != type )
        return;
338
    m_type = type;
339
    m_changed = true;
340 341
}

342
const std::string &Media::title() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
343
{
344
    return m_title;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
345 346
}

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

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

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;";
396 397 398 399

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

419
bool Media::addLabel( LabelPtr label )
420
{
421
    if ( m_id == 0 || label->id() == 0 )
422
    {
423
        LOG_ERROR( "Both file & label need to be inserted in database before being linked together" );
424 425 426
        return false;
    }
    const char* req = "INSERT INTO LabelFileRelation VALUES(?, ?)";
427 428 429 430 431
    if ( sqlite::Tools::insert( m_dbConnection, req, label->id(), m_id ) == 0 )
        return false;
    const std::string reqFts = "UPDATE " + policy::MediaTable::Name + "Fts "
        "SET labels = labels || ' ' || ? WHERE rowid = ?";
    return sqlite::Tools::executeUpdate( m_dbConnection, reqFts, label->name(), m_id );
432 433
}

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


std::vector<MediaPtr> Media::search( DBConnection dbConn, const std::string& title )
{
    static const std::string req = "SELECT * FROM " + policy::MediaTable::Name + " WHERE"
            " id_media IN (SELECT rowid FROM " + policy::MediaTable::Name + "Fts"
454 455
            " WHERE " + policy::MediaTable::Name + "Fts MATCH ?)"
            "AND is_present = 1";
456 457
    return Media::fetchAll<IMedia>( dbConn, req, title + "*" );
}