FsDiscoverer.cpp 11.6 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 24 25 26
#if HAVE_CONFIG_H
# include "config.h"
#endif

27 28
#include "FsDiscoverer.h"

29
#include <algorithm>
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
30 31
#include <queue>

32
#include "factory/FileSystemFactory.h"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
33
#include "filesystem/IDevice.h"
34
#include "Media.h"
35
#include "File.h"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
36
#include "Device.h"
37
#include "Folder.h"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
38
#include "logging/Logger.h"
39
#include "MediaLibrary.h"
40
#include "utils/Filename.h"
41

42 43 44
namespace medialibrary
{

45
FsDiscoverer::FsDiscoverer( std::shared_ptr<factory::IFileSystem> fsFactory, MediaLibrary* ml, IMediaLibraryCb* cb )
46
    : m_ml( ml )
47
    , m_fsFactory( fsFactory )
48
    , m_cb( cb )
49 50 51
{
}

52
bool FsDiscoverer::discover( const std::string &entryPoint )
53
{
54
    LOG_INFO( "Adding to discovery list: ", entryPoint );
55

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
56
    if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
57
        return false;
58

59 60
    std::shared_ptr<fs::IDirectory> fsDir = m_fsFactory->createDirectory( entryPoint );
    // Otherwise, create a directory and check it for modifications
61 62 63 64 65
    if ( fsDir == nullptr )
    {
        LOG_ERROR("Failed to create an IDirectory for ", entryPoint );
        return false;
    }
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
66
    auto f = Folder::fromMrl( m_ml, fsDir->mrl() );
67 68 69
    // If the folder exists, we assume it will be handled by reload()
    if ( f != nullptr )
        return true;
70 71
    try
    {
72 73
        if ( hasDotNoMediaFile( *fsDir ) )
            return true;
74 75
        return addFolder( *fsDir, nullptr );
    }
76 77 78 79 80
    catch ( std::system_error& ex )
    {
        LOG_WARN( entryPoint, " discovery aborted because of a filesystem error: ", ex.what() );
    }

81 82 83 84 85
    catch ( sqlite::errors::ConstraintViolation& ex )
    {
        LOG_WARN( entryPoint, " discovery aborted (assuming blacklisted folder): ", ex.what() );
    }
    return true;
86 87
}

88
bool FsDiscoverer::reload()
89
{
90
    LOG_INFO( "Reloading all folders" );
91
    // Start by checking if previously known devices have been plugged/unplugged
92 93 94 95 96
    if ( checkDevices() == false )
    {
        LOG_ERROR( "Refusing to reloading files with no storage device" );
        return false;
    }
97
    auto rootFolders = Folder::fetchRootFolders( m_ml );
98
    for ( const auto& f : rootFolders )
99
    {
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
100
        auto folder = m_fsFactory->createDirectory( f->mrl() );
101 102
        if ( folder == nullptr )
        {
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
103
            LOG_INFO( "Removing folder ", f->mrl() );
104
            m_ml->deleteFolder( *f );
105 106
            continue;
        }
107
        checkFolder( *folder, *f, false );
108
    }
109
    return true;
110 111
}

112
bool FsDiscoverer::reload( const std::string& entryPoint )
113
{
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
114
    if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
115
        return false;
116
    LOG_INFO( "Reloading folder ", entryPoint );
117 118 119 120 121 122
    // Start by checking if previously known devices have been plugged/unplugged
    if ( checkDevices() == false )
    {
        LOG_ERROR( "Refusing to reloading files with no storage device" );
        return false;
    }
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
123
    auto folder = Folder::fromMrl( m_ml, entryPoint );
124 125 126
    if ( folder == nullptr )
    {
        LOG_ERROR( "Can't reload ", entryPoint, ": folder wasn't found in database" );
127
        return false;
128
    }
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
129
    auto folderFs = m_fsFactory->createDirectory( folder->mrl() );
130 131
    if ( folderFs == nullptr )
    {
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
132
        LOG_ERROR(" Failed to create a fs::IDirectory representing ", folder->mrl() );
133
        return false;
134
    }
135
    checkFolder( *folderFs, *folder, false );
136
    return true;
137 138
}

139
bool FsDiscoverer::checkDevices()
140
{
141 142
    if ( m_fsFactory->refreshDevices() == false )
        return false;
143
    auto devices = Device::fetchAll( m_ml );
144 145 146 147 148 149 150 151 152 153 154 155 156 157
    for ( auto& d : devices )
    {
        auto deviceFs = m_fsFactory->createDevice( d->uuid() );
        auto fsDevicePresent = deviceFs != nullptr && deviceFs->isPresent();
        if ( d->isPresent() != fsDevicePresent )
        {
            LOG_INFO( "Device ", d->uuid(), " changed presence state: ", d->isPresent(), " -> ", fsDevicePresent );
            d->setPresent( fsDevicePresent );
        }
        else
        {
            LOG_INFO( "Device ", d->uuid(), " unchanged" );
        }
    }
158
    return true;
159 160
}

161
void FsDiscoverer::checkFolder( fs::IDirectory& currentFolderFs, Folder& currentFolder, bool newFolder ) const
162
{
163 164 165 166 167 168
    try
    {
        // We already know of this folder, though it may now contain a .nomedia file.
        // In this case, simply delete the folder.
        if ( hasDotNoMediaFile( currentFolderFs ) )
        {
169 170 171 172 173
            if ( newFolder == false )
            {
                LOG_INFO( "Deleting folder ", currentFolderFs.mrl(), " due to a .nomedia file" );
                m_ml->deleteFolder( currentFolder );
            }
174 175 176 177 178 179 180
            return;
        }
    }
    // Only check once for a system_error. They are bound to happen when we list the files/folders
    // within, and hasDotMediaFile is the first place when this is done (except in case the root
    // entry point fails to be browsed, in which case the failure would happen before)
    catch ( std::system_error& ex )
181
    {
182 183 184 185 186 187
        LOG_WARN( "Failed to browse ", currentFolderFs.mrl(), ": ", ex.what() );
        if ( newFolder == false )
        {
            // If we ever came across this folder, its content is now unaccessible: let's remove it.
            m_ml->deleteFolder( currentFolder );
        }
188
        return;
189
    }
190

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
191
    m_cb->onDiscoveryProgress( currentFolderFs.mrl() );
192
    // Load the folders we already know of:
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
193
    LOG_INFO( "Checking for modifications in ", currentFolderFs.mrl() );
194 195 196
    // Don't try to fetch any potential sub folders if the folder was freshly added
    std::vector<std::shared_ptr<Folder>> subFoldersInDB;
    if ( newFolder == false )
197
        subFoldersInDB = currentFolder.folders();
198
    for ( const auto& subFolder : currentFolderFs.dirs() )
199
    {
200
        auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [&subFolder](const std::shared_ptr<Folder>& f) {
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
201
            return f->mrl() == subFolder->mrl();
202 203 204
        });
        // We don't know this folder, it's a new one
        if ( it == end( subFoldersInDB ) )
205
        {
206 207 208 209 210
            if ( hasDotNoMediaFile( *subFolder ) )
            {
                LOG_INFO( "Ignoring folder with a .nomedia file" );
                continue;
            }
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
211
            LOG_INFO( "New folder detected: ", subFolder->mrl() );
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
            try
            {
                addFolder( *subFolder, &currentFolder );
                continue;
            }
            catch ( sqlite::errors::ConstraintViolation& ex )
            {
                // Best attempt to detect a foreign key violation, indicating the parent folders have been
                // deleted due to blacklisting
                if ( strstr( ex.what(), "foreign key" ) != NULL )
                {
                    LOG_WARN( "Creation of a folder failed because the parent is non existing: ", ex.what(),
                              ". Assuming it was deleted due to blacklisting" );
                    return;
                }
                LOG_WARN( "Creation of a duplicated folder failed: ", ex.what(), ". Assuming it was blacklisted" );
                continue;
            }
230
        }
231
        auto folderInDb = *it;
232 233 234
        // In any case, check for modifications, as a change related to a mountpoint might
        // not update the folder modification date.
        // Also, relying on the modification date probably isn't portable
235
        checkFolder( *subFolder, *folderInDb, false );
236 237 238 239 240
        subFoldersInDB.erase( it );
    }
    // Now all folders we had in DB but haven't seen from the FS must have been deleted.
    for ( auto f : subFoldersInDB )
    {
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
241
        LOG_INFO( "Folder ", f->mrl(), " not found in FS, deleting it" );
242
        m_ml->deleteFolder( *f );
243
    }
244
    checkFiles( currentFolderFs, currentFolder );
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
245
    LOG_INFO( "Done checking subfolders in ", currentFolderFs.mrl() );
246
}
247

