Split the lib in smaller libs to ease unit tests

This commit is contained in:
emeric
2020-02-13 18:04:35 +01:00
parent 1e2c1caeed
commit 15e53caa2d
131 changed files with 382 additions and 138 deletions
+37
View File
@@ -0,0 +1,37 @@
add_library(lmsdatabase SHARED
impl/Artist.cpp
impl/Cluster.cpp
impl/Db.cpp
impl/TrackArtistLink.cpp
impl/TrackFeatures.cpp
impl/TrackList.cpp
impl/Release.cpp
impl/ScanSettings.cpp
impl/Session.cpp
impl/SessionPool.cpp
impl/SqlQuery.cpp
impl/Track.cpp
impl/TrackBookmark.cpp
impl/User.cpp
)
target_include_directories(lmsdatabase INTERFACE
include
)
target_include_directories(lmsdatabase PRIVATE
include
)
target_link_libraries(lmsdatabase PRIVATE
wtdbosqlite3
)
target_link_libraries(lmsdatabase PUBLIC
lmsutils
wtdbo
)
install(TARGETS lmsdatabase DESTINATION lib)
+395
View File
@@ -0,0 +1,395 @@
/*
* Copyright (C) 2015 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 "database/Artist.hpp"
#include <Wt/Dbo/WtSqlTraits.h>
#include "database/Cluster.hpp"
#include "database/Release.hpp"
#include "database/Session.hpp"
#include "database/Track.hpp"
#include "database/User.hpp"
#include "utils/Logger.hpp"
#include "SqlQuery.hpp"
namespace Database
{
Artist::Artist(const std::string& name, const std::optional<UUID>& MBID)
: _name {std::string(name, 0 , _maxNameLength)},
_sortName {_name},
_MBID {MBID ? MBID->getAsString() : ""}
{
}
std::vector<Artist::pointer>
Artist::getByName(Session& session, const std::string& name)
{
session.checkSharedLocked();
Wt::Dbo::collection<Artist::pointer> res = session.getDboSession().find<Artist>().where("name = ?").bind( std::string{name, 0, _maxNameLength} );
return std::vector<Artist::pointer>(res.begin(), res.end());
}
Artist::pointer
Artist::getByMBID(Session& session, const UUID& mbid)
{
session.checkSharedLocked();
return session.getDboSession().find<Artist>().where("mbid = ?").bind(std::string {mbid.getAsString()});
}
Artist::pointer
Artist::getById(Session& session, IdType id)
{
session.checkSharedLocked();
return session.getDboSession().find<Artist>().where("id = ?").bind(id);
}
Artist::pointer
Artist::create(Session& session, const std::string& name, const std::optional<UUID>& MBID)
{
session.checkUniqueLocked();
Artist::pointer res {session.getDboSession().add(std::make_unique<Artist>(name, MBID))};
session.getDboSession().flush();
return res;
}
std::vector<Artist::pointer>
Artist::getAll(Session& session, std::optional<std::size_t> offset, std::optional<std::size_t> size)
{
session.checkSharedLocked();
Wt::Dbo::collection<pointer> res = session.getDboSession().find<Artist>()
.offset(offset ? static_cast<int>(*offset) : -1)
.limit(size ? static_cast<int>(*size) : -1)
.orderBy("sort_name COLLATE NOCASE");
return std::vector<pointer>(res.begin(), res.end());
}
std::vector<IdType>
Artist::getAllIds(Session& session)
{
session.checkSharedLocked();
Wt::Dbo::collection<IdType> res = session.getDboSession().query<IdType>("SELECT id FROM artist");
return std::vector<IdType>(res.begin(), res.end());
}
std::vector<Artist::pointer>
Artist::getAllOrphans(Session& session)
{
session.checkSharedLocked();
Wt::Dbo::collection<Wt::Dbo::ptr<Artist>> res {session.getDboSession().query<Wt::Dbo::ptr<Artist>>("SELECT DISTINCT a FROM artist a WHERE NOT EXISTS(SELECT 1 FROM track t INNER JOIN track_artist_link t_a_l ON t_a_l.artist_id = a.id WHERE t.id = t_a_l.track_id)")};
return std::vector<pointer>(res.begin(), res.end());
}
static
Wt::Dbo::Query<Artist::pointer>
getQuery(Session& session,
const std::set<IdType>& clusterIds,
const std::vector<std::string>& keywords,
std::optional<TrackArtistLink::Type> linkType)
{
session.checkSharedLocked();
WhereClause where;
std::ostringstream oss;
oss << "SELECT DISTINCT a FROM artist a";
for (auto keyword : keywords)
where.And(WhereClause("a.name LIKE ?")).bind("%%" + keyword + "%%");
if (!clusterIds.empty() || linkType)
{
oss << " 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";
if (!clusterIds.empty())
{
oss << " 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 = ?")).bind(std::to_string(id));
where.And(clusterClause);
}
if (linkType)
where.And(WhereClause {"t_a_l.type = ?"}.bind(std::to_string(static_cast<int>(*linkType))));
}
oss << " " << where.get();
if (!clusterIds.empty())
oss << " GROUP BY t.id HAVING COUNT(DISTINCT c.id) = " << clusterIds.size();
oss << " ORDER BY a.sort_name COLLATE NOCASE";
Wt::Dbo::Query<Artist::pointer> query = session.getDboSession().query<Artist::pointer>( oss.str() );
for (const std::string& bindArg : where.getBindArgs())
{
query.bind(bindArg);
}
return query;
}
std::vector<Artist::pointer>
Artist::getByClusters(Session& session, const std::set<IdType>& clusters)
{
assert(!clusters.empty());
session.checkSharedLocked();
bool more;
return getByFilter(session, clusters, {}, {}, {}, {}, more);
}
std::vector<Artist::pointer>
Artist::getByFilter(Session& session,
const std::set<IdType>& clusters,
const std::vector<std::string>& keywords,
std::optional<TrackArtistLink::Type> linkType,
std::optional<std::size_t> offset,
std::optional<std::size_t> size,
bool& moreResults)
{
session.checkSharedLocked();
Wt::Dbo::collection<Artist::pointer> collection = getQuery(session, clusters, keywords, linkType)
.limit(size ? static_cast<int>(*size) + 1 : -1)
.offset(offset ? static_cast<int>(*offset) : -1);
auto res {std::vector<pointer>(collection.begin(), collection.end())};
if (size && res.size() == static_cast<std::size_t>(*size) + 1)
{
moreResults = true;
res.pop_back();
}
else
moreResults = false;
return res;
}
std::vector<Artist::pointer>
Artist::getLastAdded(Session& session, Wt::WDateTime after, std::optional<std::size_t> limit)
{
session.checkSharedLocked();
Wt::Dbo::collection<Artist::pointer> res = session.getDboSession().query<Artist::pointer>("SELECT a from artist a INNER JOIN track_artist_link t_a_l ON t_a_l.artist_id = a.id INNER JOIN track t ON t.id = t_a_l.track_id")
.where("t.file_added > ?").bind(after)
.groupBy("a.id")
.orderBy("t.file_added DESC")
.limit(limit ? static_cast<int>(*limit) : -1);
return std::vector<pointer>(res.begin(), res.end());
}
std::vector<Wt::Dbo::ptr<Release>>
Artist::getReleases(const std::set<IdType>& clusterIds) const
{
assert(self());
assert(IdIsValid(self()->id()));
assert(session());
WhereClause where;
std::ostringstream oss;
oss << "SELECT DISTINCT r FROM release r INNER JOIN artist a ON a.id = t_a_l.artist_id INNER JOIN track_artist_link t_a_l ON t_a_l.track_id = t.id INNER JOIN track t ON t.release_id = r.id";
if (!clusterIds.empty())
{
oss << " 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 = ?")).bind(std::to_string(id));
where.And(clusterClause);
}
where.And(WhereClause("a.id = ?")).bind(std::to_string(id()));
oss << " " << where.get();
if (!clusterIds.empty())
oss << " GROUP BY t.id HAVING COUNT(DISTINCT c.id) = " << clusterIds.size();
oss << " ORDER BY t.year,r.name";
Wt::Dbo::Query<Release::pointer> query = session()->query<Release::pointer>( oss.str() );
for (const std::string& bindArg : where.getBindArgs())
query.bind(bindArg);
Wt::Dbo::collection<Wt::Dbo::ptr<Release>> res = query;
return std::vector<Wt::Dbo::ptr<Release>>(res.begin(), res.end());
}
std::size_t
Artist::getReleaseCount() const
{
assert(self());
assert(IdIsValid(self()->id()));
assert(session());
int res = session()->query<int>("SELECT COUNT(DISTINCT r.id) FROM release r INNER JOIN artist a ON a.id = t_a_l.artist_id INNER JOIN track_artist_link t_a_l ON t_a_l.track_id = t.id INNER JOIN track t ON t.release_id = r.id")
.where("a.id = ?").bind(self()->id());
return res;
}
std::vector<Wt::Dbo::ptr<Track>>
Artist::getTracks(std::optional<TrackArtistLink::Type> linkType) const
{
assert(self());
assert(IdIsValid(self()->id()));
assert(session());
auto query {session()->query<Wt::Dbo::ptr<Track>>("SELECT DISTINCT t FROM track t INNER JOIN artist a ON a.id = t_a_l.artist_id INNER JOIN track_artist_link t_a_l ON t_a_l.track_id = t.id")
.where("a.id = ?").bind(self()->id())
.orderBy("t.year,t.release_id,t.disc_number,t.track_number")};
if (linkType)
query.where("t_a_l.type = ?").bind(*linkType);
Wt::Dbo::collection<Wt::Dbo::ptr<Track>> tracks {query.resultList()};
return std::vector<Wt::Dbo::ptr<Track>>(tracks.begin(), tracks.end());
}
std::vector<Wt::Dbo::ptr<Track>>
Artist::getTracksWithRelease(std::optional<TrackArtistLink::Type> linkType) const
{
assert(self());
assert(IdIsValid(self()->id()));
assert(session());
auto query {session()->query<Wt::Dbo::ptr<Track>>("SELECT t FROM track t INNER JOIN artist a ON a.id = t_a_l.artist_id INNER JOIN track_artist_link t_a_l ON t_a_l.track_id = t.id INNER JOIN release r ON r.id = t.release_id")
.where("a.id = ?").bind(self()->id())
.orderBy("t.year,r.name,t.disc_number,t.track_number")};
if (linkType)
query.where("t_a_l.type = ?").bind(*linkType);
Wt::Dbo::collection<Wt::Dbo::ptr<Track>> tracks {query.resultList()};
return std::vector<Wt::Dbo::ptr<Track>>(tracks.begin(), tracks.end());
}
std::vector<Wt::Dbo::ptr<Track>>
Artist::getRandomTracks(std::optional<std::size_t> count) const
{
assert(self());
assert(IdIsValid(self()->id()));
assert(session());
Wt::Dbo::collection<Wt::Dbo::ptr<Track>> tracks {session()->query<Wt::Dbo::ptr<Track>>("SELECT t from track t INNER JOIN artist a ON a.id = t_a_l.artist_id INNER JOIN track_artist_link t_a_l ON t_a_l.track_id = t.id")
.where("a.id = ?").bind(self()->id())
.orderBy("RANDOM()")
.limit(count ? static_cast<int>(*count) : -1)};
return std::vector<Wt::Dbo::ptr<Track>>(tracks.begin(), tracks.end());
}
std::vector<Wt::Dbo::ptr<Artist>>
Artist::getSimilarArtists(std::optional<std::size_t> offset, std::optional<std::size_t> count) const
{
assert(self());
assert(IdIsValid(self()->id()));
assert(session());
Wt::Dbo::Query<pointer> query {session()->query<pointer>(
"SELECT a FROM artist a"
" INNER JOIN track_artist_link t_a_l ON t_a_l.artist_id = a.id"
" INNER JOIN track t ON t.id = t_a_l.track_id"
" INNER JOIN track_cluster t_c ON t_c.track_id = t.id"
" WHERE "
" t_c.cluster_id IN (SELECT c.id from cluster c INNER JOIN track t ON c.id = t_c.cluster_id INNER JOIN track_cluster t_c ON t_c.track_id = t.id INNER JOIN artist a ON a.id = t_a_l.artist_id INNER JOIN track_artist_link t_a_l ON t_a_l.track_id = t.id WHERE a.id = ?)"
" AND a.id <> ?"
)
.bind(self()->id())
.bind(self()->id())
.groupBy("a.id")
.orderBy("COUNT(*) DESC")
.limit(count ? static_cast<int>(*count) : -1)
.offset(offset ? static_cast<int>(*offset) : -1)};
Wt::Dbo::collection<pointer> res = query;
return std::vector<pointer>(res.begin(), res.end());
}
std::vector<std::vector<Wt::Dbo::ptr<Cluster>>>
Artist::getClusterGroups(std::vector<ClusterType::pointer> clusterTypes, std::size_t size) const
{
assert(self());
assert(IdIsValid(self()->id()));
assert(session());
WhereClause where;
std::ostringstream oss;
oss << "SELECT c FROM cluster c INNER JOIN track t ON c.id = t_c.cluster_id INNER JOIN track_cluster t_c ON t_c.track_id = t.id INNER JOIN cluster_type c_type ON c.cluster_type_id = c_type.id INNER JOIN artist a ON t_a_l.artist_id = a.id INNER JOIN track_artist_link t_a_l ON t_a_l.track_id = t.id";
where.And(WhereClause("a.id = ?")).bind(std::to_string(self()->id()));
{
WhereClause clusterClause;
for (auto clusterType : clusterTypes)
clusterClause.Or(WhereClause("c_type.id = ?")).bind(std::to_string(clusterType.id()));
where.And(clusterClause);
}
oss << " " << where.get();
oss << "GROUP BY c.id ORDER BY COUNT(DISTINCT c.id) DESC";
Wt::Dbo::Query<Cluster::pointer> query = session()->query<Cluster::pointer>( oss.str() );
for (const std::string& bindArg : where.getBindArgs())
query.bind(bindArg);
Wt::Dbo::collection<Cluster::pointer> queryRes = query;
std::map<IdType, std::vector<Cluster::pointer>> clusters;
for (auto cluster : queryRes)
{
if (clusters[cluster->getType().id()].size() < size)
clusters[cluster->getType().id()].push_back(cluster);
}
std::vector<std::vector<Cluster::pointer>> res;
for (auto cluster_list : clusters)
res.push_back(cluster_list.second);
return res;
}
void
Artist::setSortName(const std::string& sortName)
{
_sortName = std::string(sortName, 0 , _maxNameLength);
}
} // namespace Database
+206
View File
@@ -0,0 +1,206 @@
/*
* Copyright (C) 2013-2016 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 "database/Cluster.hpp"
#include "database/Artist.hpp"
#include "database/Release.hpp"
#include "database/ScanSettings.hpp"
#include "database/Session.hpp"
#include "database/Track.hpp"
#include "SqlQuery.hpp"
namespace Database {
Cluster::Cluster()
{
}
Cluster::Cluster(Wt::Dbo::ptr<ClusterType> type, std::string name)
: _name(std::string(name, 0, _maxNameLength)),
_clusterType(type)
{
}
Cluster::pointer
Cluster::create(Session& session, Wt::Dbo::ptr<ClusterType> type, std::string name)
{
session.checkUniqueLocked();
Cluster::pointer res {session.getDboSession().add(std::make_unique<Cluster>(type, name))};
session.getDboSession().flush();
return res;
}
std::vector<Cluster::pointer>
Cluster::getAll(Session& session)
{
session.checkSharedLocked();
Wt::Dbo::collection<Cluster::pointer> res {session.getDboSession().find<Cluster>()};
return std::vector<Cluster::pointer>(res.begin(), res.end());
}
std::vector<Cluster::pointer>
Cluster::getAllOrphans(Session& session)
{
session.checkSharedLocked();
Wt::Dbo::collection<Cluster::pointer> res {session.getDboSession().query<Cluster::pointer>("SELECT DISTINCT c FROM cluster c WHERE NOT EXISTS(SELECT 1 FROM track_cluster t_c WHERE t_c.cluster_id = c.id)")};
return std::vector<Cluster::pointer>(res.begin(), res.end());
}
Cluster::pointer
Cluster::getById(Session& session, IdType id)
{
session.checkSharedLocked();
return session.getDboSession().find<Cluster>().where("id = ?").bind(id);
}
void
Cluster::addTrack(Wt::Dbo::ptr<Track> track)
{
_tracks.insert(track);
}
std::vector<Wt::Dbo::ptr<Track>>
Cluster::getTracks(std::optional<std::size_t> offset, std::optional<std::size_t> limit) const
{
assert(session());
assert(IdIsValid(self()->id()));
Wt::Dbo::collection<Track::pointer> res
{session()->query<Track::pointer>("SELECT t FROM track t INNER JOIN cluster c ON c.id = t_c.cluster_id INNER JOIN track_cluster t_c ON t_c.track_id = t.id")
.where("c.id = ?").bind(self()->id())
.offset(offset ? static_cast<int>(*offset) : -1)
.limit(limit ? static_cast<int>(*limit) : -1)};
return std::vector<Wt::Dbo::ptr<Track>>(res.begin(), res.end());
}
std::set<IdType>
Cluster::getTrackIds() const
{
assert(session());
assert(IdIsValid(self()->id()));
Wt::Dbo::collection<IdType> res = session()->query<IdType>("SELECT t_c.track_id FROM track_cluster t_c INNER JOIN cluster c ON c.id = t_c.cluster_id")
.where("c.id = ?").bind(self()->id());
return std::set<IdType>(res.begin(), res.end());
}
std::size_t
Cluster::getReleasesCount() const
{
assert(session());
assert(IdIsValid(self()->id()));
return session()->query<int>("SELECT COUNT(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")
.where("c.id = ?").bind(self()->id());
}
ClusterType::ClusterType(std::string name)
: _name(name)
{
}
std::vector<ClusterType::pointer>
ClusterType::getAllOrphans(Session& session)
{
session.checkSharedLocked();
Wt::Dbo::collection<pointer> res = session.getDboSession().query<Wt::Dbo::ptr<ClusterType>>("select c_t from cluster_type c_t LEFT OUTER JOIN cluster c ON c_t.id = c.cluster_type_id WHERE c.id IS NULL");
return std::vector<pointer>(res.begin(), res.end());
}
ClusterType::pointer
ClusterType::getByName(Session& session, const std::string& name)
{
session.checkSharedLocked();
return session.getDboSession().find<ClusterType>().where("name = ?").bind(name);
}
ClusterType::pointer
ClusterType::getById(Session& session, IdType id)
{
session.checkSharedLocked();
return session.getDboSession().find<ClusterType>().where("id= ?").bind(id);
}
std::vector<ClusterType::pointer>
ClusterType::getAll(Session& session)
{
session.checkSharedLocked();
Wt::Dbo::collection<pointer> res = session.getDboSession().find<ClusterType>();
return std::vector<pointer>(res.begin(), res.end());
}
ClusterType::pointer
ClusterType::create(Session& session, const std::string& name)
{
session.checkUniqueLocked();
ClusterType::pointer res {session.getDboSession().add(std::make_unique<ClusterType>(name))};
session.getDboSession().flush();
return res;
}
Cluster::pointer
ClusterType::getCluster(const std::string& name) const
{
assert(self());
assert(IdIsValid(self()->id()));
assert(session());
return session()->find<Cluster>()
.where("name = ?").bind(name)
.where("cluster_type_id = ?").bind(self()->id());
}
std::vector<Cluster::pointer>
ClusterType::getClusters() const
{
assert(self());
assert(IdIsValid(self()->id()));
assert(session());
Wt::Dbo::collection<Cluster::pointer> res = session()->find<Cluster>()
.where("cluster_type_id = ?").bind(self()->id())
.orderBy("name");
return std::vector<Cluster::pointer>(res.begin(), res.end());
}
} // namespace Database
+47
View File
@@ -0,0 +1,47 @@
/*
* 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 "database/Db.hpp"
#include <Wt/Dbo/FixedSqlConnectionPool.h>
#include <Wt/Dbo/backend/Sqlite3.h>
#include "database/User.hpp"
#include "utils/Logger.hpp"
namespace Database {
// Session living class handling the database and the login
Db::Db(const std::filesystem::path& dbPath)
{
LMS_LOG(DB, INFO) << "Creating connection pool on file " << dbPath.string();
std::unique_ptr<Wt::Dbo::backend::Sqlite3> connection {std::make_unique<Wt::Dbo::backend::Sqlite3>(dbPath.string())};
connection->executeSql("pragma journal_mode=WAL");
// connection->setProperty("show-queries", "true");
auto connectionPool = std::make_unique<Wt::Dbo::FixedSqlConnectionPool>(std::move(connection), 10);
connectionPool->setTimeout(std::chrono::seconds(10));
_connectionPool = std::move(connectionPool);
}
} // namespace Database
+493
View File
@@ -0,0 +1,493 @@
/*
* Copyright (C) 2015 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 "database/Release.hpp"
#include "utils/Logger.hpp"
#include "database/Artist.hpp"
#include "database/Cluster.hpp"
#include "database/Session.hpp"
#include "database/Track.hpp"
#include "database/User.hpp"
#include "SqlQuery.hpp"
namespace Database
{
Release::Release(const std::string& name, const std::optional<UUID>& MBID)
: _name {std::string(name, 0 , _maxNameLength)},
_MBID {MBID ? MBID->getAsString() : ""}
{
}
std::vector<Release::pointer>
Release::getByName(Session& session, const std::string& name)
{
session.checkUniqueLocked();
Wt::Dbo::collection<Release::pointer> res = session.getDboSession().find<Release>().where("name = ?").bind( std::string(name, 0, _maxNameLength) );
return std::vector<Release::pointer>(res.begin(), res.end());
}
Release::pointer
Release::getByMBID(Session& session, const UUID& mbid)
{
session.checkSharedLocked();
return session.getDboSession().find<Release>().where("mbid = ?").bind(std::string {mbid.getAsString()});
}
Release::pointer
Release::getById(Session& session, IdType id)
{
session.checkSharedLocked();
return session.getDboSession().find<Release>().where("id = ?").bind(id);
}
Release::pointer
Release::create(Session& session, const std::string& name, const std::optional<UUID>& MBID)
{
session.checkSharedLocked();
Release::pointer res {session.getDboSession().add(std::make_unique<Release>(name, MBID))};
session.getDboSession().flush();
return res;
}
std::size_t
Release::getCount(Session& session)
{
session.checkSharedLocked();
Wt::Dbo::collection<pointer> releases {session.getDboSession().find<Release>()};
return releases.size();
}
std::vector<Release::pointer>
Release::getAll(Session& session, std::optional<std::size_t> offset, std::optional<std::size_t> size)
{
session.checkSharedLocked();
Wt::Dbo::collection<pointer> res = session.getDboSession().find<Release>()
.offset(offset ? static_cast<int>(*offset) : -1)
.limit(size ? static_cast<int>(*size) : -1)
.orderBy("name COLLATE NOCASE");
return std::vector<pointer>(res.begin(), res.end());
}
std::vector<IdType>
Release::getAllIds(Session& session)
{
session.checkSharedLocked();
Wt::Dbo::collection<IdType> res = session.getDboSession().query<IdType>("SELECT id FROM release");
return std::vector<IdType>(res.begin(), res.end());
}
std::vector<Release::pointer>
Release::getAllOrderedByArtist(Session& session, std::optional<std::size_t> offset, std::optional<std::size_t> size)
{
session.checkSharedLocked();
Wt::Dbo::collection<pointer> res = session.getDboSession().query<Wt::Dbo::ptr<Release>>(
"SELECT DISTINCT r FROM release r"
" INNER JOIN track t ON r.id = t.release_id"
" INNER JOIN track_artist_link t_a_l ON t_a_l.track_id = t.id"
" INNER JOIN artist a ON t_a_l.artist_id = a.id")
.offset(offset ? static_cast<int>(*offset) : -1)
.limit(size ? static_cast<int>(*size) : -1)
.orderBy("a.name COLLATE NOCASE, r.name COLLATE NOCASE");
return std::vector<pointer>(res.begin(), res.end());
}
std::vector<Release::pointer>
Release::getAllRandom(Session& session, std::optional<std::size_t> size)
{
session.checkSharedLocked();
Wt::Dbo::collection<pointer> res = session.getDboSession().find<Release>()
.limit(size ? static_cast<int>(*size) : -1)
.orderBy("RANDOM()");
return std::vector<pointer>(res.begin(), res.end());
}
std::vector<Release::pointer>
Release::getAllOrphans(Session& session)
{
session.checkSharedLocked();
Wt::Dbo::collection<Release::pointer> res = session.getDboSession().query<Wt::Dbo::ptr<Release>>("select r from release r LEFT OUTER JOIN Track t ON r.id = t.release_id WHERE t.id IS NULL");
return std::vector<pointer>(res.begin(), res.end());
}
std::vector<Release::pointer>
Release::getLastAdded(Session& session, const Wt::WDateTime& after, std::optional<std::size_t> offset, std::optional<std::size_t> limit)
{
session.checkSharedLocked();
Wt::Dbo::collection<Release::pointer> res = session.getDboSession().query<Release::pointer>("SELECT r from release r INNER JOIN track t ON r.id = t.release_id")
.where("t.file_added > ?").bind(after)
.groupBy("r.id")
.orderBy("t.file_added DESC")
.offset(offset ? static_cast<int>(*offset) : -1)
.limit(limit ? static_cast<int>(*limit) : -1);
return std::vector<pointer>(res.begin(), res.end());
}
std::vector<Release::pointer>
Release::getByYear(Session& session, int yearFrom, int yearTo, std::optional<std::size_t> offset, std::optional<std::size_t> limit)
{
Wt::Dbo::collection<Release::pointer> res = session.getDboSession().query<Release::pointer>
("SELECT DISTINCT r from release r INNER JOIN track t ON r.id = t.release_id")
.where("t.year >= ?").bind(yearFrom)
.where("t.year <= ?").bind(yearTo)
.orderBy("t.year, r.name COLLATE NOCASE")
.offset(offset ? static_cast<int>(*offset) : -1)
.limit(limit ? static_cast<int>(*limit) : -1);
return std::vector<pointer>(res.begin(), res.end());
}
static
Wt::Dbo::Query<Release::pointer>
getQuery(Session& session,
const std::set<IdType>& clusterIds,
const std::vector<std::string>& keywords)
{
WhereClause where;
std::ostringstream oss;
oss << "SELECT DISTINCT r FROM release r";
for (auto keyword : keywords)
where.And(WhereClause("r.name LIKE ?")).bind("%%" + keyword + "%%");
if (!clusterIds.empty())
{
oss << " 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 (auto id : clusterIds)
clusterClause.Or(WhereClause("c.id = ?")).bind(std::to_string(id));
where.And(clusterClause);
}
oss << " " << where.get();
if (!clusterIds.empty())
oss << " GROUP BY t.id HAVING COUNT(*) = " << clusterIds.size();
oss << " ORDER BY r.name COLLATE NOCASE";
Wt::Dbo::Query<Release::pointer> query = session.getDboSession().query<Release::pointer>( oss.str() );
for (const std::string& bindArg : where.getBindArgs())
query.bind(bindArg);
return query;
}
std::vector<Release::pointer>
Release::getByClusters(Session& session, const std::set<IdType>& clusters)
{
assert(!clusters.empty());
session.checkSharedLocked();
bool moreResults;
return getByFilter(session, clusters, {}, {}, {}, moreResults);
}
std::vector<Release::pointer>
Release::getByFilter(Session& session,
const std::set<IdType>& clusterIds,
const std::vector<std::string>& keywords,
std::optional<std::size_t> offset,
std::optional<std::size_t> size,
bool& moreResults)
{
session.checkSharedLocked();
Wt::Dbo::collection<pointer> collection = getQuery(session, clusterIds, keywords)
.limit(size ? static_cast<int>(*size) + 1 : -1)
.offset(offset ? static_cast<int>(*offset) : -1);
auto res {std::vector<pointer>(collection.begin(), collection.end())};
if (size && res.size() == static_cast<std::size_t>(*size) + 1)
{
moreResults = true;
res.pop_back();
}
else
moreResults = false;
return res;
}
std::optional<std::size_t>
Release::getTotalTrackNumber(void) const
{
return (_totalTrackNumber > 0) ? std::make_optional<std::size_t>(_totalTrackNumber) : std::nullopt;
}
std::optional<std::size_t>
Release::getTotalDiscNumber(void) const
{
return (_totalDiscNumber > 0) ? std::make_optional<std::size_t>(_totalDiscNumber) : std::nullopt;
}
std::optional<int>
Release::getReleaseYear(bool original) const
{
assert(session());
const std::string field {original ? "original_year" : "year"};
Wt::Dbo::collection<int> dates = session()->query<int>(
std::string{"SELECT "} + "t." + field + " FROM track t INNER JOIN release r ON r.id = t.release_id")
.where("r.id = ?")
.groupBy(field)
.bind(this->id());
// various dates => no date
if (dates.empty() || dates.size() > 1)
return std::nullopt;
auto date {dates.front()};
if (date > 0)
return date;
else
return std::nullopt;
}
std::optional<std::string>
Release::getCopyright() const
{
assert(session());
Wt::Dbo::collection<std::string> copyrights = session()->query<std::string>
("SELECT copyright FROM track t INNER JOIN release r ON r.id = t.release_id")
.where("r.id = ?")
.groupBy("copyright")
.bind(this->id());
std::vector<std::string> values(copyrights.begin(), copyrights.end());
// various copyrights => no copyright
if (values.empty() || values.size() > 1 || values.front().empty())
return std::nullopt;
return values.front();
}
std::optional<std::string>
Release::getCopyrightURL() const
{
assert(session());
Wt::Dbo::collection<std::string> copyrights = session()->query<std::string>
("SELECT copyright_url FROM track t INNER JOIN release r ON r.id = t.release_id")
.where("r.id = ?")
.groupBy("copyright_url")
.bind(this->id());
std::vector<std::string> values(copyrights.begin(), copyrights.end());
// various copyright URLs => no copyright URL
if (values.empty() || values.size() > 1 || values.front().empty())
return std::nullopt;
return values.front();
}
std::vector<Wt::Dbo::ptr<Artist>>
Release::getArtists(TrackArtistLink::Type linkType) const
{
assert(self());
assert(IdIsValid(self()->id()));
assert(session());
Wt::Dbo::collection<Wt::Dbo::ptr<Artist>> res = session()->query<Wt::Dbo::ptr<Artist>>(
"SELECT DISTINCT a FROM artist a"
" INNER JOIN track_artist_link t_a_l ON t_a_l.artist_id = a.id"
" INNER JOIN track t ON t.id = t_a_l.track_id"
" INNER JOIN release r ON r.id = t.release_id")
.where("r.id = ?").bind(self()->id())
.where("t_a_l.type = ?").bind(linkType);
return std::vector<Wt::Dbo::ptr<Artist>>(res.begin(), res.end());
}
std::vector<Release::pointer>
Release::getSimilarReleases(std::optional<std::size_t> offset, std::optional<std::size_t> count) const
{
assert(self());
assert(IdIsValid(self()->id()));
assert(session());
Wt::Dbo::Query<pointer> query {session()->query<pointer>(
"SELECT r FROM release r"
" INNER JOIN track t ON t.release_id = r.id"
" INNER JOIN track_cluster t_c ON t_c.track_id = t.id"
" WHERE "
" t_c.cluster_id IN (SELECT c.id from cluster c INNER JOIN track t ON c.id = t_c.cluster_id INNER JOIN track_cluster t_c ON t_c.track_id = t.id INNER JOIN release r ON r.id = t.release_id WHERE r.id = ?)"
" AND r.id <> ?"
)
.bind(self()->id())
.bind(self()->id())
.groupBy("r.id")
.orderBy("COUNT(*) DESC")
.limit(count ? static_cast<int>(*count) : -1)
.offset(offset ? static_cast<int>(*offset) : -1)};
Wt::Dbo::collection<pointer> res = query;
return std::vector<pointer>(res.begin(), res.end());
}
bool
Release::hasVariousArtists() const
{
// TODO optimize
return getArtists().size() > 1;
}
std::vector<Wt::Dbo::ptr<Track>>
Release::getTracks(const std::set<IdType>& clusterIds) const
{
assert(self());
assert(self()->id() != Wt::Dbo::dbo_traits<Release>::invalidId() );
assert(session());
WhereClause where;
std::ostringstream oss;
oss << "SELECT t FROM track t INNER JOIN release r ON t.release_id = r.id";
if (!clusterIds.empty())
{
oss << " 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 = ?")).bind(std::to_string(id));
where.And(clusterClause);
}
where.And(WhereClause("r.id = ?")).bind(std::to_string(id()));
oss << " " << where.get();
if (!clusterIds.empty())
oss << " GROUP BY t.id HAVING COUNT(*) = " << clusterIds.size();
oss << " ORDER BY t.disc_number,t.track_number";
Wt::Dbo::Query<Track::pointer> query = session()->query<Track::pointer>( oss.str() );
for (const std::string& bindArg : where.getBindArgs())
{
query.bind(bindArg);
}
Wt::Dbo::collection< Wt::Dbo::ptr<Track> > res = query;
return std::vector< Wt::Dbo::ptr<Track> > (res.begin(), res.end());
}
std::size_t
Release::getTracksCount() const
{
return _tracks.size();
}
std::chrono::milliseconds
Release::getDuration() const
{
assert(self());
assert(self()->id() != Wt::Dbo::dbo_traits<Artist>::invalidId() );
assert(session());
using milli = std::chrono::duration<int, std::milli>;
Wt::Dbo::Query<milli> query {session()->query<milli>("SELECT SUM(duration) FROM track t INNER JOIN release r ON t.release_id = r.id")
.where("r.id = ?").bind(self()->id())};
return query.resultValue();
}
std::vector<std::vector<Wt::Dbo::ptr<Cluster>>>
Release::getClusterGroups(std::vector<ClusterType::pointer> clusterTypes, std::size_t size) const
{
assert(self());
assert(self()->id() != Wt::Dbo::dbo_traits<Artist>::invalidId() );
assert(session());
WhereClause where;
std::ostringstream oss;
oss << "SELECT c from cluster c INNER JOIN track t ON c.id = t_c.cluster_id INNER JOIN track_cluster t_c ON t_c.track_id = t.id INNER JOIN cluster_type c_type ON c.cluster_type_id = c_type.id INNER JOIN release r ON t.release_id = r.id ";
where.And(WhereClause("r.id = ?")).bind(std::to_string(self()->id()));
{
WhereClause clusterClause;
for (auto clusterType : clusterTypes)
clusterClause.Or(WhereClause("c_type.id = ?")).bind(std::to_string(clusterType.id()));
where.And(clusterClause);
}
oss << " " << where.get();
oss << " GROUP BY c.id ORDER BY COUNT(c.id) DESC";
Wt::Dbo::Query<Cluster::pointer> query = session()->query<Cluster::pointer>( oss.str() );
for (const std::string& bindArg : where.getBindArgs())
query.bind(bindArg);
Wt::Dbo::collection<Cluster::pointer> queryRes = query;
std::map<IdType, std::vector<Cluster::pointer>> clusters;
for (auto cluster : queryRes)
{
if (clusters[cluster->getType().id()].size() < size)
clusters[cluster->getType().id()].push_back(cluster);
}
std::vector<std::vector<Cluster::pointer>> res;
for (auto cluster_list : clusters)
res.push_back(cluster_list.second);
return res;
}
} // namespace Database
+146
View File
@@ -0,0 +1,146 @@
/*
* Copyright (C) 2018 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 "database/ScanSettings.hpp"
#include <Wt/Dbo/WtSqlTraits.h>
#include "utils/Logger.hpp"
#include "utils/String.hpp"
#include "database/Cluster.hpp"
#include "database/Session.hpp"
namespace {
const std::set<std::string> defaultClusterTypeNames =
{
"GENRE",
"ALBUMGROUPING",
"MOOD",
"ALBUMMOOD",
};
}
namespace Database {
void
ScanSettings::init(Session& session)
{
session.checkUniqueLocked();
pointer settings {get(session)};
if (settings)
return;
settings = session.getDboSession().add(std::make_unique<ScanSettings>());
settings.modify()->setClusterTypes(session, defaultClusterTypeNames );
}
ScanSettings::pointer
ScanSettings::get(Session& session)
{
session.checkSharedLocked();
return session.getDboSession().find<ScanSettings>();
}
std::set<std::filesystem::path>
ScanSettings::getAudioFileExtensions() const
{
auto extensions = StringUtils::splitString(_audioFileExtensions, " ");
return std::set<std::filesystem::path>(std::cbegin(extensions), std::cend(extensions));
}
void
ScanSettings::addAudioFileExtension(const std::filesystem::path& ext)
{
_audioFileExtensions += " " + ext.string();
}
std::vector<ClusterType::pointer>
ScanSettings::getClusterTypes() const
{
return std::vector<ClusterType::pointer>(std::cbegin(_clusterTypes), std::cend(_clusterTypes));
}
void
ScanSettings::setMediaDirectory(const std::filesystem::path& p)
{
_mediaDirectory = StringUtils::stringTrimEnd(p.string(), "/\\");
}
template <typename It>
std::set<std::string> getNames(It begin, It end)
{
std::set<std::string> names;
std::transform(begin, end, std::inserter(names, std::cbegin(names)),
[](const ClusterType::pointer& clusterType)
{
return clusterType->getName();
});
return names;
}
void
ScanSettings::setClusterTypes(Session& session, const std::set<std::string>& clusterTypeNames)
{
session.checkUniqueLocked();
bool needRescan {};
// Create any missing cluster type
for (const std::string& clusterTypeName : clusterTypeNames)
{
auto clusterType {ClusterType::getByName(session, clusterTypeName)};
if (!clusterType)
{
LMS_LOG(DB, INFO) << "Creating cluster type " << clusterTypeName;
clusterType = ClusterType::create(session, clusterTypeName);
_clusterTypes.insert(clusterType);
needRescan = true;
}
}
// Delete no longer existing cluster types
for (ClusterType::pointer& clusterType : _clusterTypes)
{
if (std::none_of(clusterTypeNames.begin(), clusterTypeNames.end(),
[clusterType](const std::string& name) { return name == clusterType->getName(); }))
{
LMS_LOG(DB, INFO) << "Deleting cluster type " << clusterType->getName();
clusterType.remove();
}
}
if (needRescan)
_scanVersion += 1;
}
void
ScanSettings::incScanVersion()
{
_scanVersion += 1;
}
} // namespace Database
+314
View File
@@ -0,0 +1,314 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include "database/Session.hpp"
#include <map>
#include <mutex>
#include <thread>
#include "utils/Exception.hpp"
#include "utils/Logger.hpp"
#include "database/Artist.hpp"
#include "database/Cluster.hpp"
#include "database/Db.hpp"
#include "database/Release.hpp"
#include "database/ScanSettings.hpp"
#include "database/Track.hpp"
#include "database/TrackBookmark.hpp"
#include "database/TrackArtistLink.hpp"
#include "database/TrackList.hpp"
#include "database/TrackFeatures.hpp"
#include "database/User.hpp"
namespace Database {
#define LMS_DATABASE_VERSION 12
using Version = std::size_t;
class VersionInfo
{
public:
using pointer = Wt::Dbo::ptr<VersionInfo>;
static VersionInfo::pointer getOrCreate(Session& session)
{
session.checkUniqueLocked();
pointer versionInfo {session.getDboSession().find<VersionInfo>()};
if (!versionInfo)
return session.getDboSession().add(std::make_unique<VersionInfo>());
return versionInfo;
}
static VersionInfo::pointer get(Session& session)
{
session.checkSharedLocked();
return session.getDboSession().find<VersionInfo>();
}
Version getVersion() const { return _version; }
void setVersion(Version version) { _version = static_cast<int>(version); }
template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, _version, "db_version");
}
private:
int _version {LMS_DATABASE_VERSION};
};
void
Session::doDatabaseMigrationIfNeeded()
{
auto uniqueTransaction {createUniqueTransaction()};
static const std::string outdatedMsg {"Outdated database, please rebuild it (delete the .db file and restart)"};
Version version;
try
{
version = VersionInfo::getOrCreate(*this)->getVersion();
LMS_LOG(DB, INFO) << "Database version = " << version << ", LMS binary version = " << LMS_DATABASE_VERSION;
if (version == LMS_DATABASE_VERSION)
return;
}
catch (std::exception& e)
{
LMS_LOG(DB, ERROR) << "Cannot get database version info: " << e.what();
throw LmsException {outdatedMsg};
}
while (version < LMS_DATABASE_VERSION)
{
LMS_LOG(DB, INFO) << "Migrating database from version " << version << "...";
if (version == 5)
{
_session.execute("DELETE FROM auth_token"); // format has changed
}
else if (version == 6)
{
// Just increment the scan version of the settings to make the next scheduled scan rescan everything
ScanSettings::get(*this).modify()->incScanVersion();
}
else if (version == 7)
{
_session.execute("DROP TABLE similarity_settings");
_session.execute("DROP TABLE similarity_settings_feature");
_session.execute("ALTER TABLE scan_settings ADD similarity_engine_type INTEGER NOT NULL DEFAULT(" + std::to_string(static_cast<int>(ScanSettings::SimilarityEngineType::Clusters)) + ")");
}
else if (version == 8)
{
// Better cover handling, need to rescan the whole files
// Just increment the scan version of the settings to make the next scheduled scan rescan everything
ScanSettings::get(*this).modify()->incScanVersion();
}
else if (version == 9)
{
_session.execute(R"(
CREATE TABLE IF NOT EXISTS "track_bookmark" (
"id" integer primary key autoincrement,
"version" integer not null,
"offset" integer,
"comment" text not null,
"track_id" bigint,
"user_id" bigint,
constraint "fk_track_bookmark_track" foreign key ("track_id") references "track" ("id") on delete cascade deferrable initially deferred,
constraint "fk_track_bookmark_user" foreign key ("user_id") references "user" ("id") on delete cascade deferrable initially deferred
);)");
}
else if (version == 10)
{
ScanSettings::get(*this).modify()->addAudioFileExtension(".m4b");
ScanSettings::get(*this).modify()->addAudioFileExtension(".alac");
}
else if (version == 11)
{
// Sanitize bad MBID, need to rescan the whole files
// Just increment the scan version of the settings to make the next scheduled scan rescan everything
ScanSettings::get(*this).modify()->incScanVersion();
}
else
{
LMS_LOG(DB, ERROR) << "Database version " << version << " cannot be handled using migration";
throw LmsException { LMS_DATABASE_VERSION > version ? outdatedMsg : "Server binary outdated, please upgrade it to handle this database"};
}
++version;
VersionInfo::get(*this).modify()->setVersion(LMS_DATABASE_VERSION);
}
}
Session::Session(Db& db)
: _db {db}
{
_session.setConnectionPool(_db.getConnectionPool());
_session.mapClass<VersionInfo>("version_info");
_session.mapClass<Artist>("artist");
_session.mapClass<AuthToken>("auth_token");
_session.mapClass<Cluster>("cluster");
_session.mapClass<ClusterType>("cluster_type");
_session.mapClass<Release>("release");
_session.mapClass<ScanSettings>("scan_settings");
_session.mapClass<Track>("track");
_session.mapClass<TrackBookmark>("track_bookmark");
_session.mapClass<TrackArtistLink>("track_artist_link");
_session.mapClass<TrackFeatures>("track_features");
_session.mapClass<TrackList>("tracklist");
_session.mapClass<TrackListEntry>("tracklist_entry");
_session.mapClass<User>("user");
}
enum class OwnedLock
{
None,
Shared,
Unique,
};
static thread_local std::map<std::shared_mutex*, OwnedLock> lockDebug;
UniqueTransaction::UniqueTransaction(std::shared_mutex& mutex, Wt::Dbo::Session& session)
: _lock {mutex},
_transaction {session}
{
assert(lockDebug[_lock.mutex()] == OwnedLock::None);
lockDebug[_lock.mutex()] = OwnedLock::Unique;
}
UniqueTransaction::~UniqueTransaction()
{
assert(lockDebug[_lock.mutex()] == OwnedLock::Unique);
lockDebug[_lock.mutex()] = OwnedLock::None;
}
SharedTransaction::SharedTransaction(std::shared_mutex& mutex, Wt::Dbo::Session& session)
: _lock {mutex},
_transaction {session}
{
assert(lockDebug[_lock.mutex()] == OwnedLock::None);
lockDebug[_lock.mutex()] = OwnedLock::Shared;
}
SharedTransaction::~SharedTransaction()
{
assert(lockDebug[_lock.mutex()] == OwnedLock::Shared);
lockDebug[_lock.mutex()] = OwnedLock::None;
}
void
Session::checkUniqueLocked()
{
assert(lockDebug[&_db.getMutex()] == OwnedLock::Unique);
}
void
Session::checkSharedLocked()
{
assert(lockDebug[&_db.getMutex()] != OwnedLock::None);
}
UniqueTransaction
Session::createUniqueTransaction()
{
return UniqueTransaction{_db.getMutex(), _session};
}
SharedTransaction
Session::createSharedTransaction()
{
return SharedTransaction{_db.getMutex(), _session};
}
void
Session::prepareTables()
{
// Creation case
try {
_session.createTables();
LMS_LOG(DB, INFO) << "Tables created";
}
catch (Wt::Dbo::Exception& e)
{
LMS_LOG(DB, ERROR) << "Cannot create tables: " << e.what();
}
doDatabaseMigrationIfNeeded();
// Indexes
{
auto uniqueTransaction {createUniqueTransaction()};
_session.execute("CREATE INDEX IF NOT EXISTS artist_name_idx ON artist(name)");
_session.execute("CREATE INDEX IF NOT EXISTS artist_sort_name_nocase_idx ON artist(sort_name COLLATE NOCASE)");
_session.execute("CREATE INDEX IF NOT EXISTS artist_mbid_idx ON artist(mbid)");
_session.execute("CREATE INDEX IF NOT EXISTS auth_token_user_idx ON auth_token(user_id)");
_session.execute("CREATE INDEX IF NOT EXISTS auth_token_expiry_idx ON auth_token(expiry)");
_session.execute("CREATE INDEX IF NOT EXISTS auth_token_value_idx ON auth_token(value)");
_session.execute("CREATE INDEX IF NOT EXISTS cluster_name_idx ON cluster(name)");
_session.execute("CREATE INDEX IF NOT EXISTS cluster_cluster_type_idx ON cluster(cluster_type_id)");
_session.execute("CREATE INDEX IF NOT EXISTS cluster_type_name_idx ON cluster_type(name)");
_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 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)");
_session.execute("CREATE INDEX IF NOT EXISTS track_mbid_idx ON track(mbid)");
_session.execute("CREATE INDEX IF NOT EXISTS track_release_idx ON track(release_id)");
_session.execute("CREATE INDEX IF NOT EXISTS track_year_idx ON track(year)");
_session.execute("CREATE INDEX IF NOT EXISTS track_original_year_idx ON track(original_year)");
_session.execute("CREATE INDEX IF NOT EXISTS tracklist_name_idx ON tracklist(name)");
_session.execute("CREATE INDEX IF NOT EXISTS tracklist_user_idx ON tracklist(user_id)");
_session.execute("CREATE INDEX IF NOT EXISTS track_features_track_idx ON track_features(track_id)");
_session.execute("CREATE INDEX IF NOT EXISTS track_artist_link_artist_idx ON track_artist_link(artist_id)");
_session.execute("CREATE INDEX IF NOT EXISTS track_artist_link_name_idx ON track_artist_link(name)");
_session.execute("CREATE INDEX IF NOT EXISTS track_artist_link_track_idx ON track_artist_link(track_id)");
_session.execute("CREATE INDEX IF NOT EXISTS track_artist_link_type_idx ON track_artist_link(type)");
_session.execute("CREATE INDEX IF NOT EXISTS track_bookmark_user_idx ON track_bookmark(user_id)");
_session.execute("CREATE INDEX IF NOT EXISTS track_bookmark_user_track_idx ON track_bookmark(user_id,track_id)");
}
// Initial settings tables
{
auto uniqueTransaction {createUniqueTransaction()};
ScanSettings::init(*this);
}
}
void
Session::optimize()
{
auto uniqueTransaction {createUniqueTransaction()};
_session.execute("ANALYZE");
}
} // namespace Database
+69
View File
@@ -0,0 +1,69 @@
/*
* 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 "database/SessionPool.hpp"
#include "database/Session.hpp"
#include "utils/Exception.hpp"
#include "utils/Logger.hpp"
namespace Database {
SessionPool::SessionPool(Db& database, std::size_t maxSessionCount)
: _db {database},
_maxSessionCount {maxSessionCount}
{
}
Session&
SessionPool::acquireSession()
{
std::scoped_lock lock {_mutex};
if (_freeSessions.empty())
{
if (_acquiredSessions.size() == _maxSessionCount)
throw LmsException {"Too many database sessions!"};
_freeSessions.emplace_back(std::make_unique<Session>(_db));
}
std::unique_ptr<Session> session {std::move(_freeSessions.back())};
_freeSessions.pop_back();
_acquiredSessions.push_back(std::move(session));
return *_acquiredSessions.back().get();
}
void
SessionPool::releaseSession(Session& sessionToRelease)
{
std::scoped_lock lock {_mutex};
auto it {std::find_if(std::begin(_acquiredSessions), std::end(_acquiredSessions), [&](const std::unique_ptr<Session>& session) { return session.get() == &sessionToRelease; })};
if (it == std::end(_acquiredSessions))
throw LmsException {"Unknown released Session!"};
std::unique_ptr<Session> session {std::move(*it)};
_acquiredSessions.erase(it);
_freeSessions.push_back(std::move(session));
}
} // namespace Database
+199
View File
@@ -0,0 +1,199 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SqlQuery.hpp"
#include <algorithm>
#include <cassert>
#include <sstream>
WhereClause&
WhereClause::And(const WhereClause& otherClause)
{
if (!otherClause._clause.empty()) {
if (!_clause.empty())
_clause += " AND ";
_clause += "(" + otherClause._clause + ")";
// Add associated bind args
for (const std::string& otherBindArg : otherClause._bindArgs)
{
_bindArgs.push_back(otherBindArg);
}
}
return *this;
}
WhereClause&
WhereClause::Or(const WhereClause& otherClause)
{
if (!otherClause._clause.empty()) {
if (!_clause.empty())
_clause += " OR ";
_clause += "(" + otherClause._clause + ")";
// Add associated bind args
for (const std::string& otherBindArg : otherClause._bindArgs)
{
_bindArgs.push_back(otherBindArg);
}
}
return *this;
}
std::string
WhereClause::get(void) const
{
if (!_clause.empty())
return "WHERE " + _clause;
else
return "";
}
WhereClause&
WhereClause::bind(const std::string& bindArg)
{
assert(_bindArgs.size() < static_cast<std::size_t>(std::count(_clause.begin(), _clause.end(), '?')));
_bindArgs.push_back(bindArg);
return *this;
}
InnerJoinClause::InnerJoinClause(const std::string& clause)
:_clause(clause)
{
}
InnerJoinClause&
InnerJoinClause::And(const InnerJoinClause& clause)
{
if (!_clause.empty())
_clause += " ";
_clause += "INNER JOIN " + clause._clause;
return *this;
}
SelectStatement::SelectStatement(const std::string& statement)
{
And(statement);
}
SelectStatement&
SelectStatement::And(const std::string& statement)
{
_statement.push_back(statement);
_statement.sort();
_statement.unique();
return *this;
}
std::string
SelectStatement::get() const
{
std::string res = "SELECT ";
for (std::list<std::string>::const_iterator it = _statement.begin(); it != _statement.end(); ++it)
{
if (it != _statement.begin())
res += ",";
res += *it;
}
return res;
}
GroupByStatement&
GroupByStatement::And(const GroupByStatement& statement)
{
if( _statement.empty() && !statement._statement.empty())
_statement = "GROUP BY ";
else if (!_statement.empty() && !statement._statement.empty())
_statement += ",";
_statement += statement._statement;
return *this;
}
FromClause::FromClause(const std::string& clause)
{
_clause.push_back(clause);
}
FromClause&
FromClause::And(const FromClause& clause)
{
for (const std::string fromClause : clause._clause)
{
_clause.push_back(fromClause);
}
_clause.sort();
_clause.unique();
return *this;
}
std::string
FromClause::get() const
{
std::ostringstream oss;
if (!_clause.empty())
{
oss << "FROM ";
for (std::list<std::string>::const_iterator it = _clause.begin(); it != _clause.end(); ++it) {
if (it != _clause.begin())
oss << ",";
oss << *it;
}
}
return oss.str();
}
std::string
SqlQuery::get(void) const
{
std::ostringstream oss;
oss << _selectStatement.get();
if (!_fromClause.get().empty())
oss << " " << _fromClause.get();
if (!_innerJoinClause.get().empty())
oss << " " << _innerJoinClause.get();
if (!_whereClause.get().empty())
oss << " " << _whereClause.get();
if (!_groupByStatement.get().empty())
oss << " " << _groupByStatement.get();
return oss.str();
}
+135
View File
@@ -0,0 +1,135 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <list>
#include <string>
class WhereClause
{
public:
WhereClause() {}
WhereClause(const std::string& clause) { _clause = clause; }
WhereClause& And(const WhereClause& clause);
WhereClause& Or(const WhereClause& clause);
// Arguments binding (for each '?' in where clause)
WhereClause& bind(const std::string& arg);
std::string get() const;
const std::list<std::string>& getBindArgs(void) const {return _bindArgs;}
private:
std::string _clause; // WHERE clause
std::list<std::string> _bindArgs;
};
class InnerJoinClause
{
public:
InnerJoinClause() {}
InnerJoinClause(const std::string& clause);
InnerJoinClause& And(const InnerJoinClause& clause);
std::string get() const { return _clause;}
private:
std::string _clause;
};
class GroupByStatement
{
public:
GroupByStatement() {}
GroupByStatement(const std::string& statement) { _statement = statement; }
GroupByStatement& And(const GroupByStatement& statement);
std::string get() const {return _statement;}
private:
std::string _statement; // SELECT statement
};
class SelectStatement
{
public:
SelectStatement() {};
SelectStatement(const std::string& item);
SelectStatement& And(const std::string& item);
std::string get() const;
private:
std::list<std::string> _statement;
};
class FromClause
{
public:
FromClause() {}
FromClause(const std::string& clause);
FromClause& And(const FromClause& clause);
std::string get() const;
private:
std::list<std::string> _clause;
};
class SqlQuery
{
public:
SelectStatement& select(void) { return _selectStatement;}
SelectStatement& select(const std::string& statement) { _selectStatement = SelectStatement(statement); return _selectStatement; }
FromClause& from(void) { return _fromClause; }
FromClause& from(const std::string& clause) { _whereClause = WhereClause(clause); return _fromClause; }
InnerJoinClause& innerJoin(void) { return _innerJoinClause; }
WhereClause& where(void) { return _whereClause; }
const WhereClause& where(void) const { return _whereClause; }
GroupByStatement& groupBy(void) { return _groupByStatement; }
const GroupByStatement& groupBy(void) const { return _groupByStatement; }
std::string get(void) const;
private:
SelectStatement _selectStatement; // SELECT statement
InnerJoinClause _innerJoinClause; // INNER JOIN
FromClause _fromClause; // FROM tables
WhereClause _whereClause; // WHERE clause
GroupByStatement _groupByStatement; // GROUP BY statement
};
+465
View File
@@ -0,0 +1,465 @@
/*
* Copyright (C) 2013-2016 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 "database/Track.hpp"
#include <Wt/Dbo/WtSqlTraits.h>
#include "database/Artist.hpp"
#include "database/Cluster.hpp"
#include "database/Release.hpp"
#include "database/TrackFeatures.hpp"
#include "database/Session.hpp"
#include "utils/Logger.hpp"
#include "SqlQuery.hpp"
namespace Database {
Track::Track(const std::filesystem::path& p)
:
_filePath( p.string() )
{
}
std::vector<Track::pointer>
Track::getAll(Session& session, std::optional<std::size_t> limit)
{
session.checkSharedLocked();
Wt::Dbo::collection<Track::pointer> res {session.getDboSession().find<Track>()
.limit(limit ? static_cast<int>(*limit) : -1)};
return std::vector<Track::pointer>(std::cbegin(res), std::cend(res));
}
std::vector<Track::pointer>
Track::getAllRandom(Session& session, std::optional<std::size_t> limit)
{
session.checkSharedLocked();
Wt::Dbo::collection<Track::pointer> res {session.getDboSession().find<Track>()
.limit(limit ? static_cast<int>(*limit) : -1)
.orderBy("RANDOM()")};
return std::vector<Track::pointer>(std::cbegin(res), std::cend(res));
}
std::vector<IdType>
Track::getAllIds(Session& session)
{
session.checkSharedLocked();
Wt::Dbo::collection<IdType> res = session.getDboSession().query<IdType>("SELECT id FROM track");
return std::vector<IdType>(res.begin(), res.end());
}
Track::pointer
Track::getByPath(Session& session, const std::filesystem::path& p)
{
session.checkSharedLocked();
return session.getDboSession().find<Track>().where("file_path = ?").bind(p.string());
}
Track::pointer
Track::getById(Session& session, IdType id)
{
session.checkSharedLocked();
return session.getDboSession().find<Track>()
.where("id = ?").bind(id);
}
Track::pointer
Track::getByMBID(Session& session, const UUID& mbid)
{
session.checkSharedLocked();
return session.getDboSession().find<Track>()
.where("mbid = ?").bind(std::string {mbid.getAsString()});
}
Track::pointer
Track::create(Session& session, const std::filesystem::path& p)
{
session.checkUniqueLocked();
Track::pointer res {session.getDboSession().add(std::make_unique<Track>(p))};
session.getDboSession().flush();
return res;
}
std::vector<std::filesystem::path>
Track::getAllPaths(Session& session)
{
session.checkSharedLocked();
Wt::Dbo::collection<std::string> res = session.getDboSession().query<std::string>("SELECT file_path FROM track");
return std::vector<std::filesystem::path>(res.begin(), res.end());
}
std::vector<Track::pointer>
Track::getMBIDDuplicates(Session& session)
{
session.checkSharedLocked();
Wt::Dbo::collection<pointer> res = session.getDboSession().query<pointer>( "SELECT track FROM track WHERE mbid in (SELECT mbid FROM track WHERE mbid <> '' GROUP BY mbid HAVING COUNT (*) > 1)").orderBy("track.release_id,track.disc_number,track.track_number,track.mbid");
return std::vector<pointer>(res.begin(), res.end());
}
std::vector<Track::pointer>
Track::getLastAdded(Session& session, const Wt::WDateTime& after, std::optional<std::size_t> limit)
{
session.checkSharedLocked();
Wt::Dbo::collection<Track::pointer> res = session.getDboSession().find<Track>()
.where("file_added > ?").bind(after)
.orderBy("file_added DESC")
.limit(limit ? static_cast<int>(*limit) : -1);
return std::vector<pointer>(res.begin(), res.end());
}
std::vector<Track::pointer>
Track::getAllWithMBIDAndMissingFeatures(Session& session)
{
session.checkSharedLocked();
Wt::Dbo::collection<pointer> res = session.getDboSession().query<pointer>
("SELECT t FROM track t")
.where("LENGTH(t.mbid) > 0")
.where("NOT EXISTS (SELECT * FROM track_features t_f WHERE t_f.track_id = t.id)");
return std::vector<pointer>(res.begin(), res.end());
}
std::vector<IdType>
Track::getAllIdsWithFeatures(Session& session, std::optional<std::size_t> limit)
{
session.checkSharedLocked();
Wt::Dbo::collection<IdType> res = session.getDboSession().query<IdType>
("SELECT t.id FROM track t")
.where("EXISTS (SELECT * from track_features t_f WHERE t_f.track_id = t.id)")
.limit(limit ? static_cast<int>(*limit) : -1);
return std::vector<IdType>(res.begin(), res.end());
}
std::vector<Cluster::pointer>
Track::getClusters(void) const
{
std::vector< Cluster::pointer > clusters;
std::copy(_clusters.begin(), _clusters.end(), std::back_inserter(clusters));
return clusters;
}
std::vector<IdType>
Track::getClusterIds(void) const
{
assert(self());
assert(IdIsValid(self()->id()));
assert(session());
Wt::Dbo::collection<IdType> res = session()->query<IdType>
("SELECT DISTINCT c.id FROM cluster c INNER JOIN track_cluster t_c ON t_c.cluster_id = c.id INNER JOIN track t ON t.id = t_c.track_id")
.where("t.id = ?").bind(self()->id());
return std::vector<IdType>(res.begin(), res.end());
}
bool
Track::hasTrackFeatures() const
{
return (_trackFeatures.lock() != Database::TrackFeatures::pointer());
}
static
Wt::Dbo::Query< Track::pointer >
getQuery(Session& session,
const std::set<IdType>& clusterIds,
const std::vector<std::string>& keywords)
{
session.checkSharedLocked();
WhereClause where;
std::ostringstream oss;
oss << "SELECT t FROM track t";
for (auto keyword : keywords)
where.And(WhereClause("t.name LIKE ?")).bind("%%" + keyword + "%%");
if (!clusterIds.empty())
{
oss << " 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 = ?")).bind(std::to_string(id));
where.And(clusterClause);
}
oss << " " << where.get();
if (!clusterIds.empty())
oss << " GROUP BY t.id HAVING COUNT(*) = " << clusterIds.size();
oss << " ORDER BY t.name COLLATE NOCASE";
Wt::Dbo::Query<Track::pointer> query = session.getDboSession().query<Track::pointer>( oss.str() );
for (const std::string& bindArg : where.getBindArgs())
query.bind(bindArg);
return query;
}
std::vector<Track::pointer>
Track::getByFilter(Session& session,
const std::set<IdType>& clusterIds,
const std::vector<std::string>& keywords,
std::optional<std::size_t> offset,
std::optional<std::size_t> size,
bool& moreResults)
{
session.checkSharedLocked();
Wt::Dbo::collection<pointer> collection = getQuery(session, clusterIds, keywords)
.limit(size ? static_cast<int>(*size) + 1 : -1)
.offset(offset ? static_cast<int>(*offset) : -1);
std::vector<pointer> res(collection.begin(), collection.end());
if (size && (res.size() == static_cast<std::size_t>(*size) + 1))
{
moreResults = true;
res.pop_back();
}
else
moreResults = false;
return res;
}
std::vector<Track::pointer>
Track::getSimilarTracks(Session& session,
const std::set<IdType>& tracks,
std::optional<std::size_t> offset,
std::optional<std::size_t> size)
{
assert(!tracks.empty());
session.checkSharedLocked();
std::ostringstream oss;
for (std::size_t i {}; i < tracks.size(); ++i)
{
if (!oss.str().empty())
oss << ", ";
oss << "?";
}
Wt::Dbo::Query<pointer> query {session.getDboSession().query<pointer>(
"SELECT t FROM track t"
" INNER JOIN track_cluster t_c ON t_c.track_id = t.id"
" AND t_c.cluster_id IN (SELECT c.id FROM cluster c INNER JOIN track_cluster t_c ON t_c.cluster_id = c.id WHERE t_c.track_id IN (" + oss.str() + "))"
" AND t.id NOT IN (" + oss.str() + ")")
.groupBy("t.id")
.orderBy("COUNT(*) DESC")
.limit(size ? static_cast<int>(*size) : -1)
.offset(offset ? static_cast<int>(*offset) : -1)};
for (IdType trackId : tracks)
query.bind(trackId );
for (IdType trackId : tracks)
query.bind(trackId );
Wt::Dbo::collection<pointer> res = query;
return std::vector<pointer>(res.begin(), res.end());
}
std::vector<Track::pointer>
Track::getByClusters(Session& session,
const std::set<IdType>& clusters)
{
assert(!clusters.empty());
session.checkSharedLocked();
bool moreResults;
return getByFilter(session,
clusters,
{},
{},
{},
moreResults);
}
void
Track::clearArtistLinks()
{
_trackArtistLinks.clear();
}
void
Track::addArtistLink(const Wt::Dbo::ptr<TrackArtistLink>& artistLink)
{
_trackArtistLinks.insert(artistLink);
}
void
Track::setClusters(const std::vector<Wt::Dbo::ptr<Cluster>>& clusters)
{
_clusters.clear();
for (const Wt::Dbo::ptr<Cluster>& cluster : clusters)
_clusters.insert(cluster);
}
void
Track::setFeatures(const Wt::Dbo::ptr<TrackFeatures>& features)
{
_trackFeatures = features;
}
std::optional<std::size_t>
Track::getTrackNumber(void) const
{
return (_trackNumber > 0) ? std::make_optional<std::size_t>(_trackNumber) : std::nullopt;
}
std::optional<std::size_t>
Track::getDiscNumber(void) const
{
return (_discNumber > 0) ? std::make_optional<std::size_t>(_discNumber) : std::nullopt;
}
std::optional<int>
Track::getYear() const
{
return (_year > 0) ? std::make_optional<int>(_year) : std::nullopt;
}
std::optional<int>
Track::getOriginalYear() const
{
return (_originalYear > 0) ? std::make_optional<int>(_originalYear) : std::nullopt;
}
std::optional<std::string>
Track::getCopyright() const
{
return _copyright != "" ? std::make_optional<std::string>(_copyright) : std::nullopt;
}
std::optional<std::string>
Track::getCopyrightURL() const
{
return _copyrightURL != "" ? std::make_optional<std::string>(_copyrightURL) : std::nullopt;
}
std::vector<Wt::Dbo::ptr<Artist>>
Track::getArtists(TrackArtistLink::Type type) const
{
assert(self());
assert(IdIsValid(self()->id()));
assert(session());
Wt::Dbo::collection<Wt::Dbo::ptr<Artist>> artists {session()->query<Artist::pointer>("SELECT a from artist a INNER JOIN track_artist_link t_a_l ON a.id = t_a_l.artist_id INNER JOIN track t ON t.id = t_a_l.track_id")
.where("t.id = ?").bind(self()->id())
.where("t_a_l.type = ?").bind(type)};
return std::vector<Wt::Dbo::ptr<Artist>>(artists.begin(), artists.end());
}
std::vector<IdType>
Track::getArtistIds(TrackArtistLink::Type type) const
{
assert(self());
assert(IdIsValid(self()->id()));
assert(session());
Wt::Dbo::collection<IdType> artists {session()->query<IdType>("SELECT a.id from artist a INNER JOIN track_artist_link t_a_l ON a.id = t_a_l.artist_id INNER JOIN track t ON t.id = t_a_l.track_id")
.where("t.id = ?").bind(self()->id())
.where("t_a_l.type = ?").bind(type)};
return std::vector<IdType>(artists.begin(), artists.end());
}
std::vector<Wt::Dbo::ptr<TrackArtistLink>>
Track::getArtistLinks() const
{
return std::vector<Wt::Dbo::ptr<TrackArtistLink>>(_trackArtistLinks.begin(), _trackArtistLinks.end());
}
Wt::Dbo::ptr<TrackFeatures>
Track::getTrackFeatures() const
{
return _trackFeatures.lock();
}
std::vector<std::vector<Cluster::pointer>>
Track::getClusterGroups(std::vector<ClusterType::pointer> clusterTypes, std::size_t size) const
{
assert(self());
assert(IdIsValid(self()->id()));
assert(session());
WhereClause where;
std::ostringstream oss;
oss << "SELECT c from cluster c INNER JOIN track t ON c.id = t_c.cluster_id INNER JOIN track_cluster t_c ON t_c.track_id = t.id INNER JOIN cluster_type c_type ON c.cluster_type_id = c_type.id";
where.And(WhereClause("t.id = ?")).bind(std::to_string(self()->id()));
{
WhereClause clusterClause;
for (auto clusterType : clusterTypes)
clusterClause.Or(WhereClause("c_type.id = ?")).bind(std::to_string(clusterType.id()));
where.And(clusterClause);
}
oss << " " << where.get();
oss << " GROUP BY c.id ORDER BY COUNT(c.id) DESC";
Wt::Dbo::Query<Cluster::pointer> query = session()->query<Cluster::pointer>( oss.str() );
for (const std::string& bindArg : where.getBindArgs())
query.bind(bindArg);
Wt::Dbo::collection<Cluster::pointer> queryRes = query;
std::map<IdType, std::vector<Cluster::pointer>> clusters;
for (auto cluster : queryRes)
{
if (clusters[cluster->getType().id()].size() < size)
clusters[cluster->getType().id()].push_back(cluster);
}
std::vector<std::vector<Cluster::pointer>> res;
for (auto cluster_list : clusters)
res.push_back(cluster_list.second);
return res;
}
} // namespace Database
@@ -0,0 +1,47 @@
/*
* Copyright (C) 2013-2016 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 "database/TrackArtistLink.hpp"
#include "database/Artist.hpp"
#include "database/Session.hpp"
#include "database/Track.hpp"
namespace Database {
TrackArtistLink::TrackArtistLink(Wt::Dbo::ptr<Track> track, Wt::Dbo::ptr<Artist> artist, Type type)
: _type {type},
_track {track},
_artist {artist}
{
}
TrackArtistLink::pointer
TrackArtistLink::create(Session& session, Wt::Dbo::ptr<Track> track, Wt::Dbo::ptr<Artist> artist,Type type)
{
session.checkUniqueLocked();
TrackArtistLink::pointer res {session.getDboSession().add(std::make_unique<TrackArtistLink>(track, artist, type))};
session.getDboSession().flush();
return res;
}
}
+91
View File
@@ -0,0 +1,91 @@
/*
* Copyright (C) 2020 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 "database/TrackBookmark.hpp"
#include "database/Session.hpp"
#include "database/Track.hpp"
#include "database/User.hpp"
namespace Database {
TrackBookmark::TrackBookmark(Wt::Dbo::ptr<User> user, Wt::Dbo::ptr<Track> track)
: _user {user},
_track {track}
{
}
TrackBookmark::pointer
TrackBookmark::create(Session& session, Wt::Dbo::ptr<User> user, Wt::Dbo::ptr<Track> track)
{
session.checkUniqueLocked();
TrackBookmark::pointer res {session.getDboSession().add(std::make_unique<TrackBookmark>(user, track))};
session.getDboSession().flush();
return res;
}
std::vector<TrackBookmark::pointer>
TrackBookmark::getAll(Session& session)
{
session.checkSharedLocked();
Wt::Dbo::collection<TrackBookmark::pointer> res {session.getDboSession().find<TrackBookmark>()};
return std::vector<TrackBookmark::pointer>(std::cbegin(res), std::cend(res));
}
std::vector<TrackBookmark::pointer>
TrackBookmark::getByUser(Session& session, Wt::Dbo::ptr<User> user)
{
session.checkSharedLocked();
Wt::Dbo::collection<TrackBookmark::pointer> res
{
session.getDboSession().find<TrackBookmark>()
.where("user_id = ?").bind(user.id())
};
return std::vector<TrackBookmark::pointer>(std::cbegin(res), std::cend(res));
}
TrackBookmark::pointer
TrackBookmark::getByUser(Session& session, Wt::Dbo::ptr<User> user, Wt::Dbo::ptr<Track> track)
{
session.checkSharedLocked();
return session.getDboSession().find<TrackBookmark>()
.where("user_id = ?").bind(user.id())
.where("track_id = ?").bind(track.id());
}
TrackBookmark::pointer
TrackBookmark::getById(Session& session, IdType id)
{
session.checkSharedLocked();
return session.getDboSession().find<TrackBookmark>()
.where("id = ?").bind(id);
}
} // namespace Database
+88
View File
@@ -0,0 +1,88 @@
/*
* Copyright (C) 2018 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 "database/TrackFeatures.hpp"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "database/Session.hpp"
#include "database/Track.hpp"
#include "utils/Logger.hpp"
namespace Database {
TrackFeatures::TrackFeatures(Wt::Dbo::ptr<Track> track, const std::string& jsonEncodedFeatures)
: _data(jsonEncodedFeatures),
_track(track)
{
}
TrackFeatures::pointer
TrackFeatures::create(Session& session, Wt::Dbo::ptr<Track> track, const std::string& jsonEncodedFeatures)
{
session.checkUniqueLocked();
return session.getDboSession().add(std::make_unique<TrackFeatures>(track, jsonEncodedFeatures));
}
FeatureValues
TrackFeatures::getFeatureValues(const FeatureName& featureNode) const
{
FeatureValuesMap featuresValuesMap {getFeatureValuesMap({featureNode})};
return std::move(featuresValuesMap[featureNode]);
}
FeatureValuesMap
TrackFeatures::getFeatureValuesMap(const std::unordered_set<FeatureName>& featureNames) const
{
try
{
std::istringstream iss {_data};
boost::property_tree::ptree root;
boost::property_tree::read_json(iss, root);
FeatureValuesMap res;
for (const FeatureName& featureName : featureNames)
{
FeatureValues& featureValues {res[featureName]};
auto node {root.get_child(featureName)};
bool hasChildren = false;
for (const auto& child : node.get_child(""))
{
hasChildren = true;
featureValues.push_back(child.second.get_value<double>());
}
if (!hasChildren)
featureValues.push_back(node.get_value<double>());
}
return res;
}
catch (boost::property_tree::ptree_error& error)
{
LMS_LOG(DB, ERROR) << "Track " << _track.id() << ": ptree exception: " << error.what();
return {};
}
}
} // namespace Database
+310
View File
@@ -0,0 +1,310 @@
/*
* Copyright (C) 2014 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 "database/TrackList.hpp"
#include <cassert>
#include "utils/Logger.hpp"
#include "database/Artist.hpp"
#include "database/Cluster.hpp"
#include "database/Release.hpp"
#include "database/Session.hpp"
#include "database/User.hpp"
#include "database/Track.hpp"
namespace Database {
TrackList::TrackList(const std::string& name, Type type, bool isPublic, Wt::Dbo::ptr<User> user)
: _name {name},
_type {type},
_isPublic {isPublic},
_user {user}
{
}
TrackList::pointer
TrackList::create(Session& session, const std::string& name, Type type, bool isPublic, Wt::Dbo::ptr<User> user)
{
session.checkUniqueLocked();
assert(user);
auto res = session.getDboSession().add( std::make_unique<TrackList>(name, type, isPublic, user) );
session.getDboSession().flush();
return res;
}
TrackList::pointer
TrackList::get(Session& session, const std::string& name, Type type, Wt::Dbo::ptr<User> user)
{
session.checkSharedLocked();
assert(user);
return session.getDboSession().find<TrackList>()
.where("name = ?").bind(name)
.where("type = ?").bind(type)
.where("user_id = ?").bind(user.id());
}
std::vector<TrackList::pointer>
TrackList::getAll(Session& session)
{
session.checkSharedLocked();
Wt::Dbo::collection<TrackList::pointer> res = session.getDboSession().find<TrackList>();
return std::vector<TrackList::pointer>(res.begin(), res.end());
}
std::vector<TrackList::pointer>
TrackList::getAll(Session& session, Wt::Dbo::ptr<User> user)
{
session.checkSharedLocked();
Wt::Dbo::collection<TrackList::pointer> res = session.getDboSession().find<TrackList>()
.where("user_id = ?").bind(user.id())
.orderBy("name COLLATE NOCASE");
return std::vector<TrackList::pointer>(res.begin(), res.end());
}
std::vector<TrackList::pointer>
TrackList::getAll(Session& session, Wt::Dbo::ptr<User> user, Type type)
{
session.checkSharedLocked();
Wt::Dbo::collection<TrackList::pointer> res = session.getDboSession().find<TrackList>()
.where("user_id = ?").bind(user.id())
.where("type = ?").bind(type)
.orderBy("name COLLATE NOCASE");
return std::vector<TrackList::pointer>(res.begin(), res.end());
}
TrackList::pointer
TrackList::getById(Session& session, IdType id)
{
session.checkSharedLocked();
return session.getDboSession().find<TrackList>().where("id = ?").bind(id);
}
std::vector<Wt::Dbo::ptr<TrackListEntry>>
TrackList::getEntries(std::optional<std::size_t> offset, std::optional<std::size_t> size) const
{
assert(session());
assert(IdIsValid(self()->id()));
Wt::Dbo::collection<Wt::Dbo::ptr<TrackListEntry>> entries =
session()->find<TrackListEntry>()
.where("tracklist_id = ?").bind(self().id())
.orderBy("id")
.limit(size ? static_cast<int>(*size) : -1)
.offset(offset ? static_cast<int>(*offset) : -1);
return std::vector<Wt::Dbo::ptr<TrackListEntry>>(entries.begin(), entries.end());
}
std::vector<Wt::Dbo::ptr<TrackListEntry>>
TrackList::getEntriesReverse(std::optional<std::size_t> offset, std::optional<std::size_t> size) const
{
assert(session());
assert(IdIsValid(self()->id()));
Wt::Dbo::collection<Wt::Dbo::ptr<TrackListEntry>> entries =
session()->find<TrackListEntry>()
.where("tracklist_id = ?").bind(self().id())
.orderBy("id DESC")
.limit(size ? static_cast<int>(*size) : -1)
.offset(offset ? static_cast<int>(*offset) : -1);
return std::vector<Wt::Dbo::ptr<TrackListEntry>>(entries.begin(), entries.end());
}
Wt::Dbo::ptr<TrackListEntry>
TrackList::getEntry(std::size_t pos) const
{
Wt::Dbo::ptr<TrackListEntry> res;
auto entries = getEntries(pos, 1);
if (!entries.empty())
res = entries.front();
return res;
}
std::size_t
TrackList::getCount() const
{
return _entries.size();
}
std::vector<Wt::Dbo::ptr<Cluster>>
TrackList::getClusters() const
{
assert(session());
assert(IdIsValid(self()->id()));
Wt::Dbo::collection<Cluster::pointer> res = session()->query<Cluster::pointer>("SELECT c from cluster c INNER JOIN track t ON c.id = t_c.cluster_id INNER JOIN track_cluster t_c ON t_c.track_id = t.id INNER JOIN tracklist_entry p_e ON p_e.track_id = t.id INNER JOIN tracklist p ON p.id = p_e.tracklist_id")
.where("p.id = ?").bind(self()->id())
.groupBy("c.id")
.orderBy("COUNT(c.id) DESC");
return std::vector<Wt::Dbo::ptr<Cluster>>(res.begin(), res.end());
}
bool
TrackList::hasTrack(IdType trackId) const
{
assert(session());
assert(IdIsValid(self()->id()));
Wt::Dbo::collection<TrackListEntry::pointer> res = session()->query<TrackListEntry::pointer>("SELECT p_e from tracklist_entry p_e INNER JOIN tracklist p ON p_e.tracklist_id = p.id")
.where("p_e.track_id = ?").bind(trackId)
.where("p.id = ?").bind(self()->id());
return res.size() > 0;
}
std::vector<Track::pointer>
TrackList::getSimilarTracks(std::optional<std::size_t> offset, std::optional<std::size_t> size) const
{
assert(session());
assert(IdIsValid(self()->id()));
Wt::Dbo::Query<Track::pointer> query {session()->query<Track::pointer>(
"SELECT t FROM track t"
" INNER JOIN track_cluster t_c ON t_c.track_id = t.id"
" WHERE "
" (t_c.cluster_id IN (SELECT c.id from cluster c INNER JOIN track t ON c.id = t_c.cluster_id INNER JOIN track_cluster t_c ON t_c.track_id = t.id INNER JOIN tracklist_entry p_e ON p_e.track_id = t.id INNER JOIN tracklist p ON p.id = p_e.tracklist_id WHERE p.id = ?)"
" AND t.id NOT IN (SELECT tracklist_t.id FROM track tracklist_t INNER JOIN tracklist_entry t_e ON t_e.track_id = tracklist_t.id WHERE t_e.tracklist_id = ?))"
)
.bind(self()->id())
.bind(self()->id())
.groupBy("t.id")
.orderBy("COUNT(*) DESC")
.limit(size ? static_cast<int>(*size) : -1)
.offset(offset ? static_cast<int>(*offset) : -1)};
Wt::Dbo::collection<Track::pointer> tracks = query;
return std::vector<Track::pointer>(tracks.begin(), tracks.end());
}
std::vector<IdType>
TrackList::getTrackIds() const
{
assert(session());
assert(IdIsValid(self()->id()));
Wt::Dbo::collection<IdType> res = session()->query<IdType>("SELECT p_e.track_id from tracklist_entry p_e INNER JOIN tracklist p ON p_e.tracklist_id = p.id")
.where("p.id = ?").bind(self()->id());
return std::vector<IdType>(res.begin(), res.end());
}
std::chrono::milliseconds
TrackList::getDuration() const
{
assert(session());
assert(IdIsValid(self()->id()));
using milli = std::chrono::duration<int, std::milli>;
Wt::Dbo::Query<milli> query {session()->query<milli>("SELECT SUM(duration) FROM track t INNER JOIN tracklist_entry p_e ON t.id = p_e.track_id")
.where("p_e.tracklist_id = ?").bind(self()->id())};
return query.resultValue();
}
std::vector<Artist::pointer>
TrackList::getTopArtists(std::size_t limit) const
{
assert(session());
assert(IdIsValid(self()->id()));
Wt::Dbo::collection<Artist::pointer> res = session()->query<Artist::pointer>("SELECT a 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 tracklist_entry p_e ON p_e.track_id = t.id INNER JOIN tracklist p ON p.id = p_e.tracklist_id")
.where("p.id = ?").bind(self()->id())
.groupBy("a.id")
.orderBy("COUNT(a.id) DESC")
.limit(static_cast<int>(limit));
return std::vector<Artist::pointer>(res.begin(), res.end());
}
std::vector<Release::pointer>
TrackList::getTopReleases(std::size_t limit) const
{
assert(session());
assert(IdIsValid(self()->id()));
Wt::Dbo::collection<Release::pointer> res = session()->query<Release::pointer>("SELECT r from release r INNER JOIN track t ON t.release_id = r.id INNER JOIN tracklist_entry p_e ON p_e.track_id = t.id INNER JOIN tracklist p ON p.id = p_e.tracklist_id")
.where("p.id = ?").bind(self()->id())
.groupBy("r.id")
.orderBy("COUNT(r.id) DESC")
.limit(static_cast<int>(limit));
return std::vector<Release::pointer>(res.begin(), res.end());
}
std::vector<Track::pointer>
TrackList::getTopTracks(std::size_t limit) const
{
assert(session());
assert(IdIsValid(self()->id()));
Wt::Dbo::collection<Track::pointer> res = session()->query<Track::pointer>("SELECT t from track t INNER JOIN tracklist_entry p_e ON p_e.track_id = t.id INNER JOIN tracklist p ON p.id = p_e.tracklist_id")
.where("p.id = ?").bind(self()->id())
.groupBy("t.id")
.orderBy("COUNT(t.id) DESC")
.limit(static_cast<int>(limit));
return std::vector<Track::pointer>(res.begin(), res.end());
}
TrackListEntry::TrackListEntry(Wt::Dbo::ptr<Track> track, Wt::Dbo::ptr<TrackList> tracklist)
: _track(track),
_tracklist(tracklist)
{
}
TrackListEntry::pointer
TrackListEntry::create(Session& session, Wt::Dbo::ptr<Track> track, Wt::Dbo::ptr<TrackList> tracklist)
{
session.checkUniqueLocked();
assert(track);
assert(tracklist);
auto res = session.getDboSession().add( std::make_unique<TrackListEntry>( track, tracklist) );
session.getDboSession().flush();
return res;
}
TrackListEntry::pointer
TrackListEntry::getById(Session& session, IdType id)
{
session.checkSharedLocked();
return session.getDboSession().find<TrackListEntry>().where("id = ?").bind(id);
}
} // namespace Database
+288
View File
@@ -0,0 +1,288 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include "database/User.hpp"
#include "database/Artist.hpp"
#include "database/Release.hpp"
#include "database/Session.hpp"
#include "database/Track.hpp"
#include "database/TrackList.hpp"
#include "utils/Logger.hpp"
namespace Database {
AuthToken::AuthToken(const std::string& value, const Wt::WDateTime& expiry, Wt::Dbo::ptr<User> user)
: _value {value}
, _expiry {expiry}
, _user {user}
{
}
AuthToken::pointer
AuthToken::create(Session& session, const std::string& value, const Wt::WDateTime& expiry, Wt::Dbo::ptr<User> user)
{
session.checkUniqueLocked();
auto res {session.getDboSession().add(std::make_unique<AuthToken>(value, expiry, user))};
session.getDboSession().flush();
return res;
}
void
AuthToken::removeExpiredTokens(Session& session, const Wt::WDateTime& now)
{
session.checkUniqueLocked();
session.getDboSession().execute
("DELETE FROM auth_token WHERE expiry < ?").bind(now);
}
AuthToken::pointer
AuthToken::getByValue(Session& session, const std::string& value)
{
session.checkSharedLocked();
return session.getDboSession().find<AuthToken>()
.where("value = ?").bind(value);
}
static const std::string playedListName {"__played_tracks__"};
static const std::string queuedListName {"__queued_tracks__"};
const std::set<Bitrate>
User::audioTranscodeAllowedBitrates =
{
64000,
96000,
128000,
192000,
320000,
};
User::User()
: _maxAudioTranscodeBitrate {static_cast<int>(*audioTranscodeAllowedBitrates.rbegin())}
{
}
User::User(const std::string& loginName, const PasswordHash& passwordHash)
: User()
{
_loginName = loginName;
_passwordHash = passwordHash.hash;
_passwordSalt = passwordHash.salt;
}
std::vector<User::pointer>
User::getAll(Session& session)
{
session.checkSharedLocked();
Wt::Dbo::collection<pointer> res = session.getDboSession().find<User>();
return std::vector<pointer>(res.begin(), res.end());
}
User::pointer
User::getDemo(Session& session)
{
session.checkSharedLocked();
pointer res = session.getDboSession().find<User>().where("type = ?").bind(Type::DEMO);
return res;
}
User::pointer
User::create(Session& session, const std::string& loginName, const PasswordHash& passwordHash)
{
session.checkUniqueLocked();
User::pointer user {session.getDboSession().add(std::make_unique<User>(loginName, passwordHash))};
TrackList::create(session, playedListName, TrackList::Type::Internal, false, user);
TrackList::create(session, queuedListName, TrackList::Type::Internal, false, user);
session.getDboSession().flush();
return user;
}
User::pointer
User::getById(Session& session, IdType id)
{
return session.getDboSession().find<User>().where("id = ?").bind( id );
}
User::pointer
User::getByLoginName(Session& session, const std::string& name)
{
return session.getDboSession().find<User>()
.where("login_name = ?").bind(name);
}
void
User::setAudioTranscodeBitrate(Bitrate bitrate)
{
_audioTranscodeBitrate = std::min(bitrate, static_cast<Bitrate>(_maxAudioTranscodeBitrate));
}
void
User::setMaxAudioTranscodeBitrate(Bitrate requestedBitrate)
{
Bitrate bitrate {*audioTranscodeAllowedBitrates.begin()};
for (auto allowedBitrate : audioTranscodeAllowedBitrates)
{
if (requestedBitrate < allowedBitrate)
break;
bitrate = allowedBitrate;
}
_maxAudioTranscodeBitrate = bitrate;
if (_audioTranscodeBitrate > _maxAudioTranscodeBitrate)
_audioTranscodeBitrate = _maxAudioTranscodeBitrate;
}
void
User::clearAuthTokens()
{
_authTokens.clear();
}
Bitrate
User::getAudioTranscodeBitrate(void) const
{
return _audioTranscodeBitrate;
}
std::size_t
User::getMaxAudioTranscodeBitrate(void) const
{
return _maxAudioTranscodeBitrate;
}
Wt::Dbo::ptr<TrackList>
User::getPlayedTrackList(Session& session) const
{
assert(self());
session.checkSharedLocked();
return TrackList::get(session, playedListName, TrackList::Type::Internal, self());
}
Wt::Dbo::ptr<TrackList>
User::getQueuedTrackList(Session& session) const
{
assert(self());
session.checkSharedLocked();
return TrackList::get(session, queuedListName, TrackList::Type::Internal, self());
}
void
User::starArtist(Wt::Dbo::ptr<Artist> artist)
{
if (_starredArtists.count(artist) == 0)
_starredArtists.insert(artist);
}
void
User::unstarArtist(Wt::Dbo::ptr<Artist> artist)
{
if (_starredArtists.count(artist) != 0)
_starredArtists.erase(artist);
}
bool
User::hasStarredArtist(Wt::Dbo::ptr<Artist> artist) const
{
return _starredArtists.count(artist) != 0;
}
std::vector<Wt::Dbo::ptr<Artist>>
User::getStarredArtists() const
{
return std::vector<Wt::Dbo::ptr<Artist>>(_starredArtists.begin(), _starredArtists.end());
}
void
User::starRelease(Wt::Dbo::ptr<Release> release)
{
if (_starredReleases.count(release) == 0)
_starredReleases.insert(release);
}
void
User::unstarRelease(Wt::Dbo::ptr<Release> release)
{
if (_starredReleases.count(release) != 0)
_starredReleases.erase(release);
}
bool
User::hasStarredRelease(Wt::Dbo::ptr<Release> release) const
{
return _starredReleases.count(release) != 0;
}
std::vector<Wt::Dbo::ptr<Release>>
User::getStarredReleases(std::optional<std::size_t> offset, std::optional<std::size_t> limit) const
{
Wt::Dbo::collection<Wt::Dbo::ptr<Release>> res = _starredReleases.find()
.offset(offset ? static_cast<int>(*offset) : -1)
.limit(limit ? static_cast<int>(*limit) : -1);
return std::vector<Wt::Dbo::ptr<Release>>(res.begin(), res.end());
}
void
User::starTrack(Wt::Dbo::ptr<Track> track)
{
if (_starredTracks.count(track) == 0)
_starredTracks.insert(track);
}
void
User::unstarTrack(Wt::Dbo::ptr<Track> track)
{
if (_starredTracks.count(track) != 0)
_starredTracks.erase(track);
}
bool
User::hasStarredTrack(Wt::Dbo::ptr<Track> track) const
{
return _starredTracks.count(track) != 0;
}
std::vector<Wt::Dbo::ptr<Track>>
User::getStarredTracks() const
{
return std::vector<Wt::Dbo::ptr<Track>>(_starredTracks.begin(), _starredTracks.end());
}
} // namespace Database
@@ -0,0 +1,118 @@
/*
* Copyright (C) 2015 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 <vector>
#include <Wt/WDateTime.h>
#include <Wt/Dbo/Dbo.h>
#include "utils/UUID.hpp"
#include "TrackArtistLink.hpp"
#include "Types.hpp"
namespace Database
{
class Cluster;
class ClusterType;
class Release;
class Session;
class Track;
class User;
class Artist : public Wt::Dbo::Dbo<Artist>
{
public:
using pointer = Wt::Dbo::ptr<Artist>;
Artist() {}
Artist(const std::string& name, const std::optional<UUID>& MBID = {});
// Accessors
static pointer getByMBID(Session& session, const UUID& MBID);
static pointer getById(Session& session, IdType id);
static std::vector<pointer> getByName(Session& session, const std::string& name);
static std::vector<pointer> getByClusters(Session& session,
const std::set<IdType>& clusters); // at least one track that belongs to these clusters
static std::vector<pointer> getByFilter(Session& session,
const std::set<IdType>& clusters, // if non empty, at least one artist that belongs to these clusters
const std::vector<std::string>& keywords, // if non empty, name must match all of these keywords
std::optional<TrackArtistLink::Type> linkType, // if set, only artists that have produced at least one track with this link type
std::optional<std::size_t> offset,
std::optional<std::size_t> size,
bool& moreExpected);
static std::vector<pointer> getAll(Session& session, std::optional<std::size_t> offset = {}, std::optional<std::size_t> size = {});
static std::vector<IdType> getAllIds(Session& session);
static std::vector<pointer> getAllOrphans(Session& session); // No track related
static std::vector<pointer> getLastAdded(Session& session, Wt::WDateTime after, std::optional<std::size_t> size = {});
// Accessors
const std::string& getName(void) const { return _name; }
std::optional<UUID> getMBID(void) const { return UUID::fromString(_MBID); }
std::vector<Wt::Dbo::ptr<Release>> getReleases(const std::set<IdType>& clusterIds = {}) const; // if non empty, get the releases that match all these clusters
std::size_t getReleaseCount() const;
std::vector<Wt::Dbo::ptr<Track>> getTracks(std::optional<TrackArtistLink::Type> linkType = {}) const;
std::vector<Wt::Dbo::ptr<Track>> getTracksWithRelease(std::optional<TrackArtistLink::Type> linkType = {}) const;
std::vector<Wt::Dbo::ptr<Track>> getRandomTracks(std::optional<std::size_t> count) const;
std::vector<pointer> getSimilarArtists(std::optional<std::size_t> offset = {}, std::optional<std::size_t> count = {}) const;
// Get the cluster of the tracks made by this artist
// Each clusters are grouped by cluster type, sorted by the number of occurence
// size is the max number of cluster per cluster type
std::vector<std::vector<Wt::Dbo::ptr<Cluster>>> getClusterGroups(std::vector<Wt::Dbo::ptr<ClusterType>> clusterTypes, std::size_t size) const;
void setMBID(const std::optional<UUID>& mbid) { _MBID = mbid ? mbid->getAsString() : ""; }
void setSortName(const std::string& sortName);
// Create
static pointer create(Session& session, const std::string& name, const std::optional<UUID>& UUID = {});
template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, _name, "name");
Wt::Dbo::field(a, _name, "sort_name");
Wt::Dbo::field(a, _MBID, "mbid");
Wt::Dbo::hasMany(a, _trackArtistLinks, Wt::Dbo::ManyToOne, "artist");
Wt::Dbo::hasMany(a, _starringUsers, Wt::Dbo::ManyToMany, "user_release_starred", "", Wt::Dbo::OnDeleteCascade);
}
private:
static const std::size_t _maxNameLength = 128;
std::string _name;
std::string _sortName;
std::string _MBID; // Musicbrainz Identifier
Wt::Dbo::collection<Wt::Dbo::ptr<TrackArtistLink>> _trackArtistLinks; // Tracks involving this artist
Wt::Dbo::collection<Wt::Dbo::ptr<User>> _starringUsers; // Users that starred this artist
};
} // namespace Database
@@ -0,0 +1,124 @@
/*
* Copyright (C) 2018 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 <string>
#include <vector>
#include <Wt/Dbo/Dbo.h>
#include <Wt/WDateTime.h>
#include "Types.hpp"
namespace Database {
class Track;
class ClusterType;
class ScanSettings;
class Session;
class Cluster : public Wt::Dbo::Dbo<Cluster>
{
public:
using pointer = Wt::Dbo::ptr<Cluster>;
Cluster();
Cluster(Wt::Dbo::ptr<ClusterType> type, std::string name);
// Find utility
static std::vector<pointer> getAll(Session& session);
static std::vector<pointer> getAllOrphans(Session& session);
static pointer getById(Session& session, IdType id);
// Create utility
static pointer create(Session& session, Wt::Dbo::ptr<ClusterType> type, std::string name);
// Accessors
const std::string& getName() const { return _name; }
Wt::Dbo::ptr<ClusterType> getType() const { return _clusterType; }
std::size_t getTracksCount() const { return _tracks.size(); }
std::vector<Wt::Dbo::ptr<Track>> getTracks(std::optional<std::size_t> offset = {}, std::optional<std::size_t> limit = {}) const;
std::set<IdType> getTrackIds() const;
std::size_t getReleasesCount() const;
void addTrack(Wt::Dbo::ptr<Track> track);
template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, _name, "name");
Wt::Dbo::belongsTo(a, _clusterType, "cluster_type", Wt::Dbo::OnDeleteCascade);
Wt::Dbo::hasMany(a, _tracks, Wt::Dbo::ManyToMany, "track_cluster", "", Wt::Dbo::OnDeleteCascade);
}
private:
static const std::size_t _maxNameLength = 128;
std::string _name;
Wt::Dbo::ptr<ClusterType> _clusterType;
Wt::Dbo::collection< Wt::Dbo::ptr<Track> > _tracks;
};
class ClusterType : public Wt::Dbo::Dbo<ClusterType>
{
public:
using pointer = Wt::Dbo::ptr<ClusterType>;
ClusterType() {}
ClusterType(std::string name);
static std::vector<pointer> getAllOrphans(Session& session);
static pointer getByName(Session& session, const std::string& name);
static pointer getById(Session& session, IdType id);
static std::vector<pointer> getAll(Session& session);
static pointer create(Session& session, const std::string& name);
static void remove(Session& session, const std::string& name);
// Accessors
const std::string& getName(void) const { return _name; }
std::vector<Cluster::pointer> getClusters() const;
Cluster::pointer getCluster(const std::string& name) const;
template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, _name, "name");
Wt::Dbo::hasMany(a, _clusters, Wt::Dbo::ManyToOne, "cluster_type");
Wt::Dbo::belongsTo(a, _scanSettings, "scan_settings", Wt::Dbo::OnDeleteCascade);
}
private:
static const std::size_t _maxNameLength = 128;
std::string _name;
Wt::Dbo::collection< Wt::Dbo::ptr<Cluster> > _clusters;
Wt::Dbo::ptr<ScanSettings> _scanSettings;
};
} // namespace Database
+48
View File
@@ -0,0 +1,48 @@
/*
* Copyright (C) 2019 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <filesystem>
#include <shared_mutex>
#include <Wt/Dbo/SqlConnectionPool.h>
namespace Database {
// Session living class handling the database and the login
class Db
{
public:
Db(const std::filesystem::path& dbPath);
private:
friend class Session;
std::shared_mutex& getMutex() { return _sharedMutex; }
Wt::Dbo::SqlConnectionPool& getConnectionPool() { return *_connectionPool; }
std::shared_mutex _sharedMutex;
std::unique_ptr<Wt::Dbo::SqlConnectionPool> _connectionPool;
};
} // namespace Database
@@ -0,0 +1,131 @@
/*
* Copyright (C) 2015 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 <Wt/Dbo/WtSqlTraits.h>
#include "utils/UUID.hpp"
#include "TrackArtistLink.hpp"
#include "Types.hpp"
namespace Database
{
class Artist;
class Cluster;
class ClusterType;
class Release;
class Track;
class User;
class Release : public Wt::Dbo::Dbo<Release>
{
public:
using pointer = Wt::Dbo::ptr<Release>;
Release() {}
Release(const std::string& name, const std::optional<UUID>& MBID = {});
// Accessors
static std::size_t getCount(Session& session);
static pointer getByMBID(Session& session, const UUID& MBID);
static std::vector<pointer> getByName(Session& session, const std::string& name);
static pointer getById(Session& session, IdType id);
static std::vector<pointer> getAllOrphans(Session& session); // no track related
static std::vector<pointer> getAll(Session& session, std::optional<std::size_t> offset = {}, std::optional<std::size_t> size = {});
static std::vector<IdType> getAllIds(Session& session);
static std::vector<pointer> getAllOrderedByArtist(Session& session, std::optional<std::size_t> offset = {}, std::optional<std::size_t> size = {});
static std::vector<pointer> getAllRandom(Session& session, std::optional<std::size_t> size = {});
static std::vector<pointer> getLastAdded(Session& session, const Wt::WDateTime& after, std::optional<std::size_t> offset = {}, std::optional<std::size_t> size = {});
static std::vector<pointer> getByYear(Session& session, int yearFrom, int yearTo, std::optional<std::size_t> offset = {}, std::optional<std::size_t> size = {});
static std::vector<pointer> getByClusters(Session& session, const std::set<IdType>& clusters);
static std::vector<pointer> getByFilter(Session& session,
const std::set<IdType>& clusters, // if non empty, at least one release that belongs to these clusters
const std::vector<std::string>& keywords, // if non empty, name must match all of these keywords
std::optional<std::size_t> offset,
std::optional<std::size_t> size,
bool& moreExpected);
std::vector<Wt::Dbo::ptr<Track>> getTracks(const std::set<IdType>& clusters = std::set<IdType>()) const;
std::size_t getTracksCount() const;
// Get the cluster of the tracks that belong to this release
// Each clusters are grouped by cluster type, sorted by the number of occurence (max to min)
// size is the max number of cluster per cluster type
std::vector<std::vector<Wt::Dbo::ptr<Cluster>>> getClusterGroups(std::vector<Wt::Dbo::ptr<ClusterType>> clusterTypes, std::size_t size) const;
// Create
static pointer create(Session& session, const std::string& name, const std::optional<UUID>& MBID = {});
// Utility functions
std::optional<int> getReleaseYear(bool originalDate = false) const; // 0 if unknown or various
std::optional<std::string> getCopyright() const;
std::optional<std::string> getCopyrightURL() const;
// Modifiers
void setTotalDiscNumber(std::size_t num) { _totalDiscNumber = static_cast<int>(num); }
void setTotalTrackNumber(std::size_t num) { _totalTrackNumber = static_cast<int>(num); }
// Accessors
std::string getName() const { return _name; }
std::optional<UUID> getMBID() const { return UUID::fromString(_MBID); }
std::optional<std::size_t> getTotalTrackNumber() const;
std::optional<std::size_t> getTotalDiscNumber() const;
std::chrono::milliseconds getDuration() const;
// Get the artists of this release
std::vector<Wt::Dbo::ptr<Artist> > getArtists(TrackArtistLink::Type type = TrackArtistLink::Type::Artist) const;
std::vector<Wt::Dbo::ptr<Artist> > getReleaseArtists() const { return getArtists(TrackArtistLink::Type::ReleaseArtist); }
bool hasVariousArtists() const;
std::vector<pointer> getSimilarReleases(std::optional<std::size_t> offset = {}, std::optional<std::size_t> count = {}) const;
void setMBID(const std::optional<UUID>& mbid) { _MBID = mbid ? mbid->getAsString() : ""; }
template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, _name, "name");
Wt::Dbo::field(a, _MBID, "mbid");
Wt::Dbo::field(a, _totalDiscNumber, "total_disc_number");
Wt::Dbo::field(a, _totalTrackNumber, "total_track_number");
Wt::Dbo::hasMany(a, _tracks, Wt::Dbo::ManyToOne, "release");
Wt::Dbo::hasMany(a, _starringUsers, Wt::Dbo::ManyToMany, "user_release_starred", "", Wt::Dbo::OnDeleteCascade);
}
private:
static const std::size_t _maxNameLength {128};
std::string _name;
std::string _MBID;
int _totalDiscNumber {};
int _totalTrackNumber {};
Wt::Dbo::collection<Wt::Dbo::ptr<Track>> _tracks; // Tracks in the release
Wt::Dbo::collection<Wt::Dbo::ptr<User>> _starringUsers; // Users that starred this release
};
} // namespace Database
@@ -0,0 +1,99 @@
/*
* Copyright (C) 2018 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 <filesystem>
#include <Wt/Dbo/Dbo.h>
#include <Wt/WTime.h>
namespace Database {
class ClusterType;
class Session;
class ScanSettings : public Wt::Dbo::Dbo<ScanSettings>
{
public:
using pointer = Wt::Dbo::ptr<ScanSettings>;
// Do not modify values (just add)
enum class UpdatePeriod {
Never = 0,
Daily,
Weekly,
Monthly
};
// Do not modify values (just add)
enum class SimilarityEngineType
{
Clusters = 0,
Features,
};
static void init(Session& session);
static pointer get(Session& session);
// Getters
std::size_t getScanVersion() const { return _scanVersion; }
std::filesystem::path getMediaDirectory() const { return _mediaDirectory; }
Wt::WTime getUpdateStartTime() const { return _startTime; }
UpdatePeriod getUpdatePeriod() const { return _updatePeriod; }
std::vector<Wt::Dbo::ptr<ClusterType>> getClusterTypes() const;
std::set<std::filesystem::path> getAudioFileExtensions() const;
SimilarityEngineType getSimilarityEngineType() const { return _similarityEngineType; }
// Setters
void addAudioFileExtension(const std::filesystem::path& ext);
void setMediaDirectory(const std::filesystem::path& p);
void setUpdateStartTime(Wt::WTime t) { _startTime = t; }
void setUpdatePeriod(UpdatePeriod p) { _updatePeriod = p; }
void setClusterTypes(Session& session, const std::set<std::string>& clusterTypeNames);
void setSimilarityEngineType(SimilarityEngineType type) { _similarityEngineType = type; }
void incScanVersion();
template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, _scanVersion, "scan_version");
Wt::Dbo::field(a, _mediaDirectory, "media_directory");
Wt::Dbo::field(a, _startTime, "start_time");
Wt::Dbo::field(a, _updatePeriod, "update_period");
Wt::Dbo::field(a, _audioFileExtensions, "audio_file_extensions");
Wt::Dbo::field(a, _similarityEngineType,"similarity_engine_type");
Wt::Dbo::hasMany(a, _clusterTypes, Wt::Dbo::ManyToOne, "scan_settings");
}
private:
int _scanVersion {};
std::string _mediaDirectory;
Wt::WTime _startTime = Wt::WTime {0,0,0};
UpdatePeriod _updatePeriod {UpdatePeriod::Never};
SimilarityEngineType _similarityEngineType {SimilarityEngineType::Clusters};
std::string _audioFileExtensions {".alac .mp3 .ogg .oga .aac .m4a .m4b .flac .wav .wma .aif .aiff .ape .mpc .shn .opus"};
Wt::Dbo::collection<Wt::Dbo::ptr<ClusterType>> _clusterTypes;
};
} // namespace Database
@@ -0,0 +1,93 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <mutex>
#include <map>
#include <memory>
#include <shared_mutex>
#include <vector>
#include <Wt/Dbo/Dbo.h>
#include <Wt/Dbo/SqlConnectionPool.h>
namespace Database {
class UniqueTransaction
{
public:
~UniqueTransaction();
private:
friend class Session;
UniqueTransaction(std::shared_mutex& mutex, Wt::Dbo::Session& session);
std::unique_lock<std::shared_mutex> _lock;
Wt::Dbo::Transaction _transaction;
};
class SharedTransaction
{
public:
~SharedTransaction();
private:
friend class Session;
SharedTransaction(std::shared_mutex& mutex, Wt::Dbo::Session& session);
std::shared_lock<std::shared_mutex> _lock;
Wt::Dbo::Transaction _transaction;
};
class Db;
class Session
{
public:
Session (Db& database);
Session(const Session&) = delete;
Session(Session&&) = delete;
Session& operator=(const Session&) = delete;
Session& operator=(Session&&) = delete;
[[nodiscard]] UniqueTransaction createUniqueTransaction();
[[nodiscard]] SharedTransaction createSharedTransaction();
void checkUniqueLocked();
void checkSharedLocked();
void optimize();
void prepareTables(); // need to run only once at startup
Wt::Dbo::Session& getDboSession() { return _session; }
private:
Session(std::shared_mutex& mutex, Wt::Dbo::SqlConnectionPool& connectionPool);
void doDatabaseMigrationIfNeeded();
Db& _db;
Wt::Dbo::Session _session;
};
} // namespace Database
@@ -0,0 +1,72 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <memory>
#include <mutex>
#include <vector>
#include "Session.hpp"
namespace Database {
class SessionPool
{
public:
class ScopedSession
{
public:
ScopedSession(SessionPool& pool) : _pool {pool}, _session {_pool.acquireSession()} {}
~ScopedSession() { _pool.releaseSession(_session); }
ScopedSession(const ScopedSession&) = delete;
ScopedSession(ScopedSession&&) = delete;
ScopedSession& operator=(const ScopedSession&) = delete;
ScopedSession& operator=(ScopedSession&&) = delete;
Session& get() { return _session; }
private:
SessionPool& _pool;
Session& _session;
};
SessionPool(Db& database, std::size_t maxSessionCount = 30);
SessionPool(const SessionPool&) = delete;
SessionPool(SessionPool&&) = delete;
SessionPool& operator=(const SessionPool&) = delete;
SessionPool& operator=(SessionPool&&) = delete;
private:
friend class ScopedSession;
Session& acquireSession();
void releaseSession(Session& session);
std::mutex _mutex;
Db& _db;
std::size_t _maxSessionCount;
std::vector<std::unique_ptr<Session>> _freeSessions;
std::vector<std::unique_ptr<Session>> _acquiredSessions;
};
} // namespace Database
@@ -0,0 +1,189 @@
/*
* Copyright (C) 2013-2016 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 <chrono>
#include <filesystem>
#include <optional>
#include <vector>
#include <string>
#include <Wt/Dbo/Dbo.h>
#include <Wt/WDateTime.h>
#include "utils/UUID.hpp"
#include "TrackArtistLink.hpp"
#include "Types.hpp"
namespace Database {
class Artist;
class Cluster;
class ClusterType;
class Release;
class TrackFeatures;
class TrackListEntry;
class TrackStats;
class User;
class Track : public Wt::Dbo::Dbo<Track>
{
public:
using pointer = Wt::Dbo::ptr<Track>;
Track() {}
Track(const std::filesystem::path& p);
// Find utility functions
static pointer getByPath(Session& session, const std::filesystem::path& p);
static pointer getById(Session& session, IdType id);
static pointer getByMBID(Session& session, const UUID& MBID);
static std::vector<pointer> getSimilarTracks(Session& session,
const std::set<IdType>& trackIds,
std::optional<std::size_t> offset = {},
std::optional<std::size_t> size = {});
static std::vector<pointer> getByClusters(Session& session,
const std::set<IdType>& clusters); // tracks that belong to these clusters
static std::vector<pointer> getByFilter(Session& session,
const std::set<IdType>& clusters, // if non empty, tracks that belong to these clusters
const std::vector<std::string>& keywords, // if non empty, name must match all of these keywords
std::optional<std::size_t> offset,
std::optional<std::size_t> size,
bool& moreExpected);
static std::vector<pointer> getAll(Session& session, std::optional<std::size_t> limit = {});
static std::vector<pointer> getAllRandom(Session& session, std::optional<std::size_t> limit = {});
static std::vector<IdType> getAllIds(Session& session);
static std::vector<std::filesystem::path> getAllPaths(Session& session);
static std::vector<pointer> getMBIDDuplicates(Session& session);
static std::vector<pointer> getLastAdded(Session& session, const Wt::WDateTime& after, std::optional<std::size_t> size = 1);
static std::vector<pointer> getAllWithMBIDAndMissingFeatures(Session& session);
static std::vector<IdType> getAllIdsWithFeatures(Session& session, std::optional<std::size_t> limit = {});
// Create utility
static pointer create(Session& session, const std::filesystem::path& p);
// Accessors
void setScanVersion(std::size_t version) { _scanVersion = version; }
void setTrackNumber(int num) { _trackNumber = num; }
void setDiscNumber(int num) { _discNumber = num; }
void setName(const std::string& name) { _name = std::string(name, 0, _maxNameLength); }
void setDuration(std::chrono::milliseconds duration) { _duration = duration; }
void setLastWriteTime(Wt::WDateTime time) { _fileLastWrite = time; }
void setAddedTime(Wt::WDateTime time) { _fileAdded = time; }
void setYear(int year) { _year = year; }
void setOriginalYear(int year) { _originalYear = year; }
void setHasCover(bool hasCover) { _hasCover = hasCover; }
void setMBID(const std::optional<UUID>& MBID) { _MBID = MBID ? MBID->getAsString() : ""; }
void setCopyright(const std::string& copyright) { _copyright = std::string(copyright, 0, _maxCopyrightLength); }
void setCopyrightURL(const std::string& copyrightURL) { _copyrightURL = std::string(copyrightURL, 0, _maxCopyrightURLLength); }
void clearArtistLinks();
void addArtistLink(const Wt::Dbo::ptr<TrackArtistLink>& artistLink);
void setRelease(Wt::Dbo::ptr<Release> release) { _release = release; }
void setClusters(const std::vector<Wt::Dbo::ptr<Cluster>>& clusters );
void setFeatures(const Wt::Dbo::ptr<TrackFeatures>& features);
std::size_t getScanVersion() const { return _scanVersion; }
std::optional<std::size_t> getTrackNumber() const;
std::optional<std::size_t> getDiscNumber() const;
std::string getName() const { return _name; }
std::filesystem::path getPath() const { return _filePath; }
std::chrono::milliseconds getDuration() const { return _duration; }
std::optional<int> getYear() const;
std::optional<int> getOriginalYear() const;
Wt::WDateTime getLastWriteTime() const { return _fileLastWrite; }
Wt::WDateTime getAddedTime() const { return _fileAdded; }
bool hasCover() const { return _hasCover; }
std::optional<UUID> getMBID() const { return UUID::fromString(_MBID); }
std::optional<std::string> getCopyright() const;
std::optional<std::string> getCopyrightURL() const;
std::vector<Wt::Dbo::ptr<Artist>> getArtists(TrackArtistLink::Type type = TrackArtistLink::Type::Artist) const;
std::vector<IdType> getArtistIds(TrackArtistLink::Type type = TrackArtistLink::Type::Artist) const;
std::vector<Wt::Dbo::ptr<TrackArtistLink>> getArtistLinks() const;
Wt::Dbo::ptr<Release> getRelease() const { return _release; }
std::vector<Wt::Dbo::ptr<Cluster>> getClusters() const;
std::vector<IdType> getClusterIds() const;
bool hasTrackFeatures() const;
Wt::Dbo::ptr<TrackFeatures> getTrackFeatures() const;
std::vector<std::vector<Wt::Dbo::ptr<Cluster>>> getClusterGroups(std::vector<Wt::Dbo::ptr<ClusterType>> clusterTypes, std::size_t size) const;
template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, _scanVersion, "scan_version");
Wt::Dbo::field(a, _trackNumber, "track_number");
Wt::Dbo::field(a, _discNumber, "disc_number");
Wt::Dbo::field(a, _name, "name");
Wt::Dbo::field(a, _duration, "duration");
Wt::Dbo::field(a, _year, "year");
Wt::Dbo::field(a, _originalYear, "original_year");
Wt::Dbo::field(a, _filePath, "file_path");
Wt::Dbo::field(a, _fileLastWrite, "file_last_write");
Wt::Dbo::field(a, _fileAdded, "file_added");
Wt::Dbo::field(a, _hasCover, "has_cover");
Wt::Dbo::field(a, _MBID, "mbid");
Wt::Dbo::field(a, _copyright, "copyright");
Wt::Dbo::field(a, _copyrightURL, "copyright_url");
Wt::Dbo::belongsTo(a, _release, "release", Wt::Dbo::OnDeleteCascade);
Wt::Dbo::hasMany(a, _trackArtistLinks, Wt::Dbo::ManyToOne, "track");
Wt::Dbo::hasMany(a, _clusters, Wt::Dbo::ManyToMany, "track_cluster", "", Wt::Dbo::OnDeleteCascade);
Wt::Dbo::hasMany(a, _playlistEntries, Wt::Dbo::ManyToOne, "track");
Wt::Dbo::hasMany(a, _starringUsers, Wt::Dbo::ManyToMany, "user_track_starred", "", Wt::Dbo::OnDeleteCascade);
Wt::Dbo::hasOne(a, _trackFeatures);
}
private:
static const std::size_t _maxNameLength = 128;
static const std::size_t _maxCopyrightLength = 128;
static const std::size_t _maxCopyrightURLLength = 128;
int _scanVersion = 0;
int _trackNumber = 0;
int _discNumber = 0;
std::string _name;
std::string _artistName;
std::string _releaseName;
std::chrono::duration<int, std::milli> _duration;
int _year = 0;
int _originalYear = 0;
std::string _filePath;
Wt::WDateTime _fileLastWrite;
Wt::WDateTime _fileAdded;
bool _hasCover = false;
std::string _MBID; // Musicbrainz Identifier
std::string _copyright;
std::string _copyrightURL;
Wt::Dbo::ptr<Release> _release;
Wt::Dbo::collection<Wt::Dbo::ptr<TrackArtistLink>> _trackArtistLinks;
Wt::Dbo::collection<Wt::Dbo::ptr<Cluster>> _clusters;
Wt::Dbo::collection<Wt::Dbo::ptr<TrackListEntry>> _playlistEntries;
Wt::Dbo::collection<Wt::Dbo::ptr<User>> _starringUsers;
Wt::Dbo::weak_ptr<TrackFeatures> _trackFeatures;
};
} // namespace database
@@ -0,0 +1,82 @@
/*
* Copyright (C) 2013-2016 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 <Wt/Dbo/Dbo.h>
#include "Types.hpp"
namespace Database {
class Artist;
class Session;
class Track;
class TrackArtistLink
{
public:
enum class Type
{
Artist, // regular artist
Arranger,
Composer,
Conductor,
Lyricist,
Mixer,
Performer,
Producer,
ReleaseArtist,
Remixer,
Writer,
};
using pointer = Wt::Dbo::ptr<TrackArtistLink>;
TrackArtistLink() = default;
TrackArtistLink(Wt::Dbo::ptr<Track> track, Wt::Dbo::ptr<Artist> artist, Type type);
static pointer create(Session& session, Wt::Dbo::ptr<Track> track, Wt::Dbo::ptr<Artist> artist,Type type);
Wt::Dbo::ptr<Track> getTrack() const { return _track; }
Wt::Dbo::ptr<Artist> getArtist() const { return _artist; }
Type getType() const { return _type; }
template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, _type, "type");
Wt::Dbo::field(a, _type, "name");
Wt::Dbo::belongsTo(a, _track, "track", Wt::Dbo::OnDeleteCascade);
Wt::Dbo::belongsTo(a, _artist, "artist", Wt::Dbo::OnDeleteCascade);
}
private:
Type _type;
std::string _name;
Wt::Dbo::ptr<Track> _track;
Wt::Dbo::ptr<Artist> _artist;
};
}
@@ -0,0 +1,82 @@
/*
* Copyright (C) 2020 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 <chrono>
#include <Wt/Dbo/Dbo.h>
#include "Types.hpp"
namespace Database {
class Session;
class Track;
class User;
class TrackBookmark : public Wt::Dbo::Dbo<TrackBookmark>
{
public:
using pointer = Wt::Dbo::ptr<TrackBookmark>;
TrackBookmark () = default;
TrackBookmark(Wt::Dbo::ptr<User> user, Wt::Dbo::ptr<Track> track);
// utility
static pointer create(Session& session, Wt::Dbo::ptr<User> user, Wt::Dbo::ptr<Track> track);
// Find utility functions
static std::vector<pointer> getAll(Session& session);
static std::vector<pointer> getByUser(Session& session, Wt::Dbo::ptr<User> user);
static pointer getByUser(Session& session, Wt::Dbo::ptr<User> user, Wt::Dbo::ptr<Track> track);
static pointer getById(Session& session, IdType id);
// Setters
void setOffset(std::chrono::milliseconds offset) { _offset = offset; }
void setComment(std::string_view comment) { _comment = comment; }
// Getters
std::chrono::milliseconds getOffset() const { return _offset; }
std::string_view getComment() const { return _comment; }
Wt::Dbo::ptr<Track> getTrack() const { return _track; }
Wt::Dbo::ptr<User> getUser() const { return _user; }
template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, _offset, "offset");
Wt::Dbo::field(a, _comment, "comment");
Wt::Dbo::belongsTo(a, _track, "track", Wt::Dbo::OnDeleteCascade);
Wt::Dbo::belongsTo(a, _user, "user", Wt::Dbo::OnDeleteCascade);
}
private:
static const std::size_t _maxCommentLength = 128;
std::chrono::duration<int, std::milli> _offset;
std::string _comment;
Wt::Dbo::ptr<User> _user;
Wt::Dbo::ptr<Track> _track;
};
} // namespace database
@@ -0,0 +1,71 @@
/*
* Copyright (C) 2018 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 <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <Wt/Dbo/Dbo.h>
#include "Types.hpp"
namespace Database {
class Session;
class Track;
using FeatureName = std::string;
using FeatureValues = std::vector<double>;
using FeatureValuesMap = std::unordered_map<FeatureName, FeatureValues>;
class TrackFeatures : public Wt::Dbo::Dbo<TrackFeatures>
{
public:
using pointer = Wt::Dbo::ptr<TrackFeatures>;
TrackFeatures() = default;
TrackFeatures(Wt::Dbo::ptr<Track> track, const std::string& jsonEncodedFeatures);
// Create utility
static pointer create(Session& session, Wt::Dbo::ptr<Track> track, const std::string& jsonEncodedFeatures);
FeatureValues getFeatureValues(const FeatureName& feature) const;
FeatureValuesMap getFeatureValuesMap(const std::unordered_set<FeatureName>& featureNames) const;
template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, _data, "data");
Wt::Dbo::belongsTo(a, _track, "track", Wt::Dbo::OnDeleteCascade);
}
private:
std::string _data;
Wt::Dbo::ptr<Track> _track;
};
} // namespace database
@@ -0,0 +1,150 @@
/*
* Copyright (C) 2014 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 <Wt/Dbo/Dbo.h>
#include "Types.hpp"
namespace Database {
class Artist;
class Cluster;
class Release;
class Session;
class Track;
class TrackListEntry;
class User;
class TrackList : public Wt::Dbo::Dbo<TrackList>
{
public:
using pointer = Wt::Dbo::ptr<TrackList>;
enum class Type
{
Playlist, // user controlled playlists
Internal, // current playqueue, history
};
TrackList() = default;
TrackList(const std::string& name, Type type, bool isPublic, Wt::Dbo::ptr<User> user);
// Stats utility
std::vector<Wt::Dbo::ptr<Artist>> getTopArtists(std::size_t limit = 1) const;
std::vector<Wt::Dbo::ptr<Release>> getTopReleases(std::size_t limit = 1) const;
std::vector<Wt::Dbo::ptr<Track>> getTopTracks(std::size_t limit = 1) const;
// Search utility
static pointer get(Session& session, const std::string& name, Type type, Wt::Dbo::ptr<User> user);
static pointer getById(Session& session, IdType tracklistId);
static std::vector<pointer> getAll(Session& session);
static std::vector<pointer> getAll(Session& session, Wt::Dbo::ptr<User> user);
static std::vector<pointer> getAll(Session& session, Wt::Dbo::ptr<User> user, Type type);
// Create utility
static pointer create(Session& session, const std::string& name, Type type, bool isPublic, Wt::Dbo::ptr<User> user);
// Accessors
std::string getName() const { return _name; }
bool isPublic() const { return _isPublic; }
Type getType() const { return _type; }
Wt::Dbo::ptr<User> getUser() const { return _user; }
// Modifiers
void setName(const std::string& name) { _name = name; }
void setIsPublic(bool isPublic) { _isPublic = isPublic; }
void clear() { _entries.clear(); }
// Get tracks, ordered by position
std::size_t getCount() const;
Wt::Dbo::ptr<TrackListEntry> getEntry(std::size_t pos) const;
std::vector<Wt::Dbo::ptr<TrackListEntry>> getEntries(std::optional<std::size_t> offset = {}, std::optional<std::size_t> size = {}) const;
std::vector<Wt::Dbo::ptr<TrackListEntry>> getEntriesReverse(std::optional<std::size_t> offset = {}, std::optional<std::size_t> size = {}) const;
std::vector<IdType> getTrackIds() const;
std::chrono::milliseconds getDuration() const;
// Get clusters, order by occurence
std::vector<Wt::Dbo::ptr<Cluster>> getClusters() const;
bool hasTrack(IdType trackId) const;
// Ordered from most clusters in common
std::vector<Wt::Dbo::ptr<Track>> getSimilarTracks(std::optional<std::size_t> offset = {}, std::optional<std::size_t> size = {}) const;
template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, _name, "name");
Wt::Dbo::field(a, _type, "type");
Wt::Dbo::field(a, _isPublic, "public");
Wt::Dbo::belongsTo(a, _user, "user", Wt::Dbo::OnDeleteCascade);
Wt::Dbo::hasMany(a, _entries, Wt::Dbo::ManyToOne, "tracklist");
}
private:
std::string _name;
Type _type {Type::Playlist};
bool _isPublic {false};
Wt::Dbo::ptr<User> _user;
Wt::Dbo::collection< Wt::Dbo::ptr<TrackListEntry> > _entries;
};
class TrackListEntry : public Wt::Dbo::Dbo<TrackListEntry>
{
public:
using pointer = Wt::Dbo::ptr<TrackListEntry>;
TrackListEntry() = default;
TrackListEntry(Wt::Dbo::ptr<Track> track, Wt::Dbo::ptr<TrackList> tracklist);
static pointer getById(Session& session, IdType id);
// Create utility
static pointer create(Session& session, Wt::Dbo::ptr<Track> track, Wt::Dbo::ptr<TrackList> tracklist);
// Accessors
Wt::Dbo::ptr<Track> getTrack() const { return _track; }
template<class Action>
void persist(Action& a)
{
Wt::Dbo::belongsTo(a, _track, "track", Wt::Dbo::OnDeleteCascade);
Wt::Dbo::belongsTo(a, _tracklist, "tracklist", Wt::Dbo::OnDeleteCascade);
}
private:
Wt::Dbo::ptr<Track> _track;
Wt::Dbo::ptr<TrackList> _tracklist;
};
} // namespace Database
@@ -0,0 +1,32 @@
/*
* Copyright (C) 2015 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 <Wt/Dbo/ptr.h>
namespace Database {
using IdType = Wt::Dbo::dbo_default_traits::IdType;
static inline bool IdIsValid(IdType id)
{
return id != Wt::Dbo::dbo_default_traits::invalidId();
}
}
+230
View File
@@ -0,0 +1,230 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <optional>
#include <vector>
#include <Wt/Dbo/Dbo.h>
#include <Wt/WDateTime.h>
#include "Types.hpp"
namespace Database {
class Artist;
class Release;
class Session;
class TrackList;
class Track;
// User selectable audio formats
// Do not change values
enum class AudioFormat
{
MP3 = 1,
OGG_OPUS = 2,
OGG_VORBIS = 3,
WEBM_VORBIS = 4,
MATROSKA_OPUS = 5,
};
using Bitrate = std::size_t;
class User;
class AuthToken
{
public:
using pointer = Wt::Dbo::ptr<AuthToken>;
AuthToken() = default;
AuthToken(const std::string& value, const Wt::WDateTime& expiry, Wt::Dbo::ptr<User> user);
// Utility
static pointer create(Session& session, const std::string& value, const Wt::WDateTime&expiry, Wt::Dbo::ptr<User> user);
static void removeExpiredTokens(Session& session, const Wt::WDateTime& now);
static pointer getByValue(Session& session, const std::string& value);
static pointer getById(Session& session, IdType tokenId);
// Accessors
const Wt::WDateTime& getExpiry() const { return _expiry; }
Wt::Dbo::ptr<User> getUser() const { return _user; }
const std::string& getValue() const { return _value; }
template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, _value, "value");
Wt::Dbo::field(a, _expiry, "expiry");
Wt::Dbo::belongsTo(a, _user, "user", Wt::Dbo::OnDeleteCascade);
}
private:
std::string _value;
Wt::WDateTime _expiry;
Wt::Dbo::ptr<User> _user;
};
class User : public Wt::Dbo::Dbo<User>
{
public:
using pointer = Wt::Dbo::ptr<User>;
static const std::size_t MinNameLength = 3;
static const std::size_t MaxNameLength = 15;
enum class Type
{
REGULAR,
ADMIN,
DEMO
};
struct PasswordHash
{
std::string salt;
std::string hash;
};
// list of audio parameters
static const std::set<Bitrate> audioTranscodeAllowedBitrates;
User();
User(const std::string& loginName, const PasswordHash& passwordHash);
// utility
static pointer create(Session& session, const std::string& loginName, const PasswordHash& passwordHash);
static pointer getById(Session& session, IdType id);
static pointer getByLoginName(Session& session, const std::string& loginName);
static std::vector<pointer> getAll(Session& session);
static pointer getDemo(Session& session);
// accessors
const std::string& getLoginName() const { return _loginName; }
PasswordHash getPasswordHash() const { return PasswordHash {_passwordSalt, _passwordHash}; }
Wt::WDateTime getLastLogin() const { return _lastLogin; }
std::size_t getAuthTokensCount() const { return _authTokens.size(); }
// write
void setLastLogin(const Wt::WDateTime& dateTime) { _lastLogin = dateTime; }
void setPasswordHash(const PasswordHash& passwordHash) { _passwordSalt = passwordHash.salt; _passwordHash = passwordHash.hash; }
void setType(Type type) { _type = type; }
void setAudioTranscodeEnable(bool value) { _audioTranscodeEnable = value; }
void setAudioTranscodeFormat(AudioFormat format) { _audioTranscodeFormat = format; }
void setAudioTranscodeBitrate(Bitrate bitrate);
void setMaxAudioTranscodeBitrate(Bitrate bitrate);
void setCurPlayingTrackPos(std::size_t pos) { _curPlayingTrackPos = pos; }
void setRadio(bool val) { _radio = val; }
void setRepeatAll(bool val) { _repeatAll = val; }
void clearAuthTokens();
// read
bool isAdmin() const { return _type == Type::ADMIN; }
bool isDemo() const { return _type == Type::DEMO; }
bool getAudioTranscodeEnable() const { return _audioTranscodeEnable; }
Bitrate getAudioTranscodeBitrate() const;
AudioFormat getAudioTranscodeFormat() const { return _audioTranscodeFormat; }
Bitrate getMaxAudioTranscodeBitrate() const;
std::size_t getCurPlayingTrackPos() const { return _curPlayingTrackPos; }
bool isRepeatAllSet() const { return _repeatAll; }
bool isRadioSet() const { return _radio; }
Wt::Dbo::ptr<TrackList> getPlayedTrackList(Session& session) const;
Wt::Dbo::ptr<TrackList> getQueuedTrackList(Session& session) const;
void starArtist(Wt::Dbo::ptr<Artist> artist);
void unstarArtist(Wt::Dbo::ptr<Artist> artist);
bool hasStarredArtist(Wt::Dbo::ptr<Artist> artist) const;
std::vector<Wt::Dbo::ptr<Artist>> getStarredArtists() const;
void starRelease(Wt::Dbo::ptr<Release> release);
void unstarRelease(Wt::Dbo::ptr<Release> release);
bool hasStarredRelease(Wt::Dbo::ptr<Release> release) const;
std::vector<Wt::Dbo::ptr<Release>> getStarredReleases(std::optional<std::size_t> offset = {}, std::optional<std::size_t> size = {}) const;
// Stars
void starTrack(Wt::Dbo::ptr<Track> track);
void unstarTrack(Wt::Dbo::ptr<Track> track);
bool hasStarredTrack(Wt::Dbo::ptr<Track> track) const;
std::vector<Wt::Dbo::ptr<Track>> getStarredTracks() const;
template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, _type, "type");
Wt::Dbo::field(a, _loginName, "login_name");
Wt::Dbo::field(a, _passwordSalt, "password_salt");
Wt::Dbo::field(a, _passwordHash, "password_hash");
Wt::Dbo::field(a, _lastLogin, "last_login");
Wt::Dbo::field(a, _maxAudioTranscodeBitrate, "max_audio_bitrate");
Wt::Dbo::field(a, _audioTranscodeEnable, "audio_transcode_enable");
Wt::Dbo::field(a, _audioTranscodeBitrate, "audio_transcode_bitrate");
Wt::Dbo::field(a, _audioTranscodeFormat, "audio_transcode_format");
// User's dynamic data
Wt::Dbo::field(a, _curPlayingTrackPos, "cur_playing_track_pos");
Wt::Dbo::field(a, _repeatAll, "repeat_all");
Wt::Dbo::field(a, _radio, "radio");
Wt::Dbo::hasMany(a, _tracklists, Wt::Dbo::ManyToOne, "user");
Wt::Dbo::hasMany(a, _starredArtists, Wt::Dbo::ManyToMany, "user_artist_starred", "", Wt::Dbo::OnDeleteCascade);
Wt::Dbo::hasMany(a, _starredReleases, Wt::Dbo::ManyToMany, "user_release_starred", "", Wt::Dbo::OnDeleteCascade);
Wt::Dbo::hasMany(a, _starredTracks, Wt::Dbo::ManyToMany, "user_track_starred", "", Wt::Dbo::OnDeleteCascade);
Wt::Dbo::hasMany(a, _authTokens, Wt::Dbo::ManyToOne, "user");
}
private:
static const bool defaultAudioTranscodeEnable {true};
static const AudioFormat defaultAudioTranscodeFormat {AudioFormat::OGG_OPUS};
static const Bitrate defaultAudioTranscodeBitrate {128000};
std::string _loginName;
std::string _passwordSalt;
std::string _passwordHash;
Wt::WDateTime _lastLogin;
// Admin defined settings
int _maxAudioTranscodeBitrate;
Type _type {Type::REGULAR};
// User defined settings
bool _audioTranscodeEnable {defaultAudioTranscodeEnable};
AudioFormat _audioTranscodeFormat {defaultAudioTranscodeFormat};
int _audioTranscodeBitrate {defaultAudioTranscodeBitrate};
// User's dynamic data (UI)
int _curPlayingTrackPos {}; // Current track position in queue
bool _repeatAll {};
bool _radio {};
Wt::Dbo::collection<Wt::Dbo::ptr<TrackList>> _tracklists;
Wt::Dbo::collection<Wt::Dbo::ptr<Artist>> _starredArtists;
Wt::Dbo::collection<Wt::Dbo::ptr<Release>> _starredReleases;
Wt::Dbo::collection<Wt::Dbo::ptr<Track>> _starredTracks;
Wt::Dbo::collection<Wt::Dbo::ptr<AuthToken>> _authTokens;
};
} // namespace Databas'