Task.cpp 12.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 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 57 58 59 60 61 62 63
    row >> m_id
        >> m_step
        >> m_retryCount
        >> mrl
        >> m_fileId
        >> m_parentFolderId
        >> m_parentPlaylistId
        >> parentPlaylistIndex;
64
    m_item = Item{ std::move( mrl ) };
65 66
}

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

void Task::markStepCompleted( ParserStep stepCompleted )
{
87 88
    m_step = static_cast<ParserStep>( static_cast<uint8_t>( m_step ) |
                                      static_cast<uint8_t>( stepCompleted ) );
89 90
}

91 92 93 94 95 96 97 98 99 100 101
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
{
102 103 104 105
    using StepType = typename std::underlying_type<ParserStep>::type;
    return ( static_cast<StepType>( m_step ) &
             static_cast<StepType>( ParserStep::Completed ) ) ==
             static_cast<StepType>( ParserStep::Completed );
106 107 108 109 110 111 112 113 114 115 116 117 118 119
}

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

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

132 133 134 135 136
int64_t Task::id() const
{
    return m_id;
}

137 138 139 140 141
Task::Item& Task::item()
{
    return m_item;
}

142 143 144 145 146
Task::Item::Item( std::string mrl )
    : m_mrl( std::move( mrl ) )
{
}

147
std::string Task::Item::meta( Task::Item::Metadata type ) const
148 149 150 151 152 153 154
{
    auto it = m_metadata.find( type );
    if ( it == end( m_metadata ) )
        return std::string{};
    return it->second;
}

155
void Task::Item::setMeta( Task::Item::Metadata type, std::string value )
156 157 158 159
{
    m_metadata[type] = std::move( value );
}

160 161 162 163 164
const std::string& Task::Item::mrl() const
{
    return m_mrl;
}

165 166 167 168 169 170 171 172 173 174
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 ) );
}

175 176 177 178 179 180 181 182 183 184
int64_t Task::Item::duration() const
{
    return m_duration;
}

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

185 186 187 188 189 190 191 192 193 194
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 ) );
}

195 196 197 198 199 200 201 202 203 204
std::shared_ptr<Media> Task::Item::media()
{
    return m_media;
}

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

205
bool Task::restoreLinkedEntities()
206
{
207
    LOG_INFO("Restoring linked entities of task ", m_id);
208 209
    // MRL will be empty if the task has been resumed from unparsed files
    // parentFolderId == 0 indicates an external file
210
    if ( m_item.mrl().empty() == true && m_parentFolderId == 0 )
211 212 213 214 215
    {
        LOG_WARN( "Aborting & removing external file task (#", m_id, ')' );
        destroy( m_ml, m_id );
        return false;
    }
216 217
    // First of all, we need to know if the file has been created already
    // ie. have we run the MetadataParser service, at least partially
218 219
    if ( m_fileId != 0 )
        file = File::fetch( m_ml, m_fileId );
220

221 222
    // We might re-create tasks without mrl to ease the handling of files on
    // external storage.
223
    if ( m_item.mrl().empty() == true )
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
    {
        // 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.
        if ( file == nullptr )
        {
            assert( !"Can't process a file without a file nor an mrl" );
            return false;
        }
        auto folder = Folder::fetch( m_ml, file->folderId() );
        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 )
        {
            LOG_WARN( "Postponing rescan of removable file ", file->rawMrl(),
                      " until the device containing it is present again" );
            return false;
        }
        setMrl( file->mrl() );
    }
250
    auto fsFactory = m_ml->fsFactoryForMrl( m_item.mrl() );
251 252 253
    if ( fsFactory == nullptr )
        return false;

254 255
    try
    {
256
        parentFolderFs = fsFactory->createDirectory( utils::file::directory( m_item.mrl() ) );
257 258 259 260
    }
    catch ( const std::system_error& ex )
    {
        LOG_ERROR( "Failed to restore task: ", ex.what() );
261
        return false;
262
    }
263 264 265 266 267

    try
    {
        auto files = parentFolderFs->files();
        auto it = std::find_if( begin( files ), end( files ), [this]( std::shared_ptr<fs::IFile> f ) {
268
            return f->mrl() == m_item.mrl();
269 270 271
        });
        if ( it == end( files ) )
        {
272
            LOG_ERROR( "Failed to restore fs::IFile associated with ", m_item.mrl() );
273 274 275 276 277
            return false;
        }
        fileFs = *it;
    }
    catch ( const std::system_error& ex )
278
    {
279 280 281 282
        // If we never found the file yet, we can delete the task. It will be
        // recreated upon next discovery
        if ( file == nullptr )
        {
283
            LOG_WARN( "Failed to restore file system instances for mrl ", m_item.mrl(), "."
284 285 286 287 288 289 290 291 292
                      " 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)
293
            LOG_WARN( "Failed to restore file system instances for mrl ", m_item.mrl(), "."
294 295
                      " Postponing the task." );
        }
296 297 298
        return false;
    }

299
    if ( file != nullptr )
300
        m_item.setMedia( file->media() );
301

302 303 304 305 306 307 308
    parentFolder = Folder::fetch( m_ml, m_parentFolderId );
    if ( m_parentPlaylistId != 0 )
        parentPlaylist = Playlist::fetch( m_ml, m_parentPlaylistId );

    return true;
}

309 310
void Task::setMrl( std::string newMrl )
{
311
    if ( m_item.mrl() == newMrl )
312 313 314 315 316
        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;
317
    m_item = Item{ std::move( newMrl ) };
318 319
}

320 321 322 323 324 325 326 327 328 329 330
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,"
331
        "UNIQUE(mrl, parent_playlist_id) ON CONFLICT FAIL,"
332 333 334 335 336 337 338 339 340 341 342 343 344
        "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 "
345 346 347
            "retry_count = 0 WHERE step & ? != ?";
    sqlite::Tools::executeUpdate( ml->getConn(), req, parser::Task::ParserStep::Completed,
                                  parser::Task::ParserStep::Completed);
348 349 350 351 352 353 354 355 356
}

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

357
std::vector<std::shared_ptr<Task>> Task::fetchUncompleted( MediaLibraryPtr ml )
358 359 360
{
    static const std::string req = "SELECT * FROM " + policy::TaskTable::Name + " t"
        " LEFT JOIN " + policy::FileTable::Name + " f ON f.id_file = t.file_id"
361
        " WHERE step & ? != ? AND retry_count < 3 AND (f.is_present != 0 OR "
362
        " t.file_id IS NULL)";
363 364
    return Task::fetchAll<Task>( ml, req, parser::Task::ParserStep::Completed,
                                 parser::Task::ParserStep::Completed );
365 366 367 368 369 370 371 372 373 374 375 376 377
}

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 )
{
    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(?, ?, ?, ?)";
378
    if ( insert( ml, self, req, self->m_item.mrl(), self->parentFolder->id(), sqlite::ForeignKey(
379 380 381 382
                 self->parentPlaylist ? self->parentPlaylist->id() : 0 ),
                 self->parentPlaylistIndex ) == false )
        return nullptr;
    return self;
383 384
}

385 386 387 388 389 390
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"
391 392
            " ON t.file_id = f.id_file WHERE t.file_id IS NULL"
            " AND f.folder_id IS NOT NULL";
393 394 395
    sqlite::Tools::executeInsert( ml->getConn(), req );
}

396 397 398
}

}