371 lines
11 KiB
C++
371 lines
11 KiB
C++
#pragma once
|
|
|
|
#include "TrackTypes.hpp"
|
|
#include "Types.hpp"
|
|
#include <atomic>
|
|
#include <functional>
|
|
#include <memory>
|
|
#include <mutex>
|
|
#include <optional>
|
|
#include <shared_mutex>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
namespace Echoion::Api
|
|
{
|
|
|
|
// Forward declaration
|
|
class DatabaseImpl;
|
|
|
|
// Database configuration
|
|
struct DatabaseConfig {
|
|
std::string path = "echoion.db";
|
|
bool walMode = true; // Write-Ahead Logging for better concurrency
|
|
int maxConnections = 4;
|
|
std::chrono::seconds busyTimeout{5000};
|
|
};
|
|
|
|
// Playlist with tracks
|
|
struct Playlist {
|
|
uint64_t id;
|
|
std::string name;
|
|
std::string description;
|
|
uint64_t createdBy;
|
|
std::chrono::system_clock::time_point createdAt;
|
|
std::chrono::system_clock::time_point updatedAt;
|
|
std::vector<TrackInfo> tracks;
|
|
bool isPublic = false;
|
|
std::string externalId; // YouTube playlist ID, etc.
|
|
};
|
|
|
|
// Playback history entry
|
|
struct PlaybackHistoryEntry {
|
|
uint64_t id;
|
|
TrackInfo track;
|
|
uint64_t playedBy;
|
|
std::chrono::system_clock::time_point playedAt;
|
|
std::chrono::milliseconds duration; // How long it played
|
|
bool completed = false; // Did it play to the end
|
|
};
|
|
|
|
// User favorites
|
|
struct FavoriteTrack {
|
|
TrackInfo track;
|
|
uint64_t userId;
|
|
std::chrono::system_clock::time_point addedAt;
|
|
};
|
|
|
|
// Statistics
|
|
struct PlaybackStatistics {
|
|
uint64_t totalPlays = 0;
|
|
uint64_t totalTracks = 0;
|
|
uint64_t totalPlaytimeMs = 0;
|
|
std::optional<TrackInfo> mostPlayedTrack;
|
|
uint64_t mostPlayedCount = 0;
|
|
};
|
|
|
|
// Server-wide aggregate statistics (web dashboard)
|
|
struct AggregateStats {
|
|
uint64_t tracksToday = 0; // completed plays today
|
|
uint64_t listeningMsToday = 0; // summed play duration today
|
|
uint64_t queueAdditionsToday = 0;
|
|
uint64_t skipsToday = 0;
|
|
uint64_t playsTotal = 0;
|
|
uint64_t skipsTotal = 0;
|
|
// Most active requesters, most additions first.
|
|
struct TopRequester {
|
|
std::string uid; // TeamSpeak uid (may be empty for old rows)
|
|
std::string nickname;
|
|
uint64_t count = 0;
|
|
};
|
|
std::vector<TopRequester> topRequesters;
|
|
// Source split over the whole history
|
|
uint64_t youtubeCount = 0;
|
|
uint64_t yandexCount = 0;
|
|
uint64_t otherCount = 0;
|
|
};
|
|
|
|
// Main database interface
|
|
class Database
|
|
{
|
|
public:
|
|
|
|
Database();
|
|
~Database();
|
|
|
|
// Non-copyable
|
|
Database(const Database&) = delete;
|
|
Database& operator=(const Database&) = delete;
|
|
|
|
// Initialization
|
|
Api::Result<void> initialize(const DatabaseConfig& config = {});
|
|
void shutdown();
|
|
[[nodiscard]] bool isInitialized() const;
|
|
|
|
// Migrations
|
|
Api::Result<void> migrate(); // Run pending migrations
|
|
[[nodiscard]] int getCurrentVersion() const;
|
|
|
|
// ===== Playlists =====
|
|
|
|
// Create a new playlist
|
|
[[nodiscard]] Api::Result<uint64_t>
|
|
createPlaylist(const std::string& name,
|
|
const std::string& description,
|
|
uint64_t createdBy,
|
|
bool isPublic = false,
|
|
const std::string& externalId = "");
|
|
|
|
// Get or create playlist by external ID (e.g., YouTube playlist ID)
|
|
// Returns existing playlist ID if found, creates new one otherwise
|
|
[[nodiscard]] Api::Result<uint64_t>
|
|
getOrCreatePlaylistByExternalId(const std::string& externalId,
|
|
const std::string& name,
|
|
const std::string& description,
|
|
uint64_t createdBy,
|
|
bool isPublic = false);
|
|
|
|
// Get playlist by ID
|
|
[[nodiscard]] Api::Result<std::optional<Playlist>>
|
|
getPlaylist(uint64_t id);
|
|
|
|
// Get all playlists for a user
|
|
[[nodiscard]] Api::Result<std::vector<Playlist>>
|
|
getUserPlaylists(uint64_t userId);
|
|
|
|
// Get every playlist (used by the RPC GetPlaylists endpoint).
|
|
[[nodiscard]] Api::Result<std::vector<Playlist>>
|
|
getAllPlaylists();
|
|
|
|
// Update playlist
|
|
Api::Result<void> updatePlaylist(
|
|
uint64_t id,
|
|
const std::optional<std::string>& name = std::nullopt,
|
|
const std::optional<std::string>& description = std::nullopt,
|
|
const std::optional<bool>& isPublic = std::nullopt);
|
|
|
|
// Delete playlist
|
|
Api::Result<void> deletePlaylist(uint64_t id);
|
|
|
|
// Add track to playlist
|
|
Api::Result<void> addTrackToPlaylist(uint64_t playlistId,
|
|
const TrackInfo& track,
|
|
uint32_t position = 0);
|
|
|
|
// Remove track from playlist
|
|
Api::Result<void> removeTrackFromPlaylist(uint64_t playlistId,
|
|
uint64_t trackId);
|
|
|
|
// Reorder playlist tracks
|
|
Api::Result<void> reorderPlaylistTrack(uint64_t playlistId,
|
|
uint64_t trackId,
|
|
uint32_t newPosition);
|
|
|
|
// ===== Playback History =====
|
|
|
|
// Record a playback
|
|
Api::Result<void> recordPlayback(const TrackInfo& track,
|
|
uint64_t playedBy,
|
|
std::chrono::milliseconds duration,
|
|
bool completed);
|
|
|
|
// Get playback history for a user
|
|
[[nodiscard]] Api::Result<std::vector<PlaybackHistoryEntry>>
|
|
getPlaybackHistory(uint64_t userId,
|
|
size_t limit = 100,
|
|
size_t offset = 0);
|
|
|
|
// Get recently played tracks
|
|
[[nodiscard]] Api::Result<std::vector<TrackInfo>>
|
|
getRecentlyPlayed(uint64_t userId, size_t limit = 20);
|
|
|
|
// Record a skipped track (playback aborted by user action)
|
|
Api::Result<void> recordSkip(const TrackInfo& track,
|
|
uint64_t playedBy);
|
|
|
|
// Log a queue addition (daily stats / top requesters)
|
|
Api::Result<void> logQueueAddition(const std::string& uid,
|
|
const std::string& nickname);
|
|
|
|
// ===== Favorites =====
|
|
|
|
// Add track to favorites
|
|
Api::Result<void> addFavorite(uint64_t userId,
|
|
const TrackInfo& track);
|
|
|
|
// Remove track from favorites
|
|
Api::Result<void> removeFavorite(uint64_t userId,
|
|
const std::string& trackUrl);
|
|
|
|
// Check if track is favorited
|
|
[[nodiscard]] Api::Result<bool>
|
|
isFavorite(uint64_t userId, const std::string& trackUrl);
|
|
|
|
// Get all favorites for a user
|
|
[[nodiscard]] Api::Result<std::vector<FavoriteTrack>>
|
|
getFavorites(uint64_t userId);
|
|
|
|
// ===== Statistics =====
|
|
|
|
// Get playback statistics
|
|
[[nodiscard]] Api::Result<PlaybackStatistics> getStatistics(
|
|
uint64_t userId,
|
|
std::optional<std::chrono::system_clock::time_point> since =
|
|
std::nullopt);
|
|
|
|
// Get most played tracks
|
|
[[nodiscard]] Api::Result<
|
|
std::vector<std::pair<TrackInfo, uint64_t>>>
|
|
getMostPlayed(uint64_t userId, size_t limit = 10);
|
|
|
|
// Get server-wide aggregate statistics (web dashboard)
|
|
[[nodiscard]] Api::Result<AggregateStats> getAggregateStats();
|
|
|
|
// ===== Key/value store =====
|
|
// Small persisted state (healthy instance lists, ...). Values
|
|
// are opaque strings (callers serialize as needed).
|
|
[[nodiscard]] Api::Result<std::optional<std::string>>
|
|
getKv(const std::string& key);
|
|
Api::Result<void> setKv(const std::string& key,
|
|
const std::string& value);
|
|
|
|
// ===== Cached avatars (web UI) =====
|
|
// TeamSpeak avatar images persisted by uid so the web UI can show
|
|
// them even when the client is offline or out of the bot's view
|
|
// (the live TS avatar cache only holds in-view clients). `data` is
|
|
// base64-encoded image bytes.
|
|
struct CachedAvatar {
|
|
std::string uid;
|
|
std::string mime;
|
|
std::string dataBase64;
|
|
// The source myTeamSpeak avatar URL, so an offline user's
|
|
// avatar can be re-fetched even when the image bytes were
|
|
// never stored. Empty for legacy/file avatars.
|
|
std::string url;
|
|
};
|
|
// Image (mime + base64 data + url) for one uid, or nullopt if none.
|
|
[[nodiscard]] Api::Result<std::optional<CachedAvatar>>
|
|
getCachedAvatar(const std::string& uid);
|
|
// Insert or replace the cached avatar image for a uid (keeps any
|
|
// previously stored url).
|
|
Api::Result<void> putCachedAvatar(const std::string& uid,
|
|
const std::string& mime,
|
|
const std::string& dataBase64);
|
|
// Record just the source url for a uid (upsert), so it survives to
|
|
// be re-fetched after the user goes offline.
|
|
Api::Result<void> putCachedAvatarUrl(const std::string& uid,
|
|
const std::string& url);
|
|
|
|
// ===== Subscriptions =====
|
|
|
|
// Subscriber info
|
|
struct SubscriberInfo {
|
|
std::string uid;
|
|
std::string nickname;
|
|
std::chrono::system_clock::time_point subscribedAt;
|
|
};
|
|
|
|
// Add a subscriber (by UID)
|
|
Api::Result<void> addSubscriber(const std::string& uid,
|
|
const std::string& nickname);
|
|
|
|
// Remove a subscriber (by UID)
|
|
Api::Result<void> removeSubscriber(const std::string& uid);
|
|
|
|
// Check if client is subscribed (by UID)
|
|
[[nodiscard]] Api::Result<bool>
|
|
isSubscriber(const std::string& uid);
|
|
|
|
// Get all subscribers
|
|
[[nodiscard]] Api::Result<std::vector<SubscriberInfo>>
|
|
getAllSubscribers();
|
|
|
|
// Get subscriber count
|
|
[[nodiscard]] Api::Result<size_t> getSubscriberCount();
|
|
|
|
// Clear all subscribers
|
|
Api::Result<void> clearAllSubscribers();
|
|
|
|
// ===== RPC Authentication =====
|
|
|
|
// RPC token info
|
|
struct RpcTokenInfo {
|
|
std::string uid;
|
|
std::string token;
|
|
std::chrono::system_clock::time_point createdAt;
|
|
std::chrono::system_clock::time_point lastUsedAt;
|
|
bool isActive = true;
|
|
};
|
|
|
|
// Generate new RPC token for subscriber
|
|
[[nodiscard]] Api::Result<std::string>
|
|
generateRpcToken(const std::string& uid);
|
|
|
|
// Get existing RPC token for subscriber (if any)
|
|
[[nodiscard]] Api::Result<std::optional<std::string>>
|
|
getExistingRpcToken(const std::string& uid);
|
|
|
|
// Validate RPC token
|
|
[[nodiscard]] Api::Result<bool>
|
|
validateRpcToken(const std::string& token);
|
|
|
|
// Get UID from RPC token
|
|
[[nodiscard]] Api::Result<std::optional<std::string>>
|
|
getUidFromRpcToken(const std::string& token);
|
|
|
|
// Revoke RPC token
|
|
Api::Result<void> revokeRpcToken(const std::string& token);
|
|
|
|
// Get subscriber UID by nickname (case-insensitive)
|
|
[[nodiscard]] Api::Result<std::optional<std::string>>
|
|
getSubscriberByNickname(const std::string& nickname);
|
|
|
|
// Get all subscriber UIDs
|
|
[[nodiscard]] Api::Result<std::vector<std::string>>
|
|
getAllSubscriberUids();
|
|
|
|
// ===== Cache Management =====
|
|
|
|
// Clear old history (keep last N entries)
|
|
Api::Result<void> trimHistory(size_t keepCount = 10000);
|
|
|
|
// Clear all data for a user
|
|
Api::Result<void> clearUserData(uint64_t userId);
|
|
|
|
// Vacuum database (reclaim space)
|
|
Api::Result<void> vacuum();
|
|
|
|
// ===== Raw Query (for advanced use) =====
|
|
|
|
using RowCallback = std::function<void(
|
|
const std::vector<std::optional<std::string>>&)>;
|
|
Api::Result<void> executeQuery(const std::string& sql,
|
|
RowCallback callback = nullptr);
|
|
|
|
private:
|
|
|
|
std::unique_ptr<DatabaseImpl> impl_;
|
|
mutable std::shared_mutex
|
|
mutex_; // Shared mutex for read/write concurrency
|
|
std::atomic<bool> shutdown_{
|
|
false}; // Flag to prevent operations after shutdown
|
|
};
|
|
|
|
// Database manager (singleton)
|
|
class DatabaseManager
|
|
{
|
|
public:
|
|
|
|
static Database& instance();
|
|
|
|
static Api::Result<void>
|
|
initialize(const DatabaseConfig& config = {});
|
|
static void shutdown();
|
|
|
|
private:
|
|
|
|
DatabaseManager() = default;
|
|
};
|
|
|
|
} // namespace Echoion::Api
|