Task.cpp 16.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 23 24 25 26 27 28 29
/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 - 2017 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *          Alexandre Fernandez <nerf@boboop.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.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "Task.h"

30 31
#include "medialibrary/filesystem/IFile.h"
#include "medialibrary/filesystem/IDirectory.h"
32
#include "Device.h"
33
#include "File.h"
34 35
#include "Folder.h"
#include "Playlist.h"
36
#include "Media.h"
37 38
#include "parser/Task.h"
#include "utils/Filename.h"
39
#include "utils/Url.h"
40

41 42
#include <algorithm>

43 44 45 46 47 48
namespace medialibrary
{

namespace parser
{

49 50 51 52
const std::string Task::Table::Name = "Task";
const std::string Task::Table::PrimaryKeyColumn = "id_task";
int64_t parser::Task::* const Task::Table::PrimaryKey = &parser::Task::m_id;

53 54 55
Task::Task( MediaLibraryPtr ml, sqlite::Row& row )
    : currentService( 0 )
    , m_ml( ml )
56
{
57
    std::string mrl;
58
    unsigned int parentPlaylistIndex;
59
    IFile::Type fileType;
60
    bool isRefresh;
61 62 63 64
    row >> m_id
        >> m_step
        >> m_retryCount
        >> mrl
65
        >> fileType
66 67 68
        >> m_fileId
        >> m_parentFolderId
        >> m_parentPlaylistId
69 70
        >> parentPlaylistIndex
        >> isRefresh;
71
    m_item = Item{ this, std::move( mrl ), fileType, parentPlaylistIndex, isRefresh };
72 73
}

74
Task::Task( MediaLibraryPtr ml, std::shared_ptr<fs::IFile> fileFs,
75
            std::shared_ptr<Folder> parentFolder,
76
            std::shared_ptr<fs::IDirectory> parentFolderFs,
77
            IFile::Type fileType,
78
            std::shared_ptr<Playlist> parentPlaylist,
79
            unsigned int parentPlaylistIndex )
80
    : currentService( 0 )
81
    , m_ml( ml )
82
    , m_step( Step::None )
83
    , m_fileId( 0 )
84
    , m_item( this, std::move( fileFs ), std::move( parentFolder ),
85 86
              std::move( parentFolderFs ), fileType,
              std::move( parentPlaylist ), parentPlaylistIndex, false )
87 88 89 90 91 92 93 94 95 96
{
}

Task::Task( MediaLibraryPtr ml, std::shared_ptr<File> file,
            std::shared_ptr<fs::IFile> fileFs )
    : currentService( 0 )
    , m_ml( ml )
    , m_step( Step::None )
    , m_fileId( file->id() )
    , m_item( this, std::move( file ), std::move( fileFs ) )
97 98 99
{
}

100
void Task::markStepCompleted( Step stepCompleted )
101
{
102
    m_step = static_cast<Step>( static_cast<uint8_t>( m_step ) |
103
                                      static_cast<uint8_t>( stepCompleted ) );
104 105
}

106 107
bool Task::saveParserStep()
{
108
    static const std::string req = "UPDATE " + Task::Table::Name + " SET step = ?, "
109
            "retry_count = 0 WHERE id_task = ?";
110
    return sqlite::Tools::executeUpdate( m_ml->getConn(), req, m_step, m_id );
111 112
}

113
bool Task::decrementRetryCount()
114
{
115
    static const std::string req = "UPDATE " + Task::Table::Name + " SET "
116
            "retry_count = retry_count - 1 WHERE id_task = ?";
117 118 119
    return sqlite::Tools::executeUpdate( m_ml->getConn(), req, m_id );
}

120 121
bool Task::isCompleted() const
{
122
    using StepType = typename std::underlying_type<Step>::type;
123
    return ( static_cast<StepType>( m_step ) &
124 125
             static_cast<StepType>( Step::Completed ) ) ==
             static_cast<StepType>( Step::Completed );
126 127
}

128
bool Task::isStepCompleted( Step step ) const
129 130 131 132 133 134
{
    return ( static_cast<uint8_t>( m_step ) & static_cast<uint8_t>( step ) ) != 0;
}

void Task::startParserStep()
{
135
    static const std::string req = "UPDATE " + Task::Table::Name + " SET "
136 137 138 139
            "retry_count = retry_count + 1 WHERE id_task = ?";
    sqlite::Tools::executeUpdate( m_ml->getConn(), req, m_id );
}

140
bool Task::updateFileId( int64_t fileId )
141
{
142 143 144 145 146 147
    // When restoring a task, we will invoke ITaskCb::updateFileId while the
    // task already knows the fileId (since we're using it to restore the file instance)
    // In this case, bail out. Otherwise, it is not expected for the task to change
    // its associated file during the processing.
    if ( m_fileId == fileId && fileId != 0 )
        return true ;
148
    assert( m_fileId == 0 );
149
    assert( fileId != 0 );
150
    static const std::string req = "UPDATE " + Task::Table::Name + " SET "
151
            "file_id = ? WHERE id_task = ?";
152
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, fileId, m_id ) == false )
153
        return false;
154
    m_fileId = fileId;
155 156 157
    return true;
}

