Various minor cleanup

This commit is contained in:
emeric
2024-12-05 20:09:14 +01:00
parent 76b9c1fe10
commit 45175a721c
35 changed files with 104 additions and 137 deletions
+4 -3
View File
@@ -25,9 +25,10 @@
#include "core/IChildProcessManager.hpp" #include "core/IChildProcessManager.hpp"
#include "core/IConfig.hpp" #include "core/IConfig.hpp"
#include "core/ILogger.hpp" #include "core/ILogger.hpp"
#include "core/Path.hpp"
#include "core/Service.hpp" #include "core/Service.hpp"
#include "av/Types.hpp"
namespace lms::av::transcoding namespace lms::av::transcoding
{ {
@@ -81,7 +82,7 @@ namespace lms::av::transcoding
{ {
if (!std::filesystem::exists(_inputParameters.trackPath)) if (!std::filesystem::exists(_inputParameters.trackPath))
throw Exception{ "File '" + _inputParameters.trackPath.string() + "' does not exist!" }; throw Exception{ "File '" + _inputParameters.trackPath.string() + "' does not exist!" };
else if (!std::filesystem::is_regular_file(_inputParameters.trackPath)) if (!std::filesystem::is_regular_file(_inputParameters.trackPath))
throw Exception{ "File '" + _inputParameters.trackPath.string() + "' is not regular!" }; throw Exception{ "File '" + _inputParameters.trackPath.string() + "' is not regular!" };
} }
catch (const std::filesystem::filesystem_error& e) catch (const std::filesystem::filesystem_error& e)
@@ -108,7 +109,7 @@ namespace lms::av::transcoding
args.emplace_back("-ss"); args.emplace_back("-ss");
std::ostringstream oss; std::ostringstream oss;
oss << std::fixed << std::showpoint << std::setprecision(3) << (_outputParameters.offset.count() / float{ 1000 }); oss << std::fixed << std::showpoint << std::setprecision(3) << (_outputParameters.offset.count() / float{ 1'000 });
args.emplace_back(oss.str()); args.emplace_back(oss.str());
} }
-3
View File
@@ -19,11 +19,9 @@
#pragma once #pragma once
#include <filesystem>
#include <functional> #include <functional>
#include "av/TranscodingParameters.hpp" #include "av/TranscodingParameters.hpp"
#include "av/Types.hpp"
namespace lms::core namespace lms::core
{ {
@@ -37,7 +35,6 @@ namespace lms::av::transcoding
public: public:
Transcoder(const InputParameters& inputParameters, const OutputParameters& outputParameters); Transcoder(const InputParameters& inputParameters, const OutputParameters& outputParameters);
~Transcoder(); ~Transcoder();
Transcoder(const Transcoder&) = delete; Transcoder(const Transcoder&) = delete;
Transcoder& operator=(const Transcoder&) = delete; Transcoder& operator=(const Transcoder&) = delete;
Transcoder(Transcoder&&) = delete; Transcoder(Transcoder&&) = delete;
+11 -13
View File
@@ -59,7 +59,7 @@ namespace lms::av::transcoding
{ {
LMS_LOG(TRANSCODING, DEBUG, "Writing " << _bytesReadyCount << " bytes back to client"); LMS_LOG(TRANSCODING, DEBUG, "Writing " << _bytesReadyCount << " bytes back to client");
response.out().write(reinterpret_cast<const char*>(&_buffer[0]), _bytesReadyCount); response.out().write(reinterpret_cast<const char*>(_buffer.data()), _bytesReadyCount);
_totalServedByteCount += _bytesReadyCount; _totalServedByteCount += _bytesReadyCount;
_bytesReadyCount = 0; _bytesReadyCount = 0;
} }
@@ -78,24 +78,22 @@ namespace lms::av::transcoding
return continuation; return continuation;
} }
else
// pad with 0 if necessary as duration may not be accurate
if (_estimatedContentLength && *_estimatedContentLength > _totalServedByteCount)
{ {
// pad with 0 if necessary as duration may not be accurate const std::size_t padSize{ *_estimatedContentLength - _totalServedByteCount };
if (_estimatedContentLength && *_estimatedContentLength > _totalServedByteCount)
{
const std::size_t padSize{ *_estimatedContentLength - _totalServedByteCount };
LMS_LOG(TRANSCODING, DEBUG, "Adding " << padSize << " padding bytes"); LMS_LOG(TRANSCODING, DEBUG, "Adding " << padSize << " padding bytes");
for (std::size_t i{}; i < padSize; ++i) for (std::size_t i{}; i < padSize; ++i)
response.out().put(0); response.out().put(0);
_totalServedByteCount += padSize; _totalServedByteCount += padSize;
}
LMS_LOG(TRANSCODING, DEBUG, "Transcoding finished. Total served byte count = " << _totalServedByteCount);
} }
LMS_LOG(TRANSCODING, DEBUG, "Transcoding finished. Total served byte count = " << _totalServedByteCount);
return {}; return {};
} }
} // namespace lms::av::transcoding } // namespace lms::av::transcoding
@@ -20,7 +20,6 @@
#pragma once #pragma once
#include <array> #include <array>
#include <filesystem>
#include <optional> #include <optional>
#include "av/TranscodingParameters.hpp" #include "av/TranscodingParameters.hpp"
@@ -34,9 +33,13 @@ namespace lms::av::transcoding
{ {
public: public:
TranscodingResourceHandler(const InputParameters& inputParameters, const OutputParameters& outputParameters, bool estimateContentLength); TranscodingResourceHandler(const InputParameters& inputParameters, const OutputParameters& outputParameters, bool estimateContentLength);
~TranscodingResourceHandler() override = default;
TranscodingResourceHandler(const TranscodingResourceHandler&) = delete;
TranscodingResourceHandler& operator=(const TranscodingResourceHandler&) = delete;
private: private:
Wt::Http::ResponseContinuation* processRequest(const Wt::Http::Request& request, Wt::Http::Response& reponse) override; Wt::Http::ResponseContinuation* processRequest(const Wt::Http::Request& request, Wt::Http::Response& response) override;
void abort() override{}; void abort() override{};
static constexpr std::size_t _chunkSize{ 262'144 }; static constexpr std::size_t _chunkSize{ 262'144 };
@@ -23,8 +23,6 @@
#include <filesystem> #include <filesystem>
#include <optional> #include <optional>
#include "Types.hpp"
namespace lms::av::transcoding namespace lms::av::transcoding
{ {
struct InputParameters struct InputParameters
@@ -47,7 +45,7 @@ namespace lms::av::transcoding
struct OutputParameters struct OutputParameters
{ {
OutputFormat format; OutputFormat format;
std::size_t bitrate{ 128000 }; std::size_t bitrate{ 128'000 };
std::optional<std::size_t> stream; // Id of the stream to be transcoded (auto detect by default) std::optional<std::size_t> stream; // Id of the stream to be transcoded (auto detect by default)
std::chrono::milliseconds offset{ 0 }; std::chrono::milliseconds offset{ 0 };
bool stripMetadata{ true }; bool stripMetadata{ true };
+2 -2
View File
@@ -29,8 +29,8 @@
namespace lms::core namespace lms::core
{ {
// The trace logger is meant to built/destroyed once // The trace logger is meant to built/destroyed once
Service<logging::ILogger> logger{ std::make_unique<logging::StreamLogger>(std::cout, logging::StreamLogger::allSeverities) }; const Service<logging::ILogger> logger{ std::make_unique<logging::StreamLogger>(std::cout, logging::StreamLogger::allSeverities) };
Service<tracing::ITraceLogger> traceLogger{ tracing::createTraceLogger(tracing::Level::Overview) }; const Service<tracing::ITraceLogger> traceLogger{ tracing::createTraceLogger(tracing::Level::Overview) };
static void BM_TraceLogger_Overview(benchmark::State& state) static void BM_TraceLogger_Overview(benchmark::State& state)
{ {
+8 -8
View File
@@ -217,14 +217,14 @@ namespace lms::zip
if (!std::filesystem::is_regular_file(entry.filePath)) if (!std::filesystem::is_regular_file(entry.filePath))
throw FileException{ entry.filePath, "not a regular file" }; throw FileException{ entry.filePath, "not a regular file" };
ArchiveEntryPtr archiveEntry{ archive_entry_new() }; ArchiveEntryPtr archiveEntry{ ::archive_entry_new() };
if (!archiveEntry) if (!archiveEntry)
throw Exception{ "Cannot create archive entry control struct" }; throw Exception{ "Cannot create archive entry control struct" };
archive_entry_set_pathname(archiveEntry.get(), entry.fileName.c_str()); ::archive_entry_set_pathname(archiveEntry.get(), entry.fileName.c_str());
archive_entry_set_size(archiveEntry.get(), std::filesystem::file_size(entry.filePath)); ::archive_entry_set_size(archiveEntry.get(), std::filesystem::file_size(entry.filePath));
archive_entry_set_mode(archiveEntry.get(), permsToMode(std::filesystem::status(entry.filePath).permissions())); ::archive_entry_set_mode(archiveEntry.get(), permsToMode(std::filesystem::status(entry.filePath).permissions()));
archive_entry_set_filetype(archiveEntry.get(), AE_IFREG); ::archive_entry_set_filetype(archiveEntry.get(), AE_IFREG);
return archiveEntry; return archiveEntry;
} }
@@ -256,7 +256,7 @@ namespace lms::zip
if (!ifs.seekg(_currentEntryOffset, std::ios::beg)) if (!ifs.seekg(_currentEntryOffset, std::ios::beg))
throw FileException{ _currentEntry->filePath, "seek failed", errno }; throw FileException{ _currentEntry->filePath, "seek failed", errno };
if (!ifs.read(reinterpret_cast<char*>(&_readBuffer[0]), bytesToRead)) if (!ifs.read(reinterpret_cast<char*>(_readBuffer.data()), bytesToRead))
throw FileException{ _currentEntry->filePath, "read failed", errno }; throw FileException{ _currentEntry->filePath, "read failed", errno };
const std::uint64_t actualBytesRead{ static_cast<std::uint64_t>(ifs.gcount()) }; const std::uint64_t actualBytesRead{ static_cast<std::uint64_t>(ifs.gcount()) };
@@ -266,7 +266,7 @@ namespace lms::zip
std::uint64_t remainingBytesToWrite{ actualBytesRead }; std::uint64_t remainingBytesToWrite{ actualBytesRead };
while (remainingBytesToWrite > 0) while (remainingBytesToWrite > 0)
{ {
const auto writtenBytes{ archive_write_data(_archive.get(), &_readBuffer[actualBytesRead - remainingBytesToWrite], remainingBytesToWrite) }; const auto writtenBytes{ ::archive_write_data(_archive.get(), &_readBuffer[actualBytesRead - remainingBytesToWrite], remainingBytesToWrite) };
if (writtenBytes < 0) if (writtenBytes < 0)
throw ArchiveException{ _archive.get() }; throw ArchiveException{ _archive.get() };
@@ -283,7 +283,7 @@ namespace lms::zip
{ {
if (!_currentOutputStream) if (!_currentOutputStream)
{ {
archive_set_error(_archive.get(), EIO, "IO error: operation cancelled"); ::archive_set_error(_archive.get(), EIO, "IO error: operation cancelled");
return -1; return -1;
} }
+2 -1
View File
@@ -35,7 +35,8 @@ namespace lms::zip
class ArchiveZipper : public IZipper class ArchiveZipper : public IZipper
{ {
public: public:
ArchiveZipper(const EntryContainer& files); ArchiveZipper(const EntryContainer& entries);
~ArchiveZipper() = default;
ArchiveZipper(const ArchiveZipper&) = delete; ArchiveZipper(const ArchiveZipper&) = delete;
ArchiveZipper& operator=(const ArchiveZipper&) = delete; ArchiveZipper& operator=(const ArchiveZipper&) = delete;
+4 -1
View File
@@ -36,8 +36,11 @@ namespace lms::core
class ChildProcess : public IChildProcess class ChildProcess : public IChildProcess
{ {
public: public:
~ChildProcess();
ChildProcess(boost::asio::io_context& ioContext, const std::filesystem::path& path, const Args& args); ChildProcess(boost::asio::io_context& ioContext, const std::filesystem::path& path, const Args& args);
~ChildProcess() override;
ChildProcess(const ChildProcess&) = delete;
ChildProcess& operator=(const ChildProcess&) = delete;
private: private:
void asyncRead(std::byte* data, std::size_t bufferSize, ReadCallback callback) override; void asyncRead(std::byte* data, std::size_t bufferSize, ReadCallback callback) override;
+1 -2
View File
@@ -20,7 +20,6 @@
#pragma once #pragma once
#include <memory> #include <memory>
#include <thread>
#include <boost/asio/io_context.hpp> #include <boost/asio/io_context.hpp>
@@ -32,7 +31,7 @@ namespace lms::core
{ {
public: public:
ChildProcessManager(boost::asio::io_context& ioContext); ChildProcessManager(boost::asio::io_context& ioContext);
~ChildProcessManager() = default; ~ChildProcessManager() override = default;
ChildProcessManager(const ChildProcessManager&) = delete; ChildProcessManager(const ChildProcessManager&) = delete;
ChildProcessManager(ChildProcessManager&&) = delete; ChildProcessManager(ChildProcessManager&&) = delete;
-1
View File
@@ -20,7 +20,6 @@
#include "Config.hpp" #include "Config.hpp"
#include "core/Exception.hpp" #include "core/Exception.hpp"
#include "core/ILogger.hpp"
namespace lms::core namespace lms::core
{ {
+2 -2
View File
@@ -29,13 +29,14 @@ namespace lms::core
{ {
public: public:
Config(const std::filesystem::path& p); Config(const std::filesystem::path& p);
~Config() = default; ~Config() override = default;
Config(const Config&) = delete; Config(const Config&) = delete;
Config& operator=(const Config&) = delete; Config& operator=(const Config&) = delete;
Config(Config&&) = delete; Config(Config&&) = delete;
Config& operator=(Config&&) = delete; Config& operator=(Config&&) = delete;
private:
// Default values are returned in case of setting not found // Default values are returned in case of setting not found
std::string_view getString(std::string_view setting, std::string_view def = "") override; std::string_view getString(std::string_view setting, std::string_view def = "") override;
void visitStrings(std::string_view setting, std::function<void(std::string_view)> _func, std::initializer_list<std::string_view> defs) override; void visitStrings(std::string_view setting, std::function<void(std::string_view)> _func, std::initializer_list<std::string_view> defs) override;
@@ -44,7 +45,6 @@ namespace lms::core
long getLong(std::string_view setting, long def = 0) override; long getLong(std::string_view setting, long def = 0) override;
bool getBool(std::string_view setting, bool def = false) override; bool getBool(std::string_view setting, bool def = false) override;
private:
libconfig::Config _config; libconfig::Config _config;
}; };
} // namespace lms::core } // namespace lms::core
+3 -1
View File
@@ -44,6 +44,8 @@ namespace lms::core::tracing
private: private:
CurrentThreadUnregisterer(const CurrentThreadUnregisterer&) = delete; CurrentThreadUnregisterer(const CurrentThreadUnregisterer&) = delete;
CurrentThreadUnregisterer& operator=(const CurrentThreadUnregisterer&) = delete; CurrentThreadUnregisterer& operator=(const CurrentThreadUnregisterer&) = delete;
CurrentThreadUnregisterer(CurrentThreadUnregisterer&&) = delete;
CurrentThreadUnregisterer& operator=(CurrentThreadUnregisterer&&) = delete;
TraceLogger* _logger; TraceLogger* _logger;
}; };
@@ -295,7 +297,7 @@ namespace lms::core::tracing
oss << threadId; oss << threadId;
std::istringstream iss{ oss.str() }; std::istringstream iss{ oss.str() };
std::uint64_t id; std::uint64_t id{};
iss >> id; iss >> id;
return static_cast<std::uint32_t>(id); return static_cast<std::uint32_t>(id);
+1 -1
View File
@@ -167,7 +167,7 @@ namespace lms::core::stringUtils::tests
std::string expectedOutput; std::string expectedOutput;
}; };
TestCase tests[]{ const TestCase tests[]{
{ { "" }, ';', '\\', "" }, { { "" }, ';', '\\', "" },
{ { ";" }, ';', '\\', "\\;" }, { { ";" }, ';', '\\', "\\;" },
{ { ";;" }, ';', '\\', "\\;\\;" }, { { ";;" }, ';', '\\', "\\;\\;" },
+6 -6
View File
@@ -29,7 +29,6 @@
#include "database/Track.hpp" #include "database/Track.hpp"
#include "database/User.hpp" #include "database/User.hpp"
#include "EnumSetTraits.hpp"
#include "IdTypeTraits.hpp" #include "IdTypeTraits.hpp"
#include "SqlQuery.hpp" #include "SqlQuery.hpp"
#include "Utils.hpp" #include "Utils.hpp"
@@ -182,16 +181,16 @@ namespace lms::db
} }
} // namespace } // namespace
Artist::Artist(const std::string& name, const std::optional<core::UUID>& MBID) Artist::Artist(const std::string& name, const std::optional<core::UUID>& mbid)
: _MBID{ MBID ? MBID->getAsString() : "" } : _mbid{ mbid ? mbid->getAsString() : "" }
{ {
setName(name); setName(name);
_sortName = _name; _sortName = _name;
} }
Artist::pointer Artist::create(Session& session, const std::string& name, const std::optional<core::UUID>& MBID) Artist::pointer Artist::create(Session& session, const std::string& name, const std::optional<core::UUID>& mbid)
{ {
return session.getDboSession()->add(std::unique_ptr<Artist>{ new Artist{ name, MBID } }); return session.getDboSession()->add(std::unique_ptr<Artist>{ new Artist{ name, mbid } });
} }
std::size_t Artist::getCount(Session& session) std::size_t Artist::getCount(Session& session)
@@ -322,7 +321,7 @@ namespace lms::db
return utils::execRangeQuery<ArtistId>(query, range); return utils::execRangeQuery<ArtistId>(query, range);
} }
std::vector<std::vector<Cluster::pointer>> Artist::getClusterGroups(std::vector<ClusterTypeId> clusterTypeIds, std::size_t size) const std::vector<std::vector<Cluster::pointer>> Artist::getClusterGroups(std::span<const ClusterTypeId> clusterTypeIds, std::size_t size) const
{ {
assert(session()); assert(session());
@@ -354,6 +353,7 @@ namespace lms::db
}); });
std::vector<std::vector<Cluster::pointer>> res; std::vector<std::vector<Cluster::pointer>> res;
res.reserve(clustersByType.size());
for (const auto& [clusterTypeId, clusters] : clustersByType) for (const auto& [clusterTypeId, clusters] : clustersByType)
res.push_back(clusters); res.push_back(clusters);
-1
View File
@@ -24,7 +24,6 @@
#include "core/IConfig.hpp" #include "core/IConfig.hpp"
#include "core/ILogger.hpp" #include "core/ILogger.hpp"
#include "core/ITraceLogger.hpp"
#include "core/Service.hpp" #include "core/Service.hpp"
#include "database/Session.hpp" #include "database/Session.hpp"
#include "database/User.hpp" #include "database/User.hpp"
+2 -2
View File
@@ -71,11 +71,11 @@ namespace lms::db
return utils::fetchQuerySingleResult(session.getDboSession()->query<Wt::Dbo::ptr<Image>>("SELECT i from image i").where("i.id = ?").bind(id)); return utils::fetchQuerySingleResult(session.getDboSession()->query<Wt::Dbo::ptr<Image>>("SELECT i from image i").where("i.id = ?").bind(id));
} }
Image::pointer Image::find(Session& session, const std::filesystem::path& path) Image::pointer Image::find(Session& session, const std::filesystem::path& file)
{ {
session.checkReadTransaction(); session.checkReadTransaction();
return utils::fetchQuerySingleResult(session.getDboSession()->query<Wt::Dbo::ptr<Image>>("SELECT i from image i").where("i.absolute_file_path = ?").bind(path)); return utils::fetchQuerySingleResult(session.getDboSession()->query<Wt::Dbo::ptr<Image>>("SELECT i from image i").where("i.absolute_file_path = ?").bind(file));
} }
void Image::find(Session& session, ImageId& lastRetrievedImage, std::size_t count, const std::function<void(const Image::pointer&)>& func) void Image::find(Session& session, ImageId& lastRetrievedImage, std::size_t count, const std::function<void(const Image::pointer&)>& func)
@@ -130,16 +130,16 @@ namespace lms::db
static pointer find(Session& session, ArtistId id); static pointer find(Session& session, ArtistId id);
static std::vector<pointer> find(Session& session, std::string_view name); // exact match on name field static std::vector<pointer> find(Session& session, std::string_view name); // exact match on name field
static void find(Session& session, ArtistId& lastRetrievedArtist, std::size_t count, const std::function<void(const Artist::pointer&)>& func, MediaLibraryId library = {}); static void find(Session& session, ArtistId& lastRetrievedArtist, std::size_t count, const std::function<void(const Artist::pointer&)>& func, MediaLibraryId library = {});
static RangeResults<pointer> find(Session& session, const FindParameters& parameters); static RangeResults<pointer> find(Session& session, const FindParameters& params);
static void find(Session& session, const FindParameters& parameters, std::function<void(const pointer&)> func); static void find(Session& session, const FindParameters& params, std::function<void(const pointer&)> func);
static RangeResults<ArtistId> findIds(Session& session, const FindParameters& parameters); static RangeResults<ArtistId> findIds(Session& session, const FindParameters& params);
static RangeResults<ArtistId> findOrphanIds(Session& session, std::optional<Range> range = std::nullopt); // No track related static RangeResults<ArtistId> findOrphanIds(Session& session, std::optional<Range> range = std::nullopt); // No track related
static bool exists(Session& session, ArtistId id); static bool exists(Session& session, ArtistId id);
// Accessors // Accessors
const std::string& getName() const { return _name; } const std::string& getName() const { return _name; }
const std::string& getSortName() const { return _sortName; } const std::string& getSortName() const { return _sortName; }
std::optional<core::UUID> getMBID() const { return core::UUID::fromString(_MBID); } std::optional<core::UUID> getMBID() const { return core::UUID::fromString(_mbid); }
ObjectPtr<Image> getImage() const; ObjectPtr<Image> getImage() const;
// No artistLinkTypes means get them all // No artistLinkTypes means get them all
@@ -148,10 +148,10 @@ namespace lms::db
// Get the cluster of the tracks made by this artist // Get the cluster of the tracks made by this artist
// Each clusters are grouped by cluster type, sorted by the number of occurence // Each clusters are grouped by cluster type, sorted by the number of occurence
// size is the max number of cluster per cluster type // size is the max number of cluster per cluster type
std::vector<std::vector<ObjectPtr<Cluster>>> getClusterGroups(std::vector<ClusterTypeId> clusterTypeIds, std::size_t size) const; std::vector<std::vector<ObjectPtr<Cluster>>> getClusterGroups(std::span<const ClusterTypeId> clusterTypeIds, std::size_t size) const;
void setName(std::string_view name); void setName(std::string_view name);
void setMBID(const std::optional<core::UUID>& mbid) { _MBID = mbid ? mbid->getAsString() : ""; } void setMBID(const std::optional<core::UUID>& mbid) { _mbid = mbid ? mbid->getAsString() : ""; }
void setSortName(std::string_view sortName); void setSortName(std::string_view sortName);
void setImage(ObjectPtr<Image> image); void setImage(ObjectPtr<Image> image);
@@ -160,7 +160,7 @@ namespace lms::db
{ {
Wt::Dbo::field(a, _name, "name"); Wt::Dbo::field(a, _name, "name");
Wt::Dbo::field(a, _sortName, "sort_name"); Wt::Dbo::field(a, _sortName, "sort_name");
Wt::Dbo::field(a, _MBID, "mbid"); Wt::Dbo::field(a, _mbid, "mbid");
Wt::Dbo::belongsTo(a, _image, "image", Wt::Dbo::OnDeleteSetNull); Wt::Dbo::belongsTo(a, _image, "image", Wt::Dbo::OnDeleteSetNull);
Wt::Dbo::hasMany(a, _trackArtistLinks, Wt::Dbo::ManyToOne, "artist"); Wt::Dbo::hasMany(a, _trackArtistLinks, Wt::Dbo::ManyToOne, "artist");
@@ -173,11 +173,11 @@ namespace lms::db
friend class Session; friend class Session;
// Create // Create
Artist(const std::string& name, const std::optional<core::UUID>& MBID = {}); Artist(const std::string& name, const std::optional<core::UUID>& MBID = {});
static pointer create(Session& session, const std::string& name, const std::optional<core::UUID>& UUID = {}); static pointer create(Session& session, const std::string& name, const std::optional<core::UUID>& mbid = std::nullopt);
std::string _name; std::string _name;
std::string _sortName; std::string _sortName;
std::string _MBID; // Musicbrainz Identifier std::string _mbid; // Musicbrainz Identifier
Wt::Dbo::ptr<Image> _image; Wt::Dbo::ptr<Image> _image;
Wt::Dbo::collection<Wt::Dbo::ptr<TrackArtistLink>> _trackArtistLinks; // Tracks involving this artist Wt::Dbo::collection<Wt::Dbo::ptr<TrackArtistLink>> _trackArtistLinks; // Tracks involving this artist
+1
View File
@@ -19,6 +19,7 @@
#include "SvgImage.hpp" #include "SvgImage.hpp"
#include <filesystem>
#include <fstream> #include <fstream>
#include "core/ITraceLogger.hpp" #include "core/ITraceLogger.hpp"
+3 -5
View File
@@ -19,8 +19,6 @@
#pragma once #pragma once
#include <filesystem>
#include <memory>
#include <vector> #include <vector>
#include "image/IEncodedImage.hpp" #include "image/IEncodedImage.hpp"
@@ -33,9 +31,9 @@ namespace lms::image
SvgImage(std::vector<std::byte>&& data) SvgImage(std::vector<std::byte>&& data)
: _data{ std::move(data) } {} : _data{ std::move(data) } {}
const std::byte* getData() const { return &_data.front(); } const std::byte* getData() const override { return &_data.front(); }
std::size_t getDataSize() const { return _data.size(); } std::size_t getDataSize() const override { return _data.size(); }
std::string_view getMimeType() const { return "image/svg+xml"; } std::string_view getMimeType() const override { return "image/svg+xml"; }
private: private:
const std::vector<std::byte> _data; const std::vector<std::byte> _data;
+2 -4
View File
@@ -47,8 +47,7 @@ namespace lms::image::STB
} }
} }
const std::byte* const std::byte* JPEGImage::getData() const
JPEGImage::getData() const
{ {
if (_data.empty()) if (_data.empty())
return nullptr; return nullptr;
@@ -56,8 +55,7 @@ namespace lms::image::STB
return &_data.front(); return &_data.front();
} }
std::size_t std::size_t JPEGImage::getDataSize() const
JPEGImage::getDataSize() const
{ {
return _data.size(); return _data.size();
} }
+2 -2
View File
@@ -45,7 +45,7 @@ namespace lms::image::STB
{ {
RawImage::RawImage(const std::byte* encodedData, std::size_t encodedDataSize) RawImage::RawImage(const std::byte* encodedData, std::size_t encodedDataSize)
{ {
int n; int n{};
_data = UniquePtrFree{ ::stbi_load_from_memory(reinterpret_cast<const stbi_uc*>(encodedData), encodedDataSize, &_width, &_height, &n, 3), std::free }; _data = UniquePtrFree{ ::stbi_load_from_memory(reinterpret_cast<const stbi_uc*>(encodedData), encodedDataSize, &_width, &_height, &n, 3), std::free };
if (!_data) if (!_data)
throw Exception{ "Cannot load image from memory: " + std::string{ ::stbi_failure_reason() } }; throw Exception{ "Cannot load image from memory: " + std::string{ ::stbi_failure_reason() } };
@@ -78,7 +78,7 @@ namespace lms::image::STB
width = (size_t)((float)height / _height * _width); width = (size_t)((float)height / _height * _width);
} }
UniquePtrFree resizedData{ reinterpret_cast<unsigned char*>(malloc(width * height * 3)), std::free }; UniquePtrFree resizedData{ static_cast<unsigned char*>(malloc(width * height * 3)), std::free };
if (!resizedData) if (!resizedData)
throw Exception{ "Cannot allocate memory for resized image!" }; throw Exception{ "Cannot allocate memory for resized image!" };
+6 -2
View File
@@ -33,6 +33,10 @@ namespace lms::image::STB
RawImage(const std::byte* encodedData, std::size_t encodedDataSize); RawImage(const std::byte* encodedData, std::size_t encodedDataSize);
RawImage(const std::filesystem::path& path); RawImage(const std::filesystem::path& path);
~RawImage() override = default;
RawImage(const RawImage&) = delete;
RawImage& operator=(const RawImage&) = delete;
ImageSize getWidth() const override; ImageSize getWidth() const override;
ImageSize getHeight() const override; ImageSize getHeight() const override;
@@ -42,8 +46,8 @@ namespace lms::image::STB
const std::byte* getData() const; const std::byte* getData() const;
private: private:
int _width; int _width{};
int _height; int _height{};
using UniquePtrFree = std::unique_ptr<unsigned char, decltype(&std::free)>; using UniquePtrFree = std::unique_ptr<unsigned char, decltype(&std::free)>;
UniquePtrFree _data{ nullptr, std::free }; UniquePtrFree _data{ nullptr, std::free };
}; };
@@ -19,6 +19,8 @@
#pragma once #pragma once
#include <memory>
#include "image/IEncodedImage.hpp" #include "image/IEncodedImage.hpp"
namespace lms::image namespace lms::image
+1 -5
View File
@@ -19,16 +19,12 @@
#include "AvFormatTagReader.hpp" #include "AvFormatTagReader.hpp"
#include <algorithm>
#include <iostream>
#include "av/IAudioFile.hpp" #include "av/IAudioFile.hpp"
#include "av/Types.hpp"
#include "core/ILogger.hpp" #include "core/ILogger.hpp"
#include "core/String.hpp" #include "core/String.hpp"
#include "metadata/Exception.hpp" #include "metadata/Exception.hpp"
#include "Utils.hpp"
namespace lms::metadata namespace lms::metadata
{ {
namespace namespace
+2 -3
View File
@@ -22,7 +22,6 @@
#include <filesystem> #include <filesystem>
#include "av/IAudioFile.hpp" #include "av/IAudioFile.hpp"
#include "metadata/IParser.hpp"
#include "ITagReader.hpp" #include "ITagReader.hpp"
@@ -32,11 +31,11 @@ namespace lms::metadata
{ {
public: public:
AvFormatTagReader(const std::filesystem::path& path, bool debug); AvFormatTagReader(const std::filesystem::path& path, bool debug);
~AvFormatTagReader() override = default;
private:
AvFormatTagReader(const AvFormatTagReader&) = delete; AvFormatTagReader(const AvFormatTagReader&) = delete;
AvFormatTagReader& operator=(const AvFormatTagReader&) = delete; AvFormatTagReader& operator=(const AvFormatTagReader&) = delete;
private:
void visitTagValues(TagType tag, TagValueVisitor visitor) const override; void visitTagValues(TagType tag, TagValueVisitor visitor) const override;
void visitTagValues(std::string_view tag, TagValueVisitor visitor) const override; void visitTagValues(std::string_view tag, TagValueVisitor visitor) const override;
void visitPerformerTags(PerformerVisitor visitor) const override; void visitPerformerTags(PerformerVisitor visitor) const override;
@@ -43,7 +43,7 @@ namespace lms::scanner
{ {
public: public:
ScannerService(db::Db& db); ScannerService(db::Db& db);
~ScannerService(); ~ScannerService() override;
private: private:
ScannerService(const ScannerService&) = delete; ScannerService(const ScannerService&) = delete;
@@ -55,7 +55,6 @@ namespace lms::scanner
Status getStatus() const override; Status getStatus() const override;
Events& getEvents() override { return _events; } Events& getEvents() override { return _events; }
private:
void start(); void start();
void stop(); void stop();
@@ -19,6 +19,9 @@
#pragma once #pragma once
#include <optional>
#include <string_view>
#include "core/String.hpp" #include "core/String.hpp"
namespace lms::api::subsonic namespace lms::api::subsonic
-17
View File
@@ -19,9 +19,6 @@
#include "SubsonicId.hpp" #include "SubsonicId.hpp"
#include "SubsonicResponse.hpp"
#include "core/ILogger.hpp"
#include "core/String.hpp" #include "core/String.hpp"
namespace lms::api::subsonic namespace lms::api::subsonic
@@ -47,11 +44,6 @@ namespace lms::api::subsonic
return "al-" + id.toString(); return "al-" + id.toString();
} }
std::string idToString(RootId)
{
return "root";
}
std::string idToString(db::TrackId id) std::string idToString(db::TrackId id)
{ {
return "tr-" + id.toString(); return "tr-" + id.toString();
@@ -122,15 +114,6 @@ namespace lms::core::stringUtils
return std::nullopt; return std::nullopt;
} }
template<>
std::optional<api::subsonic::RootId> readAs(std::string_view str)
{
if (str == "root")
return api::subsonic::RootId{};
return std::nullopt;
}
template<> template<>
std::optional<db::TrackId> readAs(std::string_view str) std::optional<db::TrackId> readAs(std::string_view str)
{ {
-8
View File
@@ -29,25 +29,17 @@
namespace lms::api::subsonic namespace lms::api::subsonic
{ {
struct RootId
{
};
std::string idToString(db::ArtistId id); std::string idToString(db::ArtistId id);
std::string idToString(db::DirectoryId id); std::string idToString(db::DirectoryId id);
std::string idToString(db::MediaLibraryId id); std::string idToString(db::MediaLibraryId id);
std::string idToString(db::ReleaseId id); std::string idToString(db::ReleaseId id);
std::string idToString(db::TrackId id); std::string idToString(db::TrackId id);
std::string idToString(db::TrackListId id); std::string idToString(db::TrackListId id);
std::string idToString(RootId);
} // namespace lms::api::subsonic } // namespace lms::api::subsonic
// Used to parse parameters // Used to parse parameters
namespace lms::core::stringUtils namespace lms::core::stringUtils
{ {
template<>
std::optional<api::subsonic::RootId> readAs(std::string_view str);
template<> template<>
std::optional<db::ArtistId> readAs(std::string_view str); std::optional<db::ArtistId> readAs(std::string_view str);
+16 -18
View File
@@ -29,7 +29,6 @@
#include "core/LiteralString.hpp" #include "core/LiteralString.hpp"
#include "core/Service.hpp" #include "core/Service.hpp"
#include "core/String.hpp" #include "core/String.hpp"
#include "core/Utils.hpp"
#include "database/Db.hpp" #include "database/Db.hpp"
#include "database/Session.hpp" #include "database/Session.hpp"
#include "database/User.hpp" #include "database/User.hpp"
@@ -39,7 +38,6 @@
#include "ParameterParsing.hpp" #include "ParameterParsing.hpp"
#include "ProtocolVersion.hpp" #include "ProtocolVersion.hpp"
#include "RequestContext.hpp" #include "RequestContext.hpp"
#include "SubsonicId.hpp"
#include "SubsonicResponse.hpp" #include "SubsonicResponse.hpp"
#include "endpoints/AlbumSongLists.hpp" #include "endpoints/AlbumSongLists.hpp"
#include "endpoints/Bookmarks.hpp" #include "endpoints/Bookmarks.hpp"
@@ -105,8 +103,8 @@ namespace lms::api::subsonic
auto censorValue = [](const std::string& type, const std::string& value) -> std::string { auto censorValue = [](const std::string& type, const std::string& value) -> std::string {
if (type == "p" || type == "password") if (type == "p" || type == "password")
return "*REDACTED*"; return "*REDACTED*";
else
return value; return value;
}; };
std::string res; std::string res;
@@ -138,7 +136,7 @@ namespace lms::api::subsonic
throw UserNotAuthorizedError{}; throw UserNotAuthorizedError{};
} }
Response handleNotImplemented(RequestContext&) Response handleNotImplemented(RequestContext& /*context*/)
{ {
throw NotImplementedGenericError{}; throw NotImplementedGenericError{};
} }
@@ -292,6 +290,18 @@ namespace lms::api::subsonic
throw UserNotAuthorizedError{}; throw UserNotAuthorizedError{};
} }
ClientInfo getClientInfo(const Wt::Http::Request& request)
{
const auto& parameters{ request.getParameterMap() };
ClientInfo res;
// Mandatory parameters
res.name = getMandatoryParameterAs<std::string>(parameters, "c");
res.version = getMandatoryParameterAs<ProtocolVersion>(parameters, "v");
return res;
}
} // namespace } // namespace
SubsonicResource::SubsonicResource(db::Db& db) SubsonicResource::SubsonicResource(db::Db& db)
@@ -403,25 +413,13 @@ namespace lms::api::subsonic
throw ClientMustUpgradeError{}; throw ClientMustUpgradeError{};
if (client.minor > server.minor) if (client.minor > server.minor)
throw ServerMustUpgradeError{}; throw ServerMustUpgradeError{};
else if (client.minor == server.minor) if (client.minor == server.minor)
{ {
if (client.patch > server.patch) if (client.patch > server.patch)
throw ServerMustUpgradeError{}; throw ServerMustUpgradeError{};
} }
} }
ClientInfo SubsonicResource::getClientInfo(const Wt::Http::Request& request)
{
const auto& parameters{ request.getParameterMap() };
ClientInfo res;
// Mandatory parameters
res.name = getMandatoryParameterAs<std::string>(parameters, "c");
res.version = getMandatoryParameterAs<ProtocolVersion>(parameters, "v");
return res;
}
RequestContext SubsonicResource::buildRequestContext(const Wt::Http::Request& request) RequestContext SubsonicResource::buildRequestContext(const Wt::Http::Request& request)
{ {
const Wt::Http::ParameterMap& parameters{ request.getParameterMap() }; const Wt::Http::ParameterMap& parameters{ request.getParameterMap() };
@@ -25,10 +25,8 @@
#include <Wt/Http/Response.h> #include <Wt/Http/Response.h>
#include <Wt/WResource.h> #include <Wt/WResource.h>
#include "database/Types.hpp"
#include "database/UserId.hpp" #include "database/UserId.hpp"
#include "ClientInfo.hpp"
#include "RequestContext.hpp" #include "RequestContext.hpp"
namespace lms::db namespace lms::db
@@ -48,7 +46,6 @@ namespace lms::api::subsonic
ProtocolVersion getServerProtocolVersion(const std::string& clientName) const; ProtocolVersion getServerProtocolVersion(const std::string& clientName) const;
static void checkProtocolVersion(ProtocolVersion client, ProtocolVersion server); static void checkProtocolVersion(ProtocolVersion client, ProtocolVersion server);
ClientInfo getClientInfo(const Wt::Http::Request& request);
RequestContext buildRequestContext(const Wt::Http::Request& request); RequestContext buildRequestContext(const Wt::Http::Request& request);
db::UserId authenticateUser(const Wt::Http::Request& request); db::UserId authenticateUser(const Wt::Http::Request& request);
@@ -25,7 +25,6 @@
#include <boost/property_tree/xml_parser.hpp> #include <boost/property_tree/xml_parser.hpp>
#include "core/Exception.hpp"
#include "core/String.hpp" #include "core/String.hpp"
#include "ProtocolVersion.hpp" #include "ProtocolVersion.hpp"
@@ -38,7 +38,7 @@ namespace lms::api::subsonic
constexpr Allocator() noexcept = default; constexpr Allocator() noexcept = default;
template<typename U> template<typename U>
constexpr Allocator(const Allocator<MemoryResource, U>&) noexcept constexpr Allocator(const Allocator<MemoryResource, U>& /*allocator*/) noexcept
{ {
} }
@@ -54,7 +54,7 @@ namespace lms::api::subsonic
} }
// Deallocate memory pointed to by p // Deallocate memory pointed to by p
void deallocate(pointer p, std::size_t) noexcept void deallocate(pointer p, std::size_t /*n*/) noexcept
{ {
MemoryResource::getInstance().deallocate(reinterpret_cast<std::byte*>(p)); MemoryResource::getInstance().deallocate(reinterpret_cast<std::byte*>(p));
} }
+2 -4
View File
@@ -27,9 +27,7 @@
#include <Wt/WFormModel.h> #include <Wt/WFormModel.h>
#include "core/Exception.hpp"
#include "core/IConfig.hpp" #include "core/IConfig.hpp"
#include "core/ILogger.hpp"
#include "core/Service.hpp" #include "core/Service.hpp"
#include "core/String.hpp" #include "core/String.hpp"
#include "database/Session.hpp" #include "database/Session.hpp"
@@ -125,7 +123,7 @@ namespace lms::ui
const User::pointer user{ User::find(LmsApp->getDbSession(), *_userId) }; const User::pointer user{ User::find(LmsApp->getDbSession(), *_userId) };
if (!user) if (!user)
throw UserNotFoundException{}; throw UserNotFoundException{};
else if (user == LmsApp->getUser()) if (user == LmsApp->getUser())
throw UserNotAllowedException{}; throw UserNotAllowedException{};
} }
@@ -155,7 +153,7 @@ namespace lms::ui
return valueText(LoginField).toUTF8(); return valueText(LoginField).toUTF8();
} }
bool validateField(Field field) bool validateField(Field field) override
{ {
Wt::WString error; Wt::WString error;