Media.cpp 13.5 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;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
65 66
}

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

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

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

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

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

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

112
int64_t Media::duration() const
113 114 115 116
{
    return m_duration;
}

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

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

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

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

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

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

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

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

189
const std::vector<FilePtr>& Media::files() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
190
{
191 192 193 194 195 196 197 198
    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
199 200
}

201
MoviePtr Media::movie() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
202
{
203 204 205
    if ( m_subType != SubType::Movie )
        return nullptr;

206 207
    auto lock = m_movie.lock();

208
    if ( m_movie.isCached() == false )
209 210
        m_movie = Movie::fromMedia( m_dbConnection, m_id );
    return m_movie.get();
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
211 212
}

213
void Media::setMovie(MoviePtr movie)
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
214
{
215
    auto lock = m_movie.lock();
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
216
    m_movie = movie;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
217 218
    m_subType = SubType::Movie;
    m_changed = true;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
219 220
}

221
bool Media::addVideoTrack(const std::string& codec, unsigned int width, unsigned int height, float fps)
222
{
223
    return VideoTrack::create( m_dbConnection, codec, width, height, fps, m_id ) != nullptr;
224 225
}

226
std::vector<VideoTrackPtr> Media::videoTracks()
227
{
228 229
    static const std::string req = "SELECT * FROM " + policy::VideoTrackTable::Name +
            " WHERE media_id = ?";
230
    return VideoTrack::fetchAll<IVideoTrack>( m_dbConnection, req, m_id );
231 232
}

233
bool Media::addAudioTrack( const std::string& codec, unsigned int bitrate,
234 235
                          unsigned int sampleRate, unsigned int nbChannels,
                          const std::string& language, const std::string& desc )
236
{
237
    return AudioTrack::create( m_dbConnection, codec, bitrate, sampleRate, nbChannels, language, desc, m_id ) != nullptr;
238 239
}

240
std::vector<AudioTrackPtr> Media::audioTracks()
241
{
242 243
    static const std::string req = "SELECT * FROM " + policy::AudioTrackTable::Name +
            " WHERE media_id = ?";
244
    return AudioTrack::fetchAll<IAudioTrack>( m_dbConnection, req, m_id );
245 246
}

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
247
const std::string &Media::thumbnail()
248
{
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
249
    return m_thumbnail;
250 251
}

252 253 254 255 256
unsigned int Media::insertionDate() const
{
    return m_insertionDate;
}

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
257
void Media::setThumbnail(const std::string& thumbnail )
258
{
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
259
    if ( m_thumbnail == thumbnail )
260
        return;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
261
    m_thumbnail = thumbnail;
262 263 264 265 266 267
    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
268
            "type = ?, subtype = ?, duration = ?, play_count = ?, progress = ?, rating = ?,"
269
            "thumbnail = ?, title = ? WHERE id_media = ?";
270 271
    if ( m_changed == false )
        return true;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
272
    if ( sqlite::Tools::executeUpdate( m_dbConnection, req, m_type, m_subType, m_duration, m_playCount,
273
                                       m_progress, m_rating, m_thumbnail, m_title, m_id ) == false )
274 275 276 277
    {
        return false;
    }
    m_changed = false;
278 279 280
    return true;
}

281
std::shared_ptr<File> Media::addFile( const fs::IFile& fileFs, Folder& parentFolder, fs::IDirectory& parentFolderFs, IFile::Type type )
282
{
283
    auto file = File::create( m_dbConnection, m_id, type, fileFs, parentFolder.id(), parentFolderFs.device()->isRemovable() );
284 285 286 287 288 289
    if ( file == nullptr )
        return nullptr;
    auto lock = m_files.lock();
    if ( m_files.isCached() )
        m_files.get().push_back( file );
    return file;
290 291
}