158 159 160 161 162
int64_t Task::id() const
{
    return m_id;
}

163 164 165 166 167
Task::Item& Task::item()
{
    return m_item;
}

168 169
Task::Item::Item( ITaskCb* taskCb, std::string mrl, IFile::Type fileType,
                  unsigned int subitemPosition, bool isRefresh )
170 171
    : m_taskCb( taskCb )
    , m_mrl( std::move( mrl ) )
172
    , m_fileType( fileType )
173
    , m_duration( 0 )
174
    , m_parentPlaylistIndex( subitemPosition )
175
    , m_isRefresh( isRefresh )
176 177 178
{
}

179
Task::Item::Item(ITaskCb* taskCb, std::shared_ptr<fs::IFile> fileFs,
180
                  std::shared_ptr<Folder> parentFolder,
181
                  std::shared_ptr<fs::IDirectory> parentFolderFs, IFile::Type fileType,
182 183
                  std::shared_ptr<Playlist> parentPlaylist, unsigned int parentPlaylistIndex,
                  bool isRefresh )
184 185
    : m_taskCb( taskCb )
    , m_mrl( fileFs->mrl() )
186
    , m_fileType( fileType )
187 188 189 190 191 192
    , m_duration( 0 )
    , m_fileFs( std::move( fileFs ) )
    , m_parentFolder( std::move( parentFolder ) )
    , m_parentFolderFs( std::move( parentFolderFs ) )
    , m_parentPlaylist( std::move( parentPlaylist ) )
    , m_parentPlaylistIndex( parentPlaylistIndex )
193 194 195 196
    , m_isRefresh( isRefresh )
{
}

197 198
Task::Item::Item( ITaskCb* taskCb, std::shared_ptr<File> file,
                  std::shared_ptr<fs::IFile> fileFs )
199 200
    : m_taskCb( taskCb )
    , m_mrl( fileFs->mrl() )
201
    , m_fileType( file->type() )
202 203 204 205
    , m_duration( 0 )
    , m_file( std::move( file ) )
    , m_fileFs( std::move( fileFs ) )
    , m_isRefresh( true )
206 207 208
{
}

209
std::string Task::Item::meta( Task::Item::Metadata type ) const
210 211 212 213 214 215 216
{
    auto it = m_metadata.find( type );
    if ( it == end( m_metadata ) )
        return std::string{};
    return it->second;
}

217
void Task::Item::setMeta( Task::Item::Metadata type, std::string value )
218 219 220 221
{
    m_metadata[type] = std::move( value );
}

222 223 224 225 226
const std::string& Task::Item::mrl() const
{
    return m_mrl;
}

227 228 229 230 231
void Task::Item::setMrl( std::string mrl )
{
    m_mrl = std::move( mrl );
}

232 233 234 235 236
IFile::Type Task::Item::fileType() const
{
    return m_fileType;
}

