Merge branch 'develop' for release v3.46.0

This commit is contained in:
emeric
2023-12-18 09:49:43 +01:00
59 changed files with 1231 additions and 876 deletions
+5 -4
View File
@@ -190,12 +190,12 @@
<plural case="1">Producers</plural>
</message>
<message id="Lms.Explore.Artists.linktype-releaseartist">
<plural case="0">Album artists</plural>
<plural case="1">Album artist</plural>
<plural case="0">Album artist</plural>
<plural case="1">Album artists</plural>
</message>
<message id="Lms.Explore.Artists.linktype-remixer">
<plural case="0">Remixers</plural>
<plural case="1">Remixer</plural>
<plural case="0">Remixer</plural>
<plural case="1">Remixers</plural>
</message>
<!--Explore:Release-->
@@ -213,6 +213,7 @@
<message id="Lms.Explore.Release.type-secondary-compilation">Compilation</message>
<message id="Lms.Explore.Release.type-secondary-demo">Demo</message>
<message id="Lms.Explore.Release.type-secondary-djmix">DJ-mix</message>
<message id="Lms.Explore.Release.type-secondary-field-recording">Field recording</message>
<message id="Lms.Explore.Release.type-secondary-interview">Interview</message>
<message id="Lms.Explore.Release.type-secondary-live">Live</message>
<message id="Lms.Explore.Release.type-secondary-mixtape-street">Mixtape/Street</message>
+7 -6
View File
@@ -204,21 +204,22 @@
<message id="Lms.Explore.Release.disc">Disque {1}</message>
<message id="Lms.Explore.Release.type">Type</message>
<message id="Lms.Explore.Release.type-primary-album">Album</message>
<message id="Lms.Explore.Release.type-primary-broadcast">Broadcast</message>
<message id="Lms.Explore.Release.type-primary-broadcast">Diffusion</message>
<message id="Lms.Explore.Release.type-primary-ep">EP</message>
<message id="Lms.Explore.Release.type-primary-other">Other</message>
<message id="Lms.Explore.Release.type-primary-single">Single</message>
<message id="Lms.Explore.Release.type-secondary-audiobook">Audiobook</message>
<message id="Lms.Explore.Release.type-secondary-audiodrama">Audio drama</message>
<message id="Lms.Explore.Release.type-secondary-audiobook">Livre audio</message>
<message id="Lms.Explore.Release.type-secondary-audiodrama">Drame audio</message>
<message id="Lms.Explore.Release.type-secondary-compilation">Compilation</message>
<message id="Lms.Explore.Release.type-secondary-demo">Demo</message>
<message id="Lms.Explore.Release.type-secondary-demo">Démo</message>
<message id="Lms.Explore.Release.type-secondary-djmix">DJ-mix</message>
<message id="Lms.Explore.Release.type-secondary-field-recording">Enregistrement sur le terrain</message>
<message id="Lms.Explore.Release.type-secondary-interview">Interview</message>
<message id="Lms.Explore.Release.type-secondary-live">Live</message>
<message id="Lms.Explore.Release.type-secondary-mixtape-street">Mixtape/Street</message>
<message id="Lms.Explore.Release.type-secondary-remix">Remix</message>
<message id="Lms.Explore.Release.type-secondary-soundtrack">Soundtrack</message>
<message id="Lms.Explore.Release.type-secondary-spokenword">Spokenword</message>
<message id="Lms.Explore.Release.type-secondary-soundtrack">Bande son</message>
<message id="Lms.Explore.Release.type-secondary-spokenword">Création parlée</message>
<!--Explore:TrackLists-->
<message id="Lms.Explore.TrackLists.del-tracklist-confirm">Supprimer la liste de lecture ?</message>
+1
View File
@@ -220,6 +220,7 @@
<!--Explore:TrackLists-->
+1
View File
@@ -220,6 +220,7 @@
<!--Explore:TrackLists-->
<message id="Lms.Explore.TrackLists.del-tracklist-confirm">删除播放列表?</message>
+4 -1
View File
@@ -84,7 +84,10 @@ cover-max-cache-size = 30;
cover-jpeg-quality = 75;
# Preferred file names for covers (order is important)
cover-preferred-file-names = ("cover", "front" );
cover-preferred-file-names = ("cover", "front");
# File names for artist images (order is important)
artist-image-file-names = ("artist");
# Playqueue max entry count
playqueue-max-entry-count = 1000;
+1 -1
View File
@@ -180,7 +180,7 @@ namespace Database
return session.getDboSession().query<int>("SELECT COUNT(*) FROM artist");
}
std::vector<Artist::pointer> Artist::find(Session& session, const std::string& name)
std::vector<Artist::pointer> Artist::find(Session& session, std::string_view name)
{
session.checkReadTransaction();
+25 -26
View File
@@ -26,35 +26,34 @@
namespace Wt::Dbo
{
template<typename T>
struct sql_value_traits<T, typename std::enable_if<std::is_base_of<Database::IdType, T>::value>::type>
{
static_assert(!std::is_same_v<Database::IdType, T>, "Cannot use IdType, use derived types");
static const bool specialized = true;
template<typename T>
struct sql_value_traits<T, typename std::enable_if<std::is_base_of<Database::IdType, T>::value>::type>
{
static_assert(!std::is_same_v<Database::IdType, T>, "Cannot use IdType, use derived types");
static const bool specialized = true;
static std::string type(SqlConnection* conn, int size)
{
return sql_value_traits<typename T::ValueType, void>::type(conn, size);
}
static std::string type(SqlConnection *conn, int size)
{
return sql_value_traits<typename T::ValueType, void>::type(conn, size);
}
static void bind(const T& v, SqlStatement* statement, int column, int size)
{
sql_value_traits<typename T::ValueType>::bind(v.getValue(), statement, column, size);
}
static void bind(const T& v, SqlStatement *statement, int column, int size)
{
sql_value_traits<typename T::ValueType>::bind(v.getValue(), statement, column, size);
}
static bool read(T& v, SqlStatement* statement, int column, int size)
{
typename T::ValueType value;
if (sql_value_traits<typename T::ValueType>::read(value, statement, column, size))
{
v = value;
return true;
}
static bool read(T& v, SqlStatement *statement, int column, int size)
{
typename T::ValueType value;
if (sql_value_traits<typename T::ValueType>::read(value, statement, column, size))
{
v = value;
return true;
}
v = {};
return false;
}
};
v = {};
return false;
}
};
}
+117 -107
View File
@@ -25,112 +25,113 @@
#include "SqlQuery.hpp"
#include "Utils.hpp"
namespace
{
using namespace Database;
Wt::Dbo::Query<ArtistId> createArtistsQuery(Wt::Dbo::Session& session, UserId userId, ScrobblingBackend backend, const std::vector<ClusterId>& clusterIds, std::optional<TrackArtistLinkType> linkType)
{
auto query{ session.query<ArtistId>("SELECT a.id from artist a")
.join("track t ON t.id = t_a_l.track_id")
.join("track_artist_link t_a_l ON t_a_l.artist_id = a.id")
.join("listen l ON l.track_id = t.id")
.where("l.user_id = ?").bind(userId)
.where("l.backend = ?").bind(backend) };
if (linkType)
query.where("t_a_l.type = ?").bind(*linkType);
if (!clusterIds.empty())
{
std::ostringstream oss;
oss << "a.id IN (SELECT DISTINCT a.id FROM artist a"
" INNER JOIN track t ON t.id = t_a_l.track_id"
" INNER JOIN track_artist_link t_a_l ON t_a_l.artist_id = a.id"
" INNER JOIN cluster c ON c.id = t_c.cluster_id"
" INNER JOIN track_cluster t_c ON t_c.track_id = t.id";
WhereClause clusterClause;
for (auto id : clusterIds)
{
clusterClause.Or(WhereClause("c.id = ?"));
query.bind(id);
}
oss << " " << clusterClause.get();
oss << " GROUP BY t.id,a.id HAVING COUNT(DISTINCT c.id) = " << clusterIds.size() << ")";
query.where(oss.str());
}
return query;
}
Wt::Dbo::Query<ReleaseId> createReleasesQuery(Wt::Dbo::Session& session, UserId userId, ScrobblingBackend backend, const std::vector<ClusterId>& clusterIds)
{
auto query{ session.query<ReleaseId>("SELECT r.id from release r")
.join("track t ON t.release_id = r.id")
.join("listen l ON l.track_id = t.id")
.where("l.user_id = ?").bind(userId)
.where("l.backend = ?").bind(backend) };
if (!clusterIds.empty())
{
std::ostringstream oss;
oss << "r.id IN (SELECT DISTINCT r.id FROM release r"
" INNER JOIN track t ON t.release_id = r.id"
" INNER JOIN cluster c ON c.id = t_c.cluster_id"
" INNER JOIN track_cluster t_c ON t_c.track_id = t.id";
WhereClause clusterClause;
for (ClusterId id : clusterIds)
{
clusterClause.Or(WhereClause("c.id = ?"));
query.bind(id);
}
oss << " " << clusterClause.get();
oss << " GROUP BY t.id HAVING COUNT(DISTINCT c.id) = " << clusterIds.size() << ")";
query.where(oss.str());
}
return query;
}
Wt::Dbo::Query<TrackId> createTracksQuery(Wt::Dbo::Session& session, UserId userId, ScrobblingBackend backend, const std::vector<ClusterId>& clusterIds)
{
auto query{ session.query<TrackId>("SELECT t.id from track t")
.join("listen l ON l.track_id = t.id")
.where("l.user_id = ?").bind(userId)
.where("l.backend = ?").bind(backend) };
if (!clusterIds.empty())
{
std::ostringstream oss;
oss << "t.id IN (SELECT DISTINCT t.id FROM track t"
" INNER JOIN track_cluster t_c ON t_c.track_id = t.id"
" INNER JOIN cluster c ON c.id = t_c.cluster_id";
WhereClause clusterClause;
for (auto id : clusterIds)
{
clusterClause.Or(WhereClause("c.id = ?")).bind(id.toString());
query.bind(id);
}
oss << " " << clusterClause.get();
oss << " GROUP BY t.id HAVING COUNT(*) = " << clusterIds.size() << ")";
query.where(oss.str());
}
return query;
}
}
namespace Database
{
namespace
{
Wt::Dbo::Query<ArtistId> createArtistsQuery(Wt::Dbo::Session& session, UserId userId, ScrobblingBackend backend, const std::vector<ClusterId>& clusterIds, std::optional<TrackArtistLinkType> linkType)
{
auto query{ session.query<ArtistId>("SELECT a.id from artist a")
.join("track t ON t.id = t_a_l.track_id")
.join("track_artist_link t_a_l ON t_a_l.artist_id = a.id")
.join("listen l ON l.track_id = t.id")
.where("l.user_id = ?").bind(userId)
.where("l.backend = ?").bind(backend) };
if (linkType)
query.where("t_a_l.type = ?").bind(*linkType);
if (!clusterIds.empty())
{
std::ostringstream oss;
oss << "a.id IN (SELECT DISTINCT a.id FROM artist a"
" INNER JOIN track t ON t.id = t_a_l.track_id"
" INNER JOIN track_artist_link t_a_l ON t_a_l.artist_id = a.id"
" INNER JOIN cluster c ON c.id = t_c.cluster_id"
" INNER JOIN track_cluster t_c ON t_c.track_id = t.id";
WhereClause clusterClause;
for (auto id : clusterIds)
{
clusterClause.Or(WhereClause("c.id = ?"));
query.bind(id);
}
oss << " " << clusterClause.get();
oss << " GROUP BY t.id,a.id HAVING COUNT(DISTINCT c.id) = " << clusterIds.size() << ")";
query.where(oss.str());
}
return query;
}
Wt::Dbo::Query<ReleaseId> createReleasesQuery(Wt::Dbo::Session& session, UserId userId, ScrobblingBackend backend, const std::vector<ClusterId>& clusterIds)
{
auto query{ session.query<ReleaseId>("SELECT r.id from release r")
.join("track t ON t.release_id = r.id")
.join("listen l ON l.track_id = t.id")
.where("l.user_id = ?").bind(userId)
.where("l.backend = ?").bind(backend) };
if (!clusterIds.empty())
{
std::ostringstream oss;
oss << "r.id IN (SELECT DISTINCT r.id FROM release r"
" INNER JOIN track t ON t.release_id = r.id"
" INNER JOIN cluster c ON c.id = t_c.cluster_id"
" INNER JOIN track_cluster t_c ON t_c.track_id = t.id";
WhereClause clusterClause;
for (ClusterId id : clusterIds)
{
clusterClause.Or(WhereClause("c.id = ?"));
query.bind(id);
}
oss << " " << clusterClause.get();
oss << " GROUP BY t.id HAVING COUNT(DISTINCT c.id) = " << clusterIds.size() << ")";
query.where(oss.str());
}
return query;
}
Wt::Dbo::Query<TrackId> createTracksQuery(Wt::Dbo::Session& session, UserId userId, ArtistId artistId, ScrobblingBackend backend, const std::vector<ClusterId>& clusterIds)
{
auto query{ session.query<TrackId>("SELECT t.id from track t")
.join("listen l ON l.track_id = t.id")
.where("l.user_id = ?").bind(userId)
.where("l.backend = ?").bind(backend) };
if (artistId.isValid())
query.join("track_artist_link t_a_l ON t_a_l.track_id = t.id").where("t_a_l.artist_id = ?").bind(artistId);
if (!clusterIds.empty())
{
std::ostringstream oss;
oss << "t.id IN (SELECT DISTINCT t.id FROM track t"
" INNER JOIN track_cluster t_c ON t_c.track_id = t.id"
" INNER JOIN cluster c ON c.id = t_c.cluster_id";
WhereClause clusterClause;
for (auto id : clusterIds)
{
clusterClause.Or(WhereClause("c.id = ?")).bind(id.toString());
query.bind(id);
}
oss << " " << clusterClause.get();
oss << " GROUP BY t.id HAVING COUNT(*) = " << clusterIds.size() << ")";
query.where(oss.str());
}
return query;
}
}
Listen::Listen(ObjectPtr<User> user, ObjectPtr<Track> track, ScrobblingBackend backend, const Wt::WDateTime& dateTime)
: _dateTime{ Wt::WDateTime::fromTime_t(dateTime.toTime_t()) }
, _backend{ backend }
@@ -212,7 +213,17 @@ namespace Database
RangeResults<TrackId> Listen::getTopTracks(Session& session, UserId userId, ScrobblingBackend backend, const std::vector<ClusterId>& clusterIds, std::optional<Range> range)
{
session.checkReadTransaction();
auto query{ createTracksQuery(session.getDboSession(), userId, backend, clusterIds)
auto query{ createTracksQuery(session.getDboSession(), userId, ArtistId{}, backend, clusterIds)
.orderBy("COUNT(t.id) DESC")
.groupBy("t.id") };
return Utils::execQuery<TrackId>(query, range);
}
RangeResults<TrackId> Listen::getTopTracks(Session& session, UserId userId, ArtistId artistId, ScrobblingBackend backend, const std::vector<ClusterId>& clusterIds, std::optional<Range> range)
{
session.checkReadTransaction();
auto query{ createTracksQuery(session.getDboSession(), userId, artistId, backend, clusterIds)
.orderBy("COUNT(t.id) DESC")
.groupBy("t.id") };
@@ -242,7 +253,7 @@ namespace Database
RangeResults<TrackId> Listen::getRecentTracks(Session& session, UserId userId, ScrobblingBackend backend, const std::vector<ClusterId>& clusterIds, std::optional<Range> range)
{
session.checkReadTransaction();
auto query{ createTracksQuery(session.getDboSession(), userId, backend, clusterIds)
auto query{ createTracksQuery(session.getDboSession(), userId, ArtistId{}, backend, clusterIds)
.groupBy("t.id").having("l.date_time = MAX(l.date_time)")
.orderBy("l.date_time DESC") };
@@ -307,4 +318,3 @@ namespace Database
.resultValue();
}
} // namespace Database
+26
View File
@@ -267,6 +267,31 @@ CREATE TABLE IF NOT EXISTS "track_backup" (
session.getDboSession().execute("UPDATE scan_settings SET scan_version = scan_version + 1");
}
void migrateFromV47(Session& session)
{
// release type, new way
session.getDboSession().execute("ALTER TABLE release DROP primary_type");
session.getDboSession().execute("ALTER TABLE release DROP secondary_types");
session.getDboSession().execute(R"(CREATE TABLE IF NOT EXISTS "release_type" (
"id" integer primary key autoincrement,
"version" integer not null,
"name" text not null))");
session.getDboSession().execute(R"(CREATE TABLE IF NOT EXISTS "release_release_type" (
"release_type_id" bigint,
"release_id" bigint,
primary key ("release_type_id", "release_id"),
constraint "fk_release_release_type_key1" foreign key ("release_type_id") references "release_type" ("id") on delete cascade deferrable initially deferred,
constraint "fk_release_release_type_key2" foreign key ("release_id") references "release" ("id") on delete cascade deferrable initially deferred
))");
session.getDboSession().execute(R"(CREATE INDEX "release_release_type_release_type" on "release_release_type" ("release_type_id"))");
session.getDboSession().execute(R"(CREATE INDEX "release_release_type_release" on "release_release_type" ("release_id"))");
// Just increment the scan version of the settings to make the next scheduled scan rescan everything
session.getDboSession().execute("UPDATE scan_settings SET scan_version = scan_version + 1");
}
void doDbMigration(Session& session)
{
static const std::string outdatedMsg{ "Outdated database, please rebuild it (delete the .db file and restart)" };
@@ -292,6 +317,7 @@ CREATE TABLE IF NOT EXISTS "track_backup" (
{44, migrateFromV44},
{45, migrateFromV45},
{46, migrateFromV46},
{47, migrateFromV47},
};
{
+1 -1
View File
@@ -26,7 +26,7 @@ namespace Database
class Session;
using Version = std::size_t;
static constexpr Version LMS_DATABASE_VERSION{ 47 };
static constexpr Version LMS_DATABASE_VERSION{ 48 };
class VersionInfo
{
public:
+63 -5
View File
@@ -30,6 +30,7 @@
#include "SqlQuery.hpp"
#include "EnumSetTraits.hpp"
#include "IdTypeTraits.hpp"
#include "StringViewTraits.hpp"
#include "Utils.hpp"
namespace Database
@@ -53,6 +54,13 @@ namespace Database
query.join("track t ON t.release_id = r.id");
}
if (!params.releaseType.empty())
{
query.join("release_release_type r_r_t ON r_r_t.release_id = r.id");
query.join("release_type r_t ON r_t.id = r_r_t.release_type_id")
.where("r_t.name = ?").bind(params.releaseType);
}
if (params.writtenAfter.isValid())
query.where("t.file_last_write > ?").bind(params.writtenAfter);
@@ -148,11 +156,6 @@ namespace Database
query.where(oss.str());
}
if (params.primaryType)
query.where("primary_type = ?").bind(*params.primaryType);
if (!params.secondaryTypes.empty())
query.where("secondary_type = ?").bind(params.secondaryTypes);
switch (params.sortMethod)
{
case ReleaseSortMethod::None:
@@ -185,6 +188,36 @@ namespace Database
}
}
ReleaseType::ReleaseType(std::string_view name)
: _name{ std::string(name, 0 , _maxNameLength) }
{
}
ReleaseType::pointer ReleaseType::create(Session& session, std::string_view name)
{
return session.getDboSession().add(std::unique_ptr<ReleaseType> {new ReleaseType{ name }});
}
ReleaseType::pointer ReleaseType::find(Session& session, ReleaseTypeId id)
{
session.checkReadTransaction();
return session.getDboSession()
.find<ReleaseType>()
.where("id = ?").bind(id)
.resultValue();
}
ReleaseType::pointer ReleaseType::find(Session& session, std::string_view name)
{
session.checkReadTransaction();
return session.getDboSession()
.find<ReleaseType>()
.where("name = ?").bind(name)
.resultValue();
}
Release::Release(const std::string& name, const std::optional<UUID>& MBID)
: _name{ std::string(name, 0 , _maxNameLength) },
_MBID{ MBID ? MBID->getAsString() : "" }
@@ -448,6 +481,16 @@ namespace Database
return std::vector<pointer>(res.begin(), res.end());
}
void Release::clearReleaseTypes()
{
_releaseTypes.clear();
}
void Release::addReleaseType(ObjectPtr<ReleaseType> releaseType)
{
_releaseTypes.insert(getDboPtr(releaseType));
}
bool Release::hasVariousArtists() const
{
// TODO optimize
@@ -459,6 +502,21 @@ namespace Database
return _tracks.size();
}
std::vector<ObjectPtr<ReleaseType>> Release::getReleaseTypes() const
{
return std::vector<ObjectPtr<ReleaseType>>(_releaseTypes.begin(), _releaseTypes.end());
}
std::vector<std::string> Release::getReleaseTypeNames() const
{
std::vector<std::string> res;
for (const auto& releaseType : _releaseTypes)
res.push_back(std::string{ releaseType->getName() });
return res;
}
std::chrono::milliseconds Release::getDuration() const
{
assert(session());
+2
View File
@@ -82,6 +82,7 @@ namespace Database
_session.mapClass<ClusterType>("cluster_type");
_session.mapClass<Listen>("listen");
_session.mapClass<Release>("release");
_session.mapClass<ReleaseType>("release_type");
_session.mapClass<ScanSettings>("scan_settings");
_session.mapClass<StarredArtist>("starred_artist");
_session.mapClass<StarredRelease>("starred_release");
@@ -142,6 +143,7 @@ namespace Database
_session.execute("CREATE INDEX IF NOT EXISTS release_name_idx ON release(name)");
_session.execute("CREATE INDEX IF NOT EXISTS release_name_nocase_idx ON release(name COLLATE NOCASE)");
_session.execute("CREATE INDEX IF NOT EXISTS release_mbid_idx ON release(mbid)");
_session.execute("CREATE INDEX IF NOT EXISTS release_type_name_idx ON release_type(name)");
_session.execute("CREATE INDEX IF NOT EXISTS track_path_idx ON track(file_path)");
_session.execute("CREATE INDEX IF NOT EXISTS track_name_idx ON track(name)");
_session.execute("CREATE INDEX IF NOT EXISTS track_name_nocase_idx ON track(name COLLATE NOCASE)");
+1 -2
View File
@@ -197,8 +197,7 @@ namespace Database
return session.getDboSession().add(std::unique_ptr<Track> {new Track{ p }});
}
std::size_t
Track::getCount(Session& session)
std::size_t Track::getCount(Session& session)
{
session.checkReadTransaction();
@@ -82,7 +82,7 @@ namespace Database
static std::size_t getCount(Session& session);
static pointer find(Session& session, const UUID& MBID);
static pointer find(Session& session, ArtistId id);
static std::vector<pointer> find(Session& session, const std::string& name); // exact match on name field
static std::vector<pointer> find(Session& session, std::string_view name); // exact match on name field
static RangeResults<pointer> find(Session& session, const FindParameters& parameters);
static void find(Session& session, const FindParameters& parameters, std::function<void(const pointer&)> func);
static RangeResults<ArtistId> findIds(Session& session, const FindParameters& parameters);
@@ -68,6 +68,7 @@ namespace Database
static RangeResults<ArtistId> getTopArtists(Session& session, UserId userId, ScrobblingBackend backend, const std::vector<ClusterId>& clusterIds, std::optional<TrackArtistLinkType> linkType, std::optional<Range> range = std::nullopt);
static RangeResults<ReleaseId> getTopReleases(Session& session, UserId userId, ScrobblingBackend backend, const std::vector<ClusterId>& clusterIds, std::optional<Range> range = std::nullopt);
static RangeResults<TrackId> getTopTracks(Session& session, UserId userId, ScrobblingBackend backend, const std::vector<ClusterId>& clusterIds, std::optional<Range> range = std::nullopt);
static RangeResults<TrackId> getTopTracks(Session& session, UserId userId, ArtistId artistId, ScrobblingBackend backend, const std::vector<ClusterId>& clusterIds, std::optional<Range> range = std::nullopt);
static RangeResults<ArtistId> getRecentArtists(Session& session, UserId userId, ScrobblingBackend backend, const std::vector<ClusterId>& clusterIds, std::optional<TrackArtistLinkType> linkType, std::optional<Range> range = std::nullopt);
static RangeResults<ReleaseId> getRecentReleases(Session& session, UserId userId, ScrobblingBackend backend, const std::vector<ClusterId>& clusterIds, std::optional<Range> range = std::nullopt);
+41 -16
View File
@@ -21,6 +21,8 @@
#include <filesystem>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
#include <Wt/WDateTime.h>
@@ -30,6 +32,7 @@
#include "database/ClusterId.hpp"
#include "database/Object.hpp"
#include "database/ReleaseId.hpp"
#include "database/ReleaseTypeId.hpp"
#include "database/Types.hpp"
#include "database/UserId.hpp"
#include "utils/EnumSet.hpp"
@@ -37,7 +40,6 @@
namespace Database
{
class Artist;
class Cluster;
class ClusterType;
@@ -46,6 +48,34 @@ namespace Database
class Track;
class User;
class ReleaseType final : public Object<ReleaseType, ReleaseTypeId>
{
public:
ReleaseType() = default;
static pointer find(Session& session, ReleaseTypeId id);
static pointer find(Session& session, std::string_view name);
// Accessors
std::string_view getName() const { return _name; }
template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, _name, "name");
Wt::Dbo::hasMany(a, _releases, Wt::Dbo::ManyToMany, "release_release_type", "", Wt::Dbo::OnDeleteCascade);
}
private:
static constexpr std::size_t _maxNameLength{ 128 };
friend class Session;
ReleaseType(std::string_view name);
static pointer create(Session& session, std::string_view name);
std::string _name;
Wt::Dbo::collection<Wt::Dbo::ptr<Release>> _releases; // releases that match this type
};
class Release final : public Object<Release, ReleaseId>
{
public:
@@ -62,9 +92,8 @@ namespace Database
ArtistId artist; // only releases that involved this user
EnumSet<TrackArtistLinkType> trackArtistLinkTypes; // and for these link types
EnumSet<TrackArtistLinkType> excludedTrackArtistLinkTypes; // but not for these link types
std::optional<ReleaseTypePrimary> primaryType; // if set, matching this primary type
EnumSet<ReleaseTypeSecondary> secondaryTypes; // Matching all this (if any)
std::string releaseType; // If set, albums that has this release type
FindParameters& setClusters(const std::vector<ClusterId>& _clusters) { clusters = _clusters; return *this; }
FindParameters& setKeywords(const std::vector<std::string_view>& _keywords) { keywords = _keywords; return *this; }
FindParameters& setSortMethod(ReleaseSortMethod _sortMethod) { sortMethod = _sortMethod; return *this; }
@@ -79,6 +108,7 @@ namespace Database
excludedTrackArtistLinkTypes = _excludedTrackArtistLinkTypes;
return *this;
}
FindParameters& setReleaseType(std::string_view _releaseType) { releaseType = _releaseType; return *this; }
};
Release() = default;
@@ -116,18 +146,18 @@ namespace Database
std::vector<DiscInfo> getDiscs() const;
std::chrono::milliseconds getDuration() const;
Wt::WDateTime getLastWritten() const;
std::optional<ReleaseTypePrimary> getPrimaryType() const { return _primaryType; }
EnumSet<ReleaseTypeSecondary> getSecondaryTypes() const { return _secondaryTypes; }
std::string_view getArtistDisplayName() const { return _artistDisplayName; }
std::size_t getTracksCount() const;
std::vector<ObjectPtr<ReleaseType>> getReleaseTypes() const;
std::vector<std::string> getReleaseTypeNames() const;
// Setters
void setName(std::string_view name) { _name = name; }
void setMBID(const std::optional<UUID>& mbid) { _MBID = mbid ? mbid->getAsString() : ""; }
void setTotalDisc(std::optional<int> totalDisc) { _totalDisc = totalDisc; }
void setPrimaryType(std::optional<ReleaseTypePrimary> type) { _primaryType = type; }
void setSecondaryTypes(EnumSet<ReleaseTypeSecondary> types) { _secondaryTypes = types; }
void setArtistDisplayName(std::string_view name) { _artistDisplayName = name; }
void clearReleaseTypes();
void addReleaseType(ObjectPtr<ReleaseType> releaseType);
// Get the artists of this release
std::vector<ObjectPtr<Artist>> getArtists(TrackArtistLinkType type = TrackArtistLinkType::Artist) const;
@@ -135,17 +165,15 @@ namespace Database
bool hasVariousArtists() const;
std::vector<pointer> getSimilarReleases(std::optional<std::size_t> offset = {}, std::optional<std::size_t> count = {}) const;
template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, _name, "name");
Wt::Dbo::field(a, _MBID, "mbid");
Wt::Dbo::field(a, _totalDisc, "total_disc");
Wt::Dbo::field(a, _primaryType, "primary_type");
Wt::Dbo::field(a, _secondaryTypes, "secondary_types");
Wt::Dbo::field(a, _artistDisplayName, "artist_display_name");
Wt::Dbo::hasMany(a, _tracks, Wt::Dbo::ManyToOne, "release");
Wt::Dbo::hasMany(a, _releaseTypes, Wt::Dbo::ManyToMany, "release_release_type", "", Wt::Dbo::OnDeleteCascade);
}
private:
@@ -160,13 +188,10 @@ namespace Database
std::string _name;
std::string _MBID;
std::optional<int> _totalDisc{};
std::optional<ReleaseTypePrimary> _primaryType;
EnumSet<ReleaseTypeSecondary> _secondaryTypes;
std::string _artistDisplayName;
Wt::Dbo::collection<Wt::Dbo::ptr<Track>> _tracks; // Tracks in the release
Wt::Dbo::collection<Wt::Dbo::ptr<Track>> _tracks; // Tracks in the release
Wt::Dbo::collection<Wt::Dbo::ptr<ReleaseType>> _releaseTypes; // Release types
};
} // namespace Database
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2021 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 "database/IdType.hpp"
LMS_DECLARE_IDTYPE(ReleaseTypeId)
@@ -88,10 +88,6 @@ namespace Database {
std::vector<ObjectPtr<TrackListEntry>> getEntries(std::optional<Range> range = {}) const;
ObjectPtr<TrackListEntry> getEntryByTrackAndDateTime(ObjectPtr<Track> track, const Wt::WDateTime& dateTime) const;
RangeResults<ObjectPtr<Artist>> getArtists(const std::vector<ClusterId>& clusters, std::optional<TrackArtistLinkType> linkType, ArtistSortMethod sortMethod, std::optional<Range> range, bool& moreResults) const;
RangeResults<ObjectPtr<Release>> getReleases(const std::vector<ClusterId>& clusters, std::optional<Range> range, bool& moreResults) const;
RangeResults<ObjectPtr<Track>> getTracks(const std::vector<ClusterId>& clusters, std::optional<Range> range, bool& moreResults) const;
std::vector<TrackId> getTrackIds() const;
std::chrono::milliseconds getDuration() const;
@@ -220,30 +220,5 @@ namespace Database
Playlist, // user controlled playlists
Internal, // internal usage (current playqueue, history, ...)
};
// as defined in https://musicbrainz.org/doc/Release_Group/Type
enum class ReleaseTypePrimary
{
Album,
Single,
EP,
Broadcast,
Other,
};
enum class ReleaseTypeSecondary
{
Compilation,
Soundtrack,
Spokenword,
Interview,
Audiobook,
AudioDrama,
Live,
Remix,
DJMix,
Mixtape_Street,
Demo,
};
}
+1 -1
View File
@@ -40,7 +40,7 @@
#include "database/User.hpp"
template <typename T>
class ScopedEntity
class [[nodiscard]] ScopedEntity
{
public:
using IdType = typename T::IdType;
+41
View File
@@ -438,6 +438,47 @@ TEST_F(DatabaseFixture, Listen_getTopTracks)
}
}
TEST_F(DatabaseFixture, Listen_getTopTracks_artist)
{
ScopedTrack track{ session, "MyTrack" };
ScopedUser user{ session, "MyUser" };
ScopedArtist artist{ session, "MyArtist" };
const Wt::WDateTime dateTime{ Wt::WDate{2000, 1, 2}, Wt::WTime{12,0, 1} };
{
auto transaction{ session.createReadTransaction() };
auto tracks{ Listen::getTopTracks(session, user->getId(), artist->getId(), ScrobblingBackend::Internal, {}) };
EXPECT_EQ(tracks.moreResults, false);
ASSERT_EQ(tracks.results.size(), 0);
}
ScopedListen listen{ session, user.lockAndGet(), track.lockAndGet(), ScrobblingBackend::Internal, dateTime };
{
auto transaction{ session.createReadTransaction() };
auto tracks{ Listen::getTopTracks(session, user->getId(), artist->getId(), ScrobblingBackend::Internal, {}) };
EXPECT_EQ(tracks.moreResults, false);
ASSERT_EQ(tracks.results.size(), 0);
}
{
auto transaction{ session.createWriteTransaction() };
TrackArtistLink::create(session, track.get(), artist.get(), TrackArtistLinkType::Artist);
}
{
auto transaction{ session.createReadTransaction() };
auto tracks{ Listen::getTopTracks(session, user->getId(), artist->getId(), ScrobblingBackend::Internal, {}) };
EXPECT_EQ(tracks.moreResults, false);
ASSERT_EQ(tracks.results.size(), 1);
EXPECT_EQ(tracks.results[0], track.getId());
}
}
TEST_F(DatabaseFixture, Listen_getTopTrack_multi)
{
ScopedTrack track1{ session, "MyTrack1" };
+59 -6
View File
@@ -20,6 +20,7 @@
#include "Common.hpp"
using namespace Database;
using ScopedReleaseType = ScopedEntity<Database::ReleaseType>;
TEST_F(DatabaseFixture, Release)
{
@@ -559,26 +560,78 @@ TEST_F(DatabaseFixture, Release_getDiscCount)
}
}
TEST_F(DatabaseFixture, ReleaseType)
{
{
auto transaction{ session.createReadTransaction() };
ReleaseType::pointer res{ ReleaseType::find(session, "album") };
EXPECT_EQ(res, ReleaseType::pointer{});
}
ScopedReleaseType releaseType{ session, "album" };
{
auto transaction{ session.createReadTransaction() };
ReleaseType::pointer res{ ReleaseType::find(session, "album") };
EXPECT_EQ(res, releaseType.get());
}
}
TEST_F(DatabaseFixture, Release_releaseType)
{
ScopedRelease release{ session, "MyRelease" };
{
auto transaction{ session.createReadTransaction() };
EXPECT_EQ(release.get()->getPrimaryType(), std::nullopt);
EXPECT_EQ(release.get()->getSecondaryTypes(), EnumSet<ReleaseTypeSecondary> {});
EXPECT_EQ(release.get()->getReleaseTypes().size(), 0);
}
ScopedReleaseType releaseType{ session, "album" };
{
auto transaction{ session.createWriteTransaction() };
release.get().modify()->setPrimaryType({ ReleaseTypePrimary::Album });
release.get().modify()->setSecondaryTypes({ ReleaseTypeSecondary::Compilation });
release.get().modify()->addReleaseType(releaseType.get());
}
{
auto transaction{ session.createReadTransaction() };
EXPECT_EQ(release.get()->getPrimaryType(), ReleaseTypePrimary::Album);
EXPECT_TRUE(release.get()->getSecondaryTypes().contains(ReleaseTypeSecondary::Compilation));
const auto releaseTypes{ release.get()->getReleaseTypes() };
ASSERT_EQ(releaseTypes.size(), 1);
EXPECT_EQ(releaseTypes.front()->getId(), releaseType.getId());
const auto releaseTypeNames{ release.get()->getReleaseTypeNames() };
ASSERT_EQ(releaseTypeNames.size(), 1);
EXPECT_EQ(releaseTypeNames.front(), "album");
}
}
TEST_F(DatabaseFixture, Release_find_releaseType)
{
ScopedRelease release{ session, "MyRelease" };
{
auto transaction{ session.createReadTransaction() };
auto releases{ Release::find(session, Release::FindParameters{}.setReleaseType("Foo")).results };
EXPECT_EQ(releases.size(), 0);
}
ScopedReleaseType releaseType{ session, "album" };
{
auto transaction{ session.createWriteTransaction() };
release.get().modify()->addReleaseType(releaseType.get());
}
{
auto transaction{ session.createReadTransaction() };
auto releases{ Release::find(session, Release::FindParameters{}.setReleaseType("Foo")).results };
EXPECT_EQ(releases.size(), 0);
releases = Release::find(session, Release::FindParameters{}.setReleaseType("album")).results;
ASSERT_EQ(releases.size(), 1);
EXPECT_EQ(releases.front()->getId(), release.getId());
}
}
+3 -3
View File
@@ -226,15 +226,15 @@ namespace MetaData
{
track.recordingMBID = UUID::fromString(value);
}
else if (std::find(std::cbegin(_extraTags), std::cend(_extraTags), tag) != std::cend(_extraTags))
else if (std::find(std::cbegin(_userExtraTags), std::cend(_userExtraTags), tag) != std::cend(_userExtraTags))
{
const std::vector<std::string_view> tagValues{ StringUtils::splitString(value, "/,;") };
if (!tagValues.empty())
{
std::set<std::string> values;
std::vector<std::string> values;
std::transform(std::cbegin(tagValues), std::cend(tagValues), std::inserter(values, std::begin(values)), [](std::string_view v) { return std::string{ v }; });
track.tags[tag] = std::move(values);
track.userExtraTags[tag] = std::move(values);
}
}
}
+5 -10
View File
@@ -214,12 +214,7 @@ namespace MetaData
}
}
release->primaryType = getPropertyValueFirstMatchAs<MetaData::Release::PrimaryType>(tags, { "MUSICBRAINZ_ALBUMTYPE", "RELEASETYPE", "MUSICBRAINZ ALBUM TYPE", "MUSICBRAINZ/ALBUM TYPE" });
if (release->primaryType)
{
const auto secondaryTypes{ getPropertyValuesFirstMatchAs<MetaData::Release::SecondaryType>(tags, {"MUSICBRAINZ_ALBUMTYPE", "RELEASETYPE", "MUSICBRAINZ ALBUM TYPE", "MUSICBRAINZ/ALBUM TYPE"}) };
release->secondaryTypes.assign(std::cbegin(secondaryTypes), std::cend(secondaryTypes));
}
release->releaseTypes = getPropertyValuesFirstMatchAs<std::string>(tags, { "MUSICBRAINZ_ALBUMTYPE", "RELEASETYPE", "MUSICBRAINZ ALBUM TYPE", "MUSICBRAINZ/ALBUM TYPE" });
return release;
}
@@ -368,18 +363,18 @@ namespace MetaData
track.replayGain = StringUtils::readAs<float>(value);
else if (tag == "ARTIST")
track.artistDisplayName = value;
else if (std::find(std::cbegin(_extraTags), std::cend(_extraTags), tag) != std::cend(_extraTags))
else if (std::find(std::cbegin(_userExtraTags), std::cend(_userExtraTags), tag) != std::cend(_userExtraTags))
{
std::set<std::string> tagValues;
std::vector<std::string> tagValues;
for (std::string_view valueList : values)
{
const std::vector<std::string_view> splittedValues{ splitAndTrimString(valueList, "/,;") }; // handle possibily bad split tags
for (std::string_view value : splittedValues)
tagValues.insert(std::string{ value });
tagValues.push_back(std::string{ value });
}
if (!tagValues.empty())
track.tags[tag] = std::move(tagValues);
track.userExtraTags[tag] = std::move(tagValues);
}
}
+74 -125
View File
@@ -27,142 +27,91 @@
namespace MetaData::Utils
{
Wt::WDate
parseDate(std::string_view dateStr)
{
static constexpr const char* formats[]
{
"%Y-%m-%d",
"%Y/%m/%d",
};
Wt::WDate parseDate(std::string_view dateStr)
{
static constexpr const char* formats[]
{
"%Y-%m-%d",
"%Y/%m/%d",
};
for (const char* format : formats)
{
std::tm tm = {};
std::istringstream ss {std::string {dateStr}}; // TODO, remove extra copy here
ss >> std::get_time(&tm, format);
if (ss.fail())
continue;
for (const char* format : formats)
{
std::tm tm = {};
std::istringstream ss{ std::string {dateStr} }; // TODO, remove extra copy here
ss >> std::get_time(&tm, format);
if (ss.fail())
continue;
const Wt::WDate res
{
tm.tm_year + 1900, // years since 1900
tm.tm_mon + 1, // months since January [0, 11]
tm.tm_mday ? tm.tm_mday : 1 // day of the month [1, 31]
};
if (!res.isValid())
continue;
const Wt::WDate res
{
tm.tm_year + 1900, // years since 1900
tm.tm_mon + 1, // months since January [0, 11]
tm.tm_mday ? tm.tm_mday : 1 // day of the month [1, 31]
};
if (!res.isValid())
continue;
return res;
}
return res;
}
return {};
}
return {};
}
std::string_view
readStyleToString(ParserReadStyle readStyle)
{
switch (readStyle)
{
case ParserReadStyle::Fast: return "fast";
case ParserReadStyle::Average: return "average";
case ParserReadStyle::Accurate: return "accurate";
}
std::string_view readStyleToString(ParserReadStyle readStyle)
{
switch (readStyle)
{
case ParserReadStyle::Fast: return "fast";
case ParserReadStyle::Average: return "average";
case ParserReadStyle::Accurate: return "accurate";
}
throw LmsException {"Unknown read style"};
}
throw LmsException{ "Unknown read style" };
}
PerformerArtist
extractPerformerAndRole(std::string_view entry)
{
std::string_view artistName;
std::string_view role;
PerformerArtist extractPerformerAndRole(std::string_view entry)
{
std::string_view artistName;
std::string_view role;
std::size_t roleBegin {};
std::size_t roleEnd {};
std::size_t count {};
std::size_t roleBegin{};
std::size_t roleEnd{};
std::size_t count{};
for (std::size_t i {}; i < entry.size(); ++i)
{
std::size_t currentIndex {entry.size() - i - 1};
const char c {entry[currentIndex]};
for (std::size_t i{}; i < entry.size(); ++i)
{
std::size_t currentIndex{ entry.size() - i - 1 };
const char c{ entry[currentIndex] };
if (std::isspace(c))
continue;
if (std::isspace(c))
continue;
if (c == ')')
{
if (count++ == 0)
roleEnd = currentIndex;
}
else if (c == '(')
{
if (count == 0)
break;
if (c == ')')
{
if (count++ == 0)
roleEnd = currentIndex;
}
else if (c == '(')
{
if (count == 0)
break;
if (--count == 0)
{
roleBegin = currentIndex + 1;
role = StringUtils::stringTrim(entry.substr(roleBegin, roleEnd - roleBegin));
artistName = StringUtils::stringTrim(entry.substr(0, currentIndex));
break;
}
}
else if (count == 0)
break;
}
if (--count == 0)
{
roleBegin = currentIndex + 1;
role = StringUtils::stringTrim(entry.substr(roleBegin, roleEnd - roleBegin));
artistName = StringUtils::stringTrim(entry.substr(0, currentIndex));
break;
}
}
else if (count == 0)
break;
}
if (!roleEnd || !roleBegin)
artistName = StringUtils::stringTrim(entry);
return PerformerArtist {Artist {artistName}, std::string {role}};
}
}
namespace StringUtils
{
static bool iequals(std::string_view a, std::string_view b)
{
return std::equal(std::cbegin(a), std::cend(a),
std::cbegin(b), std::cend(b),
[](char a, char b) { return tolower(a) == tolower(b);}
);
}
template<>
std::optional<MetaData::Release::PrimaryType> readAs(std::string_view str)
{
str = stringTrim(str);
if (iequals(str, "album"))
return MetaData::Release::PrimaryType::Album;
else if (iequals(str, "single"))
return MetaData::Release::PrimaryType::Single;
else if (iequals(str, "EP"))
return MetaData::Release::PrimaryType::EP;
else if (iequals(str, "broadcast"))
return MetaData::Release::PrimaryType::Broadcast;
else if (iequals(str, "other"))
return MetaData::Release::PrimaryType::Other;
return std::nullopt;
}
template<>
std::optional<MetaData::Release::SecondaryType> readAs(std::string_view str)
{
str = stringTrim(str);
if (iequals(str, "compilation"))
return MetaData::Release::SecondaryType::Compilation;
else if (iequals(str, "soundtrack"))
return MetaData::Release::SecondaryType::Soundtrack;
else if (iequals(str, "live"))
return MetaData::Release::SecondaryType::Live;
else if (iequals(str, "demo"))
return MetaData::Release::SecondaryType::Demo;
return std::nullopt;
}
}
if (!roleEnd || !roleBegin)
artistName = StringUtils::stringTrim(entry);
return PerformerArtist{ Artist {artistName}, std::string {role} };
}
}
-10
View File
@@ -39,13 +39,3 @@ namespace MetaData::Utils
// format is "artist name (role)"
PerformerArtist extractPerformerAndRole(std::string_view entry);
}
namespace StringUtils
{
template<>
std::optional<MetaData::Release::PrimaryType> readAs(std::string_view str);
template<>
std::optional<MetaData::Release::SecondaryType> readAs(std::string_view str);
}
+10 -35
View File
@@ -23,18 +23,16 @@
#include <filesystem>
#include <map>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <vector>
#include <Wt/WDate.h>
#include "utils/EnumSet.hpp"
#include "utils/UUID.hpp"
namespace MetaData
{
using Tags = std::map<std::string /* type */, std::set<std::string> /* values */>;
using Tags = std::map<std::string /* type */, std::vector<std::string> /* values */>;
// Very simplified version of https://musicbrainz.org/doc/MusicBrainz_Database/Schema
@@ -52,43 +50,17 @@ namespace MetaData
struct Release
{
// see https://musicbrainz.org/doc/Release_Group/Type
enum class PrimaryType
{
Album,
Single,
EP,
Broadcast,
Other
};
enum class SecondaryType
{
Compilation,
Soundtrack,
Spokenword,
Interview,
Audiobook,
AudioDrama,
Live,
Remix,
DJMix,
Mixtape_Street,
Demo,
};
std::optional<UUID> mbid;
std::string name;
std::string artistDisplayName;
std::vector<Artist> artists;
std::optional<std::size_t> mediumCount;
std::optional<PrimaryType> primaryType;
EnumSet<SecondaryType> secondaryTypes;
std::vector<std::string> releaseTypes;
};
struct Medium
{
std::string type;
std::string type; // CD, etc.
std::string name;
std::optional<Release> release;
std::optional<std::size_t> position; // in release
@@ -103,7 +75,11 @@ namespace MetaData
std::string title;
std::optional<Medium> medium;
std::optional<std::size_t> position; // in medium
Tags tags;
std::vector<std::string> grouping;
std::vector<std::string> genres;
std::vector<std::string> moods;
std::vector<std::string> languages;
Tags userExtraTags;
std::chrono::milliseconds duration{};
std::size_t bitrate{};
Wt::WDate date;
@@ -131,10 +107,10 @@ namespace MetaData
virtual std::optional<Track> parse(const std::filesystem::path& p, bool debug = false) = 0;
void setExtraTags(const std::vector<std::string>& extraTags) { _extraTags = std::set(extraTags.cbegin(), extraTags.cend()); }
void setUserExtraTags(const std::vector<std::string>& extraTags) { _userExtraTags = std::vector(extraTags.cbegin(), extraTags.cend()); }
protected:
std::set<std::string> _extraTags;
std::vector<std::string> _userExtraTags;
};
enum class ParserType
@@ -151,4 +127,3 @@ namespace MetaData
};
std::unique_ptr<IParser> createParser(ParserType parserType, ParserReadStyle parserReadStyle);
} // namespace MetaData
-57
View File
@@ -115,60 +115,3 @@ TEST(MetaData, extractPerformerAndRole)
EXPECT_EQ(performer.role, testCase.expectedRole) << " str was '" << testCase.str << "'";
}
}
TEST(MetaData, primaryReleaseTypes)
{
using namespace MetaData;
struct TestCase
{
std::string str;
std::optional<Release::PrimaryType> result;
} testCases []
{
{ "", std::nullopt },
{ "album", Release::PrimaryType::Album },
{ "Album", Release::PrimaryType::Album },
{ " Album", Release::PrimaryType::Album },
{ "Album ", Release::PrimaryType::Album },
{ "ep", Release::PrimaryType::EP },
{ " ep ", Release::PrimaryType::EP },
{ "broadcast", Release::PrimaryType::Broadcast },
{ "single", Release::PrimaryType::Single },
{ "other", Release::PrimaryType::Other },
};
for (const TestCase& testCase : testCases)
{
std::optional<Release::PrimaryType> parsed {StringUtils::readAs<Release::PrimaryType>(testCase.str)};
EXPECT_EQ(parsed, testCase.result) << " str was '" << testCase.str << "'";
}
}
TEST(MetaData, secondaryReleaseTypes)
{
using namespace MetaData;
struct TestCase
{
std::string str;
std::optional<Release::SecondaryType> result;
} testCases []
{
{ "", std::nullopt },
{ "compilation", Release::SecondaryType::Compilation },
{ " compilation ", Release::SecondaryType::Compilation },
{ "soundtrack", Release::SecondaryType::Soundtrack },
{ "live", Release::SecondaryType::Live },
{ "demo", Release::SecondaryType::Demo },
};
for (const TestCase& testCase : testCases)
{
std::optional<Release::SecondaryType> parsed {StringUtils::readAs<Release::SecondaryType>(testCase.str)};
EXPECT_EQ(parsed, testCase.result) << " str was '" << testCase.str << "'";
}
}
+73 -12
View File
@@ -19,6 +19,8 @@
#include "CoverService.hpp"
#include <set>
#include "av/IAudioFile.hpp"
#include "database/Db.hpp"
@@ -30,13 +32,13 @@
#include "image/IRawImage.hpp"
#include "utils/IConfig.hpp"
#include "utils/ILogger.hpp"
#include "utils/Path.hpp"
#include "utils/Random.hpp"
#include "utils/String.hpp"
#include "utils/Utils.hpp"
namespace Cover
{
namespace
{
struct TrackInfo
@@ -85,6 +87,19 @@ namespace Cover
return res;
}
std::vector<std::string> constructArtistFileNames()
{
std::vector<std::string> res;
Service<IConfig>::get()->visitStrings("artist-image-file-names",
[&res](std::string_view fileName)
{
res.emplace_back(fileName);
}, { "artist" });
return res;
}
bool isFileSupported(const std::filesystem::path& file, const std::vector<std::filesystem::path>& extensions)
{
return (std::find(std::cbegin(extensions), std::cend(extensions), file.extension()) != std::cend(extensions));
@@ -106,7 +121,7 @@ namespace Cover
, _maxCacheSize{ Service<IConfig>::get()->getULong("cover-max-cache-size", 30) * 1000 * 1000 }
, _maxFileSize{ Service<IConfig>::get()->getULong("cover-max-file-size", 10) * 1000 * 1000 }
, _preferredFileNames{ constructPreferredFileNames() }
, _artistFileNames{ constructArtistFileNames() }
{
setJpegQuality(Service<IConfig>::get()->getULong("cover-jpeg-quality", 75));
@@ -196,7 +211,7 @@ namespace Cover
}
}
std::unique_ptr<IEncodedImage> CoverService::getFromDirectory(const std::filesystem::path& directory, ImageSize width) const
std::unique_ptr<IEncodedImage> CoverService::getFromDirectory(const std::filesystem::path& directory, ImageSize width, const std::vector<std::string>& preferredFileNames, bool allowPickRandom) const
{
const std::multimap<std::string, std::filesystem::path> coverPaths{ getCoverPaths(directory) };
@@ -216,19 +231,21 @@ namespace Cover
std::unique_ptr<IEncodedImage> image;
for (std::string_view filename : _preferredFileNames)
for (std::string_view filename : preferredFileNames)
{
image = tryLoadImageFromFilename(filename);
if (image)
return image;
}
// Just pick one
for (const auto& [filename, coverPath] : coverPaths)
if (allowPickRandom)
{
image = getFromCoverFile(coverPath, width);
if (image)
return image;
for (const auto& [filename, coverPath] : coverPaths)
{
image = getFromCoverFile(coverPath, width);
if (image)
return image;
}
}
return image;
@@ -269,7 +286,7 @@ namespace Cover
if (std::filesystem::file_size(filePath, ec) > _maxFileSize && !ec)
{
LMS_LOG(COVER, INFO, "Cover file '" << filePath.string() << " is too big (" << std::filesystem::file_size(filePath, ec) << "), limit is " << _maxFileSize);
LMS_LOG(COVER, INFO, "Image file '" << filePath.string() << " is too big (" << std::filesystem::file_size(filePath, ec) << "), limit is " << _maxFileSize);
return false;
}
@@ -341,7 +358,7 @@ namespace Cover
if (!cover && trackInfo->isMultiDisc)
{
if (trackInfo->trackPath.parent_path().has_parent_path())
cover = getFromDirectory(trackInfo->trackPath.parent_path().parent_path(), width);
cover = getFromDirectory(trackInfo->trackPath.parent_path().parent_path(), width, _preferredFileNames, true);
}
}
@@ -389,7 +406,7 @@ namespace Cover
if (const std::optional<ReleaseInfo> releaseInfo{ getReleaseInfo() })
{
cover = getFromDirectory(releaseInfo->releaseDirectory, width);
cover = getFromDirectory(releaseInfo->releaseDirectory, width, _preferredFileNames, true);
if (!cover)
cover = getFromTrack(session, releaseInfo->firstTrackId, width, false /* no release fallback */);
}
@@ -400,6 +417,50 @@ namespace Cover
return cover;
}
std::shared_ptr<IEncodedImage> CoverService::getFromArtist(Database::ArtistId artistId, ImageSize width)
{
using namespace Database;
const CacheEntryDesc cacheEntryDesc{ artistId, width };
std::shared_ptr<IEncodedImage> artistImage{ loadFromCache(cacheEntryDesc) };
if (artistImage)
return artistImage;
std::set<std::filesystem::path> parentPaths;
{
Session& session{ _db.getTLSSession() };
auto transaction{ session.createReadTransaction() };
Track::find(session, Track::FindParameters{}.setArtist(artistId), [&](const Track::pointer& track)
{
parentPaths.insert(track->getPath().parent_path());
});
}
if (parentPaths.size() == 1)
artistImage = getFromDirectory(parentPaths.begin()->parent_path(), width, _artistFileNames, false);
else if (parentPaths.size() > 1)
{
const std::filesystem::path longestCommonPath{ PathUtils::getLongestCommonPath(std::cbegin(parentPaths), std::cend(parentPaths)) };
artistImage = getFromDirectory(longestCommonPath, width, _artistFileNames, false);
}
if (!artistImage)
{
for (const std::filesystem::path& parentPath : parentPaths)
{
artistImage = getFromDirectory(parentPath, width, _artistFileNames, false);
if (artistImage)
break;
}
}
if (artistImage)
saveToCache(cacheEntryDesc, artistImage);
return artistImage;
}
void CoverService::flushCache()
{
std::unique_lock lock{ _cacheMutex };
@@ -47,7 +47,7 @@ namespace Cover
{
struct CacheEntryDesc
{
std::variant<Database::TrackId, Database::ReleaseId> id;
std::variant<Database::ArtistId, Database::ReleaseId, Database::TrackId> id;
std::size_t size;
bool operator==(const CacheEntryDesc& other) const
@@ -92,6 +92,7 @@ namespace Cover
private:
std::shared_ptr<Image::IEncodedImage> getFromTrack(Database::TrackId trackId, Image::ImageSize width) override;
std::shared_ptr<Image::IEncodedImage> getFromRelease(Database::ReleaseId releaseId, Image::ImageSize width) override;
std::shared_ptr<Image::IEncodedImage> getFromArtist(Database::ArtistId artistId, Image::ImageSize width) override;
std::shared_ptr<Image::IEncodedImage> getDefault(Image::ImageSize width) override;
void flushCache() override;
void setJpegQuality(unsigned quality) override;
@@ -102,7 +103,7 @@ namespace Cover
std::unique_ptr<Image::IEncodedImage> getFromTrack(const std::filesystem::path& path, Image::ImageSize width) const;
std::multimap<std::string, std::filesystem::path> getCoverPaths(const std::filesystem::path& directoryPath) const;
std::unique_ptr<Image::IEncodedImage> getFromDirectory(const std::filesystem::path& directory, Image::ImageSize width) const;
std::unique_ptr<Image::IEncodedImage> getFromDirectory(const std::filesystem::path& directory, Image::ImageSize width, const std::vector<std::string>& preferredFileNames, bool allowPickRandom) const;
std::unique_ptr<Image::IEncodedImage> getFromSameNamedFile(const std::filesystem::path& filePath, Image::ImageSize width) const;
bool checkCoverFile(const std::filesystem::path& directoryPath) const;
@@ -124,6 +125,7 @@ namespace Cover
static inline const std::vector<std::filesystem::path> _fileExtensions{ ".jpg", ".jpeg", ".png", ".bmp" }; // TODO parametrize
const std::size_t _maxFileSize;
const std::vector<std::string> _preferredFileNames;
const std::vector<std::string> _artistFileNames;
unsigned _jpegQuality;
};
@@ -22,6 +22,7 @@
#include <filesystem>
#include <memory>
#include "database/ArtistId.hpp"
#include "database/ReleaseId.hpp"
#include "database/TrackId.hpp"
#include "image/IEncodedImage.hpp"
@@ -40,6 +41,7 @@ namespace Cover
virtual std::shared_ptr<Image::IEncodedImage> getFromTrack(Database::TrackId trackId, Image::ImageSize width) = 0;
virtual std::shared_ptr<Image::IEncodedImage> getFromRelease(Database::ReleaseId releaseId, Image::ImageSize width) = 0;
virtual std::shared_ptr<Image::IEncodedImage> getFromArtist(Database::ArtistId artistId, Image::ImageSize width) = 0;
virtual std::shared_ptr<Image::IEncodedImage> getDefault(Image::ImageSize width) = 0;
@@ -114,84 +114,29 @@ namespace Scanner
return artists;
}
ReleaseTypePrimary convertReleaseTypePrimary(MetaData::Release::PrimaryType type)
ReleaseType::pointer getOrCreateReleaseType(Session& session, std::string_view name)
{
switch (type)
{
case MetaData::Release::PrimaryType::Album: return ReleaseTypePrimary::Album;
case MetaData::Release::PrimaryType::Single: return ReleaseTypePrimary::Single;
case MetaData::Release::PrimaryType::EP: return ReleaseTypePrimary::EP;
case MetaData::Release::PrimaryType::Broadcast: return ReleaseTypePrimary::Broadcast;
case MetaData::Release::PrimaryType::Other: return ReleaseTypePrimary::Other;
}
ReleaseType::pointer releaseType{ ReleaseType::find(session, name) };
if (!releaseType)
releaseType = session.create<ReleaseType>(name);
return ReleaseTypePrimary::Other;
return releaseType;
}
EnumSet<ReleaseTypeSecondary> convertReleaseTypesSecondary(EnumSet<MetaData::Release::SecondaryType> types)
{
EnumSet<ReleaseTypeSecondary> res;
for (MetaData::Release::SecondaryType type : types)
{
switch (type)
{
case MetaData::Release::SecondaryType::Compilation:
res.insert(ReleaseTypeSecondary::Compilation);
break;
case MetaData::Release::SecondaryType::Soundtrack:
res.insert(ReleaseTypeSecondary::Soundtrack);
break;
case MetaData::Release::SecondaryType::Spokenword:
res.insert(ReleaseTypeSecondary::Spokenword);
break;
case MetaData::Release::SecondaryType::Interview:
res.insert(ReleaseTypeSecondary::Interview);
break;
case MetaData::Release::SecondaryType::Audiobook:
res.insert(ReleaseTypeSecondary::Audiobook);
break;
case MetaData::Release::SecondaryType::AudioDrama:
res.insert(ReleaseTypeSecondary::AudioDrama);
break;
case MetaData::Release::SecondaryType::Live:
res.insert(ReleaseTypeSecondary::Live);
break;
case MetaData::Release::SecondaryType::Remix:
res.insert(ReleaseTypeSecondary::Remix);
break;
case MetaData::Release::SecondaryType::DJMix:
res.insert(ReleaseTypeSecondary::DJMix);
break;
case MetaData::Release::SecondaryType::Mixtape_Street:
res.insert(ReleaseTypeSecondary::Mixtape_Street);
break;
case MetaData::Release::SecondaryType::Demo:
res.insert(ReleaseTypeSecondary::Demo);
break;
}
}
return res;
}
void updateReleaseIfNeeded(Release::pointer release, const MetaData::Release& releaseInfo)
void updateReleaseIfNeeded(Session& session, Release::pointer release, const MetaData::Release& releaseInfo)
{
if (release->getName() != releaseInfo.name)
release.modify()->setName(releaseInfo.name);
if (release->getTotalDisc() != releaseInfo.mediumCount)
release.modify()->setTotalDisc(releaseInfo.mediumCount);
if (releaseInfo.primaryType)
{
const ReleaseTypePrimary primaryType{ convertReleaseTypePrimary(*releaseInfo.primaryType) };
if (release->getPrimaryType() != primaryType)
release.modify()->setPrimaryType(primaryType);
}
const EnumSet<ReleaseTypeSecondary> secondaryTypes{ convertReleaseTypesSecondary(releaseInfo.secondaryTypes) };
if (release->getSecondaryTypes() != secondaryTypes)
release.modify()->setSecondaryTypes(secondaryTypes);
if (release->getArtistDisplayName() != releaseInfo.artistDisplayName)
release.modify()->setArtistDisplayName(releaseInfo.artistDisplayName);
if (release->getReleaseTypeNames() != releaseInfo.releaseTypes)
{
release.modify()->clearReleaseTypes();
for (std::string_view releaseType : releaseInfo.releaseTypes)
release.modify()->addReleaseType(getOrCreateReleaseType(session, releaseType));
}
}
Release::pointer getOrCreateRelease(Session& session, const MetaData::Release& releaseInfo, const std::filesystem::path& expectedReleaseDirectory)
@@ -205,7 +150,7 @@ namespace Scanner
if (!release)
release = session.create<Release>(releaseInfo.name, releaseInfo.mbid);
updateReleaseIfNeeded(release, releaseInfo);
updateReleaseIfNeeded(session, release, releaseInfo);
return release;
}
@@ -226,7 +171,7 @@ namespace Scanner
if (!release)
release = session.create<Release>(releaseInfo.name);
updateReleaseIfNeeded(release, releaseInfo);
updateReleaseIfNeeded(session, release, releaseInfo);
return release;
}
@@ -279,10 +224,7 @@ namespace Scanner
void ScanStepScanFiles::process(ScanContext& context)
{
std::vector<std::string> tagsToParse{ _tagsToParse };
tagsToParse.insert(std::end(tagsToParse), std::cbegin(_settings.extraTags), std::cend(_settings.extraTags));
_metadataParser->setExtraTags(tagsToParse);
_metadataParser->setUserExtraTags(_extraTagsToParse);
context.currentStepStats.totalElems = context.stats.filesScanned;
@@ -488,7 +430,7 @@ namespace Scanner
track.modify()->setTotalTrack(trackInfo->medium ? trackInfo->medium->trackCount : std::nullopt);
track.modify()->setReleaseReplayGain(trackInfo->medium ? trackInfo->medium->replayGain : std::nullopt);
track.modify()->setDiscSubtitle(trackInfo->medium ? trackInfo->medium->name : "");
track.modify()->setClusters(getOrCreateClusters(dbSession, trackInfo->tags));
track.modify()->setClusters(getOrCreateClusters(dbSession, trackInfo->userExtraTags));
track.modify()->setLastWriteTime(lastWriteTime);
track.modify()->setName(title);
track.modify()->setDuration(trackInfo->duration);
@@ -41,6 +41,6 @@ namespace Scanner
void scanAudioFile(const std::filesystem::path& file, ScanContext& context);
std::unique_ptr<MetaData::IParser> _metadataParser;
const std::vector<std::string> _tagsToParse{ "GENRE", "MOOD", "LANGUAGE", "ALBUMGROUPING" };
const std::vector<std::string> _extraTagsToParse{ "GENRE", "MOOD", "LANGUAGE", "ALBUMGROUPING" };
};
}
@@ -214,5 +214,20 @@ namespace Scrobbling
res = Database::Listen::getTopTracks(session, userId, *backend, clusterIds, range);
return res;
}
ScrobblingService::TrackContainer ScrobblingService::getTopTracks(UserId userId, Database::ArtistId artistId, const std::vector<ClusterId>& clusterIds, Range range)
{
TrackContainer res;
const auto backend{ getUserBackend(userId) };
if (!backend)
return res;
Session& session{ _db.getTLSSession() };
auto transaction{ session.createReadTransaction() };
res = Database::Listen::getTopTracks(session, userId, artistId, *backend, clusterIds, range);
return res;
}
} // ns Scrobbling
@@ -52,6 +52,7 @@ namespace Scrobbling
ArtistContainer getTopArtists(Database::UserId userId, const std::vector<Database::ClusterId>& clusterIds, std::optional<Database::TrackArtistLinkType> linkType, Database::Range range) override;
ReleaseContainer getTopReleases(Database::UserId userId, const std::vector<Database::ClusterId>& clusterIds, Database::Range range) override;
TrackContainer getTopTracks(Database::UserId userId, const std::vector<Database::ClusterId>& clusterIds, Database::Range range) override;
TrackContainer getTopTracks(Database::UserId userId, Database::ArtistId artistId, const std::vector<Database::ClusterId>& clusterIds, Database::Range range) override;
std::optional<Database::ScrobblingBackend> getUserBackend(Database::UserId userId);
@@ -71,6 +71,7 @@ namespace Scrobbling
virtual ArtistContainer getTopArtists(Database::UserId userId, const std::vector<Database::ClusterId>& clusterIds, std::optional<Database::TrackArtistLinkType> linkType, Database::Range) = 0;
virtual ReleaseContainer getTopReleases(Database::UserId userId, const std::vector<Database::ClusterId>& clusterIds, Database::Range range) = 0;
virtual TrackContainer getTopTracks(Database::UserId userId, const std::vector<Database::ClusterId>& clusterIds, Database::Range range) = 0;
virtual TrackContainer getTopTracks(Database::UserId userId, Database::ArtistId artistId, const std::vector<Database::ClusterId>& clusterIds, Database::Range range) = 0;
};
std::unique_ptr<IScrobblingService> createScrobblingService(boost::asio::io_service& ioService, Database::Db& db);
+1 -1
View File
@@ -31,7 +31,7 @@ namespace API::Subsonic
};
static inline constexpr ProtocolVersion defaultServerProtocolVersion{ 1, 16, 0 };
static inline constexpr std::string_view serverVersion{ "4" };
static inline constexpr std::string_view serverVersion{ "5" };
}
namespace StringUtils
+1 -1
View File
@@ -182,7 +182,7 @@ namespace API::Subsonic
{"/getAlbumInfo2", {handleNotImplemented}},
{"/getSimilarSongs", {handleGetSimilarSongsRequest}},
{"/getSimilarSongs2", {handleGetSimilarSongs2Request}},
{"/getTopSongs", {handleNotImplemented}},
{"/getTopSongs", {handleGetTopSongs}},
// Album/song lists
{"/getAlbumList", {handleGetAlbumListRequest}},
@@ -26,6 +26,7 @@
#include "database/Track.hpp"
#include "database/User.hpp"
#include "services/recommendation/IRecommendationService.hpp"
#include "services/scrobbling/IScrobblingService.hpp"
#include "utils/ILogger.hpp"
#include "utils/Random.hpp"
#include "utils/Service.hpp"
@@ -480,4 +481,34 @@ namespace API::Subsonic
return handleGetSimilarSongsRequestCommon(context, true /* id3 */);
}
Response handleGetTopSongs(RequestContext& context)
{
// Mandatory params
std::string_view artistName{ getMandatoryParameterAs<std::string_view>(context.parameters, "artist") };
std::size_t count{ getParameterAs<std::size_t>(context.parameters, "count").value_or(50) };
if (count > defaultMaxCountSize)
throw ParameterValueTooHighGenericError{ "count", defaultMaxCountSize };
auto transaction{ context.dbSession.createReadTransaction() };
const auto artists{ Artist::find(context.dbSession, artistName) };
if (artists.size() != 1)
throw RequestedDataNotFoundError{};
User::pointer user{ User::find(context.dbSession, context.userId) };
if (!user)
throw UserNotAuthorizedError{};
Response response{ Response::createOkResponse(context.serverProtocolVersion) };
Response::Node& topSongs{ response.createNode("topSongs") };
const auto trackIds{ Service<Scrobbling::IScrobblingService>::get()->getTopTracks(context.userId, artists.front()->getId(), {}, Database::Range{ 0, count }) };
for (const TrackId trackId : trackIds.results)
{
if (Track::pointer track{ Track::find(context.dbSession, trackId) })
topSongs.addArrayChild("song", createSongNode(context, track, user));
}
return response;
}
}
@@ -36,4 +36,5 @@ namespace API::Subsonic
Response handleGetArtistInfo2Request(RequestContext& context);
Response handleGetSimilarSongsRequest(RequestContext& context);
Response handleGetSimilarSongs2Request(RequestContext& context);
Response handleGetTopSongs(RequestContext& context);
}
@@ -269,13 +269,9 @@ namespace API::Subsonic
else if (releaseId)
cover = Service<Cover::ICoverService>::get()->getFromRelease(*releaseId, size);
else if (artistId)
{
// TODO handle a placeholder for artists
response.setStatus(404);
return;
}
cover = Service<Cover::ICoverService>::get()->getFromArtist(*artistId, size);
if (!cover && context.enableDefaultCover)
if (!cover && context.enableDefaultCover && !artistId)
cover = Service<Cover::ICoverService>::get()->getDefault(size);
if (!cover)
@@ -89,7 +89,7 @@ namespace API::Subsonic
std::vector<TrackId> trackIds{ getMultiParametersAs<TrackId>(context.parameters, "songId") };
if (!name && !id)
throw RequiredParameterMissingError{ "name or id" };
throw RequiredParameterMissingError{ "name or playlistId" };
auto transaction{ context.dbSession.createWriteTransaction() };
@@ -125,7 +125,16 @@ namespace API::Subsonic
context.dbSession.create<TrackListEntry>(track, tracklist);
}
return Response::createOkResponse(context.serverProtocolVersion);
Response response{ Response::createOkResponse(context.serverProtocolVersion) };
Response::Node playlistNode{ createPlaylistNode(tracklist, context.dbSession) };
auto entries{ tracklist->getEntries() };
for (const TrackListEntry::pointer& entry : entries)
playlistNode.addArrayChild("entry", createSongNode(context, entry->getTrack(), user));
response.addNode("playlist", std::move(playlistNode));
return response;
}
Response handleUpdatePlaylistRequest(RequestContext& context)
+14 -43
View File
@@ -37,43 +37,6 @@ namespace API::Subsonic
{
using namespace Database;
namespace
{
std::string_view toString(ReleaseTypePrimary releaseType)
{
switch (releaseType)
{
case ReleaseTypePrimary::Album: return "album";
case ReleaseTypePrimary::Broadcast: return "broadcast";
case ReleaseTypePrimary::EP: return "ep";
case ReleaseTypePrimary::Single: return "single";
case ReleaseTypePrimary::Other: return "other";
}
return "unknown";
}
std::string_view toString(ReleaseTypeSecondary releaseType)
{
switch (releaseType)
{
case ReleaseTypeSecondary::Audiobook: return "audiobook";
case ReleaseTypeSecondary::AudioDrama: return "audiodrama";
case ReleaseTypeSecondary::Compilation: return "compilation";
case ReleaseTypeSecondary::Demo: return "demo";
case ReleaseTypeSecondary::DJMix: return "djmix";
case ReleaseTypeSecondary::Interview: return "interview";
case ReleaseTypeSecondary::Live: return "live";
case ReleaseTypeSecondary::Mixtape_Street: return "mixtapestreet";
case ReleaseTypeSecondary::Remix: return "remix";
case ReleaseTypeSecondary::Soundtrack: return "soundtrack";
case ReleaseTypeSecondary::Spokenword: return "soundtrack";
}
return "unknown";
}
}
Response::Node createAlbumNode(RequestContext& context, const Release::pointer& release, const User::pointer& user, bool id3)
{
Response::Node albumNode;
@@ -192,12 +155,20 @@ namespace API::Subsonic
albumNode.setAttribute("originalReleaseDate", originalReleaseDate.isValid() ? StringUtils::toISO8601String(originalReleaseDate) : "");
}
albumNode.setAttribute("isCompilation", release->getSecondaryTypes().contains(ReleaseTypeSecondary::Compilation));
albumNode.createEmptyArrayValue("releaseTypes");
if (auto releaseType{ release->getPrimaryType() })
albumNode.addArrayValue("releaseTypes", toString(*releaseType));
for (const ReleaseTypeSecondary releaseType : release->getSecondaryTypes())
albumNode.addArrayValue("releaseTypes", toString(releaseType));
{
bool isCompilation{};
albumNode.createEmptyArrayValue("releaseTypes");
for (std::string_view releaseType : release->getReleaseTypeNames())
{
if (StringUtils::stringCaseInsensitiveEqual(releaseType, "compilation"))
isCompilation = true;
albumNode.addArrayValue("releaseTypes", releaseType);
}
// TODO: the Compilation tag does not have the same meaning
albumNode.setAttribute("isCompilation", isCompilation);
}
// disc titles
albumNode.createEmptyArrayChild("discTitles");
@@ -79,6 +79,7 @@ namespace API::Subsonic
artistNode.setAttribute("id", idToString(artist->getId()));
artistNode.setAttribute("name", artist->getName());
artistNode.setAttribute("coverArt", idToString(artist->getId()));
if (id3)
{
@@ -19,6 +19,7 @@
#include "Playlist.hpp"
#include "database/Track.hpp"
#include "database/TrackList.hpp"
#include "database/User.hpp"
#include "SubsonicId.hpp"
@@ -41,6 +42,9 @@ namespace API::Subsonic
playlistNode.setAttribute("created", reportedDummyDate);
playlistNode.setAttribute("owner", tracklist->getUser()->getLoginName());
if (const auto entry {tracklist->getEntry(0)})
playlistNode.setAttribute("coverArt", idToString(entry->getTrack()->getId()));
return playlistNode;
}
}
+17
View File
@@ -162,4 +162,21 @@ namespace PathUtils
return false;
}
std::filesystem::path getLongestCommonPath(const std::filesystem::path& path1, const std::filesystem::path& path2)
{
std::filesystem::path longestCommonPath;
auto it1{ path1.begin() };
auto it2{ path2.begin() };
while (it1 != std::cend(path1) && it2 != std::cend(path2) && *it1 == *it2)
{
longestCommonPath /= *it1;
++it1;
++it2;
}
return longestCommonPath;
}
} // ns PathUtils
+28 -12
View File
@@ -28,23 +28,39 @@
namespace PathUtils
{
std::uint32_t computeCrc32(const std::filesystem::path& p);
std::uint32_t computeCrc32(const std::filesystem::path& p);
// Make sure the given path is a directory
// Create it if needed
bool ensureDirectory(const std::filesystem::path& dir);
// Make sure the given path is a directory
// Create it if needed
bool ensureDirectory(const std::filesystem::path& dir);
// Get the last write time since Epoch
Wt::WDateTime getLastWriteTime(const std::filesystem::path& dir);
// Get the last write time since Epoch
Wt::WDateTime getLastWriteTime(const std::filesystem::path& dir);
// returns false if aborted by user
bool exploreFilesRecursive(const std::filesystem::path& directory, std::function<bool(std::error_code, const std::filesystem::path&)> cb, const std::filesystem::path* excludeDirFileName = {});
// returns false if aborted by user
bool exploreFilesRecursive(const std::filesystem::path& directory, std::function<bool(std::error_code, const std::filesystem::path&)> cb, const std::filesystem::path* excludeDirFileName = {});
// Check if file's extension is one of provided extensions
bool hasFileAnyExtension(const std::filesystem::path& file, const std::vector<std::filesystem::path>& extensions);
// Check if file's extension is one of provided extensions
bool hasFileAnyExtension(const std::filesystem::path& file, const std::vector<std::filesystem::path>& extensions);
// Check if a path is within a directory (excludeDirFileName is a relative can be used to exclude a whole directory and its subdirectory, must not have parent_path)
bool isPathInRootPath(const std::filesystem::path& path, const std::filesystem::path& rootPath, const std::filesystem::path* excludeDirFileName = {});
// Check if a path is within a directory (excludeDirFileName is a relative can be used to exclude a whole directory and its subdirectory, must not have parent_path)
bool isPathInRootPath(const std::filesystem::path& path, const std::filesystem::path& rootPath, const std::filesystem::path* excludeDirFileName = {});
std::filesystem::path getLongestCommonPath(const std::filesystem::path& path1, const std::filesystem::path& path2);
template <typename Iterator>
std::filesystem::path getLongestCommonPath(Iterator first, Iterator last)
{
std::filesystem::path longestCommonPath;
if (first == last)
return longestCommonPath;
longestCommonPath = *first++;
while (first != last)
longestCommonPath = PathUtils::getLongestCommonPath(*first++, longestCommonPath);
return longestCommonPath;
}
}
+1
View File
@@ -2,6 +2,7 @@ include(GoogleTest)
add_executable(test-utils
EnumSet.cpp
Path.cpp
RecursiveSharedMutex.cpp
String.cpp
Utils.cpp
+78
View File
@@ -0,0 +1,78 @@
/*
* 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 <gtest/gtest.h>
#include "utils/Path.hpp"
TEST(Path, getLongestCommonPath)
{
using namespace PathUtils;
struct TestCase
{
std::filesystem::path path1;
std::filesystem::path path2;
std::filesystem::path expectedCommonPath;
};
TestCase tests[]
{
{"foo.txt", "/foo/foo.txt", ""},
{"/", "/file.txt", "/"},
{"/foo/bar/file1.txt", "/foo/bar/file2.txt", "/foo/bar"},
{"/foo/bar/file.txt", "/foo/bar/file.txt", "/foo/bar/file.txt"},
{"/dir1/file.txt", "/dir2/file.txt", "/"},
{"/prefix/folder/file.txt", "/prefix/folder/subfolder/file.txt", "/prefix/folder"},
};
for (const TestCase& test : tests)
{
EXPECT_EQ(PathUtils::getLongestCommonPath(test.path1, test.path2), test.expectedCommonPath);
}
}
TEST(Path, getLongestCommonPathIterator)
{
using namespace PathUtils;
struct TestCase
{
std::vector<std::filesystem::path> paths;
std::filesystem::path expectedCommonPath;
};
TestCase tests[]
{
{{}, ""},
{{"/"}, "/"},
{{"/foo", "/bar"}, "/"},
{{"/foo/bar/file1.txt", "/foo/bar/file2.txt"}, "/foo/bar"},
{{"/foo", "/foo/"}, "/foo"},
{{"/foo/", "/foo/"}, "/foo/"},
{{"/foo/", "/foo/", "/bar"}, "/"},
{{"/foo/", "/foo/", "/foo/bar"}, "/foo"},
};
for (const TestCase& test : tests)
{
EXPECT_EQ(PathUtils::getLongestCommonPath(std::cbegin(test.paths), std::cend(test.paths)), test.expectedCommonPath);
}
}
+1 -1
View File
@@ -38,6 +38,7 @@ add_executable(lms
ui/explore/ReleaseHelpers.cpp
ui/explore/ReleasesView.cpp
ui/explore/ReleaseView.cpp
ui/explore/ReleaseTypes.cpp
ui/explore/SearchView.cpp
ui/explore/TrackCollector.cpp
ui/explore/TrackListHelpers.cpp
@@ -70,4 +71,3 @@ target_link_libraries(lms PRIVATE
)
install(TARGETS lms DESTINATION bin)
+1 -1
View File
@@ -292,7 +292,7 @@ int main(int argc, char* argv[])
scannerService->getEvents().scanComplete.connect([&]
{
// Flush cover cache even if no changes:
// covers may be external files that changed and we don't keep track of them
// covers may be external files that changed and we don't keep track of them for now (but we should)
coverService->flushCache();
});
+6 -18
View File
@@ -69,18 +69,6 @@ namespace UserInterface
}
}
bool Artist::ReleaseType::operator<(const ReleaseType& other) const
{
if (!primaryType && other.primaryType)
return false;
else if (primaryType && !other.primaryType)
return true;
else if (*primaryType == *other.primaryType)
return secondaryTypes.getBitfield() < other.secondaryTypes.getBitfield();
else
return static_cast<int>(*primaryType) < static_cast<int>(*other.primaryType);
}
Artist::Artist(Filters& filters, PlayQueueController& controller)
: Template{ Wt::WString::tr("Lms.Explore.Artist.template") }
, _filters{ filters }
@@ -217,12 +205,12 @@ namespace UserInterface
const auto releases{ Release::findIds(LmsApp->getDbSession(), params) };
if (!releases.results.empty())
{
// first pass: gather all ids and sort by type
// first pass: gather all ids and sort by release type
for (const ReleaseId releaseId : releases.results)
{
const Database::Release::pointer release{ Database::Release::find(LmsApp->getDbSession(), releaseId) };
ReleaseType releaseType{ release->getPrimaryType(), release->getSecondaryTypes() };
ReleaseType releaseType{ parseReleaseType(release->getReleaseTypeNames())};
_releaseContainers[releaseType].releases.push_back(releaseId);
}
@@ -232,11 +220,11 @@ namespace UserInterface
{
Wt::WTemplate* releaseContainer{ releaseContainers->addNew<Wt::WTemplate>(Wt::WString::tr("Lms.Explore.Artist.template.release-container")) };
if (releaseType.primaryType)
releaseContainer->bindString("release-type", ReleaseHelpers::buildReleaseTypeString(*releaseType.primaryType, releaseType.secondaryTypes));
if (releaseType.primaryType || !releaseType.customTypes.empty())
releaseContainer->bindString("release-type", ReleaseHelpers::buildReleaseTypeString(releaseType));
else
releaseContainer->bindString("release-type", Wt::WString::tr("Lms.Explore.releases")); // fallback when not tagged with MB
releaseContainer->bindString("release-type", Wt::WString::tr("Lms.Explore.releases")); // fallback when not tagged with MB or custom type
releases.container = releaseContainer->bindNew<InfiniteScrollingContainer>("releases", Wt::WString::tr("Lms.Explore.Releases.template.container"));
releases.container->onRequestElements.connect(this, [this, &releases = releases]
{
+37 -44
View File
@@ -24,63 +24,56 @@
#include "database/ArtistId.hpp"
#include "database/Object.hpp"
#include "database/ReleaseId.hpp"
#include "database/Types.hpp"
#include "utils/EnumSet.hpp"
#include "common/Template.hpp"
#include "ReleaseTypes.hpp"
namespace Database
{
class Artist;
class Release;
class Artist;
class Release;
}
namespace UserInterface
{
class Filters;
class PlayQueueController;
class InfiniteScrollingContainer;
class Filters;
class PlayQueueController;
class InfiniteScrollingContainer;
class Artist : public Template
{
public:
Artist(Filters& filters, PlayQueueController& controller);
class Artist : public Template
{
public:
Artist(Filters& filters, PlayQueueController& controller);
private:
void refreshView();
void refreshReleases();
void refreshAppearsOnReleases();
void refreshNonReleaseTracks();
void refreshSimilarArtists(const std::vector<Database::ArtistId>& similarArtistsId);
void refreshLinks(const Database::ObjectPtr<Database::Artist>& artist);
private:
void refreshView();
void refreshReleases();
void refreshAppearsOnReleases();
void refreshNonReleaseTracks();
void refreshSimilarArtists(const std::vector<Database::ArtistId>& similarArtistsId);
void refreshLinks(const Database::ObjectPtr<Database::Artist>& artist);
struct ReleaseContainer;
void addSomeReleases(ReleaseContainer& releaseContainer);
bool addSomeNonReleaseTracks();
static constexpr std::size_t _releasesBatchSize {6};
static constexpr std::size_t _tracksBatchSize {6};
static constexpr std::size_t _tracksMaxCount {160};
struct ReleaseContainer;
void addSomeReleases(ReleaseContainer& releaseContainer);
bool addSomeNonReleaseTracks();
static constexpr std::size_t _releasesBatchSize{ 6 };
static constexpr std::size_t _tracksBatchSize{ 6 };
static constexpr std::size_t _tracksMaxCount{ 160 };
Filters& _filters;
PlayQueueController& _playQueueController;
Filters& _filters;
PlayQueueController& _playQueueController;
struct ReleaseType
{
std::optional<Database::ReleaseTypePrimary> primaryType;
EnumSet<Database::ReleaseTypeSecondary> secondaryTypes;
bool operator<(const ReleaseType& other) const;
};
struct ReleaseContainer
{
InfiniteScrollingContainer* container {};
std::vector<Database::ReleaseId> releases;
};
std::map<ReleaseType, ReleaseContainer> _releaseContainers;
ReleaseContainer _appearsOnReleaseContainer {};
InfiniteScrollingContainer* _trackContainer {};
Database::ArtistId _artistId {};
bool _needForceRefresh {};
};
// Display releases the same way as MusicBrainz
struct ReleaseContainer
{
InfiniteScrollingContainer* container{};
std::vector<Database::ReleaseId> releases;
};
std::map<ReleaseType, ReleaseContainer> _releaseContainers;
ReleaseContainer _appearsOnReleaseContainer{};
InfiniteScrollingContainer* _trackContainer{};
Database::ArtistId _artistId{};
bool _needForceRefresh{};
};
} // namespace UserInterface
+33 -20
View File
@@ -87,39 +87,52 @@ namespace UserInterface::ReleaseListHelpers
namespace UserInterface::ReleaseHelpers
{
Wt::WString buildReleaseTypeString(ReleaseTypePrimary primaryType, EnumSet<ReleaseTypeSecondary> secondaryTypes)
Wt::WString buildReleaseTypeString(const ReleaseType& releaseType)
{
Wt::WString res;
switch (primaryType)
if (releaseType.primaryType)
{
case ReleaseTypePrimary::Album: res = Wt::WString::tr("Lms.Explore.Release.type-primary-album"); break;
case ReleaseTypePrimary::Broadcast: res = Wt::WString::tr("Lms.Explore.Release.type-primary-broadcast"); break;
case ReleaseTypePrimary::EP: res = Wt::WString::tr("Lms.Explore.Release.type-primary-ep"); break;
case ReleaseTypePrimary::Single: res = Wt::WString::tr("Lms.Explore.Release.type-primary-single"); break;
case ReleaseTypePrimary::Other: res = Wt::WString::tr("Lms.Explore.Release.type-primary-other"); break;
switch (*releaseType.primaryType)
{
case PrimaryReleaseType::Album: res = Wt::WString::tr("Lms.Explore.Release.type-primary-album"); break;
case PrimaryReleaseType::Broadcast: res = Wt::WString::tr("Lms.Explore.Release.type-primary-broadcast"); break;
case PrimaryReleaseType::EP: res = Wt::WString::tr("Lms.Explore.Release.type-primary-ep"); break;
case PrimaryReleaseType::Single: res = Wt::WString::tr("Lms.Explore.Release.type-primary-single"); break;
case PrimaryReleaseType::Other: res = Wt::WString::tr("Lms.Explore.Release.type-primary-other"); break;
}
}
for (ReleaseTypeSecondary secondaryType : secondaryTypes)
for (SecondaryReleaseType secondaryType : releaseType.secondaryTypes)
{
res += Wt::WString{ " · " };
if (!res.empty())
res += Wt::WString{ " · " };
switch (secondaryType)
{
case ReleaseTypeSecondary::Compilation: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-compilation"); break;
case ReleaseTypeSecondary::Spokenword: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-spokenword"); break;
case ReleaseTypeSecondary::Soundtrack: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-soundtrack"); break;
case ReleaseTypeSecondary::Interview: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-interview"); break;
case ReleaseTypeSecondary::Audiobook: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-audiobook"); break;
case ReleaseTypeSecondary::AudioDrama: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-audiodrama"); break;
case ReleaseTypeSecondary::Live: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-live"); break;
case ReleaseTypeSecondary::Remix: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-remix"); break;
case ReleaseTypeSecondary::DJMix: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-djmix"); break;
case ReleaseTypeSecondary::Mixtape_Street: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-mixtape-street"); break;
case ReleaseTypeSecondary::Demo: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-demo"); break;
case SecondaryReleaseType::Compilation: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-compilation"); break;
case SecondaryReleaseType::Spokenword: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-spokenword"); break;
case SecondaryReleaseType::Soundtrack: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-soundtrack"); break;
case SecondaryReleaseType::Interview: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-interview"); break;
case SecondaryReleaseType::Audiobook: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-audiobook"); break;
case SecondaryReleaseType::AudioDrama: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-audiodrama"); break;
case SecondaryReleaseType::Live: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-live"); break;
case SecondaryReleaseType::Remix: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-remix"); break;
case SecondaryReleaseType::DJMix: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-djmix"); break;
case SecondaryReleaseType::Mixtape_Street: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-mixtape-street"); break;
case SecondaryReleaseType::Demo: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-demo"); break;
case SecondaryReleaseType::FieldRecording: res += Wt::WString::tr("Lms.Explore.Release.type-secondary-field-recording"); break;
}
}
for (const std::string& customType : releaseType.customTypes)
{
if (!res.empty())
res += Wt::WString{ " · " };
res += customType;
}
return res;
}
+2 -1
View File
@@ -28,6 +28,7 @@
#include "database/Object.hpp"
#include "database/Types.hpp"
#include "utils/EnumSet.hpp"
#include "ReleaseTypes.hpp"
namespace Database
{
@@ -43,6 +44,6 @@ namespace UserInterface::ReleaseListHelpers
namespace UserInterface::ReleaseHelpers
{
Wt::WString buildReleaseTypeString(Database::ReleaseTypePrimary primaryType, EnumSet<Database::ReleaseTypeSecondary> secondaryTypes);
Wt::WString buildReleaseTypeString(const ReleaseType& releaseType);
Wt::WString buildReleaseYearString(const Wt::WDate& releaseDate, const Wt::WDate& originalReleaseDate);
}
+120
View File
@@ -0,0 +1,120 @@
/*
* Copyright (C) 2023 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 <tuple>
#include <unordered_map>
#include "ReleaseTypes.hpp"
#include "utils/String.hpp"
namespace StringUtils
{
template<>
std::optional<UserInterface::PrimaryReleaseType> readAs(std::string_view str)
{
static const std::unordered_map<std::string, UserInterface::PrimaryReleaseType> entries
{
{"album", UserInterface::PrimaryReleaseType::Album},
{"single", UserInterface::PrimaryReleaseType::Single},
{"ep", UserInterface::PrimaryReleaseType::EP},
{"broadcast", UserInterface::PrimaryReleaseType::Broadcast},
{"other", UserInterface::PrimaryReleaseType::Other},
};
const auto it{ entries.find(stringToLower(stringTrim(str))) };
if (it == std::cend(entries))
return std::nullopt;
return it->second;
}
template<>
std::optional<UserInterface::SecondaryReleaseType> readAs(std::string_view str)
{
static const std::unordered_map<std::string, UserInterface::SecondaryReleaseType> entries
{
{"compilation", UserInterface::SecondaryReleaseType::Compilation},
{"soundtrack", UserInterface::SecondaryReleaseType::Soundtrack},
{"spokenword", UserInterface::SecondaryReleaseType::Spokenword},
{"interview", UserInterface::SecondaryReleaseType::Interview},
{"audiobook", UserInterface::SecondaryReleaseType::Audiobook},
{"audio drama", UserInterface::SecondaryReleaseType::AudioDrama},
{"live", UserInterface::SecondaryReleaseType::Live},
{"remix", UserInterface::SecondaryReleaseType::Remix},
{"dj-mix", UserInterface::SecondaryReleaseType::DJMix},
{"mixtape/street", UserInterface::SecondaryReleaseType::Mixtape_Street},
{"demo", UserInterface::SecondaryReleaseType::Demo},
{"field recording", UserInterface::SecondaryReleaseType::FieldRecording},
};
const auto it{ entries.find(stringToLower(stringTrim(str))) };
if (it == std::cend(entries))
return std::nullopt;
return it->second;
}
}
namespace UserInterface
{
ReleaseType parseReleaseType(const std::vector<std::string>& releaseTypeNames)
{
ReleaseType res;
for (std::string_view releaseTypeName : releaseTypeNames)
{
if (auto primaryType{ StringUtils::readAs<PrimaryReleaseType>(releaseTypeName) })
{
if (!res.primaryType)
res.primaryType = primaryType;
else
res.customTypes.push_back(std::string{ releaseTypeName });
}
else if (auto secondaryType{ StringUtils::readAs<SecondaryReleaseType>(releaseTypeName) })
{
res.secondaryTypes.insert(*secondaryType);
}
else
res.customTypes.push_back(std::string{ releaseTypeName });
}
return res;
}
bool operator<(std::optional<PrimaryReleaseType> typeA, std::optional<PrimaryReleaseType> typeB)
{
if (!typeA && typeB)
return false;
else if (typeA && !typeB)
return true;
else
return static_cast<int>(*typeA) < static_cast<int>(*typeB);
}
bool operator<(EnumSet<SecondaryReleaseType> typesA, EnumSet<SecondaryReleaseType> typesB)
{
return typesA.getBitfield() < typesB.getBitfield();
}
bool ReleaseType::operator<(const ReleaseType& other) const
{
// TODO : order custom types and compare for each element (size is not to be compared first)
return std::tie(primaryType, secondaryTypes, customTypes) < std::tie(other.primaryType, other.secondaryTypes, other.customTypes);
}
} // namespace UserInterface
+68
View File
@@ -0,0 +1,68 @@
/*
* Copyright (C) 2023 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 <optional>
#include <string>
#include <string_view>
#include <vector>
#include "utils/EnumSet.hpp"
namespace UserInterface
{
// see https://musicbrainz.org/doc/Release_Group/Type
enum class PrimaryReleaseType
{
Album,
Single,
EP,
Broadcast,
Other
};
enum class SecondaryReleaseType
{
Compilation,
Soundtrack,
Spokenword,
Interview,
Audiobook,
AudioDrama,
Live,
Remix,
DJMix,
Mixtape_Street,
Demo,
FieldRecording,
};
struct ReleaseType
{
std::optional<PrimaryReleaseType> primaryType;
EnumSet<SecondaryReleaseType> secondaryTypes;
std::vector<std::string> customTypes;
bool operator<(const ReleaseType& other) const;
};
ReleaseType parseReleaseType(const std::vector<std::string>& releaseTypeNames);
} // namespace UserInterface
+2 -2
View File
@@ -68,10 +68,10 @@ namespace UserInterface
Wt::WWidget* releaseInfoPtr{ releaseInfo.get() };
releaseInfo->addFunction("tr", &Wt::WTemplate::Functions::tr);
if (auto primaryReleaseType{ release->getPrimaryType() })
if (const auto releaseTypeNames{ release->getReleaseTypeNames() }; !releaseTypeNames.empty())
{
releaseInfo->setCondition("if-has-release-type", true);
releaseInfo->bindString("release-type", ReleaseHelpers::buildReleaseTypeString(*primaryReleaseType, release->getSecondaryTypes()));
releaseInfo->bindString("release-type", ReleaseHelpers::buildReleaseTypeString(parseReleaseType(releaseTypeNames)));
}
std::map<Wt::WString, std::set<ArtistId>> artistMap;
+143 -189
View File
@@ -29,215 +29,169 @@
#include "metadata/IParser.hpp"
#include "utils/StreamLogger.hpp"
static
std::ostream&
operator<<(std::ostream& os, const MetaData::Artist& artist)
namespace
{
os << artist.name;
if (artist.mbid)
os << " (" << artist.mbid->getAsString() << ")";
if (artist.sortName)
os << " '" << *artist.sortName << "'";
return os;
}
static
std::ostream&
operator<<(std::ostream& os, MetaData::Release::PrimaryType type)
{
switch (type)
std::ostream& operator<<(std::ostream& os, const MetaData::Artist& artist)
{
case MetaData::Release::PrimaryType::Album: os << "Album"; break;
case MetaData::Release::PrimaryType::Single: os << "Single"; break;
case MetaData::Release::PrimaryType::EP: os << "EP"; break;
case MetaData::Release::PrimaryType::Broadcast: os << "Broadcast"; break;
case MetaData::Release::PrimaryType::Other: os << "Other"; break;
default:
os << "??";
}
return os;
}
os << artist.name;
static
std::ostream&
operator<<(std::ostream& os, MetaData::Release::SecondaryType type)
{
switch (type)
{
case MetaData::Release::SecondaryType::Compilation: os << "Compilation"; break;
case MetaData::Release::SecondaryType::Soundtrack: os << "Soundtrack"; break;
case MetaData::Release::SecondaryType::Spokenword: os << "Spokenword"; break;
case MetaData::Release::SecondaryType::Interview: os << "Interview"; break;
case MetaData::Release::SecondaryType::Audiobook: os << "Audiobook"; break;
case MetaData::Release::SecondaryType::AudioDrama: os << "Audio drama"; break;
case MetaData::Release::SecondaryType::Live: os << "Live"; break;
case MetaData::Release::SecondaryType::Remix: os << "Remix"; break;
case MetaData::Release::SecondaryType::DJMix: os << "DJ-mix"; break;
case MetaData::Release::SecondaryType::Mixtape_Street: os << "Mixtape/Street"; break;
case MetaData::Release::SecondaryType::Demo: os << "Mixtape/Demo"; break;
default:
os << "??";
}
return os;
}
if (artist.mbid)
os << " (" << artist.mbid->getAsString() << ")";
static
std::ostream&
operator<<(std::ostream& os, const MetaData::Release& release)
{
os << release.name;
if (artist.sortName)
os << " '" << *artist.sortName << "'";
if (release.mbid)
os << " (" << release.mbid->getAsString() << ")" << std::endl;
if (release.mediumCount)
std::cout << "\tMediumCount: " << *release.mediumCount << std::endl;
if (!release.artistDisplayName.empty())
std::cout << "\tDisplay artist: " << release.artistDisplayName << std::endl;
for (const MetaData::Artist& artist : release.artists)
std::cout << "\tRelease artist: " << artist << std::endl;
if (release.primaryType)
{
std::cout << "\tPrimary type: " << *release.primaryType << std::endl;
for (MetaData::Release::SecondaryType type : release.secondaryTypes)
std::cout << "\tSecondary type:" << type << std::endl;
return os;
}
return os;
}
static
std::ostream&
operator<<(std::ostream& os, const MetaData::Medium& medium)
{
if (!medium.name.empty())
os << medium.name;
os << std::endl;
if (medium.position)
os << "\tPosition: " << *medium.position << std::endl;
if (!medium.type.empty())
os << "\tType: " << medium.type << std::endl;
if (medium.trackCount)
std::cout << "\tTrackCount: " << *medium.trackCount << std::endl;
if (medium.replayGain)
std::cout << "\tReplay gain: " << *medium.replayGain << std::endl;
if (medium.release)
std::cout << "Release: " << *medium.release << std::endl;
return os;
}
void parse(MetaData::IParser& parser, const std::filesystem::path& file)
{
using namespace MetaData;
parser.setExtraTags({ "MOOD", "ALBUMGROUPING", "GENRE", "LANGUAGE" });
const auto start{ std::chrono::steady_clock::now() };
std::optional<Track> track{ parser.parse(file, true) };
if (!track)
std::ostream& operator<<(std::ostream& os, const MetaData::Release& release)
{
std::cerr << "Parsing failed" << std::endl;
return;
}
const auto end{ std::chrono::steady_clock::now() };
os << release.name;
std::cout << "Parsing time: " << std::fixed << std::setprecision(2) << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / 1000. << "ms" << std::endl;
if (release.mbid)
os << " (" << release.mbid->getAsString() << ")" << std::endl;
std::cout << "Parsed metadata:" << std::endl;
if (release.mediumCount)
std::cout << "\tMediumCount: " << *release.mediumCount << std::endl;
if (!track->artistDisplayName.empty())
std::cout << "Display artist: " << track->artistDisplayName << std::endl;
if (!release.artistDisplayName.empty())
std::cout << "\tDisplay artist: " << release.artistDisplayName << std::endl;
for (const Artist& artist : track->artists)
std::cout << "Artist: " << artist << std::endl;
for (const MetaData::Artist& artist : release.artists)
std::cout << "\tRelease artist: " << artist << std::endl;
for (const Artist& artist : track->conductorArtists)
std::cout << "Conductor: " << artist << std::endl;
std::cout << "Release types:" << std::endl;
for (std::string_view releaseType : release.releaseTypes)
std::cout << "\t" << releaseType << std::endl;
for (const Artist& artist : track->composerArtists)
std::cout << "Composer: " << artist << std::endl;
for (const Artist& artist : track->lyricistArtists)
std::cout << "Lyricist: " << artist << std::endl;
for (const Artist& artist : track->mixerArtists)
std::cout << "Mixer: " << artist << std::endl;
for (const auto& [role, artists] : track->performerArtists)
{
std::cout << "Performer";
if (!role.empty())
std::cout << " (" << role << ")";
std::cout << ":" << std::endl;
for (const Artist& artist : artists)
std::cout << "\t" << artist << std::endl;
return os;
}
for (const Artist& artist : track->producerArtists)
std::cout << "Producer: " << artist << std::endl;
for (const Artist& artist : track->remixerArtists)
std::cout << "Remixer: " << artist << std::endl;
if (track->medium)
std::cout << "Medium: " << *track->medium;
std::cout << "Title: " << track->title << std::endl;
if (track->mbid)
std::cout << "Track MBID = " << track->mbid->getAsString() << std::endl;
if (track->recordingMBID)
std::cout << "Recording MBID = " << track->recordingMBID->getAsString() << std::endl;
for (const auto& [tag, values] : track->tags)
std::ostream& operator<<(std::ostream& os, const MetaData::Medium& medium)
{
std::cout << "Tag: " << tag << std::endl;
for (const auto& value : values)
if (!medium.name.empty())
os << medium.name;
os << std::endl;
if (medium.position)
os << "\tPosition: " << *medium.position << std::endl;
if (!medium.type.empty())
os << "\tType: " << medium.type << std::endl;
if (medium.trackCount)
std::cout << "\tTrackCount: " << *medium.trackCount << std::endl;
if (medium.replayGain)
std::cout << "\tReplay gain: " << *medium.replayGain << std::endl;
if (medium.release)
std::cout << "Release: " << *medium.release << std::endl;
return os;
}
void parse(MetaData::IParser& parser, const std::filesystem::path& file)
{
using namespace MetaData;
parser.setUserExtraTags({ "MOOD", "ALBUMGROUPING", "GENRE", "LANGUAGE" });
const auto start{ std::chrono::steady_clock::now() };
std::optional<Track> track{ parser.parse(file, true) };
if (!track)
{
std::cout << "\t" << value << std::endl;
std::cerr << "Parsing failed" << std::endl;
return;
}
const auto end{ std::chrono::steady_clock::now() };
std::cout << "Parsing time: " << std::fixed << std::setprecision(2) << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / 1000. << "ms" << std::endl;
std::cout << "Parsed metadata:" << std::endl;
if (!track->artistDisplayName.empty())
std::cout << "Display artist: " << track->artistDisplayName << std::endl;
for (const Artist& artist : track->artists)
std::cout << "Artist: " << artist << std::endl;
for (const Artist& artist : track->conductorArtists)
std::cout << "Conductor: " << artist << std::endl;
for (const Artist& artist : track->composerArtists)
std::cout << "Composer: " << artist << std::endl;
for (const Artist& artist : track->lyricistArtists)
std::cout << "Lyricist: " << artist << std::endl;
for (const Artist& artist : track->mixerArtists)
std::cout << "Mixer: " << artist << std::endl;
for (const auto& [role, artists] : track->performerArtists)
{
std::cout << "Performer";
if (!role.empty())
std::cout << " (" << role << ")";
std::cout << ":" << std::endl;
for (const Artist& artist : artists)
std::cout << "\t" << artist << std::endl;
}
for (const Artist& artist : track->producerArtists)
std::cout << "Producer: " << artist << std::endl;
for (const Artist& artist : track->remixerArtists)
std::cout << "Remixer: " << artist << std::endl;
if (track->medium)
std::cout << "Medium: " << *track->medium;
std::cout << "Title: " << track->title << std::endl;
if (track->mbid)
std::cout << "Track MBID = " << track->mbid->getAsString() << std::endl;
if (track->recordingMBID)
std::cout << "Recording MBID = " << track->recordingMBID->getAsString() << std::endl;
for (const auto& [tag, values] : track->userExtraTags)
{
std::cout << "Tag: " << tag << std::endl;
for (const auto& value : values)
{
std::cout << "\t" << value << std::endl;
}
}
std::cout << "Duration: " << std::fixed << std::setprecision(2) << track->duration.count() / 1000. << "s" << std::endl;
std::cout << "Bitrate: " << track->bitrate << " bps" << std::endl;
if (track->position)
std::cout << "Position: " << *track->position << std::endl;
if (track->date.isValid())
std::cout << "Date: " << track->date.toString("yyyy-MM-dd") << std::endl;
if (track->originalDate.isValid())
std::cout << "Original date: " << track->originalDate.toString("yyyy-MM-dd") << std::endl;
std::cout << "HasCover = " << std::boolalpha << track->hasCover << std::endl;
if (track->replayGain)
std::cout << "Track replay gain: " << *track->replayGain << std::endl;
if (track->acoustID)
std::cout << "AcoustID: " << track->acoustID->getAsString() << std::endl;
if (!track->copyright.empty())
std::cout << "Copyright: " << track->copyright << std::endl;
if (!track->copyrightURL.empty())
std::cout << "CopyrightURL: " << track->copyrightURL << std::endl;
std::cout << std::endl;
}
std::cout << "Duration: " << std::fixed << std::setprecision(2) << track->duration.count() / 1000. << "s" << std::endl;
std::cout << "Bitrate: " << track->bitrate << " bps" << std::endl;
if (track->position)
std::cout << "Position: " << *track->position << std::endl;
if (track->date.isValid())
std::cout << "Date: " << track->date.toString("yyyy-MM-dd") << std::endl;
if (track->originalDate.isValid())
std::cout << "Original date: " << track->originalDate.toString("yyyy-MM-dd") << std::endl;
std::cout << "HasCover = " << std::boolalpha << track->hasCover << std::endl;
if (track->replayGain)
std::cout << "Track replay gain: " << *track->replayGain << std::endl;
if (track->acoustID)
std::cout << "AcoustID: " << track->acoustID->getAsString() << std::endl;
if (!track->copyright.empty())
std::cout << "Copyright: " << track->copyright << std::endl;
if (!track->copyrightURL.empty())
std::cout << "CopyrightURL: " << track->copyrightURL << std::endl;
std::cout << std::endl;
}
int main(int argc, char* argv[])