FsDiscoverer.cpp 8.74 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"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
31
#include "Device.h"
32
#include "Folder.h"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
33
#include "logging/Logger.h"
34
#include "MediaLibrary.h"
35
#include "utils/Filename.h"
36

37
FsDiscoverer::FsDiscoverer( std::shared_ptr<factory::IFileSystem> fsFactory, MediaLibrary* ml, DBConnection dbConn )
38 39
    : m_ml( ml )
    , m_dbConn( dbConn )
40
    , m_fsFactory( fsFactory )
41 42 43
{
}

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

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

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

89 90
void FsDiscoverer::checkDevices()
{
91
    m_fsFactory->refresh();
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    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" );
        }
    }
}

109
bool FsDiscoverer::checkSubfolders( fs::IDirectory& parentFolderFs, Folder& parentFolder, const std::vector<std::shared_ptr<Folder>> blacklist ) const
110 111
{
    // Load the folders we already know of:
112
    LOG_INFO( "Checking for modifications in ", parentFolderFs.path() );
113
    auto subFoldersInDB = Folder::fetchAll( m_dbConn, parentFolder.id() );
114
    for ( const auto& subFolderPath : parentFolderFs.dirs() )
115
    {
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
116
        auto subFolder = m_fsFactory->createDirectory( subFolderPath );
117 118
        if ( subFolder == nullptr )
            continue;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
119

120
        auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [subFolderPath](const std::shared_ptr<Folder>& f) {
121 122 123 124
            return f->path() == subFolderPath;
        });
        // We don't know this folder, it's a new one
        if ( it == end( subFoldersInDB ) )
125
        {
126
            // Check if it is blacklisted
127
            if ( isBlacklisted( *subFolder, blacklist ) == true )
128 129 130 131
            {
                LOG_INFO( "Ignoring blacklisted folder: ", subFolderPath );
                continue;
            }
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
132
            LOG_INFO( "New folder detected: ", subFolderPath );
133
            addFolder( *subFolder, &parentFolder, blacklist );
134
            continue;
135
        }
136
        auto folderInDb = *it;
137 138 139
        // 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
140 141
        checkSubfolders( *subFolder, *folderInDb, blacklist );
        checkFiles( *subFolder, *folderInDb );
142 143 144 145 146
        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 )
    {
147
        LOG_INFO( "Folder ", f->path(), " not found in FS, deleting it" );
148
        m_ml->deleteFolder( f.get() );
149
    }
150
    LOG_INFO( "Done checking subfolders in ", parentFolderFs.path() );
151 152
    return true;
}
153

154
void FsDiscoverer::checkFiles( fs::IDirectory& parentFolderFs, Folder& parentFolder ) const
155
{
156
    LOG_INFO( "Checking file in ", parentFolderFs.path() );
157
    static const std::string req = "SELECT * FROM " + policy::MediaTable::Name
158
            + " WHERE folder_id = ?";
159
    auto files = Media::fetchAll<Media>( m_dbConn, req, parentFolder.id() );
160
    for ( const auto& filePath : parentFolderFs.files() )
161
    {        
162
        auto it = std::find_if( begin( files ), end( files ), [filePath](const std::shared_ptr<IMedia>& f) {
163 164 165 166
            return f->mrl() == filePath;
        });
        if ( it == end( files ) )
        {
167
            m_ml->addFile( filePath, parentFolder, parentFolderFs );
168
            continue;
169 170
        }
        auto file = m_fsFactory->createFile( filePath );
171
        if ( file->lastModificationDate() == (*it)->lastModificationDate() )
172
        {
173 174 175
            // Unchanged file
            files.erase( it );
            continue;
176
        }
177
        LOG_INFO( "Forcing file refresh ", filePath );
178
        m_ml->deleteFile( (*it).get() );
179
        m_ml->addFile( filePath, parentFolder, parentFolderFs );
180 181 182 183
        files.erase( it );
    }
    for ( auto file : files )
    {
184
        LOG_INFO( "File ", file->mrl(), " not found on filesystem, deleting it" );
185
        m_ml->deleteFile( file.get() );
186
    }
187
    LOG_INFO( "Done checking files ", parentFolderFs.path() );
188
}
189 190 191 192 193 194

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

196
bool FsDiscoverer::isBlacklisted( const fs::IDirectory& directory, const std::vector<std::shared_ptr<Folder>>& blacklist ) const
197
{
198
    auto deviceFs = directory.device();
199
    //FIXME: We could avoid fetching the device if the directory is non removable.
200 201 202 203 204 205 206
    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();

207 208
    return std::find_if( begin( blacklist ), end( blacklist ), [&directory, deviceId]( const std::shared_ptr<Folder>& f ) {
        return f->path() == directory.path() && f->deviceId() == deviceId;
209 210
    }) != end( blacklist );
}
211

212
bool FsDiscoverer::addFolder( fs::IDirectory& folder, Folder* parentFolder, const std::vector<std::shared_ptr<Folder>>& blacklist ) const
213
{
214
    auto deviceFs = folder.device();
215 216 217 218
    // 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 )
219
    {
220 221
        LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
        device = Device::create( m_dbConn, deviceFs->uuid(), deviceFs->isRemovable() );
222 223
    }

224 225
    auto f = Folder::create( m_dbConn, folder.path(),
                             parentFolder != nullptr ? parentFolder->id() : 0,
226
                             *device, *deviceFs );
227 228
    if ( f == nullptr )
        return false;
229 230
    checkFiles( folder, *f );
    checkSubfolders( folder, *f, blacklist );
231 232
    return true;
}
233