237
size_t Task::Item::nbSubItems() const
238
{
239 240 241
    return m_subItems.size();
}

242
const IItem& Task::Item::subItem( unsigned int index ) const
243 244
{
    return m_subItems[index];
245 246
}

247
IItem& Task::Item::createSubItem( std::string mrl, unsigned int playlistIndex )
248
{
249 250
    m_subItems.emplace_back( nullptr, std::move( mrl ), IFile::Type::Main,
                             playlistIndex, false );
251
    return m_subItems.back();
252 253
}

254 255 256 257 258 259 260 261 262 263
int64_t Task::Item::duration() const
{
    return m_duration;
}

void Task::Item::setDuration( int64_t duration )
{
    m_duration = duration;
}

264 265 266 267 268 269 270 271 272 273
const std::vector<Task::Item::Track>& Task::Item::tracks() const
{
    return m_tracks;
}

void Task::Item::addTrack(Task::Item::Track t)
{
    m_tracks.emplace_back( std::move( t ) );
}

274
MediaPtr Task::Item::media()
275 276 277 278
{
    return m_media;
}

279
void Task::Item::setMedia( MediaPtr media )
280 281 282 283
{
    m_media = std::move( media );
}

284
FilePtr Task::Item::file()
285 286 287 288
{
    return m_file;
}

289
bool Task::Item::setFile( FilePtr file)
290 291
{
    m_file = std::move( file );
292 293
    assert( m_taskCb != nullptr );
    return m_taskCb->updateFileId( m_file->id() );
294 295
}

296
FolderPtr Task::Item::parentFolder()
297 298 299 300 301 302 303 304 305 306 307 308 309 310
{
    return m_parentFolder;
}

std::shared_ptr<fs::IFile> Task::Item::fileFs()
{
    return m_fileFs;
}

std::shared_ptr<fs::IDirectory> Task::Item::parentFolderFs()
{
    return m_parentFolderFs;
}

311
PlaylistPtr Task::Item::parentPlaylist()
312 313 314 315 316 317 318 319 320
{
    return m_parentPlaylist;
}

unsigned int Task::Item::parentPlaylistIndex() const
{
    return m_parentPlaylistIndex;
}

321 322 323 324 325
bool Task::Item::isRefresh() const
{
    return m_isRefresh;
}

