FsDiscoverer.cpp 9.52 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

36
FsDiscoverer::FsDiscoverer( std::shared_ptr<factory::IFileSystem> fsFactory, MediaLibrary* ml, DBConnection dbConn )
37 38
    : m_ml( ml )
    , m_dbConn( dbConn )
39 40 41 42
{
    if ( fsFactory != nullptr )
        m_fsFactory = fsFactory;
    else
43
        m_fsFactory.reset( new factory::FileSystemFactory );
44 45
}

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

71
void FsDiscoverer::reload()
72
{
73 74
    // Start by checking if previously known devices have been plugged/unplugged
    checkDevices();
75 76 77
    //FIXME: This should probably be in a sql transaction
    static const std::string req = "SELECT * FROM " + policy::FolderTable::Name
            + " WHERE id_parent IS NULL";
78
    auto rootFolders = Folder::fetchAll<Folder>( m_dbConn, req );
79
    auto blist = blacklist();
80
    for ( const auto& f : rootFolders )
81
    {
82
        auto folder = m_fsFactory->createDirectory( f->path() );
83 84 85
        if ( folder == nullptr )
        {
            LOG_INFO( "Removing folder ", f->path() );
86
            m_ml->deleteFolder( f.get() );
87 88
            continue;
        }
89
        if ( folder->lastModificationDate() == f->lastModificationDate() )
90 91
        {
            LOG_INFO( f->path(), " isn't modified" );
92
            continue;
93
        }
94 95
        checkSubfolders( folder.get(), f.get(), blist );
        checkFiles( folder.get(), f.get() );
96
        f->setLastModificationDate( folder->lastModificationDate() );
97 98 99
    }
}

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
void FsDiscoverer::checkDevices()
{
    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" );
        }
    }
}

119
bool FsDiscoverer::checkSubfolders( fs::IDirectory* folder, Folder* parentFolder, const std::vector<std::shared_ptr<Folder>> blacklist ) const
120 121 122 123 124 125 126 127
{
    // From here we can have:
    // - New subfolder(s)
    // - Deleted subfolder(s)
    // - New file(s)
    // - Deleted file(s)
    // - Changed file(s)
    // ... in this folder, or in all the sub folders.
128

129 130 131
    // Load the folders we already know of:
    static const std::string req = "SELECT * FROM " + policy::FolderTable::Name
            + " WHERE id_parent = ?";
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
132
    LOG_INFO( "Checking for modifications in ", folder->path() );
133
    auto subFoldersInDB = Folder::fetchAll<Folder>( m_dbConn, req, parentFolder->id() );
134 135
    for ( const auto& subFolderPath : folder->dirs() )
    {
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
136
        auto subFolder = m_fsFactory->createDirectory( subFolderPath );
137 138
        if ( subFolder == nullptr )
            continue;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
139

140
        auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [subFolderPath](const std::shared_ptr<Folder>& f) {
141 142 143 144
            return f->path() == subFolderPath;
        });
        // We don't know this folder, it's a new one
        if ( it == end( subFoldersInDB ) )
145
        {
146
            // Check if it is blacklisted
147
            if ( isBlacklisted( subFolderPath, blacklist ) == true )
148 149 150 151
            {
                LOG_INFO( "Ignoring blacklisted folder: ", subFolderPath );
                continue;
            }
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
152
            LOG_INFO( "New folder detected: ", subFolderPath );
153
            addFolder( subFolder.get(), parentFolder, blacklist );
154
            continue;
155
        }
156
        auto folderInDb = *it;
157 158 159 160 161 162 163
        // If the folder isn't present, don't check it for modifications
        if ( folderInDb->isPresent() == false )
        {
            subFoldersInDB.erase( it );
            continue;
        }
        if ( subFolder->lastModificationDate() == folderInDb->lastModificationDate() )
164
        {
165
            subFoldersInDB.erase( it );
166 167
            continue;
        }
168 169 170
        // 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
171 172
        checkSubfolders( subFolder.get(), folderInDb.get(), blacklist );
        checkFiles( subFolder.get(), folderInDb.get() );
173
        folderInDb->setLastModificationDate( subFolder->lastModificationDate() );
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.get() );
181 182 183
    }
    return true;
}
184

185
void FsDiscoverer::checkFiles( fs::IDirectory* folder, Folder* parentFolder ) const
186
{
187
    LOG_INFO( "Checking file in ", folder->path() );
188
    static const std::string req = "SELECT * FROM " + policy::MediaTable::Name
189
            + " WHERE folder_id = ?";
190
    auto files = Media::fetchAll<Media>( m_dbConn, req, parentFolder->id() );
191 192
    for ( const auto& filePath : folder->files() )
    {        
193
        auto it = std::find_if( begin( files ), end( files ), [filePath](const std::shared_ptr<IMedia>& f) {
194 195 196 197
            return f->mrl() == filePath;
        });
        if ( it == end( files ) )
        {
198
            m_ml->addFile( filePath, parentFolder );
199
            continue;
200 201
        }
        auto file = m_fsFactory->createFile( filePath );
202
        if ( file->lastModificationDate() == (*it)->lastModificationDate() )
203
        {
204 205 206
            // Unchanged file
            files.erase( it );
            continue;
207
        }
208
        LOG_INFO( "Forcing file refresh ", filePath );
209
        m_ml->deleteFile( (*it).get() );
210
        m_ml->addFile( filePath, parentFolder );
211 212 213 214
        files.erase( it );
    }
    for ( auto file : files )
    {
215
        LOG_INFO( "File ", file->mrl(), " not found on filesystem, deleting it" );
216
        m_ml->deleteFile( file.get() );
217 218
    }
}
219 220 221 222 223 224

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 );
}
225 226 227 228 229 230 231

bool FsDiscoverer::isBlacklisted(const std::string& path, const std::vector<std::shared_ptr<Folder>>& blacklist ) const
{
    return std::find_if( begin( blacklist ), end( blacklist ), [&path]( const std::shared_ptr<Folder>& f ) {
        return path == f->path();
    }) != end( blacklist );
}
232

233
bool FsDiscoverer::addFolder( fs::IDirectory* folder, Folder* parentFolder, const std::vector<std::shared_ptr<Folder>>& blacklist ) const
234 235 236 237
{
    // Force <0> as lastModificationDate, so this folder is detected as outdated
    // by the modification checking code
    auto deviceFs = folder->device();
238 239 240 241
    // 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 )
242
    {
243 244
        LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
        device = Device::create( m_dbConn, deviceFs->uuid(), deviceFs->isRemovable() );
245 246
    }

247 248
    auto f = Folder::create( m_dbConn, folder->path(), 0,
                             parentFolder != nullptr ? parentFolder->id() : 0, *device );
249 250 251 252 253 254 255
    if ( f == nullptr )
        return false;
    checkFiles( folder, f.get() );
    checkSubfolders( folder, f.get(), blacklist );
    f->setLastModificationDate( folder->lastModificationDate() );
    return true;
}
256