FsDiscoverer.cpp 8.63 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;
60 61 62 63 64 65 66 67 68
    try
    {
        fsDir = m_fsFactory->createDirectory( entryPoint );
    }
    catch (std::exception& ex)
    {
        LOG_ERROR("Failed to create an IDirectory for ", entryPoint, ": ", ex.what());
        return false;
    }
69
    auto blist = blacklist();
70
    if ( isBlacklisted( fsDir->path(), blist ) == true )
71
        return false;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
72 73 74
    // Force <0> as lastModificationDate, so this folder is detected as outdated
    // by the modification checking code
    auto f = Folder::create( m_dbConn, fsDir->path(), 0, fsDir->isRemovable(), 0 );
75 76
    if ( f == nullptr )
        return false;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
77 78 79 80 81
    // Since this is the "root" folder, we will always try to add the device it's located on
    // to our devices list. We can then check if the subfolders containing device are different
    auto deviceFs = fsDir->device();
    auto device = Device::fromUuid( m_dbConn, deviceFs->uuid() );
    if ( device == nullptr )
82
    {
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
83 84
        LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
        device = Device::create( m_dbConn, deviceFs->uuid(), deviceFs->isRemovable() );
85
    }
86 87
    checkFiles( fsDir.get(), f.get() );
    checkSubfolders( fsDir.get(), f.get(), blist );
88
    f->setLastModificationDate( fsDir->lastModificationDate() );
89 90 91
    return true;
}

92
void FsDiscoverer::reload()
93 94 95 96 97
{
    //FIXME: This should probably be in a sql transaction
    //FIXME: This shouldn't be done for "removable"/network files
    static const std::string req = "SELECT * FROM " + policy::FolderTable::Name
            + " WHERE id_parent IS NULL";
98
    auto rootFolders = Folder::fetchAll<Folder>( m_dbConn, req );
99
    auto blist = blacklist();
100
    for ( const auto& f : rootFolders )
101
    {
102 103 104
        auto folder = m_fsFactory->createDirectory( f->path() );
        if ( folder->lastModificationDate() == f->lastModificationDate() )
            continue;
105 106
        checkSubfolders( folder.get(), f.get(), blist );
        checkFiles( folder.get(), f.get() );
107
        f->setLastModificationDate( folder->lastModificationDate() );
108 109 110
    }
}

111
bool FsDiscoverer::checkSubfolders( fs::IDirectory* folder, Folder* parentFolder, const std::vector<std::shared_ptr<Folder>> blacklist )
112 113 114 115 116 117 118 119
{
    // 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.
120

121 122 123
    // 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
124
    LOG_INFO( "Checking for modifications in ", folder->path() );
125
    auto subFoldersInDB = Folder::fetchAll<Folder>( m_dbConn, req, parentFolder->id() );
126 127
    for ( const auto& subFolderPath : folder->dirs() )
    {
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
128 129
        auto subFolder = m_fsFactory->createDirectory( subFolderPath );

130 131 132 133 134
        auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [subFolderPath](const std::shared_ptr<IFolder>& f) {
            return f->path() == subFolderPath;
        });
        // We don't know this folder, it's a new one
        if ( it == end( subFoldersInDB ) )
135
        {
136
            // Check if it is blacklisted
137
            if ( isBlacklisted( subFolderPath, blacklist ) == true )
138 139 140 141
            {
                LOG_INFO( "Ignoring blacklisted folder: ", subFolderPath );
                continue;
            }
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
142 143 144
            LOG_INFO( "New folder detected: ", subFolderPath );
            // Force a scan by setting lastModificationDate to 0
            auto f = Folder::create( m_dbConn, subFolder->path(), 0, subFolder->isRemovable(), parentFolder->id() );
145 146
            checkFiles( subFolder.get(), f.get() );
            checkSubfolders( subFolder.get(), f.get(), blacklist );
147
            f->setLastModificationDate( subFolder->lastModificationDate() );
148
            continue;
149
        }
150
        auto folderInDb = *it;
151
        if ( subFolder->lastModificationDate() == folderInDb->lastModificationDate() )
152
        {
153 154 155 156
            // Remove all folders that still exist in FS. That way, the list of folders that
            // will still be in subFoldersInDB when we're done is the list of folders that have
            // been deleted from the FS
            subFoldersInDB.erase( it );
157 158
            continue;
        }
159
        // This folder was modified, let's recurse
160 161
        checkSubfolders( subFolder.get(), folderInDb.get(), blacklist );
        checkFiles( subFolder.get(), folderInDb.get() );
162
        folderInDb->setLastModificationDate( subFolder->lastModificationDate() );
163 164 165 166 167
        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 )
    {
168 169
        LOG_INFO( "Folder ", f->path(), " not found in FS, deleting it" );
        m_ml->deleteFolder( f );
170 171 172
    }
    return true;
}
173

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

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 );
}
214 215 216 217 218 219 220

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