326
bool Task::restoreLinkedEntities()
327
{
328
    LOG_INFO("Restoring linked entities of task ", m_id);
329 330
    // MRL will be empty if the task has been resumed from unparsed files
    // parentFolderId == 0 indicates an external file
331 332
    auto mrl = m_item.mrl();
    if ( mrl.empty() == true && m_parentFolderId == 0 )
333 334 335 336 337
    {
        LOG_WARN( "Aborting & removing external file task (#", m_id, ')' );
        destroy( m_ml, m_id );
        return false;
    }
338 339
    // First of all, we need to know if the file has been created already
    // ie. have we run the MetadataParser service, at least partially
340
    std::shared_ptr<File> file;
341
    if ( m_fileId != 0 )
342
        file = File::fetch( m_ml, m_fileId );
343

344 345
    // We might re-create tasks without mrl to ease the handling of files on
    // external storage.
346
    if ( mrl.empty() == true )
347 348 349 350
    {
        // but we expect those to be created from an existing file after a
        // partial/failed migration. If we don't have a file nor an mrl, we
        // can't really process it.
351
        if ( file == nullptr )
352 353 354 355
        {
            assert( !"Can't process a file without a file nor an mrl" );
            return false;
        }
356
        auto folder = Folder::fetch( m_ml, file->folderId() );
357 358 359 360 361 362 363 364 365 366
        if ( folder == nullptr )
        {
            assert( !"Can't file the folder associated with a file" );
            // If the folder can't be found in db while the file can, it looks
            // a lot like a sporadic failure, since file are deleted through
            // triggers when its parent folder gets deleted. Just postpone this.
            return false;
        }
        if ( folder->isPresent() == false )
        {
367
            LOG_WARN( "Postponing rescan of removable file ", file->rawMrl(),
368 369 370
                      " until the device containing it is present again" );
            return false;
        }
371
        setMrl( file->mrl() );
372
    }
373
    auto fsFactory = m_ml->fsFactoryForMrl( mrl );
374 375 376
    if ( fsFactory == nullptr )
        return false;

377
    std::shared_ptr<fs::IDirectory> parentFolderFs;
378 379
    try
    {
380
        parentFolderFs = fsFactory->createDirectory( utils::file::directory( mrl ) );
381 382 383 384
    }
    catch ( const std::system_error& ex )
    {
        LOG_ERROR( "Failed to restore task: ", ex.what() );
385
        return false;
386
    }
387

388
    std::shared_ptr<fs::IFile> fileFs;
389 390
    try
    {
391 392 393
        auto files = parentFolderFs->files();
        auto it = std::find_if( begin( files ), end( files ), [&mrl]( std::shared_ptr<fs::IFile> f ) {
            return f->mrl() == mrl;
394 395 396
        });
        if ( it == end( files ) )
        {
397
            LOG_ERROR( "Failed to restore fs::IFile associated with ", mrl );
398 399
            return false;
        }
400
        fileFs = std::move( *it );
401 402
    }
    catch ( const std::system_error& ex )
403
    {
404 405
        // If we never found the file yet, we can delete the task. It will be
        // recreated upon next discovery
406
        if ( file == nullptr )
407
        {
408 409
            LOG_WARN( "Failed to restore file system instances for mrl ", mrl, "(",
                      ex.what(), ").", " Removing the task until it gets detected again." );
410 411 412 413 414 415 416 417
            destroy( m_ml, m_id );
        }
        else
        {
            // Otherwise we need to postpone it, although most likely we will
            // detect that the file is now missing, and we won't try to restore
            // this task until it comes back (since the task restoration request
            // includes the file.is_present flag)
418
            LOG_WARN( "Failed to restore file system instances for mrl ", mrl, "."
419 420
                      " Postponing the task." );
        }
421 422 423
        return false;
    }

424 425 426 427 428 429 430
    std::shared_ptr<Folder> parentFolder = Folder::fetch( m_ml, m_parentFolderId );
    if ( parentFolder == nullptr )
    {
        LOG_ERROR( "Failed to restore parent folder #", m_parentFolderId );
        return false;
    }
    std::shared_ptr<Playlist> parentPlaylist;
431
    if ( m_parentPlaylistId != 0 )
432 433 434 435 436 437 438 439
    {
        parentPlaylist = Playlist::fetch( m_ml, m_parentPlaylistId );
        if ( parentPlaylist == nullptr )
        {
            LOG_ERROR( "Failed to restore parent playlist #", m_parentPlaylistId );
            return false;
        }
    }
440

441
    m_item = Item{ this, std::move( fileFs ), std::move( parentFolder ),
442 443 444
                   std::move( parentFolderFs ), m_item.fileType(),
                   std::move( parentPlaylist ), m_item.parentPlaylistIndex(),
                   m_item.isRefresh() };
445 446 447 448 449
    if ( file != nullptr )
    {
        m_item.setMedia( file->media() );
        m_item.setFile( std::move( file ) );
    }
450 451 452
    return true;
}

453 454
void Task::setMrl( std::string newMrl )
{
455
    if ( m_item.mrl() == newMrl )
456
        return;
457
    static const std::string req = "UPDATE " + Task::Table::Name + " SET "
458 459 460
            "mrl = ? WHERE id_task = ?";
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, newMrl, m_id ) == false )
        return;
461
    m_item.setMrl( std::move( newMrl ) );
462 463
}

464 465
void Task::createTable( sqlite::Connection* dbConnection )
{
466 467 468 469 470
    std::string reqs[] = {
        #include "database/tables/Task_v14.sql"
    };
    for ( const auto& req : reqs )
        sqlite::Tools::executeRequest( dbConnection, req );
471 472 473 474
}

