Split the LMS_LOG macro to work either with a ostream logger or a wt logger

This commit is contained in:
emeric
2019-11-19 18:14:23 +01:00
parent 9259ec19e1
commit b69e0c0c3d
32 changed files with 282 additions and 88 deletions
+5 -1
View File
@@ -151,8 +151,12 @@ lms_SOURCES = \
$(srcdir)/utils/Path.cpp \
$(srcdir)/utils/Path.hpp \
$(srcdir)/utils/Service.hpp \
$(srcdir)/utils/StreamLogger.cpp \
$(srcdir)/utils/StreamLogger.hpp \
$(srcdir)/utils/Utils.cpp \
$(srcdir)/utils/Utils.hpp
$(srcdir)/utils/Utils.hpp \
$(srcdir)/utils/WtLogger.cpp \
$(srcdir)/utils/WtLogger.hpp
lms_CXXFLAGS=-std=c++17 -I$(srcdir)/ui $(MAGICKXX_CFLAGS) -D_REENTRANT
lms_LDADD=$(MAGICKXX_LIBS)
+11 -11
View File
@@ -595,10 +595,10 @@ handleChangePassword(RequestContext& context)
std::string username {getMandatoryParameterAs<std::string>(context.parameters, "username")};
std::string password {decodePasswordIfNeeded(getMandatoryParameterAs<std::string>(context.parameters, "password"))};
if (!getService<Auth::PasswordService>()->evaluatePasswordStrength(username, password))
if (!ServiceProvider<Auth::PasswordService>::get()->evaluatePasswordStrength(username, password))
throw PasswordTooWeakGenericError {};
const User::PasswordHash hash {getService<Auth::PasswordService>()->hashPassword(password)};
const User::PasswordHash hash {ServiceProvider<Auth::PasswordService>::get()->hashPassword(password)};
auto transaction {context.dbSession.createUniqueTransaction()};
@@ -677,10 +677,10 @@ handleCreateUserRequest(RequestContext& context)
std::string password {decodePasswordIfNeeded(getMandatoryParameterAs<std::string>(context.parameters, "password"))};
// Just ignore all the other fields as we don't handle them
if (!getService<Auth::PasswordService>()->evaluatePasswordStrength(username, password))
if (!ServiceProvider<Auth::PasswordService>::get()->evaluatePasswordStrength(username, password))
throw PasswordTooWeakGenericError {};
const User::PasswordHash hash {getService<Auth::PasswordService>()->hashPassword(password)};
const User::PasswordHash hash {ServiceProvider<Auth::PasswordService>::get()->hashPassword(password)};
auto transaction {context.dbSession.createUniqueTransaction()};
@@ -960,7 +960,7 @@ handleGetArtistInfoRequestCommon(RequestContext& context, bool id3)
artistInfoNode.createChild("musicBrainzId").setValue(artist->getMBID());
}
auto similarArtistsId {getService<Similarity::Searcher>()->getSimilarArtists(context.dbSession, id.value, count)};
auto similarArtistsId {ServiceProvider<Similarity::Searcher>::get()->getSimilarArtists(context.dbSession, id.value, count)};
{
auto transaction {context.dbSession.createSharedTransaction()};
@@ -1156,7 +1156,7 @@ handleGetSimilarSongsRequestCommon(RequestContext& context, bool id3)
// Optional params
std::size_t count {getParameterAs<std::size_t>(context.parameters, "count").value_or(50)};
auto similarArtistsId {getService<Similarity::Searcher>()->getSimilarArtists(context.dbSession, id.value, 5)};
auto similarArtistsId {ServiceProvider<Similarity::Searcher>::get()->getSimilarArtists(context.dbSession, id.value, 5)};
auto transaction {context.dbSession.createSharedTransaction()};
@@ -1604,10 +1604,10 @@ handleUpdateUserRequest(RequestContext& context)
if (password)
{
*password = decodePasswordIfNeeded(*password);
if (!getService<Auth::PasswordService>()->evaluatePasswordStrength(username, *password))
if (!ServiceProvider<Auth::PasswordService>::get()->evaluatePasswordStrength(username, *password))
throw PasswordTooWeakGenericError {};
hash = getService<Auth::PasswordService>()->hashPassword(*password);
hash = ServiceProvider<Auth::PasswordService>::get()->hashPassword(*password);
}
auto transaction {context.dbSession.createUniqueTransaction()};
@@ -1816,10 +1816,10 @@ handleGetCoverArt(RequestContext& context, Wt::Http::ResponseContinuation*)
switch (id.type)
{
case Id::Type::Track:
res.data = getService<CoverArt::Grabber>()->getFromTrack(context.dbSession, id.value, Image::Format::JPEG, size);
res.data = ServiceProvider<CoverArt::Grabber>::get()->getFromTrack(context.dbSession, id.value, Image::Format::JPEG, size);
break;
case Id::Type::Release:
res.data = getService<CoverArt::Grabber>()->getFromRelease(context.dbSession, id.value, Image::Format::JPEG, size);
res.data = ServiceProvider<CoverArt::Grabber>::get()->getFromRelease(context.dbSession, id.value, Image::Format::JPEG, size);
break;
default:
throw BadParameterGenericError {"id"};
@@ -1908,7 +1908,7 @@ SubsonicResource::handleRequest(const Wt::Http::Request &request, Wt::Http::Resp
Session& dbSession {getOrCreateDbSession(_db)};
switch (getService<Auth::PasswordService>()->checkUserPassword(dbSession,
switch (ServiceProvider<Auth::PasswordService>::get()->checkUserPassword(dbSession,
boost::asio::ip::address::from_string(request.clientAddress()),
clientInfo.user, clientInfo.password))
{
+1 -1
View File
@@ -38,7 +38,7 @@ static std::filesystem::path ffmpegPath;
void
Transcoder::init()
{
ffmpegPath = getService<Config>()->getPath("ffmpeg-file", "/usr/bin/ffmpeg");
ffmpegPath = ServiceProvider<Config>::get()->getPath("ffmpeg-file", "/usr/bin/ffmpeg");
if (!std::filesystem::exists(ffmpegPath))
throw LmsException {"File '" + ffmpegPath.string() + "' does not exist!"};
}
+24 -23
View File
@@ -35,35 +35,35 @@
#include "similarity/SimilaritySearcher.hpp"
#include "ui/LmsApplication.hpp"
#include "utils/Config.hpp"
#include "utils/Logger.hpp"
#include "utils/Service.hpp"
#include "utils/WtLogger.hpp"
std::vector<std::string> generateWtConfig(std::string execPath)
{
std::vector<std::string> args;
const std::filesystem::path wtConfigPath {getService<Config>()->getPath("working-dir") / "wt_config.xml"};
const std::filesystem::path wtLogFilePath {getService<Config>()->getPath("log-file", "/var/log/lms.log")};
const std::filesystem::path wtAccessLogFilePath {getService<Config>()->getPath("access-log-file", "/var/log/lms.access.log")};
const std::filesystem::path wtConfigPath {ServiceProvider<Config>::get()->getPath("working-dir") / "wt_config.xml"};
const std::filesystem::path wtLogFilePath {ServiceProvider<Config>::get()->getPath("log-file", "/var/log/lms.log")};
const std::filesystem::path wtAccessLogFilePath {ServiceProvider<Config>::get()->getPath("access-log-file", "/var/log/lms.access.log")};
args.push_back(execPath);
args.push_back("--config=" + wtConfigPath.string());
args.push_back("--docroot=" + getService<Config>()->getString("docroot"));
args.push_back("--approot=" + getService<Config>()->getString("approot"));
args.push_back("--resources-dir=" + getService<Config>()->getString("wt-resources"));
args.push_back("--docroot=" + ServiceProvider<Config>::get()->getString("docroot"));
args.push_back("--approot=" + ServiceProvider<Config>::get()->getString("approot"));
args.push_back("--resources-dir=" + ServiceProvider<Config>::get()->getString("wt-resources"));
if (getService<Config>()->getBool("tls-enable", false))
if (ServiceProvider<Config>::get()->getBool("tls-enable", false))
{
args.push_back("--https-port=" + std::to_string( getService<Config>()->getULong("listen-port", 5082)));
args.push_back("--https-address=" + getService<Config>()->getString("listen-addr", "0.0.0.0"));
args.push_back("--ssl-certificate=" + getService<Config>()->getString("tls-cert"));
args.push_back("--ssl-private-key=" + getService<Config>()->getString("tls-key"));
args.push_back("--ssl-tmp-dh=" + getService<Config>()->getString("tls-dh"));
args.push_back("--https-port=" + std::to_string( ServiceProvider<Config>::get()->getULong("listen-port", 5082)));
args.push_back("--https-address=" + ServiceProvider<Config>::get()->getString("listen-addr", "0.0.0.0"));
args.push_back("--ssl-certificate=" + ServiceProvider<Config>::get()->getString("tls-cert"));
args.push_back("--ssl-private-key=" + ServiceProvider<Config>::get()->getString("tls-key"));
args.push_back("--ssl-tmp-dh=" + ServiceProvider<Config>::get()->getString("tls-dh"));
}
else
{
args.push_back("--http-port=" + std::to_string( getService<Config>()->getULong("listen-port", 5082)));
args.push_back("--http-address=" + getService<Config>()->getString("listen-addr", "0.0.0.0"));
args.push_back("--http-port=" + std::to_string( ServiceProvider<Config>::get()->getULong("listen-port", 5082)));
args.push_back("--http-address=" + ServiceProvider<Config>::get()->getString("listen-addr", "0.0.0.0"));
}
if (!wtAccessLogFilePath.empty())
@@ -74,8 +74,8 @@ std::vector<std::string> generateWtConfig(std::string execPath)
pt.put("server.application-settings.<xmlattr>.location", "*");
pt.put("server.application-settings.log-file", wtLogFilePath.string());
pt.put("server.application-settings.log-config", getService<Config>()->getString("log-config", "* -debug -info:WebRequest"));
pt.put("server.application-settings.behind-reverse-proxy", getService<Config>()->getBool("behind-reverse-proxy", false));
pt.put("server.application-settings.log-config", ServiceProvider<Config>::get()->getString("log-config", "* -debug -info:WebRequest"));
pt.put("server.application-settings.behind-reverse-proxy", ServiceProvider<Config>::get()->getBool("behind-reverse-proxy", false));
pt.put("server.application-settings.progressive-bootstrap", true);
std::ofstream oss(wtConfigPath.string().c_str(), std::ios::out);
@@ -109,10 +109,11 @@ int main(int argc, char* argv[])
close(STDIN_FILENO);
ServiceProvider<Config>::create(configFilePath);
ServiceProvider<Logger>::create<WtLogger>();
// Make sure the working directory exists
std::filesystem::create_directories(getService<Config>()->getPath("working-dir"));
std::filesystem::create_directories(getService<Config>()->getPath("working-dir") / "cache");
std::filesystem::create_directories(ServiceProvider<Config>::get()->getPath("working-dir"));
std::filesystem::create_directories(ServiceProvider<Config>::get()->getPath("working-dir") / "cache");
// Construct WT configuration and get the argc/argv back
std::vector<std::string> wtServerArgs = generateWtConfig(argv[0]);
@@ -132,13 +133,13 @@ int main(int argc, char* argv[])
Av::Transcoder::init();
// Initializing a connection pool to the database that will be shared along services
Database::Db database {getService<Config>()->getPath("working-dir") / "lms.db"};
Database::Db database {ServiceProvider<Config>::get()->getPath("working-dir") / "lms.db"};
UserInterface::LmsApplicationGroupContainer appGroups;
// Service initialization order is important
ServiceProvider<Auth::AuthTokenService>::create(getService<Config>()->getULong("login-throttler-max-entriees", 10000));
ServiceProvider<Auth::PasswordService>::create(getService<Config>()->getULong("login-throttler-max-entriees", 10000));
ServiceProvider<Auth::AuthTokenService>::create(ServiceProvider<Config>::get()->getULong("login-throttler-max-entriees", 10000));
ServiceProvider<Auth::PasswordService>::create(ServiceProvider<Config>::get()->getULong("login-throttler-max-entriees", 10000));
Scanner::MediaScanner& mediaScanner {ServiceProvider<Scanner::MediaScanner>::create(database.createSession())};
Similarity::FeaturesScannerAddon similarityFeaturesScannerAddon {database.createSession()};
@@ -153,7 +154,7 @@ int main(int argc, char* argv[])
API::Subsonic::SubsonicResource subsonicResource {database};
// bind API resources
if (getService<Config>()->getBool("api-subsonic", true))
if (ServiceProvider<Config>::get()->getBool("api-subsonic", true))
server.addResource(&subsonicResource, subsonicResource.getPath());
// bind UI entry point
@@ -38,7 +38,7 @@ getJsonData(const std::string& mbid)
{
static const std::string defaultAPIURL = "https://acousticbrainz.org/api/v1/";
const std::string url {getService<Config>()->getString("acousticbrainz-api-url", defaultAPIURL) + mbid + "/low-level"};
const std::string url {ServiceProvider<Config>::get()->getString("acousticbrainz-api-url", defaultAPIURL) + mbid + "/low-level"};
boost::asio::io_service ioService;
@@ -33,7 +33,7 @@ namespace Similarity {
static
std::filesystem::path getCacheDirectory()
{
return getService<Config>()->getPath("working-dir") / "cache" / "features";
return ServiceProvider<Config>::get()->getPath("working-dir") / "cache" / "features";
}
static std::filesystem::path getCacheNetworkFilePath()
@@ -243,7 +243,7 @@ FeaturesCache::read()
void
FeaturesCache::write()
{
std::filesystem::create_directories(getService<Config>()->getPath("working-dir") / "cache" / "features");
std::filesystem::create_directories(ServiceProvider<Config>::get()->getPath("working-dir") / "cache" / "features");
if (!networkToCacheFile(_network, getCacheNetworkFilePath())
|| !objectPositionToCacheFile(_trackPositions, getCacheTrackPositionsFilePath()))
+3 -3
View File
@@ -43,7 +43,7 @@ static
void
createAuthToken(Database::IdType userId, const Wt::WDateTime& expiry)
{
const std::string secret {getService<::Auth::AuthTokenService>()->createAuthToken(LmsApp->getDbSession(), userId, expiry)};
const std::string secret {ServiceProvider<::Auth::AuthTokenService>::get()->createAuthToken(LmsApp->getDbSession(), userId, expiry)};
LmsApp->setCookie(authCookieName,
secret,
@@ -61,7 +61,7 @@ processAuthToken(const Wt::WEnvironment& env)
if (!authCookie)
return std::nullopt;
const auto res {getService<::Auth::AuthTokenService>()->processAuthToken(LmsApp->getDbSession(), boost::asio::ip::address::from_string(env.clientAddress()), *authCookie)};
const auto res {ServiceProvider<::Auth::AuthTokenService>::get()->processAuthToken(LmsApp->getDbSession(), boost::asio::ip::address::from_string(env.clientAddress()), *authCookie)};
switch (res.state)
{
case ::Auth::AuthTokenService::AuthTokenProcessResult::State::NotFound:
@@ -124,7 +124,7 @@ class AuthModel : public Wt::WFormModel
if (field == PasswordField)
{
switch (getService<::Auth::PasswordService>()->checkUserPassword(
switch (ServiceProvider<::Auth::PasswordService>::get()->checkUserPassword(
LmsApp->getDbSession(),
boost::asio::ip::address::from_string(LmsApp->environment().clientAddress()),
valueText(LoginNameField).toUTF8(),
+4 -4
View File
@@ -529,7 +529,7 @@ LmsApplication::createHome()
// Events from MediaScanner
{
const std::string sessionId {LmsApp->sessionId()};
getService<Scanner::MediaScanner>()->scanComplete().connect(this, [=] ()
ServiceProvider<Scanner::MediaScanner>::get()->scanComplete().connect(this, [=] ()
{
Wt::WServer::instance()->post(sessionId, [=]
{
@@ -538,7 +538,7 @@ LmsApplication::createHome()
});
});
getService<Scanner::MediaScanner>()->scanInProgress().connect(this, [=] (Scanner::ScanProgressStats stats)
ServiceProvider<Scanner::MediaScanner>::get()->scanInProgress().connect(this, [=] (Scanner::ScanProgressStats stats)
{
Wt::WServer::instance()->post(sessionId, [=]
{
@@ -547,7 +547,7 @@ LmsApplication::createHome()
});
});
getService<Scanner::MediaScanner>()->scheduled().connect(this, [=] (Wt::WDateTime dateTime)
ServiceProvider<Scanner::MediaScanner>::get()->scheduled().connect(this, [=] (Wt::WDateTime dateTime)
{
Wt::WServer::instance()->post(sessionId, [=]
{
@@ -562,7 +562,7 @@ LmsApplication::createHome()
{
if (isUserAdmin())
{
const auto& stats {*getService<Scanner::MediaScanner>()->getStatus().lastCompleteScanStats};
const auto& stats {*ServiceProvider<Scanner::MediaScanner>::get()->getStatus().lastCompleteScanStats};
notifyMsg(MsgType::Info, Wt::WString::tr("Lms.Admin.Database.scan-complete")
.arg(static_cast<unsigned>(stats.nbFiles()))
+1 -1
View File
@@ -412,7 +412,7 @@ PlayQueue::addSome()
void
PlayQueue::enqueueRadioTrack()
{
const std::vector<Database::IdType> trackToAddIds {getService<Similarity::Searcher>()->getSimilarTracksFromTrackList(LmsApp->getDbSession(), _tracklistId, 1)};
const std::vector<Database::IdType> trackToAddIds {ServiceProvider<Similarity::Searcher>::get()->getSimilarTracksFromTrackList(LmsApp->getDbSession(), _tracklistId, 1)};
enqueueTracks(trackToAddIds);
}
+3 -3
View File
@@ -80,7 +80,7 @@ class SettingsModel : public Wt::WFormModel
Database::User::PasswordHash passwordHash;
if (!valueText(PasswordField).empty())
passwordHash = getService<::Auth::PasswordService>()->hashPassword(valueText(PasswordField).toUTF8());
passwordHash = ServiceProvider<::Auth::PasswordService>::get()->hashPassword(valueText(PasswordField).toUTF8());
auto transaction {LmsApp->getDbSession().createUniqueTransaction()};
@@ -133,7 +133,7 @@ class SettingsModel : public Wt::WFormModel
{
if (!valueText(PasswordOldField).empty())
{
switch (getService<::Auth::PasswordService>()->checkUserPassword(
switch (ServiceProvider<::Auth::PasswordService>::get()->checkUserPassword(
LmsApp->getDbSession(),
boost::asio::ip::address::from_string(LmsApp->environment().clientAddress()),
LmsApp->getUserLoginName(),
@@ -161,7 +161,7 @@ class SettingsModel : public Wt::WFormModel
{
if (!valueText(PasswordField).empty())
{
if (!getService<::Auth::PasswordService>()->evaluatePasswordStrength(LmsApp->getUserLoginName(), valueText(PasswordField).toUTF8()))
if (!ServiceProvider<::Auth::PasswordService>::get()->evaluatePasswordStrength(LmsApp->getUserLoginName(), valueText(PasswordField).toUTF8()))
error = Wt::WString::tr("Lms.password-too-weak");
}
else
+2 -2
View File
@@ -232,7 +232,7 @@ DatabaseSettingsView::refreshView()
{
model->saveData();
getService<Scanner::MediaScanner>()->requestReschedule();
ServiceProvider<Scanner::MediaScanner>::get()->requestReschedule();
LmsApp->notifyMsg(MsgType::Success, Wt::WString::tr("Lms.Admin.Database.settings-saved"));
}
@@ -249,7 +249,7 @@ DatabaseSettingsView::refreshView()
immScanBtn->clicked().connect([=] ()
{
getService<Scanner::MediaScanner>()->requestImmediateScan();
ServiceProvider<Scanner::MediaScanner>::get()->requestImmediateScan();
LmsApp->notifyMsg(MsgType::Info, Wt::WString::tr("Lms.Admin.Database.scan-launched"));
});
+1 -1
View File
@@ -136,7 +136,7 @@ DatabaseStatus::refreshContents()
Wt::WPushButton* reportBtn {bindNew<Wt::WPushButton>("btn-report", Wt::WString::tr("Lms.Admin.Database.Status.get-report"))};
const MediaScanner::Status status {getService<MediaScanner>()->getStatus()};
const MediaScanner::Status status {ServiceProvider<MediaScanner>::get()->getStatus()};
if (status.lastCompleteScanStats)
{
bindString("last-scan", Wt::WString::tr("Lms.Admin.Database.Status.last-scan-status")
+2 -2
View File
@@ -55,7 +55,7 @@ class InitWizardModel : public Wt::WFormModel
void saveData()
{
const Database::User::PasswordHash passwordHash {getService<::Auth::PasswordService>()->hashPassword(valueText(PasswordField).toUTF8())};
const Database::User::PasswordHash passwordHash {ServiceProvider<::Auth::PasswordService>::get()->hashPassword(valueText(PasswordField).toUTF8())};
auto transaction(LmsApp->getDbSession().createUniqueTransaction());
@@ -77,7 +77,7 @@ class InitWizardModel : public Wt::WFormModel
if (!valueText(PasswordField).empty())
{
// Evaluate the strength of the password
if (!getService<::Auth::PasswordService>()->evaluatePasswordStrength(valueText(AdminLoginField).toUTF8(), valueText(PasswordField).toUTF8()))
if (!ServiceProvider<::Auth::PasswordService>::get()->evaluatePasswordStrength(valueText(AdminLoginField).toUTF8(), valueText(PasswordField).toUTF8()))
error = Wt::WString::tr("Lms.password-too-weak");
}
else
+3 -3
View File
@@ -82,7 +82,7 @@ class UserModel : public Wt::WFormModel
{
std::optional<Database::User::PasswordHash> passwordHash;
if (!valueText(PasswordField).empty())
passwordHash = getService<::Auth::PasswordService>()->hashPassword(valueText(PasswordField).toUTF8());
passwordHash = ServiceProvider<::Auth::PasswordService>::get()->hashPassword(valueText(PasswordField).toUTF8());
auto transaction {LmsApp->getDbSession().createUniqueTransaction()};
@@ -174,7 +174,7 @@ class UserModel : public Wt::WFormModel
else
{
// Evaluate the strength of the password for non demo accounts
if (!getService<::Auth::PasswordService>()->evaluatePasswordStrength(getLoginName(), valueText(PasswordField).toUTF8()))
if (!ServiceProvider<::Auth::PasswordService>::get()->evaluatePasswordStrength(getLoginName(), valueText(PasswordField).toUTF8()))
error = Wt::WString::tr("Lms.password-too-weak");
}
}
@@ -270,7 +270,7 @@ UserView::refreshView()
// Demo account
t->setFormWidget(UserModel::DemoField, std::make_unique<Wt::WCheckBox>());
if (!userId && getService<Config>()->getBool("demo", false))
if (!userId && ServiceProvider<Config>::get()->getBool("demo", false))
t->setCondition("if-demo", true);
Wt::WPushButton* saveBtn = t->bindNew<Wt::WPushButton>("save-btn", Wt::WString::tr(userId ? "Lms.save" : "Lms.create"));
+1 -1
View File
@@ -63,7 +63,7 @@ ArtistInfo::refresh()
if (!artistId)
return;
const std::vector<Database::IdType> artistsIds {getService<Similarity::Searcher>()->getSimilarArtists(LmsApp->getDbSession(), *artistId, 5)};
const std::vector<Database::IdType> artistsIds {ServiceProvider<Similarity::Searcher>::get()->getSimilarArtists(LmsApp->getDbSession(), *artistId, 5)};
auto transaction {LmsApp->getDbSession().createSharedTransaction()};
+1 -1
View File
@@ -68,7 +68,7 @@ ReleaseInfo::refresh()
if (!releaseId)
return;
const std::vector<Database::IdType> releasesIds {getService<Similarity::Searcher>()->getSimilarReleases(LmsApp->getDbSession(), *releaseId, 5)};
const std::vector<Database::IdType> releasesIds {ServiceProvider<Similarity::Searcher>::get()->getSimilarReleases(LmsApp->getDbSession(), *releaseId, 5)};
auto transaction {LmsApp->getDbSession().createSharedTransaction()};
+2 -2
View File
@@ -80,7 +80,7 @@ ImageResource::handleRequest(const Wt::Http::Request& request, Wt::Http::Respons
// DbSession are not thread safe
{
Wt::WApplication::UpdateLock lock {LmsApp};
cover = getService<CoverArt::Grabber>()->getFromTrack(LmsApp->getDbSession(), *trackId, Image::Format::JPEG, *size);
cover = ServiceProvider<CoverArt::Grabber>::get()->getFromTrack(LmsApp->getDbSession(), *trackId, Image::Format::JPEG, *size);
}
}
else if (releaseIdStr)
@@ -92,7 +92,7 @@ ImageResource::handleRequest(const Wt::Http::Request& request, Wt::Http::Respons
// DbSession are not thread safe
{
Wt::WApplication::UpdateLock lock {LmsApp};
cover = getService<CoverArt::Grabber>()->getFromRelease(LmsApp->getDbSession(), *releaseId, Image::Format::JPEG, *size);
cover = ServiceProvider<CoverArt::Grabber>::get()->getFromRelease(LmsApp->getDbSession(), *releaseId, Image::Format::JPEG, *size);
}
}
else
+18
View File
@@ -54,3 +54,21 @@ const char* getSeverityName(Severity sev)
return "";
}
Log::Log(Logger* logger, Module module, Severity severity)
: _module {module},
_severity {severity},
_logger {logger}
{}
Log::~Log()
{
if (_logger)
_logger->processLog(*this);
}
std::string
Log::getMessage() const
{
return _oss.str();
}
+26 -6
View File
@@ -20,9 +20,9 @@
#pragma once
#include <string>
#include <sstream>
#include <Wt/WApplication.h>
#include <Wt/WLogger.h>
#include "Service.hpp"
enum class Severity
{
@@ -54,11 +54,31 @@ enum class Module
const char* getModuleName(Module mod);
const char* getSeverityName(Severity sev);
class Logger;
class Log
{
public:
Log(Logger* logger, Module module, Severity severity);
~Log();
TODO class logger
TODO class log entry
Module getModule() const { return _module; }
Severity getSeverity() const { return _severity; }
std::string getMessage() const;
TODO configure logger to redirect to either Wt's logger or to a ostream
std::ostringstream& getOstream() { return _oss; }
#define LMS_LOG(module, level) Wt::log(getSeverityName(Severity::level)) << Wt::WLogger::sep << "[" << getModuleName(Module::module) << "]" << Wt::WLogger::sep
private:
Module _module;
Severity _severity;
std::ostringstream _oss;
Logger* _logger {};
};
class Logger
{
public:
virtual void processLog(const Log& log) = 0;
};
#define LMS_LOG(module, severity) Log(ServiceProvider<Logger>::get(), Module::module, Severity::severity).getOstream()
+21 -18
View File
@@ -17,38 +17,41 @@
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include <memory>
#pragma once
template <typename T>
#include <memory>
#include <type_traits>
template <typename Class>
class ServiceProvider
{
public:
template <class DerivedClass, class ...Args>
static
Class&
create(Args&&... args)
{
static_assert(std::is_base_of<Class, DerivedClass>::value);
assign(std::make_unique<DerivedClass>(std::forward<Args>(args)...));
return *get();
}
template <class ...Args>
static
T&
Class&
create(Args&&... args)
{
assign(std::make_unique<T>(std::forward<Args>(args)...));
assign(std::make_unique<Class>(std::forward<Args>(args)...));
return *get();
}
static void assign(std::unique_ptr<T> service) { _service = std::move(service); }
static void assign(std::unique_ptr<Class> service) { _service = std::move(service); }
static void clear() { _service.reset(); }
static T* get() { return _service.get(); }
static Class* get() { return _service.get(); }
private:
static std::unique_ptr<T> _service;
static inline std::unique_ptr<Class> _service;
};
template <typename T>
std::unique_ptr<T> ServiceProvider<T>::_service = {};
template <typename T>
T*
getService()
{
return ServiceProvider<T>::get();
}
+32
View File
@@ -0,0 +1,32 @@
/*
* Copyright (C) 2019 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 <http://www.gnu.org/licenses/>.
*/
#include "StreamLogger.hpp"
StreamLogger::StreamLogger(std::ostream& os)
: _os {os}
{
}
void
StreamLogger::processLog(const Log& log)
{
_os << "[" << getSeverityName(log.getSeverity()) << "] [" << getModuleName(log.getModule()) << "] " << log.getMessage() << std::endl;
}
+34
View File
@@ -0,0 +1,34 @@
/*
* Copyright (C) 2019 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 <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "Logger.hpp"
class StreamLogger final : public Logger
{
public:
StreamLogger(std::ostream& oss);
void processLog(const Log& log);
private:
std::ostream& _os;
};
+32
View File
@@ -0,0 +1,32 @@
/*
* Copyright (C) 2019 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 <http://www.gnu.org/licenses/>.
*/
#include "WtLogger.hpp"
#include <Wt/WApplication.h>
#include <Wt/WLogger.h>
#include "Logger.hpp"
void
WtLogger::processLog(const Log& log)
{
Wt::log(getSeverityName(log.getSeverity())) << Wt::WLogger::sep << "[" << getModuleName(log.getModule()) << "]" << log.getMessage();
}
+29
View File
@@ -0,0 +1,29 @@
/*
* Copyright (C) 2019 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 <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "Logger.hpp"
class WtLogger final : public Logger
{
public:
void processLog(const Log& log) override;
};
+1
View File
@@ -27,6 +27,7 @@ test_database_SOURCES = \
$(top_srcdir)/src/database/Track.cpp \
$(top_srcdir)/src/database/User.cpp \
$(top_srcdir)/src/utils/Logger.cpp \
$(top_srcdir)/src/utils/StreamLogger.cpp \
$(top_srcdir)/src/utils/Utils.cpp
test_database_CXXFLAGS=-std=c++17 -I${top_srcdir}/src/
+5
View File
@@ -30,6 +30,8 @@
#include "database/Track.hpp"
#include "database/User.hpp"
#include "utils/StreamLogger.hpp"
using namespace Database;
#define CHECK(PRED) \
@@ -1253,6 +1255,9 @@ int main()
try
{
// log to stdout
ServiceProvider<Logger>::create<StreamLogger>(std::cout);
const std::filesystem::path tmpFile {std::tmpnam(nullptr)};
ScopedFileDeleter tmpFileDeleter {tmpFile};
+4
View File
@@ -9,6 +9,7 @@
#include "av/AvInfo.hpp"
#include "metadata/AvFormat.hpp"
#include "metadata/TagLibParser.hpp"
#include "utils/StreamLogger.hpp"
std::ostream& operator<<(std::ostream& os, const MetaData::Artist& artist)
{
@@ -124,6 +125,9 @@ int main(int argc, char *argv[])
try
{
// log to stdout
ServiceProvider<Logger>::create<StreamLogger>(std::cout);
for (std::size_t i {}; i < static_cast<std::size_t>(argc - 1); ++i)
{
std::filesystem::path file {argv[i + 1]};
+1
View File
@@ -6,6 +6,7 @@ lms_metadata_SOURCES = \
$(top_srcdir)/src/metadata/AvFormat.cpp \
$(top_srcdir)/src/metadata/TagLibParser.cpp \
$(top_srcdir)/src/utils/Logger.cpp \
$(top_srcdir)/src/utils/StreamLogger.cpp \
$(top_srcdir)/src/utils/Utils.cpp
lms_metadata_CXXFLAGS=-std=c++17 -I$(top_srcdir)/src -D_REENTRANT
@@ -6,19 +6,23 @@
#include "database/Db.hpp"
#include "utils/Config.hpp"
#include "utils/Service.hpp"
#include "utils/StreamLogger.hpp"
int main(int argc, char *argv[])
{
try
{
// log to stdout
ServiceProvider<Logger>::create<StreamLogger>(std::cout);
std::filesystem::path configFilePath {"/etc/lms.conf"};
if (argc >= 2)
configFilePath = std::string(argv[1], 0, 256);
ServiceProvider<Config>::create(configFilePath);
Database::Db db {getService<Config>()->getPath("working-dir") / "lms.db"};
Database::Db db {ServiceProvider<Config>::get()->getPath("working-dir") / "lms.db"};
auto session {db.createSession()};
/* const FeatureSettings
+1
View File
@@ -18,6 +18,7 @@ lms_similarity_parameters_SOURCES = \
$(top_srcdir)/src/similarity/features/som/Network.cpp \
$(top_srcdir)/src/utils/Config.cpp \
$(top_srcdir)/src/utils/Logger.cpp \
$(top_srcdir)/src/utils/StreamLogger.cpp \
$(top_srcdir)/src/utils/Utils.cpp
lms_similarity_parameters_CXXFLAGS=-std=c++17 -I$(top_srcdir)/src -D_REENTRANT
+5 -1
View File
@@ -7,6 +7,7 @@
#include "database/Session.hpp"
#include "utils/Config.hpp"
#include "utils/Service.hpp"
#include "utils/StreamLogger.hpp"
#include "similarity/features/SimilarityFeaturesSearcher.hpp"
int main(int argc, char *argv[])
@@ -15,6 +16,9 @@ int main(int argc, char *argv[])
{
using namespace Similarity;
// log to stdout
ServiceProvider<Logger>::create<StreamLogger>(std::cout);
const FeatureSettingsMap featuresSettings
{
// { "lowlevel.average_loudness", 1 },
@@ -34,7 +38,7 @@ int main(int argc, char *argv[])
ServiceProvider<Config>::create(configFilePath);
Database::Db db {getService<Config>()->getPath("working-dir") / "lms.db"};
Database::Db db {ServiceProvider<Config>::get()->getPath("working-dir") / "lms.db"};
auto session {db.createSession()};
std::cout << "Getting all features..." << std::endl;
+1
View File
@@ -21,6 +21,7 @@ lms_similarity_SOURCES = \
$(top_srcdir)/src/similarity/features/SimilarityFeaturesDefs.cpp \
$(top_srcdir)/src/utils/Config.cpp \
$(top_srcdir)/src/utils/Logger.cpp \
$(top_srcdir)/src/utils/StreamLogger.cpp \
$(top_srcdir)/src/utils/Utils.cpp
lms_similarity_CXXFLAGS=-std=c++17 -I$(top_srcdir)/src -D_REENTRANT