diff --git a/src/libs/av/impl/AvTranscoder.cpp b/src/libs/av/impl/AvTranscoder.cpp index f1b9ed94..574f8299 100644 --- a/src/libs/av/impl/AvTranscoder.cpp +++ b/src/libs/av/impl/AvTranscoder.cpp @@ -38,7 +38,7 @@ static std::filesystem::path ffmpegPath; void Transcoder::init() { - ffmpegPath = ServiceProvider::get()->getPath("ffmpeg-file", "/usr/bin/ffmpeg"); + ffmpegPath = Service::get()->getPath("ffmpeg-file", "/usr/bin/ffmpeg"); if (!std::filesystem::exists(ffmpegPath)) throw LmsException {"File '" + ffmpegPath.string() + "' does not exist!"}; } diff --git a/src/libs/recommendation/impl/features/FeaturesClassifierCache.cpp b/src/libs/recommendation/impl/features/FeaturesClassifierCache.cpp index fc80098d..d184ac60 100644 --- a/src/libs/recommendation/impl/features/FeaturesClassifierCache.cpp +++ b/src/libs/recommendation/impl/features/FeaturesClassifierCache.cpp @@ -32,7 +32,7 @@ namespace Recommendation { static std::filesystem::path getCacheDirectory() { - return ServiceProvider::get()->getPath("working-dir") / "cache" / "features"; + return Service::get()->getPath("working-dir") / "cache" / "features"; } static std::filesystem::path getCacheNetworkFilePath() @@ -237,7 +237,7 @@ FeaturesClassifierCache::read() void FeaturesClassifierCache::write() const { - std::filesystem::create_directories(ServiceProvider::get()->getPath("working-dir") / "cache" / "features"); + std::filesystem::create_directories(Service::get()->getPath("working-dir") / "cache" / "features"); if (!networkToCacheFile(_network, getCacheNetworkFilePath()) || !objectPositionToCacheFile(_trackPositions, getCacheTrackPositionsFilePath())) diff --git a/src/libs/scanner/impl/AcousticBrainzUtils.cpp b/src/libs/scanner/impl/AcousticBrainzUtils.cpp index 970e04da..b10cdd46 100644 --- a/src/libs/scanner/impl/AcousticBrainzUtils.cpp +++ b/src/libs/scanner/impl/AcousticBrainzUtils.cpp @@ -40,7 +40,7 @@ getJsonData(const UUID& mbid) { static const std::string defaultAPIURL = "https://acousticbrainz.org/api/v1/"; - const std::string url {ServiceProvider::get()->getString("acousticbrainz-api-url", defaultAPIURL) + std::string {mbid.getAsString()} + "/low-level"}; + const std::string url {Service::get()->getString("acousticbrainz-api-url", defaultAPIURL) + std::string {mbid.getAsString()} + "/low-level"}; boost::asio::io_service ioService; diff --git a/src/libs/subsonic/impl/Scan.cpp b/src/libs/subsonic/impl/Scan.cpp index b663aed2..3b9325a6 100644 --- a/src/libs/subsonic/impl/Scan.cpp +++ b/src/libs/subsonic/impl/Scan.cpp @@ -32,7 +32,7 @@ namespace API::Subsonic::Scan { Response::Node statusResponse; - const IMediaScanner::Status scanStatus {ServiceProvider::get()->getStatus()}; + const IMediaScanner::Status scanStatus {Service::get()->getStatus()}; statusResponse.setAttribute("scanning", scanStatus.currentState == IMediaScanner::State::InProgress); if (scanStatus.currentState == IMediaScanner::State::InProgress) @@ -61,7 +61,7 @@ namespace API::Subsonic::Scan Response handleStartScan(RequestContext& context) { - ServiceProvider::get()->requestImmediateScan(false); + Service::get()->requestImmediateScan(false); Response response {Response::createOkResponse(context)}; response.addNode("scanStatus", createStatusResponseNode()); diff --git a/src/libs/subsonic/impl/SubsonicResource.cpp b/src/libs/subsonic/impl/SubsonicResource.cpp index 2c98cdd8..f5cbd81b 100644 --- a/src/libs/subsonic/impl/SubsonicResource.cpp +++ b/src/libs/subsonic/impl/SubsonicResource.cpp @@ -511,10 +511,10 @@ handleChangePassword(RequestContext& context) std::string username {getMandatoryParameterAs(context.parameters, "username")}; std::string password {decodePasswordIfNeeded(getMandatoryParameterAs(context.parameters, "password"))}; - if (!ServiceProvider::get()->evaluatePasswordStrength(username, password)) + if (!Service::get()->evaluatePasswordStrength(username, password)) throw PasswordTooWeakGenericError {}; - const User::PasswordHash hash {ServiceProvider::get()->hashPassword(password)}; + const User::PasswordHash hash {Service::get()->hashPassword(password)}; auto transaction {context.dbSession.createUniqueTransaction()}; @@ -593,10 +593,10 @@ handleCreateUserRequest(RequestContext& context) std::string password {decodePasswordIfNeeded(getMandatoryParameterAs(context.parameters, "password"))}; // Just ignore all the other fields as we don't handle them - if (!ServiceProvider::get()->evaluatePasswordStrength(username, password)) + if (!Service::get()->evaluatePasswordStrength(username, password)) throw PasswordTooWeakGenericError {}; - const User::PasswordHash hash {ServiceProvider::get()->hashPassword(password)}; + const User::PasswordHash hash {Service::get()->hashPassword(password)}; auto transaction {context.dbSession.createUniqueTransaction()}; @@ -878,7 +878,7 @@ handleGetArtistInfoRequestCommon(RequestContext& context, bool id3) artistInfoNode.createChild("musicBrainzId").setValue(artistMBID->getAsString()); } - auto similarArtistsId {ServiceProvider::get()->getSimilarArtists(context.dbSession, id.value, count)}; + auto similarArtistsId {Service::get()->getSimilarArtists(context.dbSession, id.value, count)}; { auto transaction {context.dbSession.createSharedTransaction()}; @@ -1107,7 +1107,7 @@ handleGetSimilarSongsRequestCommon(RequestContext& context, bool id3) // Optional params std::size_t count {getParameterAs(context.parameters, "count").value_or(50)}; - auto similarArtistsId {ServiceProvider::get()->getSimilarArtists(context.dbSession, id.value, 5)}; + auto similarArtistsId {Service::get()->getSimilarArtists(context.dbSession, id.value, 5)}; auto transaction {context.dbSession.createSharedTransaction()}; @@ -1552,10 +1552,10 @@ handleUpdateUserRequest(RequestContext& context) if (password) { *password = decodePasswordIfNeeded(*password); - if (!ServiceProvider::get()->evaluatePasswordStrength(username, *password)) + if (!Service::get()->evaluatePasswordStrength(username, *password)) throw PasswordTooWeakGenericError {}; - hash = ServiceProvider::get()->hashPassword(*password); + hash = Service::get()->hashPassword(*password); } auto transaction {context.dbSession.createUniqueTransaction()}; @@ -1746,10 +1746,10 @@ handleGetCoverArt(RequestContext& context, const Wt::Http::Request& /*request*/, switch (id.type) { case Id::Type::Track: - data = ServiceProvider::get()->getFromTrack(context.dbSession, id.value, CoverArt::Format::JPEG, size); + data = Service::get()->getFromTrack(context.dbSession, id.value, CoverArt::Format::JPEG, size); break; case Id::Type::Release: - data = ServiceProvider::get()->getFromRelease(context.dbSession, id.value, CoverArt::Format::JPEG, size); + data = Service::get()->getFromRelease(context.dbSession, id.value, CoverArt::Format::JPEG, size); break; default: throw BadParameterGenericError {"id"}; @@ -1909,7 +1909,7 @@ SubsonicResource::handleRequest(const Wt::Http::Request &request, Wt::Http::Resp SessionPool::ScopedSession dbSession {_sessionPool}; - switch (ServiceProvider::get()->checkUserPassword(dbSession.get(), + switch (Service::get()->checkUserPassword(dbSession.get(), boost::asio::ip::address::from_string(request.clientAddress()), clientInfo.user, clientInfo.password)) { diff --git a/src/libs/utils/include/utils/Logger.hpp b/src/libs/utils/include/utils/Logger.hpp index 11789b17..430beb39 100644 --- a/src/libs/utils/include/utils/Logger.hpp +++ b/src/libs/utils/include/utils/Logger.hpp @@ -82,5 +82,5 @@ class Logger virtual void processLog(const Log& log) = 0; }; -#define LMS_LOG(module, severity) Log(ServiceProvider::get(), Module::module, Severity::severity).getOstream() +#define LMS_LOG(module, severity) Log(Service::get(), Module::module, Severity::severity).getOstream() diff --git a/src/libs/utils/include/utils/Service.hpp b/src/libs/utils/include/utils/Service.hpp index c53a8c81..95a44e37 100644 --- a/src/libs/utils/include/utils/Service.hpp +++ b/src/libs/utils/include/utils/Service.hpp @@ -19,46 +19,44 @@ #pragma once +#include #include -#include template -class ServiceProvider +class Service { public: - template - static - Class& - create(Args&&... args) + Service(std::unique_ptr service) { - static_assert(std::is_base_of::value); - - assign(std::make_unique(std::forward(args)...)); - return *get(); + assign(std::move(service)); } - template - static - Class& - create(Args&&... args) + ~Service() { - assign(std::make_unique(std::forward(args)...)); - return *get(); + clear(); } - static - Class& - assign(std::unique_ptr service) - { - _service = std::move(service); - return *get(); - } + Service(const Service&) = delete; + Service(Service&&) = delete; + Service& operator=(const Service&) = delete; + Service& operator=(Service&&) = delete; - static void clear() { _service.reset(); } + Class* operator->() const + { + return Service::get(); + } static Class* get() { return _service.get(); } private: + static Class& assign(std::unique_ptr service) + { + assert(!_service); + _service = std::move(service); + return *get(); + } + static void clear() { _service.reset(); } + static inline std::unique_ptr _service; }; diff --git a/src/lms/main.cpp b/src/lms/main.cpp index 51244cc1..c70f5ca3 100644 --- a/src/lms/main.cpp +++ b/src/lms/main.cpp @@ -42,31 +42,31 @@ generateWtConfig(std::string execPath) { std::vector args; - const std::filesystem::path wtConfigPath {ServiceProvider::get()->getPath("working-dir") / "wt_config.xml"}; - const std::filesystem::path wtLogFilePath {ServiceProvider::get()->getPath("log-file", "/var/log/lms.log")}; - const std::filesystem::path wtAccessLogFilePath {ServiceProvider::get()->getPath("access-log-file", "/var/log/lms.access.log")}; - const std::filesystem::path wtResourcesPath {ServiceProvider::get()->getPath("wt-resources", "/usr/share/Wt/resources")}; + const std::filesystem::path wtConfigPath {Service::get()->getPath("working-dir") / "wt_config.xml"}; + const std::filesystem::path wtLogFilePath {Service::get()->getPath("log-file", "/var/log/lms.log")}; + const std::filesystem::path wtAccessLogFilePath {Service::get()->getPath("access-log-file", "/var/log/lms.access.log")}; + const std::filesystem::path wtResourcesPath {Service::get()->getPath("wt-resources", "/usr/share/Wt/resources")}; args.push_back(execPath); args.push_back("--config=" + wtConfigPath.string()); - args.push_back("--docroot=" + ServiceProvider::get()->getString("docroot")); - args.push_back("--approot=" + ServiceProvider::get()->getString("approot")); - args.push_back("--deploy-path=" + ServiceProvider::get()->getString("deploy-path", "/")); + args.push_back("--docroot=" + Service::get()->getString("docroot")); + args.push_back("--approot=" + Service::get()->getString("approot")); + args.push_back("--deploy-path=" + Service::get()->getString("deploy-path", "/")); if (!wtResourcesPath.empty()) args.push_back("--resources-dir=" + wtResourcesPath.string()); - if (ServiceProvider::get()->getBool("tls-enable", false)) + if (Service::get()->getBool("tls-enable", false)) { - args.push_back("--https-port=" + std::to_string( ServiceProvider::get()->getULong("listen-port", 5082))); - args.push_back("--https-address=" + ServiceProvider::get()->getString("listen-addr", "0.0.0.0")); - args.push_back("--ssl-certificate=" + ServiceProvider::get()->getString("tls-cert")); - args.push_back("--ssl-private-key=" + ServiceProvider::get()->getString("tls-key")); - args.push_back("--ssl-tmp-dh=" + ServiceProvider::get()->getString("tls-dh")); + args.push_back("--https-port=" + std::to_string( Service::get()->getULong("listen-port", 5082))); + args.push_back("--https-address=" + Service::get()->getString("listen-addr", "0.0.0.0")); + args.push_back("--ssl-certificate=" + Service::get()->getString("tls-cert")); + args.push_back("--ssl-private-key=" + Service::get()->getString("tls-key")); + args.push_back("--ssl-tmp-dh=" + Service::get()->getString("tls-dh")); } else { - args.push_back("--http-port=" + std::to_string( ServiceProvider::get()->getULong("listen-port", 5082))); - args.push_back("--http-address=" + ServiceProvider::get()->getString("listen-addr", "0.0.0.0")); + args.push_back("--http-port=" + std::to_string( Service::get()->getULong("listen-port", 5082))); + args.push_back("--http-address=" + Service::get()->getString("listen-addr", "0.0.0.0")); } if (!wtAccessLogFilePath.empty()) @@ -77,8 +77,8 @@ generateWtConfig(std::string execPath) pt.put("server.application-settings..location", "*"); pt.put("server.application-settings.log-file", wtLogFilePath.string()); - pt.put("server.application-settings.log-config", ServiceProvider::get()->getString("log-config", "* -debug -info:WebRequest")); - pt.put("server.application-settings.behind-reverse-proxy", ServiceProvider::get()->getBool("behind-reverse-proxy", false)); + pt.put("server.application-settings.log-config", Service::get()->getString("log-config", "* -debug -info:WebRequest")); + pt.put("server.application-settings.behind-reverse-proxy", Service::get()->getBool("behind-reverse-proxy", false)); { boost::property_tree::ptree viewport; @@ -132,12 +132,12 @@ int main(int argc, char* argv[]) // Make pstream work with ffmpeg close(STDIN_FILENO); - ServiceProvider::assign(createConfig(configFilePath)); - ServiceProvider::create(); + Service config {createConfig(configFilePath)}; + Service logger {std::make_unique()}; // Make sure the working directory exists - std::filesystem::create_directories(ServiceProvider::get()->getPath("working-dir")); - std::filesystem::create_directories(ServiceProvider::get()->getPath("working-dir") / "cache"); + std::filesystem::create_directories(config->getPath("working-dir")); + std::filesystem::create_directories(config->getPath("working-dir") / "cache"); // Construct WT configuration and get the argc/argv back std::vector wtServerArgs = generateWtConfig(argv[0]); @@ -156,7 +156,7 @@ 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 {ServiceProvider::get()->getPath("working-dir") / "lms.db"}; + Database::Db database {config->getPath("working-dir") / "lms.db"}; { Database::Session session {database}; session.prepareTables(); @@ -166,22 +166,21 @@ int main(int argc, char* argv[]) UserInterface::LmsApplicationGroupContainer appGroups; // Service initialization order is important - ServiceProvider::assign(Auth::createAuthTokenService(ServiceProvider::get()->getULong("login-throttler-max-entriees", 10000))); - ServiceProvider::assign(Auth::createPasswordService(ServiceProvider::get()->getULong("login-throttler-max-entriees", 10000))); - Scanner::IMediaScanner& mediaScanner {ServiceProvider::assign(Scanner::createMediaScanner(database))}; + Service authTokenService {Auth::createAuthTokenService(config->getULong("login-throttler-max-entriees", 10000))}; + Service passwordService {Auth::createPasswordService(config->getULong("login-throttler-max-entriees", 10000))}; + Service coverArtService {CoverArt::createGrabber(argv[0])}; + coverArtService->setDefaultCover(server.appRoot() + "/images/unknown-cover.jpg"); + Service recommendationEngineService {Recommendation::createEngine(database)}; + Service mediaScannerService {Scanner::createMediaScanner(database)}; - Recommendation::IEngine& recommendationEngine {ServiceProvider::assign(Recommendation::createEngine(database))}; - CoverArt::IGrabber& coverArtGrabber {ServiceProvider::assign(CoverArt::createGrabber(argv[0]))}; - coverArtGrabber.setDefaultCover(server.appRoot() + "/images/unknown-cover.jpg"); - - mediaScanner.scanComplete().connect([&]() + mediaScannerService->scanComplete().connect([&]() { - auto status = mediaScanner.getStatus(); + auto status = mediaScannerService->getStatus(); if (status.lastCompleteScanStats->nbChanges() > 0 || status.lastCompleteScanStats->featuresFetched > 0) { LMS_LOG(MAIN, INFO) << "Scanner changed some files, reloading the recommendation engine..."; - recommendationEngine.requestReload(); + recommendationEngineService->requestReload(); } else { @@ -189,13 +188,13 @@ int main(int argc, char* argv[]) } // Flush cover cache even if no changes: // covers may be external files that changed and we don't keep track of them - coverArtGrabber.flushCache(); + coverArtService->flushCache(); }); API::Subsonic::SubsonicResource subsonicResource {database}; // bind API resources - if (ServiceProvider::get()->getBool("api-subsonic", true)) + if (config->getBool("api-subsonic", true)) server.addResource(&subsonicResource, subsonicResource.getPath()); // bind UI entry point @@ -203,32 +202,15 @@ int main(int argc, char* argv[]) std::bind(UserInterface::LmsApplication::create, std::placeholders::_1, std::ref(database), std::ref(appGroups))); - // Start - LMS_LOG(MAIN, INFO) << "Starting recommendation engine"; - recommendationEngine.start(); - - LMS_LOG(MAIN, INFO) << "Starting media scanner..."; - mediaScanner.start(); - LMS_LOG(MAIN, INFO) << "Starting server..."; server.start(); - // Wait LMS_LOG(MAIN, INFO) << "Now running..."; Wt::WServer::waitForShutdown(); - // Stop LMS_LOG(MAIN, INFO) << "Stopping server..."; server.stop(); - LMS_LOG(MAIN, INFO) << "Stopping media scanner..."; - mediaScanner.stop(); - - LMS_LOG(MAIN, INFO) << "Stopping recommendation engine..."; - recommendationEngine.stop(); - - ServiceProvider::clear(); - LMS_LOG(MAIN, INFO) << "Clean stop!"; res = EXIT_SUCCESS; } diff --git a/src/lms/ui/Auth.cpp b/src/lms/ui/Auth.cpp index cae9ee16..e3cab312 100644 --- a/src/lms/ui/Auth.cpp +++ b/src/lms/ui/Auth.cpp @@ -43,7 +43,7 @@ static void createAuthToken(Database::IdType userId, const Wt::WDateTime& expiry) { - const std::string secret {ServiceProvider<::Auth::IAuthTokenService>::get()->createAuthToken(LmsApp->getDbSession(), userId, expiry)}; + const std::string secret {Service<::Auth::IAuthTokenService>::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 {ServiceProvider<::Auth::IAuthTokenService>::get()->processAuthToken(LmsApp->getDbSession(), boost::asio::ip::address::from_string(env.clientAddress()), *authCookie)}; + const auto res {Service<::Auth::IAuthTokenService>::get()->processAuthToken(LmsApp->getDbSession(), boost::asio::ip::address::from_string(env.clientAddress()), *authCookie)}; switch (res.state) { case ::Auth::IAuthTokenService::AuthTokenProcessResult::State::NotFound: @@ -124,7 +124,7 @@ class AuthModel : public Wt::WFormModel if (field == PasswordField) { - switch (ServiceProvider<::Auth::IPasswordService>::get()->checkUserPassword( + switch (Service<::Auth::IPasswordService>::get()->checkUserPassword( LmsApp->getDbSession(), boost::asio::ip::address::from_string(LmsApp->environment().clientAddress()), valueText(LoginNameField).toUTF8(), diff --git a/src/lms/ui/LmsApplication.cpp b/src/lms/ui/LmsApplication.cpp index de5ad4c3..adeb8ce7 100644 --- a/src/lms/ui/LmsApplication.cpp +++ b/src/lms/ui/LmsApplication.cpp @@ -530,7 +530,7 @@ LmsApplication::createHome() { const std::string sessionId {LmsApp->sessionId()}; - ServiceProvider::get()->scanStarted().connect(this, [=] () + Service::get()->scanStarted().connect(this, [=] () { Wt::WServer::instance()->post(sessionId, [=] { @@ -539,7 +539,7 @@ LmsApplication::createHome() }); }); - ServiceProvider::get()->scanComplete().connect(this, [=] () + Service::get()->scanComplete().connect(this, [=] () { Wt::WServer::instance()->post(sessionId, [=] { @@ -548,7 +548,7 @@ LmsApplication::createHome() }); }); - ServiceProvider::get()->scanInProgress().connect(this, [=] (Scanner::ScanStepStats stepStats) + Service::get()->scanInProgress().connect(this, [=] (Scanner::ScanStepStats stepStats) { Wt::WServer::instance()->post(sessionId, [=] { @@ -557,7 +557,7 @@ LmsApplication::createHome() }); }); - ServiceProvider::get()->scheduled().connect(this, [=] (Wt::WDateTime dateTime) + Service::get()->scheduled().connect(this, [=] (Wt::WDateTime dateTime) { Wt::WServer::instance()->post(sessionId, [=] { @@ -572,7 +572,7 @@ LmsApplication::createHome() { if (isUserAdmin()) { - const auto& stats {*ServiceProvider::get()->getStatus().lastCompleteScanStats}; + const auto& stats {*Service::get()->getStatus().lastCompleteScanStats}; notifyMsg(MsgType::Info, Wt::WString::tr("Lms.Admin.Database.scan-complete") .arg(static_cast(stats.nbFiles())) diff --git a/src/lms/ui/PlayQueue.cpp b/src/lms/ui/PlayQueue.cpp index ab3d06da..6d5f3765 100644 --- a/src/lms/ui/PlayQueue.cpp +++ b/src/lms/ui/PlayQueue.cpp @@ -500,7 +500,7 @@ PlayQueue::addSome() void PlayQueue::enqueueRadioTrack() { - const std::vector trackToAddIds {ServiceProvider::get()->getSimilarTracksFromTrackList(LmsApp->getDbSession(), _tracklistId, 1)}; + const std::vector trackToAddIds {Service::get()->getSimilarTracksFromTrackList(LmsApp->getDbSession(), _tracklistId, 1)}; enqueueTracks(trackToAddIds); } diff --git a/src/lms/ui/SettingsView.cpp b/src/lms/ui/SettingsView.cpp index 33cfd766..ebecb3d9 100644 --- a/src/lms/ui/SettingsView.cpp +++ b/src/lms/ui/SettingsView.cpp @@ -120,7 +120,7 @@ class SettingsModel : public Wt::WFormModel User::PasswordHash passwordHash; if (!valueText(PasswordField).empty()) - passwordHash = ServiceProvider<::Auth::IPasswordService>::get()->hashPassword(valueText(PasswordField).toUTF8()); + passwordHash = Service<::Auth::IPasswordService>::get()->hashPassword(valueText(PasswordField).toUTF8()); auto transaction {LmsApp->getDbSession().createUniqueTransaction()}; @@ -243,7 +243,7 @@ class SettingsModel : public Wt::WFormModel { if (!valueText(PasswordOldField).empty()) { - switch (ServiceProvider<::Auth::IPasswordService>::get()->checkUserPassword( + switch (Service<::Auth::IPasswordService>::get()->checkUserPassword( LmsApp->getDbSession(), boost::asio::ip::address::from_string(LmsApp->environment().clientAddress()), LmsApp->getUserLoginName(), @@ -271,7 +271,7 @@ class SettingsModel : public Wt::WFormModel { if (!valueText(PasswordField).empty()) { - if (!ServiceProvider<::Auth::IPasswordService>::get()->evaluatePasswordStrength(LmsApp->getUserLoginName(), valueText(PasswordField).toUTF8())) + if (!Service<::Auth::IPasswordService>::get()->evaluatePasswordStrength(LmsApp->getUserLoginName(), valueText(PasswordField).toUTF8())) error = Wt::WString::tr("Lms.password-too-weak"); } else @@ -468,7 +468,7 @@ SettingsView::refreshView() // Subsonic { - t->setCondition("if-has-subsonic-api", ServiceProvider::get()->getBool("api-subsonic", true)); + t->setCondition("if-has-subsonic-api", Service::get()->getBool("api-subsonic", true)); // Transcode auto transcode {std::make_unique()}; diff --git a/src/lms/ui/admin/DatabaseSettingsView.cpp b/src/lms/ui/admin/DatabaseSettingsView.cpp index 3b734728..34ed61a2 100644 --- a/src/lms/ui/admin/DatabaseSettingsView.cpp +++ b/src/lms/ui/admin/DatabaseSettingsView.cpp @@ -230,7 +230,7 @@ DatabaseSettingsView::refreshView() { model->saveData(); - ServiceProvider::get()->requestReload(); + Service::get()->requestReload(); LmsApp->notifyMsg(MsgType::Success, Wt::WString::tr("Lms.Admin.Database.settings-saved")); } @@ -247,7 +247,7 @@ DatabaseSettingsView::refreshView() immScanBtn->clicked().connect([=] () { - ServiceProvider::get()->requestImmediateScan(false); + Service::get()->requestImmediateScan(false); }); t->updateView(model.get()); diff --git a/src/lms/ui/admin/InitWizardView.cpp b/src/lms/ui/admin/InitWizardView.cpp index a14a386e..bbec809c 100644 --- a/src/lms/ui/admin/InitWizardView.cpp +++ b/src/lms/ui/admin/InitWizardView.cpp @@ -62,7 +62,7 @@ class InitWizardModel : public Wt::WFormModel void saveData() { - const Database::User::PasswordHash passwordHash {ServiceProvider<::Auth::IPasswordService>::get()->hashPassword(valueText(PasswordField).toUTF8())}; + const Database::User::PasswordHash passwordHash {Service<::Auth::IPasswordService>::get()->hashPassword(valueText(PasswordField).toUTF8())}; auto transaction(LmsApp->getDbSession().createUniqueTransaction()); @@ -97,7 +97,7 @@ class InitWizardModel : public Wt::WFormModel if (!valueText(PasswordField).empty()) { // Evaluate the strength of the password - if (!ServiceProvider<::Auth::IPasswordService>::get()->evaluatePasswordStrength(valueText(AdminLoginField).toUTF8(), valueText(PasswordField).toUTF8())) + if (!Service<::Auth::IPasswordService>::get()->evaluatePasswordStrength(valueText(AdminLoginField).toUTF8(), valueText(PasswordField).toUTF8())) error = Wt::WString::tr("Lms.password-too-weak"); } else diff --git a/src/lms/ui/admin/ScannerController.cpp b/src/lms/ui/admin/ScannerController.cpp index 2e971064..f6193b98 100644 --- a/src/lms/ui/admin/ScannerController.cpp +++ b/src/lms/ui/admin/ScannerController.cpp @@ -146,20 +146,20 @@ ScannerController::refreshContents() actionBtn->actionButton()->setText(Wt::WString::tr("Lms.Admin.ScannerController.scan-now")); actionBtn->actionButton()->clicked().connect([] { - ServiceProvider::get()->requestImmediateScan(false); + Service::get()->requestImmediateScan(false); }); auto popup = std::make_unique(); popup->addItem(Wt::WString::tr("Lms.Admin.ScannerController.force-scan-now")); popup->itemSelected().connect([] { - ServiceProvider::get()->requestImmediateScan(true); + Service::get()->requestImmediateScan(true); }); actionBtn->dropDownButton()->setMenu(std::move(popup)); actionBtn->dropDownButton()->addStyleClass("btn-primary"); - const IMediaScanner::Status status {ServiceProvider::get()->getStatus()}; + const IMediaScanner::Status status {Service::get()->getStatus()}; if (status.lastCompleteScanStats) { bindString("last-scan", Wt::WString::tr("Lms.Admin.ScannerController.last-scan-status") diff --git a/src/lms/ui/admin/UserView.cpp b/src/lms/ui/admin/UserView.cpp index 5255cd60..63c118e3 100644 --- a/src/lms/ui/admin/UserView.cpp +++ b/src/lms/ui/admin/UserView.cpp @@ -80,7 +80,7 @@ class UserModel : public Wt::WFormModel { std::optional passwordHash; if (!valueText(PasswordField).empty()) - passwordHash = ServiceProvider<::Auth::IPasswordService>::get()->hashPassword(valueText(PasswordField).toUTF8()); + passwordHash = Service<::Auth::IPasswordService>::get()->hashPassword(valueText(PasswordField).toUTF8()); auto transaction {LmsApp->getDbSession().createUniqueTransaction()}; @@ -143,7 +143,7 @@ class UserModel : public Wt::WFormModel else { // Evaluate the strength of the password for non demo accounts - if (!ServiceProvider<::Auth::IPasswordService>::get()->evaluatePasswordStrength(getLoginName(), valueText(PasswordField).toUTF8())) + if (!Service<::Auth::IPasswordService>::get()->evaluatePasswordStrength(getLoginName(), valueText(PasswordField).toUTF8())) error = Wt::WString::tr("Lms.password-too-weak"); } } @@ -304,7 +304,7 @@ UserView::refreshView() // Demo account t->setFormWidget(UserModel::DemoField, std::make_unique()); - if (!userId && ServiceProvider::get()->getBool("demo", false)) + if (!userId && Service::get()->getBool("demo", false)) t->setCondition("if-demo", true); Wt::WPushButton* saveBtn = t->bindNew("save-btn", Wt::WString::tr(userId ? "Lms.save" : "Lms.create")); diff --git a/src/lms/ui/common/AuthModeModel.cpp b/src/lms/ui/common/AuthModeModel.cpp index 1a74b440..e96b6daa 100644 --- a/src/lms/ui/common/AuthModeModel.cpp +++ b/src/lms/ui/common/AuthModeModel.cpp @@ -30,9 +30,9 @@ createAuthModeModel() { auto model {std::make_unique()}; - if (ServiceProvider<::Auth::IPasswordService>::get()->isAuthModeSupported(Database::User::AuthMode::Internal)) + if (Service<::Auth::IPasswordService>::get()->isAuthModeSupported(Database::User::AuthMode::Internal)) model->add(Wt::WString::tr("Lms.Admin.User.auth-mode.internal"), Database::User::AuthMode::Internal); - if (ServiceProvider<::Auth::IPasswordService>::get()->isAuthModeSupported(Database::User::AuthMode::PAM)) + if (Service<::Auth::IPasswordService>::get()->isAuthModeSupported(Database::User::AuthMode::PAM)) model->add(Wt::WString::tr("Lms.Admin.User.auth-mode.pam"), Database::User::AuthMode::PAM); return model; diff --git a/src/lms/ui/explore/ArtistView.cpp b/src/lms/ui/explore/ArtistView.cpp index 082f0634..4f86b4a0 100644 --- a/src/lms/ui/explore/ArtistView.cpp +++ b/src/lms/ui/explore/ArtistView.cpp @@ -73,7 +73,7 @@ Artist::refreshView() if (!artistId) return; - const std::vector similarArtistIds {ServiceProvider::get()->getSimilarArtists(LmsApp->getDbSession(), *artistId, 5)}; + const std::vector similarArtistIds {Service::get()->getSimilarArtists(LmsApp->getDbSession(), *artistId, 5)}; auto transaction {LmsApp->getDbSession().createSharedTransaction()}; diff --git a/src/lms/ui/explore/ReleaseView.cpp b/src/lms/ui/explore/ReleaseView.cpp index aa2d4350..4c9d10b7 100644 --- a/src/lms/ui/explore/ReleaseView.cpp +++ b/src/lms/ui/explore/ReleaseView.cpp @@ -76,7 +76,7 @@ Release::refreshView() if (!releaseId) return; - const std::vector similarReleasesIds {ServiceProvider::get()->getSimilarReleases(LmsApp->getDbSession(), *releaseId, 6)}; + const std::vector similarReleasesIds {Service::get()->getSimilarReleases(LmsApp->getDbSession(), *releaseId, 6)}; auto transaction {LmsApp->getDbSession().createSharedTransaction()}; diff --git a/src/lms/ui/resource/ImageResource.cpp b/src/lms/ui/resource/ImageResource.cpp index 37adb781..a99e7317 100644 --- a/src/lms/ui/resource/ImageResource.cpp +++ b/src/lms/ui/resource/ImageResource.cpp @@ -90,7 +90,7 @@ ImageResource::handleRequest(const Wt::Http::Request& request, Wt::Http::Respons // DbSession are not thread safe { Wt::WApplication::UpdateLock lock {LmsApp}; - cover = ServiceProvider::get()->getFromTrack(LmsApp->getDbSession(), *trackId, CoverArt::Format::JPEG, *size); + cover = Service::get()->getFromTrack(LmsApp->getDbSession(), *trackId, CoverArt::Format::JPEG, *size); } } else if (releaseIdStr) @@ -104,7 +104,7 @@ ImageResource::handleRequest(const Wt::Http::Request& request, Wt::Http::Respons // DbSession are not thread safe { Wt::WApplication::UpdateLock lock {LmsApp}; - cover = ServiceProvider::get()->getFromRelease(LmsApp->getDbSession(), *releaseId, CoverArt::Format::JPEG, *size); + cover = Service::get()->getFromRelease(LmsApp->getDbSession(), *releaseId, CoverArt::Format::JPEG, *size); } } else diff --git a/src/test/database/DatabaseTest.cpp b/src/test/database/DatabaseTest.cpp index c96a625d..8da1ecf6 100644 --- a/src/test/database/DatabaseTest.cpp +++ b/src/test/database/DatabaseTest.cpp @@ -1882,7 +1882,7 @@ int main() try { // log to stdout - ServiceProvider::create(std::cout); + Service logger {std::make_unique(std::cout)}; const std::filesystem::path tmpFile {std::tmpnam(nullptr)}; ScopedFileDeleter tmpFileDeleter {tmpFile}; diff --git a/src/tools/metadata/LmsMetadata.cpp b/src/tools/metadata/LmsMetadata.cpp index 24071070..963d44b0 100644 --- a/src/tools/metadata/LmsMetadata.cpp +++ b/src/tools/metadata/LmsMetadata.cpp @@ -156,7 +156,7 @@ int main(int argc, char *argv[]) try { // log to stdout - ServiceProvider::create(std::cout); + Service logger {std::make_unique(std::cout)}; for (std::size_t i {}; i < static_cast(argc - 1); ++i) { diff --git a/src/tools/recommendation/LmsRecommendation.cpp b/src/tools/recommendation/LmsRecommendation.cpp index dd8a017c..ecb625f8 100644 --- a/src/tools/recommendation/LmsRecommendation.cpp +++ b/src/tools/recommendation/LmsRecommendation.cpp @@ -131,15 +131,15 @@ int main(int argc, char *argv[]) try { // log to stdout - ServiceProvider::create(std::cout); + Service logger {std::make_unique(std::cout)}; std::filesystem::path configFilePath {"/etc/lms.conf"}; if (argc >= 2) configFilePath = std::string(argv[1], 0, 256); - ServiceProvider::assign(createConfig(configFilePath)); + Service config {createConfig(configFilePath)}; - Database::Db db {ServiceProvider::get()->getPath("working-dir") / "lms.db"}; + Database::Db db {config->getPath("working-dir") / "lms.db"}; Database::Session session {db}; std::cout << "Creating recommendation engine..." << std::endl;