FsDiscoverer.cpp 10.7 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
#include "FsDiscoverer.h"

25
#include <algorithm>
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
26 27
#include <queue>

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

38 39 40
namespace medialibrary
{

41
FsDiscoverer::FsDiscoverer( std::shared_ptr<factory::IFileSystem> fsFactory, MediaLibrary* ml, IMediaLibraryCb* cb )
42
    : m_ml( ml )
43
    , m_fsFactory( fsFactory )
44
    , m_cb( cb )
45 46 47
{
}

48
bool FsDiscoverer::discover( const std::string &entryPoint )
49
{
50
    LOG_INFO( "Adding to discovery list: ", entryPoint );
51 52 53
    // Assume :// denotes a scheme that isn't a file path, and refuse to discover it.
    if ( entryPoint.find( "://" ) != std::string::npos )
        return false;
54

55 56
    std::shared_ptr<fs::IDirectory> fsDir = m_fsFactory->createDirectory( entryPoint );
    // Otherwise, create a directory and check it for modifications
57 58 59 60 61
    if ( fsDir == nullptr )
    {
        LOG_ERROR("Failed to create an IDirectory for ", entryPoint );
        return false;
    }
62
    auto f = Folder::fromPath( m_ml, fsDir->path() );
63 64 65
    // If the folder exists, we assume it will be handled by reload()
    if ( f != nullptr )
        return true;
66
    auto blist = blacklist();
67
    if ( isBlacklisted( *fsDir, blist ) == true )
68
        return true;
69
    if ( hasDotNoMediaFile( *fsDir ) )
70
        return true;
71
    return addFolder( *fsDir, nullptr, blist );
72 73
}

74
void FsDiscoverer::reload()
75
{
76
    LOG_INFO( "Reloading all folders" );
77 78
    // Start by checking if previously known devices have been plugged/unplugged
    checkDevices();
79
    auto rootFolders = Folder::fetchAll( m_ml, 0 );
80
    auto blist = blacklist();
81
    for ( const auto& f : rootFolders )
82
    {
83
        auto folder = m_fsFactory->createDirectory( f->path() );
84 85 86
        if ( folder == nullptr )
        {
            LOG_INFO( "Removing folder ", f->path() );
87
            m_ml->deleteFolder( *f );
88 89
            continue;
        }
90
        checkFolder( *folder, *f, blist );
91 92 93
    }
}

94 95 96
void FsDiscoverer::reload( const std::string& entryPoint )
{
    LOG_INFO( "Reloading folder ", entryPoint );
97
    auto folder = Folder::fromPath( m_ml, entryPoint );
98 99 100 101 102 103 104 105 106 107 108 109 110 111
    if ( folder == nullptr )
    {
        LOG_ERROR( "Can't reload ", entryPoint, ": folder wasn't found in database" );
        return;
    }
    auto folderFs = m_fsFactory->createDirectory( folder->path() );
    if ( folderFs == nullptr )
    {
        LOG_ERROR(" Failed to create a fs::IDirectory representing ", folder->path() );
    }
    auto blist = blacklist();
    checkFolder( *folderFs, *folder, blist );
}

112 113
void FsDiscoverer::checkDevices()
{
114
    m_fsFactory->refresh();
115
    auto devices = Device::fetchAll( m_ml );
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    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" );
        }
    }
}

132
void FsDiscoverer::checkFolder( fs::IDirectory& currentFolderFs, Folder& currentFolder, const std::vector<std::shared_ptr<Folder>>& blacklist ) const
133
{
134 135
    // We already know of this folder, though it may now contain a .nomedia file.
    // In this case, simply delete the folder.
136
    if ( hasDotNoMediaFile( currentFolderFs ) )
137
    {
138 139
        LOG_INFO( "Deleting folder ", currentFolderFs.path(), " due to a .nomedia file" );
        m_ml->deleteFolder( currentFolder );
140
        return;
141
    }
142
    m_cb->onDiscoveryStarted( currentFolderFs.path() );
143
    // Load the folders we already know of:
144
    LOG_INFO( "Checking for modifications in ", currentFolderFs.path() );
145
    auto subFoldersInDB = Folder::fetchAll( m_ml, currentFolder.id() );
146
    for ( const auto& subFolder : currentFolderFs.dirs() )
147
    {
148 149
        auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [&subFolder](const std::shared_ptr<Folder>& f) {
            return f->path() == subFolder->path();
150 151 152
        });
        // We don't know this folder, it's a new one
        if ( it == end( subFoldersInDB ) )
153
        {
154
            // Check if it is blacklisted
155
            if ( isBlacklisted( *subFolder, blacklist ) == true )
156
            {
157
                LOG_INFO( "Ignoring blacklisted folder: ", subFolder->path() );
158 159
                continue;
            }
160 161 162 163 164
            if ( hasDotNoMediaFile( *subFolder ) )
            {
                LOG_INFO( "Ignoring folder with a .nomedia file" );
                continue;
            }
165
            LOG_INFO( "New folder detected: ", subFolder->path() );
166
            addFolder( *subFolder, &currentFolder, blacklist );
167
            continue;
168
        }
169
        auto folderInDb = *it;
170 171 172
        // 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
173
        checkFolder( *subFolder, *folderInDb, blacklist );
174 175 176 177 178
        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 )
    {
179
        LOG_INFO( "Folder ", f->path(), " not found in FS, deleting it" );
180
        m_ml->deleteFolder( *f );
181
    }
