/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see .
*/
#include
#include
#include
#include
#include "cover/CoverArtGrabber.hpp"
#include "database/Setting.hpp"
#include "database/Types.hpp"
#include "utils/Logger.hpp"
#include "utils/Path.hpp"
#include "utils/Utils.hpp"
#include "MediaScanner.hpp"
namespace {
boost::gregorian::date
getNextDay(const boost::gregorian::date& current)
{
boost::gregorian::day_iterator it(current);
return *(++it);
}
boost::gregorian::date
getNextMonday(const boost::gregorian::date& current)
{
boost::gregorian::day_iterator it(current);
++it;
// While it's not monday
while( it->day_of_week() != 1 )
++it;
return *(it);
}
boost::gregorian::date
getNextFirstOfMonth(const boost::gregorian::date& current)
{
boost::gregorian::day_iterator it(current);
++it;
// While it's not the 1st of the month
while( it->day() != 1 )
++it;
return (*it);
}
bool
isFileSupported(const boost::filesystem::path& file, const std::vector extensions)
{
boost::filesystem::path fileExtension = file.extension();
for (auto& extension : extensions)
{
if (extension == fileExtension)
return true;
}
return false;
}
bool
isPathInParentPath(const boost::filesystem::path& path, const boost::filesystem::path& parentPath)
{
boost::filesystem::path curPath = path;
while (curPath.has_parent_path())
{
curPath = curPath.parent_path();
if (curPath == parentPath)
return true;
}
return false;
}
} // namespace
namespace Scanner {
using namespace Database;
UpdatePeriod
getUpdatePeriod(Wt::Dbo::Session& session)
{
return static_cast(Setting::getInt(session, "update_period", static_cast(UpdatePeriod::Never)));
}
void
setUpdatePeriod(Wt::Dbo::Session& session, UpdatePeriod updatePeriod)
{
Setting::setInt(session, "update_period", static_cast(updatePeriod));
}
boost::posix_time::time_duration getUpdateStartTime(Wt::Dbo::Session& session)
{
return Setting::getDuration(session, "update_start_time");
}
void setUpdateStartTime(Wt::Dbo::Session& session, boost::posix_time::time_duration startTime)
{
Setting::setDuration(session, "update_start_time", startTime);
}
MediaScanner::MediaScanner(Wt::Dbo::SqlConnectionPool& connectionPool)
: _running(false),
_scheduleTimer(_ioService),
_db(connectionPool)
{
_ioService.setThreadCount(1);
Wt::Dbo::Transaction transaction(_db.getSession());
if (!Setting::exists(_db.getSession(), "file_extensions"))
Setting::setString(_db.getSession(), "file_extensions", ".mp3 .ogg .oga .aac .m4a .flac .wav .wma .aif .aiff .ape .mpc .shn" );
}
void
MediaScanner::restart(void)
{
stop();
start();
}
void
MediaScanner::start(void)
{
_running = true;
// post some jobs in the io_service
scheduleScan();
_ioService.start();
}
void
MediaScanner::stop(void)
{
_running = false;
_scheduleTimer.cancel();
_ioService.stop();
}
void
MediaScanner::scheduleImmediateScan()
{
_ioService.post([=]()
{
LMS_LOG(DBUPDATER, INFO) << "Schedule immediate scan";
scheduleScan( boost::posix_time::seconds(0) );
});
}
void
MediaScanner::reschedule()
{
_ioService.post([=]()
{
LMS_LOG(DBUPDATER, INFO) << "Rescheduling scan";
scheduleScan();
});
}
void
MediaScanner::scheduleScan()
{
boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
boost::posix_time::time_duration startTime = getUpdateStartTime(_db.getSession());
boost::gregorian::date nextScanDate;
switch ( getUpdatePeriod(_db.getSession()) )
{
case UpdatePeriod::Daily:
if (now.time_of_day() < startTime)
nextScanDate = now.date();
else
nextScanDate = getNextDay(now.date());
break;
case UpdatePeriod::Weekly:
if (now.time_of_day() < startTime && now.date().day_of_week() == 1)
nextScanDate = now.date();
else
nextScanDate = getNextMonday(now.date());
break;
case UpdatePeriod::Monthly:
if (now.time_of_day() < startTime && now.date().day() == 1)
nextScanDate = now.date();
else
nextScanDate = getNextFirstOfMonth(now.date());
break;
case UpdatePeriod::Never:
LMS_LOG(DBUPDATER, INFO) << "Auto scan disabled!";
break;
}
if (!nextScanDate.is_special())
scheduleScan( boost::posix_time::ptime (nextScanDate, startTime) );
}
void
MediaScanner::scheduleScan( boost::posix_time::time_duration duration)
{
LMS_LOG(DBUPDATER, INFO) << "Scheduling next scan in " << duration;
_scheduleTimer.expires_from_now(duration);
_scheduleTimer.async_wait( boost::bind( &MediaScanner::scan, this, boost::asio::placeholders::error) );
}
void
MediaScanner::scheduleScan( boost::posix_time::ptime time)
{
LMS_LOG(DBUPDATER, INFO) << "Scheduling next scan at " << time;
_scheduleTimer.expires_at(time);
_scheduleTimer.async_wait( boost::bind( &MediaScanner::scan, this, boost::asio::placeholders::error) );
}
void
MediaScanner::scan(boost::system::error_code err)
{
if (err)
return;
refreshScanSettings();
Stats stats;
checkAudioFiles(stats);
for (auto rootDirectory : _rootDirectories)
{
if (!_running)
break;
LMS_LOG(DBUPDATER, INFO) << "scaning root directory '" << rootDirectory << "'...";
scanRootDirectory(rootDirectory, stats);
LMS_LOG(DBUPDATER, INFO) << "scaning root directory '" << rootDirectory << "' DONE";
}
if (_running)
checkDuplicatedAudioFiles(stats);
LMS_LOG(DBUPDATER, INFO) << "Scan " << (_running ? "complete" : "aborted") << ". Changes = " << stats.nbChanges() << " (added = " << stats.nbAdded << ", removed = " << stats.nbRemoved << ", updated = " << stats.nbUpdated << "), Not changed = " << stats.nbNoChange << ", Scanned = " << stats.nbScanned << " (errors = " << stats.nbScanErrors << ", not imported = " << stats.nbNotImported << ")";
// Update database stats
boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
if (stats.nbChanges() > 0)
Setting::setTime(_db.getSession(), "last_update", now);
// Save the last scan only if it has been completed
if (_running)
{
Setting::setTime(_db.getSession(), "last_scan", now);
scheduleScan();
scanComplete().emit(stats);
}
}
void
MediaScanner::refreshScanSettings()
{
Wt::Dbo::Transaction transaction(_db.getSession());
_fileExtensions.clear();
for (auto extension : splitString(Setting::getString(_db.getSession(), "file_extensions"), " "))
_fileExtensions.push_back( extension );
_rootDirectories.clear();
for (auto rootDir : Database::MediaDirectory::getAll(_db.getSession()))
_rootDirectories.push_back(rootDir->getPath());
}
Artist::pointer
MediaScanner::getArtist( const boost::filesystem::path& file, const std::string& name, const std::string& mbid)
{
Artist::pointer artist;
// First try to get by MBID
if (!mbid.empty())
{
artist = Artist::getByMBID( _db.getSession(), mbid );
if (!artist)
artist = Artist::create( _db.getSession(), name, mbid);
return artist;
}
// Fall back on artist name (collisions may occur)
if (!name.empty())
{
for (Artist::pointer sameNamedArtist : Artist::getByName( _db.getSession(), name ))
{
if (sameNamedArtist->getMBID().empty())
{
artist = sameNamedArtist;
break;
}
}
// No Artist found with the same name and without MBID -> creating
if (!artist)
artist = Artist::create( _db.getSession(), name);
return artist;
}
return Artist::pointer();
}
Release::pointer
MediaScanner::getRelease( const boost::filesystem::path& file, const std::string& name, const std::string& mbid)
{
Release::pointer release;
// First try to get by MBID
if (!mbid.empty())
{
release = Release::getByMBID( _db.getSession(), mbid );
if (!release)
release = Release::create( _db.getSession(), name, mbid);
return release;
}
// Fall back on release name (collisions may occur)
if (!name.empty())
{
for (Release::pointer sameNamedRelease : Release::getByName( _db.getSession(), name ))
{
if (sameNamedRelease->getMBID().empty())
{
release = sameNamedRelease;
break;
}
}
// No release found with the same name and without MBID -> creating
if (!release)
release = Release::create( _db.getSession(), name);
return release;
}
return Release::pointer();
}
std::vector
MediaScanner::getClusters( const MetaData::Clusters& clustersNames)
{
std::vector< Cluster::pointer > clusters;
for (auto clusterNames : clustersNames)
{
ClusterType::pointer clusterType = ClusterType::getByName(_db.getSession(), clusterNames.first);
bool newType = !clusterType;
if (!clusterType)
clusterType = ClusterType::create(_db.getSession(), clusterNames.first);
std::cout << "Cluster type = " << clusterType.id() << "\n";
for (auto clusterName : clusterNames.second)
{
Cluster::pointer cluster;
if (!newType)
cluster = clusterType->getCluster(clusterName);
if (!cluster)
cluster = Cluster::create(_db.getSession(), clusterType, clusterName);
clusters.push_back(cluster);
}
}
return clusters;
}
void
MediaScanner::scanAudioFile( const boost::filesystem::path& file, Stats& stats)
{
boost::posix_time::ptime lastWriteTime (boost::posix_time::from_time_t( boost::filesystem::last_write_time( file ) ) );
// Skip file if last write is the same
{
Wt::Dbo::Transaction transaction(_db.getSession());
Wt::Dbo::ptr