FsDiscoverer.cpp 10.4 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/FileSystem.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
FsDiscoverer::FsDiscoverer( std::shared_ptr<factory::IFileSystem> fsFactory, MediaLibrary* ml, DBConnection dbConn )
39 40
    : m_ml( ml )
    , m_dbConn( dbConn )
41
    , m_fsFactory( fsFactory )
42 43 44
{
}

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

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

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

93 94
void FsDiscoverer::checkDevices()
{
95
    m_fsFactory->refresh();
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
    auto devices = Device::fetchAll( m_dbConn );
    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" );
        }
    }
}

113
bool FsDiscoverer::checkSubfolders( fs::IDirectory& currentFolderFs, Folder& currentFolder, const std::vector<std::shared_ptr<Folder>> blacklist ) const
114
{
115 116
    // We already know of this folder, though it may now contain a .nomedia file.
    // In this case, simply delete the folder.
117
    if ( hasDotNoMediaFile( currentFolderFs ) )
118
    {
119 120
        LOG_INFO( "Deleting folder ", currentFolderFs.path(), " due to a .nomedia file" );
        m_ml->deleteFolder( currentFolder );
121 122
        return false;
    }
123
    // Load the folders we already know of:
124 125 126
    LOG_INFO( "Checking for modifications in ", currentFolderFs.path() );
    auto subFoldersInDB = Folder::fetchAll( m_dbConn, currentFolder.id() );
    for ( const auto& subFolderPath : currentFolderFs.dirs() )
127
    {
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
128
        auto subFolder = m_fsFactory->createDirectory( subFolderPath );
129 130
        if ( subFolder == nullptr )
            continue;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
131

132
        auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [subFolderPath](const std::shared_ptr<Folder>& f) {
133 134 135 136
            return f->path() == subFolderPath;
        });
        // We don't know this folder, it's a new one
        if ( it == end( subFoldersInDB ) )
137
        {
138
            // Check if it is blacklisted
139
            if ( isBlacklisted( *subFolder, blacklist ) == true )
140 141 142 143
            {
                LOG_INFO( "Ignoring blacklisted folder: ", subFolderPath );
                continue;
            }
144 145 146 147 148
            if ( hasDotNoMediaFile( *subFolder ) )
            {
                LOG_INFO( "Ignoring folder with a .nomedia file" );
                continue;
            }
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
149
            LOG_INFO( "New folder detected: ", subFolderPath );
150
            addFolder( *subFolder, &currentFolder, blacklist );
151
            continue;
152
        }
153
        auto folderInDb = *it;
154 155 156
        // 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
157 158 159 160
        if ( checkSubfolders( *subFolder, *folderInDb, blacklist ) == true )
        {
            checkFiles( *subFolder, *folderInDb );
        }
161 162 163 164 165
        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 )
    {
166
        LOG_INFO( "Folder ", f->path(), " not found in FS, deleting it" );
167
        m_ml->deleteFolder( *f );
168
    }
169
    LOG_INFO( "Done checking subfolders in ", currentFolderFs.path() );
170 171
    return true;
}
172

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

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

228
bool FsDiscoverer::isBlacklisted( const fs::IDirectory& directory, const std::vector<std::shared_ptr<Folder>>& blacklist ) const
229
{
230
    auto deviceFs = directory.device();
231
    //FIXME: We could avoid fetching the device if the directory is non removable.
232 233 234 235 236 237 238
    auto device = Device::fromUuid( m_dbConn, deviceFs->uuid() );
    // 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();

239 240
    return std::find_if( begin( blacklist ), end( blacklist ), [&directory, deviceId]( const std::shared_ptr<Folder>& f ) {
        return f->path() == directory.path() && f->deviceId() == deviceId;
241 242
    }) != end( blacklist );
}
243

244 245 246 247 248 249 250 251 252
bool FsDiscoverer::hasDotNoMediaFile( const fs::IDirectory& directory )
{
    const auto& files = directory.files();
    return std::find_if( begin( files ), end( files ), []( const std::string& filePath ){
        constexpr unsigned int endLength = strlen( "/.nomedia" );
        return filePath.compare( filePath.length() - endLength, endLength, "/.nomedia" ) == 0;
    }) != end( files );
}

253
bool FsDiscoverer::addFolder( fs::IDirectory& folder, Folder* parentFolder, const std::vector<std::shared_ptr<Folder>>& blacklist ) const
254
{
255
    auto deviceFs = folder.device();
256 257 258 259
    // We are creating a folder, there has to be a device containing it.
    assert( deviceFs != nullptr );
    auto device = Device::fromUuid( m_dbConn, deviceFs->uuid() );
    if ( device == nullptr )
260
    {
261 262
        LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
        device = Device::create( m_dbConn, deviceFs->uuid(), deviceFs->isRemovable() );
263 264
    }

265 266
    auto f = Folder::create( m_dbConn, folder.path(),
                             parentFolder != nullptr ? parentFolder->id() : 0,
267
                             *device, *deviceFs );
268 269
    if ( f == nullptr )
        return false;
270 271
    checkFiles( folder, *f );
    checkSubfolders( folder, *f, blacklist );
272 273
    return true;
}
274