Mechanically convert std::unexpected(Api::Error(ErrorCode::X, msg[, src])) to Api::fail(ErrorCode::X, msg[, src]) across Core. Pure syntax; forwards of existing errors (std::unexpected(x.error())) are unchanged. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1222 lines
35 KiB
C++
1222 lines
35 KiB
C++
#include <Database.hpp>
|
|
#include "echoion/core/Logger.hpp"
|
|
#include <Void/Math/Random.hpp>
|
|
#include <Void/Sqlite/Sqlite.hpp>
|
|
#include <cstring>
|
|
#include <format>
|
|
#include <shared_mutex>
|
|
#include <sqlite3.h>
|
|
|
|
namespace Echoion::Api
|
|
{
|
|
|
|
// Internal implementation. The connection lifecycle (open/close, WAL,
|
|
// busy-timeout, foreign keys) is owned by Void::Sqlite::Database; `db` is a
|
|
// non-owning handle into it so the existing raw-sqlite3 query methods and
|
|
// the schema_migrations framework keep working byte-identically. 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;
|
|
sqlite3* db = nullptr; // non-owning, == voidDb.handle()
|
|
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). The raw handle is borrowed for the existing
|
|
// query methods.
|
|
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);
|
|
impl_->db = impl_->voidDb.handle();
|
|
|
|
// Honor the configured busy timeout (Void defaults to 5s).
|
|
sqlite3_busy_timeout(impl_->db,
|
|
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;
|
|
ECHOION_LOG_INFO(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_);
|
|
|
|
// Drop the borrowed handle first, then let Void::Sqlite close the
|
|
// connection via RAII (move-assign an empty Database).
|
|
impl_->db = nullptr;
|
|
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
|
|
);
|
|
)";
|
|
|
|
char* errMsg = nullptr;
|
|
sqlite3_exec(impl_->db, createMigrationsTable, nullptr, nullptr,
|
|
&errMsg);
|
|
if (errMsg) {
|
|
std::string error = errMsg;
|
|
sqlite3_free(errMsg);
|
|
return fail(ErrorCode::DatabaseError, error);
|
|
}
|
|
|
|
// Get current version
|
|
sqlite3_stmt* stmt;
|
|
int currentVersion = 0;
|
|
if (sqlite3_prepare_v2(impl_->db,
|
|
"SELECT MAX(version) FROM schema_migrations", -1,
|
|
&stmt, nullptr) == SQLITE_OK) {
|
|
if (sqlite3_step(stmt) == SQLITE_ROW) {
|
|
currentVersion = sqlite3_column_int(stmt, 0);
|
|
}
|
|
sqlite3_finalize(stmt);
|
|
}
|
|
|
|
// 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);
|
|
)";
|
|
|
|
sqlite3_exec(impl_->db, migration1, nullptr, nullptr, &errMsg);
|
|
if (errMsg) {
|
|
std::string error = errMsg;
|
|
sqlite3_free(errMsg);
|
|
return fail(ErrorCode::DatabaseError, error);
|
|
}
|
|
|
|
sqlite3_exec(impl_->db,
|
|
"INSERT INTO schema_migrations (version) VALUES (1)",
|
|
nullptr, nullptr, nullptr);
|
|
|
|
ECHOION_LOG_INFO("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);
|
|
)";
|
|
|
|
sqlite3_exec(impl_->db, migration2, nullptr, nullptr, &errMsg);
|
|
if (errMsg) {
|
|
std::string error = errMsg;
|
|
sqlite3_free(errMsg);
|
|
return fail(ErrorCode::DatabaseError, error);
|
|
}
|
|
|
|
sqlite3_exec(impl_->db,
|
|
"INSERT INTO schema_migrations (version) VALUES (2)",
|
|
nullptr, nullptr, nullptr);
|
|
|
|
ECHOION_LOG_INFO(
|
|
"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);
|
|
)";
|
|
|
|
sqlite3_exec(impl_->db, migration3, nullptr, nullptr, &errMsg);
|
|
if (errMsg) {
|
|
// Column might already exist, ignore error
|
|
sqlite3_free(errMsg);
|
|
errMsg = nullptr;
|
|
}
|
|
|
|
sqlite3_exec(impl_->db,
|
|
"INSERT INTO schema_migrations (version) VALUES (3)",
|
|
nullptr, nullptr, nullptr);
|
|
|
|
ECHOION_LOG_INFO("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);
|
|
)";
|
|
|
|
sqlite3_exec(impl_->db, migration4, nullptr, nullptr, &errMsg);
|
|
if (errMsg) {
|
|
std::string error = errMsg;
|
|
sqlite3_free(errMsg);
|
|
return fail(ErrorCode::DatabaseError, error);
|
|
}
|
|
|
|
sqlite3_exec(impl_->db,
|
|
"INSERT INTO schema_migrations (version) VALUES (4)",
|
|
nullptr, nullptr, nullptr);
|
|
|
|
ECHOION_LOG_INFO(
|
|
"Database migration 4 applied: RPC tokens table added");
|
|
}
|
|
|
|
impl_->version = 4;
|
|
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 (?, ?, ?, ?, ?);
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_text(stmt, 1, name.c_str(), -1, SQLITE_STATIC);
|
|
sqlite3_bind_text(stmt, 2, description.c_str(), -1, SQLITE_STATIC);
|
|
sqlite3_bind_int64(stmt, 3, static_cast<sqlite3_int64>(createdBy));
|
|
sqlite3_bind_int(stmt, 4, isPublic ? 1 : 0);
|
|
if (!externalId.empty()) {
|
|
sqlite3_bind_text(stmt, 5, externalId.c_str(), -1, SQLITE_STATIC);
|
|
}
|
|
|
|
if (sqlite3_step(stmt) != SQLITE_DONE) {
|
|
sqlite3_finalize(stmt);
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
uint64_t id =
|
|
static_cast<uint64_t>(sqlite3_last_insert_rowid(impl_->db));
|
|
sqlite3_finalize(stmt);
|
|
|
|
return id;
|
|
}
|
|
|
|
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 = ?;
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, selectSql, -1, &stmt, nullptr) ==
|
|
SQLITE_OK) {
|
|
sqlite3_bind_text(stmt, 1, externalId.c_str(), -1, SQLITE_STATIC);
|
|
|
|
if (sqlite3_step(stmt) == SQLITE_ROW) {
|
|
uint64_t existingId =
|
|
static_cast<uint64_t>(sqlite3_column_int64(stmt, 0));
|
|
sqlite3_finalize(stmt);
|
|
return existingId;
|
|
}
|
|
sqlite3_finalize(stmt);
|
|
}
|
|
|
|
// 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 = ?;
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(id));
|
|
|
|
Playlist playlist;
|
|
bool found = false;
|
|
|
|
if (sqlite3_step(stmt) == SQLITE_ROW) {
|
|
found = true;
|
|
playlist.id = static_cast<uint64_t>(sqlite3_column_int64(stmt, 0));
|
|
playlist.name =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
|
|
playlist.description =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2));
|
|
playlist.createdBy =
|
|
static_cast<uint64_t>(sqlite3_column_int64(stmt, 3));
|
|
playlist.isPublic = sqlite3_column_int(stmt, 6) != 0;
|
|
}
|
|
|
|
sqlite3_finalize(stmt);
|
|
|
|
if (!found) {
|
|
return std::optional<Playlist>{};
|
|
}
|
|
|
|
// Load tracks
|
|
const char* tracksSql = R"(
|
|
SELECT track_url, track_title, track_artist, track_thumbnail
|
|
FROM playlist_tracks
|
|
WHERE playlist_id = ?
|
|
ORDER BY position;
|
|
)";
|
|
|
|
if (sqlite3_prepare_v2(impl_->db, tracksSql, -1, &stmt, nullptr) ==
|
|
SQLITE_OK) {
|
|
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(id));
|
|
|
|
while (sqlite3_step(stmt) == SQLITE_ROW) {
|
|
TrackInfo track;
|
|
track.originalUrl =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
|
|
track.title =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
|
|
track.artist =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2));
|
|
if (sqlite3_column_text(stmt, 3)) {
|
|
track.thumbnailUrl = reinterpret_cast<const char*>(
|
|
sqlite3_column_text(stmt, 3));
|
|
}
|
|
playlist.tracks.push_back(track);
|
|
}
|
|
|
|
sqlite3_finalize(stmt);
|
|
}
|
|
|
|
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;
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
|
|
|
|
while (sqlite3_step(stmt) == SQLITE_ROW) {
|
|
Playlist playlist;
|
|
playlist.id = static_cast<uint64_t>(sqlite3_column_int64(stmt, 0));
|
|
playlist.name =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
|
|
playlist.description =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2));
|
|
playlist.isPublic = sqlite3_column_int(stmt, 4) != 0;
|
|
playlists.push_back(playlist);
|
|
}
|
|
|
|
sqlite3_finalize(stmt);
|
|
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 = ?;";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(id));
|
|
sqlite3_step(stmt);
|
|
sqlite3_finalize(stmt);
|
|
|
|
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, position)
|
|
VALUES (?, ?, ?, ?, ?, ?);
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(playlistId));
|
|
sqlite3_bind_text(stmt, 2, track.originalUrl.c_str(), -1,
|
|
SQLITE_STATIC);
|
|
sqlite3_bind_text(stmt, 3, track.title.c_str(), -1, SQLITE_STATIC);
|
|
sqlite3_bind_text(stmt, 4, track.artist.c_str(), -1, SQLITE_STATIC);
|
|
sqlite3_bind_text(stmt, 5,
|
|
track.thumbnailUrl ? track.thumbnailUrl->c_str() : "",
|
|
-1, SQLITE_STATIC);
|
|
sqlite3_bind_int(stmt, 6, position);
|
|
|
|
sqlite3_step(stmt);
|
|
sqlite3_finalize(stmt);
|
|
|
|
// Update playlist timestamp
|
|
sqlite3_exec(impl_->db,
|
|
std::format("UPDATE playlists SET updated_at = "
|
|
"CURRENT_TIMESTAMP WHERE id = {}",
|
|
playlistId)
|
|
.c_str(),
|
|
nullptr, nullptr, nullptr);
|
|
|
|
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)
|
|
VALUES (?, ?, ?, ?, ?, ?);
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_text(stmt, 1, track.originalUrl.c_str(), -1,
|
|
SQLITE_STATIC);
|
|
sqlite3_bind_text(stmt, 2, track.title.c_str(), -1, SQLITE_STATIC);
|
|
sqlite3_bind_text(stmt, 3, track.artist.c_str(), -1, SQLITE_STATIC);
|
|
sqlite3_bind_int64(stmt, 4, static_cast<sqlite3_int64>(playedBy));
|
|
sqlite3_bind_int64(stmt, 5, duration.count());
|
|
sqlite3_bind_int(stmt, 6, completed ? 1 : 0);
|
|
|
|
sqlite3_step(stmt);
|
|
sqlite3_finalize(stmt);
|
|
|
|
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
|
|
FROM playback_history
|
|
WHERE played_by = ?
|
|
ORDER BY played_at DESC
|
|
LIMIT ? OFFSET ?;
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
|
|
sqlite3_bind_int64(stmt, 2, static_cast<sqlite3_int64>(limit));
|
|
sqlite3_bind_int64(stmt, 3, static_cast<sqlite3_int64>(offset));
|
|
|
|
while (sqlite3_step(stmt) == SQLITE_ROW) {
|
|
PlaybackHistoryEntry entry;
|
|
entry.id = static_cast<uint64_t>(sqlite3_column_int64(stmt, 0));
|
|
entry.track.originalUrl =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
|
|
entry.track.title =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2));
|
|
entry.track.artist =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 3));
|
|
entry.playedBy = userId;
|
|
entry.duration =
|
|
std::chrono::milliseconds(sqlite3_column_int64(stmt, 5));
|
|
entry.completed = sqlite3_column_int(stmt, 6) != 0;
|
|
history.push_back(entry);
|
|
}
|
|
|
|
sqlite3_finalize(stmt);
|
|
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)
|
|
VALUES (?, ?, ?, ?);
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
|
|
sqlite3_bind_text(stmt, 2, track.originalUrl.c_str(), -1,
|
|
SQLITE_STATIC);
|
|
sqlite3_bind_text(stmt, 3, track.title.c_str(), -1, SQLITE_STATIC);
|
|
sqlite3_bind_text(stmt, 4, track.artist.c_str(), -1, SQLITE_STATIC);
|
|
|
|
sqlite3_step(stmt);
|
|
sqlite3_finalize(stmt);
|
|
|
|
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 = ?;";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
|
|
sqlite3_bind_text(stmt, 2, trackUrl.c_str(), -1, SQLITE_STATIC);
|
|
|
|
sqlite3_step(stmt);
|
|
sqlite3_finalize(stmt);
|
|
|
|
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;";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
|
|
sqlite3_bind_text(stmt, 2, trackUrl.c_str(), -1, SQLITE_STATIC);
|
|
|
|
bool found = sqlite3_step(stmt) == SQLITE_ROW;
|
|
sqlite3_finalize(stmt);
|
|
|
|
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
|
|
FROM user_favorites
|
|
WHERE user_id = ?
|
|
ORDER BY added_at DESC;
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
|
|
|
|
while (sqlite3_step(stmt) == SQLITE_ROW) {
|
|
FavoriteTrack fav;
|
|
fav.track.originalUrl =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
|
|
fav.track.title =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
|
|
fav.track.artist =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2));
|
|
fav.userId = userId;
|
|
favorites.push_back(fav);
|
|
}
|
|
|
|
sqlite3_finalize(stmt);
|
|
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 ?
|
|
);
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(keepCount));
|
|
sqlite3_step(stmt);
|
|
sqlite3_finalize(stmt);
|
|
|
|
// Vacuum to reclaim space
|
|
sqlite3_exec(impl_->db, "VACUUM;", nullptr, nullptr, nullptr);
|
|
|
|
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 = ?;";
|
|
|
|
sqlite3_stmt* stmt;
|
|
|
|
for (const char* sql : {sql1, sql2, sql3}) {
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) ==
|
|
SQLITE_OK) {
|
|
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
|
|
sqlite3_step(stmt);
|
|
sqlite3_finalize(stmt);
|
|
}
|
|
}
|
|
|
|
return {};
|
|
}
|
|
|
|
Result<void> Database::vacuum()
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
sqlite3_exec(impl_->db, "VACUUM;", nullptr, nullptr, nullptr);
|
|
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);
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC);
|
|
sqlite3_bind_text(stmt, 2, nickname.c_str(), -1, SQLITE_STATIC);
|
|
sqlite3_step(stmt);
|
|
sqlite3_finalize(stmt);
|
|
|
|
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 = ?;";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC);
|
|
sqlite3_step(stmt);
|
|
sqlite3_finalize(stmt);
|
|
|
|
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;";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC);
|
|
bool found = sqlite3_step(stmt) == SQLITE_ROW;
|
|
sqlite3_finalize(stmt);
|
|
|
|
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;";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
while (sqlite3_step(stmt) == SQLITE_ROW) {
|
|
SubscriberInfo info;
|
|
info.uid =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
|
|
info.nickname =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
|
|
info.subscribedAt = std::chrono::system_clock::from_time_t(
|
|
sqlite3_column_int64(stmt, 2));
|
|
subscribers.push_back(std::move(info));
|
|
}
|
|
|
|
sqlite3_finalize(stmt);
|
|
return subscribers;
|
|
}
|
|
|
|
Result<void> Database::clearAllSubscribers()
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
sqlite3_exec(impl_->db, "DELETE FROM subscriptions;", nullptr, nullptr,
|
|
nullptr);
|
|
return {};
|
|
}
|
|
|
|
Result<size_t> Database::getSubscriberCount()
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
const char* sql = "SELECT COUNT(*) FROM subscriptions;";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
size_t count = 0;
|
|
if (sqlite3_step(stmt) == SQLITE_ROW) {
|
|
count = static_cast<size_t>(sqlite3_column_int64(stmt, 0));
|
|
}
|
|
|
|
sqlite3_finalize(stmt);
|
|
return count;
|
|
}
|
|
|
|
// Stub implementations for missing methods
|
|
Result<void>
|
|
Database::updatePlaylist(uint64_t id,
|
|
const std::optional<std::string>& name,
|
|
const std::optional<std::string>& description,
|
|
const std::optional<bool>& isPublic)
|
|
{
|
|
(void)id;
|
|
(void)name;
|
|
(void)description;
|
|
(void)isPublic;
|
|
return {};
|
|
}
|
|
|
|
Result<void> Database::removeTrackFromPlaylist(uint64_t playlistId,
|
|
uint64_t trackId)
|
|
{
|
|
(void)playlistId;
|
|
(void)trackId;
|
|
return {};
|
|
}
|
|
|
|
Result<void> Database::reorderPlaylistTrack(uint64_t playlistId,
|
|
uint64_t trackId,
|
|
uint32_t newPosition)
|
|
{
|
|
(void)playlistId;
|
|
(void)trackId;
|
|
(void)newPosition;
|
|
return {};
|
|
}
|
|
|
|
Result<std::vector<TrackInfo>> Database::getRecentlyPlayed(uint64_t userId,
|
|
size_t limit)
|
|
{
|
|
(void)userId;
|
|
(void)limit;
|
|
return std::vector<TrackInfo>{};
|
|
}
|
|
|
|
Result<PlaybackStatistics> Database::getStatistics(
|
|
uint64_t userId,
|
|
std::optional<std::chrono::system_clock::time_point>
|
|
since)
|
|
{
|
|
(void)userId;
|
|
(void)since;
|
|
return PlaybackStatistics{};
|
|
}
|
|
|
|
Result<std::vector<std::pair<TrackInfo, uint64_t>>>
|
|
Database::getMostPlayed(uint64_t userId, size_t limit)
|
|
{
|
|
(void)userId;
|
|
(void)limit;
|
|
return std::vector<std::pair<TrackInfo, uint64_t>>{};
|
|
}
|
|
|
|
Result<void> Database::executeQuery(const std::string& sql,
|
|
RowCallback callback)
|
|
{
|
|
(void)sql;
|
|
(void)callback;
|
|
return {};
|
|
}
|
|
|
|
// 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
|
|
sqlite3_stmt* checkStmt;
|
|
if (sqlite3_prepare_v2(impl_->db,
|
|
"SELECT 1 FROM subscriptions WHERE uid = ?", -1,
|
|
&checkStmt, nullptr) != SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
sqlite3_bind_text(checkStmt, 1, uid.c_str(), -1, SQLITE_STATIC);
|
|
bool exists = sqlite3_step(checkStmt) == SQLITE_ROW;
|
|
sqlite3_finalize(checkStmt);
|
|
|
|
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'));
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_text(stmt, 1, token.c_str(), -1, SQLITE_STATIC);
|
|
sqlite3_bind_text(stmt, 2, uid.c_str(), -1, SQLITE_STATIC);
|
|
|
|
if (sqlite3_step(stmt) != SQLITE_DONE) {
|
|
sqlite3_finalize(stmt);
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_finalize(stmt);
|
|
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;
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC);
|
|
|
|
std::optional<std::string> token;
|
|
if (sqlite3_step(stmt) == SQLITE_ROW) {
|
|
const char* tokenStr =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
|
|
if (tokenStr) {
|
|
token = tokenStr;
|
|
}
|
|
}
|
|
|
|
sqlite3_finalize(stmt);
|
|
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 = ?;
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_text(stmt, 1, token.c_str(), -1, SQLITE_STATIC);
|
|
|
|
bool valid = sqlite3_step(stmt) == SQLITE_ROW;
|
|
sqlite3_finalize(stmt);
|
|
|
|
if (valid) {
|
|
// Update last_used_at
|
|
const char* updateSql = R"(
|
|
UPDATE rpc_tokens SET last_used_at = datetime('now') WHERE token = ?;
|
|
)";
|
|
sqlite3_stmt* updateStmt;
|
|
if (sqlite3_prepare_v2(impl_->db, updateSql, -1, &updateStmt,
|
|
nullptr) == SQLITE_OK) {
|
|
sqlite3_bind_text(updateStmt, 1, token.c_str(), -1,
|
|
SQLITE_STATIC);
|
|
sqlite3_step(updateStmt);
|
|
sqlite3_finalize(updateStmt);
|
|
}
|
|
}
|
|
|
|
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 = ?;
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_text(stmt, 1, token.c_str(), -1, SQLITE_STATIC);
|
|
|
|
std::optional<std::string> uid;
|
|
if (sqlite3_step(stmt) == SQLITE_ROW) {
|
|
const char* uidStr =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
|
|
if (uidStr) {
|
|
uid = uidStr;
|
|
}
|
|
}
|
|
|
|
sqlite3_finalize(stmt);
|
|
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;
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_text(stmt, 1, nickname.c_str(), -1, SQLITE_STATIC);
|
|
|
|
std::optional<std::string> uid;
|
|
if (sqlite3_step(stmt) == SQLITE_ROW) {
|
|
const char* uidStr =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
|
|
if (uidStr) {
|
|
uid = uidStr;
|
|
}
|
|
}
|
|
|
|
sqlite3_finalize(stmt);
|
|
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 = ?;
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_bind_text(stmt, 1, token.c_str(), -1, SQLITE_STATIC);
|
|
|
|
if (sqlite3_step(stmt) != SQLITE_DONE) {
|
|
sqlite3_finalize(stmt);
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
sqlite3_finalize(stmt);
|
|
return {};
|
|
}
|
|
|
|
Result<std::vector<std::string>> Database::getAllSubscriberUids()
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
const char* sql = R"(
|
|
SELECT uid FROM subscriptions;
|
|
)";
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
|
|
SQLITE_OK) {
|
|
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
|
|
}
|
|
|
|
std::vector<std::string> uids;
|
|
while (sqlite3_step(stmt) == SQLITE_ROW) {
|
|
const char* uidStr =
|
|
reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
|
|
if (uidStr) {
|
|
uids.push_back(uidStr);
|
|
}
|
|
}
|
|
|
|
sqlite3_finalize(stmt);
|
|
return uids;
|
|
}
|
|
|
|
} // namespace Echoion::Api
|