FsDiscoverer.cpp 9.82 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 25 26
#if HAVE_CONFIG_H
# include "config.h"
#endif

27 28
#include "FsDiscoverer.h"

29
#include <algorithm>
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
30 31
#include <queue>

32
#include "factory/FileSystemFactory.h"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
33
#include "filesystem/IDevice.h"
34
#include "Media.h"
35
#include "File.h"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
36
#include "Device.h"
37
#include "Folder.h"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
38
#include "logging/Logger.h"
39
#include "MediaLibrary.h"
40
#include "utils/Filename.h"
41

42 43 44
namespace medialibrary
{

45
FsDiscoverer::FsDiscoverer( std::shared_ptr<factory::IFileSystem> fsFactory, MediaLibrary* ml, IMediaLibraryCb* cb )
46
    : m_ml( ml )
47
    , m_fsFactory( fsFactory )
48
    , m_cb( cb )
49 50 51
{
}

52
bool FsDiscoverer::discover( const std::string &entryPoint )
53
{
54
    LOG_INFO( "Adding to discovery list: ", entryPoint );
55 56 57
    // Assume :// denotes a scheme that isn't a file path, and refuse to discover it.
    if ( entryPoint.find( "://" ) != std::string::npos )
        return false;
58

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

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

94 95 96
void FsDiscoverer::reload( const std::string& entryPoint )
{
    LOG_INFO( "Reloading folder ", entryPoint );
97
    auto folder = Folder::fromPath( m_ml, entryPoint );
98 99 100 101 102 103 104 105 106 107
    if ( folder == nullptr )
    {
        LOG_ERROR( "Can't reload ", entryPoint, ": folder wasn't found in database" );
        return;
    }
    auto folderFs = m_fsFactory->createDirectory( folder->path() );
    if ( folderFs == nullptr )
    {
        LOG_ERROR(" Failed to create a fs::IDirectory representing ", folder->path() );
    }
108
    checkFolder( *folderFs, *folder );
109 110
}

111 112
void FsDiscoverer::checkDevices()
{
113
    m_fsFactory->refreshDevices();
114
    auto devices = Device::fetchAll( m_ml );
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    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" );
        }
    }
}

131
void FsDiscoverer::checkFolder( fs::IDirectory& currentFolderFs, Folder& currentFolder ) const
132
{
133 134
    // We already know of this folder, though it may now contain a .nomedia file.
    // In this case, simply delete the folder.
135
    if ( hasDotNoMediaFile( currentFolderFs ) )
136
    {
137 138
        LOG_INFO( "Deleting folder ", currentFolderFs.path(), " due to a .nomedia file" );
        m_ml->deleteFolder( currentFolder );
139
        return;
140
    }
141
    m_cb->onDiscoveryProgress( currentFolderFs.path() );
142
    // Load the folders we already know of:
143
    LOG_INFO( "Checking for modifications in ", currentFolderFs.path() );
144
    auto subFoldersInDB = Folder::fetchAll( m_ml, currentFolder.id() );
145
    for ( const auto& subFolder : currentFolderFs.dirs() )
146
    {
147 148
        auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [&subFolder](const std::shared_ptr<Folder>& f) {
            return f->path() == subFolder->path();
149 150 151
        });
        // We don't know this folder, it's a new one
        if ( it == end( subFoldersInDB ) )
152
        {
153 154 155 156 157
            if ( hasDotNoMediaFile( *subFolder ) )
            {
                LOG_INFO( "Ignoring folder with a .nomedia file" );
                continue;
            }
158
            LOG_INFO( "New folder detected: ", subFolder->path() );
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
            try
            {
                addFolder( *subFolder, &currentFolder );
                continue;
            }
            catch ( sqlite::errors::ConstraintViolation& ex )
            {
                // Best attempt to detect a foreign key violation, indicating the parent folders have been
                // deleted due to blacklisting
                if ( strstr( ex.what(), "foreign key" ) != NULL )
                {
                    LOG_WARN( "Creation of a folder failed because the parent is non existing: ", ex.what(),
                              ". Assuming it was deleted due to blacklisting" );
                    return;
                }
                LOG_WARN( "Creation of a duplicated folder failed: ", ex.what(), ". Assuming it was blacklisted" );
                continue;
            }
177
        }
178
        auto folderInDb = *it;
179 180 181
        // 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
182
        checkFolder( *subFolder, *folderInDb );
183 184 185 186 187
        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 )
    {
188
        LOG_INFO( "Folder ", f->path(), " not found in FS, deleting it" );
189
        m_ml->deleteFolder( *f );
190
    }
191
    checkFiles( currentFolderFs, currentFolder );
192
    LOG_INFO( "Done checking subfolders in ", currentFolderFs.path() );
193
}
194

195
void FsDiscoverer::checkFiles( fs::IDirectory& parentFolderFs, Folder& parentFolder ) const
196
{
197
    LOG_INFO( "Checking file in ", parentFolderFs.path() );
198
    static const std::string req = "SELECT * FROM " + policy::FileTable::Name
199
            + " WHERE folder_id = ?";
200
    auto files = File::fetchAll<File>( m_ml, req, parentFolder.id() );
201
    std::vector<std::shared_ptr<fs::IFile>> filesToAdd;
202
    std::vector<std::shared_ptr<File>> filesToRemove;
203
    for ( const auto& fileFs: parentFolderFs.files() )
204
    {
205 206
        auto it = std::find_if( begin( files ), end( files ), [fileFs](const std::shared_ptr<File>& f) {
            return f->mrl() == fileFs->fullPath();
207 208 209
        });
        if ( it == end( files ) )
        {
210
            filesToAdd.push_back( fileFs );
211
            continue;
212
        }
213
        if ( fileFs->lastModificationDate() == (*it)->lastModificationDate() )
214
        {
215 216 217
            // Unchanged file
            files.erase( it );
            continue;
218
        }
219
        auto& file = (*it);
220
        LOG_INFO( "Forcing file refresh ", fileFs->fullPath() );
221 222 223 224
        // 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 );
225
        filesToAdd.push_back( fileFs );
226 227
        files.erase( it );
    }
228
    auto t = m_ml->getConn()->newTransaction();
229 230
    for ( auto file : files )
    {
231
        LOG_INFO( "File ", file->mrl(), " not found on filesystem, deleting it" );
232
        file->media()->removeFile( *file );
233
    }
234 235 236 237
    for ( auto& f : filesToRemove )
        f->media()->removeFile( *f );
    // Insert all files at once to avoid SQL write contention
    for ( auto& p : filesToAdd )
238
        m_ml->addFile( *p, parentFolder, parentFolderFs );
239
    t->commit();
240
    LOG_INFO( "Done checking files in ", parentFolderFs.path() );
241
}
242

243 244 245
bool FsDiscoverer::hasDotNoMediaFile( const fs::IDirectory& directory )
{
    const auto& files = directory.files();
246 247
    return std::find_if( begin( files ), end( files ), []( const std::shared_ptr<fs::IFile>& file ){
        return file->name() == ".nomedia";
248 249 250
    }) != end( files );
}

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

263
    auto f = Folder::create( m_ml, folder.path(),
264
                             parentFolder != nullptr ? parentFolder->id() : 0,
265
                             *device, *deviceFs );
266 267
    if ( f == nullptr )
        return false;
268
    checkFolder( folder, *f );
269 270
    return true;
}
271

272
}