292
void Media::removeFile( File& file )
293
{
294 295 296
    file.destroy();
    auto lock = m_files.lock();
    if ( m_files.isCached() == false )
297
        return;
298 299 300
    m_files.get().erase( std::remove_if( begin( m_files.get() ), end( m_files.get() ), [&file]( const FilePtr& f ) {
        return f->id() == file.id();
    }));
301 302
}

303
unsigned int Media::id() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
304 305 306 307
{
    return m_id;
}

308
IMedia::Type Media::type()
309 310 311 312
{
    return m_type;
}

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
313 314 315 316 317
IMedia::SubType Media::subType() const
{
    return m_subType;
}

318
void Media::setType( Type type )
319
{
320 321
    if ( m_type != type )
        return;
322
    m_type = type;
323
    m_changed = true;
324 325
}

326
const std::string &Media::title() const
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
327
{
328
    return m_title;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
329 330
}

331
void Media::setTitle( const std::string &title )
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
332
{
333 334
    if ( m_title == title )
        return;
335
    m_title = title;
336
    m_changed = true;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
337 338
}

339
bool Media::createTable( DBConnection connection )
340
{
341 342
    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
343
            "type INTEGER,"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
344
            "subtype INTEGER,"
345
            "duration INTEGER DEFAULT -1,"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
346
            "play_count UNSIGNED INTEGER,"
347 348
            "progress REAL,"
            "rating INTEGER DEFAULT -1,"
349
            "insertion_date UNSIGNED INTEGER,"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
350
            "thumbnail TEXT,"
351
            "title TEXT,"
352
            "is_present BOOLEAN NOT NULL DEFAULT 1"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
353
            ")";
354 355
    static const std::string vtableReq = "CREATE VIRTUAL TABLE IF NOT EXISTS "
                + policy::MediaTable::Name + "Fts USING FTS3("
356 357
                "title,"
                "labels"
358 359 360
            ")";
    return sqlite::Tools::executeRequest( connection, req ) &&
            sqlite::Tools::executeRequest( connection, vtableReq );
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
}

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;";
379 380 381 382

    static const std::string vtableInsertTrigger = "CREATE TRIGGER IF NOT EXISTS insert_media_fts"
            " AFTER INSERT ON " + policy::MediaTable::Name +
            " BEGIN"
383
            " INSERT INTO " + policy::MediaTable::Name + "Fts(rowid,title,labels) VALUES(new.id_media, new.title, '');"
384 385
            " 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
386
            " BEFORE DELETE ON " + policy::MediaTable::Name +
387 388 389 390 391 392 393 394
            " 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";
395
    return sqlite::Tools::executeRequest( connection, triggerReq ) &&
396 397 398 399
            sqlite::Tools::executeRequest( connection, triggerReq2 ) &&
            sqlite::Tools::executeRequest( connection, vtableInsertTrigger ) &&
            sqlite::Tools::executeRequest( connection, vtableDeleteTrigger ) &&
            sqlite::Tools::executeRequest( connection, vtableUpdateTitleTrigger2 );
400
}
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
401

402
bool Media::addLabel( LabelPtr label )
403
{
404
    if ( m_id == 0 || label->id() == 0 )
405
    {
406
        LOG_ERROR( "Both file & label need to be inserted in database before being linked together" );
407 408 409
        return false;
    }
    const char* req = "INSERT INTO LabelFileRelation VALUES(?, ?)";
410 411 412 413 414
    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 );
415 416
}

417
bool Media::removeLabel( LabelPtr label )
418
{
419
    if ( m_id == 0 || label->id() == 0 )
420
    {
421
        LOG_ERROR( "Can't unlink a label/file not inserted in database" );
422 423
        return false;
    }
424
    const char* req = "DELETE FROM LabelFileRelation WHERE label_id = ? AND media_id = ?";
425 426 427 428 429
    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 );
430
}
431 432 433 434 435 436 437 438 439


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"
            " WHERE " + policy::MediaTable::Name + "Fts MATCH ?)";
    return Media::fetchAll<IMedia>( dbConn, req, title + "*" );
}