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 65
        >> m_title
        >> m_isFavorite;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
66 67
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

204
const std::vector<FilePtr>& Media::files() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
205
{
206 207 208 209 210 211 212 213
    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
214 215
}

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

221 222
    auto lock = m_movie.lock();

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

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

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

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

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

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

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

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

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
272
void Media::setThumbnail(const std::string& thumbnail )
273
{
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
274
    if ( m_thumbnail == thumbnail )
275
        return;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
276
    m_thumbnail = thumbnail;
277 278 279 280 281 282
    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
283
            "type = ?, subtype = ?, duration = ?, play_count = ?, progress = ?, rating = ?,"
284
            "thumbnail = ?, title = ?, is_favorite = ? WHERE id_media = ?";
285 286
    if ( m_changed == false )
        return true;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
287
    if ( sqlite::Tools::executeUpdate( m_dbConnection, req, m_type, m_subType, m_duration, m_playCount,
288
                                       m_progress, m_rating, m_thumbnail, m_title, m_isFavorite, m_id ) == false )
289 290 291 292
    {
        return false;
    }
    m_changed = false;
293 294 295
    return true;
}

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

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

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

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

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

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

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

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

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

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

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

418
bool Media::addLabel( LabelPtr label )
419
{
420
    if ( m_id == 0 || label->id() == 0 )
421
    {
422
        LOG_ERROR( "Both file & label need to be inserted in database before being linked together" );
423 424 425
        return false;
    }
    const char* req = "INSERT INTO LabelFileRelation VALUES(?, ?)";
426 427 428 429 430
    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 );
431 432
}

433
bool Media::removeLabel( LabelPtr label )
434
{
435
    if ( m_id == 0 || label->id() == 0 )
436
    {
437
        LOG_ERROR( "Can't unlink a label/file not inserted in database" );
438 439
        return false;
    }
440
    const char* req = "DELETE FROM LabelFileRelation WHERE label_id = ? AND media_id = ?";
441 442 443 444 445
    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 );
446
}
447 448 449 450 451 452


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"
453 454
            " WHERE " + policy::MediaTable::Name + "Fts MATCH ?)"
            "AND is_present = 1";
455 456
    return Media::fetchAll<IMedia>( dbConn, req, title + "*" );
}