Task.cpp 15 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 30
/*****************************************************************************
 * 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"

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

39 40
#include <algorithm>

41 42 43
namespace medialibrary
{

44 45 46 47
const std::string policy::TaskTable::Name = "Task";
const std::string policy::TaskTable::PrimaryKeyColumn = "id_task";
int64_t parser::Task::* const policy::TaskTable::PrimaryKey = &parser::Task::m_id;

48 49 50
namespace parser
{

51 52 53
Task::Task( MediaLibraryPtr ml, sqlite::Row& row )
    : currentService( 0 )
    , m_ml( ml )
54
{
55
    std::string mrl;
56
    unsigned int parentPlaylistIndex;
57 58 59 60 61 62 63 64
    row >> m_id
        >> m_step
        >> m_retryCount
        >> mrl
        >> m_fileId
        >> m_parentFolderId
        >> m_parentPlaylistId
        >> parentPlaylistIndex;
65
    m_item = Item{ std::move( mrl ), parentPlaylistIndex };
66 67
}

68
Task::Task( MediaLibraryPtr ml, std::shared_ptr<fs::IFile> fileFs,
69
            std::shared_ptr<Folder> parentFolder,
70
            std::shared_ptr<fs::IDirectory> parentFolderFs,
71
            std::shared_ptr<Playlist> parentPlaylist,
72
            unsigned int parentPlaylistIndex )
73
    : currentService( 0 )
74 75
    , m_ml( ml )
    , m_step( ParserStep::None )
76
    , m_fileId( 0 )
77 78
    , m_item( std::move( fileFs ), std::move( parentFolder ),
              std::move( parentFolderFs ), std::move( parentPlaylist ), parentPlaylistIndex )
79 80 81 82 83
{
}

void Task::markStepCompleted( ParserStep stepCompleted )
{
84 85
    m_step = static_cast<ParserStep>( static_cast<uint8_t>( m_step ) |
                                      static_cast<uint8_t>( stepCompleted ) );
86 87
}

88 89 90 91 92 93 94 95 96 97 98
bool Task::saveParserStep()
{
    static const std::string req = "UPDATE " + policy::TaskTable::Name + " SET step = ?, "
            "retry_count = 0 WHERE id_task = ?";
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, m_step, m_id ) == false )
        return false;
    return true;
}

bool Task::isCompleted() const
{
99 100 101 102
    using StepType = typename std::underlying_type<ParserStep>::type;
    return ( static_cast<StepType>( m_step ) &
             static_cast<StepType>( ParserStep::Completed ) ) ==
             static_cast<StepType>( ParserStep::Completed );
103 104 105 106 107 108 109 110 111 112 113 114 115 116
}

bool Task::isStepCompleted( Task::ParserStep step ) const
{
    return ( static_cast<uint8_t>( m_step ) & static_cast<uint8_t>( step ) ) != 0;
}

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

117 118 119
bool Task::updateFileId()
{
    assert( m_fileId == 0 );
120
    assert( m_item.file() != nullptr && m_item.file()->id() != 0 );
121 122
    static const std::string req = "UPDATE " + policy::TaskTable::Name + " SET "
            "file_id = ? WHERE id_task = ?";
123
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, m_item.file()->id(), m_id ) == false )
124
        return false;
125
    m_fileId = m_item.file()->id();
126 127 128
    return true;
}

129 130 131 132 133
int64_t Task::id() const
{
    return m_id;
}

134 135 136 137 138
Task::Item& Task::item()
{
    return m_item;
}

139
Task::Item::Item( std::string mrl, unsigned int subitemPosition )
140
    : m_mrl( std::move( mrl ) )
141
    , m_duration( 0 )
142
    , m_parentPlaylistIndex( subitemPosition )
143 144 145 146 147 148 149 150 151 152 153 154 155 156
{
}

Task::Item::Item( std::shared_ptr<fs::IFile> fileFs,
                  std::shared_ptr<Folder> parentFolder,
                  std::shared_ptr<fs::IDirectory> parentFolderFs,
                  std::shared_ptr<Playlist> parentPlaylist, unsigned int parentPlaylistIndex  )
    : m_mrl( fileFs->mrl() )
    , 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 )
157 158 159
{
}

160
std::string Task::Item::meta( Task::Item::Metadata type ) const
161 162 163 164 165 166 167
{
    auto it = m_metadata.find( type );
    if ( it == end( m_metadata ) )
        return std::string{};
    return it->second;
}

168
void Task::Item::setMeta( Task::Item::Metadata type, std::string value )
169 170 171 172
{
    m_metadata[type] = std::move( value );
}

173 174 175 176 177
const std::string& Task::Item::mrl() const
{
    return m_mrl;
}

178 179 180 181 182
void Task::Item::setMrl( std::string mrl )
{
    m_mrl = std::move( mrl );
}

183 184 185 186 187 188 189 190 191 192
const std::vector<Task::Item>& Task::Item::subItems() const
{
    return m_subItems;
}

void Task::Item::addSubItem( Task::Item item )
{
    m_subItems.emplace_back( std::move( item ) );
}

193 194 195 196 197 198 199 200 201 202
int64_t Task::Item::duration() const
{
    return m_duration;
}

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

203 204 205 206 207 208 209 210 211 212
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 ) );
}

213 214 215 216 217 218 219 220 221 222
std::shared_ptr<Media> Task::Item::media()
{
    return m_media;
}

void Task::Item::setMedia( std::shared_ptr<Media> media )
{
    m_media = std::move( media );
}

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
std::shared_ptr<File> Task::Item::file()
{
    return m_file;
}

void Task::Item::setFile(std::shared_ptr<File> file)
{
    m_file = std::move( file );
}

std::shared_ptr<Folder> Task::Item::parentFolder()
{
    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;
}

std::shared_ptr<Playlist> Task::Item::parentPlaylist()
{
    return m_parentPlaylist;
}

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

258
bool Task::restoreLinkedEntities()
259
{
260
    LOG_INFO("Restoring linked entities of task ", m_id);
261 262
    // MRL will be empty if the task has been resumed from unparsed files
    // parentFolderId == 0 indicates an external file
263 264
    auto mrl = m_item.mrl();
    if ( mrl.empty() == true && m_parentFolderId == 0 )
265 266 267 268 269
    {
        LOG_WARN( "Aborting & removing external file task (#", m_id, ')' );
        destroy( m_ml, m_id );
        return false;
    }
270 271
    // First of all, we need to know if the file has been created already
    // ie. have we run the MetadataParser service, at least partially
272
    std::shared_ptr<File> file;
273
    if ( m_fileId != 0 )
274
        file = File::fetch( m_ml, m_fileId );
275

276 277
    // We might re-create tasks without mrl to ease the handling of files on
    // external storage.
278
    if ( mrl.empty() == true )
279 280 281 282
    {
        // 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.
283
        if ( file == nullptr )
284 285 286 287
        {
            assert( !"Can't process a file without a file nor an mrl" );
            return false;
        }
288
        auto folder = Folder::fetch( m_ml, file->folderId() );
289 290 291 292 293 294 295 296 297 298
        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 )
        {
299
            LOG_WARN( "Postponing rescan of removable file ", file->rawMrl(),
300 301 302
                      " until the device containing it is present again" );
            return false;
        }
303
        setMrl( file->mrl() );
304
    }
305
    auto fsFactory = m_ml->fsFactoryForMrl( mrl );
306 307 308
    if ( fsFactory == nullptr )
        return false;

309
    std::shared_ptr<fs::IDirectory> parentFolderFs;
310 311
    try
    {
312
        parentFolderFs = fsFactory->createDirectory( utils::file::directory( mrl ) );
313 314 315 316
    }
    catch ( const std::system_error& ex )
    {
        LOG_ERROR( "Failed to restore task: ", ex.what() );
317
        return false;
318
    }
319

320
    std::shared_ptr<fs::IFile> fileFs;
321 322
    try
    {
323 324 325
        auto files = parentFolderFs->files();
        auto it = std::find_if( begin( files ), end( files ), [&mrl]( std::shared_ptr<fs::IFile> f ) {
            return f->mrl() == mrl;
326 327 328
        });
        if ( it == end( files ) )
        {
329
            LOG_ERROR( "Failed to restore fs::IFile associated with ", mrl );
330 331
            return false;
        }
332
        fileFs = std::move( *it );
333 334
    }
    catch ( const std::system_error& ex )
335
    {
336 337
        // If we never found the file yet, we can delete the task. It will be
        // recreated upon next discovery
338
        if ( file == nullptr )
339
        {
340
            LOG_WARN( "Failed to restore file system instances for mrl ", mrl, "."
341 342 343 344 345 346 347 348 349
                      " Removing the task until it gets detected again." );
            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)
350
            LOG_WARN( "Failed to restore file system instances for mrl ", mrl, "."
351 352
                      " Postponing the task." );
        }
353 354 355
        return false;
    }

356 357 358 359 360 361 362
    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;
363
    if ( m_parentPlaylistId != 0 )
364 365 366 367 368 369 370 371
    {
        parentPlaylist = Playlist::fetch( m_ml, m_parentPlaylistId );
        if ( parentPlaylist == nullptr )
        {
            LOG_ERROR( "Failed to restore parent playlist #", m_parentPlaylistId );
            return false;
        }
    }
372

373 374 375 376 377 378 379 380
    m_item = Item{ std::move( fileFs ), std::move( parentFolder ),
                   std::move( parentFolderFs ), std::move( parentPlaylist ),
                   m_item.parentPlaylistIndex() };
    if ( file != nullptr )
    {
        m_item.setMedia( file->media() );
        m_item.setFile( std::move( file ) );
    }
381 382 383
    return true;
}

384 385
void Task::setMrl( std::string newMrl )
{
386
    if ( m_item.mrl() == newMrl )
387 388 389 390 391
        return;
    static const std::string req = "UPDATE " + policy::TaskTable::Name + " SET "
            "mrl = ? WHERE id_task = ?";
    if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, newMrl, m_id ) == false )
        return;
392
    m_item.setMrl( std::move( newMrl ) );
393 394
}

395 396 397 398 399 400 401 402 403 404 405
void Task::createTable( sqlite::Connection* dbConnection )
{
    std::string req = "CREATE TABLE IF NOT EXISTS " + policy::TaskTable::Name + "("
        "id_task INTEGER PRIMARY KEY AUTOINCREMENT,"
        "step INTEGER NOT NULL DEFAULT 0,"
        "retry_count INTEGER NOT NULL DEFAULT 0,"
        "mrl TEXT,"
        "file_id UNSIGNED INTEGER,"
        "parent_folder_id UNSIGNED INTEGER,"
        "parent_playlist_id INTEGER,"
        "parent_playlist_index UNSIGNED INTEGER,"
406
        "UNIQUE(mrl, parent_playlist_id) ON CONFLICT FAIL,"
407 408 409 410 411 412 413 414 415 416 417 418 419
        "FOREIGN KEY (parent_folder_id) REFERENCES " + policy::FolderTable::Name
        + "(id_folder) ON DELETE CASCADE,"
        "FOREIGN KEY (file_id) REFERENCES " + policy::FileTable::Name
        + "(id_file) ON DELETE CASCADE,"
        "FOREIGN KEY (parent_playlist_id) REFERENCES " + policy::PlaylistTable::Name
        + "(id_playlist) ON DELETE CASCADE"
    ")";
    sqlite::Tools::executeRequest( dbConnection, req );
}

void Task::resetRetryCount( MediaLibraryPtr ml )
{
    static const std::string req = "UPDATE " + policy::TaskTable::Name + " SET "
420 421 422
            "retry_count = 0 WHERE step & ? != ?";
    sqlite::Tools::executeUpdate( ml->getConn(), req, parser::Task::ParserStep::Completed,
                                  parser::Task::ParserStep::Completed);
423 424 425 426 427 428 429 430 431
}

void Task::resetParsing( MediaLibraryPtr ml )
{
    static const std::string req = "UPDATE " + policy::TaskTable::Name + " SET "
            "retry_count = 0, step = ?";
    sqlite::Tools::executeUpdate( ml->getConn(), req, parser::Task::ParserStep::None );
}

432
std::vector<std::shared_ptr<Task>> Task::fetchUncompleted( MediaLibraryPtr ml )
433 434 435
{
    static const std::string req = "SELECT * FROM " + policy::TaskTable::Name + " t"
        " LEFT JOIN " + policy::FileTable::Name + " f ON f.id_file = t.file_id"
436
        " WHERE step & ? != ? AND retry_count < 3 AND (f.is_present != 0 OR "
437
        " t.file_id IS NULL)";
438 439
    return Task::fetchAll<Task>( ml, req, parser::Task::ParserStep::Completed,
                                 parser::Task::ParserStep::Completed );
440 441 442 443 444 445 446
}

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,
              std::pair<std::shared_ptr<Playlist>, unsigned int> parentPlaylist )
{
447 448 449 450
    auto parentFolderId = parentFolder->id();
    auto parentPlaylistId = parentPlaylist.first != nullptr ? parentPlaylist.first->id() : 0;
    auto parentPlaylistIndex = parentPlaylist.second;

451 452 453 454 455 456
    std::shared_ptr<Task> self = std::make_shared<Task>( ml, std::move( fileFs ),
        std::move( parentFolder ), std::move( parentFolderFs ),
        std::move( parentPlaylist.first ), parentPlaylist.second );
    const std::string req = "INSERT INTO " + policy::TaskTable::Name +
        "(mrl, parent_folder_id, parent_playlist_id, parent_playlist_index) "
        "VALUES(?, ?, ?, ?)";
457 458 459
    if ( insert( ml, self, req, self->m_item.mrl(), parentFolderId,
                 sqlite::ForeignKey( parentPlaylistId ),
                 parentPlaylistIndex ) == false )
460 461
        return nullptr;
    return self;
462 463
}

464 465 466 467 468 469
void Task::recoverUnscannedFiles( MediaLibraryPtr ml )
{
    static const std::string req = "INSERT INTO " + policy::TaskTable::Name +
            "(file_id, parent_folder_id)"
            " SELECT id_file, folder_id FROM " + policy::FileTable::Name +
            " f LEFT JOIN " + policy::TaskTable::Name + " t"
470 471
            " ON t.file_id = f.id_file WHERE t.file_id IS NULL"
            " AND f.folder_id IS NOT NULL";
472 473 474
    sqlite::Tools::executeInsert( ml->getConn(), req );
}

475 476 477
}

}