Format and .clang-format
This commit is contained in:
1 parent
6aed7b0027
commit
b94b634a87
47 files changed
+42341
-39711
No files matched your search
+321
-261
@@ -1,321 +1,381 @@
|
||||
#pragma once
|
||||
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <print>
|
||||
#include <chrono>
|
||||
#include <source_location>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <print>
|
||||
#include <source_location>
|
||||
#include <string>
|
||||
#include <deque>
|
||||
#include <condition_variable>
|
||||
#include <atomic>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
|
||||
#include <ts6bot/Config.hpp>
|
||||
|
||||
#include "Singleton.hpp"
|
||||
|
||||
class Logger : public Singleton<Logger> {
|
||||
friend class Singleton<Logger>;
|
||||
class Logger : public Singleton<Logger>
|
||||
{
|
||||
friend class Singleton<Logger>;
|
||||
|
||||
// ANSI Color codes
|
||||
struct Colors {
|
||||
static constexpr auto RESET = "\033[0m";
|
||||
static constexpr auto TRACE = "\033[37m"; // White
|
||||
static constexpr auto DEBUG = "\033[36m"; // Cyan
|
||||
static constexpr auto INFO = "\033[32m"; // Green
|
||||
static constexpr auto WARNING = "\033[33m"; // Yellow
|
||||
static constexpr auto ERROR = "\033[31m"; // Red
|
||||
static constexpr auto CRITICAL = "\033[1;31m"; // Bold Red
|
||||
};
|
||||
// ANSI Color codes
|
||||
struct Colors {
|
||||
static constexpr auto RESET = "\033[0m";
|
||||
static constexpr auto TRACE = "\033[37m"; // White
|
||||
static constexpr auto DEBUG = "\033[36m"; // Cyan
|
||||
static constexpr auto INFO = "\033[32m"; // Green
|
||||
static constexpr auto WARNING = "\033[33m"; // Yellow
|
||||
static constexpr auto ERROR = "\033[31m"; // Red
|
||||
static constexpr auto CRITICAL = "\033[1;31m"; // Bold Red
|
||||
};
|
||||
|
||||
// Internal structure to hold log data in the queue
|
||||
struct LogEntry {
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
std::thread::id threadId;
|
||||
std::source_location sourceLoc;
|
||||
ts6bot::LogLevel level;
|
||||
std::string message; // Pre-formatted user message
|
||||
};
|
||||
// Internal structure to hold log data in the queue
|
||||
struct LogEntry {
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
std::thread::id threadId;
|
||||
std::source_location sourceLoc;
|
||||
ts6bot::LogLevel level;
|
||||
std::string message; // Pre-formatted user message
|
||||
};
|
||||
|
||||
public:
|
||||
explicit Logger(const ts6bot::LogLevel logLevel = ts6bot::LogLevel::Info)
|
||||
: m_minLevel(logLevel), m_exit(false)
|
||||
{
|
||||
// 1. Setup File Sinks (Synchronous init)
|
||||
try {
|
||||
namespace fs = std::filesystem;
|
||||
const fs::path logDir = "logs";
|
||||
if (!fs::exists(logDir)) fs::create_directories(logDir);
|
||||
public:
|
||||
|
||||
// Time for filename (UTC)
|
||||
const auto now = std::chrono::system_clock::now();
|
||||
auto now_utc = std::chrono::zoned_time{std::chrono::locate_zone("UTC"), now};
|
||||
std::string timestamp = std::format("{:%Y-%m-%d_%H-%M-%S}", now_utc);
|
||||
explicit Logger(
|
||||
const ts6bot::LogLevel logLevel = ts6bot::LogLevel::Info)
|
||||
: m_minLevel(logLevel), m_exit(false)
|
||||
{
|
||||
// 1. Setup File Sinks (Synchronous init)
|
||||
try {
|
||||
namespace fs = std::filesystem;
|
||||
const fs::path logDir = "logs";
|
||||
if (!fs::exists(logDir)) {
|
||||
fs::create_directories(logDir);
|
||||
}
|
||||
|
||||
// Open trace file (all logs)
|
||||
std::string traceFilename = std::format("trace_{}.log", timestamp);
|
||||
m_logFiles[ts6bot::LogLevel::Trace].open(logDir / traceFilename, std::ios::out | std::ios::app);
|
||||
// Time for filename (UTC)
|
||||
const auto now = std::chrono::system_clock::now();
|
||||
auto now_utc = std::chrono::zoned_time{
|
||||
std::chrono::locate_zone("UTC"), now};
|
||||
std::string timestamp =
|
||||
std::format("{:%Y-%m-%d_%H-%M-%S}", now_utc);
|
||||
|
||||
// Open error file
|
||||
std::string errorFilename = std::format("error_{}.log", timestamp);
|
||||
m_logFiles[ts6bot::LogLevel::Error].open(logDir / errorFilename, std::ios::out | std::ios::app);
|
||||
// Open trace file (all logs)
|
||||
std::string traceFilename =
|
||||
std::format("trace_{}.log", timestamp);
|
||||
m_logFiles[ts6bot::LogLevel::Trace].open(
|
||||
logDir / traceFilename, std::ios::out | std::ios::app);
|
||||
|
||||
// Open warning file
|
||||
std::string warningFilename = std::format("warning_{}.log", timestamp);
|
||||
m_logFiles[ts6bot::LogLevel::Warning].open(logDir / warningFilename, std::ios::out | std::ios::app);
|
||||
// Open error file
|
||||
std::string errorFilename =
|
||||
std::format("error_{}.log", timestamp);
|
||||
m_logFiles[ts6bot::LogLevel::Error].open(
|
||||
logDir / errorFilename, std::ios::out | std::ios::app);
|
||||
|
||||
// Open critical file
|
||||
std::string criticalFilename = std::format("critical_{}.log", timestamp);
|
||||
m_logFiles[ts6bot::LogLevel::Critical].open(logDir / criticalFilename, std::ios::out | std::ios::app);
|
||||
// Open warning file
|
||||
std::string warningFilename =
|
||||
std::format("warning_{}.log", timestamp);
|
||||
m_logFiles[ts6bot::LogLevel::Warning].open(
|
||||
logDir / warningFilename, std::ios::out | std::ios::app);
|
||||
|
||||
// Check if files opened successfully
|
||||
for (const auto& [level, file] : m_logFiles) {
|
||||
if (!file.is_open()) {
|
||||
std::println(std::cerr, "Logger Error: Failed to open log file for level: {}", levelToString(level));
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
std::println(std::cerr, "Logger Initialization Error: {}", e.what());
|
||||
}
|
||||
// Open critical file
|
||||
std::string criticalFilename =
|
||||
std::format("critical_{}.log", timestamp);
|
||||
m_logFiles[ts6bot::LogLevel::Critical].open(
|
||||
logDir / criticalFilename, std::ios::out | std::ios::app);
|
||||
|
||||
// 2. Start Worker Thread
|
||||
m_workerThread = std::jthread([this](const std::stop_token &st) {
|
||||
this->workerLoop(st);
|
||||
});
|
||||
}
|
||||
// Check if files opened successfully
|
||||
for (const auto &[level, file] : m_logFiles) {
|
||||
if (!file.is_open()) {
|
||||
std::println(std::cerr,
|
||||
"Logger Error: Failed to open log file "
|
||||
"for level: {}",
|
||||
levelToString(level));
|
||||
}
|
||||
}
|
||||
} catch (const std::exception &e) {
|
||||
std::println(std::cerr, "Logger Initialization Error: {}",
|
||||
e.what());
|
||||
}
|
||||
|
||||
~Logger() override {
|
||||
// Signal exit and wake up worker
|
||||
m_exit = true;
|
||||
m_cv.notify_one();
|
||||
// m_workerThread destructor will wait for join automatically
|
||||
// 2. Start Worker Thread
|
||||
m_workerThread = std::jthread(
|
||||
[this](const std::stop_token &st) { this->workerLoop(st); });
|
||||
}
|
||||
|
||||
// Close all log files
|
||||
for (auto &file: m_logFiles | std::views::values) {
|
||||
if (file.is_open()) {
|
||||
file.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
~Logger() override
|
||||
{
|
||||
// Signal exit and wake up worker
|
||||
m_exit = true;
|
||||
m_cv.notify_one();
|
||||
// m_workerThread destructor will wait for join automatically
|
||||
|
||||
// --- Public Logging API ---
|
||||
// Close all log files
|
||||
for (auto &file : m_logFiles | std::views::values) {
|
||||
if (file.is_open()) {
|
||||
file.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Generic log function
|
||||
template <typename... Args>
|
||||
void log(const ts6bot::LogLevel level, const std::source_location& loc, std::format_string<Args...> fmt, Args&&... args) {
|
||||
if (level < m_minLevel || level == ts6bot::LogLevel::None) return;
|
||||
// --- Public Logging API ---
|
||||
|
||||
try {
|
||||
// 1. Capture context immediately
|
||||
// Generic log function
|
||||
template <typename... Args>
|
||||
void log(const ts6bot::LogLevel level, const std::source_location &loc,
|
||||
std::format_string<Args...> fmt, Args &&...args)
|
||||
{
|
||||
if (level < m_minLevel || level == ts6bot::LogLevel::None) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Push to Queue
|
||||
{
|
||||
LogEntry entry{
|
||||
.timestamp = std::chrono::system_clock::now(),
|
||||
.threadId = std::this_thread::get_id(),
|
||||
.sourceLoc = loc,
|
||||
.level = level,
|
||||
// 2. Format message immediately (capture by value) to avoid dangling references
|
||||
.message = std::format(fmt, std::forward<Args>(args)...)
|
||||
};
|
||||
std::lock_guard lock(m_queueMutex);
|
||||
m_logQueue.push_back(std::move(entry));
|
||||
}
|
||||
m_cv.notify_one();
|
||||
try {
|
||||
// 1. Capture context immediately
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
// Fallback if formatting fails
|
||||
std::println(std::cerr, "Logging Error: {}", e.what());
|
||||
}
|
||||
}
|
||||
// 3. Push to Queue
|
||||
{
|
||||
LogEntry entry{
|
||||
.timestamp = std::chrono::system_clock::now(),
|
||||
.threadId = std::this_thread::get_id(),
|
||||
.sourceLoc = loc,
|
||||
.level = level,
|
||||
// 2. Format message immediately (capture by value) to
|
||||
// avoid dangling references
|
||||
.message =
|
||||
std::format(fmt, std::forward<Args>(args)...)};
|
||||
std::lock_guard lock(m_queueMutex);
|
||||
m_logQueue.push_back(std::move(entry));
|
||||
}
|
||||
m_cv.notify_one();
|
||||
|
||||
// Convenience Wrappers
|
||||
template <typename... Args>
|
||||
void trace(std::format_string<Args...> fmt, Args&&... args) {
|
||||
log(ts6bot::LogLevel::Trace, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
} catch (const std::exception &e) {
|
||||
// Fallback if formatting fails
|
||||
std::println(std::cerr, "Logging Error: {}", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void info(std::format_string<Args...> fmt, Args&&... args) {
|
||||
log(ts6bot::LogLevel::Info, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
// Convenience Wrappers
|
||||
template <typename... Args>
|
||||
void trace(std::format_string<Args...> fmt, Args &&...args)
|
||||
{
|
||||
log(ts6bot::LogLevel::Trace, std::source_location::current(), fmt,
|
||||
std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void error(std::format_string<Args...> fmt, Args&&... args) {
|
||||
log(ts6bot::LogLevel::Error, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
template <typename... Args>
|
||||
void info(std::format_string<Args...> fmt, Args &&...args)
|
||||
{
|
||||
log(ts6bot::LogLevel::Info, std::source_location::current(), fmt,
|
||||
std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void warn(std::format_string<Args...> fmt, Args&&... args) {
|
||||
log(ts6bot::LogLevel::Warning, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
template <typename... Args>
|
||||
void error(std::format_string<Args...> fmt, Args &&...args)
|
||||
{
|
||||
log(ts6bot::LogLevel::Error, std::source_location::current(), fmt,
|
||||
std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void debug(std::format_string<Args...> fmt, Args&&... args) {
|
||||
log(ts6bot::LogLevel::Debug, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
template <typename... Args>
|
||||
void warn(std::format_string<Args...> fmt, Args &&...args)
|
||||
{
|
||||
log(ts6bot::LogLevel::Warning, std::source_location::current(), fmt,
|
||||
std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void critical(std::format_string<Args...> fmt, Args&&... args) {
|
||||
log(ts6bot::LogLevel::Critical, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
template <typename... Args>
|
||||
void debug(std::format_string<Args...> fmt, Args &&...args)
|
||||
{
|
||||
log(ts6bot::LogLevel::Debug, std::source_location::current(), fmt,
|
||||
std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
void SetLogLevel(const ts6bot::LogLevel level) { m_minLevel = level; }
|
||||
template <typename... Args>
|
||||
void critical(std::format_string<Args...> fmt, Args &&...args)
|
||||
{
|
||||
log(ts6bot::LogLevel::Critical, std::source_location::current(),
|
||||
fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
private:
|
||||
// --- Backend Worker ---
|
||||
void workerLoop(std::stop_token st) {
|
||||
while (!st.stop_requested() || !isQueueEmpty()) {
|
||||
std::unique_lock lock(m_queueMutex);
|
||||
void SetLogLevel(const ts6bot::LogLevel level) { m_minLevel = level; }
|
||||
|
||||
// Wait until data is available or stop is requested
|
||||
m_cv.wait(lock, [this, &st] {
|
||||
return !m_logQueue.empty() || st.stop_requested() || m_exit;
|
||||
});
|
||||
private:
|
||||
|
||||
if (m_logQueue.empty()) {
|
||||
if (st.stop_requested() || m_exit) break;
|
||||
continue;
|
||||
}
|
||||
// --- Backend Worker ---
|
||||
void workerLoop(std::stop_token st)
|
||||
{
|
||||
while (!st.stop_requested() || !isQueueEmpty()) {
|
||||
std::unique_lock lock(m_queueMutex);
|
||||
|
||||
// Swap queue to local buffer to minimize lock time
|
||||
std::deque<LogEntry> localQueue;
|
||||
std::swap(localQueue, m_logQueue);
|
||||
lock.unlock();
|
||||
// Wait until data is available or stop is requested
|
||||
m_cv.wait(lock, [this, &st] {
|
||||
return !m_logQueue.empty() || st.stop_requested() || m_exit;
|
||||
});
|
||||
|
||||
// Process Batch
|
||||
for (const auto& entry : localQueue) {
|
||||
writeLog(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (m_logQueue.empty()) {
|
||||
if (st.stop_requested() || m_exit) {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
bool isQueueEmpty() {
|
||||
std::lock_guard lock(m_queueMutex);
|
||||
return m_logQueue.empty();
|
||||
}
|
||||
// Swap queue to local buffer to minimize lock time
|
||||
std::deque<LogEntry> localQueue;
|
||||
std::swap(localQueue, m_logQueue);
|
||||
lock.unlock();
|
||||
|
||||
void writeLog(const LogEntry& entry) {
|
||||
// Format: "HH:MM:SS.nanoseconds [thread_id] /path/to/file.cpp:line LOG_LEVEL message"
|
||||
// Process Batch
|
||||
for (const auto &entry : localQueue) {
|
||||
writeLog(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto utc_time = std::chrono::zoned_time{std::chrono::locate_zone("UTC"), entry.timestamp};
|
||||
bool isQueueEmpty()
|
||||
{
|
||||
std::lock_guard lock(m_queueMutex);
|
||||
return m_logQueue.empty();
|
||||
}
|
||||
|
||||
// Extract nanoseconds
|
||||
const auto duration = entry.timestamp.time_since_epoch();
|
||||
const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration);
|
||||
const auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(duration - seconds);
|
||||
void writeLog(const LogEntry &entry)
|
||||
{
|
||||
// Format: "HH:MM:SS.nanoseconds [thread_id] /path/to/file.cpp:line
|
||||
// LOG_LEVEL message"
|
||||
|
||||
// Format source location
|
||||
std::string sourceLocation = std::format("{}:{}",
|
||||
entry.sourceLoc.file_name(),
|
||||
entry.sourceLoc.line());
|
||||
auto utc_time = std::chrono::zoned_time{
|
||||
std::chrono::locate_zone("UTC"), entry.timestamp};
|
||||
|
||||
// Get thread ID as integer
|
||||
std::ostringstream threadIdStream;
|
||||
threadIdStream << entry.threadId;
|
||||
std::string threadIdStr = threadIdStream.str();
|
||||
// Extract nanoseconds
|
||||
const auto duration = entry.timestamp.time_since_epoch();
|
||||
const auto seconds =
|
||||
std::chrono::duration_cast<std::chrono::seconds>(duration);
|
||||
const auto nanoseconds =
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(duration -
|
||||
seconds);
|
||||
|
||||
// Construct log without colors (for file)
|
||||
const std::string fileLog = std::format("{:%H:%M:%S}.{:09} [{}] {:<28} {:<9} {}\n",
|
||||
utc_time,
|
||||
nanoseconds.count(),
|
||||
threadIdStr,
|
||||
sourceLocation,
|
||||
levelToString(entry.level),
|
||||
entry.message
|
||||
);
|
||||
// Format source location
|
||||
std::string sourceLocation = std::format(
|
||||
"{}:{}", entry.sourceLoc.file_name(), entry.sourceLoc.line());
|
||||
|
||||
// Construct colored log (for console)
|
||||
const char* color = getColorForLevel(entry.level);
|
||||
std::string consoleLog = std::format("{}{:%H:%M:%S}.{:09}{} [{}] {:<28} {}{:<9}{} {}\n",
|
||||
color,
|
||||
utc_time,
|
||||
nanoseconds.count(),
|
||||
Colors::RESET,
|
||||
threadIdStr,
|
||||
sourceLocation,
|
||||
color,
|
||||
levelToString(entry.level),
|
||||
Colors::RESET,
|
||||
entry.message
|
||||
);
|
||||
// Get thread ID as integer
|
||||
std::ostringstream threadIdStream;
|
||||
threadIdStream << entry.threadId;
|
||||
std::string threadIdStr = threadIdStream.str();
|
||||
|
||||
// Print to Console with colors
|
||||
std::print(std::cout, "{}", consoleLog);
|
||||
// Construct log without colors (for file)
|
||||
const std::string fileLog = std::format(
|
||||
"{:%H:%M:%S}.{:09} [{}] {:<28} {:<9} {}\n", utc_time,
|
||||
nanoseconds.count(), threadIdStr, sourceLocation,
|
||||
levelToString(entry.level), entry.message);
|
||||
|
||||
// Write to trace file (all logs) - no colors
|
||||
if (m_logFiles.at(ts6bot::LogLevel::Trace).is_open()) {
|
||||
m_logFiles.at(ts6bot::LogLevel::Trace) << fileLog;
|
||||
m_logFiles.at(ts6bot::LogLevel::Trace).flush();
|
||||
}
|
||||
// Construct colored log (for console)
|
||||
const char *color = getColorForLevel(entry.level);
|
||||
std::string consoleLog = std::format(
|
||||
"{}{:%H:%M:%S}.{:09}{} [{}] {:<28} {}{:<9}{} {}\n", color,
|
||||
utc_time, nanoseconds.count(), Colors::RESET, threadIdStr,
|
||||
sourceLocation, color, levelToString(entry.level),
|
||||
Colors::RESET, entry.message);
|
||||
|
||||
// Write to specific level files - no colors
|
||||
if (entry.level == ts6bot::LogLevel::Error && m_logFiles.at(ts6bot::LogLevel::Error).is_open()) {
|
||||
m_logFiles.at(ts6bot::LogLevel::Error) << fileLog;
|
||||
m_logFiles.at(ts6bot::LogLevel::Error).flush();
|
||||
}
|
||||
else if (entry.level == ts6bot::LogLevel::Warning && m_logFiles.at(ts6bot::LogLevel::Warning).is_open()) {
|
||||
m_logFiles.at(ts6bot::LogLevel::Warning) << fileLog;
|
||||
m_logFiles.at(ts6bot::LogLevel::Warning).flush();
|
||||
}
|
||||
else if (entry.level == ts6bot::LogLevel::Critical && m_logFiles.at(ts6bot::LogLevel::Critical).is_open()) {
|
||||
m_logFiles.at(ts6bot::LogLevel::Critical) << fileLog;
|
||||
m_logFiles.at(ts6bot::LogLevel::Critical).flush();
|
||||
}
|
||||
}
|
||||
// Print to Console with colors
|
||||
std::print(std::cout, "{}", consoleLog);
|
||||
|
||||
static const char* getColorForLevel(const ts6bot::LogLevel level) {
|
||||
switch (level) {
|
||||
case ts6bot::LogLevel::Trace: return Colors::TRACE;
|
||||
case ts6bot::LogLevel::Debug: return Colors::DEBUG;
|
||||
case ts6bot::LogLevel::Info: return Colors::INFO;
|
||||
case ts6bot::LogLevel::Warning: return Colors::WARNING;
|
||||
case ts6bot::LogLevel::Error: return Colors::ERROR;
|
||||
case ts6bot::LogLevel::Critical: return Colors::CRITICAL;
|
||||
default: return Colors::RESET;
|
||||
}
|
||||
}
|
||||
// Write to trace file (all logs) - no colors
|
||||
if (m_logFiles.at(ts6bot::LogLevel::Trace).is_open()) {
|
||||
m_logFiles.at(ts6bot::LogLevel::Trace) << fileLog;
|
||||
m_logFiles.at(ts6bot::LogLevel::Trace).flush();
|
||||
}
|
||||
|
||||
static std::string_view levelToString(const ts6bot::LogLevel level) {
|
||||
switch (level) {
|
||||
case ts6bot::LogLevel::Trace: return "TRACE";
|
||||
case ts6bot::LogLevel::Debug: return "DEBUG";
|
||||
case ts6bot::LogLevel::Info: return "INFO";
|
||||
case ts6bot::LogLevel::Warning: return "WARNING";
|
||||
case ts6bot::LogLevel::Error: return "ERROR";
|
||||
case ts6bot::LogLevel::Critical: return "CRITICAL";
|
||||
default: return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
// Write to specific level files - no colors
|
||||
if (entry.level == ts6bot::LogLevel::Error &&
|
||||
m_logFiles.at(ts6bot::LogLevel::Error).is_open()) {
|
||||
m_logFiles.at(ts6bot::LogLevel::Error) << fileLog;
|
||||
m_logFiles.at(ts6bot::LogLevel::Error).flush();
|
||||
} else if (entry.level == ts6bot::LogLevel::Warning &&
|
||||
m_logFiles.at(ts6bot::LogLevel::Warning).is_open()) {
|
||||
m_logFiles.at(ts6bot::LogLevel::Warning) << fileLog;
|
||||
m_logFiles.at(ts6bot::LogLevel::Warning).flush();
|
||||
} else if (entry.level == ts6bot::LogLevel::Critical &&
|
||||
m_logFiles.at(ts6bot::LogLevel::Critical).is_open()) {
|
||||
m_logFiles.at(ts6bot::LogLevel::Critical) << fileLog;
|
||||
m_logFiles.at(ts6bot::LogLevel::Critical).flush();
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
ts6bot::LogLevel m_minLevel;
|
||||
std::unordered_map<ts6bot::LogLevel, std::ofstream> m_logFiles;
|
||||
static const char *getColorForLevel(const ts6bot::LogLevel level)
|
||||
{
|
||||
switch (level) {
|
||||
case ts6bot::LogLevel::Trace:
|
||||
return Colors::TRACE;
|
||||
case ts6bot::LogLevel::Debug:
|
||||
return Colors::DEBUG;
|
||||
case ts6bot::LogLevel::Info:
|
||||
return Colors::INFO;
|
||||
case ts6bot::LogLevel::Warning:
|
||||
return Colors::WARNING;
|
||||
case ts6bot::LogLevel::Error:
|
||||
return Colors::ERROR;
|
||||
case ts6bot::LogLevel::Critical:
|
||||
return Colors::CRITICAL;
|
||||
default:
|
||||
return Colors::RESET;
|
||||
}
|
||||
}
|
||||
|
||||
// Concurrency
|
||||
std::deque<LogEntry> m_logQueue;
|
||||
std::mutex m_queueMutex;
|
||||
std::condition_variable m_cv;
|
||||
std::jthread m_workerThread;
|
||||
std::atomic<bool> m_exit;
|
||||
static std::string_view levelToString(const ts6bot::LogLevel level)
|
||||
{
|
||||
switch (level) {
|
||||
case ts6bot::LogLevel::Trace:
|
||||
return "TRACE";
|
||||
case ts6bot::LogLevel::Debug:
|
||||
return "DEBUG";
|
||||
case ts6bot::LogLevel::Info:
|
||||
return "INFO";
|
||||
case ts6bot::LogLevel::Warning:
|
||||
return "WARNING";
|
||||
case ts6bot::LogLevel::Error:
|
||||
return "ERROR";
|
||||
case ts6bot::LogLevel::Critical:
|
||||
return "CRITICAL";
|
||||
default:
|
||||
return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
ts6bot::LogLevel m_minLevel;
|
||||
std::unordered_map<ts6bot::LogLevel, std::ofstream> m_logFiles;
|
||||
|
||||
// Concurrency
|
||||
std::deque<LogEntry> m_logQueue;
|
||||
std::mutex m_queueMutex;
|
||||
std::condition_variable m_cv;
|
||||
std::jthread m_workerThread;
|
||||
std::atomic<bool> m_exit;
|
||||
};
|
||||
|
||||
#define LOG_IF_ALIVE(level, fmt, ...) \
|
||||
do { \
|
||||
if (Logger::isAlive()) { \
|
||||
Logger::getInstance()->log(level, std::source_location::current(), fmt __VA_OPT__(,) __VA_ARGS__); \
|
||||
} \
|
||||
} while (0)
|
||||
#define LOG_IF_ALIVE(level, fmt, ...) \
|
||||
do { \
|
||||
if (Logger::isAlive()) { \
|
||||
Logger::getInstance()->log(level, std::source_location::current(), \
|
||||
fmt __VA_OPT__(, ) __VA_ARGS__); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
// --- Public API Macros ---
|
||||
#define LOG_TRACE(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Trace, fmt __VA_OPT__(,) __VA_ARGS__)
|
||||
#define LOG_DEBUG(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Debug, fmt __VA_OPT__(,) __VA_ARGS__)
|
||||
#define LOG_INFO(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Info, fmt __VA_OPT__(,) __VA_ARGS__)
|
||||
#define LOG_WARN(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Warning, fmt __VA_OPT__(,) __VA_ARGS__)
|
||||
#define LOG_ERROR(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Error, fmt __VA_OPT__(,) __VA_ARGS__)
|
||||
#define LOG_CRITICAL(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Critical, fmt __VA_OPT__(,) __VA_ARGS__)
|
||||
#define LOG_TRACE(fmt, ...) \
|
||||
LOG_IF_ALIVE(ts6bot::LogLevel::Trace, fmt __VA_OPT__(, ) __VA_ARGS__)
|
||||
#define LOG_DEBUG(fmt, ...) \
|
||||
LOG_IF_ALIVE(ts6bot::LogLevel::Debug, fmt __VA_OPT__(, ) __VA_ARGS__)
|
||||
#define LOG_INFO(fmt, ...) \
|
||||
LOG_IF_ALIVE(ts6bot::LogLevel::Info, fmt __VA_OPT__(, ) __VA_ARGS__)
|
||||
#define LOG_WARN(fmt, ...) \
|
||||
LOG_IF_ALIVE(ts6bot::LogLevel::Warning, fmt __VA_OPT__(, ) __VA_ARGS__)
|
||||
#define LOG_ERROR(fmt, ...) \
|
||||
LOG_IF_ALIVE(ts6bot::LogLevel::Error, fmt __VA_OPT__(, ) __VA_ARGS__)
|
||||
#define LOG_CRITICAL(fmt, ...) \
|
||||
LOG_IF_ALIVE(ts6bot::LogLevel::Critical, fmt __VA_OPT__(, ) __VA_ARGS__)
|
||||
+625
-395
File diff suppressed because it is too large.
Load diff
@@ -1,79 +1,85 @@
|
||||
#pragma once
|
||||
#include <glaze/core/common.hpp>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <teamspeak/public_definitions.h>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#include <glaze/core/common.hpp>
|
||||
|
||||
namespace definitions {
|
||||
namespace definitions
|
||||
{
|
||||
|
||||
struct StreamInfo {
|
||||
std::string url;
|
||||
int itag = 0;
|
||||
std::string mimeType;
|
||||
int bitrate = 0;
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
};
|
||||
|
||||
struct StreamInfo {
|
||||
std::string url;
|
||||
int itag = 0;
|
||||
std::string mimeType;
|
||||
int bitrate = 0;
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
};
|
||||
struct Streams {
|
||||
StreamInfo audio;
|
||||
StreamInfo video;
|
||||
};
|
||||
|
||||
struct Streams {
|
||||
StreamInfo audio;
|
||||
StreamInfo video;
|
||||
};
|
||||
struct QueueItem {
|
||||
std::string name;
|
||||
std::string videoId;
|
||||
std::string shortUrl;
|
||||
std::string length;
|
||||
std::string requester;
|
||||
std::optional<Streams> streams;
|
||||
|
||||
struct QueueItem {
|
||||
std::string name;
|
||||
std::string videoId;
|
||||
std::string shortUrl;
|
||||
std::string length;
|
||||
std::string requester;
|
||||
std::optional<Streams> streams;
|
||||
QueueItem() = default;
|
||||
|
||||
QueueItem() = default;
|
||||
QueueItem(std::string name, std::string videoId,
|
||||
std::string shortUrl, std::string length,
|
||||
std::string requested_by,
|
||||
const std::optional<Streams> &streams)
|
||||
: name{std::move(name)}, videoId(std::move(videoId)),
|
||||
shortUrl(std::move(shortUrl)), length(std::move(length)),
|
||||
requester{std::move(requested_by)}, streams{streams}
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
QueueItem(std::string name, std::string videoId,std::string shortUrl,std::string length, std::string requested_by, const std::optional<Streams> & streams)
|
||||
: name{std::move(name)}, videoId(std::move(videoId)),shortUrl(std::move(shortUrl)), length(std::move(length)), requester{std::move(requested_by)}, streams{streams} {}
|
||||
};
|
||||
struct SearchResultItem {
|
||||
std::string name;
|
||||
std::string length;
|
||||
std::string thumbnail;
|
||||
std::string viewCount;
|
||||
std::string url;
|
||||
std::string shortUrl;
|
||||
std::string videoId;
|
||||
};
|
||||
|
||||
|
||||
|
||||
struct SearchResultItem {
|
||||
std::string name;
|
||||
std::string length;
|
||||
std::string thumbnail;
|
||||
std::string viewCount;
|
||||
std::string url;
|
||||
std::string shortUrl;
|
||||
std::string videoId;
|
||||
};
|
||||
|
||||
struct PluginState {
|
||||
std::vector<QueueItem> queue;
|
||||
std::vector<anyID> onlineSubscribers;
|
||||
std::vector<anyID> offlineSubscribers;
|
||||
std::uint64_t serverConnection;
|
||||
bool wasPlaying = false;
|
||||
};
|
||||
}
|
||||
struct PluginState {
|
||||
std::vector<QueueItem> queue;
|
||||
std::vector<anyID> onlineSubscribers;
|
||||
std::vector<anyID> offlineSubscribers;
|
||||
std::uint64_t serverConnection;
|
||||
bool wasPlaying = false;
|
||||
};
|
||||
} // namespace definitions
|
||||
|
||||
template <> struct glz::meta<definitions::StreamInfo> {
|
||||
using T = definitions::StreamInfo;
|
||||
static constexpr auto value =
|
||||
object("url", &T::url, "itag", &T::itag, "mimeType", &T::mimeType,
|
||||
"bitrate", &T::bitrate, "width", &T::width, "height", &T::height);
|
||||
using T = definitions::StreamInfo;
|
||||
static constexpr auto value = object(
|
||||
"url", &T::url, "itag", &T::itag, "mimeType", &T::mimeType,
|
||||
"bitrate", &T::bitrate, "width", &T::width, "height", &T::height);
|
||||
};
|
||||
|
||||
template <> struct glz::meta<definitions::Streams> {
|
||||
using T = definitions::Streams;
|
||||
static constexpr auto value =
|
||||
object("audio", &T::audio, "video", &T::video);
|
||||
using T = definitions::Streams;
|
||||
static constexpr auto value =
|
||||
object("audio", &T::audio, "video", &T::video);
|
||||
};
|
||||
|
||||
template <> struct glz::meta<definitions::QueueItem> {
|
||||
using T = definitions::QueueItem;
|
||||
static constexpr auto value =
|
||||
object("name", &T::name, "videoId", &T::videoId, "shortUrl", &T::shortUrl, "length", &T::length, "requester", &T::requester,
|
||||
"streams", &T::streams);
|
||||
};
|
||||
using T = definitions::QueueItem;
|
||||
static constexpr auto value =
|
||||
object("name", &T::name, "videoId", &T::videoId, "shortUrl",
|
||||
&T::shortUrl, "length", &T::length, "requester",
|
||||
&T::requester, "streams", &T::streams);
|
||||
};
|
||||
+76
-60
@@ -1,77 +1,93 @@
|
||||
#pragma once
|
||||
|
||||
#include <concepts>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <concepts>
|
||||
#include <utility>
|
||||
|
||||
/**
|
||||
* @brief C++26 Smart Singleton for DLL Hot-Reloading.
|
||||
* Uses shared_ptr to ensure memory safety across thread boundaries
|
||||
* Uses shared_ptr to ensure memory safety across thread boundaries
|
||||
* during forceful destruction and DLL unloads.
|
||||
*/
|
||||
template <typename T>
|
||||
class Singleton {
|
||||
private:
|
||||
// This "Token" trick allows std::shared_ptr to create the object
|
||||
// even if T's constructor is private/protected.
|
||||
struct ConstructorProxy : public T {
|
||||
template<typename... Args>
|
||||
ConstructorProxy(Args&&... args) : T(std::forward<Args>(args)...) {}
|
||||
};
|
||||
public:
|
||||
// Delete copy/move
|
||||
Singleton(const Singleton&) = delete;
|
||||
Singleton& operator=(const Singleton&) = delete;
|
||||
template <typename T> class Singleton
|
||||
{
|
||||
private:
|
||||
|
||||
template <typename... Args>
|
||||
static std::shared_ptr<T> init(Args&&... args) {
|
||||
auto ptr = m_instance.load(std::memory_order_acquire);
|
||||
if (ptr) return ptr;
|
||||
// This "Token" trick allows std::shared_ptr to create the object
|
||||
// even if T's constructor is private/protected.
|
||||
struct ConstructorProxy : public T {
|
||||
template <typename... Args>
|
||||
ConstructorProxy(Args &&...args)
|
||||
: T(std::forward<Args>(args)...)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
std::lock_guard lock(m_lifecycle_mutex);
|
||||
ptr = m_instance.load(std::memory_order_relaxed);
|
||||
if (!ptr) {
|
||||
// We wrap T in ConstructorProxy so 'new' works here,
|
||||
// but the resulting shared_ptr is still shared_ptr<T>.
|
||||
ptr = std::make_shared<ConstructorProxy>(std::forward<Args>(args)...);
|
||||
m_instance.store(ptr, std::memory_order_release);
|
||||
}
|
||||
return ptr;
|
||||
}
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief Access the existing instance.
|
||||
* @throws std::runtime_error if init() hasn't been called yet.
|
||||
*/
|
||||
static std::shared_ptr<T> getInstance() {
|
||||
auto ptr = m_instance.load(std::memory_order_acquire);
|
||||
if (!ptr) {
|
||||
throw std::runtime_error("Singleton accessed via get() before init()!");
|
||||
}
|
||||
return ptr;
|
||||
}
|
||||
// Delete copy/move
|
||||
Singleton(const Singleton &) = delete;
|
||||
Singleton &operator=(const Singleton &) = delete;
|
||||
|
||||
/**
|
||||
* @brief Safe destruction for DLL unloading.
|
||||
* Shared_ptr ensures that threads currently using the instance
|
||||
* don't crash; the memory is freed only when the last reference drops.
|
||||
*/
|
||||
static void destroyInstance() {
|
||||
std::lock_guard lock(m_lifecycle_mutex);
|
||||
m_instance.store(nullptr, std::memory_order_release);
|
||||
}
|
||||
template <typename... Args>
|
||||
static std::shared_ptr<T> init(Args &&...args)
|
||||
{
|
||||
auto ptr = m_instance.load(std::memory_order_acquire);
|
||||
if (ptr) {
|
||||
return ptr;
|
||||
}
|
||||
|
||||
static bool isAlive() {
|
||||
return m_instance.load(std::memory_order_acquire) != nullptr;
|
||||
}
|
||||
std::lock_guard lock(m_lifecycle_mutex);
|
||||
ptr = m_instance.load(std::memory_order_relaxed);
|
||||
if (!ptr) {
|
||||
// We wrap T in ConstructorProxy so 'new' works here,
|
||||
// but the resulting shared_ptr is still shared_ptr<T>.
|
||||
ptr = std::make_shared<ConstructorProxy>(
|
||||
std::forward<Args>(args)...);
|
||||
m_instance.store(ptr, std::memory_order_release);
|
||||
}
|
||||
return ptr;
|
||||
}
|
||||
|
||||
protected:
|
||||
Singleton() = default;
|
||||
virtual ~Singleton() = default;
|
||||
/**
|
||||
* @brief Access the existing instance.
|
||||
* @throws std::runtime_error if init() hasn't been called yet.
|
||||
*/
|
||||
static std::shared_ptr<T> getInstance()
|
||||
{
|
||||
auto ptr = m_instance.load(std::memory_order_acquire);
|
||||
if (!ptr) {
|
||||
throw std::runtime_error(
|
||||
"Singleton accessed via get() before init()!");
|
||||
}
|
||||
return ptr;
|
||||
}
|
||||
|
||||
private:
|
||||
// atomic<shared_ptr> is a C++20 feature, perfect for C++26
|
||||
static inline std::atomic<std::shared_ptr<T>> m_instance{nullptr};
|
||||
static inline std::mutex m_lifecycle_mutex;
|
||||
};
|
||||
/**
|
||||
* @brief Safe destruction for DLL unloading.
|
||||
* Shared_ptr ensures that threads currently using the instance
|
||||
* don't crash; the memory is freed only when the last reference drops.
|
||||
*/
|
||||
static void destroyInstance()
|
||||
{
|
||||
std::lock_guard lock(m_lifecycle_mutex);
|
||||
m_instance.store(nullptr, std::memory_order_release);
|
||||
}
|
||||
|
||||
static bool isAlive()
|
||||
{
|
||||
return m_instance.load(std::memory_order_acquire) != nullptr;
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
Singleton() = default;
|
||||
virtual ~Singleton() = default;
|
||||
|
||||
private:
|
||||
|
||||
// atomic<shared_ptr> is a C++20 feature, perfect for C++26
|
||||
static inline std::atomic<std::shared_ptr<T>> m_instance{nullptr};
|
||||
static inline std::mutex m_lifecycle_mutex;
|
||||
};
|
||||
@@ -1,30 +1,40 @@
|
||||
#include <vector>
|
||||
#include <functional>
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
class SingletonManager {
|
||||
public:
|
||||
// Priority: Higher numbers are destroyed LAST (e.g., Logger = 100)
|
||||
static void registerShutdown(const int priority, const std::function<void()> &shutdownFunc) {
|
||||
m_registry.push_back({priority, shutdownFunc});
|
||||
// Sort so that high priority stays at the end (destroyed last)
|
||||
std::ranges::sort(m_registry, [](const auto& a, const auto& b) {
|
||||
return a.priority < b.priority;
|
||||
});
|
||||
}
|
||||
class SingletonManager
|
||||
{
|
||||
public:
|
||||
|
||||
static void shutdownAll() {
|
||||
// Destroy in reverse priority (highest priority first? No, usually reverse order of arrival)
|
||||
// Here we destroy from lowest priority to highest.
|
||||
for (auto& [priority, func] : m_registry) {
|
||||
std::cerr << priority << ": " << &func << std::endl;
|
||||
func();
|
||||
}
|
||||
m_registry.clear();
|
||||
}
|
||||
// Priority: Higher numbers are destroyed LAST (e.g., Logger = 100)
|
||||
static void registerShutdown(const int priority,
|
||||
const std::function<void()>& shutdownFunc)
|
||||
{
|
||||
m_registry.push_back({priority, shutdownFunc});
|
||||
// Sort so that high priority stays at the end (destroyed last)
|
||||
std::ranges::sort(m_registry, [](const auto& a, const auto& b) {
|
||||
return a.priority < b.priority;
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
struct Entry { int priority; std::function<void()> func; };
|
||||
static inline std::vector<Entry> m_registry;
|
||||
static void shutdownAll()
|
||||
{
|
||||
// Destroy in reverse priority (highest priority first? No, usually
|
||||
// reverse order of arrival) Here we destroy from lowest priority to
|
||||
// highest.
|
||||
for (auto& [priority, func] : m_registry) {
|
||||
std::cerr << priority << ": " << &func << std::endl;
|
||||
func();
|
||||
}
|
||||
m_registry.clear();
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
struct Entry {
|
||||
int priority;
|
||||
std::function<void()> func;
|
||||
};
|
||||
static inline std::vector<Entry> m_registry;
|
||||
};
|
||||
+262
-223
@@ -14,319 +14,358 @@
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace Spotify {
|
||||
namespace Spotify
|
||||
{
|
||||
|
||||
// ============================================================================
|
||||
// Error Handling
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Error Handling
|
||||
// ============================================================================
|
||||
|
||||
struct ApiError {
|
||||
int status;
|
||||
std::string message;
|
||||
std::string reason;
|
||||
struct ApiError {
|
||||
int status;
|
||||
std::string message;
|
||||
std::string reason;
|
||||
|
||||
auto GetStatus() const -> int { return status; }
|
||||
auto GetMessage() const -> const std::string & { return message; }
|
||||
};
|
||||
auto GetStatus() const -> int { return status; }
|
||||
auto GetMessage() const -> const std::string & { return message; }
|
||||
};
|
||||
|
||||
template <typename T> using Result = std::expected<T, ApiError>;
|
||||
template <typename T> using Result = std::expected<T, ApiError>;
|
||||
|
||||
// ============================================================================
|
||||
// HTTP Client Implementation Details
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// HTTP Client Implementation Details
|
||||
// ============================================================================
|
||||
|
||||
struct CurlDeleter {
|
||||
void operator()(CURL *ptr) const {
|
||||
if (ptr)
|
||||
curl_easy_cleanup(ptr);
|
||||
}
|
||||
};
|
||||
struct CurlDeleter {
|
||||
void operator()(CURL *ptr) const
|
||||
{
|
||||
if (ptr) {
|
||||
curl_easy_cleanup(ptr);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
enum class HttpMethod { GET, POST, PUT, DELETE };
|
||||
enum class HttpMethod { GET, POST, PUT, DELETE };
|
||||
|
||||
// ============================================================================
|
||||
// Main Spotify Client
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Main Spotify Client
|
||||
// ============================================================================
|
||||
|
||||
class Client {
|
||||
public:
|
||||
Client(std::string accessToken);
|
||||
~Client() = default;
|
||||
class Client
|
||||
{
|
||||
public:
|
||||
|
||||
// Configuration
|
||||
void SetVerbose(bool verbose) { m_Verbose = verbose; }
|
||||
void SetProxy(ProxyConfig config) { m_Proxy = std::move(config); }
|
||||
void SetAccessToken(std::string token) { m_AccessToken = std::move(token); }
|
||||
Client(std::string accessToken);
|
||||
~Client() = default;
|
||||
|
||||
// ========================================================================
|
||||
// Albums API
|
||||
// ========================================================================
|
||||
// Configuration
|
||||
void SetVerbose(bool verbose) { m_Verbose = verbose; }
|
||||
void SetProxy(ProxyConfig config) { m_Proxy = std::move(config); }
|
||||
void SetAccessToken(std::string token)
|
||||
{
|
||||
m_AccessToken = std::move(token);
|
||||
}
|
||||
|
||||
auto GetAlbum(const std::string &id, std::optional<std::string> market = {})
|
||||
-> Result<Album>;
|
||||
// ========================================================================
|
||||
// Albums API
|
||||
// ========================================================================
|
||||
|
||||
auto GetAlbums(const std::vector<std::string> &ids,
|
||||
std::optional<std::string> market = {})
|
||||
-> Result<std::vector<Album>>;
|
||||
auto GetAlbum(const std::string &id,
|
||||
std::optional<std::string> market = {})
|
||||
-> Result<Album>;
|
||||
|
||||
auto GetAlbumTracks(const std::string &id,
|
||||
const Request::AlbumTracksParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedTrack>>;
|
||||
auto GetAlbums(const std::vector<std::string> &ids,
|
||||
std::optional<std::string> market = {})
|
||||
-> Result<std::vector<Album>>;
|
||||
|
||||
auto GetSavedAlbums(const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SavedAlbum>>;
|
||||
auto GetAlbumTracks(const std::string &id,
|
||||
const Request::AlbumTracksParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedTrack>>;
|
||||
|
||||
auto SaveAlbums(const std::vector<std::string> &ids) -> Result<void>;
|
||||
auto GetSavedAlbums(const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SavedAlbum>>;
|
||||
|
||||
auto RemoveSavedAlbums(const std::vector<std::string> &ids) -> Result<void>;
|
||||
auto SaveAlbums(const std::vector<std::string> &ids)
|
||||
-> Result<void>;
|
||||
|
||||
auto CheckSavedAlbums(const std::vector<std::string> &ids)
|
||||
-> Result<std::vector<bool>>;
|
||||
auto RemoveSavedAlbums(const std::vector<std::string> &ids)
|
||||
-> Result<void>;
|
||||
|
||||
auto GetNewReleases(const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedAlbum>>;
|
||||
auto CheckSavedAlbums(const std::vector<std::string> &ids)
|
||||
-> Result<std::vector<bool>>;
|
||||
|
||||
// ========================================================================
|
||||
// Artists API
|
||||
// ========================================================================
|
||||
auto GetNewReleases(const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedAlbum>>;
|
||||
|
||||
auto GetArtist(const std::string &id) -> Result<Artist>;
|
||||
// ========================================================================
|
||||
// Artists API
|
||||
// ========================================================================
|
||||
|
||||
auto GetArtists(const std::vector<std::string> &ids)
|
||||
-> Result<std::vector<Artist>>;
|
||||
auto GetArtist(const std::string &id) -> Result<Artist>;
|
||||
|
||||
auto GetArtistAlbums(const std::string &id,
|
||||
const Request::ArtistAlbumsParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedAlbum>>;
|
||||
auto GetArtists(const std::vector<std::string> &ids)
|
||||
-> Result<std::vector<Artist>>;
|
||||
|
||||
auto GetArtistTopTracks(const std::string &id, const std::string &market)
|
||||
-> Result<std::vector<Track>>;
|
||||
auto GetArtistAlbums(const std::string &id,
|
||||
const Request::ArtistAlbumsParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedAlbum>>;
|
||||
|
||||
auto GetArtistRelatedArtists(const std::string &id)
|
||||
-> Result<std::vector<Artist>>;
|
||||
auto GetArtistTopTracks(const std::string &id,
|
||||
const std::string &market)
|
||||
-> Result<std::vector<Track>>;
|
||||
|
||||
// ========================================================================
|
||||
// Tracks API
|
||||
// ========================================================================
|
||||
auto GetArtistRelatedArtists(const std::string &id)
|
||||
-> Result<std::vector<Artist>>;
|
||||
|
||||
auto GetTrack(const std::string &id, std::optional<std::string> market = {})
|
||||
-> Result<Track>;
|
||||
// ========================================================================
|
||||
// Tracks API
|
||||
// ========================================================================
|
||||
|
||||
auto GetTracks(const std::vector<std::string> &ids,
|
||||
std::optional<std::string> market = {})
|
||||
-> Result<std::vector<Track>>;
|
||||
auto GetTrack(const std::string &id,
|
||||
std::optional<std::string> market = {})
|
||||
-> Result<Track>;
|
||||
|
||||
auto GetSavedTracks(const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SavedTrack>>;
|
||||
auto GetTracks(const std::vector<std::string> &ids,
|
||||
std::optional<std::string> market = {})
|
||||
-> Result<std::vector<Track>>;
|
||||
|
||||
auto SaveTracks(const std::vector<std::string> &ids) -> Result<void>;
|
||||
auto GetSavedTracks(const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SavedTrack>>;
|
||||
|
||||
auto RemoveSavedTracks(const std::vector<std::string> &ids) -> Result<void>;
|
||||
auto SaveTracks(const std::vector<std::string> &ids)
|
||||
-> Result<void>;
|
||||
|
||||
auto CheckSavedTracks(const std::vector<std::string> &ids)
|
||||
-> Result<std::vector<bool>>;
|
||||
auto RemoveSavedTracks(const std::vector<std::string> &ids)
|
||||
-> Result<void>;
|
||||
|
||||
auto GetAudioFeatures(const std::string &id) -> Result<AudioFeatures>;
|
||||
auto CheckSavedTracks(const std::vector<std::string> &ids)
|
||||
-> Result<std::vector<bool>>;
|
||||
|
||||
auto GetAudioFeaturesForTracks(const std::vector<std::string> &ids)
|
||||
-> Result<std::vector<AudioFeatures>>;
|
||||
auto GetAudioFeatures(const std::string &id)
|
||||
-> Result<AudioFeatures>;
|
||||
|
||||
auto GetAudioAnalysis(const std::string &id) -> Result<AudioAnalysis>;
|
||||
auto GetAudioFeaturesForTracks(const std::vector<std::string> &ids)
|
||||
-> Result<std::vector<AudioFeatures>>;
|
||||
|
||||
auto GetRecommendations(const Request::RecommendationParams ¶ms)
|
||||
-> Result<Recommendations>;
|
||||
auto GetAudioAnalysis(const std::string &id)
|
||||
-> Result<AudioAnalysis>;
|
||||
|
||||
// ========================================================================
|
||||
// Search API
|
||||
// ========================================================================
|
||||
auto GetRecommendations(const Request::RecommendationParams ¶ms)
|
||||
-> Result<Recommendations>;
|
||||
|
||||
auto Search(const Request::SearchParams ¶ms) -> Result<SearchResults>;
|
||||
// ========================================================================
|
||||
// Search API
|
||||
// ========================================================================
|
||||
|
||||
auto SearchTracks(const Request::TrackSearchFilters &filters,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<Track>>;
|
||||
auto Search(const Request::SearchParams ¶ms)
|
||||
-> Result<SearchResults>;
|
||||
|
||||
auto SearchAlbums(const Request::AlbumSearchFilters &filters,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedAlbum>>;
|
||||
auto SearchTracks(const Request::TrackSearchFilters &filters,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<Track>>;
|
||||
|
||||
auto SearchArtists(const Request::ArtistSearchFilters &filters,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<Artist>>;
|
||||
auto SearchAlbums(const Request::AlbumSearchFilters &filters,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedAlbum>>;
|
||||
|
||||
// ========================================================================
|
||||
// Playlists API
|
||||
// ========================================================================
|
||||
auto SearchArtists(const Request::ArtistSearchFilters &filters,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<Artist>>;
|
||||
|
||||
auto GetPlaylist(const std::string &id,
|
||||
std::optional<std::string> market = {}) -> Result<Playlist>;
|
||||
// ========================================================================
|
||||
// Playlists API
|
||||
// ========================================================================
|
||||
|
||||
auto GetPlaylistTracks(const std::string &id,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<PlaylistTrack>>;
|
||||
auto GetPlaylist(const std::string &id,
|
||||
std::optional<std::string> market = {})
|
||||
-> Result<Playlist>;
|
||||
|
||||
auto CreatePlaylist(const std::string &user_id,
|
||||
const Request::CreatePlaylistParams ¶ms)
|
||||
-> Result<Playlist>;
|
||||
auto GetPlaylistTracks(const std::string &id,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<PlaylistTrack>>;
|
||||
|
||||
auto UpdatePlaylist(const std::string &id,
|
||||
const Request::UpdatePlaylistParams ¶ms)
|
||||
-> Result<void>;
|
||||
auto CreatePlaylist(const std::string &user_id,
|
||||
const Request::CreatePlaylistParams ¶ms)
|
||||
-> Result<Playlist>;
|
||||
|
||||
auto AddTracksToPlaylist(const std::string &id,
|
||||
const Request::AddTracksToPlaylistParams ¶ms)
|
||||
-> Result<std::string>;
|
||||
auto UpdatePlaylist(const std::string &id,
|
||||
const Request::UpdatePlaylistParams ¶ms)
|
||||
-> Result<void>;
|
||||
|
||||
auto RemoveTracksFromPlaylist(
|
||||
const std::string &id,
|
||||
const Request::RemoveTracksFromPlaylistParams ¶ms)
|
||||
-> Result<std::string>;
|
||||
auto AddTracksToPlaylist(
|
||||
const std::string &id,
|
||||
const Request::AddTracksToPlaylistParams ¶ms)
|
||||
-> Result<std::string>;
|
||||
|
||||
auto ReorderPlaylistTracks(const std::string &id,
|
||||
const Request::ReorderPlaylistParams ¶ms)
|
||||
-> Result<std::string>;
|
||||
auto RemoveTracksFromPlaylist(
|
||||
const std::string &id,
|
||||
const Request::RemoveTracksFromPlaylistParams ¶ms)
|
||||
-> Result<std::string>;
|
||||
|
||||
auto ReplacePlaylistTracks(const std::string &id,
|
||||
const Request::ReplacePlaylistTracksParams ¶ms)
|
||||
-> Result<void>;
|
||||
auto ReorderPlaylistTracks(
|
||||
const std::string &id,
|
||||
const Request::ReorderPlaylistParams ¶ms)
|
||||
-> Result<std::string>;
|
||||
|
||||
auto GetCurrentUserPlaylists(const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedPlaylist>>;
|
||||
auto ReplacePlaylistTracks(
|
||||
const std::string &id,
|
||||
const Request::ReplacePlaylistTracksParams ¶ms)
|
||||
-> Result<void>;
|
||||
|
||||
auto GetUserPlaylists(const std::string &user_id,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedPlaylist>>;
|
||||
auto GetCurrentUserPlaylists(
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedPlaylist>>;
|
||||
|
||||
auto GetFeaturedPlaylists(const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedPlaylist>>;
|
||||
auto GetUserPlaylists(const std::string &user_id,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedPlaylist>>;
|
||||
|
||||
auto GetCategoryPlaylists(const std::string &category_id,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedPlaylist>>;
|
||||
auto GetFeaturedPlaylists(
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedPlaylist>>;
|
||||
|
||||
// ========================================================================
|
||||
// User API
|
||||
// ========================================================================
|
||||
auto GetCategoryPlaylists(
|
||||
const std::string &category_id,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedPlaylist>>;
|
||||
|
||||
auto GetCurrentUser() -> Result<User>;
|
||||
// ========================================================================
|
||||
// User API
|
||||
// ========================================================================
|
||||
|
||||
auto GetUser(const std::string &user_id) -> Result<User>;
|
||||
auto GetCurrentUser() -> Result<User>;
|
||||
|
||||
auto GetTopArtists(const Request::TopItemsParams ¶ms = {})
|
||||
-> Result<PagingObject<Artist>>;
|
||||
auto GetUser(const std::string &user_id) -> Result<User>;
|
||||
|
||||
auto GetTopTracks(const Request::TopItemsParams ¶ms = {})
|
||||
-> Result<PagingObject<Track>>;
|
||||
auto GetTopArtists(const Request::TopItemsParams ¶ms = {})
|
||||
-> Result<PagingObject<Artist>>;
|
||||
|
||||
// ========================================================================
|
||||
// Follow API
|
||||
// ========================================================================
|
||||
auto GetTopTracks(const Request::TopItemsParams ¶ms = {})
|
||||
-> Result<PagingObject<Track>>;
|
||||
|
||||
auto FollowArtistsOrUsers(const Request::FollowParams ¶ms)
|
||||
-> Result<void>;
|
||||
// ========================================================================
|
||||
// Follow API
|
||||
// ========================================================================
|
||||
|
||||
auto UnfollowArtistsOrUsers(const Request::UnfollowParams ¶ms)
|
||||
-> Result<void>;
|
||||
auto FollowArtistsOrUsers(const Request::FollowParams ¶ms)
|
||||
-> Result<void>;
|
||||
|
||||
auto CheckFollowingArtistsOrUsers(const Request::CheckFollowingParams ¶ms)
|
||||
-> Result<std::vector<bool>>;
|
||||
auto UnfollowArtistsOrUsers(const Request::UnfollowParams ¶ms)
|
||||
-> Result<void>;
|
||||
|
||||
auto GetFollowedArtists(std::optional<int> limit = {},
|
||||
std::optional<std::string> after = {})
|
||||
-> Result<CursorPagingObject<Artist>>;
|
||||
auto CheckFollowingArtistsOrUsers(
|
||||
const Request::CheckFollowingParams ¶ms)
|
||||
-> Result<std::vector<bool>>;
|
||||
|
||||
auto FollowPlaylist(const std::string &playlist_id,
|
||||
const Request::FollowPlaylistParams ¶ms = {})
|
||||
-> Result<void>;
|
||||
auto GetFollowedArtists(std::optional<int> limit = {},
|
||||
std::optional<std::string> after = {})
|
||||
-> Result<CursorPagingObject<Artist>>;
|
||||
|
||||
auto UnfollowPlaylist(const std::string &playlist_id) -> Result<void>;
|
||||
auto
|
||||
FollowPlaylist(const std::string &playlist_id,
|
||||
const Request::FollowPlaylistParams ¶ms = {})
|
||||
-> Result<void>;
|
||||
|
||||
auto CheckFollowingPlaylist(const std::string &playlist_id,
|
||||
const std::vector<std::string> &user_ids)
|
||||
-> Result<std::vector<bool>>;
|
||||
auto UnfollowPlaylist(const std::string &playlist_id)
|
||||
-> Result<void>;
|
||||
|
||||
// ========================================================================
|
||||
// Player API
|
||||
// ========================================================================
|
||||
auto
|
||||
CheckFollowingPlaylist(const std::string &playlist_id,
|
||||
const std::vector<std::string> &user_ids)
|
||||
-> Result<std::vector<bool>>;
|
||||
|
||||
auto GetPlaybackState(std::optional<std::string> market = {})
|
||||
-> Result<PlaybackState>;
|
||||
// ========================================================================
|
||||
// Player API
|
||||
// ========================================================================
|
||||
|
||||
auto GetAvailableDevices() -> Result<std::vector<Device>>;
|
||||
auto GetPlaybackState(std::optional<std::string> market = {})
|
||||
-> Result<PlaybackState>;
|
||||
|
||||
auto GetCurrentlyPlayingTrack(std::optional<std::string> market = {})
|
||||
-> Result<PlaybackState>;
|
||||
auto GetAvailableDevices() -> Result<std::vector<Device>>;
|
||||
|
||||
auto StartOrResumePlayback(const Request::PlayParams ¶ms,
|
||||
std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
auto
|
||||
GetCurrentlyPlayingTrack(std::optional<std::string> market = {})
|
||||
-> Result<PlaybackState>;
|
||||
|
||||
auto PausePlayback(std::optional<std::string> device_id = {}) -> Result<void>;
|
||||
auto
|
||||
StartOrResumePlayback(const Request::PlayParams ¶ms,
|
||||
std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
|
||||
auto SkipToNext(std::optional<std::string> device_id = {}) -> Result<void>;
|
||||
auto PausePlayback(std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
|
||||
auto SkipToPrevious(std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
auto SkipToNext(std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
|
||||
auto SeekToPosition(int position_ms,
|
||||
std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
auto SkipToPrevious(std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
|
||||
auto SetRepeatMode(RepeatMode mode, std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
auto SeekToPosition(int position_ms,
|
||||
std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
|
||||
auto SetPlaybackVolume(int volume_percent,
|
||||
std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
auto SetRepeatMode(RepeatMode mode,
|
||||
std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
|
||||
auto TogglePlaybackShuffle(bool state,
|
||||
std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
auto SetPlaybackVolume(int volume_percent,
|
||||
std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
|
||||
auto TransferPlayback(const Request::TransferPlaybackParams ¶ms)
|
||||
-> Result<void>;
|
||||
auto
|
||||
TogglePlaybackShuffle(bool state,
|
||||
std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
|
||||
auto AddToQueue(const Request::QueueParams ¶ms) -> Result<void>;
|
||||
auto TransferPlayback(const Request::TransferPlaybackParams ¶ms)
|
||||
-> Result<void>;
|
||||
|
||||
auto GetRecentlyPlayedTracks(std::optional<int> limit = {},
|
||||
std::optional<int64_t> after = {},
|
||||
std::optional<int64_t> before = {})
|
||||
-> Result<CursorPagingObject<PlaylistTrack>>;
|
||||
auto AddToQueue(const Request::QueueParams ¶ms) -> Result<void>;
|
||||
|
||||
// ========================================================================
|
||||
// Browse API
|
||||
// ========================================================================
|
||||
auto GetRecentlyPlayedTracks(std::optional<int> limit = {},
|
||||
std::optional<int64_t> after = {},
|
||||
std::optional<int64_t> before = {})
|
||||
-> Result<CursorPagingObject<PlaylistTrack>>;
|
||||
|
||||
auto GetCategories(const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<Category>>;
|
||||
// ========================================================================
|
||||
// Browse API
|
||||
// ========================================================================
|
||||
|
||||
auto GetCategory(const std::string &category_id,
|
||||
std::optional<std::string> locale = {}) -> Result<Category>;
|
||||
auto GetCategories(const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<Category>>;
|
||||
|
||||
auto GetAvailableGenreSeeds() -> Result<std::vector<std::string>>;
|
||||
auto GetCategory(const std::string &category_id,
|
||||
std::optional<std::string> locale = {})
|
||||
-> Result<Category>;
|
||||
|
||||
auto GetAvailableMarkets() -> Result<std::vector<std::string>>;
|
||||
auto GetAvailableGenreSeeds() -> Result<std::vector<std::string>>;
|
||||
|
||||
private:
|
||||
std::string m_AccessToken;
|
||||
ProxyConfig m_Proxy;
|
||||
bool m_Verbose = false;
|
||||
auto GetAvailableMarkets() -> Result<std::vector<std::string>>;
|
||||
|
||||
auto PerformRequest(const std::string &url,
|
||||
HttpMethod method = HttpMethod::GET,
|
||||
const std::string &body = "",
|
||||
const std::vector<std::string> &extra_headers = {})
|
||||
-> Result<std::string>;
|
||||
private:
|
||||
|
||||
static auto WriteCallback(void *contents, size_t size, size_t nmemb,
|
||||
std::string *out) -> size_t;
|
||||
std::string m_AccessToken;
|
||||
ProxyConfig m_Proxy;
|
||||
bool m_Verbose = false;
|
||||
|
||||
auto BuildUrl(const std::string &endpoint,
|
||||
const std::map<std::string, std::string> ¶ms = {}) const
|
||||
-> std::string;
|
||||
auto BuildUrl(const std::string &endpoint,
|
||||
const Request::RequestParams ¶ms) const -> std::string;
|
||||
auto UrlEncode(const std::string &value) const -> std::string;
|
||||
};
|
||||
auto PerformRequest(
|
||||
const std::string &url,
|
||||
HttpMethod method = HttpMethod::GET,
|
||||
const std::string &body = "",
|
||||
const std::vector<std::string> &extra_headers = {})
|
||||
-> Result<std::string>;
|
||||
|
||||
static auto WriteCallback(void *contents, size_t size, size_t nmemb,
|
||||
std::string *out) -> size_t;
|
||||
|
||||
auto BuildUrl(const std::string &endpoint,
|
||||
const std::map<std::string, std::string> ¶ms = {})
|
||||
const -> std::string;
|
||||
auto BuildUrl(const std::string &endpoint,
|
||||
const Request::RequestParams ¶ms) const
|
||||
-> std::string;
|
||||
auto UrlEncode(const std::string &value) const -> std::string;
|
||||
};
|
||||
|
||||
} // namespace Spotify
|
||||
@@ -4,25 +4,32 @@
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace Spotify {
|
||||
namespace Spotify
|
||||
{
|
||||
|
||||
struct CallbackResult {
|
||||
std::string code;
|
||||
std::string state;
|
||||
std::string error;
|
||||
};
|
||||
struct CallbackResult {
|
||||
std::string code;
|
||||
std::string state;
|
||||
std::string error;
|
||||
};
|
||||
|
||||
class HttpCallbackServer {
|
||||
public:
|
||||
HttpCallbackServer(std::string host, uint16_t port, std::string path);
|
||||
class HttpCallbackServer
|
||||
{
|
||||
public:
|
||||
|
||||
// Wait for one callback request or timeout. Returns std::nullopt on timeout.
|
||||
std::optional<CallbackResult> WaitForCallback(std::chrono::milliseconds timeout);
|
||||
HttpCallbackServer(std::string host, uint16_t port,
|
||||
std::string path);
|
||||
|
||||
private:
|
||||
std::string m_Host;
|
||||
uint16_t m_Port;
|
||||
std::string m_Path;
|
||||
};
|
||||
// Wait for one callback request or timeout. Returns std::nullopt on
|
||||
// timeout.
|
||||
std::optional<CallbackResult>
|
||||
WaitForCallback(std::chrono::milliseconds timeout);
|
||||
|
||||
} // namespace ts6bot
|
||||
private:
|
||||
|
||||
std::string m_Host;
|
||||
uint16_t m_Port;
|
||||
std::string m_Path;
|
||||
};
|
||||
|
||||
} // namespace Spotify
|
||||
@@ -11,47 +11,57 @@
|
||||
|
||||
#include <Spotify/Client.hpp> // for ProxyConfig + CurlDeleter + ProxyType
|
||||
|
||||
namespace Spotify {
|
||||
namespace Spotify
|
||||
{
|
||||
|
||||
struct TokenSet {
|
||||
std::string access_token;
|
||||
std::string token_type;
|
||||
std::string scope;
|
||||
std::string refresh_token;
|
||||
std::int64_t expires_at_utc{}; // unix seconds
|
||||
struct TokenSet {
|
||||
std::string access_token;
|
||||
std::string token_type;
|
||||
std::string scope;
|
||||
std::string refresh_token;
|
||||
std::int64_t expires_at_utc{}; // unix seconds
|
||||
|
||||
bool IsExpired(std::chrono::seconds skew = std::chrono::seconds{60}) const;
|
||||
};
|
||||
bool IsExpired(std::chrono::seconds skew = std::chrono::seconds{
|
||||
60}) const;
|
||||
};
|
||||
|
||||
class PkceAuth {
|
||||
public:
|
||||
PkceAuth(std::string clientId, std::string redirectUri, std::filesystem::path tokenCachePath);
|
||||
class PkceAuth
|
||||
{
|
||||
public:
|
||||
|
||||
void SetProxy(ProxyConfig p) { m_Proxy = std::move(p); }
|
||||
void SetVerbose(bool v) { m_Verbose = v; }
|
||||
PkceAuth(std::string clientId,
|
||||
std::string redirectUri,
|
||||
std::filesystem::path tokenCachePath);
|
||||
|
||||
// One-time interactive step: prints URL and waits for redirect; stores refresh token.
|
||||
void AuthorizeAndStore(const std::vector<std::string>& scopes,
|
||||
std::chrono::milliseconds timeout = std::chrono::minutes(5));
|
||||
void SetProxy(ProxyConfig p) { m_Proxy = std::move(p); }
|
||||
void SetVerbose(bool v) { m_Verbose = v; }
|
||||
|
||||
// Headless: load from cache and refresh if needed.
|
||||
TokenSet LoadOrRefresh();
|
||||
// One-time interactive step: prints URL and waits for redirect;
|
||||
// stores refresh token.
|
||||
void AuthorizeAndStore(
|
||||
const std::vector<std::string>& scopes,
|
||||
std::chrono::milliseconds timeout = std::chrono::minutes(5));
|
||||
|
||||
private:
|
||||
std::string m_ClientId;
|
||||
std::string m_RedirectUri;
|
||||
std::filesystem::path m_TokenCachePath;
|
||||
ProxyConfig m_Proxy;
|
||||
bool m_Verbose = false;
|
||||
// Headless: load from cache and refresh if needed.
|
||||
TokenSet LoadOrRefresh();
|
||||
|
||||
TokenSet ExchangeCodeForToken(const std::string& code, const std::string& codeVerifier);
|
||||
TokenSet RefreshAccessToken(const TokenSet& current);
|
||||
private:
|
||||
|
||||
void Save(const TokenSet& t) const;
|
||||
std::optional<TokenSet> Load() const;
|
||||
std::string m_ClientId;
|
||||
std::string m_RedirectUri;
|
||||
std::filesystem::path m_TokenCachePath;
|
||||
ProxyConfig m_Proxy;
|
||||
bool m_Verbose = false;
|
||||
|
||||
static std::int64_t NowUnixSeconds();
|
||||
friend TokenSet;
|
||||
};
|
||||
TokenSet ExchangeCodeForToken(const std::string& code,
|
||||
const std::string& codeVerifier);
|
||||
TokenSet RefreshAccessToken(const TokenSet& current);
|
||||
|
||||
} // namespace ts6bot
|
||||
void Save(const TokenSet& t) const;
|
||||
std::optional<TokenSet> Load() const;
|
||||
|
||||
static std::int64_t NowUnixSeconds();
|
||||
friend TokenSet;
|
||||
};
|
||||
|
||||
} // namespace Spotify
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,178 +1,169 @@
|
||||
#pragma once
|
||||
#include "Spotify/Types/Common.hpp"
|
||||
#include "Spotify/Types/Artist.hpp"
|
||||
#include "Spotify/Types/Common.hpp"
|
||||
|
||||
namespace Spotify {
|
||||
namespace Spotify
|
||||
{
|
||||
|
||||
// ============================================================================
|
||||
// Album Group Enum
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Album Group Enum
|
||||
// ============================================================================
|
||||
|
||||
enum class AlbumGroup {
|
||||
Album,
|
||||
Single,
|
||||
AppearsOn,
|
||||
Compilation
|
||||
};
|
||||
enum class AlbumGroup { Album, Single, AppearsOn, Compilation };
|
||||
|
||||
inline auto AlbumGroupToString(AlbumGroup group) -> std::string {
|
||||
switch (group) {
|
||||
case AlbumGroup::Album: return "album";
|
||||
case AlbumGroup::Single: return "single";
|
||||
case AlbumGroup::AppearsOn: return "appears_on";
|
||||
case AlbumGroup::Compilation: return "compilation";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
inline auto AlbumGroupToString(AlbumGroup group) -> std::string
|
||||
{
|
||||
switch (group) {
|
||||
case AlbumGroup::Album:
|
||||
return "album";
|
||||
case AlbumGroup::Single:
|
||||
return "single";
|
||||
case AlbumGroup::AppearsOn:
|
||||
return "appears_on";
|
||||
case AlbumGroup::Compilation:
|
||||
return "compilation";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Album Base
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Album Base
|
||||
// ============================================================================
|
||||
|
||||
class AlbumBase {
|
||||
public:
|
||||
std::string album_type;
|
||||
int total_tracks;
|
||||
std::vector<std::string> available_markets;
|
||||
ExternalUrls external_urls;
|
||||
std::string href;
|
||||
std::string id;
|
||||
std::vector<Image> images;
|
||||
std::string name;
|
||||
std::string release_date;
|
||||
std::string release_date_precision;
|
||||
std::optional<Restrictions> restrictions;
|
||||
std::string type;
|
||||
std::string uri;
|
||||
std::vector<SimplifiedArtist> artists;
|
||||
bool is_playable;
|
||||
|
||||
virtual ~AlbumBase() = default;
|
||||
|
||||
auto GetId() const -> const std::string& { return id; }
|
||||
auto GetName() const -> const std::string& { return name; }
|
||||
auto GetUri() const -> const std::string& { return uri; }
|
||||
auto GetReleaseDate() const -> const std::string& { return release_date; }
|
||||
auto GetTotalTracks() const -> int { return total_tracks; }
|
||||
|
||||
auto GetAlbumType() const -> AlbumType {
|
||||
if (album_type == "album") return AlbumType::Album;
|
||||
if (album_type == "single") return AlbumType::Single;
|
||||
return AlbumType::Compilation;
|
||||
}
|
||||
|
||||
auto GetReleaseDatePrecision() const -> ReleaseDatePrecision {
|
||||
if (release_date_precision == "year") return ReleaseDatePrecision::Year;
|
||||
if (release_date_precision == "month") return ReleaseDatePrecision::Month;
|
||||
return ReleaseDatePrecision::Day;
|
||||
}
|
||||
};
|
||||
class AlbumBase
|
||||
{
|
||||
public:
|
||||
|
||||
// ============================================================================
|
||||
// Simplified Album
|
||||
// ============================================================================
|
||||
std::string album_type;
|
||||
int total_tracks;
|
||||
std::vector<std::string> available_markets;
|
||||
ExternalUrls external_urls;
|
||||
std::string href;
|
||||
std::string id;
|
||||
std::vector<Image> images;
|
||||
std::string name;
|
||||
std::string release_date;
|
||||
std::string release_date_precision;
|
||||
std::optional<Restrictions> restrictions;
|
||||
std::string type;
|
||||
std::string uri;
|
||||
std::vector<SimplifiedArtist> artists;
|
||||
bool is_playable;
|
||||
|
||||
struct SimplifiedAlbum : AlbumBase {
|
||||
};
|
||||
virtual ~AlbumBase() = default;
|
||||
|
||||
// ============================================================================
|
||||
// Full Album
|
||||
// ============================================================================
|
||||
auto GetId() const -> const std::string & { return id; }
|
||||
auto GetName() const -> const std::string & { return name; }
|
||||
auto GetUri() const -> const std::string & { return uri; }
|
||||
auto GetReleaseDate() const -> const std::string &
|
||||
{
|
||||
return release_date;
|
||||
}
|
||||
auto GetTotalTracks() const -> int { return total_tracks; }
|
||||
|
||||
struct Album : AlbumBase {
|
||||
std::vector<Copyright> copyrights;
|
||||
ExternalIds external_ids;
|
||||
std::vector<std::string> genres;
|
||||
std::string label;
|
||||
int popularity;
|
||||
|
||||
auto GetPopularity() const -> int { return popularity; }
|
||||
auto GetLabel() const -> const std::string& { return label; }
|
||||
auto GetGenres() const -> const std::vector<std::string>& { return genres; }
|
||||
};
|
||||
auto GetAlbumType() const -> AlbumType
|
||||
{
|
||||
if (album_type == "album") {
|
||||
return AlbumType::Album;
|
||||
}
|
||||
if (album_type == "single") {
|
||||
return AlbumType::Single;
|
||||
}
|
||||
return AlbumType::Compilation;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Saved Album
|
||||
// ============================================================================
|
||||
auto GetReleaseDatePrecision() const -> ReleaseDatePrecision
|
||||
{
|
||||
if (release_date_precision == "year") {
|
||||
return ReleaseDatePrecision::Year;
|
||||
}
|
||||
if (release_date_precision == "month") {
|
||||
return ReleaseDatePrecision::Month;
|
||||
}
|
||||
return ReleaseDatePrecision::Day;
|
||||
}
|
||||
};
|
||||
|
||||
struct SavedAlbum {
|
||||
std::string added_at;
|
||||
Album album;
|
||||
|
||||
auto GetAlbum() const -> const Album& { return album; }
|
||||
auto GetAddedAt() const -> const std::string& { return added_at; }
|
||||
};
|
||||
// ============================================================================
|
||||
// Simplified Album
|
||||
// ============================================================================
|
||||
|
||||
struct AlbumsResponse {
|
||||
std::vector<Album> albums;
|
||||
};
|
||||
struct SimplifiedAlbum : AlbumBase {
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Full Album
|
||||
// ============================================================================
|
||||
|
||||
struct Album : AlbumBase {
|
||||
std::vector<Copyright> copyrights;
|
||||
ExternalIds external_ids;
|
||||
std::vector<std::string> genres;
|
||||
std::string label;
|
||||
int popularity;
|
||||
|
||||
auto GetPopularity() const -> int { return popularity; }
|
||||
auto GetLabel() const -> const std::string & { return label; }
|
||||
auto GetGenres() const -> const std::vector<std::string> &
|
||||
{
|
||||
return genres;
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Saved Album
|
||||
// ============================================================================
|
||||
|
||||
struct SavedAlbum {
|
||||
std::string added_at;
|
||||
Album album;
|
||||
|
||||
auto GetAlbum() const -> const Album & { return album; }
|
||||
auto GetAddedAt() const -> const std::string & { return added_at; }
|
||||
};
|
||||
|
||||
struct AlbumsResponse {
|
||||
std::vector<Album> albums;
|
||||
};
|
||||
} // namespace Spotify
|
||||
|
||||
// ============================================================================
|
||||
// Glaze Metadata
|
||||
// ============================================================================
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::SimplifiedAlbum> {
|
||||
using T = Spotify::SimplifiedAlbum;
|
||||
static constexpr auto value = object(
|
||||
"album_type", &T::album_type,
|
||||
"total_tracks", &T::total_tracks,
|
||||
"available_markets", &T::available_markets,
|
||||
"external_urls", &T::external_urls,
|
||||
"href", &T::href,
|
||||
"id", &T::id,
|
||||
"images", &T::images,
|
||||
"name", &T::name,
|
||||
"release_date", &T::release_date,
|
||||
"release_date_precision", &T::release_date_precision,
|
||||
"restrictions", &T::restrictions,
|
||||
"type", &T::type,
|
||||
"uri", &T::uri,
|
||||
"artists", &T::artists,
|
||||
"is_playable", &T::is_playable
|
||||
);
|
||||
template <> struct glz::meta<Spotify::SimplifiedAlbum> {
|
||||
using T = Spotify::SimplifiedAlbum;
|
||||
static constexpr auto value = object(
|
||||
"album_type", &T::album_type, "total_tracks", &T::total_tracks,
|
||||
"available_markets", &T::available_markets, "external_urls",
|
||||
&T::external_urls, "href", &T::href, "id", &T::id, "images",
|
||||
&T::images, "name", &T::name, "release_date", &T::release_date,
|
||||
"release_date_precision", &T::release_date_precision,
|
||||
"restrictions", &T::restrictions, "type", &T::type, "uri", &T::uri,
|
||||
"artists", &T::artists, "is_playable", &T::is_playable);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::AlbumsResponse> {
|
||||
using T = Spotify::AlbumsResponse;
|
||||
static constexpr auto value = object(
|
||||
"albums", &T::albums
|
||||
);
|
||||
template <> struct glz::meta<Spotify::AlbumsResponse> {
|
||||
using T = Spotify::AlbumsResponse;
|
||||
static constexpr auto value = object("albums", &T::albums);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Album> {
|
||||
using T = Spotify::Album;
|
||||
static constexpr auto value = object(
|
||||
"album_type", &T::album_type,
|
||||
"total_tracks", &T::total_tracks,
|
||||
"available_markets", &T::available_markets,
|
||||
"external_urls", &T::external_urls,
|
||||
"href", &T::href,
|
||||
"id", &T::id,
|
||||
"images", &T::images,
|
||||
"name", &T::name,
|
||||
"release_date", &T::release_date,
|
||||
"release_date_precision", &T::release_date_precision,
|
||||
"restrictions", &T::restrictions,
|
||||
"type", &T::type,
|
||||
"uri", &T::uri,
|
||||
"artists", &T::artists,
|
||||
"copyrights", &T::copyrights,
|
||||
"external_ids", &T::external_ids,
|
||||
"genres", &T::genres,
|
||||
"label", &T::label,
|
||||
"popularity", &T::popularity
|
||||
);
|
||||
template <> struct glz::meta<Spotify::Album> {
|
||||
using T = Spotify::Album;
|
||||
static constexpr auto value = object(
|
||||
"album_type", &T::album_type, "total_tracks", &T::total_tracks,
|
||||
"available_markets", &T::available_markets, "external_urls",
|
||||
&T::external_urls, "href", &T::href, "id", &T::id, "images",
|
||||
&T::images, "name", &T::name, "release_date", &T::release_date,
|
||||
"release_date_precision", &T::release_date_precision,
|
||||
"restrictions", &T::restrictions, "type", &T::type, "uri", &T::uri,
|
||||
"artists", &T::artists, "copyrights", &T::copyrights,
|
||||
"external_ids", &T::external_ids, "genres", &T::genres, "label",
|
||||
&T::label, "popularity", &T::popularity);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::SavedAlbum> {
|
||||
using T = Spotify::SavedAlbum;
|
||||
static constexpr auto value = object(
|
||||
"added_at", &T::added_at,
|
||||
"album", &T::album
|
||||
);
|
||||
template <> struct glz::meta<Spotify::SavedAlbum> {
|
||||
using T = Spotify::SavedAlbum;
|
||||
static constexpr auto value =
|
||||
object("added_at", &T::added_at, "album", &T::album);
|
||||
};
|
||||
@@ -1,84 +1,76 @@
|
||||
#pragma once
|
||||
#include "Spotify/Types/Common.hpp"
|
||||
|
||||
namespace Spotify {
|
||||
namespace Spotify
|
||||
{
|
||||
|
||||
// ============================================================================
|
||||
// Artist Base
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Artist Base
|
||||
// ============================================================================
|
||||
|
||||
class ArtistBase {
|
||||
public:
|
||||
ExternalUrls external_urls;
|
||||
std::string href;
|
||||
std::string id;
|
||||
std::string name;
|
||||
std::string type;
|
||||
std::string uri;
|
||||
|
||||
virtual ~ArtistBase() = default;
|
||||
|
||||
auto GetId() const -> const std::string& { return id; }
|
||||
auto GetName() const -> const std::string& { return name; }
|
||||
auto GetUri() const -> const std::string& { return uri; }
|
||||
};
|
||||
class ArtistBase
|
||||
{
|
||||
public:
|
||||
|
||||
// ============================================================================
|
||||
// Simplified Artist
|
||||
// ============================================================================
|
||||
ExternalUrls external_urls;
|
||||
std::string href;
|
||||
std::string id;
|
||||
std::string name;
|
||||
std::string type;
|
||||
std::string uri;
|
||||
|
||||
struct SimplifiedArtist : ArtistBase {
|
||||
};
|
||||
virtual ~ArtistBase() = default;
|
||||
|
||||
// ============================================================================
|
||||
// Full Artist
|
||||
// ============================================================================
|
||||
auto GetId() const -> const std::string & { return id; }
|
||||
auto GetName() const -> const std::string & { return name; }
|
||||
auto GetUri() const -> const std::string & { return uri; }
|
||||
};
|
||||
|
||||
struct Artist : ArtistBase {
|
||||
Followers followers;
|
||||
std::vector<std::string> genres;
|
||||
std::vector<Image> images;
|
||||
int popularity;
|
||||
|
||||
auto GetPopularity() const -> int { return popularity; }
|
||||
auto GetGenres() const -> const std::vector<std::string>& { return genres; }
|
||||
};
|
||||
// ============================================================================
|
||||
// Simplified Artist
|
||||
// ============================================================================
|
||||
|
||||
struct ArtistsResponse {
|
||||
std::vector<Artist> artists;
|
||||
};
|
||||
struct SimplifiedArtist : ArtistBase {
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Full Artist
|
||||
// ============================================================================
|
||||
|
||||
struct Artist : ArtistBase {
|
||||
Followers followers;
|
||||
std::vector<std::string> genres;
|
||||
std::vector<Image> images;
|
||||
int popularity;
|
||||
|
||||
auto GetPopularity() const -> int { return popularity; }
|
||||
auto GetGenres() const -> const std::vector<std::string> &
|
||||
{
|
||||
return genres;
|
||||
}
|
||||
};
|
||||
|
||||
struct ArtistsResponse {
|
||||
std::vector<Artist> artists;
|
||||
};
|
||||
} // namespace Spotify
|
||||
|
||||
// ============================================================================
|
||||
// Glaze Metadata
|
||||
// ============================================================================
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::SimplifiedArtist> {
|
||||
using T = Spotify::SimplifiedArtist;
|
||||
static constexpr auto value = object(
|
||||
"external_urls", &T::external_urls,
|
||||
"href", &T::href,
|
||||
"id", &T::id,
|
||||
"name", &T::name,
|
||||
"type", &T::type,
|
||||
"uri", &T::uri
|
||||
);
|
||||
template <> struct glz::meta<Spotify::SimplifiedArtist> {
|
||||
using T = Spotify::SimplifiedArtist;
|
||||
static constexpr auto value =
|
||||
object("external_urls", &T::external_urls, "href", &T::href, "id",
|
||||
&T::id, "name", &T::name, "type", &T::type, "uri", &T::uri);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Artist> {
|
||||
using T = Spotify::Artist;
|
||||
static constexpr auto value = object(
|
||||
"external_urls", &T::external_urls,
|
||||
"followers", &T::followers,
|
||||
"genres", &T::genres,
|
||||
"href", &T::href,
|
||||
"id", &T::id,
|
||||
"images", &T::images,
|
||||
"name", &T::name,
|
||||
"popularity", &T::popularity,
|
||||
"type", &T::type,
|
||||
"uri", &T::uri
|
||||
);
|
||||
template <> struct glz::meta<Spotify::Artist> {
|
||||
using T = Spotify::Artist;
|
||||
static constexpr auto value =
|
||||
object("external_urls", &T::external_urls, "followers",
|
||||
&T::followers, "genres", &T::genres, "href", &T::href, "id",
|
||||
&T::id, "images", &T::images, "name", &T::name, "popularity",
|
||||
&T::popularity, "type", &T::type, "uri", &T::uri);
|
||||
};
|
||||
@@ -1,185 +1,152 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
#include <glaze/glaze.hpp>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Spotify {
|
||||
namespace Spotify
|
||||
{
|
||||
|
||||
// ============================================================================
|
||||
// Common Enums
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Common Enums
|
||||
// ============================================================================
|
||||
|
||||
enum class AlbumType {
|
||||
Album,
|
||||
Single,
|
||||
Compilation
|
||||
};
|
||||
enum class AlbumType { Album, Single, Compilation };
|
||||
|
||||
enum class ReleaseDatePrecision {
|
||||
Year,
|
||||
Month,
|
||||
Day
|
||||
};
|
||||
enum class ReleaseDatePrecision { Year, Month, Day };
|
||||
|
||||
enum class CopyrightType {
|
||||
Copyright, // "C"
|
||||
Performance // "P"
|
||||
};
|
||||
enum class CopyrightType {
|
||||
Copyright, // "C"
|
||||
Performance // "P"
|
||||
};
|
||||
|
||||
enum class RestrictionReason {
|
||||
Market,
|
||||
Product,
|
||||
Explicit
|
||||
};
|
||||
enum class RestrictionReason { Market, Product, Explicit };
|
||||
|
||||
// ============================================================================
|
||||
// Core Structures
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Core Structures
|
||||
// ============================================================================
|
||||
|
||||
struct Image {
|
||||
std::string url;
|
||||
std::optional<int> height;
|
||||
std::optional<int> width;
|
||||
};
|
||||
struct Image {
|
||||
std::string url;
|
||||
std::optional<int> height;
|
||||
std::optional<int> width;
|
||||
};
|
||||
|
||||
struct ExternalUrls {
|
||||
std::string spotify;
|
||||
};
|
||||
struct ExternalUrls {
|
||||
std::string spotify;
|
||||
};
|
||||
|
||||
struct ExternalIds {
|
||||
std::optional<std::string> isrc;
|
||||
std::optional<std::string> ean;
|
||||
std::optional<std::string> upc;
|
||||
};
|
||||
struct ExternalIds {
|
||||
std::optional<std::string> isrc;
|
||||
std::optional<std::string> ean;
|
||||
std::optional<std::string> upc;
|
||||
};
|
||||
|
||||
struct Followers {
|
||||
std::optional<std::string> href;
|
||||
int total;
|
||||
};
|
||||
struct Followers {
|
||||
std::optional<std::string> href;
|
||||
int total;
|
||||
};
|
||||
|
||||
struct Copyright {
|
||||
std::string text;
|
||||
std::string type;
|
||||
|
||||
auto GetType() const -> CopyrightType {
|
||||
return type == "C" ? CopyrightType::Copyright : CopyrightType::Performance;
|
||||
}
|
||||
};
|
||||
struct Copyright {
|
||||
std::string text;
|
||||
std::string type;
|
||||
|
||||
struct Restrictions {
|
||||
std::string reason;
|
||||
|
||||
auto GetReason() const -> RestrictionReason {
|
||||
if (reason == "market") return RestrictionReason::Market;
|
||||
if (reason == "product") return RestrictionReason::Product;
|
||||
return RestrictionReason::Explicit;
|
||||
}
|
||||
};
|
||||
auto GetType() const -> CopyrightType
|
||||
{
|
||||
return type == "C" ? CopyrightType::Copyright
|
||||
: CopyrightType::Performance;
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Paging Objects
|
||||
// ============================================================================
|
||||
struct Restrictions {
|
||||
std::string reason;
|
||||
|
||||
template<typename T>
|
||||
struct PagingObject {
|
||||
std::string href;
|
||||
int limit;
|
||||
std::optional<std::string> next;
|
||||
int offset;
|
||||
std::optional<std::string> previous;
|
||||
int total;
|
||||
std::vector<T> items;
|
||||
};
|
||||
auto GetReason() const -> RestrictionReason
|
||||
{
|
||||
if (reason == "market") {
|
||||
return RestrictionReason::Market;
|
||||
}
|
||||
if (reason == "product") {
|
||||
return RestrictionReason::Product;
|
||||
}
|
||||
return RestrictionReason::Explicit;
|
||||
}
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct CursorPagingObject {
|
||||
std::string href;
|
||||
int limit;
|
||||
std::optional<std::string> next;
|
||||
std::optional<std::string> cursors;
|
||||
int total;
|
||||
std::vector<T> items;
|
||||
};
|
||||
// ============================================================================
|
||||
// Paging Objects
|
||||
// ============================================================================
|
||||
|
||||
template <typename T> struct PagingObject {
|
||||
std::string href;
|
||||
int limit;
|
||||
std::optional<std::string> next;
|
||||
int offset;
|
||||
std::optional<std::string> previous;
|
||||
int total;
|
||||
std::vector<T> items;
|
||||
};
|
||||
|
||||
template <typename T> struct CursorPagingObject {
|
||||
std::string href;
|
||||
int limit;
|
||||
std::optional<std::string> next;
|
||||
std::optional<std::string> cursors;
|
||||
int total;
|
||||
std::vector<T> items;
|
||||
};
|
||||
} // namespace Spotify
|
||||
|
||||
// ============================================================================
|
||||
// Glaze Metadata for Common Types
|
||||
// ============================================================================
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Image> {
|
||||
using T = Spotify::Image;
|
||||
static constexpr auto value = object(
|
||||
"url", &T::url,
|
||||
"height", &T::height,
|
||||
"width", &T::width
|
||||
);
|
||||
template <> struct glz::meta<Spotify::Image> {
|
||||
using T = Spotify::Image;
|
||||
static constexpr auto value =
|
||||
object("url", &T::url, "height", &T::height, "width", &T::width);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::ExternalUrls> {
|
||||
using T = Spotify::ExternalUrls;
|
||||
static constexpr auto value = object("spotify", &T::spotify);
|
||||
template <> struct glz::meta<Spotify::ExternalUrls> {
|
||||
using T = Spotify::ExternalUrls;
|
||||
static constexpr auto value = object("spotify", &T::spotify);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::ExternalIds> {
|
||||
using T = Spotify::ExternalIds;
|
||||
static constexpr auto value = object(
|
||||
"isrc", &T::isrc,
|
||||
"ean", &T::ean,
|
||||
"upc", &T::upc
|
||||
);
|
||||
template <> struct glz::meta<Spotify::ExternalIds> {
|
||||
using T = Spotify::ExternalIds;
|
||||
static constexpr auto value =
|
||||
object("isrc", &T::isrc, "ean", &T::ean, "upc", &T::upc);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Followers> {
|
||||
using T = Spotify::Followers;
|
||||
static constexpr auto value = object(
|
||||
"href", &T::href,
|
||||
"total", &T::total
|
||||
);
|
||||
template <> struct glz::meta<Spotify::Followers> {
|
||||
using T = Spotify::Followers;
|
||||
static constexpr auto value =
|
||||
object("href", &T::href, "total", &T::total);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Copyright> {
|
||||
using T = Spotify::Copyright;
|
||||
static constexpr auto value = object(
|
||||
"text", &T::text,
|
||||
"type", &T::type
|
||||
);
|
||||
template <> struct glz::meta<Spotify::Copyright> {
|
||||
using T = Spotify::Copyright;
|
||||
static constexpr auto value =
|
||||
object("text", &T::text, "type", &T::type);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Restrictions> {
|
||||
using T = Spotify::Restrictions;
|
||||
static constexpr auto value = object("reason", &T::reason);
|
||||
template <> struct glz::meta<Spotify::Restrictions> {
|
||||
using T = Spotify::Restrictions;
|
||||
static constexpr auto value = object("reason", &T::reason);
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct glz::meta<Spotify::PagingObject<T>> {
|
||||
using Type = Spotify::PagingObject<T>;
|
||||
static constexpr auto value = object(
|
||||
"href", &Type::href,
|
||||
"limit", &Type::limit,
|
||||
"next", &Type::next,
|
||||
"offset", &Type::offset,
|
||||
"previous", &Type::previous,
|
||||
"total", &Type::total,
|
||||
"items", &Type::items
|
||||
);
|
||||
template <typename T> struct glz::meta<Spotify::PagingObject<T>> {
|
||||
using Type = Spotify::PagingObject<T>;
|
||||
static constexpr auto value = object(
|
||||
"href", &Type::href, "limit", &Type::limit, "next", &Type::next,
|
||||
"offset", &Type::offset, "previous", &Type::previous, "total",
|
||||
&Type::total, "items", &Type::items);
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct glz::meta<Spotify::CursorPagingObject<T>> {
|
||||
using Type = Spotify::CursorPagingObject<T>;
|
||||
static constexpr auto value = object(
|
||||
"href", &Type::href,
|
||||
"limit", &Type::limit,
|
||||
"next", &Type::next,
|
||||
"cursors", &Type::cursors,
|
||||
"total", &Type::total,
|
||||
"items", &Type::items
|
||||
);
|
||||
template <typename T> struct glz::meta<Spotify::CursorPagingObject<T>> {
|
||||
using Type = Spotify::CursorPagingObject<T>;
|
||||
static constexpr auto value =
|
||||
object("href", &Type::href, "limit", &Type::limit, "next",
|
||||
&Type::next, "cursors", &Type::cursors, "total",
|
||||
&Type::total, "items", &Type::items);
|
||||
};
|
||||
@@ -1,133 +1,140 @@
|
||||
#pragma once
|
||||
#include "Spotify/Types/Common.hpp"
|
||||
#include "Spotify/Types/Track.hpp"
|
||||
#include "Spotify/Types/Artist.hpp"
|
||||
#include "Spotify/Types/Album.hpp"
|
||||
#include "Spotify/Types/Artist.hpp"
|
||||
#include "Spotify/Types/Common.hpp"
|
||||
#include "Spotify/Types/Playlist.hpp"
|
||||
#include "Spotify/Types/Track.hpp"
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Spotify {
|
||||
namespace Spotify
|
||||
{
|
||||
|
||||
// ============================================================================
|
||||
// Category
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Category
|
||||
// ============================================================================
|
||||
|
||||
struct Category {
|
||||
std::string href;
|
||||
std::vector<Image> icons;
|
||||
std::string id;
|
||||
std::string name;
|
||||
|
||||
auto GetId() const -> const std::string& { return id; }
|
||||
auto GetName() const -> const std::string& { return name; }
|
||||
};
|
||||
struct Category {
|
||||
std::string href;
|
||||
std::vector<Image> icons;
|
||||
std::string id;
|
||||
std::string name;
|
||||
|
||||
// ============================================================================
|
||||
// Recommendation Seed
|
||||
// ============================================================================
|
||||
auto GetId() const -> const std::string& { return id; }
|
||||
auto GetName() const -> const std::string& { return name; }
|
||||
};
|
||||
|
||||
enum class SeedType {
|
||||
Artist,
|
||||
Track,
|
||||
Genre
|
||||
};
|
||||
// ============================================================================
|
||||
// Recommendation Seed
|
||||
// ============================================================================
|
||||
|
||||
inline auto StringToSeedType(const std::string& str) -> SeedType {
|
||||
if (str == "ARTIST") return SeedType::Artist;
|
||||
if (str == "TRACK") return SeedType::Track;
|
||||
return SeedType::Genre;
|
||||
}
|
||||
enum class SeedType { Artist, Track, Genre };
|
||||
|
||||
struct RecommendationSeed {
|
||||
int afterFilteringSize;
|
||||
int afterRelinkingSize;
|
||||
std::optional<std::string> href;
|
||||
std::string id;
|
||||
int initialPoolSize;
|
||||
std::string type;
|
||||
|
||||
auto GetId() const -> const std::string& { return id; }
|
||||
auto GetSeedType() const -> SeedType {
|
||||
return StringToSeedType(type);
|
||||
}
|
||||
};
|
||||
inline auto StringToSeedType(const std::string& str) -> SeedType
|
||||
{
|
||||
if (str == "ARTIST") {
|
||||
return SeedType::Artist;
|
||||
}
|
||||
if (str == "TRACK") {
|
||||
return SeedType::Track;
|
||||
}
|
||||
return SeedType::Genre;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Recommendations Response
|
||||
// ============================================================================
|
||||
struct RecommendationSeed {
|
||||
int afterFilteringSize;
|
||||
int afterRelinkingSize;
|
||||
std::optional<std::string> href;
|
||||
std::string id;
|
||||
int initialPoolSize;
|
||||
std::string type;
|
||||
|
||||
struct Recommendations {
|
||||
std::vector<RecommendationSeed> seeds;
|
||||
std::vector<Track> tracks;
|
||||
|
||||
auto GetTracks() const -> const std::vector<Track>& { return tracks; }
|
||||
auto GetSeeds() const -> const std::vector<RecommendationSeed>& { return seeds; }
|
||||
};
|
||||
auto GetId() const -> const std::string& { return id; }
|
||||
auto GetSeedType() const -> SeedType
|
||||
{
|
||||
return StringToSeedType(type);
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Search Results
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Recommendations Response
|
||||
// ============================================================================
|
||||
|
||||
struct SearchResults {
|
||||
std::optional<PagingObject<Track>> tracks;
|
||||
std::optional<PagingObject<Artist>> artists;
|
||||
std::optional<PagingObject<SimplifiedAlbum>> albums;
|
||||
std::optional<PagingObject<SimplifiedPlaylist>> playlists;
|
||||
|
||||
auto GetTracks() const -> const std::optional<PagingObject<Track>>& { return tracks; }
|
||||
auto GetArtists() const -> const std::optional<PagingObject<Artist>>& { return artists; }
|
||||
auto GetAlbums() const -> const std::optional<PagingObject<SimplifiedAlbum>>& { return albums; }
|
||||
auto GetPlaylists() const -> const std::optional<PagingObject<SimplifiedPlaylist>>& { return playlists; }
|
||||
};
|
||||
struct Recommendations {
|
||||
std::vector<RecommendationSeed> seeds;
|
||||
std::vector<Track> tracks;
|
||||
|
||||
auto GetTracks() const -> const std::vector<Track>&
|
||||
{
|
||||
return tracks;
|
||||
}
|
||||
auto GetSeeds() const -> const std::vector<RecommendationSeed>&
|
||||
{
|
||||
return seeds;
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Search Results
|
||||
// ============================================================================
|
||||
|
||||
struct SearchResults {
|
||||
std::optional<PagingObject<Track>> tracks;
|
||||
std::optional<PagingObject<Artist>> artists;
|
||||
std::optional<PagingObject<SimplifiedAlbum>> albums;
|
||||
std::optional<PagingObject<SimplifiedPlaylist>> playlists;
|
||||
|
||||
auto GetTracks() const -> const std::optional<PagingObject<Track>>&
|
||||
{
|
||||
return tracks;
|
||||
}
|
||||
auto GetArtists() const
|
||||
-> const std::optional<PagingObject<Artist>>&
|
||||
{
|
||||
return artists;
|
||||
}
|
||||
auto GetAlbums() const
|
||||
-> const std::optional<PagingObject<SimplifiedAlbum>>&
|
||||
{
|
||||
return albums;
|
||||
}
|
||||
auto GetPlaylists() const
|
||||
-> const std::optional<PagingObject<SimplifiedPlaylist>>&
|
||||
{
|
||||
return playlists;
|
||||
}
|
||||
};
|
||||
} // namespace Spotify
|
||||
|
||||
// ============================================================================
|
||||
// Glaze Metadata
|
||||
// ============================================================================
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Category> {
|
||||
using T = Spotify::Category;
|
||||
static constexpr auto value = object(
|
||||
"href", &T::href,
|
||||
"icons", &T::icons,
|
||||
"id", &T::id,
|
||||
"name", &T::name
|
||||
);
|
||||
template <> struct glz::meta<Spotify::Category> {
|
||||
using T = Spotify::Category;
|
||||
static constexpr auto value =
|
||||
object("href", &T::href, "icons", &T::icons, "id", &T::id, "name",
|
||||
&T::name);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::RecommendationSeed> {
|
||||
using T = Spotify::RecommendationSeed;
|
||||
static constexpr auto value = object(
|
||||
"afterFilteringSize", &T::afterFilteringSize,
|
||||
"afterRelinkingSize", &T::afterRelinkingSize,
|
||||
"href", &T::href,
|
||||
"id", &T::id,
|
||||
"initialPoolSize", &T::initialPoolSize,
|
||||
"type", &T::type
|
||||
);
|
||||
template <> struct glz::meta<Spotify::RecommendationSeed> {
|
||||
using T = Spotify::RecommendationSeed;
|
||||
static constexpr auto value = object(
|
||||
"afterFilteringSize", &T::afterFilteringSize, "afterRelinkingSize",
|
||||
&T::afterRelinkingSize, "href", &T::href, "id", &T::id,
|
||||
"initialPoolSize", &T::initialPoolSize, "type", &T::type);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Recommendations> {
|
||||
using T = Spotify::Recommendations;
|
||||
static constexpr auto value = object(
|
||||
"seeds", &T::seeds,
|
||||
"tracks", &T::tracks
|
||||
);
|
||||
template <> struct glz::meta<Spotify::Recommendations> {
|
||||
using T = Spotify::Recommendations;
|
||||
static constexpr auto value =
|
||||
object("seeds", &T::seeds, "tracks", &T::tracks);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::SearchResults> {
|
||||
using T = Spotify::SearchResults;
|
||||
static constexpr auto value = object(
|
||||
"tracks", &T::tracks,
|
||||
"artists", &T::artists,
|
||||
"albums", &T::albums,
|
||||
"playlists", &T::playlists
|
||||
);
|
||||
template <> struct glz::meta<Spotify::SearchResults> {
|
||||
using T = Spotify::SearchResults;
|
||||
static constexpr auto value =
|
||||
object("tracks", &T::tracks, "artists", &T::artists, "albums",
|
||||
&T::albums, "playlists", &T::playlists);
|
||||
};
|
||||
|
||||
@@ -2,217 +2,246 @@
|
||||
#include "Spotify/Types/Common.hpp"
|
||||
#include "Spotify/Types/Track.hpp"
|
||||
|
||||
namespace Spotify {
|
||||
namespace Spotify
|
||||
{
|
||||
|
||||
// ============================================================================
|
||||
// Device Type Enum
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Device Type Enum
|
||||
// ============================================================================
|
||||
|
||||
enum class DeviceType {
|
||||
Computer,
|
||||
Smartphone,
|
||||
Speaker,
|
||||
TV,
|
||||
AVR,
|
||||
STB,
|
||||
AudioDongle,
|
||||
GameConsole,
|
||||
CastVideo,
|
||||
CastAudio,
|
||||
Automobile,
|
||||
Unknown
|
||||
};
|
||||
enum class DeviceType {
|
||||
Computer,
|
||||
Smartphone,
|
||||
Speaker,
|
||||
TV,
|
||||
AVR,
|
||||
STB,
|
||||
AudioDongle,
|
||||
GameConsole,
|
||||
CastVideo,
|
||||
CastAudio,
|
||||
Automobile,
|
||||
Unknown
|
||||
};
|
||||
|
||||
inline auto StringToDeviceType(const std::string& str) -> DeviceType {
|
||||
if (str == "Computer") return DeviceType::Computer;
|
||||
if (str == "Smartphone") return DeviceType::Smartphone;
|
||||
if (str == "Speaker") return DeviceType::Speaker;
|
||||
if (str == "TV") return DeviceType::TV;
|
||||
if (str == "AVR") return DeviceType::AVR;
|
||||
if (str == "STB") return DeviceType::STB;
|
||||
if (str == "AudioDongle") return DeviceType::AudioDongle;
|
||||
if (str == "GameConsole") return DeviceType::GameConsole;
|
||||
if (str == "CastVideo") return DeviceType::CastVideo;
|
||||
if (str == "CastAudio") return DeviceType::CastAudio;
|
||||
if (str == "Automobile") return DeviceType::Automobile;
|
||||
return DeviceType::Unknown;
|
||||
}
|
||||
inline auto StringToDeviceType(const std::string& str) -> DeviceType
|
||||
{
|
||||
if (str == "Computer") {
|
||||
return DeviceType::Computer;
|
||||
}
|
||||
if (str == "Smartphone") {
|
||||
return DeviceType::Smartphone;
|
||||
}
|
||||
if (str == "Speaker") {
|
||||
return DeviceType::Speaker;
|
||||
}
|
||||
if (str == "TV") {
|
||||
return DeviceType::TV;
|
||||
}
|
||||
if (str == "AVR") {
|
||||
return DeviceType::AVR;
|
||||
}
|
||||
if (str == "STB") {
|
||||
return DeviceType::STB;
|
||||
}
|
||||
if (str == "AudioDongle") {
|
||||
return DeviceType::AudioDongle;
|
||||
}
|
||||
if (str == "GameConsole") {
|
||||
return DeviceType::GameConsole;
|
||||
}
|
||||
if (str == "CastVideo") {
|
||||
return DeviceType::CastVideo;
|
||||
}
|
||||
if (str == "CastAudio") {
|
||||
return DeviceType::CastAudio;
|
||||
}
|
||||
if (str == "Automobile") {
|
||||
return DeviceType::Automobile;
|
||||
}
|
||||
return DeviceType::Unknown;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Repeat Mode Enum
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Repeat Mode Enum
|
||||
// ============================================================================
|
||||
|
||||
enum class RepeatMode {
|
||||
Off,
|
||||
Track,
|
||||
Context
|
||||
};
|
||||
enum class RepeatMode { Off, Track, Context };
|
||||
|
||||
inline auto RepeatModeToString(RepeatMode mode) -> std::string {
|
||||
switch (mode) {
|
||||
case RepeatMode::Off: return "off";
|
||||
case RepeatMode::Track: return "track";
|
||||
case RepeatMode::Context: return "context";
|
||||
}
|
||||
return "off";
|
||||
}
|
||||
inline auto RepeatModeToString(RepeatMode mode) -> std::string
|
||||
{
|
||||
switch (mode) {
|
||||
case RepeatMode::Off:
|
||||
return "off";
|
||||
case RepeatMode::Track:
|
||||
return "track";
|
||||
case RepeatMode::Context:
|
||||
return "context";
|
||||
}
|
||||
return "off";
|
||||
}
|
||||
|
||||
inline auto StringToRepeatMode(const std::string& str) -> RepeatMode {
|
||||
if (str == "track") return RepeatMode::Track;
|
||||
if (str == "context") return RepeatMode::Context;
|
||||
return RepeatMode::Off;
|
||||
}
|
||||
inline auto StringToRepeatMode(const std::string& str) -> RepeatMode
|
||||
{
|
||||
if (str == "track") {
|
||||
return RepeatMode::Track;
|
||||
}
|
||||
if (str == "context") {
|
||||
return RepeatMode::Context;
|
||||
}
|
||||
return RepeatMode::Off;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Context Type Enum
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Context Type Enum
|
||||
// ============================================================================
|
||||
|
||||
enum class ContextType {
|
||||
Artist,
|
||||
Playlist,
|
||||
Album,
|
||||
Show,
|
||||
Collection
|
||||
};
|
||||
enum class ContextType { Artist, Playlist, Album, Show, Collection };
|
||||
|
||||
inline auto StringToContextType(const std::string& str) -> ContextType {
|
||||
if (str == "artist") return ContextType::Artist;
|
||||
if (str == "playlist") return ContextType::Playlist;
|
||||
if (str == "album") return ContextType::Album;
|
||||
if (str == "show") return ContextType::Show;
|
||||
return ContextType::Collection;
|
||||
}
|
||||
inline auto StringToContextType(const std::string& str) -> ContextType
|
||||
{
|
||||
if (str == "artist") {
|
||||
return ContextType::Artist;
|
||||
}
|
||||
if (str == "playlist") {
|
||||
return ContextType::Playlist;
|
||||
}
|
||||
if (str == "album") {
|
||||
return ContextType::Album;
|
||||
}
|
||||
if (str == "show") {
|
||||
return ContextType::Show;
|
||||
}
|
||||
return ContextType::Collection;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Currently Playing Type Enum
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Currently Playing Type Enum
|
||||
// ============================================================================
|
||||
|
||||
enum class CurrentlyPlayingType {
|
||||
Track,
|
||||
Episode,
|
||||
Ad,
|
||||
Unknown
|
||||
};
|
||||
enum class CurrentlyPlayingType { Track, Episode, Ad, Unknown };
|
||||
|
||||
inline auto StringToCurrentlyPlayingType(const std::string& str) -> CurrentlyPlayingType {
|
||||
if (str == "track") return CurrentlyPlayingType::Track;
|
||||
if (str == "episode") return CurrentlyPlayingType::Episode;
|
||||
if (str == "ad") return CurrentlyPlayingType::Ad;
|
||||
return CurrentlyPlayingType::Unknown;
|
||||
}
|
||||
inline auto StringToCurrentlyPlayingType(const std::string& str)
|
||||
-> CurrentlyPlayingType
|
||||
{
|
||||
if (str == "track") {
|
||||
return CurrentlyPlayingType::Track;
|
||||
}
|
||||
if (str == "episode") {
|
||||
return CurrentlyPlayingType::Episode;
|
||||
}
|
||||
if (str == "ad") {
|
||||
return CurrentlyPlayingType::Ad;
|
||||
}
|
||||
return CurrentlyPlayingType::Unknown;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Device
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Device
|
||||
// ============================================================================
|
||||
|
||||
struct Device {
|
||||
std::optional<std::string> id;
|
||||
bool is_active;
|
||||
bool is_private_session;
|
||||
bool is_restricted;
|
||||
std::string name;
|
||||
std::string type;
|
||||
int volume_percent;
|
||||
|
||||
auto GetId() const -> const std::optional<std::string>& { return id; }
|
||||
auto GetName() const -> const std::string& { return name; }
|
||||
auto IsActive() const -> bool { return is_active; }
|
||||
auto GetVolume() const -> int { return volume_percent; }
|
||||
|
||||
auto GetDeviceType() const -> DeviceType {
|
||||
return StringToDeviceType(type);
|
||||
}
|
||||
};
|
||||
struct Device {
|
||||
std::optional<std::string> id;
|
||||
bool is_active;
|
||||
bool is_private_session;
|
||||
bool is_restricted;
|
||||
std::string name;
|
||||
std::string type;
|
||||
int volume_percent;
|
||||
|
||||
// ============================================================================
|
||||
// Context
|
||||
// ============================================================================
|
||||
auto GetId() const -> const std::optional<std::string>&
|
||||
{
|
||||
return id;
|
||||
}
|
||||
auto GetName() const -> const std::string& { return name; }
|
||||
auto IsActive() const -> bool { return is_active; }
|
||||
auto GetVolume() const -> int { return volume_percent; }
|
||||
|
||||
struct Context {
|
||||
std::string type;
|
||||
std::string href;
|
||||
ExternalUrls external_urls;
|
||||
std::string uri;
|
||||
|
||||
auto GetUri() const -> const std::string& { return uri; }
|
||||
|
||||
auto GetContextType() const -> ContextType {
|
||||
return StringToContextType(type);
|
||||
}
|
||||
};
|
||||
auto GetDeviceType() const -> DeviceType
|
||||
{
|
||||
return StringToDeviceType(type);
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Playback State
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Context
|
||||
// ============================================================================
|
||||
|
||||
struct PlaybackState {
|
||||
Device device;
|
||||
std::string repeat_state;
|
||||
bool shuffle_state;
|
||||
std::optional<Context> context;
|
||||
int timestamp;
|
||||
int progress_ms;
|
||||
bool is_playing;
|
||||
std::optional<Track> item;
|
||||
std::string currently_playing_type;
|
||||
|
||||
auto GetDevice() const -> const Device& { return device; }
|
||||
auto IsPlaying() const -> bool { return is_playing; }
|
||||
auto IsShuffled() const -> bool { return shuffle_state; }
|
||||
auto GetProgressMs() const -> int { return progress_ms; }
|
||||
auto GetCurrentTrack() const -> const std::optional<Track>& { return item; }
|
||||
|
||||
auto GetRepeatMode() const -> RepeatMode {
|
||||
return StringToRepeatMode(repeat_state);
|
||||
}
|
||||
|
||||
auto GetCurrentlyPlayingType() const -> CurrentlyPlayingType {
|
||||
return StringToCurrentlyPlayingType(currently_playing_type);
|
||||
}
|
||||
};
|
||||
struct Context {
|
||||
std::string type;
|
||||
std::string href;
|
||||
ExternalUrls external_urls;
|
||||
std::string uri;
|
||||
|
||||
auto GetUri() const -> const std::string& { return uri; }
|
||||
|
||||
auto GetContextType() const -> ContextType
|
||||
{
|
||||
return StringToContextType(type);
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Playback State
|
||||
// ============================================================================
|
||||
|
||||
struct PlaybackState {
|
||||
Device device;
|
||||
std::string repeat_state;
|
||||
bool shuffle_state;
|
||||
std::optional<Context> context;
|
||||
int timestamp;
|
||||
int progress_ms;
|
||||
bool is_playing;
|
||||
std::optional<Track> item;
|
||||
std::string currently_playing_type;
|
||||
|
||||
auto GetDevice() const -> const Device& { return device; }
|
||||
auto IsPlaying() const -> bool { return is_playing; }
|
||||
auto IsShuffled() const -> bool { return shuffle_state; }
|
||||
auto GetProgressMs() const -> int { return progress_ms; }
|
||||
auto GetCurrentTrack() const -> const std::optional<Track>&
|
||||
{
|
||||
return item;
|
||||
}
|
||||
|
||||
auto GetRepeatMode() const -> RepeatMode
|
||||
{
|
||||
return StringToRepeatMode(repeat_state);
|
||||
}
|
||||
|
||||
auto GetCurrentlyPlayingType() const -> CurrentlyPlayingType
|
||||
{
|
||||
return StringToCurrentlyPlayingType(currently_playing_type);
|
||||
}
|
||||
};
|
||||
} // namespace Spotify
|
||||
|
||||
// ============================================================================
|
||||
// Glaze Metadata
|
||||
// ============================================================================
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Device> {
|
||||
using T = Spotify::Device;
|
||||
static constexpr auto value = object(
|
||||
"id", &T::id,
|
||||
"is_active", &T::is_active,
|
||||
"is_private_session", &T::is_private_session,
|
||||
"is_restricted", &T::is_restricted,
|
||||
"name", &T::name,
|
||||
"type", &T::type,
|
||||
"volume_percent", &T::volume_percent
|
||||
);
|
||||
template <> struct glz::meta<Spotify::Device> {
|
||||
using T = Spotify::Device;
|
||||
static constexpr auto value = object(
|
||||
"id", &T::id, "is_active", &T::is_active, "is_private_session",
|
||||
&T::is_private_session, "is_restricted", &T::is_restricted, "name",
|
||||
&T::name, "type", &T::type, "volume_percent", &T::volume_percent);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Context> {
|
||||
using T = Spotify::Context;
|
||||
static constexpr auto value = object(
|
||||
"type", &T::type,
|
||||
"href", &T::href,
|
||||
"external_urls", &T::external_urls,
|
||||
"uri", &T::uri
|
||||
);
|
||||
template <> struct glz::meta<Spotify::Context> {
|
||||
using T = Spotify::Context;
|
||||
static constexpr auto value =
|
||||
object("type", &T::type, "href", &T::href, "external_urls",
|
||||
&T::external_urls, "uri", &T::uri);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::PlaybackState> {
|
||||
using T = Spotify::PlaybackState;
|
||||
static constexpr auto value = object(
|
||||
"device", &T::device,
|
||||
"repeat_state", &T::repeat_state,
|
||||
"shuffle_state", &T::shuffle_state,
|
||||
"context", &T::context,
|
||||
"timestamp", &T::timestamp,
|
||||
"progress_ms", &T::progress_ms,
|
||||
"is_playing", &T::is_playing,
|
||||
"item", &T::item,
|
||||
"currently_playing_type", &T::currently_playing_type
|
||||
);
|
||||
template <> struct glz::meta<Spotify::PlaybackState> {
|
||||
using T = Spotify::PlaybackState;
|
||||
static constexpr auto value =
|
||||
object("device", &T::device, "repeat_state", &T::repeat_state,
|
||||
"shuffle_state", &T::shuffle_state, "context", &T::context,
|
||||
"timestamp", &T::timestamp, "progress_ms", &T::progress_ms,
|
||||
"is_playing", &T::is_playing, "item", &T::item,
|
||||
"currently_playing_type", &T::currently_playing_type);
|
||||
};
|
||||
@@ -1,139 +1,121 @@
|
||||
#pragma once
|
||||
#include "Spotify/Types/Common.hpp"
|
||||
#include "Spotify/Types/Artist.hpp"
|
||||
#include "Spotify/Types/Common.hpp"
|
||||
#include "Spotify/Types/Track.hpp"
|
||||
|
||||
namespace Spotify {
|
||||
namespace Spotify
|
||||
{
|
||||
|
||||
// ============================================================================
|
||||
// Playlist Track
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Playlist Track
|
||||
// ============================================================================
|
||||
|
||||
struct PlaylistTrack {
|
||||
std::optional<std::string> added_at;
|
||||
std::optional<SimplifiedArtist> added_by;
|
||||
bool is_local;
|
||||
Track track;
|
||||
|
||||
auto GetTrack() const -> const Track& { return track; }
|
||||
auto GetAddedAt() const -> const std::optional<std::string>& { return added_at; }
|
||||
auto IsLocal() const -> bool { return is_local; }
|
||||
};
|
||||
struct PlaylistTrack {
|
||||
std::optional<std::string> added_at;
|
||||
std::optional<SimplifiedArtist> added_by;
|
||||
bool is_local;
|
||||
Track track;
|
||||
|
||||
// ============================================================================
|
||||
// Playlist Base
|
||||
// ============================================================================
|
||||
auto GetTrack() const -> const Track & { return track; }
|
||||
auto GetAddedAt() const -> const std::optional<std::string> &
|
||||
{
|
||||
return added_at;
|
||||
}
|
||||
auto IsLocal() const -> bool { return is_local; }
|
||||
};
|
||||
|
||||
class PlaylistBase {
|
||||
public:
|
||||
bool collaborative;
|
||||
std::optional<std::string> description;
|
||||
ExternalUrls external_urls;
|
||||
std::string href;
|
||||
std::string id;
|
||||
std::vector<Image> images;
|
||||
std::string name;
|
||||
SimplifiedArtist owner;
|
||||
bool public_playlist;
|
||||
std::optional<std::string> snapshot_id;
|
||||
std::string type;
|
||||
std::string uri;
|
||||
|
||||
virtual ~PlaylistBase() = default;
|
||||
|
||||
auto GetId() const -> const std::string& { return id; }
|
||||
auto GetName() const -> const std::string& { return name; }
|
||||
auto GetUri() const -> const std::string& { return uri; }
|
||||
auto GetOwner() const -> const SimplifiedArtist& { return owner; }
|
||||
auto IsPublic() const -> bool { return public_playlist; }
|
||||
auto IsCollaborative() const -> bool { return collaborative; }
|
||||
auto GetSnapshotId() const -> const std::optional<std::string>& { return snapshot_id; }
|
||||
};
|
||||
// ============================================================================
|
||||
// Playlist Base
|
||||
// ============================================================================
|
||||
|
||||
// ============================================================================
|
||||
// Simplified Playlist
|
||||
// ============================================================================
|
||||
class PlaylistBase
|
||||
{
|
||||
public:
|
||||
|
||||
struct SimplifiedPlaylist : PlaylistBase {
|
||||
struct TracksInfo {
|
||||
std::string href;
|
||||
int total;
|
||||
} tracks;
|
||||
|
||||
auto GetTotalTracks() const -> int { return tracks.total; }
|
||||
};
|
||||
bool collaborative;
|
||||
std::optional<std::string> description;
|
||||
ExternalUrls external_urls;
|
||||
std::string href;
|
||||
std::string id;
|
||||
std::vector<Image> images;
|
||||
std::string name;
|
||||
SimplifiedArtist owner;
|
||||
bool public_playlist;
|
||||
std::optional<std::string> snapshot_id;
|
||||
std::string type;
|
||||
std::string uri;
|
||||
|
||||
// ============================================================================
|
||||
// Full Playlist
|
||||
// ============================================================================
|
||||
virtual ~PlaylistBase() = default;
|
||||
|
||||
struct Playlist : PlaylistBase {
|
||||
Followers followers;
|
||||
|
||||
auto GetFollowers() const -> const Followers& { return followers; }
|
||||
};
|
||||
auto GetId() const -> const std::string & { return id; }
|
||||
auto GetName() const -> const std::string & { return name; }
|
||||
auto GetUri() const -> const std::string & { return uri; }
|
||||
auto GetOwner() const -> const SimplifiedArtist & { return owner; }
|
||||
auto IsPublic() const -> bool { return public_playlist; }
|
||||
auto IsCollaborative() const -> bool { return collaborative; }
|
||||
auto GetSnapshotId() const -> const std::optional<std::string> &
|
||||
{
|
||||
return snapshot_id;
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Simplified Playlist
|
||||
// ============================================================================
|
||||
|
||||
struct SimplifiedPlaylist : PlaylistBase {
|
||||
struct TracksInfo {
|
||||
std::string href;
|
||||
int total;
|
||||
} tracks;
|
||||
|
||||
auto GetTotalTracks() const -> int { return tracks.total; }
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Full Playlist
|
||||
// ============================================================================
|
||||
|
||||
struct Playlist : PlaylistBase {
|
||||
Followers followers;
|
||||
|
||||
auto GetFollowers() const -> const Followers & { return followers; }
|
||||
};
|
||||
} // namespace Spotify
|
||||
|
||||
// ============================================================================
|
||||
// Glaze Metadata
|
||||
// ============================================================================
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::PlaylistTrack> {
|
||||
using T = Spotify::PlaylistTrack;
|
||||
static constexpr auto value = object(
|
||||
"added_at", &T::added_at,
|
||||
"added_by", &T::added_by,
|
||||
"is_local", &T::is_local,
|
||||
"track", &T::track
|
||||
);
|
||||
template <> struct glz::meta<Spotify::PlaylistTrack> {
|
||||
using T = Spotify::PlaylistTrack;
|
||||
static constexpr auto value =
|
||||
object("added_at", &T::added_at, "added_by", &T::added_by,
|
||||
"is_local", &T::is_local, "track", &T::track);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::SimplifiedPlaylist::TracksInfo> {
|
||||
using T = Spotify::SimplifiedPlaylist::TracksInfo;
|
||||
static constexpr auto value = object(
|
||||
"href", &T::href,
|
||||
"total", &T::total
|
||||
);
|
||||
template <> struct glz::meta<Spotify::SimplifiedPlaylist::TracksInfo> {
|
||||
using T = Spotify::SimplifiedPlaylist::TracksInfo;
|
||||
static constexpr auto value =
|
||||
object("href", &T::href, "total", &T::total);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::SimplifiedPlaylist> {
|
||||
using T = Spotify::SimplifiedPlaylist;
|
||||
static constexpr auto value = object(
|
||||
"collaborative", &T::collaborative,
|
||||
"description", &T::description,
|
||||
"external_urls", &T::external_urls,
|
||||
"href", &T::href,
|
||||
"id", &T::id,
|
||||
"images", &T::images,
|
||||
"name", &T::name,
|
||||
"owner", &T::owner,
|
||||
"public", &T::public_playlist,
|
||||
"snapshot_id", &T::snapshot_id,
|
||||
"tracks", &T::tracks,
|
||||
"type", &T::type,
|
||||
"uri", &T::uri
|
||||
);
|
||||
template <> struct glz::meta<Spotify::SimplifiedPlaylist> {
|
||||
using T = Spotify::SimplifiedPlaylist;
|
||||
static constexpr auto value = object(
|
||||
"collaborative", &T::collaborative, "description", &T::description,
|
||||
"external_urls", &T::external_urls, "href", &T::href, "id", &T::id,
|
||||
"images", &T::images, "name", &T::name, "owner", &T::owner,
|
||||
"public", &T::public_playlist, "snapshot_id", &T::snapshot_id,
|
||||
"tracks", &T::tracks, "type", &T::type, "uri", &T::uri);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Playlist> {
|
||||
using T = Spotify::Playlist;
|
||||
static constexpr auto value = object(
|
||||
"collaborative", &T::collaborative,
|
||||
"description", &T::description,
|
||||
"external_urls", &T::external_urls,
|
||||
"followers", &T::followers,
|
||||
"href", &T::href,
|
||||
"id", &T::id,
|
||||
"images", &T::images,
|
||||
"name", &T::name,
|
||||
"owner", &T::owner,
|
||||
"public", &T::public_playlist,
|
||||
"snapshot_id", &T::snapshot_id,
|
||||
"type", &T::type,
|
||||
"uri", &T::uri
|
||||
);
|
||||
template <> struct glz::meta<Spotify::Playlist> {
|
||||
using T = Spotify::Playlist;
|
||||
static constexpr auto value = object(
|
||||
"collaborative", &T::collaborative, "description", &T::description,
|
||||
"external_urls", &T::external_urls, "followers", &T::followers,
|
||||
"href", &T::href, "id", &T::id, "images", &T::images, "name",
|
||||
&T::name, "owner", &T::owner, "public", &T::public_playlist,
|
||||
"snapshot_id", &T::snapshot_id, "type", &T::type, "uri", &T::uri);
|
||||
};
|
||||
@@ -1,318 +1,285 @@
|
||||
#pragma once
|
||||
#include "Spotify/Types/Common.hpp"
|
||||
#include "Spotify/Types/Artist.hpp"
|
||||
#include "Spotify/Types/Album.hpp"
|
||||
#include "Spotify/Types/Artist.hpp"
|
||||
#include "Spotify/Types/Common.hpp"
|
||||
|
||||
namespace Spotify {
|
||||
namespace Spotify
|
||||
{
|
||||
|
||||
// ============================================================================
|
||||
// Track Base
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Track Base
|
||||
// ============================================================================
|
||||
|
||||
class TrackBase {
|
||||
public:
|
||||
std::vector<SimplifiedArtist> artists;
|
||||
std::vector<std::string> available_markets;
|
||||
int disc_number;
|
||||
int duration_ms;
|
||||
bool explicit_content;
|
||||
ExternalUrls external_urls;
|
||||
std::string href;
|
||||
std::string id;
|
||||
bool is_playable;
|
||||
std::optional<std::string> linked_from;
|
||||
std::optional<Restrictions> restrictions;
|
||||
std::string name;
|
||||
std::optional<std::string> preview_url;
|
||||
int track_number;
|
||||
std::string type;
|
||||
std::string uri;
|
||||
bool is_local;
|
||||
|
||||
virtual ~TrackBase() = default;
|
||||
|
||||
auto GetId() const -> const std::string& { return id; }
|
||||
auto GetName() const -> const std::string& { return name; }
|
||||
auto GetUri() const -> const std::string& { return uri; }
|
||||
auto GetDurationMs() const -> int { return duration_ms; }
|
||||
auto GetTrackNumber() const -> int { return track_number; }
|
||||
auto IsExplicit() const -> bool { return explicit_content; }
|
||||
auto IsLocal() const -> bool { return is_local; }
|
||||
auto GetArtists() const -> const std::vector<SimplifiedArtist>& { return artists; }
|
||||
};
|
||||
class TrackBase
|
||||
{
|
||||
public:
|
||||
|
||||
// ============================================================================
|
||||
// Simplified Track
|
||||
// ============================================================================
|
||||
std::vector<SimplifiedArtist> artists;
|
||||
std::vector<std::string> available_markets;
|
||||
int disc_number;
|
||||
int duration_ms;
|
||||
bool explicit_content;
|
||||
ExternalUrls external_urls;
|
||||
std::string href;
|
||||
std::string id;
|
||||
bool is_playable;
|
||||
std::optional<std::string> linked_from;
|
||||
std::optional<Restrictions> restrictions;
|
||||
std::string name;
|
||||
std::optional<std::string> preview_url;
|
||||
int track_number;
|
||||
std::string type;
|
||||
std::string uri;
|
||||
bool is_local;
|
||||
|
||||
struct SimplifiedTrack : TrackBase {
|
||||
};
|
||||
virtual ~TrackBase() = default;
|
||||
|
||||
// ============================================================================
|
||||
// Full Track
|
||||
// ============================================================================
|
||||
auto GetId() const -> const std::string & { return id; }
|
||||
auto GetName() const -> const std::string & { return name; }
|
||||
auto GetUri() const -> const std::string & { return uri; }
|
||||
auto GetDurationMs() const -> int { return duration_ms; }
|
||||
auto GetTrackNumber() const -> int { return track_number; }
|
||||
auto IsExplicit() const -> bool { return explicit_content; }
|
||||
auto IsLocal() const -> bool { return is_local; }
|
||||
auto GetArtists() const -> const std::vector<SimplifiedArtist> &
|
||||
{
|
||||
return artists;
|
||||
}
|
||||
};
|
||||
|
||||
struct Track : TrackBase {
|
||||
SimplifiedAlbum album;
|
||||
ExternalIds external_ids;
|
||||
int popularity;
|
||||
|
||||
auto GetAlbum() const -> const SimplifiedAlbum& { return album; }
|
||||
auto GetPopularity() const -> int { return popularity; }
|
||||
};
|
||||
// ============================================================================
|
||||
// Simplified Track
|
||||
// ============================================================================
|
||||
|
||||
// ============================================================================
|
||||
// Saved Track
|
||||
// ============================================================================
|
||||
struct SimplifiedTrack : TrackBase {
|
||||
};
|
||||
|
||||
struct SavedTrack {
|
||||
std::string added_at;
|
||||
Track track;
|
||||
|
||||
auto GetTrack() const -> const Track& { return track; }
|
||||
auto GetAddedAt() const -> const std::string& { return added_at; }
|
||||
};
|
||||
// ============================================================================
|
||||
// Full Track
|
||||
// ============================================================================
|
||||
|
||||
// ============================================================================
|
||||
// Audio Features
|
||||
// ============================================================================
|
||||
struct Track : TrackBase {
|
||||
SimplifiedAlbum album;
|
||||
ExternalIds external_ids;
|
||||
int popularity;
|
||||
|
||||
enum class MusicalKey {
|
||||
C = 0, CSharp = 1, D = 2, DSharp = 3,
|
||||
E = 4, F = 5, FSharp = 6, G = 7,
|
||||
GSharp = 8, A = 9, ASharp = 10, B = 11
|
||||
};
|
||||
auto GetAlbum() const -> const SimplifiedAlbum & { return album; }
|
||||
auto GetPopularity() const -> int { return popularity; }
|
||||
};
|
||||
|
||||
enum class MusicalMode {
|
||||
Minor = 0,
|
||||
Major = 1
|
||||
};
|
||||
// ============================================================================
|
||||
// Saved Track
|
||||
// ============================================================================
|
||||
|
||||
struct AudioFeatures {
|
||||
float acousticness;
|
||||
std::string analysis_url;
|
||||
float danceability;
|
||||
int duration_ms;
|
||||
float energy;
|
||||
std::string id;
|
||||
float instrumentalness;
|
||||
int key;
|
||||
float liveness;
|
||||
float loudness;
|
||||
int mode;
|
||||
float speechiness;
|
||||
float tempo;
|
||||
int time_signature;
|
||||
std::string track_href;
|
||||
std::string type;
|
||||
std::string uri;
|
||||
float valence;
|
||||
|
||||
auto GetKey() const -> MusicalKey { return static_cast<MusicalKey>(key); }
|
||||
auto GetMode() const -> MusicalMode { return static_cast<MusicalMode>(mode); }
|
||||
auto GetAcousticness() const -> float { return acousticness; }
|
||||
auto GetDanceability() const -> float { return danceability; }
|
||||
auto GetEnergy() const -> float { return energy; }
|
||||
auto GetValence() const -> float { return valence; }
|
||||
auto GetTempo() const -> float { return tempo; }
|
||||
};
|
||||
struct SavedTrack {
|
||||
std::string added_at;
|
||||
Track track;
|
||||
|
||||
// ============================================================================
|
||||
// Audio Analysis
|
||||
// ============================================================================
|
||||
auto GetTrack() const -> const Track & { return track; }
|
||||
auto GetAddedAt() const -> const std::string & { return added_at; }
|
||||
};
|
||||
|
||||
struct TimeInterval {
|
||||
float start;
|
||||
float duration;
|
||||
float confidence;
|
||||
};
|
||||
// ============================================================================
|
||||
// Audio Features
|
||||
// ============================================================================
|
||||
|
||||
struct Section {
|
||||
float start;
|
||||
float duration;
|
||||
float confidence;
|
||||
float loudness;
|
||||
float tempo;
|
||||
float tempo_confidence;
|
||||
int key;
|
||||
float key_confidence;
|
||||
int mode;
|
||||
float mode_confidence;
|
||||
int time_signature;
|
||||
float time_signature_confidence;
|
||||
};
|
||||
enum class MusicalKey {
|
||||
C = 0,
|
||||
CSharp = 1,
|
||||
D = 2,
|
||||
DSharp = 3,
|
||||
E = 4,
|
||||
F = 5,
|
||||
FSharp = 6,
|
||||
G = 7,
|
||||
GSharp = 8,
|
||||
A = 9,
|
||||
ASharp = 10,
|
||||
B = 11
|
||||
};
|
||||
|
||||
struct Segment {
|
||||
float start;
|
||||
float duration;
|
||||
float confidence;
|
||||
float loudness_start;
|
||||
float loudness_max;
|
||||
float loudness_max_time;
|
||||
float loudness_end;
|
||||
std::vector<float> pitches;
|
||||
std::vector<float> timbre;
|
||||
};
|
||||
enum class MusicalMode { Minor = 0, Major = 1 };
|
||||
|
||||
struct AudioAnalysis {
|
||||
std::vector<TimeInterval> bars;
|
||||
std::vector<TimeInterval> beats;
|
||||
std::vector<Section> sections;
|
||||
std::vector<Segment> segments;
|
||||
std::vector<TimeInterval> tatums;
|
||||
|
||||
auto GetBars() const -> const std::vector<TimeInterval>& { return bars; }
|
||||
auto GetBeats() const -> const std::vector<TimeInterval>& { return beats; }
|
||||
auto GetSections() const -> const std::vector<Section>& { return sections; }
|
||||
};
|
||||
struct AudioFeatures {
|
||||
float acousticness;
|
||||
std::string analysis_url;
|
||||
float danceability;
|
||||
int duration_ms;
|
||||
float energy;
|
||||
std::string id;
|
||||
float instrumentalness;
|
||||
int key;
|
||||
float liveness;
|
||||
float loudness;
|
||||
int mode;
|
||||
float speechiness;
|
||||
float tempo;
|
||||
int time_signature;
|
||||
std::string track_href;
|
||||
std::string type;
|
||||
std::string uri;
|
||||
float valence;
|
||||
|
||||
struct TracksResponse {
|
||||
std::vector<Track> tracks;
|
||||
};
|
||||
auto GetKey() const -> MusicalKey
|
||||
{
|
||||
return static_cast<MusicalKey>(key);
|
||||
}
|
||||
auto GetMode() const -> MusicalMode
|
||||
{
|
||||
return static_cast<MusicalMode>(mode);
|
||||
}
|
||||
auto GetAcousticness() const -> float { return acousticness; }
|
||||
auto GetDanceability() const -> float { return danceability; }
|
||||
auto GetEnergy() const -> float { return energy; }
|
||||
auto GetValence() const -> float { return valence; }
|
||||
auto GetTempo() const -> float { return tempo; }
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Audio Analysis
|
||||
// ============================================================================
|
||||
|
||||
struct TimeInterval {
|
||||
float start;
|
||||
float duration;
|
||||
float confidence;
|
||||
};
|
||||
|
||||
struct Section {
|
||||
float start;
|
||||
float duration;
|
||||
float confidence;
|
||||
float loudness;
|
||||
float tempo;
|
||||
float tempo_confidence;
|
||||
int key;
|
||||
float key_confidence;
|
||||
int mode;
|
||||
float mode_confidence;
|
||||
int time_signature;
|
||||
float time_signature_confidence;
|
||||
};
|
||||
|
||||
struct Segment {
|
||||
float start;
|
||||
float duration;
|
||||
float confidence;
|
||||
float loudness_start;
|
||||
float loudness_max;
|
||||
float loudness_max_time;
|
||||
float loudness_end;
|
||||
std::vector<float> pitches;
|
||||
std::vector<float> timbre;
|
||||
};
|
||||
|
||||
struct AudioAnalysis {
|
||||
std::vector<TimeInterval> bars;
|
||||
std::vector<TimeInterval> beats;
|
||||
std::vector<Section> sections;
|
||||
std::vector<Segment> segments;
|
||||
std::vector<TimeInterval> tatums;
|
||||
|
||||
auto GetBars() const -> const std::vector<TimeInterval> &
|
||||
{
|
||||
return bars;
|
||||
}
|
||||
auto GetBeats() const -> const std::vector<TimeInterval> &
|
||||
{
|
||||
return beats;
|
||||
}
|
||||
auto GetSections() const -> const std::vector<Section> &
|
||||
{
|
||||
return sections;
|
||||
}
|
||||
};
|
||||
|
||||
struct TracksResponse {
|
||||
std::vector<Track> tracks;
|
||||
};
|
||||
} // namespace Spotify
|
||||
|
||||
// ============================================================================
|
||||
// Glaze Metadata
|
||||
// ============================================================================
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::SimplifiedTrack> {
|
||||
using T = Spotify::SimplifiedTrack;
|
||||
static constexpr auto value = object(
|
||||
"artists", &T::artists,
|
||||
"available_markets", &T::available_markets,
|
||||
"disc_number", &T::disc_number,
|
||||
"duration_ms", &T::duration_ms,
|
||||
"explicit", &T::explicit_content,
|
||||
"external_urls", &T::external_urls,
|
||||
"href", &T::href,
|
||||
"id", &T::id,
|
||||
"is_playable", &T::is_playable,
|
||||
"linked_from", &T::linked_from,
|
||||
"restrictions", &T::restrictions,
|
||||
"name", &T::name,
|
||||
"preview_url", &T::preview_url,
|
||||
"track_number", &T::track_number,
|
||||
"type", &T::type,
|
||||
"uri", &T::uri,
|
||||
"is_local", &T::is_local
|
||||
);
|
||||
template <> struct glz::meta<Spotify::SimplifiedTrack> {
|
||||
using T = Spotify::SimplifiedTrack;
|
||||
static constexpr auto value = object(
|
||||
"artists", &T::artists, "available_markets", &T::available_markets,
|
||||
"disc_number", &T::disc_number, "duration_ms", &T::duration_ms,
|
||||
"explicit", &T::explicit_content, "external_urls",
|
||||
&T::external_urls, "href", &T::href, "id", &T::id, "is_playable",
|
||||
&T::is_playable, "linked_from", &T::linked_from, "restrictions",
|
||||
&T::restrictions, "name", &T::name, "preview_url", &T::preview_url,
|
||||
"track_number", &T::track_number, "type", &T::type, "uri", &T::uri,
|
||||
"is_local", &T::is_local);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Track> {
|
||||
using T = Spotify::Track;
|
||||
static constexpr auto value = object(
|
||||
"album", &T::album,
|
||||
"artists", &T::artists,
|
||||
"available_markets", &T::available_markets,
|
||||
"disc_number", &T::disc_number,
|
||||
"duration_ms", &T::duration_ms,
|
||||
"explicit", &T::explicit_content,
|
||||
"external_ids", &T::external_ids,
|
||||
"external_urls", &T::external_urls,
|
||||
"href", &T::href,
|
||||
"id", &T::id,
|
||||
"is_playable", &T::is_playable,
|
||||
"linked_from", &T::linked_from,
|
||||
"restrictions", &T::restrictions,
|
||||
"name", &T::name,
|
||||
"popularity", &T::popularity,
|
||||
"preview_url", &T::preview_url,
|
||||
"track_number", &T::track_number,
|
||||
"type", &T::type,
|
||||
"uri", &T::uri,
|
||||
"is_local", &T::is_local
|
||||
);
|
||||
template <> struct glz::meta<Spotify::Track> {
|
||||
using T = Spotify::Track;
|
||||
static constexpr auto value = object(
|
||||
"album", &T::album, "artists", &T::artists, "available_markets",
|
||||
&T::available_markets, "disc_number", &T::disc_number,
|
||||
"duration_ms", &T::duration_ms, "explicit", &T::explicit_content,
|
||||
"external_ids", &T::external_ids, "external_urls",
|
||||
&T::external_urls, "href", &T::href, "id", &T::id, "is_playable",
|
||||
&T::is_playable, "linked_from", &T::linked_from, "restrictions",
|
||||
&T::restrictions, "name", &T::name, "popularity", &T::popularity,
|
||||
"preview_url", &T::preview_url, "track_number", &T::track_number,
|
||||
"type", &T::type, "uri", &T::uri, "is_local", &T::is_local);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::SavedTrack> {
|
||||
using T = Spotify::SavedTrack;
|
||||
static constexpr auto value = object(
|
||||
"added_at", &T::added_at,
|
||||
"track", &T::track
|
||||
);
|
||||
template <> struct glz::meta<Spotify::SavedTrack> {
|
||||
using T = Spotify::SavedTrack;
|
||||
static constexpr auto value =
|
||||
object("added_at", &T::added_at, "track", &T::track);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::AudioFeatures> {
|
||||
using T = Spotify::AudioFeatures;
|
||||
static constexpr auto value = object(
|
||||
"acousticness", &T::acousticness,
|
||||
"analysis_url", &T::analysis_url,
|
||||
"danceability", &T::danceability,
|
||||
"duration_ms", &T::duration_ms,
|
||||
"energy", &T::energy,
|
||||
"id", &T::id,
|
||||
"instrumentalness", &T::instrumentalness,
|
||||
"key", &T::key,
|
||||
"liveness", &T::liveness,
|
||||
"loudness", &T::loudness,
|
||||
"mode", &T::mode,
|
||||
"speechiness", &T::speechiness,
|
||||
"tempo", &T::tempo,
|
||||
"time_signature", &T::time_signature,
|
||||
"track_href", &T::track_href,
|
||||
"type", &T::type,
|
||||
"uri", &T::uri,
|
||||
"valence", &T::valence
|
||||
);
|
||||
template <> struct glz::meta<Spotify::AudioFeatures> {
|
||||
using T = Spotify::AudioFeatures;
|
||||
static constexpr auto value = object(
|
||||
"acousticness", &T::acousticness, "analysis_url", &T::analysis_url,
|
||||
"danceability", &T::danceability, "duration_ms", &T::duration_ms,
|
||||
"energy", &T::energy, "id", &T::id, "instrumentalness",
|
||||
&T::instrumentalness, "key", &T::key, "liveness", &T::liveness,
|
||||
"loudness", &T::loudness, "mode", &T::mode, "speechiness",
|
||||
&T::speechiness, "tempo", &T::tempo, "time_signature",
|
||||
&T::time_signature, "track_href", &T::track_href, "type", &T::type,
|
||||
"uri", &T::uri, "valence", &T::valence);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::TimeInterval> {
|
||||
using T = Spotify::TimeInterval;
|
||||
static constexpr auto value = object(
|
||||
"start", &T::start,
|
||||
"duration", &T::duration,
|
||||
"confidence", &T::confidence
|
||||
);
|
||||
template <> struct glz::meta<Spotify::TimeInterval> {
|
||||
using T = Spotify::TimeInterval;
|
||||
static constexpr auto value =
|
||||
object("start", &T::start, "duration", &T::duration, "confidence",
|
||||
&T::confidence);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Section> {
|
||||
using T = Spotify::Section;
|
||||
static constexpr auto value = object(
|
||||
"start", &T::start,
|
||||
"duration", &T::duration,
|
||||
"confidence", &T::confidence,
|
||||
"loudness", &T::loudness,
|
||||
"tempo", &T::tempo,
|
||||
"tempo_confidence", &T::tempo_confidence,
|
||||
"key", &T::key,
|
||||
"key_confidence", &T::key_confidence,
|
||||
"mode", &T::mode,
|
||||
"mode_confidence", &T::mode_confidence,
|
||||
"time_signature", &T::time_signature,
|
||||
"time_signature_confidence", &T::time_signature_confidence
|
||||
);
|
||||
template <> struct glz::meta<Spotify::Section> {
|
||||
using T = Spotify::Section;
|
||||
static constexpr auto value =
|
||||
object("start", &T::start, "duration", &T::duration, "confidence",
|
||||
&T::confidence, "loudness", &T::loudness, "tempo", &T::tempo,
|
||||
"tempo_confidence", &T::tempo_confidence, "key", &T::key,
|
||||
"key_confidence", &T::key_confidence, "mode", &T::mode,
|
||||
"mode_confidence", &T::mode_confidence, "time_signature",
|
||||
&T::time_signature, "time_signature_confidence",
|
||||
&T::time_signature_confidence);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Segment> {
|
||||
using T = Spotify::Segment;
|
||||
static constexpr auto value = object(
|
||||
"start", &T::start,
|
||||
"duration", &T::duration,
|
||||
"confidence", &T::confidence,
|
||||
"loudness_start", &T::loudness_start,
|
||||
"loudness_max", &T::loudness_max,
|
||||
"loudness_max_time", &T::loudness_max_time,
|
||||
"loudness_end", &T::loudness_end,
|
||||
"pitches", &T::pitches,
|
||||
"timbre", &T::timbre
|
||||
);
|
||||
template <> struct glz::meta<Spotify::Segment> {
|
||||
using T = Spotify::Segment;
|
||||
static constexpr auto value =
|
||||
object("start", &T::start, "duration", &T::duration, "confidence",
|
||||
&T::confidence, "loudness_start", &T::loudness_start,
|
||||
"loudness_max", &T::loudness_max, "loudness_max_time",
|
||||
&T::loudness_max_time, "loudness_end", &T::loudness_end,
|
||||
"pitches", &T::pitches, "timbre", &T::timbre);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::AudioAnalysis> {
|
||||
using T = Spotify::AudioAnalysis;
|
||||
static constexpr auto value = object(
|
||||
"bars", &T::bars,
|
||||
"beats", &T::beats,
|
||||
"sections", &T::sections,
|
||||
"segments", &T::segments,
|
||||
"tatums", &T::tatums
|
||||
);
|
||||
template <> struct glz::meta<Spotify::AudioAnalysis> {
|
||||
using T = Spotify::AudioAnalysis;
|
||||
static constexpr auto value = object(
|
||||
"bars", &T::bars, "beats", &T::beats, "sections", &T::sections,
|
||||
"segments", &T::segments, "tatums", &T::tatums);
|
||||
};
|
||||
@@ -1,77 +1,81 @@
|
||||
#pragma once
|
||||
#include "Spotify/Types/Common.hpp"
|
||||
|
||||
namespace Spotify {
|
||||
namespace Spotify
|
||||
{
|
||||
|
||||
// ============================================================================
|
||||
// User Product Type
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// User Product Type
|
||||
// ============================================================================
|
||||
|
||||
enum class Product {
|
||||
Premium,
|
||||
Free,
|
||||
Open,
|
||||
Unknown
|
||||
};
|
||||
enum class Product { Premium, Free, Open, Unknown };
|
||||
|
||||
inline auto StringToProductType(const std::string& str) -> Product {
|
||||
if (str == "premium") return Product::Premium;
|
||||
if (str == "free") return Product::Free;
|
||||
if (str == "open") return Product::Open;
|
||||
return Product::Unknown;
|
||||
}
|
||||
inline auto StringToProductType(const std::string& str) -> Product
|
||||
{
|
||||
if (str == "premium") {
|
||||
return Product::Premium;
|
||||
}
|
||||
if (str == "free") {
|
||||
return Product::Free;
|
||||
}
|
||||
if (str == "open") {
|
||||
return Product::Open;
|
||||
}
|
||||
return Product::Unknown;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// User
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// User
|
||||
// ============================================================================
|
||||
|
||||
struct User {
|
||||
std::optional<std::string> country;
|
||||
std::optional<std::string> display_name;
|
||||
std::optional<std::string> email;
|
||||
std::optional<ExternalUrls> external_urls;
|
||||
std::optional<Followers> followers;
|
||||
std::string href;
|
||||
std::string id;
|
||||
std::optional<std::vector<Image>> images;
|
||||
std::optional<std::string> product;
|
||||
std::string type;
|
||||
std::string uri;
|
||||
|
||||
auto GetId() const -> const std::string& { return id; }
|
||||
auto GetDisplayName() const -> const std::optional<std::string>& { return display_name; }
|
||||
auto GetEmail() const -> const std::optional<std::string>& { return email; }
|
||||
auto GetUri() const -> const std::string& { return uri; }
|
||||
|
||||
auto GetProductType() const -> Product {
|
||||
if (!product) return Product::Unknown;
|
||||
return StringToProductType(*product);
|
||||
}
|
||||
|
||||
auto IsPremium() const -> bool {
|
||||
return GetProductType() == Product::Premium;
|
||||
}
|
||||
};
|
||||
struct User {
|
||||
std::optional<std::string> country;
|
||||
std::optional<std::string> display_name;
|
||||
std::optional<std::string> email;
|
||||
std::optional<ExternalUrls> external_urls;
|
||||
std::optional<Followers> followers;
|
||||
std::string href;
|
||||
std::string id;
|
||||
std::optional<std::vector<Image>> images;
|
||||
std::optional<std::string> product;
|
||||
std::string type;
|
||||
std::string uri;
|
||||
|
||||
auto GetId() const -> const std::string& { return id; }
|
||||
auto GetDisplayName() const -> const std::optional<std::string>&
|
||||
{
|
||||
return display_name;
|
||||
}
|
||||
auto GetEmail() const -> const std::optional<std::string>&
|
||||
{
|
||||
return email;
|
||||
}
|
||||
auto GetUri() const -> const std::string& { return uri; }
|
||||
|
||||
auto GetProductType() const -> Product
|
||||
{
|
||||
if (!product) {
|
||||
return Product::Unknown;
|
||||
}
|
||||
return StringToProductType(*product);
|
||||
}
|
||||
|
||||
auto IsPremium() const -> bool
|
||||
{
|
||||
return GetProductType() == Product::Premium;
|
||||
}
|
||||
};
|
||||
} // namespace Spotify
|
||||
|
||||
// ============================================================================
|
||||
// Glaze Metadata
|
||||
// ============================================================================
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::User> {
|
||||
using T = Spotify::User;
|
||||
static constexpr auto value = object(
|
||||
"country", &T::country,
|
||||
"display_name", &T::display_name,
|
||||
"email", &T::email,
|
||||
"external_urls", &T::external_urls,
|
||||
"followers", &T::followers,
|
||||
"href", &T::href,
|
||||
"id", &T::id,
|
||||
"images", &T::images,
|
||||
"product", &T::product,
|
||||
"type", &T::type,
|
||||
"uri", &T::uri
|
||||
);
|
||||
template <> struct glz::meta<Spotify::User> {
|
||||
using T = Spotify::User;
|
||||
static constexpr auto value = object(
|
||||
"country", &T::country, "display_name", &T::display_name, "email",
|
||||
&T::email, "external_urls", &T::external_urls, "followers",
|
||||
&T::followers, "href", &T::href, "id", &T::id, "images", &T::images,
|
||||
"product", &T::product, "type", &T::type, "uri", &T::uri);
|
||||
};
|
||||
+270
-248
@@ -14,290 +14,312 @@
|
||||
#include <glaze/glaze.hpp> // Assumed available per your reference
|
||||
#include <quickjs.h>
|
||||
// Project (Assuming similar structure to your Spotify bot)
|
||||
#include <ts6bot/Proxy.hpp>
|
||||
#include <Logger.hpp>
|
||||
#include <PluginDefinitions.hpp>
|
||||
#include <ts6bot/Proxy.hpp>
|
||||
|
||||
namespace YouTube {
|
||||
namespace YouTube
|
||||
{
|
||||
|
||||
// ============================================================================
|
||||
// Data Types (Simplified for immediate usage)
|
||||
// ============================================================================
|
||||
// ============================================================================
|
||||
// Data Types (Simplified for immediate usage)
|
||||
// ============================================================================
|
||||
|
||||
struct Thumbnail {
|
||||
std::string url;
|
||||
int width;
|
||||
int height;
|
||||
};
|
||||
struct Thumbnail {
|
||||
std::string url;
|
||||
int width;
|
||||
int height;
|
||||
};
|
||||
|
||||
struct Snippet {
|
||||
std::string publishedAt;
|
||||
std::string channelId;
|
||||
std::string title;
|
||||
std::string description;
|
||||
std::string channelTitle;
|
||||
std::map<std::string, Thumbnail> thumbnails;
|
||||
std::string liveBroadcastContent;
|
||||
std::string publishTime;
|
||||
};
|
||||
struct PlayListResourceId {
|
||||
std::string kind;
|
||||
std::string videoId;
|
||||
};
|
||||
struct PlayListSnippet{
|
||||
std::string publishedAt;
|
||||
std::string channelId;
|
||||
std::string title;
|
||||
std::string description;
|
||||
std::map<std::string, Thumbnail> thumbnails;
|
||||
std::string channelTitle;
|
||||
std::string playlistId;
|
||||
int position;
|
||||
PlayListResourceId resourceId;
|
||||
std::string videoOwnerChannelTitle;
|
||||
std::string videoOwnerChannelId;
|
||||
};
|
||||
struct Snippet {
|
||||
std::string publishedAt;
|
||||
std::string channelId;
|
||||
std::string title;
|
||||
std::string description;
|
||||
std::string channelTitle;
|
||||
std::map<std::string, Thumbnail> thumbnails;
|
||||
std::string liveBroadcastContent;
|
||||
std::string publishTime;
|
||||
};
|
||||
struct PlayListResourceId {
|
||||
std::string kind;
|
||||
std::string videoId;
|
||||
};
|
||||
struct PlayListSnippet {
|
||||
std::string publishedAt;
|
||||
std::string channelId;
|
||||
std::string title;
|
||||
std::string description;
|
||||
std::map<std::string, Thumbnail> thumbnails;
|
||||
std::string channelTitle;
|
||||
std::string playlistId;
|
||||
int position;
|
||||
PlayListResourceId resourceId;
|
||||
std::string videoOwnerChannelTitle;
|
||||
std::string videoOwnerChannelId;
|
||||
};
|
||||
|
||||
struct ResourceId {
|
||||
std::string kind;
|
||||
std::string videoId;
|
||||
std::string channelId;
|
||||
std::string playlistId;
|
||||
};
|
||||
struct ResourceId {
|
||||
std::string kind;
|
||||
std::string videoId;
|
||||
std::string channelId;
|
||||
std::string playlistId;
|
||||
};
|
||||
|
||||
// Search results use a wrapper for ID, Videos use a string ID
|
||||
struct SearchResultId {
|
||||
std::string kind;
|
||||
std::string videoId;
|
||||
std::string channelId;
|
||||
std::string playlistId;
|
||||
};
|
||||
// Search results use a wrapper for ID, Videos use a string ID
|
||||
struct SearchResultId {
|
||||
std::string kind;
|
||||
std::string videoId;
|
||||
std::string channelId;
|
||||
std::string playlistId;
|
||||
};
|
||||
|
||||
struct VideoContentDetails {
|
||||
std::string duration;
|
||||
std::string dimension;
|
||||
std::string definition;
|
||||
};
|
||||
struct VideoContentDetails {
|
||||
std::string duration;
|
||||
std::string dimension;
|
||||
std::string definition;
|
||||
};
|
||||
|
||||
struct VideoStatistics {
|
||||
std::string viewCount;
|
||||
std::string likeCount;
|
||||
std::string commentCount;
|
||||
};
|
||||
struct VideoStatistics {
|
||||
std::string viewCount;
|
||||
std::string likeCount;
|
||||
std::string commentCount;
|
||||
};
|
||||
|
||||
// Main Resource Types
|
||||
struct Video {
|
||||
std::string kind;
|
||||
std::string id;
|
||||
Snippet snippet;
|
||||
VideoContentDetails contentDetails;
|
||||
VideoStatistics statistics;
|
||||
};
|
||||
// Main Resource Types
|
||||
struct Video {
|
||||
std::string kind;
|
||||
std::string id;
|
||||
Snippet snippet;
|
||||
VideoContentDetails contentDetails;
|
||||
VideoStatistics statistics;
|
||||
};
|
||||
|
||||
struct SearchResult {
|
||||
std::string kind;
|
||||
std::string etag;
|
||||
SearchResultId id;
|
||||
Snippet snippet;
|
||||
};
|
||||
struct SearchResult {
|
||||
std::string kind;
|
||||
std::string etag;
|
||||
SearchResultId id;
|
||||
Snippet snippet;
|
||||
};
|
||||
|
||||
struct SearchPlaylistResult {
|
||||
std::string kind;
|
||||
std::string etag;
|
||||
std::string id;
|
||||
PlayListSnippet snippet;
|
||||
};
|
||||
struct SearchPlaylistResult {
|
||||
std::string kind;
|
||||
std::string etag;
|
||||
std::string id;
|
||||
PlayListSnippet snippet;
|
||||
};
|
||||
|
||||
// API Response Wrappers
|
||||
template <typename T> struct PageResult {
|
||||
std::string kind;
|
||||
std::string etag;
|
||||
std::string nextPageToken;
|
||||
std::string prevPageToken;
|
||||
std::string regionCode;
|
||||
struct PageInfo {
|
||||
int totalResults;
|
||||
int resultsPerPage;
|
||||
} pageInfo;
|
||||
std::vector<T> items;
|
||||
};
|
||||
// ============================================================================
|
||||
// InnerTube (Player) Data Types
|
||||
// ============================================================================
|
||||
// API Response Wrappers
|
||||
template <typename T> struct PageResult {
|
||||
std::string kind;
|
||||
std::string etag;
|
||||
std::string nextPageToken;
|
||||
std::string prevPageToken;
|
||||
std::string regionCode;
|
||||
struct PageInfo {
|
||||
int totalResults;
|
||||
int resultsPerPage;
|
||||
} pageInfo;
|
||||
std::vector<T> items;
|
||||
};
|
||||
// ============================================================================
|
||||
// InnerTube (Player) Data Types
|
||||
// ============================================================================
|
||||
|
||||
struct AudioFormat {
|
||||
int itag;
|
||||
std::string url; // Direct URL (if unencrypted)
|
||||
std::string signatureCipher; // Encrypted signature (if present, url is empty)
|
||||
std::string mimeType;
|
||||
int bitrate;
|
||||
std::string qualityLabel;
|
||||
};
|
||||
struct AudioFormat {
|
||||
int itag;
|
||||
std::string url; // Direct URL (if unencrypted)
|
||||
std::string signatureCipher; // Encrypted signature (if present, url
|
||||
// is empty)
|
||||
std::string mimeType;
|
||||
int bitrate;
|
||||
std::string qualityLabel;
|
||||
};
|
||||
|
||||
struct StreamingData {
|
||||
std::string expiresInSeconds;
|
||||
std::vector<AudioFormat> formats; // Mixed video+audio
|
||||
std::vector<AudioFormat>
|
||||
adaptiveFormats; // Separate streams (we want audio from here)
|
||||
};
|
||||
struct StreamingData {
|
||||
std::string expiresInSeconds;
|
||||
std::vector<AudioFormat> formats; // Mixed video+audio
|
||||
std::vector<AudioFormat>
|
||||
adaptiveFormats; // Separate streams (we want audio from here)
|
||||
};
|
||||
|
||||
struct PlayerResponse {
|
||||
StreamingData streamingData;
|
||||
// ... other fields like playabilityStatus ignored for brevity
|
||||
};
|
||||
// ============================================================================
|
||||
// Error Handling
|
||||
// ============================================================================
|
||||
struct PlayerResponse {
|
||||
StreamingData streamingData;
|
||||
// ... other fields like playabilityStatus ignored for brevity
|
||||
};
|
||||
// ============================================================================
|
||||
// Error Handling
|
||||
// ============================================================================
|
||||
|
||||
struct ApiError {
|
||||
int status;
|
||||
std::string message;
|
||||
std::string reason;
|
||||
};
|
||||
struct GoogleError {
|
||||
struct Inner {
|
||||
int code;
|
||||
std::string message;
|
||||
} error;
|
||||
};
|
||||
template <typename T> using Result = std::expected<T, ApiError>;
|
||||
// ============================================================================
|
||||
// Request Parameters
|
||||
// ============================================================================
|
||||
struct ApiError {
|
||||
int status;
|
||||
std::string message;
|
||||
std::string reason;
|
||||
};
|
||||
struct GoogleError {
|
||||
struct Inner {
|
||||
int code;
|
||||
std::string message;
|
||||
} error;
|
||||
};
|
||||
template <typename T> using Result = std::expected<T, ApiError>;
|
||||
// ============================================================================
|
||||
// Request Parameters
|
||||
// ============================================================================
|
||||
|
||||
struct SearchParams {
|
||||
std::string q;
|
||||
std::vector<std::string> type = {"video"}; // video, channel, playlist
|
||||
std::string part = "snippet";
|
||||
int maxResults = 5;
|
||||
std::string order = "relevance";
|
||||
std::string pageToken = "";
|
||||
std::string videoDuration = "any"; // any, long, medium, short
|
||||
bool rawQuery = false; // Set to true to preserve -, |, etc. in query
|
||||
};
|
||||
struct ShortenResponse {
|
||||
std::string shortUrl;
|
||||
};
|
||||
// ============================================================================
|
||||
// Main YouTube Client
|
||||
// ============================================================================
|
||||
struct SearchParams {
|
||||
std::string q;
|
||||
std::vector<std::string> type = {
|
||||
"video"}; // video, channel, playlist
|
||||
std::string part = "snippet";
|
||||
int maxResults = 5;
|
||||
std::string order = "relevance";
|
||||
std::string pageToken = "";
|
||||
std::string videoDuration = "any"; // any, long, medium, short
|
||||
bool rawQuery =
|
||||
false; // Set to true to preserve -, |, etc. in query
|
||||
};
|
||||
struct ShortenResponse {
|
||||
std::string shortUrl;
|
||||
};
|
||||
// ============================================================================
|
||||
// Main YouTube Client
|
||||
// ============================================================================
|
||||
|
||||
struct CurlDeleter {
|
||||
void operator()(CURL *ptr) const {
|
||||
if (ptr)
|
||||
curl_easy_cleanup(ptr);
|
||||
}
|
||||
};
|
||||
struct CurlDeleter {
|
||||
void operator()(CURL *ptr) const
|
||||
{
|
||||
if (ptr) {
|
||||
curl_easy_cleanup(ptr);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
enum class HttpMethod { GET, POST, PUT, DELETE };
|
||||
enum class HttpMethod { GET, POST, PUT, DELETE };
|
||||
|
||||
class Client {
|
||||
public:
|
||||
// YouTube typically uses API Keys for public data, OAuth for user data.
|
||||
// Pass "" as accessToken if only using API Key.
|
||||
Client(std::string apiKey, std::string accessToken = "");
|
||||
~Client();
|
||||
auto GetBestStreams(const std::string &videoId)
|
||||
-> Result<::definitions::Streams>; // Configuration
|
||||
void SetVerbose(bool verbose) { m_Verbose = verbose; }
|
||||
void SetProxy(ProxyConfig config) { m_Proxy = std::move(config); }
|
||||
void SetAccessToken(std::string token) { m_AccessToken = std::move(token); }
|
||||
void SetApiKey(std::string key) { m_ApiKey = std::move(key); }
|
||||
class Client
|
||||
{
|
||||
public:
|
||||
|
||||
auto ShortUrl(const std::string& url) const -> Result<std::string>;
|
||||
// YouTube typically uses API Keys for public data, OAuth for user
|
||||
// data. Pass "" as accessToken if only using API Key.
|
||||
Client(std::string apiKey, std::string accessToken = "");
|
||||
~Client();
|
||||
auto GetBestStreams(const std::string &videoId)
|
||||
-> Result<::definitions::Streams>; // Configuration
|
||||
void SetVerbose(bool verbose) { m_Verbose = verbose; }
|
||||
void SetProxy(ProxyConfig config) { m_Proxy = std::move(config); }
|
||||
void SetAccessToken(std::string token)
|
||||
{
|
||||
m_AccessToken = std::move(token);
|
||||
}
|
||||
void SetApiKey(std::string key) { m_ApiKey = std::move(key); }
|
||||
|
||||
// ========================================================================
|
||||
// Search API
|
||||
// ========================================================================
|
||||
auto ShortUrl(const std::string &url) const -> Result<std::string>;
|
||||
|
||||
// https://developers.google.com/youtube/v3/docs/search/list
|
||||
auto Search(const SearchParams ¶ms) -> Result<PageResult<SearchResult>>;
|
||||
// ========================================================================
|
||||
// Search API
|
||||
// ========================================================================
|
||||
|
||||
// ========================================================================
|
||||
// Videos API
|
||||
// ========================================================================
|
||||
// https://developers.google.com/youtube/v3/docs/search/list
|
||||
auto Search(const SearchParams ¶ms)
|
||||
-> Result<PageResult<SearchResult>>;
|
||||
|
||||
// https://developers.google.com/youtube/v3/docs/videos/list
|
||||
auto GetVideo(const std::string &id,
|
||||
const std::string &part = "snippet,contentDetails,statistics")
|
||||
-> Result<Video>;
|
||||
// ========================================================================
|
||||
// Videos API
|
||||
// ========================================================================
|
||||
|
||||
auto GetVideos(const std::vector<std::string> &ids,
|
||||
const std::string &part = "snippet,contentDetails,statistics")
|
||||
-> Result<std::vector<Video>>;
|
||||
// https://developers.google.com/youtube/v3/docs/videos/list
|
||||
auto GetVideo(
|
||||
const std::string &id,
|
||||
const std::string &part = "snippet,contentDetails,statistics")
|
||||
-> Result<Video>;
|
||||
|
||||
// ========================================================================
|
||||
// Channels API
|
||||
// ========================================================================
|
||||
auto GetVideos(
|
||||
const std::vector<std::string> &ids,
|
||||
const std::string &part = "snippet,contentDetails,statistics")
|
||||
-> Result<std::vector<Video>>;
|
||||
|
||||
// https://developers.google.com/youtube/v3/docs/channels/list
|
||||
auto GetChannel(const std::string &id,
|
||||
const std::string &part = "snippet,statistics")
|
||||
-> Result<std::string>; // Returns raw JSON for brevity in this example
|
||||
// ========================================================================
|
||||
// Channels API
|
||||
// ========================================================================
|
||||
|
||||
// ========================================================================
|
||||
// Playlists API
|
||||
// ========================================================================
|
||||
// https://developers.google.com/youtube/v3/docs/channels/list
|
||||
auto GetChannel(const std::string &id,
|
||||
const std::string &part = "snippet,statistics")
|
||||
-> Result<std::string>; // Returns raw JSON for brevity in this
|
||||
// example
|
||||
|
||||
// https://developers.google.com/youtube/v3/docs/playlistItems/list
|
||||
auto GetPlaylistItems(const std::string &playlistId,
|
||||
const std::string &pageToken = "")
|
||||
-> Result<PageResult<SearchPlaylistResult>>; // Reusing SearchResult as structure
|
||||
// is similar enough for snippet
|
||||
auto GetPlaylistVideos(const std::string& playlistId) -> Result<std::vector<Video>>;
|
||||
// ========================================================================
|
||||
// Player API (The "Extraction" Logic)
|
||||
// ========================================================================
|
||||
// ========================================================================
|
||||
// Playlists API
|
||||
// ========================================================================
|
||||
|
||||
// Returns a raw https://googlevideo.com/... URL for the audio stream.
|
||||
// Returns error if the video is region locked or requires signature
|
||||
// deciphering.
|
||||
auto GetAudioStreamUrl(const std::string &videoId) -> Result<std::string>;
|
||||
// https://developers.google.com/youtube/v3/docs/playlistItems/list
|
||||
auto GetPlaylistItems(const std::string &playlistId,
|
||||
const std::string &pageToken = "")
|
||||
-> Result<PageResult<
|
||||
SearchPlaylistResult>>; // Reusing SearchResult as structure
|
||||
// is similar enough for snippet
|
||||
auto GetPlaylistVideos(const std::string &playlistId)
|
||||
-> Result<std::vector<Video>>;
|
||||
// ========================================================================
|
||||
// Player API (The "Extraction" Logic)
|
||||
// ========================================================================
|
||||
|
||||
auto ExtractVideoId(std::string_view url) const -> std::optional<std::string>;
|
||||
// Returns a raw https://googlevideo.com/... URL for the audio
|
||||
// stream. Returns error if the video is region locked or requires
|
||||
// signature deciphering.
|
||||
auto GetAudioStreamUrl(const std::string &videoId)
|
||||
-> Result<std::string>;
|
||||
|
||||
private:
|
||||
std::string m_ApiKey;
|
||||
std::string m_AccessToken;
|
||||
ProxyConfig m_Proxy;
|
||||
bool m_Verbose = false;
|
||||
const std::string m_BaseUrl = "https://www.googleapis.com/youtube/v3";
|
||||
JSRuntime *m_rt;
|
||||
JSContext *m_ctx;
|
||||
std::string m_preprocessedPlayer;
|
||||
auto ExtractVideoId(std::string_view url) const
|
||||
-> std::optional<std::string>;
|
||||
|
||||
// Helper methods for the solver logic
|
||||
void InitSolver();
|
||||
void SetPlayerJs(const std::string &js);
|
||||
std::string SolveChallenge(const std::string &challenge,
|
||||
const std::string &type);
|
||||
auto PerformRequest(
|
||||
const std::string &purl, const std::string &endpoint,
|
||||
const cpr::Parameters ¶ms = {},
|
||||
const cpr::Header &headers =
|
||||
{{"Content-Type", "application/json"},
|
||||
{"User-Agent",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}},
|
||||
HttpMethod method = HttpMethod::GET, const std::string &body = "")
|
||||
-> Result<std::string>;
|
||||
private:
|
||||
|
||||
auto PerformRequest(
|
||||
const std::string &endpoint, const cpr::Parameters ¶ms = {},
|
||||
const cpr::Header &headers =
|
||||
{{"Content-Type", "application/json"},
|
||||
{"User-Agent",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}},
|
||||
HttpMethod method = HttpMethod::GET, const std::string &body = "")
|
||||
-> Result<std::string>;
|
||||
// Helper specifically for the internal YouTube API (different Base URL)
|
||||
auto PerformInternalRequest(const std::string &endpoint,
|
||||
const std::string &jsonBody)
|
||||
-> Result<std::string>;
|
||||
static auto WriteCallback(void *contents, size_t size, size_t nmemb,
|
||||
std::string *out) -> size_t;
|
||||
auto UrlEncode(std::string_view value) const -> std::string;
|
||||
auto UrlEncodePreservingOperators(std::string_view query) const
|
||||
-> std::string;
|
||||
};
|
||||
std::string m_ApiKey;
|
||||
std::string m_AccessToken;
|
||||
ProxyConfig m_Proxy;
|
||||
bool m_Verbose = false;
|
||||
const std::string m_BaseUrl =
|
||||
"https://www.googleapis.com/youtube/v3";
|
||||
JSRuntime *m_rt;
|
||||
JSContext *m_ctx;
|
||||
std::string m_preprocessedPlayer;
|
||||
|
||||
// Helper methods for the solver logic
|
||||
void InitSolver();
|
||||
void SetPlayerJs(const std::string &js);
|
||||
std::string SolveChallenge(const std::string &challenge,
|
||||
const std::string &type);
|
||||
auto PerformRequest(
|
||||
const std::string &purl, const std::string &endpoint,
|
||||
const cpr::Parameters ¶ms = {},
|
||||
const cpr::Header &headers =
|
||||
{{"Content-Type", "application/json"},
|
||||
{"User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36"}},
|
||||
HttpMethod method = HttpMethod::GET,
|
||||
const std::string &body = "") -> Result<std::string>;
|
||||
|
||||
auto PerformRequest(
|
||||
const std::string &endpoint, const cpr::Parameters ¶ms = {},
|
||||
const cpr::Header &headers =
|
||||
{{"Content-Type", "application/json"},
|
||||
{"User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36"}},
|
||||
HttpMethod method = HttpMethod::GET,
|
||||
const std::string &body = "") -> Result<std::string>;
|
||||
// Helper specifically for the internal YouTube API (different Base
|
||||
// URL)
|
||||
auto PerformInternalRequest(const std::string &endpoint,
|
||||
const std::string &jsonBody)
|
||||
-> Result<std::string>;
|
||||
static auto WriteCallback(void *contents, size_t size, size_t nmemb,
|
||||
std::string *out) -> size_t;
|
||||
auto UrlEncode(std::string_view value) const -> std::string;
|
||||
auto UrlEncodePreservingOperators(std::string_view query) const
|
||||
-> std::string;
|
||||
};
|
||||
|
||||
} // namespace YouTube
|
||||
@@ -1,10 +1,11 @@
|
||||
#pragma once
|
||||
#include <string_view>
|
||||
|
||||
namespace YouTube::Internal {
|
||||
namespace YouTube::Internal
|
||||
{
|
||||
|
||||
// Replace the comment with the actual content of yt.solver.lib.js
|
||||
static constexpr std::string_view SOLVER_LIB_JS = R"js(
|
||||
// Replace the comment with the actual content of yt.solver.lib.js
|
||||
static constexpr std::string_view SOLVER_LIB_JS = R"js(
|
||||
/*!
|
||||
* SPDX-License-Identifier: Unlicense
|
||||
* This file was automatically generated by https://github.com/yt-dlp/ejs
|
||||
@@ -13230,8 +13231,8 @@ var lib = (function (exports) {
|
||||
})({});
|
||||
)js";
|
||||
|
||||
// Replace the comment with the actual content of yt.solver.core.js
|
||||
static constexpr std::string_view SOLVER_CORE_JS = R"js(
|
||||
// Replace the comment with the actual content of yt.solver.core.js
|
||||
static constexpr std::string_view SOLVER_CORE_JS = R"js(
|
||||
var jsc = (function (meriyah, astring) {
|
||||
'use strict';
|
||||
// ... (Paste full content of yt.solver.core.js here) ...
|
||||
|
||||
+1418
-1418
File diff suppressed because it is too large.
Load diff
+30561
-30562
File diff suppressed because it is too large.
Load diff
@@ -17,37 +17,40 @@ extern "C" {
|
||||
#include <libswresample/swresample.h>
|
||||
}
|
||||
enum class DecodeStatus { Idle, Processing, Completed, Failed, Cancelled };
|
||||
class AudioDecoder {
|
||||
public:
|
||||
struct AudioData {
|
||||
std::vector<short> buffer;
|
||||
int samples = 0;
|
||||
int channels = 0;
|
||||
int sampleRate = 0;
|
||||
};
|
||||
std::deque<std::vector<short>> m_chunkQueue;
|
||||
std::mutex m_queueMtx;
|
||||
std::condition_variable m_cv;
|
||||
std::atomic<bool> m_isDecodingFinished{false};
|
||||
AudioDecoder();
|
||||
~AudioDecoder();
|
||||
void StartDecode(const std::string &url, int targetSampleRate);
|
||||
void Cancel() { m_cancelRequested = true; }
|
||||
DecodeStatus GetStatus() const { return m_status; }
|
||||
AudioData GetResult() { return std::move(m_result); }
|
||||
bool GetNextChunk(std::vector<short> &outChunk, bool blocking = false);
|
||||
bool IsFinished() const { return m_finished.load(); }
|
||||
class AudioDecoder
|
||||
{
|
||||
public:
|
||||
|
||||
private:
|
||||
void Cleanup();
|
||||
void InternalDecode(std::string url, int targetSampleRate);
|
||||
std::atomic<DecodeStatus> m_status{DecodeStatus::Idle};
|
||||
std::atomic<bool> m_cancelRequested{false};
|
||||
std::jthread m_thread;
|
||||
std::mutex m_logMtx;
|
||||
AudioData m_result;
|
||||
std::atomic<bool> m_finished{false};
|
||||
AVFormatContext *m_formatCtx = nullptr;
|
||||
AVCodecContext *m_codecCtx = nullptr;
|
||||
SwrContext *m_swrCtx = nullptr;
|
||||
struct AudioData {
|
||||
std::vector<short> buffer;
|
||||
int samples = 0;
|
||||
int channels = 0;
|
||||
int sampleRate = 0;
|
||||
};
|
||||
std::deque<std::vector<short>> m_chunkQueue;
|
||||
std::mutex m_queueMtx;
|
||||
std::condition_variable m_cv;
|
||||
std::atomic<bool> m_isDecodingFinished{false};
|
||||
AudioDecoder();
|
||||
~AudioDecoder();
|
||||
void StartDecode(const std::string &url, int targetSampleRate);
|
||||
void Cancel() { m_cancelRequested = true; }
|
||||
DecodeStatus GetStatus() const { return m_status; }
|
||||
AudioData GetResult() { return std::move(m_result); }
|
||||
bool GetNextChunk(std::vector<short> &outChunk, bool blocking = false);
|
||||
bool IsFinished() const { return m_finished.load(); }
|
||||
|
||||
private:
|
||||
|
||||
void Cleanup();
|
||||
void InternalDecode(std::string url, int targetSampleRate);
|
||||
std::atomic<DecodeStatus> m_status{DecodeStatus::Idle};
|
||||
std::atomic<bool> m_cancelRequested{false};
|
||||
std::jthread m_thread;
|
||||
std::mutex m_logMtx;
|
||||
AudioData m_result;
|
||||
std::atomic<bool> m_finished{false};
|
||||
AVFormatContext *m_formatCtx = nullptr;
|
||||
AVCodecContext *m_codecCtx = nullptr;
|
||||
SwrContext *m_swrCtx = nullptr;
|
||||
};
|
||||
@@ -8,121 +8,119 @@
|
||||
|
||||
#include "Singleton.hpp"
|
||||
|
||||
namespace ts6bot {
|
||||
namespace ts6bot
|
||||
{
|
||||
|
||||
enum class LogLevel {
|
||||
Trace,
|
||||
Debug,
|
||||
Info,
|
||||
Warning,
|
||||
Error,
|
||||
Critical,
|
||||
None
|
||||
};
|
||||
enum class LogLevel { Trace, Debug, Info, Warning, Error, Critical, None };
|
||||
|
||||
struct ServerQueryConfig {
|
||||
std::string host{"127.0.0.1"};
|
||||
uint16_t port{
|
||||
10022}; // ServerQuery SSH default :contentReference[oaicite:6]{index=6}
|
||||
std::string username{"serveradmin"};
|
||||
std::string password{};
|
||||
int virtual_server_id{1};
|
||||
std::string nickname{"ts6bot"};
|
||||
};
|
||||
struct ServerQueryConfig {
|
||||
std::string host{"127.0.0.1"};
|
||||
uint16_t port{10022}; // ServerQuery SSH default
|
||||
// :contentReference[oaicite:6]{index=6}
|
||||
std::string username{"serveradmin"};
|
||||
std::string password{};
|
||||
int virtual_server_id{1};
|
||||
std::string nickname{"ts6bot"};
|
||||
};
|
||||
|
||||
struct AfkConfig {
|
||||
bool enabled{true};
|
||||
int idle_seconds{600};
|
||||
std::uint64_t afk_channel_id{0};
|
||||
int poll_interval_ms{5000};
|
||||
};
|
||||
struct AfkConfig {
|
||||
bool enabled{true};
|
||||
int idle_seconds{600};
|
||||
std::uint64_t afk_channel_id{0};
|
||||
int poll_interval_ms{5000};
|
||||
};
|
||||
|
||||
struct MusicConfig {
|
||||
bool enabled{true};
|
||||
std::string youtubeApiToken;
|
||||
};
|
||||
struct MusicConfig {
|
||||
bool enabled{true};
|
||||
std::string youtubeApiToken;
|
||||
};
|
||||
|
||||
struct ProxyConfiguration : public ProxyConfig {
|
||||
bool enabled{false};
|
||||
};
|
||||
struct ProxyConfiguration : public ProxyConfig {
|
||||
bool enabled{false};
|
||||
};
|
||||
|
||||
struct Config {
|
||||
std::string nickname;
|
||||
std::string host;
|
||||
std::string channel;
|
||||
std::string password;
|
||||
LogLevel loggingLevel;
|
||||
AfkConfig afk{};
|
||||
MusicConfig music{};
|
||||
ProxyConfiguration proxy{};
|
||||
};
|
||||
struct Config {
|
||||
std::string nickname;
|
||||
std::string host;
|
||||
std::string channel;
|
||||
std::string password;
|
||||
LogLevel loggingLevel;
|
||||
AfkConfig afk{};
|
||||
MusicConfig music{};
|
||||
ProxyConfiguration proxy{};
|
||||
};
|
||||
|
||||
class Configuration : public Singleton<Configuration> {
|
||||
friend class Singleton<Configuration>;
|
||||
public:
|
||||
const Config getConfig() const noexcept { return m_config; }
|
||||
class Configuration : public Singleton<Configuration>
|
||||
{
|
||||
friend class Singleton<Configuration>;
|
||||
|
||||
Configuration(std::string path) {
|
||||
auto config = Config();
|
||||
std::string buffer;
|
||||
auto ec = glz::read_file_json(config, path, buffer);
|
||||
if (ec) {
|
||||
std::string descriptive_error = glz::format_error(ec, buffer);
|
||||
std::cerr << "Not found configuration in " << path << " using default"
|
||||
<< std::endl;
|
||||
std::cerr << descriptive_error << std::endl;
|
||||
std::cerr << ec.ec << std::endl;
|
||||
m_config = Config();
|
||||
}
|
||||
this->m_config = config;
|
||||
}
|
||||
public:
|
||||
|
||||
Config m_config{};
|
||||
};
|
||||
const Config getConfig() const noexcept { return m_config; }
|
||||
|
||||
// Glaze meta (explicit, stable)
|
||||
Configuration(std::string path)
|
||||
{
|
||||
auto config = Config();
|
||||
std::string buffer;
|
||||
auto ec = glz::read_file_json(config, path, buffer);
|
||||
if (ec) {
|
||||
std::string descriptive_error =
|
||||
glz::format_error(ec, buffer);
|
||||
std::cerr << "Not found configuration in " << path
|
||||
<< " using default" << std::endl;
|
||||
std::cerr << descriptive_error << std::endl;
|
||||
std::cerr << ec.ec << std::endl;
|
||||
m_config = Config();
|
||||
}
|
||||
this->m_config = config;
|
||||
}
|
||||
|
||||
Config m_config{};
|
||||
};
|
||||
|
||||
// Glaze meta (explicit, stable)
|
||||
|
||||
} // namespace ts6bot
|
||||
template <> struct glz::meta<ProxyType> {
|
||||
using enum ProxyType;
|
||||
static constexpr auto value = enumerate(HTTP, SOCKS5, SOCKS5_HOSTNAME);
|
||||
using enum ProxyType;
|
||||
static constexpr auto value = enumerate(HTTP, SOCKS5, SOCKS5_HOSTNAME);
|
||||
};
|
||||
template <> struct glz::meta<ts6bot::LogLevel> {
|
||||
using enum ts6bot::LogLevel;
|
||||
static constexpr auto value =
|
||||
enumerate(Critical, Error, Warning, Info, Trace);
|
||||
using enum ts6bot::LogLevel;
|
||||
static constexpr auto value =
|
||||
enumerate(Critical, Error, Warning, Info, Trace);
|
||||
};
|
||||
template <> struct glz::meta<ts6bot::ServerQueryConfig> {
|
||||
using T = ts6bot::ServerQueryConfig;
|
||||
static constexpr auto value =
|
||||
object("host", &T::host, "port", &T::port, "username", &T::username,
|
||||
"password", &T::password, "virtual_server_id",
|
||||
&T::virtual_server_id, "nickname", &T::nickname);
|
||||
using T = ts6bot::ServerQueryConfig;
|
||||
static constexpr auto value =
|
||||
object("host", &T::host, "port", &T::port, "username", &T::username,
|
||||
"password", &T::password, "virtual_server_id",
|
||||
&T::virtual_server_id, "nickname", &T::nickname);
|
||||
};
|
||||
|
||||
template <> struct glz::meta<ts6bot::AfkConfig> {
|
||||
using T = ts6bot::AfkConfig;
|
||||
static constexpr auto value =
|
||||
object("enabled", &T::enabled, "idle_seconds", &T::idle_seconds,
|
||||
"afk_channel_id", &T::afk_channel_id, "poll_interval_ms",
|
||||
&T::poll_interval_ms);
|
||||
using T = ts6bot::AfkConfig;
|
||||
static constexpr auto value =
|
||||
object("enabled", &T::enabled, "idle_seconds", &T::idle_seconds,
|
||||
"afk_channel_id", &T::afk_channel_id, "poll_interval_ms",
|
||||
&T::poll_interval_ms);
|
||||
};
|
||||
|
||||
template <> struct glz::meta<ts6bot::MusicConfig> {
|
||||
using T = ts6bot::MusicConfig;
|
||||
static constexpr auto value =
|
||||
object("enabled", &T::enabled, "youtubeApiToken", &T::youtubeApiToken);
|
||||
using T = ts6bot::MusicConfig;
|
||||
static constexpr auto value = object(
|
||||
"enabled", &T::enabled, "youtubeApiToken", &T::youtubeApiToken);
|
||||
};
|
||||
template <> struct glz::meta<ts6bot::ProxyConfiguration> {
|
||||
using T = ts6bot::ProxyConfiguration;
|
||||
static constexpr auto value =
|
||||
object("url", &T::url, "username", &T::username, "password", &T::password,
|
||||
"type", &T::type, "enabled", &T::enabled);
|
||||
using T = ts6bot::ProxyConfiguration;
|
||||
static constexpr auto value =
|
||||
object("url", &T::url, "username", &T::username, "password",
|
||||
&T::password, "type", &T::type, "enabled", &T::enabled);
|
||||
};
|
||||
template <> struct glz::meta<ts6bot::Config> {
|
||||
using T = ts6bot::Config;
|
||||
static constexpr auto value =
|
||||
object("nickname", &T::nickname, "host", &T::host, "channel", &T::channel,
|
||||
"password", &T::password, "loggingLevel", &T::loggingLevel, "afk",
|
||||
&T::afk, "music", &T::music, "proxy", &T::proxy);
|
||||
using T = ts6bot::Config;
|
||||
static constexpr auto value = object(
|
||||
"nickname", &T::nickname, "host", &T::host, "channel", &T::channel,
|
||||
"password", &T::password, "loggingLevel", &T::loggingLevel, "afk",
|
||||
&T::afk, "music", &T::music, "proxy", &T::proxy);
|
||||
};
|
||||
@@ -6,18 +6,19 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace ts6bot::crypto {
|
||||
namespace ts6bot::crypto
|
||||
{
|
||||
|
||||
// RFC 7636: length 43..128, chars [A-Z a-z 0-9 - . _ ~]
|
||||
std::string GenerateCodeVerifier(std::size_t length = 64);
|
||||
// RFC 7636: length 43..128, chars [A-Z a-z 0-9 - . _ ~]
|
||||
std::string GenerateCodeVerifier(std::size_t length = 64);
|
||||
|
||||
// Random state value (base64url, no padding).
|
||||
std::string GenerateState(std::size_t bytes = 16);
|
||||
// Random state value (base64url, no padding).
|
||||
std::string GenerateState(std::size_t bytes = 16);
|
||||
|
||||
std::vector<std::uint8_t> Sha256(std::span<const std::uint8_t> data);
|
||||
std::vector<std::uint8_t> Sha256(std::span<const char> data);
|
||||
std::vector<std::uint8_t> Sha256(std::span<const std::uint8_t> data);
|
||||
std::vector<std::uint8_t> Sha256(std::span<const char> data);
|
||||
|
||||
// Base64url encode without padding.
|
||||
std::string Base64UrlEncode(std::span<const std::uint8_t> data);
|
||||
// Base64url encode without padding.
|
||||
std::string Base64UrlEncode(std::span<const std::uint8_t> data);
|
||||
|
||||
} // namespace ts6bot::crypto
|
||||
@@ -16,85 +16,105 @@
|
||||
#include <ts3_functions.h>
|
||||
#include <ts6bot/AudioDecoder.hpp>
|
||||
#include <vector>
|
||||
class MusicManager {
|
||||
public:
|
||||
explicit MusicManager(std::shared_ptr<TS3Functions> functions, std::uint64_t serverConnectionHandlerID = 0);
|
||||
~MusicManager();
|
||||
class MusicManager
|
||||
{
|
||||
public:
|
||||
|
||||
struct Music {
|
||||
std::string name;
|
||||
std::string shortUrl;
|
||||
std::string length;
|
||||
std::string videoId;
|
||||
std::string requestedBy;
|
||||
YouTube::Result<definitions::Streams> streams;
|
||||
};
|
||||
explicit MusicManager(std::shared_ptr<TS3Functions> functions,
|
||||
std::uint64_t serverConnectionHandlerID = 0);
|
||||
~MusicManager();
|
||||
|
||||
// Playback Control
|
||||
void stop();
|
||||
void skip();
|
||||
void forceSkip();
|
||||
void setStopAfterCurrent(bool val) { m_stopAfterCurrent = val; }
|
||||
bool isIdle() const { return m_isIdle; }
|
||||
std::uint64_t getServerConnectionHandlerID() const
|
||||
{return m_serverConnectionHandlerID; }
|
||||
void setServerConnectionHandlerID(std::uint64_t id) { m_serverConnectionHandlerID = id; }
|
||||
// Subscription (Whisper) Management
|
||||
void subscribe(anyID id);
|
||||
void moveSubscriberToOffline(anyID id);
|
||||
void moveSubscriberToOnline(anyID id);
|
||||
void addSubscriberToOnline(anyID id);
|
||||
void addSubscriberToOffline(anyID id);
|
||||
void unSubscribe(anyID id);
|
||||
std::set<uint64_t> getOnlineSubscribers() const;
|
||||
std::set<uint64_t> getOfflineSubscribers() const;
|
||||
// Queue Management
|
||||
std::vector<Music> getQueue() const;
|
||||
std::optional<Music> getCurrent() const { return m_current; }
|
||||
void removeFromQueue(std::size_t index);
|
||||
void removeFromQueue(const std::string &name);
|
||||
void addToQueueDirect(const std::string& vid, const std::string& title, const std::string& shortUrl, const std::string& length, const std::string& req, std::optional<definitions::Streams> streams);
|
||||
void checkQueueAndPlay();
|
||||
struct Music {
|
||||
std::string name;
|
||||
std::string shortUrl;
|
||||
std::string length;
|
||||
std::string videoId;
|
||||
std::string requestedBy;
|
||||
YouTube::Result<definitions::Streams> streams;
|
||||
};
|
||||
|
||||
// Youtube / Search
|
||||
std::vector<definitions::SearchResultItem> search(std::string name, int maxResults = 5) const;
|
||||
void playUrl(std::string url, const std::string &requester = "");
|
||||
void playPlaylist(const std::string& playlistId, const std::string& requester);
|
||||
// Helper to extract playlist ID from URL
|
||||
std::optional<std::string> extractPlaylistId(std::string_view url);
|
||||
// Selection Logic
|
||||
// Stores the results for a specific user to select later
|
||||
void storePendingSearch(anyID clientId,
|
||||
const std::vector<definitions::SearchResultItem> &results);
|
||||
bool selectSearchResult(anyID clientId, int index, const std::string& requesterName);
|
||||
// Playback Control
|
||||
void stop();
|
||||
void skip();
|
||||
void forceSkip();
|
||||
void setStopAfterCurrent(bool val) { m_stopAfterCurrent = val; }
|
||||
bool isIdle() const { return m_isIdle; }
|
||||
std::uint64_t getServerConnectionHandlerID() const
|
||||
{
|
||||
return m_serverConnectionHandlerID;
|
||||
}
|
||||
void setServerConnectionHandlerID(std::uint64_t id)
|
||||
{
|
||||
m_serverConnectionHandlerID = id;
|
||||
}
|
||||
// Subscription (Whisper) Management
|
||||
bool subscribe(anyID id);
|
||||
void moveSubscriberToOffline(anyID id);
|
||||
void moveSubscriberToOnline(anyID id);
|
||||
bool addSubscriberToOnline(anyID id);
|
||||
bool addSubscriberToOffline(anyID id);
|
||||
bool unSubscribe(anyID id);
|
||||
std::set<uint64_t> getOnlineSubscribers() const;
|
||||
std::set<uint64_t> getOfflineSubscribers() const;
|
||||
// Queue Management
|
||||
std::vector<Music> getQueue() const;
|
||||
std::optional<Music> getCurrent() const { return m_current; }
|
||||
void removeFromQueue(std::size_t index);
|
||||
void removeFromQueue(const std::string& name);
|
||||
void addToQueueDirect(const std::string& vid,
|
||||
const std::string& title,
|
||||
const std::string& shortUrl,
|
||||
const std::string& length,
|
||||
const std::string& req,
|
||||
std::optional<definitions::Streams>
|
||||
streams);
|
||||
void checkQueueAndPlay();
|
||||
|
||||
private:
|
||||
void loop(std::stop_token st);
|
||||
static std::string formatDuration(const std::string &isoDuration);
|
||||
void updateWhisperList();
|
||||
// Youtube / Search
|
||||
std::vector<definitions::SearchResultItem>
|
||||
search(std::string name, int maxResults = 5) const;
|
||||
bool playUrl(std::string url, const std::string& requester = "");
|
||||
bool playPlaylist(const std::string& playlistId,
|
||||
const std::string& requester);
|
||||
// Helper to extract playlist ID from URL
|
||||
std::optional<std::string> extractPlaylistId(std::string_view url);
|
||||
// Selection Logic
|
||||
// Stores the results for a specific user to select later
|
||||
void storePendingSearch(
|
||||
anyID clientId,
|
||||
const std::vector<definitions::SearchResultItem>& results);
|
||||
bool selectSearchResult(anyID clientId,
|
||||
int index,
|
||||
const std::string& requesterName);
|
||||
|
||||
std::shared_ptr<TS3Functions> m_functions{nullptr};
|
||||
std::unique_ptr<AudioDecoder> m_microphone{nullptr};
|
||||
std::unique_ptr<YouTube::Client> m_client{nullptr};
|
||||
private:
|
||||
|
||||
void loop(std::stop_token st);
|
||||
static std::string formatDuration(const std::string& isoDuration);
|
||||
void updateWhisperList();
|
||||
|
||||
std::atomic<bool> m_stopAfterCurrent{false};
|
||||
std::atomic<bool> m_isIdle{true};
|
||||
std::shared_ptr<TS3Functions> m_functions{nullptr};
|
||||
std::unique_ptr<AudioDecoder> m_microphone{nullptr};
|
||||
std::unique_ptr<YouTube::Client> m_client{nullptr};
|
||||
|
||||
std::deque<Music> m_queue{};
|
||||
mutable std::mutex m_queueMtx;
|
||||
std::condition_variable m_cv;
|
||||
std::atomic<bool> m_stopAfterCurrent{false};
|
||||
std::atomic<bool> m_isIdle{true};
|
||||
|
||||
std::set<anyID> m_onlineSubscribers;
|
||||
std::set<anyID> m_offlineSubscribers;
|
||||
// Playback Control
|
||||
std::atomic_bool m_skipRequested{false};
|
||||
std::deque<Music> m_queue{};
|
||||
mutable std::mutex m_queueMtx;
|
||||
std::condition_variable m_cv;
|
||||
|
||||
std::atomic<float> m_volume{0.5f}; // Default 50%
|
||||
std::uint64_t m_serverConnectionHandlerID = 0;
|
||||
std::optional<Music> m_current;
|
||||
std::mutex m_subMtx;
|
||||
std::map<anyID, std::vector<definitions::SearchResultItem>> m_pendingSearches;
|
||||
std::mutex m_pendingMtx;
|
||||
std::jthread m_worker;
|
||||
std::set<anyID> m_onlineSubscribers;
|
||||
std::set<anyID> m_offlineSubscribers;
|
||||
// Playback Control
|
||||
std::atomic_bool m_skipRequested{false};
|
||||
|
||||
std::atomic<float> m_volume{0.5f}; // Default 50%
|
||||
std::uint64_t m_serverConnectionHandlerID = 0;
|
||||
std::optional<Music> m_current;
|
||||
std::mutex m_subMtx;
|
||||
std::map<anyID, std::vector<definitions::SearchResultItem>>
|
||||
m_pendingSearches;
|
||||
std::mutex m_pendingMtx;
|
||||
std::jthread m_worker;
|
||||
};
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
#include <string>
|
||||
enum class ProxyType {
|
||||
HTTP,
|
||||
SOCKS5,
|
||||
SOCKS5_HOSTNAME // Use this to let the proxy resolve the DNS
|
||||
HTTP,
|
||||
SOCKS5,
|
||||
SOCKS5_HOSTNAME // Use this to let the proxy resolve the DNS
|
||||
};
|
||||
struct ProxyConfig {
|
||||
std::string url;
|
||||
ProxyType type = ProxyType::SOCKS5_HOSTNAME;
|
||||
std::string username = "";
|
||||
std::string password = "";
|
||||
};
|
||||
std::string url;
|
||||
ProxyType type = ProxyType::SOCKS5_HOSTNAME;
|
||||
std::string username = "";
|
||||
std::string password = "";
|
||||
};
|
||||
+13
-12
@@ -3,20 +3,21 @@
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace ts6bot::url {
|
||||
namespace ts6bot::url
|
||||
{
|
||||
|
||||
// Percent-encode a string for use as a query parameter value.
|
||||
std::string EncodeComponent(const std::string& s);
|
||||
// Percent-encode a string for use as a query parameter value.
|
||||
std::string EncodeComponent(const std::string& s);
|
||||
|
||||
struct HttpUrl {
|
||||
std::string host;
|
||||
uint16_t port{};
|
||||
std::string path; // begins with '/'
|
||||
};
|
||||
struct HttpUrl {
|
||||
std::string host;
|
||||
uint16_t port{};
|
||||
std::string path; // begins with '/'
|
||||
};
|
||||
|
||||
// Minimal parser for redirect URIs.
|
||||
// Supports: http://<host>:<port>/<path>
|
||||
// Throws std::runtime_error on invalid input.
|
||||
HttpUrl ParseHttpUrl(const std::string& httpUrl);
|
||||
// Minimal parser for redirect URIs.
|
||||
// Supports: http://<host>:<port>/<path>
|
||||
// Throws std::runtime_error on invalid input.
|
||||
HttpUrl ParseHttpUrl(const std::string& httpUrl);
|
||||
|
||||
} // namespace ts6bot::url
|
||||
Reference in new issue
Block a user