182
    checkFiles( currentFolderFs, currentFolder );
183
    LOG_INFO( "Done checking subfolders in ", currentFolderFs.path() );
184
}
185

186
void FsDiscoverer::checkFiles( fs::IDirectory& parentFolderFs, Folder& parentFolder ) const
187
{
188
    LOG_INFO( "Checking file in ", parentFolderFs.path() );
189
    static const std::string req = "SELECT * FROM " + policy::FileTable::Name
190
            + " WHERE folder_id = ?";
191
    auto files = File::fetchAll<File>( m_ml, req, parentFolder.id() );
192
    std::vector<std::shared_ptr<fs::IFile>> filesToAdd;
193
    std::vector<std::shared_ptr<File>> filesToRemove;
194
    for ( const auto& fileFs: parentFolderFs.files() )
195
    {        
196 197
        auto it = std::find_if( begin( files ), end( files ), [fileFs](const std::shared_ptr<File>& f) {
            return f->mrl() == fileFs->fullPath();
198 199 200
        });
        if ( it == end( files ) )
        {
201
            filesToAdd.push_back( fileFs );
202
            continue;
203
        }
204
        if ( fileFs->lastModificationDate() == (*it)->lastModificationDate() )
205
        {
206 207 208
            // Unchanged file
            files.erase( it );
            continue;
209
        }
210
        auto& file = (*it);
211
        LOG_INFO( "Forcing file refresh ", fileFs->fullPath() );
212 213 214 215
        // 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();
        filesToRemove.push_back( file );
216
        filesToAdd.push_back( fileFs );
217 218
        files.erase( it );
    }
219
    auto t = m_ml->getConn()->newTransaction();
220 221
    for ( auto file : files )
    {
222
        LOG_INFO( "File ", file->mrl(), " not found on filesystem, deleting it" );
223
        file->media()->removeFile( *file );
224
    }
225 226 227 228
    for ( auto& f : filesToRemove )
        f->media()->removeFile( *f );
    // Insert all files at once to avoid SQL write contention
    for ( auto& p : filesToAdd )
229
        m_ml->addFile( *p, parentFolder, parentFolderFs );
230
    t->commit();
231
    LOG_INFO( "Done checking files in ", parentFolderFs.path() );
232
}
233 234 235 236

std::vector<std::shared_ptr<Folder> > FsDiscoverer::blacklist() const
{
    static const std::string req = "SELECT * FROM " + policy::FolderTable::Name + " WHERE is_blacklisted = 1";
237
    return sqlite::Tools::fetchAll<Folder, Folder>( m_ml, req );
238
}
239

240
bool FsDiscoverer::isBlacklisted( const fs::IDirectory& directory, const std::vector<std::shared_ptr<Folder>>& blacklist ) const
241
{
242
    auto deviceFs = directory.device();
243 244 245 246 247
    if ( deviceFs == nullptr )
    {
        LOG_WARN( "Failed to fetch device containing ", directory.path() );
        return true;
    }
248
    //FIXME: We could avoid fetching the device if the directory is non removable.
249
    auto device = Device::fromUuid( m_ml, deviceFs->uuid() );
250 251 252 253 254 255
    // When blacklisting, we would insert the device if we haven't encoutered it yet.
    // So when reading, a missing device means a non-blacklisted device.
    if ( device == nullptr )
        return false;
    auto deviceId = device->id();

256 257
    return std::find_if( begin( blacklist ), end( blacklist ), [&directory, deviceId]( const std::shared_ptr<Folder>& f ) {
        return f->path() == directory.path() && f->deviceId() == deviceId;
258 259
    }) != end( blacklist );
}
260

261 262 263
bool FsDiscoverer::hasDotNoMediaFile( const fs::IDirectory& directory )
{
    const auto& files = directory.files();
264 265
    return std::find_if( begin( files ), end( files ), []( const std::shared_ptr<fs::IFile>& file ){
        return file->name() == ".nomedia";
266 267 268
    }) != end( files );
}

269
bool FsDiscoverer::addFolder( fs::IDirectory& folder, Folder* parentFolder, const std::vector<std::shared_ptr<Folder>>& blacklist ) const
270
{
271
    auto deviceFs = folder.device();
272 273
    // We are creating a folder, there has to be a device containing it.
    assert( deviceFs != nullptr );
274
    auto device = Device::fromUuid( m_ml, deviceFs->uuid() );
275
    if ( device == nullptr )
276
    {
277
        LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
278
        device = Device::create( m_ml, deviceFs->uuid(), deviceFs->isRemovable() );
279 280
    }

281
    auto f = Folder::create( m_ml, folder.path(),
282
                             parentFolder != nullptr ? parentFolder->id() : 0,
283
                             *device, *deviceFs );
284 285
    if ( f == nullptr )
        return false;
286
    checkFolder( folder, *f, blacklist );
287 288
    return true;
}
289

290
}