void Task::resetRetryCount( MediaLibraryPtr ml )
{
475
    static const std::string req = "UPDATE " + Task::Table::Name + " SET "
476
            "retry_count = 0 WHERE step & ? != ?";
477 478
    sqlite::Tools::executeUpdate( ml->getConn(), req, Step::Completed,
                                  Step::Completed);
479 480 481 482
}

void Task::resetParsing( MediaLibraryPtr ml )
{
483
    static const std::string req = "UPDATE " + Task::Table::Name + " SET "
484
            "retry_count = 0, step = ?";
485
    sqlite::Tools::executeUpdate( ml->getConn(), req, Step::None );
486 487
}

488
std::vector<std::shared_ptr<Task>> Task::fetchUncompleted( MediaLibraryPtr ml )
489
{
490 491
    static const std::string req = "SELECT * FROM " + Task::Table::Name + " t"
        " LEFT JOIN " + File::Table::Name + " f ON f.id_file = t.file_id"
492 493 494
        " LEFT JOIN " + Folder::Table::Name + " fol ON f.folder_id = fol.id_folder"
        " LEFT JOIN " + Device::Table::Name + " d ON d.id_device = fol.device_id"
        " WHERE step & ? != ? AND retry_count < 3 AND (d.is_present != 0 OR "
495
        " t.file_id IS NULL)";
496 497
    return Task::fetchAll<Task>( ml, req, Step::Completed,
                                 Step::Completed );
498 499 500 501 502
}

std::shared_ptr<Task>
Task::create( MediaLibraryPtr ml, std::shared_ptr<fs::IFile> fileFs,
              std::shared_ptr<Folder> parentFolder, std::shared_ptr<fs::IDirectory> parentFolderFs,
503
              IFile::Type fileType,
504 505
              std::pair<std::shared_ptr<Playlist>, unsigned int> parentPlaylist )
{
506 507 508 509
    auto parentFolderId = parentFolder->id();
    auto parentPlaylistId = parentPlaylist.first != nullptr ? parentPlaylist.first->id() : 0;
    auto parentPlaylistIndex = parentPlaylist.second;

510
    std::shared_ptr<Task> self = std::make_shared<Task>( ml, std::move( fileFs ),
511
        std::move( parentFolder ), std::move( parentFolderFs ), fileType,
512
        std::move( parentPlaylist.first ), parentPlaylist.second );
513
    const std::string req = "INSERT INTO " + Task::Table::Name +
514 515 516 517
        "(mrl, file_type, parent_folder_id, parent_playlist_id, "
        "parent_playlist_index, is_refresh) "
        "VALUES(?, ?, ?, ?, ?, ?)";
    if ( insert( ml, self, req, self->m_item.mrl(), fileType, parentFolderId,
518
                 sqlite::ForeignKey( parentPlaylistId ),
519
                 parentPlaylistIndex, false ) == false )
520 521
        return nullptr;
    return self;
522 523
}

524
std::shared_ptr<Task>
525
Task::createRefreshTask( MediaLibraryPtr ml, std::shared_ptr<File> file,
526 527 528 529 530 531 532 533 534 535 536
              std::shared_ptr<fs::IFile> fileFs )
{
    auto self = std::make_shared<Task>( ml, std::move( file ), std::move( fileFs ) );
    const std::string req = "INSERT INTO " + Task::Table::Name +
            "(mrl, file_id, is_refresh) VALUES(?, ?, ?)";
    if ( insert( ml, self, req, self->m_item.mrl(), self->m_item.file()->id(),
                 true ) == false )
        return nullptr;
    return self;
}

537 538
void Task::recoverUnscannedFiles( MediaLibraryPtr ml )
{
539
    static const std::string req = "INSERT INTO " + Task::Table::Name +
540
            "(file_id, parent_folder_id)"
541 542
            " SELECT id_file, folder_id FROM " + File::Table::Name +
            " f LEFT JOIN " + Task::Table::Name + " t"
543 544
            " ON t.file_id = f.id_file WHERE t.file_id IS NULL"
            " AND f.folder_id IS NOT NULL";
545 546 547
    sqlite::Tools::executeInsert( ml->getConn(), req );
}

548 549 550
}

}