248
void FsDiscoverer::checkFiles( fs::IDirectory& parentFolderFs, Folder& parentFolder ) const
249
{
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
250
    LOG_INFO( "Checking file in ", parentFolderFs.mrl() );
251
    static const std::string req = "SELECT * FROM " + policy::FileTable::Name
252
            + " WHERE folder_id = ?";
253
    auto files = File::fetchAll<File>( m_ml, req, parentFolder.id() );
254
    std::vector<std::shared_ptr<fs::IFile>> filesToAdd;
255
    std::vector<std::shared_ptr<File>> filesToRemove;
256
    for ( const auto& fileFs: parentFolderFs.files() )
257
    {
258
        auto it = std::find_if( begin( files ), end( files ), [fileFs](const std::shared_ptr<File>& f) {
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
259
            return f->mrl() == fileFs->mrl();
260 261 262
        });
        if ( it == end( files ) )
        {
263
            filesToAdd.push_back( std::move( fileFs ) );
264
            continue;
265
        }
266
        if ( fileFs->lastModificationDate() == (*it)->lastModificationDate() )
267
        {
268 269 270
            // Unchanged file
            files.erase( it );
            continue;
271
        }
272
        auto& file = (*it);
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
273
        LOG_INFO( "Forcing file refresh ", fileFs->mrl() );
274 275 276
        // Pre-cache the file's media, since we need it to remove. However, better doing it
        // out of a write context, since that way, other threads can also read the database.
        file->media();
277 278
        filesToRemove.push_back( std::move( file ) );
        filesToAdd.push_back( std::move( fileFs ) );
279 280
        files.erase( it );
    }
281
    auto t = m_ml->getConn()->newTransaction();
282 283
    for ( auto file : files )
    {
284
        LOG_INFO( "File ", file->mrl(), " not found on filesystem, deleting it" );
285
        file->media()->removeFile( *file );
286
    }
287 288 289 290
    for ( auto& f : filesToRemove )
        f->media()->removeFile( *f );
    // Insert all files at once to avoid SQL write contention
    for ( auto& p : filesToAdd )
291
        m_ml->addFile( *p, parentFolder, parentFolderFs );
292
    t->commit();
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
293
    LOG_INFO( "Done checking files in ", parentFolderFs.mrl() );
294
}
295

296 297 298
bool FsDiscoverer::hasDotNoMediaFile( const fs::IDirectory& directory )
{
    const auto& files = directory.files();
299 300
    return std::find_if( begin( files ), end( files ), []( const std::shared_ptr<fs::IFile>& file ){
        return file->name() == ".nomedia";
301 302 303
    }) != end( files );
}

304
bool FsDiscoverer::addFolder( fs::IDirectory& folder, Folder* parentFolder ) const
305
{
306
    auto deviceFs = folder.device();
307 308
    // We are creating a folder, there has to be a device containing it.
    assert( deviceFs != nullptr );
309
    auto device = Device::fromUuid( m_ml, deviceFs->uuid() );
310
    if ( device == nullptr )
311
    {
312
        LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
313 314
        device = Device::create( m_ml, deviceFs->uuid(), utils::file::scheme( folder.mrl() ),
                                 deviceFs->isRemovable() );
315 316
    }

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
317
    auto f = Folder::create( m_ml, folder.mrl(),
318
                             parentFolder != nullptr ? parentFolder->id() : 0,
319
                             *device, *deviceFs );
320 321
    if ( f == nullptr )
        return false;
322
    checkFolder( folder, *f, true );
323 324
    return true;
}
325

326
}