FsDiscoverer.cpp 8.07 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"
29
#include "Media.h"
30
#include "Folder.h"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
31
#include "logging/Logger.h"
32
#include "MediaLibrary.h"
33

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

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

    {
51
        auto f = Folder::fromPath( m_dbConn, entryPoint );
52
        // If the folder exists, we assume it will be handled by reload()
53 54 55 56 57 58 59 60 61 62 63 64 65 66
        if ( f != nullptr )
            return true;
    }
    // Otherwise, create a directory, and check it for modifications
    std::unique_ptr<fs::IDirectory> fsDir;
    try
    {
        fsDir = m_fsFactory->createDirectory( entryPoint );
    }
    catch (std::exception& ex)
    {
        LOG_ERROR("Failed to create an IDirectory for ", entryPoint, ": ", ex.what());
        return false;
    }
67 68 69 70 71 72
    auto blist = blacklist();
    auto it = std::find_if( begin( blist ), end( blist ), [&fsDir]( const std::shared_ptr<Folder>& f ) {
        return f->path() == fsDir->path();
    });
    if ( it != end( blist ) )
        return false;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
73 74 75
    // 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 );
76 77
    if ( f == nullptr )
        return false;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
78
    checkFiles( fsDir.get(), f );
79
    checkSubfolders( fsDir.get(), f, blist );
80
    f->setLastModificationDate( fsDir->lastModificationDate() );
81 82 83
    return true;
}

84
void FsDiscoverer::reload()
85 86 87 88 89
{
    //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";
90
    auto rootFolders = Folder::fetchAll<Folder>( m_dbConn, req );
91
    auto blist = blacklist();
92
    for ( const auto& f : rootFolders )
93 94 95 96
    {
        auto folder = m_fsFactory->createDirectory( f->path() );
        if ( folder->lastModificationDate() == f->lastModificationDate() )
            continue;
97
        checkSubfolders( folder.get(), f, blist );
98
        checkFiles( folder.get(), f );
99 100 101 102
        f->setLastModificationDate( folder->lastModificationDate() );
    }
}

103
bool FsDiscoverer::checkSubfolders( fs::IDirectory* folder, FolderPtr parentFolder, const std::vector<std::shared_ptr<Folder>> blacklist )
104 105 106 107 108 109 110 111
{
    // 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.
112

113 114 115
    // 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
116
    LOG_INFO( "Checking for modifications in ", folder->path() );
117
    auto subFoldersInDB = Folder::fetchAll<Folder>( m_dbConn, req, parentFolder->id() );
118 119
    for ( const auto& subFolderPath : folder->dirs() )
    {
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
120 121
        auto subFolder = m_fsFactory->createDirectory( subFolderPath );

122 123 124 125 126
        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 ) )
127
        {
128 129 130 131 132 133 134 135 136
            // Check if it is blacklisted
            auto it = std::find_if( begin( blacklist ), end( blacklist ), [subFolderPath](const std::shared_ptr<Folder>& f) {
                return f->path() == subFolderPath;
            });
            if ( it != end( blacklist ) )
            {
                LOG_INFO( "Ignoring blacklisted folder: ", subFolderPath );
                continue;
            }
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
137 138 139 140
            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() );
            checkFiles( subFolder.get(), f );
141
            checkSubfolders( subFolder.get(), f, blacklist );
142
            f->setLastModificationDate( subFolder->lastModificationDate() );
143
            continue;
144
        }
145
        auto folderInDb = *it;
146
        if ( subFolder->lastModificationDate() == folderInDb->lastModificationDate() )
147
        {
148 149 150 151
            // 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 );
152 153
            continue;
        }
154
        // This folder was modified, let's recurse
155
        checkSubfolders( subFolder.get(), folderInDb, blacklist );
156 157
        checkFiles( subFolder.get(), folderInDb );
        folderInDb->setLastModificationDate( subFolder->lastModificationDate() );
158 159 160 161 162
        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 )
    {
163 164
        LOG_INFO( "Folder ", f->path(), " not found in FS, deleting it" );
        m_ml->deleteFolder( f );
165 166 167
    }
    return true;
}
168

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

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