1740 lines
51 KiB
C++
1740 lines
51 KiB
C++
#include <Database.hpp>
|
|
#include <Void/Log/Log.hpp>
|
|
#include <Void/Math/Random.hpp>
|
|
#include <Void/Sqlite/Sqlite.hpp>
|
|
#include <algorithm>
|
|
#include <cstring>
|
|
#include <format>
|
|
#include <shared_mutex>
|
|
|
|
namespace Echoion::Api
|
|
{
|
|
|
|
// Internal implementation. The connection (open/close, WAL, busy-timeout,
|
|
// foreign keys) is owned by Void::Sqlite::Database; all queries go through
|
|
// its Statement/Transaction API. The migration mechanism is deliberately
|
|
// NOT switched to Void's user_version Migrator: existing databases track
|
|
// versions in schema_migrations with user_version=0, and migrations 2/3
|
|
// DROP tables — re-running them would destroy live data.
|
|
class DatabaseImpl
|
|
{
|
|
public:
|
|
|
|
Void::Sqlite::Database voidDb;
|
|
DatabaseConfig config;
|
|
bool initialized = false;
|
|
int version = 0;
|
|
};
|
|
|
|
Database::Database() : impl_(std::make_unique<DatabaseImpl>()) {}
|
|
|
|
Database::~Database()
|
|
{
|
|
// Only shutdown if not already shut down
|
|
if (!shutdown_.load()) {
|
|
shutdown();
|
|
}
|
|
}
|
|
|
|
Result<void> Database::initialize(const DatabaseConfig& config)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
impl_->config = config;
|
|
|
|
// Open via Void::Sqlite (RAII; sets WAL + busy_timeout + foreign_keys
|
|
// for read-write modes).
|
|
auto opened = Void::Sqlite::Database::open(
|
|
config.path, Void::Sqlite::OpenMode::ReadWriteCreate);
|
|
if (!opened) {
|
|
return fail(ErrorCode::DatabaseError,
|
|
std::format("Failed to open database: {}",
|
|
opened.error().message()));
|
|
}
|
|
impl_->voidDb = std::move(*opened);
|
|
|
|
// Honor the configured busy timeout (Void defaults to 5s).
|
|
[[maybe_unused]] auto bt = impl_->voidDb.exec(std::format(
|
|
"PRAGMA busy_timeout = {}",
|
|
static_cast<int>(config.busyTimeout.count())));
|
|
|
|
// Run migrations (without lock to avoid deadlock, since migrate() will
|
|
// acquire lock)
|
|
lock.unlock();
|
|
auto result = migrate();
|
|
lock.lock();
|
|
|
|
if (!result) {
|
|
return result;
|
|
}
|
|
|
|
impl_->initialized = true;
|
|
Void::Log::info("Database", "{}", std::format("Database initialized: {}", config.path));
|
|
return {};
|
|
}
|
|
|
|
void Database::shutdown()
|
|
{
|
|
// Check if already shut down to avoid mutex operations after
|
|
// destruction
|
|
if (shutdown_.exchange(true)) {
|
|
return; // Already shut down
|
|
}
|
|
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
// Close the connection via RAII (move-assign an empty Database).
|
|
impl_->voidDb = Void::Sqlite::Database{};
|
|
impl_->initialized = false;
|
|
}
|
|
|
|
bool Database::isInitialized() const
|
|
{
|
|
if (shutdown_.load()) {
|
|
return false;
|
|
}
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
return impl_->initialized;
|
|
}
|
|
|
|
Result<void> Database::migrate()
|
|
{
|
|
// Create migrations table
|
|
const char* createMigrationsTable = R"(
|
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
version INTEGER PRIMARY KEY,
|
|
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
);
|
|
)";
|
|
|
|
if (auto r = impl_->voidDb.exec(createMigrationsTable); !r) {
|
|
return fail(ErrorCode::DatabaseError, r.error().message());
|
|
}
|
|
|
|
// Get current version
|
|
int currentVersion = 0;
|
|
if (auto vstmt = impl_->voidDb.prepare(
|
|
"SELECT MAX(version) FROM schema_migrations")) {
|
|
auto& stmt = *vstmt;
|
|
if (stmt.step().value_or(false)) {
|
|
currentVersion = stmt.column_int(0);
|
|
}
|
|
}
|
|
|
|
// Migration 1: Initial schema
|
|
if (currentVersion < 1) {
|
|
const char* migration1 = R"(
|
|
CREATE TABLE IF NOT EXISTS playlists (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
name TEXT NOT NULL,
|
|
description TEXT,
|
|
created_by INTEGER NOT NULL,
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
is_public INTEGER DEFAULT 0,
|
|
external_id TEXT UNIQUE
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS playlist_tracks (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
playlist_id INTEGER NOT NULL,
|
|
track_url TEXT NOT NULL,
|
|
track_title TEXT NOT NULL,
|
|
track_artist TEXT,
|
|
track_thumbnail TEXT,
|
|
position INTEGER NOT NULL,
|
|
added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS playback_history (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
track_url TEXT NOT NULL,
|
|
track_title TEXT NOT NULL,
|
|
track_artist TEXT,
|
|
played_by INTEGER NOT NULL,
|
|
played_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
duration_ms INTEGER DEFAULT 0,
|
|
completed INTEGER DEFAULT 0
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS user_favorites (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
user_id INTEGER NOT NULL,
|
|
track_url TEXT NOT NULL,
|
|
track_title TEXT NOT NULL,
|
|
track_artist TEXT,
|
|
added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
UNIQUE(user_id, track_url)
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS subscriptions (
|
|
uid TEXT PRIMARY KEY,
|
|
nickname TEXT,
|
|
subscribed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_history_user ON playback_history(played_by);
|
|
CREATE INDEX IF NOT EXISTS idx_history_date ON playback_history(played_at);
|
|
CREATE INDEX IF NOT EXISTS idx_favorites_user ON user_favorites(user_id);
|
|
CREATE INDEX IF NOT EXISTS idx_playlist_tracks ON playlist_tracks(playlist_id);
|
|
CREATE INDEX IF NOT EXISTS idx_subscriptions_uid ON subscriptions(uid);
|
|
CREATE INDEX IF NOT EXISTS idx_playlists_external_id ON playlists(external_id);
|
|
)";
|
|
|
|
if (auto r = impl_->voidDb.exec(migration1); !r) {
|
|
return fail(ErrorCode::DatabaseError, r.error().message());
|
|
}
|
|
|
|
[[maybe_unused]] auto ins = impl_->voidDb.exec(
|
|
"INSERT INTO schema_migrations (version) VALUES (1)");
|
|
|
|
Void::Log::info("Database", "{}", "Database migration 1 applied");
|
|
}
|
|
|
|
// Migration 2: Fix subscriptions table to use UID
|
|
if (currentVersion < 2) {
|
|
const char* migration2 = R"(
|
|
DROP TABLE IF EXISTS subscriptions;
|
|
|
|
CREATE TABLE subscriptions (
|
|
uid TEXT PRIMARY KEY,
|
|
nickname TEXT,
|
|
subscribed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_subscriptions_uid ON subscriptions(uid);
|
|
)";
|
|
|
|
if (auto r = impl_->voidDb.exec(migration2); !r) {
|
|
return fail(ErrorCode::DatabaseError, r.error().message());
|
|
}
|
|
|
|
[[maybe_unused]] auto ins = impl_->voidDb.exec(
|
|
"INSERT INTO schema_migrations (version) VALUES (2)");
|
|
|
|
Void::Log::info("Database", "{}",
|
|
"Database migration 2 applied: subscriptions now use UID");
|
|
}
|
|
|
|
// Migration 3: Add external_id to playlists for YouTube playlist
|
|
// tracking
|
|
if (currentVersion < 3) {
|
|
const char* migration3 = R"(
|
|
DROP TABLE IF EXISTS playlists;
|
|
CREATE TABLE IF NOT EXISTS playlists (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
name TEXT NOT NULL,
|
|
description TEXT,
|
|
created_by INTEGER NOT NULL,
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
is_public INTEGER DEFAULT 0,
|
|
external_id TEXT UNIQUE
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_playlists_external_id ON playlists(external_id);
|
|
)";
|
|
|
|
[[maybe_unused]] auto r3 = impl_->voidDb.exec(migration3);
|
|
|
|
[[maybe_unused]] auto ins = impl_->voidDb.exec(
|
|
"INSERT INTO schema_migrations (version) VALUES (3)");
|
|
|
|
Void::Log::info("Database", "{}", "Database migration 3 applied: playlists now "
|
|
"support external_id");
|
|
}
|
|
|
|
// Migration 4: Add RPC tokens table for authentication
|
|
if (currentVersion < 4) {
|
|
const char* migration4 = R"(
|
|
CREATE TABLE IF NOT EXISTS rpc_tokens (
|
|
token TEXT PRIMARY KEY,
|
|
uid TEXT NOT NULL,
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
last_used_at TIMESTAMP,
|
|
FOREIGN KEY (uid) REFERENCES subscriptions(uid) ON DELETE CASCADE
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_rpc_tokens_uid ON rpc_tokens(uid);
|
|
)";
|
|
|
|
if (auto r = impl_->voidDb.exec(migration4); !r) {
|
|
return fail(ErrorCode::DatabaseError, r.error().message());
|
|
}
|
|
|
|
[[maybe_unused]] auto ins = impl_->voidDb.exec(
|
|
"INSERT INTO schema_migrations (version) VALUES (4)");
|
|
|
|
Void::Log::info("Database", "{}",
|
|
"Database migration 4 applied: RPC tokens table added");
|
|
}
|
|
|
|
// Migration 5: generic key/value store (instance persistence, small
|
|
// bits of state that don't deserve their own table)
|
|
if (currentVersion < 5) {
|
|
const char* migration5 = R"(
|
|
CREATE TABLE IF NOT EXISTS kv_store (
|
|
key TEXT PRIMARY KEY,
|
|
value TEXT,
|
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
);
|
|
)";
|
|
|
|
if (auto r = impl_->voidDb.exec(migration5); !r) {
|
|
return fail(ErrorCode::DatabaseError, r.error().message());
|
|
}
|
|
|
|
[[maybe_unused]] auto ins = impl_->voidDb.exec(
|
|
"INSERT INTO schema_migrations (version) VALUES (5)");
|
|
|
|
Void::Log::info("Database", "{}",
|
|
"Database migration 5 applied: kv_store table added");
|
|
}
|
|
|
|
// Migration 6: persist the shortened track URL alongside history,
|
|
// favorites and playlist tracks so YouTube links render short
|
|
// everywhere (they are reconstructed from the DB, which previously
|
|
// only kept the long originalUrl).
|
|
if (currentVersion < 6) {
|
|
const char* migration6 = R"(
|
|
ALTER TABLE playback_history ADD COLUMN track_short_url TEXT;
|
|
ALTER TABLE user_favorites ADD COLUMN track_short_url TEXT;
|
|
ALTER TABLE playlist_tracks ADD COLUMN track_short_url TEXT;
|
|
)";
|
|
|
|
if (auto r = impl_->voidDb.exec(migration6); !r) {
|
|
return fail(ErrorCode::DatabaseError, r.error().message());
|
|
}
|
|
|
|
[[maybe_unused]] auto ins = impl_->voidDb.exec(
|
|
"INSERT INTO schema_migrations (version) VALUES (6)");
|
|
|
|
Void::Log::info("Database", "{}",
|
|
"Database migration 6 applied: track_short_url columns added");
|
|
}
|
|
|
|
// Migration 7: aggregate-stats support — skip tracking on history and
|
|
// a queue-addition log (daily counters + top requesters for the web
|
|
// dashboard).
|
|
if (currentVersion < 7) {
|
|
const char* migration7 = R"(
|
|
ALTER TABLE playback_history ADD COLUMN skipped INTEGER DEFAULT 0;
|
|
CREATE TABLE IF NOT EXISTS queue_log (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
uid TEXT,
|
|
nickname TEXT,
|
|
added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_queue_log_date ON queue_log(added_at);
|
|
)";
|
|
|
|
if (auto r = impl_->voidDb.exec(migration7); !r) {
|
|
return fail(ErrorCode::DatabaseError, r.error().message());
|
|
}
|
|
|
|
[[maybe_unused]] auto ins = impl_->voidDb.exec(
|
|
"INSERT INTO schema_migrations (version) VALUES (7)");
|
|
|
|
Void::Log::info("Database", "{}",
|
|
"Database migration 7 applied: skip tracking and queue log");
|
|
}
|
|
|
|
// Migration 8: persist track thumbnails with history and favorites so
|
|
// the web UI can show original artwork for reconstructed tracks
|
|
// (playlist_tracks already stores track_thumbnail since v1).
|
|
if (currentVersion < 8) {
|
|
const char* migration8 = R"(
|
|
ALTER TABLE playback_history ADD COLUMN track_thumbnail TEXT;
|
|
ALTER TABLE user_favorites ADD COLUMN track_thumbnail TEXT;
|
|
)";
|
|
|
|
if (auto r = impl_->voidDb.exec(migration8); !r) {
|
|
return fail(ErrorCode::DatabaseError, r.error().message());
|
|
}
|
|
|
|
[[maybe_unused]] auto ins = impl_->voidDb.exec(
|
|
"INSERT INTO schema_migrations (version) VALUES (8)");
|
|
|
|
Void::Log::info("Database", "{}",
|
|
"Database migration 8 applied: track_thumbnail columns added");
|
|
}
|
|
|
|
// Migration 9 belonged to a retired embedded browser feature. Preserve
|
|
// its version slot so existing databases and later migrations remain
|
|
// compatible, but new Echoion databases no longer create its tables.
|
|
if (currentVersion < 9) {
|
|
[[maybe_unused]] auto ins = impl_->voidDb.exec(
|
|
"INSERT INTO schema_migrations (version) VALUES (9)");
|
|
|
|
Void::Log::info("Database", "{}", "Database migration 9 retired");
|
|
}
|
|
|
|
// Migration 10: cached TeamSpeak avatars for the web UI, keyed by uid,
|
|
// so avatars survive the client going offline/out-of-view.
|
|
if (currentVersion < 10) {
|
|
const char* migration10 = R"(
|
|
CREATE TABLE IF NOT EXISTS cached_avatars (
|
|
uid TEXT PRIMARY KEY,
|
|
mime TEXT NOT NULL,
|
|
data TEXT NOT NULL, -- base64-encoded image bytes
|
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
);
|
|
)";
|
|
|
|
if (auto r = impl_->voidDb.exec(migration10); !r) {
|
|
return fail(ErrorCode::DatabaseError, r.error().message());
|
|
}
|
|
|
|
[[maybe_unused]] auto ins = impl_->voidDb.exec(
|
|
"INSERT INTO schema_migrations (version) VALUES (10)");
|
|
|
|
Void::Log::info("Database", "{}",
|
|
"Database migration 10 applied: cached_avatars table added");
|
|
}
|
|
|
|
// Migration 11: remember the source avatar URL alongside the cached
|
|
// bytes, so an offline user's avatar can be re-fetched from it.
|
|
if (currentVersion < 11) {
|
|
// ADD COLUMN is a no-op-safe schema bump; ignore "duplicate column"
|
|
// if a prior partial run already added it.
|
|
[[maybe_unused]] auto alt = impl_->voidDb.exec(
|
|
"ALTER TABLE cached_avatars ADD COLUMN url TEXT;");
|
|
|
|
[[maybe_unused]] auto ins = impl_->voidDb.exec(
|
|
"INSERT INTO schema_migrations (version) VALUES (11)");
|
|
|
|
Void::Log::info("Database", "{}",
|
|
"Database migration 11 applied: cached_avatars.url added");
|
|
}
|
|
|
|
impl_->version = 11;
|
|
return {};
|
|
}
|
|
|
|
int Database::getCurrentVersion() const { return impl_->version; }
|
|
|
|
// Playlist operations
|
|
Result<uint64_t> Database::createPlaylist(const std::string& name,
|
|
const std::string& description,
|
|
uint64_t createdBy, bool isPublic,
|
|
const std::string& externalId)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
const char* sql = externalId.empty() ? R"(
|
|
INSERT INTO playlists (name, description, created_by, is_public)
|
|
VALUES (?, ?, ?, ?);
|
|
)"
|
|
: R"(
|
|
INSERT INTO playlists (name, description, created_by, is_public, external_id)
|
|
VALUES (?, ?, ?, ?, ?);
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
stmt.bind(1, name)
|
|
.bind(2, description)
|
|
.bind(3, static_cast<std::int64_t>(createdBy))
|
|
.bind(4, isPublic ? 1 : 0);
|
|
if (!externalId.empty()) {
|
|
stmt.bind(5, externalId);
|
|
}
|
|
|
|
if (auto stepRes = stmt.step(); !stepRes) {
|
|
return fail(ErrorCode::DatabaseError, stepRes.error().message());
|
|
}
|
|
|
|
return static_cast<uint64_t>(impl_->voidDb.last_insert_rowid());
|
|
}
|
|
|
|
Result<uint64_t> Database::getOrCreatePlaylistByExternalId(
|
|
const std::string& externalId,
|
|
const std::string& name,
|
|
const std::string& description,
|
|
uint64_t createdBy,
|
|
bool isPublic)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
// First try to find existing playlist by external_id
|
|
const char* selectSql = R"(
|
|
SELECT id FROM playlists WHERE external_id = ?;
|
|
)";
|
|
|
|
if (auto stmtRes = impl_->voidDb.prepare(selectSql)) {
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, externalId);
|
|
if (auto s = stmt.step(); s && *s) {
|
|
return static_cast<uint64_t>(stmt.column_int(0));
|
|
}
|
|
}
|
|
|
|
// Not found, create new playlist with external_id
|
|
lock.unlock();
|
|
return createPlaylist(name, description, createdBy, isPublic,
|
|
externalId);
|
|
}
|
|
|
|
Result<std::optional<Playlist>> Database::getPlaylist(uint64_t id)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
const char* sql = R"(
|
|
SELECT id, name, description, created_by, created_at, updated_at, is_public
|
|
FROM playlists WHERE id = ?;
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, static_cast<std::int64_t>(id));
|
|
|
|
Playlist playlist;
|
|
bool found = false;
|
|
|
|
if (auto s = stmt.step(); s && *s) {
|
|
found = true;
|
|
playlist.id = static_cast<uint64_t>(stmt.column_int(0));
|
|
playlist.name = stmt.column_text(1);
|
|
playlist.description = stmt.column_text(2);
|
|
playlist.createdBy = static_cast<uint64_t>(stmt.column_int(3));
|
|
playlist.isPublic = stmt.column_int(6) != 0;
|
|
}
|
|
|
|
if (!found) {
|
|
return std::optional<Playlist>{};
|
|
}
|
|
|
|
// Load tracks
|
|
const char* tracksSql = R"(
|
|
SELECT track_url, track_title, track_artist, track_thumbnail, track_short_url
|
|
FROM playlist_tracks
|
|
WHERE playlist_id = ?
|
|
ORDER BY position;
|
|
)";
|
|
|
|
if (auto tracksRes = impl_->voidDb.prepare(tracksSql)) {
|
|
auto& tracks = *tracksRes;
|
|
tracks.bind(1, static_cast<std::int64_t>(id));
|
|
|
|
while (true) {
|
|
auto s = tracks.step();
|
|
if (!s || !*s) {
|
|
break;
|
|
}
|
|
TrackInfo track;
|
|
track.originalUrl = tracks.column_text(0);
|
|
track.title = tracks.column_text(1);
|
|
track.artist = tracks.column_text(2);
|
|
if (!tracks.is_null(3)) {
|
|
track.thumbnailUrl = tracks.column_text(3);
|
|
}
|
|
if (!tracks.is_null(4)) {
|
|
if (auto shortUrl = tracks.column_text(4);
|
|
!shortUrl.empty()) {
|
|
track.shortenedUrl = shortUrl;
|
|
}
|
|
}
|
|
playlist.tracks.push_back(track);
|
|
}
|
|
}
|
|
|
|
return playlist;
|
|
}
|
|
|
|
Result<std::vector<Playlist>> Database::getUserPlaylists(uint64_t userId)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
std::vector<Playlist> playlists;
|
|
|
|
const char* sql = R"(
|
|
SELECT id, name, description, created_at, is_public
|
|
FROM playlists
|
|
WHERE created_by = ? OR is_public = 1
|
|
ORDER BY updated_at DESC;
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, static_cast<std::int64_t>(userId));
|
|
|
|
while (stmt.step().value_or(false)) {
|
|
Playlist playlist;
|
|
playlist.id = static_cast<uint64_t>(stmt.column_int(0));
|
|
playlist.name = stmt.column_text(1);
|
|
playlist.description = stmt.column_text(2);
|
|
playlist.isPublic = stmt.column_int(4) != 0;
|
|
playlists.push_back(playlist);
|
|
}
|
|
|
|
return playlists;
|
|
}
|
|
|
|
Result<std::vector<Playlist>> Database::getAllPlaylists()
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
std::vector<Playlist> playlists;
|
|
|
|
const char* sql = R"(
|
|
SELECT id, name, description, created_by, is_public, external_id
|
|
FROM playlists
|
|
ORDER BY updated_at DESC;
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
while (stmt.step().value_or(false)) {
|
|
Playlist playlist;
|
|
playlist.id = static_cast<uint64_t>(stmt.column_int(0));
|
|
playlist.name = stmt.column_text(1);
|
|
playlist.description = stmt.column_text(2);
|
|
playlist.createdBy = static_cast<uint64_t>(stmt.column_int(3));
|
|
playlist.isPublic = stmt.column_int(4) != 0;
|
|
playlist.externalId = stmt.column_text(5);
|
|
playlists.push_back(playlist);
|
|
}
|
|
|
|
return playlists;
|
|
}
|
|
|
|
Result<void> Database::deletePlaylist(uint64_t id)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
const char* sql = "DELETE FROM playlists WHERE id = ?;";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, static_cast<std::int64_t>(id));
|
|
[[maybe_unused]] auto stepRes = stmt.step();
|
|
|
|
return {};
|
|
}
|
|
|
|
Result<void> Database::addTrackToPlaylist(uint64_t playlistId,
|
|
const TrackInfo& track,
|
|
uint32_t position)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
const char* sql = R"(
|
|
INSERT INTO playlist_tracks
|
|
(playlist_id, track_url, track_title, track_artist, track_thumbnail, track_short_url, position)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?);
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, static_cast<std::int64_t>(playlistId))
|
|
.bind(2, track.originalUrl)
|
|
.bind(3, track.title)
|
|
.bind(4, track.artist)
|
|
.bind(5, track.thumbnailUrl.value_or(""))
|
|
.bind(6, track.shortenedUrl.value_or(""))
|
|
.bind(7, static_cast<int>(position));
|
|
[[maybe_unused]] auto stepRes = stmt.step();
|
|
|
|
// Update playlist timestamp
|
|
[[maybe_unused]] auto upd = impl_->voidDb.exec(
|
|
std::format("UPDATE playlists SET updated_at = "
|
|
"CURRENT_TIMESTAMP WHERE id = {}",
|
|
playlistId));
|
|
|
|
return {};
|
|
}
|
|
|
|
// Playback history
|
|
Result<void> Database::recordPlayback(const TrackInfo& track,
|
|
uint64_t playedBy,
|
|
std::chrono::milliseconds duration,
|
|
bool completed)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
const char* sql = R"(
|
|
INSERT INTO playback_history
|
|
(track_url, track_title, track_artist, played_by, duration_ms, completed, track_short_url, track_thumbnail)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?);
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, track.originalUrl)
|
|
.bind(2, track.title)
|
|
.bind(3, track.artist)
|
|
.bind(4, static_cast<std::int64_t>(playedBy))
|
|
.bind(5, static_cast<std::int64_t>(duration.count()))
|
|
.bind(6, completed ? 1 : 0)
|
|
.bind(7, track.shortenedUrl.value_or(""))
|
|
.bind(8, track.thumbnailUrl.value_or(""));
|
|
[[maybe_unused]] auto stepRes = stmt.step();
|
|
|
|
return {};
|
|
}
|
|
|
|
Result<void> Database::recordSkip(const TrackInfo& track, uint64_t playedBy)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
const char* sql = R"(
|
|
INSERT INTO playback_history
|
|
(track_url, track_title, track_artist, played_by, duration_ms, completed, track_short_url, track_thumbnail, skipped)
|
|
VALUES (?, ?, ?, ?, 0, 0, ?, ?, 1);
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, track.originalUrl)
|
|
.bind(2, track.title)
|
|
.bind(3, track.artist)
|
|
.bind(4, static_cast<std::int64_t>(playedBy))
|
|
.bind(5, track.shortenedUrl.value_or(""))
|
|
.bind(6, track.thumbnailUrl.value_or(""));
|
|
[[maybe_unused]] auto stepRes = stmt.step();
|
|
|
|
return {};
|
|
}
|
|
|
|
Result<void> Database::logQueueAddition(const std::string& uid,
|
|
const std::string& nickname)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
const char* sql =
|
|
"INSERT INTO queue_log (uid, nickname) VALUES (?, ?);";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, uid).bind(2, nickname);
|
|
[[maybe_unused]] auto stepRes = stmt.step();
|
|
|
|
return {};
|
|
}
|
|
|
|
Result<std::vector<PlaybackHistoryEntry>>
|
|
Database::getPlaybackHistory(uint64_t userId, size_t limit,
|
|
size_t offset)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
std::vector<PlaybackHistoryEntry> history;
|
|
|
|
const char* sql = R"(
|
|
SELECT id, track_url, track_title, track_artist, played_at, duration_ms, completed, track_short_url, track_thumbnail
|
|
FROM playback_history
|
|
WHERE played_by = ?
|
|
ORDER BY played_at DESC
|
|
LIMIT ? OFFSET ?;
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, static_cast<std::int64_t>(userId))
|
|
.bind(2, static_cast<std::int64_t>(limit))
|
|
.bind(3, static_cast<std::int64_t>(offset));
|
|
|
|
while (stmt.step().value_or(false)) {
|
|
PlaybackHistoryEntry entry;
|
|
entry.id = static_cast<uint64_t>(stmt.column_int(0));
|
|
entry.track.originalUrl = stmt.column_text(1);
|
|
entry.track.title = stmt.column_text(2);
|
|
entry.track.artist = stmt.column_text(3);
|
|
entry.playedBy = userId;
|
|
entry.duration =
|
|
std::chrono::milliseconds(stmt.column_int(5));
|
|
entry.completed = stmt.column_int(6) != 0;
|
|
if (auto shortUrl = stmt.column_text(7); !shortUrl.empty()) {
|
|
entry.track.shortenedUrl = shortUrl;
|
|
}
|
|
if (auto thumb = stmt.column_text(8); !thumb.empty()) {
|
|
entry.track.thumbnailUrl = thumb;
|
|
}
|
|
history.push_back(entry);
|
|
}
|
|
|
|
return history;
|
|
}
|
|
|
|
// Favorites
|
|
Result<void> Database::addFavorite(uint64_t userId, const TrackInfo& track)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
const char* sql = R"(
|
|
INSERT OR REPLACE INTO user_favorites
|
|
(user_id, track_url, track_title, track_artist, track_short_url, track_thumbnail)
|
|
VALUES (?, ?, ?, ?, ?, ?);
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
stmt.bind(1, static_cast<std::int64_t>(userId));
|
|
stmt.bind(2, track.originalUrl);
|
|
stmt.bind(3, track.title);
|
|
stmt.bind(4, track.artist);
|
|
stmt.bind(5, track.shortenedUrl.value_or(""));
|
|
stmt.bind(6, track.thumbnailUrl.value_or(""));
|
|
|
|
[[maybe_unused]] auto stepRes = stmt.step();
|
|
|
|
return {};
|
|
}
|
|
|
|
Result<void> Database::removeFavorite(uint64_t userId,
|
|
const std::string& trackUrl)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
const char* sql =
|
|
"DELETE FROM user_favorites WHERE user_id = ? AND track_url = ?;";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
stmt.bind(1, static_cast<std::int64_t>(userId));
|
|
stmt.bind(2, trackUrl);
|
|
|
|
[[maybe_unused]] auto stepRes = stmt.step();
|
|
|
|
return {};
|
|
}
|
|
|
|
Result<bool> Database::isFavorite(uint64_t userId,
|
|
const std::string& trackUrl)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
const char* sql = "SELECT 1 FROM user_favorites WHERE user_id = ? AND "
|
|
"track_url = ? LIMIT 1;";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
stmt.bind(1, static_cast<std::int64_t>(userId));
|
|
stmt.bind(2, trackUrl);
|
|
|
|
bool found = stmt.step().value_or(false);
|
|
|
|
return found;
|
|
}
|
|
|
|
Result<std::vector<FavoriteTrack>> Database::getFavorites(uint64_t userId)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
std::vector<FavoriteTrack> favorites;
|
|
|
|
const char* sql = R"(
|
|
SELECT track_url, track_title, track_artist, added_at, track_short_url, track_thumbnail
|
|
FROM user_favorites
|
|
WHERE user_id = ?
|
|
ORDER BY added_at DESC;
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
stmt.bind(1, static_cast<std::int64_t>(userId));
|
|
|
|
while (stmt.step().value_or(false)) {
|
|
FavoriteTrack fav;
|
|
fav.track.originalUrl =
|
|
stmt.column_text(0);
|
|
fav.track.title =
|
|
stmt.column_text(1);
|
|
fav.track.artist =
|
|
stmt.column_text(2);
|
|
if (auto shortUrl = stmt.column_text(4); !shortUrl.empty()) {
|
|
fav.track.shortenedUrl = shortUrl;
|
|
}
|
|
if (auto thumb = stmt.column_text(5); !thumb.empty()) {
|
|
fav.track.thumbnailUrl = thumb;
|
|
}
|
|
fav.userId = userId;
|
|
favorites.push_back(fav);
|
|
}
|
|
|
|
return favorites;
|
|
}
|
|
|
|
// Maintenance
|
|
Result<void> Database::trimHistory(size_t keepCount)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
const char* sql = R"(
|
|
DELETE FROM playback_history
|
|
WHERE id NOT IN (
|
|
SELECT id FROM playback_history
|
|
ORDER BY played_at DESC
|
|
LIMIT ?
|
|
);
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
stmt.bind(1, static_cast<std::int64_t>(keepCount));
|
|
[[maybe_unused]] auto stepRes = stmt.step();
|
|
|
|
// No VACUUM here: this runs after every finished track and a full
|
|
// vacuum would rewrite the whole file each time. Use vacuum()
|
|
// explicitly for space reclamation.
|
|
|
|
return {};
|
|
}
|
|
|
|
Result<void> Database::clearUserData(uint64_t userId)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
const char* sql1 = "DELETE FROM user_favorites WHERE user_id = ?;";
|
|
const char* sql2 = "DELETE FROM playback_history WHERE played_by = ?;";
|
|
const char* sql3 = "DELETE FROM playlists WHERE created_by = ?;";
|
|
|
|
for (const char* sql : {sql1, sql2, sql3}) {
|
|
if (auto stmtRes = impl_->voidDb.prepare(sql)) {
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, static_cast<std::int64_t>(userId));
|
|
[[maybe_unused]] auto stepRes = stmt.step();
|
|
}
|
|
}
|
|
|
|
return {};
|
|
}
|
|
|
|
Result<void> Database::vacuum()
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
[[maybe_unused]] auto execRes = impl_->voidDb.exec("VACUUM;");
|
|
return {};
|
|
}
|
|
|
|
// Subscriptions
|
|
Result<void> Database::addSubscriber(const std::string& uid,
|
|
const std::string& nickname)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
const char* sql = R"(
|
|
INSERT OR REPLACE INTO subscriptions (uid, nickname, subscribed_at)
|
|
VALUES (?, ?, CURRENT_TIMESTAMP);
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
stmt.bind(1, uid);
|
|
stmt.bind(2, nickname);
|
|
[[maybe_unused]] auto stepRes = stmt.step();
|
|
|
|
return {};
|
|
}
|
|
|
|
Result<void> Database::removeSubscriber(const std::string& uid)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
const char* sql = "DELETE FROM subscriptions WHERE uid = ?;";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
stmt.bind(1, uid);
|
|
[[maybe_unused]] auto stepRes = stmt.step();
|
|
|
|
return {};
|
|
}
|
|
|
|
Result<bool> Database::isSubscriber(const std::string& uid)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
const char* sql = "SELECT 1 FROM subscriptions WHERE uid = ? LIMIT 1;";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
stmt.bind(1, uid);
|
|
bool found = stmt.step().value_or(false);
|
|
|
|
return found;
|
|
}
|
|
|
|
Result<std::vector<Database::SubscriberInfo>> Database::getAllSubscribers()
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
std::vector<SubscriberInfo> subscribers;
|
|
|
|
const char* sql =
|
|
"SELECT uid, nickname, subscribed_at FROM subscriptions;";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
while (stmt.step().value_or(false)) {
|
|
SubscriberInfo info;
|
|
info.uid =
|
|
stmt.column_text(0);
|
|
info.nickname =
|
|
stmt.column_text(1);
|
|
info.subscribedAt = std::chrono::system_clock::from_time_t(
|
|
stmt.column_int(2));
|
|
subscribers.push_back(std::move(info));
|
|
}
|
|
|
|
return subscribers;
|
|
}
|
|
|
|
Result<void> Database::clearAllSubscribers()
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
[[maybe_unused]] auto execRes = impl_->voidDb.exec("DELETE FROM subscriptions;");
|
|
return {};
|
|
}
|
|
|
|
Result<size_t> Database::getSubscriberCount()
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
const char* sql = "SELECT COUNT(*) FROM subscriptions;";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
size_t count = 0;
|
|
if (stmt.step().value_or(false)) {
|
|
count = static_cast<size_t>(stmt.column_int(0));
|
|
}
|
|
|
|
return count;
|
|
}
|
|
|
|
Result<void>
|
|
Database::updatePlaylist(uint64_t id,
|
|
const std::optional<std::string>& name,
|
|
const std::optional<std::string>& description,
|
|
const std::optional<bool>& isPublic)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
const char* sql = R"(
|
|
UPDATE playlists SET
|
|
name = COALESCE(?, name),
|
|
description = COALESCE(?, description),
|
|
is_public = COALESCE(?, is_public),
|
|
updated_at = CURRENT_TIMESTAMP
|
|
WHERE id = ?;
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, name);
|
|
stmt.bind(2, description);
|
|
if (isPublic) {
|
|
stmt.bind(3, *isPublic ? 1 : 0);
|
|
} else {
|
|
stmt.bind(3, nullptr);
|
|
}
|
|
stmt.bind(4, static_cast<std::int64_t>(id));
|
|
[[maybe_unused]] auto stepRes = stmt.step();
|
|
return {};
|
|
}
|
|
|
|
Result<void> Database::removeTrackFromPlaylist(uint64_t playlistId,
|
|
uint64_t trackId)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
// Delete the row, then compact positions so ordering stays dense.
|
|
[[maybe_unused]] auto begin = impl_->voidDb.exec("BEGIN;");
|
|
|
|
std::int64_t removedPos = -1;
|
|
if (auto posRes = impl_->voidDb.prepare(
|
|
"SELECT position FROM playlist_tracks WHERE id = ? AND "
|
|
"playlist_id = ?;")) {
|
|
auto& posStmt = *posRes;
|
|
posStmt.bind(1, static_cast<std::int64_t>(trackId))
|
|
.bind(2, static_cast<std::int64_t>(playlistId));
|
|
if (posStmt.step().value_or(false)) {
|
|
removedPos = posStmt.column_int(0);
|
|
}
|
|
}
|
|
if (removedPos < 0) {
|
|
[[maybe_unused]] auto rollback = impl_->voidDb.exec("ROLLBACK;");
|
|
return fail(ErrorCode::NotFound, "Track not in playlist");
|
|
}
|
|
|
|
if (auto delRes = impl_->voidDb.prepare(
|
|
"DELETE FROM playlist_tracks WHERE id = ?;")) {
|
|
auto& delStmt = *delRes;
|
|
delStmt.bind(1, static_cast<std::int64_t>(trackId));
|
|
[[maybe_unused]] auto s = delStmt.step();
|
|
}
|
|
if (auto shiftRes = impl_->voidDb.prepare(
|
|
"UPDATE playlist_tracks SET position = position - 1 WHERE "
|
|
"playlist_id = ? AND position > ?;")) {
|
|
auto& shiftStmt = *shiftRes;
|
|
shiftStmt.bind(1, static_cast<std::int64_t>(playlistId))
|
|
.bind(2, removedPos);
|
|
[[maybe_unused]] auto s = shiftStmt.step();
|
|
}
|
|
|
|
[[maybe_unused]] auto commit = impl_->voidDb.exec("COMMIT;");
|
|
return {};
|
|
}
|
|
|
|
Result<void> Database::reorderPlaylistTrack(uint64_t playlistId,
|
|
uint64_t trackId,
|
|
uint32_t newPosition)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
[[maybe_unused]] auto begin = impl_->voidDb.exec("BEGIN;");
|
|
|
|
std::int64_t oldPos = -1;
|
|
if (auto posRes = impl_->voidDb.prepare(
|
|
"SELECT position FROM playlist_tracks WHERE id = ? AND "
|
|
"playlist_id = ?;")) {
|
|
auto& posStmt = *posRes;
|
|
posStmt.bind(1, static_cast<std::int64_t>(trackId))
|
|
.bind(2, static_cast<std::int64_t>(playlistId));
|
|
if (posStmt.step().value_or(false)) {
|
|
oldPos = posStmt.column_int(0);
|
|
}
|
|
}
|
|
if (oldPos < 0) {
|
|
[[maybe_unused]] auto rollback = impl_->voidDb.exec("ROLLBACK;");
|
|
return fail(ErrorCode::NotFound, "Track not in playlist");
|
|
}
|
|
|
|
const auto newPos = static_cast<std::int64_t>(newPosition);
|
|
const char* shiftSql =
|
|
oldPos < newPos
|
|
? "UPDATE playlist_tracks SET position = position - 1 WHERE "
|
|
"playlist_id = ? AND position > ? AND position <= ?;"
|
|
: "UPDATE playlist_tracks SET position = position + 1 WHERE "
|
|
"playlist_id = ? AND position >= ? AND position < ?;";
|
|
if (auto shiftRes = impl_->voidDb.prepare(shiftSql)) {
|
|
auto& shiftStmt = *shiftRes;
|
|
if (oldPos < newPos) {
|
|
shiftStmt.bind(1, static_cast<std::int64_t>(playlistId))
|
|
.bind(2, oldPos)
|
|
.bind(3, newPos);
|
|
} else {
|
|
shiftStmt.bind(1, static_cast<std::int64_t>(playlistId))
|
|
.bind(2, newPos)
|
|
.bind(3, oldPos);
|
|
}
|
|
[[maybe_unused]] auto s = shiftStmt.step();
|
|
}
|
|
if (auto moveRes = impl_->voidDb.prepare(
|
|
"UPDATE playlist_tracks SET position = ? WHERE id = ?;")) {
|
|
auto& moveStmt = *moveRes;
|
|
moveStmt.bind(1, newPos).bind(2, static_cast<std::int64_t>(trackId));
|
|
[[maybe_unused]] auto s = moveStmt.step();
|
|
}
|
|
|
|
[[maybe_unused]] auto commit = impl_->voidDb.exec("COMMIT;");
|
|
return {};
|
|
}
|
|
|
|
Result<std::vector<TrackInfo>> Database::getRecentlyPlayed(uint64_t userId,
|
|
size_t limit)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
std::vector<TrackInfo> tracks;
|
|
|
|
// userId 0 = global history. Deduplicate by URL, newest first.
|
|
const char* sql = R"(
|
|
SELECT track_url, track_title, track_artist, MAX(played_at), MAX(track_short_url), MAX(track_thumbnail)
|
|
FROM playback_history
|
|
WHERE (?1 = 0 OR played_by = ?1)
|
|
GROUP BY track_url
|
|
ORDER BY MAX(played_at) DESC
|
|
LIMIT ?2;
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, static_cast<std::int64_t>(userId))
|
|
.bind(2, static_cast<std::int64_t>(limit));
|
|
|
|
while (stmt.step().value_or(false)) {
|
|
TrackInfo track;
|
|
track.originalUrl = stmt.column_text(0);
|
|
track.title = stmt.column_text(1);
|
|
track.artist = stmt.column_text(2);
|
|
if (auto shortUrl = stmt.column_text(4); !shortUrl.empty()) {
|
|
track.shortenedUrl = shortUrl;
|
|
}
|
|
if (auto thumb = stmt.column_text(5); !thumb.empty()) {
|
|
track.thumbnailUrl = thumb;
|
|
}
|
|
tracks.push_back(std::move(track));
|
|
}
|
|
return tracks;
|
|
}
|
|
|
|
Result<PlaybackStatistics> Database::getStatistics(
|
|
uint64_t userId,
|
|
std::optional<std::chrono::system_clock::time_point>
|
|
since)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
(void)since; // "since" filtering can come with a real need for it
|
|
PlaybackStatistics stats;
|
|
|
|
if (auto totalsRes = impl_->voidDb.prepare(R"(
|
|
SELECT COUNT(*), COUNT(DISTINCT track_url), COALESCE(SUM(duration_ms), 0)
|
|
FROM playback_history
|
|
WHERE (?1 = 0 OR played_by = ?1);
|
|
)")) {
|
|
auto& stmt = *totalsRes;
|
|
stmt.bind(1, static_cast<std::int64_t>(userId));
|
|
if (stmt.step().value_or(false)) {
|
|
stats.totalPlays = static_cast<uint64_t>(stmt.column_int(0));
|
|
stats.totalTracks = static_cast<uint64_t>(stmt.column_int(1));
|
|
stats.totalPlaytimeMs =
|
|
static_cast<uint64_t>(stmt.column_int(2));
|
|
}
|
|
}
|
|
|
|
if (auto topRes = impl_->voidDb.prepare(R"(
|
|
SELECT track_url, track_title, track_artist, COUNT(*) AS plays, MAX(track_short_url)
|
|
FROM playback_history
|
|
WHERE (?1 = 0 OR played_by = ?1)
|
|
GROUP BY track_url
|
|
ORDER BY plays DESC
|
|
LIMIT 1;
|
|
)")) {
|
|
auto& stmt = *topRes;
|
|
stmt.bind(1, static_cast<std::int64_t>(userId));
|
|
if (stmt.step().value_or(false)) {
|
|
TrackInfo track;
|
|
track.originalUrl = stmt.column_text(0);
|
|
track.title = stmt.column_text(1);
|
|
track.artist = stmt.column_text(2);
|
|
if (auto shortUrl = stmt.column_text(4); !shortUrl.empty()) {
|
|
track.shortenedUrl = shortUrl;
|
|
}
|
|
stats.mostPlayedTrack = std::move(track);
|
|
stats.mostPlayedCount =
|
|
static_cast<uint64_t>(stmt.column_int(3));
|
|
}
|
|
}
|
|
|
|
return stats;
|
|
}
|
|
|
|
Result<std::vector<std::pair<TrackInfo, uint64_t>>>
|
|
Database::getMostPlayed(uint64_t userId, size_t limit)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
std::vector<std::pair<TrackInfo, uint64_t>> result;
|
|
|
|
const char* sql = R"(
|
|
SELECT track_url, track_title, track_artist, COUNT(*) AS plays, MAX(track_short_url)
|
|
FROM playback_history
|
|
WHERE (?1 = 0 OR played_by = ?1)
|
|
GROUP BY track_url
|
|
ORDER BY plays DESC
|
|
LIMIT ?2;
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, static_cast<std::int64_t>(userId))
|
|
.bind(2, static_cast<std::int64_t>(limit));
|
|
|
|
while (stmt.step().value_or(false)) {
|
|
TrackInfo track;
|
|
track.originalUrl = stmt.column_text(0);
|
|
track.title = stmt.column_text(1);
|
|
track.artist = stmt.column_text(2);
|
|
if (auto shortUrl = stmt.column_text(4); !shortUrl.empty()) {
|
|
track.shortenedUrl = shortUrl;
|
|
}
|
|
result.emplace_back(std::move(track),
|
|
static_cast<uint64_t>(stmt.column_int(3)));
|
|
}
|
|
return result;
|
|
}
|
|
|
|
Result<AggregateStats> Database::getAggregateStats()
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
AggregateStats stats;
|
|
|
|
// played_at/added_at are CURRENT_TIMESTAMP (UTC); "today" follows the
|
|
// same clock.
|
|
{
|
|
const char* sql = R"(
|
|
SELECT
|
|
SUM(CASE WHEN completed = 1 AND date(played_at) = date('now') THEN 1 ELSE 0 END),
|
|
SUM(CASE WHEN completed = 1 AND date(played_at) = date('now') THEN duration_ms ELSE 0 END),
|
|
SUM(CASE WHEN skipped = 1 AND date(played_at) = date('now') THEN 1 ELSE 0 END),
|
|
SUM(CASE WHEN completed = 1 THEN 1 ELSE 0 END),
|
|
SUM(CASE WHEN skipped = 1 THEN 1 ELSE 0 END),
|
|
SUM(CASE WHEN track_url LIKE '%youtu%' THEN 1 ELSE 0 END),
|
|
SUM(CASE WHEN track_url LIKE '%yandex%' THEN 1 ELSE 0 END),
|
|
COUNT(*)
|
|
FROM playback_history;
|
|
)";
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError,
|
|
stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
if (stmt.step().value_or(false)) {
|
|
stats.tracksToday = static_cast<uint64_t>(stmt.column_int(0));
|
|
stats.listeningMsToday =
|
|
static_cast<uint64_t>(stmt.column_int(1));
|
|
stats.skipsToday = static_cast<uint64_t>(stmt.column_int(2));
|
|
stats.playsTotal = static_cast<uint64_t>(stmt.column_int(3));
|
|
stats.skipsTotal = static_cast<uint64_t>(stmt.column_int(4));
|
|
stats.youtubeCount = static_cast<uint64_t>(stmt.column_int(5));
|
|
stats.yandexCount = static_cast<uint64_t>(stmt.column_int(6));
|
|
const auto total = static_cast<uint64_t>(stmt.column_int(7));
|
|
stats.otherCount =
|
|
total - std::min(total, stats.youtubeCount +
|
|
stats.yandexCount);
|
|
}
|
|
}
|
|
|
|
{
|
|
const char* sql = R"(
|
|
SELECT COUNT(*) FROM queue_log WHERE date(added_at) = date('now');
|
|
)";
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError,
|
|
stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
if (stmt.step().value_or(false)) {
|
|
stats.queueAdditionsToday =
|
|
static_cast<uint64_t>(stmt.column_int(0));
|
|
}
|
|
}
|
|
|
|
{
|
|
const char* sql = R"(
|
|
SELECT nickname, COUNT(*) AS adds, MAX(uid) AS uid
|
|
FROM queue_log
|
|
WHERE nickname IS NOT NULL AND nickname != ''
|
|
GROUP BY nickname
|
|
ORDER BY adds DESC
|
|
LIMIT 5;
|
|
)";
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError,
|
|
stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
while (stmt.step().value_or(false)) {
|
|
stats.topRequesters.push_back(AggregateStats::TopRequester{
|
|
.uid = stmt.column_text(2),
|
|
.nickname = stmt.column_text(0),
|
|
.count = static_cast<uint64_t>(stmt.column_int(1))});
|
|
}
|
|
}
|
|
|
|
return stats;
|
|
}
|
|
|
|
Result<std::optional<std::string>> Database::getKv(const std::string& key)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
auto stmtRes = impl_->voidDb.prepare(
|
|
"SELECT value FROM kv_store WHERE key = ?;");
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, key);
|
|
if (stmt.step().value_or(false)) {
|
|
return std::optional<std::string>{stmt.column_text(0)};
|
|
}
|
|
return std::optional<std::string>{};
|
|
}
|
|
|
|
Result<void> Database::setKv(const std::string& key,
|
|
const std::string& value)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
auto stmtRes = impl_->voidDb.prepare(R"(
|
|
INSERT OR REPLACE INTO kv_store (key, value, updated_at)
|
|
VALUES (?, ?, CURRENT_TIMESTAMP);
|
|
)");
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, key).bind(2, value);
|
|
[[maybe_unused]] auto stepRes = stmt.step();
|
|
return {};
|
|
}
|
|
|
|
Result<std::optional<Database::CachedAvatar>>
|
|
Database::getCachedAvatar(const std::string& uid)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
auto stmtRes = impl_->voidDb.prepare(
|
|
"SELECT uid, mime, data, COALESCE(url, '') FROM cached_avatars "
|
|
"WHERE uid = ?;");
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, uid);
|
|
if (stmt.step().value_or(false)) {
|
|
return std::optional<CachedAvatar>{
|
|
CachedAvatar{.uid = stmt.column_text(0),
|
|
.mime = stmt.column_text(1),
|
|
.dataBase64 = stmt.column_text(2),
|
|
.url = stmt.column_text(3)}};
|
|
}
|
|
return std::optional<CachedAvatar>{};
|
|
}
|
|
|
|
Result<void> Database::putCachedAvatar(const std::string& uid,
|
|
const std::string& mime,
|
|
const std::string& dataBase64)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
// Upsert the image but keep any url already recorded for this uid.
|
|
auto stmtRes = impl_->voidDb.prepare(R"(
|
|
INSERT INTO cached_avatars (uid, mime, data, updated_at)
|
|
VALUES (?, ?, ?, CURRENT_TIMESTAMP)
|
|
ON CONFLICT(uid) DO UPDATE SET
|
|
mime = excluded.mime,
|
|
data = excluded.data,
|
|
updated_at = CURRENT_TIMESTAMP;
|
|
)");
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, uid).bind(2, mime).bind(3, dataBase64);
|
|
if (auto stepRes = stmt.step(); !stepRes) {
|
|
return fail(ErrorCode::DatabaseError, stepRes.error().message());
|
|
}
|
|
return {};
|
|
}
|
|
|
|
Result<void> Database::putCachedAvatarUrl(const std::string& uid,
|
|
const std::string& url)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
// Insert a url-only row (empty mime/data satisfy NOT NULL) or update the
|
|
// url on an existing one, without touching cached bytes.
|
|
auto stmtRes = impl_->voidDb.prepare(R"(
|
|
INSERT INTO cached_avatars (uid, mime, data, url)
|
|
VALUES (?, '', '', ?)
|
|
ON CONFLICT(uid) DO UPDATE SET url = excluded.url;
|
|
)");
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
stmt.bind(1, uid).bind(2, url);
|
|
if (auto stepRes = stmt.step(); !stepRes) {
|
|
return fail(ErrorCode::DatabaseError, stepRes.error().message());
|
|
}
|
|
return {};
|
|
}
|
|
|
|
Result<void> Database::executeQuery(const std::string& sql,
|
|
RowCallback callback)
|
|
{
|
|
// Deliberately unimplemented: free-form SQL over the RPC surface is
|
|
// a footgun. Dedicated accessors (getKv/setKv, ...) cover the needs.
|
|
(void)sql;
|
|
(void)callback;
|
|
return fail(ErrorCode::NotSupported, "executeQuery is not available");
|
|
}
|
|
|
|
// Database manager
|
|
Database& DatabaseManager::instance()
|
|
{
|
|
static Database db;
|
|
return db;
|
|
}
|
|
|
|
Result<void> DatabaseManager::initialize(const DatabaseConfig& config)
|
|
{
|
|
return instance().initialize(config);
|
|
}
|
|
|
|
void DatabaseManager::shutdown() { instance().shutdown(); }
|
|
|
|
// RPC Token operations
|
|
Result<std::string> Database::generateRpcToken(const std::string& uid)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
// Check if subscriber exists
|
|
auto checkRes =
|
|
impl_->voidDb.prepare("SELECT 1 FROM subscriptions WHERE uid = ?");
|
|
if (!checkRes) {
|
|
return fail(ErrorCode::DatabaseError, checkRes.error().message());
|
|
}
|
|
auto& checkStmt = *checkRes;
|
|
checkStmt.bind(1, uid);
|
|
bool exists = checkStmt.step().value_or(false);
|
|
|
|
if (!exists) {
|
|
return fail(ErrorCode::NotFound, "Subscriber not found");
|
|
}
|
|
|
|
// Generate a random 32-character alphanumeric token (Void::Random is
|
|
// seeded from std::random_device, unlike the former rand()).
|
|
const std::string token = Void::Random::random_string(32);
|
|
|
|
// Insert token
|
|
const char* sql = R"(
|
|
INSERT INTO rpc_tokens (token, uid, created_at)
|
|
VALUES (?, ?, datetime('now'));
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
stmt.bind(1, token);
|
|
stmt.bind(2, uid);
|
|
|
|
if (auto stepRes = stmt.step(); !stepRes) {
|
|
return fail(ErrorCode::DatabaseError, stepRes.error().message());
|
|
}
|
|
|
|
return token;
|
|
}
|
|
|
|
Result<std::optional<std::string>>
|
|
Database::getExistingRpcToken(const std::string& uid)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
const char* sql = R"(
|
|
SELECT token FROM rpc_tokens WHERE uid = ? LIMIT 1;
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
stmt.bind(1, uid);
|
|
|
|
std::optional<std::string> token;
|
|
if (stmt.step().value_or(false)) {
|
|
if (!stmt.is_null(0)) {
|
|
token = stmt.column_text(0);
|
|
}
|
|
}
|
|
|
|
return token;
|
|
}
|
|
|
|
Result<bool> Database::validateRpcToken(const std::string& token)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
const char* sql = R"(
|
|
SELECT 1 FROM rpc_tokens WHERE token = ?;
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
stmt.bind(1, token);
|
|
|
|
bool valid = stmt.step().value_or(false);
|
|
|
|
if (valid) {
|
|
// Update last_used_at
|
|
const char* updateSql = R"(
|
|
UPDATE rpc_tokens SET last_used_at = datetime('now') WHERE token = ?;
|
|
)";
|
|
if (auto updateRes = impl_->voidDb.prepare(updateSql)) {
|
|
auto& updateStmt = *updateRes;
|
|
updateStmt.bind(1, token);
|
|
[[maybe_unused]] auto stepRes = updateStmt.step();
|
|
}
|
|
}
|
|
|
|
return valid;
|
|
}
|
|
|
|
Result<std::optional<std::string>>
|
|
Database::getUidFromRpcToken(const std::string& token)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
const char* sql = R"(
|
|
SELECT uid FROM rpc_tokens WHERE token = ?;
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
stmt.bind(1, token);
|
|
|
|
std::optional<std::string> uid;
|
|
if (stmt.step().value_or(false)) {
|
|
if (!stmt.is_null(0)) {
|
|
uid = stmt.column_text(0);
|
|
}
|
|
}
|
|
|
|
return uid;
|
|
}
|
|
|
|
Result<std::optional<std::string>>
|
|
Database::getSubscriberByNickname(const std::string& nickname)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
const char* sql = R"(
|
|
SELECT uid FROM subscriptions WHERE nickname = ? COLLATE NOCASE;
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
stmt.bind(1, nickname);
|
|
|
|
std::optional<std::string> uid;
|
|
if (stmt.step().value_or(false)) {
|
|
if (!stmt.is_null(0)) {
|
|
uid = stmt.column_text(0);
|
|
}
|
|
}
|
|
|
|
return uid;
|
|
}
|
|
|
|
Result<void> Database::revokeRpcToken(const std::string& token)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
const char* sql = R"(
|
|
DELETE FROM rpc_tokens WHERE token = ?;
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
stmt.bind(1, token);
|
|
|
|
if (auto stepRes = stmt.step(); !stepRes) {
|
|
return fail(ErrorCode::DatabaseError, stepRes.error().message());
|
|
}
|
|
|
|
return {};
|
|
}
|
|
|
|
Result<std::vector<std::string>> Database::getAllSubscriberUids()
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
const char* sql = R"(
|
|
SELECT uid FROM subscriptions;
|
|
)";
|
|
|
|
auto stmtRes = impl_->voidDb.prepare(sql);
|
|
if (!stmtRes) {
|
|
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
|
}
|
|
auto& stmt = *stmtRes;
|
|
|
|
std::vector<std::string> uids;
|
|
while (stmt.step().value_or(false)) {
|
|
if (!stmt.is_null(0)) {
|
|
uids.push_back(stmt.column_text(0));
|
|
}
|
|
}
|
|
|
|
return uids;
|
|
}
|
|
|
|
} // namespace Echoion::Api
|