diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..1c0ed4b --- /dev/null +++ b/.clang-format @@ -0,0 +1,272 @@ +--- +BasedOnStyle: LLVM +AccessModifierOffset: 0 +AlignAfterOpenBracket: Align +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCaseArrows: false + AlignCaseColons: false +AlignConsecutiveTableGenBreakingDAGArgColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenCondOperatorColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenDefinitionColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowBreakBeforeNoexceptSpecifier: Never +AllowShortBlocksOnASingleLine: Never +AllowShortCaseExpressionOnASingleLine: true +AllowShortCaseLabelsOnASingleLine: false +AllowShortCompoundRequirementOnASingleLine: true +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BitFieldColonSpacing: Both +BraceWrapping: + AfterCaseLabel: true + AfterClass: true + AfterControlStatement: Never + AfterEnum: false + AfterFunction: true + AfterNamespace: true + AfterObjCDeclaration: false + AfterStruct: true + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: true + BeforeLambdaBody: true + BeforeWhile: true + IndentBraces: true + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakAdjacentStringLiterals: true +BreakAfterAttributes: Leave +BreakAfterJavaFieldAnnotations: false +BreakAfterReturnType: None +BreakArrays: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Linux +BreakBeforeConceptDeclarations: Always +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeColon +BreakFunctionDefinitionParameters: false +BreakInheritanceList: BeforeColon +BreakStringLiterals: true +BreakTemplateDeclarations: MultiLine +ColumnLimit: 80 +CommentPragmas: "" +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: true +DisableFormat: false +EmptyLineAfterAccessModifier: Always +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: true +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Preserve +IncludeCategories: + - Regex: ^"(llvm|llvm-c|clang|clang-c)/ + Priority: 2 + SortPriority: 0 + CaseSensitive: true + - Regex: ^(<|"(gtest|gmock|isl|json)/) + Priority: 3 + SortPriority: 0 + CaseSensitive: true + - Regex: .* + Priority: 1 + SortPriority: 0 + CaseSensitive: true +IncludeIsMainRegex: (Test)?$ +IncludeIsMainSourceRegex: "" +IndentAccessModifiers: true +IndentCaseBlocks: true +IndentCaseLabels: true +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true +IndentPPDirectives: None +IndentRequiresClause: true +IndentWidth: 4 +IndentWrappedFunctionNames: true +InsertBraces: true +InsertNewlineAtEOF: true +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLines: + AtEndOfFile: false + AtStartOfBlock: true + AtStartOfFile: true +LambdaBodyIndentation: Signature +LineEnding: DeriveLF +MacroBlockBegin: "" +MacroBlockEnd: "" +MainIncludeChar: AngleBracket +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: All +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PPIndentWidth: -1 +PackConstructorInitializers: BinPack +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakScopeResolution: 500 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Right +QualifierAlignment: Leave +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SkipMacroDefinitionBody: false +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDeclarationName: false + AfterFunctionDefinitionName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterPlacementOperator: true + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInContainerLiterals: true +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + ExceptDoubleParentheses: false + InConditionalStatements: false + InCStyleCasts: false + InEmptyParentheses: false + Other: false +SpacesInSquareBrackets: false +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 4 +TableGenBreakInsideDAGArg: DontBreak +UseTab: Always +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE diff --git a/include/Core/Logger.hpp b/include/Core/Logger.hpp index 28404b2..9df611f 100644 --- a/include/Core/Logger.hpp +++ b/include/Core/Logger.hpp @@ -1,321 +1,381 @@ #pragma once -#include -#include +#include +#include +#include +#include #include #include -#include -#include -#include +#include +#include #include -#include +#include +#include #include -#include -#include -#include +#include #include #include #include "Singleton.hpp" -class Logger : public Singleton { - friend class Singleton; +class Logger : public Singleton +{ + friend class Singleton; - // 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 - void log(const ts6bot::LogLevel level, const std::source_location& loc, std::format_string fmt, Args&&... args) { - if (level < m_minLevel || level == ts6bot::LogLevel::None) return; + // --- Public Logging API --- - try { - // 1. Capture context immediately + // Generic log function + template + void log(const ts6bot::LogLevel level, const std::source_location &loc, + std::format_string 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)...) - }; - 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)...)}; + std::lock_guard lock(m_queueMutex); + m_logQueue.push_back(std::move(entry)); + } + m_cv.notify_one(); - // Convenience Wrappers - template - void trace(std::format_string fmt, Args&&... args) { - log(ts6bot::LogLevel::Trace, std::source_location::current(), fmt, std::forward(args)...); - } + } catch (const std::exception &e) { + // Fallback if formatting fails + std::println(std::cerr, "Logging Error: {}", e.what()); + } + } - template - void info(std::format_string fmt, Args&&... args) { - log(ts6bot::LogLevel::Info, std::source_location::current(), fmt, std::forward(args)...); - } + // Convenience Wrappers + template + void trace(std::format_string fmt, Args &&...args) + { + log(ts6bot::LogLevel::Trace, std::source_location::current(), fmt, + std::forward(args)...); + } - template - void error(std::format_string fmt, Args&&... args) { - log(ts6bot::LogLevel::Error, std::source_location::current(), fmt, std::forward(args)...); - } + template + void info(std::format_string fmt, Args &&...args) + { + log(ts6bot::LogLevel::Info, std::source_location::current(), fmt, + std::forward(args)...); + } - template - void warn(std::format_string fmt, Args&&... args) { - log(ts6bot::LogLevel::Warning, std::source_location::current(), fmt, std::forward(args)...); - } + template + void error(std::format_string fmt, Args &&...args) + { + log(ts6bot::LogLevel::Error, std::source_location::current(), fmt, + std::forward(args)...); + } - template - void debug(std::format_string fmt, Args&&... args) { - log(ts6bot::LogLevel::Debug, std::source_location::current(), fmt, std::forward(args)...); - } + template + void warn(std::format_string fmt, Args &&...args) + { + log(ts6bot::LogLevel::Warning, std::source_location::current(), fmt, + std::forward(args)...); + } - template - void critical(std::format_string fmt, Args&&... args) { - log(ts6bot::LogLevel::Critical, std::source_location::current(), fmt, std::forward(args)...); - } + template + void debug(std::format_string fmt, Args &&...args) + { + log(ts6bot::LogLevel::Debug, std::source_location::current(), fmt, + std::forward(args)...); + } - void SetLogLevel(const ts6bot::LogLevel level) { m_minLevel = level; } + template + void critical(std::format_string fmt, Args &&...args) + { + log(ts6bot::LogLevel::Critical, std::source_location::current(), + fmt, std::forward(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 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 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(duration); - const auto nanoseconds = std::chrono::duration_cast(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(duration); + const auto nanoseconds = + std::chrono::duration_cast(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 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 m_logQueue; - std::mutex m_queueMutex; - std::condition_variable m_cv; - std::jthread m_workerThread; - std::atomic 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 m_logFiles; + + // Concurrency + std::deque m_logQueue; + std::mutex m_queueMutex; + std::condition_variable m_cv; + std::jthread m_workerThread; + std::atomic 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__) \ No newline at end of file +#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__) diff --git a/include/Core/Plugin.hpp b/include/Core/Plugin.hpp index e541b2e..8a78895 100644 --- a/include/Core/Plugin.hpp +++ b/include/Core/Plugin.hpp @@ -2,411 +2,641 @@ #include "PluginInterface.hpp" // #include "Youtube/Client.hpp" #include "ts6bot/AudioDecoder.hpp" -#include #include "ts6bot/Config.hpp" +#include #include #include #include "PluginDefinitions.hpp" #include "ts6bot/MusicManager.hpp" -class EchoionCore : public IEchoionPlugin { - // Dependencies - std::shared_ptr m_ts3; - std::unique_ptr m_musicManager; - -public: - explicit EchoionCore(std::shared_ptr funcs) { - m_ts3 = std::move(funcs); - } - - void Initialize(bool start = true) override; - - void Shutdown() override; - - // --- HOT RELOAD --- - void RequestGracefulStop() override ; - - bool IsStopped() override; - - std::string SerializeState() override; - - void DeserializeState(const std::string &jsonState) override; - - void onConnectStatusChangeEvent(uint64 serverConnectionHandlerID, int newStatus, unsigned errorNumber) override { - } - - void onNewChannelEvent(uint64 serverConnectionHandlerID, uint64 channelID, uint64 channelParentID) override { - } - - void onNewChannelCreatedEvent(uint64 serverConnectionHandlerID, uint64 channelID, uint64 channelParentID, - anyID invokerID, const char *invokerName, - const char *invokerUniqueIdentifier) override { - } - - void onDelChannelEvent(uint64 serverConnectionHandlerID, uint64 channelID, anyID invokerID, const char *invokerName, - const char *invokerUniqueIdentifier) override { - } - - void onChannelMoveEvent(uint64 serverConnectionHandlerID, uint64 channelID, uint64 newChannelParentID, - anyID invokerID, const char *invokerName, const char *invokerUniqueIdentifier) override { - } - - void onUpdateChannelEvent(uint64 serverConnectionHandlerID, uint64 channelID) override { - } - - void onUpdateChannelEditedEvent(uint64 serverConnectionHandlerID, uint64 channelID, anyID invokerID, - const char *invokerName, const char *invokerUniqueIdentifier) override { - } - - void onUpdateClientEvent(uint64 serverConnectionHandlerID, anyID clientID, anyID invokerID, const char *invokerName, - const char *invokerUniqueIdentifier) override { - } - - void onClientMoveEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, uint64 newChannelID, - int visibility, const char *moveMessage) override; - - void onClientMoveSubscriptionEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, - uint64 newChannelID, int visibility) override { - } - - void onClientMoveTimeoutEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, - uint64 newChannelID, int visibility, const char *timeoutMessage) override { - } - - void onClientMoveMovedEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, - uint64 newChannelID, int visibility, anyID moverID, const char *moverName, - const char *moverUniqueIdentifier, - const char *moveMessage) override { - } - - void onClientKickFromChannelEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, - uint64 newChannelID, int visibility, anyID kickerID, const char *kickerName, - const char *kickerUniqueIdentifier, - const char *kickMessage) override { - } - - void onClientKickFromServerEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, - uint64 newChannelID, int visibility, anyID kickerID, const char *kickerName, - const char *kickerUniqueIdentifier, - const char *kickMessage) override { - } - - void onClientIDsEvent(uint64 serverConnectionHandlerID, const char *uniqueClientIdentifier, anyID clientID, - const char *clientName) override { - } - - void onClientIDsFinishedEvent(uint64 serverConnectionHandlerID) override { - } - - void onServerEditedEvent(uint64 serverConnectionHandlerID, anyID editerID, const char *editerName, - const char *editerUniqueIdentifier) override { - } - - void onServerUpdatedEvent(uint64 serverConnectionHandlerID) override { - } - - int onServerErrorEvent(uint64 serverConnectionHandlerID, const char *errorMessage, unsigned error, - const char *returnCode, const char *extraMessage) override { - return 0; - } - - void onServerStopEvent(uint64 serverConnectionHandlerID, const char *shutdownMessage) override { - } - - int onTextMessageEvent(uint64 serverConnectionHandlerID, anyID targetMode, anyID toID, anyID fromID, - const char *fromName, const char *fromUniqueIdentifier, const char *message, - int ffIgnored) override; - - void onTalkStatusChangeEvent(uint64 serverConnectionHandlerID, int status, int isReceivedWhisper, - anyID clientID) override { - } - - void onConnectionInfoEvent(uint64 serverConnectionHandlerID, anyID clientID) override { - } - - void onServerConnectionInfoEvent(uint64 serverConnectionHandlerID) override { - } - - void onChannelSubscribeEvent(uint64 serverConnectionHandlerID, uint64 channelID) override { - } - - void onChannelSubscribeFinishedEvent(uint64 serverConnectionHandlerID) override { - } - - void onChannelUnsubscribeEvent(uint64 serverConnectionHandlerID, uint64 channelID) override { - } - - void onChannelUnsubscribeFinishedEvent(uint64 serverConnectionHandlerID) override { - } - - void onChannelDescriptionUpdateEvent(uint64 serverConnectionHandlerID, uint64 channelID) override { - } - - void onChannelPasswordChangedEvent(uint64 serverConnectionHandlerID, uint64 channelID) override { - } - - void onPlaybackShutdownCompleteEvent(uint64 serverConnectionHandlerID) override { - } - - void onSoundDeviceListChangedEvent(const char *modeID, int playOrCap) override { - } - - void onEditPlaybackVoiceDataEvent(uint64 serverConnectionHandlerID, anyID clientID, short *samples, int sampleCount, - int channels) override { - } - - void onEditPostProcessVoiceDataEvent(uint64 serverConnectionHandlerID, anyID clientID, short *samples, - int sampleCount, int channels, const unsigned *channelSpeakerArray, - unsigned *channelFillMask) override { - } - - void onEditMixedPlaybackVoiceDataEvent(uint64 serverConnectionHandlerID, short *samples, int sampleCount, - int channels, const unsigned *channelSpeakerArray, - unsigned *channelFillMask) override { - } - - void onEditCapturedVoiceDataEvent(uint64 serverConnectionHandlerID, short *samples, int sampleCount, int channels, - int *edited) override { - } - - void onCustom3dRolloffCalculationClientEvent(uint64 serverConnectionHandlerID, anyID clientID, float distance, - float *volume) override { - } - - void onCustom3dRolloffCalculationWaveEvent(uint64 serverConnectionHandlerID, uint64 waveHandle, float distance, - float *volume) override { - } - - void onUserLoggingMessageEvent(const char *logMessage, int logLevel, const char *logChannel, uint64 logID, - const char *logTime, const char *completeLogString) override { - } - - void onClientBanFromServerEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, - uint64 newChannelID, int visibility, anyID kickerID, const char *kickerName, - const char *kickerUniqueIdentifier, - uint64 time, const char *kickMessage) override { - } - - int onClientPokeEvent(uint64 serverConnectionHandlerID, anyID fromClientID, const char *pokerName, - const char *pokerUniqueIdentity, const char *message, int ffIgnored) override { - return 0; - } - - void onClientSelfVariableUpdateEvent(uint64 serverConnectionHandlerID, int flag, const char *oldValue, - const char *newValue) override { - } - - void onFileListEvent(uint64 serverConnectionHandlerID, uint64 channelID, const char *path, const char *name, - uint64 size, uint64 datetime, int type, uint64 incompletesize, const char *returnCode) override { - } - - void onFileListFinishedEvent(uint64 serverConnectionHandlerID, uint64 channelID, const char *path) override { - } - - void onFileInfoEvent(uint64 serverConnectionHandlerID, uint64 channelID, const char *name, uint64 size, - uint64 datetime) override { - } - - void onServerGroupListEvent(uint64 serverConnectionHandlerID, uint64 serverGroupID, const char *name, int type, - int iconID, int saveDB) override { - } - - void onServerGroupListFinishedEvent(uint64 serverConnectionHandlerID) override { - } - - void onServerGroupByClientIDEvent(uint64 serverConnectionHandlerID, const char *name, uint64 serverGroupList, - uint64 clientDatabaseID) override { - } - - void onServerGroupPermListEvent(uint64 serverConnectionHandlerID, uint64 serverGroupID, unsigned permissionID, - int permissionValue, int permissionNegated, int permissionSkip) override { - } - - void onServerGroupPermListFinishedEvent(uint64 serverConnectionHandlerID, uint64 serverGroupID) override { - } - - void onServerGroupClientListEvent(uint64 serverConnectionHandlerID, uint64 serverGroupID, uint64 clientDatabaseID, - const char *clientNameIdentifier, const char *clientUniqueID) override { - } - - void onChannelGroupListEvent(uint64 serverConnectionHandlerID, uint64 channelGroupID, const char *name, int type, - int iconID, int saveDB) override { - } - - void onChannelGroupListFinishedEvent(uint64 serverConnectionHandlerID) override { - } - - void onChannelGroupPermListEvent(uint64 serverConnectionHandlerID, uint64 channelGroupID, unsigned permissionID, - int permissionValue, int permissionNegated, int permissionSkip) override { - } - - void onChannelGroupPermListFinishedEvent(uint64 serverConnectionHandlerID, uint64 channelGroupID) override { - } - - void onChannelPermListEvent(uint64 serverConnectionHandlerID, uint64 channelID, unsigned permissionID, - int permissionValue, int permissionNegated, int permissionSkip) override { - } - - void onChannelPermListFinishedEvent(uint64 serverConnectionHandlerID, uint64 channelID) override { - } - - void onClientPermListEvent(uint64 serverConnectionHandlerID, uint64 clientDatabaseID, unsigned permissionID, - int permissionValue, int permissionNegated, int permissionSkip) override { - } - - void onClientPermListFinishedEvent(uint64 serverConnectionHandlerID, uint64 clientDatabaseID) override { - } - - void onChannelClientPermListEvent(uint64 serverConnectionHandlerID, uint64 channelID, uint64 clientDatabaseID, - unsigned permissionID, int permissionValue, int permissionNegated, - int permissionSkip) override { - } - - void onChannelClientPermListFinishedEvent(uint64 serverConnectionHandlerID, uint64 channelID, - uint64 clientDatabaseID) override { - } - - void onClientChannelGroupChangedEvent(uint64 serverConnectionHandlerID, uint64 channelGroupID, uint64 channelID, - anyID clientID, anyID invokerClientID, const char *invokerName, - const char *invokerUniqueIdentity) override { - } - - int onServerPermissionErrorEvent(uint64 serverConnectionHandlerID, const char *errorMessage, unsigned error, - const char *returnCode, unsigned failedPermissionID) override { - } - - void onPermissionListGroupEndIDEvent(uint64 serverConnectionHandlerID, unsigned groupEndID) override { - } - - void onPermissionListEvent(uint64 serverConnectionHandlerID, unsigned permissionID, const char *permissionName, - const char *permissionDescription) override { - } - - void onPermissionListFinishedEvent(uint64 serverConnectionHandlerID) override { - } - - void onPermissionOverviewEvent(uint64 serverConnectionHandlerID, uint64 clientDatabaseID, uint64 channelID, - int overviewType, uint64 overviewID1, uint64 overviewID2, unsigned permissionID, - int permissionValue, - int permissionNegated, int permissionSkip) override { - } - - void onPermissionOverviewFinishedEvent(uint64 serverConnectionHandlerID) override { - } - - void onServerGroupClientAddedEvent(uint64 serverConnectionHandlerID, anyID clientID, const char *clientName, - const char *clientUniqueIdentity, uint64 serverGroupID, anyID invokerClientID, - const char *invokerName, - const char *invokerUniqueIdentity) override { - } - - void onServerGroupClientDeletedEvent(uint64 serverConnectionHandlerID, anyID clientID, const char *clientName, - const char *clientUniqueIdentity, uint64 serverGroupID, anyID invokerClientID, - const char *invokerName, - const char *invokerUniqueIdentity) override { - } - - void onClientNeededPermissionsEvent(uint64 serverConnectionHandlerID, unsigned permissionID, - int permissionValue) override { - } - - void onClientNeededPermissionsFinishedEvent(uint64 serverConnectionHandlerID) override { - } - - void onFileTransferStatusEvent(anyID transferID, unsigned status, const char *statusMessage, uint64 remotefileSize, - uint64 serverConnectionHandlerID) override { - } - - void onClientChatClosedEvent(uint64 serverConnectionHandlerID, anyID clientID, - const char *clientUniqueIdentity) override { - } - - void onClientChatComposingEvent(uint64 serverConnectionHandlerID, anyID clientID, - const char *clientUniqueIdentity) override { - } - - void onServerLogEvent(uint64 serverConnectionHandlerID, const char *logMsg) override { - } - - void onServerLogFinishedEvent(uint64 serverConnectionHandlerID, uint64 lastPos, uint64 fileSize) override { - } - - void onMessageListEvent(uint64 serverConnectionHandlerID, uint64 messageID, const char *fromClientUniqueIdentity, - const char *subject, uint64 timestamp, int flagRead) override { - } - - void onMessageGetEvent(uint64 serverConnectionHandlerID, uint64 messageID, const char *fromClientUniqueIdentity, - const char *subject, const char *message, uint64 timestamp) override { - } - - void onClientDBIDfromUIDEvent(uint64 serverConnectionHandlerID, const char *uniqueClientIdentifier, - uint64 clientDatabaseID) override { - } - - void onClientNamefromUIDEvent(uint64 serverConnectionHandlerID, const char *uniqueClientIdentifier, - uint64 clientDatabaseID, const char *clientNickName) override { - } - - void onClientNamefromDBIDEvent(uint64 serverConnectionHandlerID, const char *uniqueClientIdentifier, - uint64 clientDatabaseID, const char *clientNickName) override { - } - - void onComplainListEvent(uint64 serverConnectionHandlerID, uint64 targetClientDatabaseID, - const char *targetClientNickName, uint64 fromClientDatabaseID, - const char *fromClientNickName, - const char *complainReason, uint64 timestamp) override { - } - - void onBanListEvent(uint64 serverConnectionHandlerID, uint64 banid, const char *ip, const char *name, const char *uid, - const char *mytsid, uint64 creationTime, uint64 durationTime, const char *invokerName, - uint64 invokercldbid, - const char *invokeruid, const char *reason, int numberOfEnforcements, - const char *lastNickName) override { - } - - void onClientServerQueryLoginPasswordEvent(uint64 serverConnectionHandlerID, const char *loginPassword) override { - } - - void onPluginCommandEvent(uint64 serverConnectionHandlerID, const char *pluginName, const char *pluginCommand, - anyID invokerClientID, const char *invokerName, - const char *invokerUniqueIdentity) override { - } - - void onIncomingClientQueryEvent(uint64 serverConnectionHandlerID, const char *commandText) override { - } - - void onServerTemporaryPasswordListEvent(uint64 serverConnectionHandlerID, const char *clientNickname, - const char *uniqueClientIdentifier, const char *description, - const char *password, uint64 timestampStart, - uint64 timestampEnd, uint64 targetChannelID, - const char *targetChannelPW) override { - } - - void onAvatarUpdated(uint64 serverConnectionHandlerID, anyID clientID, const char *avatarPath) override { - } - - void onMenuItemEvent(uint64 serverConnectionHandlerID, PluginMenuType type, int menuItemID, - uint64 selectedItemID) override { - } - - void onHotkeyEvent(const char *keyword) override { - } - - void onHotkeyRecordedEvent(const char *keyword, const char *key) override { - } - - void onClientDisplayNameChanged(uint64 serverConnectionHandlerID, anyID clientID, const char *displayName, - const char *uniqueClientIdentifier) override { - } +class EchoionCore : public IEchoionPlugin +{ + // Dependencies + std::shared_ptr m_ts3; + std::unique_ptr m_musicManager; + + public: + + explicit EchoionCore(std::shared_ptr funcs) + { + m_ts3 = std::move(funcs); + } + + void Initialize(bool start = true) override; + + void Shutdown() override; + + // --- HOT RELOAD --- + void RequestGracefulStop() override; + + bool IsStopped() override; + + std::string SerializeState() override; + + void DeserializeState(const std::string &jsonState) override; + + void onConnectStatusChangeEvent(uint64 serverConnectionHandlerID, + int newStatus, + unsigned errorNumber) override + { + } + + void onNewChannelEvent(uint64 serverConnectionHandlerID, + uint64 channelID, + uint64 channelParentID) override + { + } + + void onNewChannelCreatedEvent( + uint64 serverConnectionHandlerID, uint64 channelID, + uint64 channelParentID, anyID invokerID, const char *invokerName, + const char *invokerUniqueIdentifier) override + { + } + + void onDelChannelEvent(uint64 serverConnectionHandlerID, + uint64 channelID, anyID invokerID, + const char *invokerName, + const char *invokerUniqueIdentifier) override + { + } + + void onChannelMoveEvent(uint64 serverConnectionHandlerID, + uint64 channelID, uint64 newChannelParentID, + anyID invokerID, const char *invokerName, + const char *invokerUniqueIdentifier) override + { + } + + void onUpdateChannelEvent(uint64 serverConnectionHandlerID, + uint64 channelID) override + { + } + + void onUpdateChannelEditedEvent( + uint64 serverConnectionHandlerID, uint64 channelID, anyID invokerID, + const char *invokerName, + const char *invokerUniqueIdentifier) override + { + } + + void onUpdateClientEvent(uint64 serverConnectionHandlerID, + anyID clientID, anyID invokerID, + const char *invokerName, + const char *invokerUniqueIdentifier) override + { + } + + void onClientMoveEvent(uint64 serverConnectionHandlerID, anyID clientID, + uint64 oldChannelID, uint64 newChannelID, + int visibility, + const char *moveMessage) override; + + void onClientMoveSubscriptionEvent(uint64 serverConnectionHandlerID, + anyID clientID, uint64 oldChannelID, + uint64 newChannelID, + int visibility) override + { + } + + void onClientMoveTimeoutEvent(uint64 serverConnectionHandlerID, + anyID clientID, uint64 oldChannelID, + uint64 newChannelID, int visibility, + const char *timeoutMessage) override + { + } + + void onClientMoveMovedEvent(uint64 serverConnectionHandlerID, + anyID clientID, uint64 oldChannelID, + uint64 newChannelID, int visibility, + anyID moverID, const char *moverName, + const char *moverUniqueIdentifier, + const char *moveMessage) override + { + } + + void onClientKickFromChannelEvent(uint64 serverConnectionHandlerID, + anyID clientID, uint64 oldChannelID, + uint64 newChannelID, int visibility, + anyID kickerID, + const char *kickerName, + const char *kickerUniqueIdentifier, + const char *kickMessage) override + { + } + + void onClientKickFromServerEvent(uint64 serverConnectionHandlerID, + anyID clientID, uint64 oldChannelID, + uint64 newChannelID, int visibility, + anyID kickerID, const char *kickerName, + const char *kickerUniqueIdentifier, + const char *kickMessage) override + { + } + + void onClientIDsEvent(uint64 serverConnectionHandlerID, + const char *uniqueClientIdentifier, + anyID clientID, const char *clientName) override + { + } + + void onClientIDsFinishedEvent(uint64 serverConnectionHandlerID) override + { + } + + void onServerEditedEvent(uint64 serverConnectionHandlerID, + anyID editerID, const char *editerName, + const char *editerUniqueIdentifier) override + { + } + + void onServerUpdatedEvent(uint64 serverConnectionHandlerID) override {} + + int onServerErrorEvent(uint64 serverConnectionHandlerID, + const char *errorMessage, unsigned error, + const char *returnCode, + const char *extraMessage) override + { + return 0; + } + + void onServerStopEvent(uint64 serverConnectionHandlerID, + const char *shutdownMessage) override + { + } + + int onTextMessageEvent(uint64 serverConnectionHandlerID, + anyID targetMode, anyID toID, anyID fromID, + const char *fromName, + const char *fromUniqueIdentifier, + const char *message, int ffIgnored) override; + + void onTalkStatusChangeEvent(uint64 serverConnectionHandlerID, + int status, int isReceivedWhisper, + anyID clientID) override + { + } + + void onConnectionInfoEvent(uint64 serverConnectionHandlerID, + anyID clientID) override + { + } + + void onServerConnectionInfoEvent( + uint64 serverConnectionHandlerID) override + { + } + + void onChannelSubscribeEvent(uint64 serverConnectionHandlerID, + uint64 channelID) override + { + } + + void onChannelSubscribeFinishedEvent( + uint64 serverConnectionHandlerID) override + { + } + + void onChannelUnsubscribeEvent(uint64 serverConnectionHandlerID, + uint64 channelID) override + { + } + + void onChannelUnsubscribeFinishedEvent( + uint64 serverConnectionHandlerID) override + { + } + + void onChannelDescriptionUpdateEvent(uint64 serverConnectionHandlerID, + uint64 channelID) override + { + } + + void onChannelPasswordChangedEvent(uint64 serverConnectionHandlerID, + uint64 channelID) override + { + } + + void onPlaybackShutdownCompleteEvent( + uint64 serverConnectionHandlerID) override + { + } + + void onSoundDeviceListChangedEvent(const char *modeID, + int playOrCap) override + { + } + + void onEditPlaybackVoiceDataEvent(uint64 serverConnectionHandlerID, + anyID clientID, short *samples, + int sampleCount, + int channels) override + { + } + + void onEditPostProcessVoiceDataEvent( + uint64 serverConnectionHandlerID, anyID clientID, short *samples, + int sampleCount, int channels, const unsigned *channelSpeakerArray, + unsigned *channelFillMask) override + { + } + + void onEditMixedPlaybackVoiceDataEvent( + uint64 serverConnectionHandlerID, short *samples, int sampleCount, + int channels, const unsigned *channelSpeakerArray, + unsigned *channelFillMask) override + { + } + + void onEditCapturedVoiceDataEvent(uint64 serverConnectionHandlerID, + short *samples, int sampleCount, + int channels, int *edited) override + { + } + + void onCustom3dRolloffCalculationClientEvent( + uint64 serverConnectionHandlerID, anyID clientID, float distance, + float *volume) override + { + } + + void onCustom3dRolloffCalculationWaveEvent( + uint64 serverConnectionHandlerID, uint64 waveHandle, float distance, + float *volume) override + { + } + + void onUserLoggingMessageEvent(const char *logMessage, int logLevel, + const char *logChannel, uint64 logID, + const char *logTime, + const char *completeLogString) override + { + } + + void onClientBanFromServerEvent(uint64 serverConnectionHandlerID, + anyID clientID, uint64 oldChannelID, + uint64 newChannelID, int visibility, + anyID kickerID, const char *kickerName, + const char *kickerUniqueIdentifier, + uint64 time, + const char *kickMessage) override + { + } + + int onClientPokeEvent(uint64 serverConnectionHandlerID, + anyID fromClientID, const char *pokerName, + const char *pokerUniqueIdentity, + const char *message, int ffIgnored) override + { + return 0; + } + + void onClientSelfVariableUpdateEvent(uint64 serverConnectionHandlerID, + int flag, const char *oldValue, + const char *newValue) override + { + } + + void onFileListEvent(uint64 serverConnectionHandlerID, uint64 channelID, + const char *path, const char *name, uint64 size, + uint64 datetime, int type, uint64 incompletesize, + const char *returnCode) override + { + } + + void onFileListFinishedEvent(uint64 serverConnectionHandlerID, + uint64 channelID, + const char *path) override + { + } + + void onFileInfoEvent(uint64 serverConnectionHandlerID, uint64 channelID, + const char *name, uint64 size, + uint64 datetime) override + { + } + + void onServerGroupListEvent(uint64 serverConnectionHandlerID, + uint64 serverGroupID, const char *name, + int type, int iconID, int saveDB) override + { + } + + void onServerGroupListFinishedEvent( + uint64 serverConnectionHandlerID) override + { + } + + void onServerGroupByClientIDEvent(uint64 serverConnectionHandlerID, + const char *name, + uint64 serverGroupList, + uint64 clientDatabaseID) override + { + } + + void onServerGroupPermListEvent(uint64 serverConnectionHandlerID, + uint64 serverGroupID, + unsigned permissionID, + int permissionValue, + int permissionNegated, + int permissionSkip) override + { + } + + void + onServerGroupPermListFinishedEvent(uint64 serverConnectionHandlerID, + uint64 serverGroupID) override + { + } + + void onServerGroupClientListEvent(uint64 serverConnectionHandlerID, + uint64 serverGroupID, + uint64 clientDatabaseID, + const char *clientNameIdentifier, + const char *clientUniqueID) override + { + } + + void onChannelGroupListEvent(uint64 serverConnectionHandlerID, + uint64 channelGroupID, const char *name, + int type, int iconID, int saveDB) override + { + } + + void onChannelGroupListFinishedEvent( + uint64 serverConnectionHandlerID) override + { + } + + void onChannelGroupPermListEvent(uint64 serverConnectionHandlerID, + uint64 channelGroupID, + unsigned permissionID, + int permissionValue, + int permissionNegated, + int permissionSkip) override + { + } + + void onChannelGroupPermListFinishedEvent( + uint64 serverConnectionHandlerID, uint64 channelGroupID) override + { + } + + void onChannelPermListEvent(uint64 serverConnectionHandlerID, + uint64 channelID, unsigned permissionID, + int permissionValue, int permissionNegated, + int permissionSkip) override + { + } + + void onChannelPermListFinishedEvent(uint64 serverConnectionHandlerID, + uint64 channelID) override + { + } + + void onClientPermListEvent(uint64 serverConnectionHandlerID, + uint64 clientDatabaseID, + unsigned permissionID, int permissionValue, + int permissionNegated, + int permissionSkip) override + { + } + + void onClientPermListFinishedEvent(uint64 serverConnectionHandlerID, + uint64 clientDatabaseID) override + { + } + + void onChannelClientPermListEvent( + uint64 serverConnectionHandlerID, uint64 channelID, + uint64 clientDatabaseID, unsigned permissionID, int permissionValue, + int permissionNegated, int permissionSkip) override + { + } + + void onChannelClientPermListFinishedEvent( + uint64 serverConnectionHandlerID, + uint64 channelID, + uint64 clientDatabaseID) override + { + } + + void onClientChannelGroupChangedEvent( + uint64 serverConnectionHandlerID, uint64 channelGroupID, + uint64 channelID, anyID clientID, anyID invokerClientID, + const char *invokerName, const char *invokerUniqueIdentity) override + { + } + + int onServerPermissionErrorEvent(uint64 serverConnectionHandlerID, + const char *errorMessage, + unsigned error, const char *returnCode, + unsigned failedPermissionID) override + { + } + + void onPermissionListGroupEndIDEvent(uint64 serverConnectionHandlerID, + unsigned groupEndID) override + { + } + + void onPermissionListEvent(uint64 serverConnectionHandlerID, + unsigned permissionID, + const char *permissionName, + const char *permissionDescription) override + { + } + + void onPermissionListFinishedEvent( + uint64 serverConnectionHandlerID) override + { + } + + void onPermissionOverviewEvent( + uint64 serverConnectionHandlerID, uint64 clientDatabaseID, + uint64 channelID, int overviewType, uint64 overviewID1, + uint64 overviewID2, unsigned permissionID, int permissionValue, + int permissionNegated, int permissionSkip) override + { + } + + void onPermissionOverviewFinishedEvent( + uint64 serverConnectionHandlerID) override + { + } + + void onServerGroupClientAddedEvent( + uint64 serverConnectionHandlerID, anyID clientID, + const char *clientName, const char *clientUniqueIdentity, + uint64 serverGroupID, anyID invokerClientID, + const char *invokerName, const char *invokerUniqueIdentity) override + { + } + + void onServerGroupClientDeletedEvent( + uint64 serverConnectionHandlerID, anyID clientID, + const char *clientName, const char *clientUniqueIdentity, + uint64 serverGroupID, anyID invokerClientID, + const char *invokerName, const char *invokerUniqueIdentity) override + { + } + + void onClientNeededPermissionsEvent(uint64 serverConnectionHandlerID, + unsigned permissionID, + int permissionValue) override + { + } + + void onClientNeededPermissionsFinishedEvent( + uint64 serverConnectionHandlerID) override + { + } + + void onFileTransferStatusEvent( + anyID transferID, unsigned status, const char *statusMessage, + uint64 remotefileSize, uint64 serverConnectionHandlerID) override + { + } + + void onClientChatClosedEvent(uint64 serverConnectionHandlerID, + anyID clientID, + const char *clientUniqueIdentity) override + { + } + + void onClientChatComposingEvent( + uint64 serverConnectionHandlerID, + anyID clientID, + const char *clientUniqueIdentity) override + { + } + + void onServerLogEvent(uint64 serverConnectionHandlerID, + const char *logMsg) override + { + } + + void onServerLogFinishedEvent(uint64 serverConnectionHandlerID, + uint64 lastPos, uint64 fileSize) override + { + } + + void onMessageListEvent(uint64 serverConnectionHandlerID, + uint64 messageID, + const char *fromClientUniqueIdentity, + const char *subject, uint64 timestamp, + int flagRead) override + { + } + + void onMessageGetEvent(uint64 serverConnectionHandlerID, + uint64 messageID, + const char *fromClientUniqueIdentity, + const char *subject, const char *message, + uint64 timestamp) override + { + } + + void onClientDBIDfromUIDEvent(uint64 serverConnectionHandlerID, + const char *uniqueClientIdentifier, + uint64 clientDatabaseID) override + { + } + + void onClientNamefromUIDEvent(uint64 serverConnectionHandlerID, + const char *uniqueClientIdentifier, + uint64 clientDatabaseID, + const char *clientNickName) override + { + } + + void onClientNamefromDBIDEvent(uint64 serverConnectionHandlerID, + const char *uniqueClientIdentifier, + uint64 clientDatabaseID, + const char *clientNickName) override + { + } + + void onComplainListEvent(uint64 serverConnectionHandlerID, + uint64 targetClientDatabaseID, + const char *targetClientNickName, + uint64 fromClientDatabaseID, + const char *fromClientNickName, + const char *complainReason, + uint64 timestamp) override + { + } + + void onBanListEvent(uint64 serverConnectionHandlerID, uint64 banid, + const char *ip, const char *name, const char *uid, + const char *mytsid, uint64 creationTime, + uint64 durationTime, const char *invokerName, + uint64 invokercldbid, const char *invokeruid, + const char *reason, int numberOfEnforcements, + const char *lastNickName) override + { + } + + void onClientServerQueryLoginPasswordEvent( + uint64 serverConnectionHandlerID, + const char *loginPassword) override + { + } + + void onPluginCommandEvent(uint64 serverConnectionHandlerID, + const char *pluginName, + const char *pluginCommand, + anyID invokerClientID, + const char *invokerName, + const char *invokerUniqueIdentity) override + { + } + + void onIncomingClientQueryEvent(uint64 serverConnectionHandlerID, + const char *commandText) override + { + } + + void onServerTemporaryPasswordListEvent( + uint64 serverConnectionHandlerID, const char *clientNickname, + const char *uniqueClientIdentifier, const char *description, + const char *password, uint64 timestampStart, uint64 timestampEnd, + uint64 targetChannelID, const char *targetChannelPW) override + { + } + + void onAvatarUpdated(uint64 serverConnectionHandlerID, anyID clientID, + const char *avatarPath) override + { + } + + void onMenuItemEvent(uint64 serverConnectionHandlerID, + PluginMenuType type, int menuItemID, + uint64 selectedItemID) override + { + } + + void onHotkeyEvent(const char *keyword) override {} + + void onHotkeyRecordedEvent(const char *keyword, + const char *key) override + { + } + + void onClientDisplayNameChanged( + uint64 serverConnectionHandlerID, anyID clientID, + const char *displayName, + const char *uniqueClientIdentifier) override + { + } }; extern "C" { - IEchoionPlugin *CreatePlugin(const TS3Functions* funcs) { - return new EchoionCore(std::make_shared(*funcs)); +IEchoionPlugin *CreatePlugin(const TS3Functions *funcs) +{ + return new EchoionCore(std::make_shared(*funcs)); } - void DestroyPlugin(const IEchoionPlugin *plugin) { - delete plugin; - } +void DestroyPlugin(const IEchoionPlugin *plugin) { delete plugin; } } diff --git a/include/Core/PluginDefinitions.hpp b/include/Core/PluginDefinitions.hpp index d8b99d0..9bf34e0 100644 --- a/include/Core/PluginDefinitions.hpp +++ b/include/Core/PluginDefinitions.hpp @@ -1,79 +1,85 @@ #pragma once +#include #include #include #include #include #include -#include -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; - struct QueueItem { - std::string name; - std::string videoId; - std::string shortUrl; - std::string length; - std::string requester; - std::optional 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) + : 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) - : 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 queue; - std::vector onlineSubscribers; - std::vector offlineSubscribers; - std::uint64_t serverConnection; - bool wasPlaying = false; - }; -} + struct PluginState { + std::vector queue; + std::vector onlineSubscribers; + std::vector offlineSubscribers; + std::uint64_t serverConnection; + bool wasPlaying = false; + }; +} // namespace definitions template <> struct glz::meta { - 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 { - 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 { - 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); -}; \ No newline at end of file + 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); +}; diff --git a/include/Core/Singleton.hpp b/include/Core/Singleton.hpp index 1ce9aed..ac71dd4 100644 --- a/include/Core/Singleton.hpp +++ b/include/Core/Singleton.hpp @@ -1,77 +1,93 @@ #pragma once +#include #include #include -#include #include /** * @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 -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 - ConstructorProxy(Args&&... args) : T(std::forward(args)...) {} - }; -public: - // Delete copy/move - Singleton(const Singleton&) = delete; - Singleton& operator=(const Singleton&) = delete; +template class Singleton +{ + private: - template - static std::shared_ptr 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 + ConstructorProxy(Args &&...args) + : T(std::forward(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. - ptr = std::make_shared(std::forward(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 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 + static std::shared_ptr 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. + ptr = std::make_shared( + std::forward(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 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 is a C++20 feature, perfect for C++26 - static inline std::atomic> m_instance{nullptr}; - static inline std::mutex m_lifecycle_mutex; -}; \ No newline at end of file + /** + * @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 is a C++20 feature, perfect for C++26 + static inline std::atomic> m_instance{nullptr}; + static inline std::mutex m_lifecycle_mutex; +}; diff --git a/include/Core/SingletonManager.hpp b/include/Core/SingletonManager.hpp index f1800ba..a53d136 100644 --- a/include/Core/SingletonManager.hpp +++ b/include/Core/SingletonManager.hpp @@ -1,30 +1,40 @@ -#include -#include #include +#include #include +#include -class SingletonManager { -public: - // Priority: Higher numbers are destroyed LAST (e.g., Logger = 100) - static void registerShutdown(const int priority, const std::function &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& 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 func; }; - static inline std::vector 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 func; + }; + static inline std::vector m_registry; }; diff --git a/include/Core/Spotify/Client.hpp b/include/Core/Spotify/Client.hpp index 53d3cff..f64f0a7 100644 --- a/include/Core/Spotify/Client.hpp +++ b/include/Core/Spotify/Client.hpp @@ -14,319 +14,358 @@ #include #include -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 using Result = std::expected; + template using Result = std::expected; -// ============================================================================ -// 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 market = {}) - -> Result; + // ======================================================================== + // Albums API + // ======================================================================== - auto GetAlbums(const std::vector &ids, - std::optional market = {}) - -> Result>; + auto GetAlbum(const std::string &id, + std::optional market = {}) + -> Result; - auto GetAlbumTracks(const std::string &id, - const Request::AlbumTracksParams ¶ms = {}) - -> Result>; + auto GetAlbums(const std::vector &ids, + std::optional market = {}) + -> Result>; - auto GetSavedAlbums(const Request::PaginationParams ¶ms = {}) - -> Result>; + auto GetAlbumTracks(const std::string &id, + const Request::AlbumTracksParams ¶ms = {}) + -> Result>; - auto SaveAlbums(const std::vector &ids) -> Result; + auto GetSavedAlbums(const Request::PaginationParams ¶ms = {}) + -> Result>; - auto RemoveSavedAlbums(const std::vector &ids) -> Result; + auto SaveAlbums(const std::vector &ids) + -> Result; - auto CheckSavedAlbums(const std::vector &ids) - -> Result>; + auto RemoveSavedAlbums(const std::vector &ids) + -> Result; - auto GetNewReleases(const Request::PaginationParams ¶ms = {}) - -> Result>; + auto CheckSavedAlbums(const std::vector &ids) + -> Result>; - // ======================================================================== - // Artists API - // ======================================================================== + auto GetNewReleases(const Request::PaginationParams ¶ms = {}) + -> Result>; - auto GetArtist(const std::string &id) -> Result; + // ======================================================================== + // Artists API + // ======================================================================== - auto GetArtists(const std::vector &ids) - -> Result>; + auto GetArtist(const std::string &id) -> Result; - auto GetArtistAlbums(const std::string &id, - const Request::ArtistAlbumsParams ¶ms = {}) - -> Result>; + auto GetArtists(const std::vector &ids) + -> Result>; - auto GetArtistTopTracks(const std::string &id, const std::string &market) - -> Result>; + auto GetArtistAlbums(const std::string &id, + const Request::ArtistAlbumsParams ¶ms = {}) + -> Result>; - auto GetArtistRelatedArtists(const std::string &id) - -> Result>; + auto GetArtistTopTracks(const std::string &id, + const std::string &market) + -> Result>; - // ======================================================================== - // Tracks API - // ======================================================================== + auto GetArtistRelatedArtists(const std::string &id) + -> Result>; - auto GetTrack(const std::string &id, std::optional market = {}) - -> Result; + // ======================================================================== + // Tracks API + // ======================================================================== - auto GetTracks(const std::vector &ids, - std::optional market = {}) - -> Result>; + auto GetTrack(const std::string &id, + std::optional market = {}) + -> Result; - auto GetSavedTracks(const Request::PaginationParams ¶ms = {}) - -> Result>; + auto GetTracks(const std::vector &ids, + std::optional market = {}) + -> Result>; - auto SaveTracks(const std::vector &ids) -> Result; + auto GetSavedTracks(const Request::PaginationParams ¶ms = {}) + -> Result>; - auto RemoveSavedTracks(const std::vector &ids) -> Result; + auto SaveTracks(const std::vector &ids) + -> Result; - auto CheckSavedTracks(const std::vector &ids) - -> Result>; + auto RemoveSavedTracks(const std::vector &ids) + -> Result; - auto GetAudioFeatures(const std::string &id) -> Result; + auto CheckSavedTracks(const std::vector &ids) + -> Result>; - auto GetAudioFeaturesForTracks(const std::vector &ids) - -> Result>; + auto GetAudioFeatures(const std::string &id) + -> Result; - auto GetAudioAnalysis(const std::string &id) -> Result; + auto GetAudioFeaturesForTracks(const std::vector &ids) + -> Result>; - auto GetRecommendations(const Request::RecommendationParams ¶ms) - -> Result; + auto GetAudioAnalysis(const std::string &id) + -> Result; - // ======================================================================== - // Search API - // ======================================================================== + auto GetRecommendations(const Request::RecommendationParams ¶ms) + -> Result; - auto Search(const Request::SearchParams ¶ms) -> Result; + // ======================================================================== + // Search API + // ======================================================================== - auto SearchTracks(const Request::TrackSearchFilters &filters, - const Request::PaginationParams ¶ms = {}) - -> Result>; + auto Search(const Request::SearchParams ¶ms) + -> Result; - auto SearchAlbums(const Request::AlbumSearchFilters &filters, - const Request::PaginationParams ¶ms = {}) - -> Result>; + auto SearchTracks(const Request::TrackSearchFilters &filters, + const Request::PaginationParams ¶ms = {}) + -> Result>; - auto SearchArtists(const Request::ArtistSearchFilters &filters, - const Request::PaginationParams ¶ms = {}) - -> Result>; + auto SearchAlbums(const Request::AlbumSearchFilters &filters, + const Request::PaginationParams ¶ms = {}) + -> Result>; - // ======================================================================== - // Playlists API - // ======================================================================== + auto SearchArtists(const Request::ArtistSearchFilters &filters, + const Request::PaginationParams ¶ms = {}) + -> Result>; - auto GetPlaylist(const std::string &id, - std::optional market = {}) -> Result; + // ======================================================================== + // Playlists API + // ======================================================================== - auto GetPlaylistTracks(const std::string &id, - const Request::PaginationParams ¶ms = {}) - -> Result>; + auto GetPlaylist(const std::string &id, + std::optional market = {}) + -> Result; - auto CreatePlaylist(const std::string &user_id, - const Request::CreatePlaylistParams ¶ms) - -> Result; + auto GetPlaylistTracks(const std::string &id, + const Request::PaginationParams ¶ms = {}) + -> Result>; - auto UpdatePlaylist(const std::string &id, - const Request::UpdatePlaylistParams ¶ms) - -> Result; + auto CreatePlaylist(const std::string &user_id, + const Request::CreatePlaylistParams ¶ms) + -> Result; - auto AddTracksToPlaylist(const std::string &id, - const Request::AddTracksToPlaylistParams ¶ms) - -> Result; + auto UpdatePlaylist(const std::string &id, + const Request::UpdatePlaylistParams ¶ms) + -> Result; - auto RemoveTracksFromPlaylist( - const std::string &id, - const Request::RemoveTracksFromPlaylistParams ¶ms) - -> Result; + auto AddTracksToPlaylist( + const std::string &id, + const Request::AddTracksToPlaylistParams ¶ms) + -> Result; - auto ReorderPlaylistTracks(const std::string &id, - const Request::ReorderPlaylistParams ¶ms) - -> Result; + auto RemoveTracksFromPlaylist( + const std::string &id, + const Request::RemoveTracksFromPlaylistParams ¶ms) + -> Result; - auto ReplacePlaylistTracks(const std::string &id, - const Request::ReplacePlaylistTracksParams ¶ms) - -> Result; + auto ReorderPlaylistTracks( + const std::string &id, + const Request::ReorderPlaylistParams ¶ms) + -> Result; - auto GetCurrentUserPlaylists(const Request::PaginationParams ¶ms = {}) - -> Result>; + auto ReplacePlaylistTracks( + const std::string &id, + const Request::ReplacePlaylistTracksParams ¶ms) + -> Result; - auto GetUserPlaylists(const std::string &user_id, - const Request::PaginationParams ¶ms = {}) - -> Result>; + auto GetCurrentUserPlaylists( + const Request::PaginationParams ¶ms = {}) + -> Result>; - auto GetFeaturedPlaylists(const Request::PaginationParams ¶ms = {}) - -> Result>; + auto GetUserPlaylists(const std::string &user_id, + const Request::PaginationParams ¶ms = {}) + -> Result>; - auto GetCategoryPlaylists(const std::string &category_id, - const Request::PaginationParams ¶ms = {}) - -> Result>; + auto GetFeaturedPlaylists( + const Request::PaginationParams ¶ms = {}) + -> Result>; - // ======================================================================== - // User API - // ======================================================================== + auto GetCategoryPlaylists( + const std::string &category_id, + const Request::PaginationParams ¶ms = {}) + -> Result>; - auto GetCurrentUser() -> Result; + // ======================================================================== + // User API + // ======================================================================== - auto GetUser(const std::string &user_id) -> Result; + auto GetCurrentUser() -> Result; - auto GetTopArtists(const Request::TopItemsParams ¶ms = {}) - -> Result>; + auto GetUser(const std::string &user_id) -> Result; - auto GetTopTracks(const Request::TopItemsParams ¶ms = {}) - -> Result>; + auto GetTopArtists(const Request::TopItemsParams ¶ms = {}) + -> Result>; - // ======================================================================== - // Follow API - // ======================================================================== + auto GetTopTracks(const Request::TopItemsParams ¶ms = {}) + -> Result>; - auto FollowArtistsOrUsers(const Request::FollowParams ¶ms) - -> Result; + // ======================================================================== + // Follow API + // ======================================================================== - auto UnfollowArtistsOrUsers(const Request::UnfollowParams ¶ms) - -> Result; + auto FollowArtistsOrUsers(const Request::FollowParams ¶ms) + -> Result; - auto CheckFollowingArtistsOrUsers(const Request::CheckFollowingParams ¶ms) - -> Result>; + auto UnfollowArtistsOrUsers(const Request::UnfollowParams ¶ms) + -> Result; - auto GetFollowedArtists(std::optional limit = {}, - std::optional after = {}) - -> Result>; + auto CheckFollowingArtistsOrUsers( + const Request::CheckFollowingParams ¶ms) + -> Result>; - auto FollowPlaylist(const std::string &playlist_id, - const Request::FollowPlaylistParams ¶ms = {}) - -> Result; + auto GetFollowedArtists(std::optional limit = {}, + std::optional after = {}) + -> Result>; - auto UnfollowPlaylist(const std::string &playlist_id) -> Result; + auto + FollowPlaylist(const std::string &playlist_id, + const Request::FollowPlaylistParams ¶ms = {}) + -> Result; - auto CheckFollowingPlaylist(const std::string &playlist_id, - const std::vector &user_ids) - -> Result>; + auto UnfollowPlaylist(const std::string &playlist_id) + -> Result; - // ======================================================================== - // Player API - // ======================================================================== + auto + CheckFollowingPlaylist(const std::string &playlist_id, + const std::vector &user_ids) + -> Result>; - auto GetPlaybackState(std::optional market = {}) - -> Result; + // ======================================================================== + // Player API + // ======================================================================== - auto GetAvailableDevices() -> Result>; + auto GetPlaybackState(std::optional market = {}) + -> Result; - auto GetCurrentlyPlayingTrack(std::optional market = {}) - -> Result; + auto GetAvailableDevices() -> Result>; - auto StartOrResumePlayback(const Request::PlayParams ¶ms, - std::optional device_id = {}) - -> Result; + auto + GetCurrentlyPlayingTrack(std::optional market = {}) + -> Result; - auto PausePlayback(std::optional device_id = {}) -> Result; + auto + StartOrResumePlayback(const Request::PlayParams ¶ms, + std::optional device_id = {}) + -> Result; - auto SkipToNext(std::optional device_id = {}) -> Result; + auto PausePlayback(std::optional device_id = {}) + -> Result; - auto SkipToPrevious(std::optional device_id = {}) - -> Result; + auto SkipToNext(std::optional device_id = {}) + -> Result; - auto SeekToPosition(int position_ms, - std::optional device_id = {}) - -> Result; + auto SkipToPrevious(std::optional device_id = {}) + -> Result; - auto SetRepeatMode(RepeatMode mode, std::optional device_id = {}) - -> Result; + auto SeekToPosition(int position_ms, + std::optional device_id = {}) + -> Result; - auto SetPlaybackVolume(int volume_percent, - std::optional device_id = {}) - -> Result; + auto SetRepeatMode(RepeatMode mode, + std::optional device_id = {}) + -> Result; - auto TogglePlaybackShuffle(bool state, - std::optional device_id = {}) - -> Result; + auto SetPlaybackVolume(int volume_percent, + std::optional device_id = {}) + -> Result; - auto TransferPlayback(const Request::TransferPlaybackParams ¶ms) - -> Result; + auto + TogglePlaybackShuffle(bool state, + std::optional device_id = {}) + -> Result; - auto AddToQueue(const Request::QueueParams ¶ms) -> Result; + auto TransferPlayback(const Request::TransferPlaybackParams ¶ms) + -> Result; - auto GetRecentlyPlayedTracks(std::optional limit = {}, - std::optional after = {}, - std::optional before = {}) - -> Result>; + auto AddToQueue(const Request::QueueParams ¶ms) -> Result; - // ======================================================================== - // Browse API - // ======================================================================== + auto GetRecentlyPlayedTracks(std::optional limit = {}, + std::optional after = {}, + std::optional before = {}) + -> Result>; - auto GetCategories(const Request::PaginationParams ¶ms = {}) - -> Result>; + // ======================================================================== + // Browse API + // ======================================================================== - auto GetCategory(const std::string &category_id, - std::optional locale = {}) -> Result; + auto GetCategories(const Request::PaginationParams ¶ms = {}) + -> Result>; - auto GetAvailableGenreSeeds() -> Result>; + auto GetCategory(const std::string &category_id, + std::optional locale = {}) + -> Result; - auto GetAvailableMarkets() -> Result>; + auto GetAvailableGenreSeeds() -> Result>; -private: - std::string m_AccessToken; - ProxyConfig m_Proxy; - bool m_Verbose = false; + auto GetAvailableMarkets() -> Result>; - auto PerformRequest(const std::string &url, - HttpMethod method = HttpMethod::GET, - const std::string &body = "", - const std::vector &extra_headers = {}) - -> Result; + 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 ¶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 &extra_headers = {}) + -> Result; + + 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 ¶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 diff --git a/include/Core/Spotify/HttpCallbackServer.hpp b/include/Core/Spotify/HttpCallbackServer.hpp index 2c58511..9c571c7 100644 --- a/include/Core/Spotify/HttpCallbackServer.hpp +++ b/include/Core/Spotify/HttpCallbackServer.hpp @@ -4,25 +4,32 @@ #include #include -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 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 + WaitForCallback(std::chrono::milliseconds timeout); -} // namespace ts6bot + private: + + std::string m_Host; + uint16_t m_Port; + std::string m_Path; + }; + +} // namespace Spotify diff --git a/include/Core/Spotify/PkceAuth.hpp b/include/Core/Spotify/PkceAuth.hpp index 0d8428c..92ff7c1 100644 --- a/include/Core/Spotify/PkceAuth.hpp +++ b/include/Core/Spotify/PkceAuth.hpp @@ -11,47 +11,57 @@ #include // 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& 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& 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 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 Load() const; + + static std::int64_t NowUnixSeconds(); + friend TokenSet; + }; + +} // namespace Spotify diff --git a/include/Core/Spotify/RequestParams.hpp b/include/Core/Spotify/RequestParams.hpp index 8345163..0847634 100644 --- a/include/Core/Spotify/RequestParams.hpp +++ b/include/Core/Spotify/RequestParams.hpp @@ -1,496 +1,655 @@ #pragma once +#include +#include +#include +#include +#include #include #include -#include -#include -#include -#include -#include -namespace Spotify::Request { +namespace Spotify::Request +{ -// ============================================================================ -// Base Request Parameter Class -// ============================================================================ + // ============================================================================ + // Base Request Parameter Class + // ============================================================================ -class RequestParams { -public: - virtual ~RequestParams() = default; - virtual auto ToQueryParams() const -> std::map = 0; -}; + class RequestParams + { + public: -// ============================================================================ -// Search Type Enum -// ============================================================================ + virtual ~RequestParams() = default; + virtual auto ToQueryParams() const + -> std::map = 0; + }; -enum class SearchType { - Album, - Artist, - Playlist, - Track, - Show, - Episode, - Audiobook -}; + // ============================================================================ + // Search Type Enum + // ============================================================================ -inline auto SearchTypeToString(SearchType type) -> std::string { - switch (type) { - case SearchType::Album: return "album"; - case SearchType::Artist: return "artist"; - case SearchType::Playlist: return "playlist"; - case SearchType::Track: return "track"; - case SearchType::Show: return "show"; - case SearchType::Episode: return "episode"; - case SearchType::Audiobook: return "audiobook"; - } - return ""; -} + enum class SearchType { + Album, + Artist, + Playlist, + Track, + Show, + Episode, + Audiobook + }; -// ============================================================================ -// Time Range Enum -// ============================================================================ + inline auto SearchTypeToString(SearchType type) -> std::string + { + switch (type) { + case SearchType::Album: + return "album"; + case SearchType::Artist: + return "artist"; + case SearchType::Playlist: + return "playlist"; + case SearchType::Track: + return "track"; + case SearchType::Show: + return "show"; + case SearchType::Episode: + return "episode"; + case SearchType::Audiobook: + return "audiobook"; + } + return ""; + } -enum class TimeRange { - LongTerm, - MediumTerm, - ShortTerm -}; + // ============================================================================ + // Time Range Enum + // ============================================================================ -inline auto TimeRangeToString(TimeRange range) -> std::string { - switch (range) { - case TimeRange::LongTerm: return "long_term"; - case TimeRange::MediumTerm: return "medium_term"; - case TimeRange::ShortTerm: return "short_term"; - } - return "medium_term"; -} + enum class TimeRange { LongTerm, MediumTerm, ShortTerm }; -// ============================================================================ -// Pagination Parameters -// ============================================================================ + inline auto TimeRangeToString(TimeRange range) -> std::string + { + switch (range) { + case TimeRange::LongTerm: + return "long_term"; + case TimeRange::MediumTerm: + return "medium_term"; + case TimeRange::ShortTerm: + return "short_term"; + } + return "medium_term"; + } -struct PaginationParams : public RequestParams { -public: - std::optional limit = 20; - std::optional offset = 0; - std::optional market; - - auto ToQueryParams() const -> std::map override { - std::map params; - if (limit) params["limit"] = std::to_string(*limit); - if (offset) params["offset"] = std::to_string(*offset); - if (market) params["market"] = *market; - return params; - } -}; + // ============================================================================ + // Pagination Parameters + // ============================================================================ -// ============================================================================ -// Search Parameters -// ============================================================================ + struct PaginationParams : public RequestParams { + public: -struct SearchParams : public RequestParams { -public: - //You can narrow down your search using field filters. The available filters are album, artist, track, year, upc, tag:hipster, tag:new, isrc, and genre. Each field filter only applies to certain result types. - //The artist and year filters can be used while searching albums, artists and tracks. You can filter on a single year or a range (e.g. 1955-1960). - //The album filter can be used while searching albums and tracks. - //The genre filter can be used while searching artists and tracks. - //The isrc and track filters can be used while searching tracks. - //The upc, tag:new and tag:hipster filters can only be used while searching albums. The tag:new filter will return albums released in the past two weeks and tag:hipster can be used to return only albums with the lowest 10% popularity. - //Example: q=remaster%2520track%3ADoxy%2520artist%3AMiles%2520Davis - std::string query; - std::vector types; - std::optional market; - std::optional limit = 20; - std::optional offset = 0; - std::optional include_external; - - auto ToQueryParams() const -> std::map override { - std::map params; - params["q"] = query; - - std::vector type_strings; - for (const auto& type : types) { - type_strings.push_back(SearchTypeToString(type)); - } - params["type"] = std::views::join_with(type_strings, ',') | std::ranges::to(); - - if (market) params["market"] = *market; - if (limit) params["limit"] = std::to_string(*limit); - if (offset) params["offset"] = std::to_string(*offset); - if (include_external) params["include_external"] = *include_external ? "audio" : ""; - - return params; - } -}; + std::optional limit = 20; + std::optional offset = 0; + std::optional market; -// ============================================================================ -// Track Search Filters -// ============================================================================ + auto ToQueryParams() const + -> std::map override + { + std::map params; + if (limit) { + params["limit"] = std::to_string(*limit); + } + if (offset) { + params["offset"] = std::to_string(*offset); + } + if (market) { + params["market"] = *market; + } + return params; + } + }; -struct TrackSearchFilters : public RequestParams { -public: - std::optional track; - std::optional artist; - std::optional album; - std::optional year; - std::optional genre; - std::optional isrc; - std::optional upc; - std::optional is_new; - std::optional hipster; - - auto ToQueryString() const -> std::string { - std::vector parts; - - if (track) parts.push_back(std::format("track:{}", *track)); - if (artist) parts.push_back(std::format("artist:{}", *artist)); - if (album) parts.push_back(std::format("album:{}", *album)); - if (year) parts.push_back(std::format("year:{}", *year)); - if (genre) parts.push_back(std::format("genre:{}", *genre)); - if (isrc) parts.push_back(std::format("isrc:{}", *isrc)); - if (upc) parts.push_back(std::format("upc:{}", *upc)); - if (is_new && *is_new) parts.push_back("tag:new"); - if (hipster && *hipster) parts.push_back("tag:hipster"); - - return std::views::join_with(parts, ' ') | std::ranges::to(); - } - - auto ToQueryParams() const -> std::map override { - return {}; - } -}; + // ============================================================================ + // Search Parameters + // ============================================================================ -// ============================================================================ -// Album Search Filters -// ============================================================================ + struct SearchParams : public RequestParams { + public: -struct AlbumSearchFilters : public RequestParams { -public: - std::optional album; - std::optional artist; - std::optional year; - std::optional genre; - std::optional upc; - - auto ToQueryString() const -> std::string { - std::vector parts; - - if (album) parts.push_back(std::format("album:{}", *album)); - if (artist) parts.push_back(std::format("artist:{}", *artist)); - if (year) parts.push_back(std::format("year:{}", *year)); - if (genre) parts.push_back(std::format("genre:{}", *genre)); - if (upc) parts.push_back(std::format("upc:{}", *upc)); - - return std::views::join_with(parts, ' ') | std::ranges::to(); - } - - auto ToQueryParams() const -> std::map override { - return {}; - } -}; + // You can narrow down your search using field filters. The + // available filters are album, artist, track, year, upc, + // tag:hipster, tag:new, isrc, and genre. Each field filter only + // applies to certain result types. The artist and year filters can + // be used while searching albums, artists and tracks. You can + // filter on a single year or a range (e.g. 1955-1960). The album + // filter can be used while searching albums and tracks. The genre + // filter can be used while searching artists and tracks. The isrc + // and track filters can be used while searching tracks. The upc, + // tag:new and tag:hipster filters can only be used while searching + // albums. The tag:new filter will return albums released in the + // past two weeks and tag:hipster can be used to return only albums + // with the lowest 10% popularity. Example: + // q=remaster%2520track%3ADoxy%2520artist%3AMiles%2520Davis + std::string query; + std::vector types; + std::optional market; + std::optional limit = 20; + std::optional offset = 0; + std::optional include_external; -// ============================================================================ -// Artist Search Filters -// ============================================================================ + auto ToQueryParams() const + -> std::map override + { + std::map params; + params["q"] = query; -struct ArtistSearchFilters : public RequestParams { -public: - std::optional artist; - std::optional genre; - - auto ToQueryString() const -> std::string { - std::vector parts; - - if (artist) parts.push_back(std::format("artist:{}", *artist)); - if (genre) parts.push_back(std::format("genre:{}", *genre)); - - return std::views::join_with(parts, ' ') | std::ranges::to(); - } - - auto ToQueryParams() const -> std::map override { - return {}; - } -}; + std::vector type_strings; + for (const auto& type : types) { + type_strings.push_back(SearchTypeToString(type)); + } + params["type"] = std::views::join_with(type_strings, ',') | + std::ranges::to(); -// ============================================================================ -// Album Tracks Parameters -// ============================================================================ + if (market) { + params["market"] = *market; + } + if (limit) { + params["limit"] = std::to_string(*limit); + } + if (offset) { + params["offset"] = std::to_string(*offset); + } + if (include_external) { + params["include_external"] = + *include_external ? "audio" : ""; + } -struct AlbumTracksParams : public RequestParams { -public: - std::optional limit = 20; - std::optional offset = 0; - std::optional market; - - auto ToQueryParams() const -> std::map override { - std::map params; - if (limit) params["limit"] = std::to_string(*limit); - if (offset) params["offset"] = std::to_string(*offset); - if (market) params["market"] = *market; - return params; - } -}; + return params; + } + }; -// ============================================================================ -// Artist Albums Parameters -// ============================================================================ + // ============================================================================ + // Track Search Filters + // ============================================================================ -struct ArtistAlbumsParams : public RequestParams { -public: - std::optional> include_groups; - std::optional market; - std::optional limit = 20; - std::optional offset = 0; - - auto ToQueryParams() const -> std::map override { - std::map params; - - if (include_groups && !include_groups->empty()) { - params["include_groups"] = std::views::join_with(*include_groups, ',') | std::ranges::to(); - } - if (market) params["market"] = *market; - if (limit) params["limit"] = std::to_string(*limit); - if (offset) params["offset"] = std::to_string(*offset); - - return params; - } -}; + struct TrackSearchFilters : public RequestParams { + public: -// ============================================================================ -// Top Items Parameters -// ============================================================================ + std::optional track; + std::optional artist; + std::optional album; + std::optional year; + std::optional genre; + std::optional isrc; + std::optional upc; + std::optional is_new; + std::optional hipster; -struct TopItemsParams : public RequestParams { -public: - std::optional time_range = TimeRange::MediumTerm; - std::optional limit = 20; - std::optional offset = 0; - - auto ToQueryParams() const -> std::map override { - std::map params; - - if (time_range) params["time_range"] = TimeRangeToString(*time_range); - if (limit) params["limit"] = std::to_string(*limit); - if (offset) params["offset"] = std::to_string(*offset); - - return params; - } -}; + auto ToQueryString() const -> std::string + { + std::vector parts; -// ============================================================================ -// Recommendation Parameters -// ============================================================================ + if (track) { + parts.push_back(std::format("track:{}", *track)); + } + if (artist) { + parts.push_back(std::format("artist:{}", *artist)); + } + if (album) { + parts.push_back(std::format("album:{}", *album)); + } + if (year) { + parts.push_back(std::format("year:{}", *year)); + } + if (genre) { + parts.push_back(std::format("genre:{}", *genre)); + } + if (isrc) { + parts.push_back(std::format("isrc:{}", *isrc)); + } + if (upc) { + parts.push_back(std::format("upc:{}", *upc)); + } + if (is_new && *is_new) { + parts.push_back("tag:new"); + } + if (hipster && *hipster) { + parts.push_back("tag:hipster"); + } -struct RecommendationParams : public RequestParams { -public: - std::optional> seed_artists; - std::optional> seed_genres; - std::optional> seed_tracks; - std::optional limit = 20; - std::optional market; - - // Tunable attributes - std::optional min_acousticness; - std::optional max_acousticness; - std::optional target_acousticness; - - std::optional min_danceability; - std::optional max_danceability; - std::optional target_danceability; - - std::optional min_duration_ms; - std::optional max_duration_ms; - std::optional target_duration_ms; - - std::optional min_energy; - std::optional max_energy; - std::optional target_energy; - - std::optional min_instrumentalness; - std::optional max_instrumentalness; - std::optional target_instrumentalness; - - std::optional min_key; - std::optional max_key; - std::optional target_key; - - std::optional min_liveness; - std::optional max_liveness; - std::optional target_liveness; - - std::optional min_loudness; - std::optional max_loudness; - std::optional target_loudness; - - std::optional min_mode; - std::optional max_mode; - std::optional target_mode; - - std::optional min_popularity; - std::optional max_popularity; - std::optional target_popularity; - - std::optional min_speechiness; - std::optional max_speechiness; - std::optional target_speechiness; - - std::optional min_tempo; - std::optional max_tempo; - std::optional target_tempo; - - std::optional min_time_signature; - std::optional max_time_signature; - std::optional target_time_signature; - - std::optional min_valence; - std::optional max_valence; - std::optional target_valence; - - auto ToQueryParams() const -> std::map override { - std::map params; - - if (seed_artists && !seed_artists->empty()) { - params["seed_artists"] = std::views::join_with(*seed_artists, ',') | std::ranges::to(); - } - if (seed_genres && !seed_genres->empty()) { - params["seed_genres"] = std::views::join_with(*seed_genres, ',') | std::ranges::to(); - } - if (seed_tracks && !seed_tracks->empty()) { - params["seed_tracks"] = std::views::join_with(*seed_tracks, ',') | std::ranges::to(); - } - - if (limit) params["limit"] = std::to_string(*limit); - if (market) params["market"] = *market; - - // Add all tunable attributes - if (min_acousticness) params["min_acousticness"] = std::to_string(*min_acousticness); - if (max_acousticness) params["max_acousticness"] = std::to_string(*max_acousticness); - if (target_acousticness) params["target_acousticness"] = std::to_string(*target_acousticness); - - if (min_danceability) params["min_danceability"] = std::to_string(*min_danceability); - if (max_danceability) params["max_danceability"] = std::to_string(*max_danceability); - if (target_danceability) params["target_danceability"] = std::to_string(*target_danceability); - - if (min_energy) params["min_energy"] = std::to_string(*min_energy); - if (max_energy) params["max_energy"] = std::to_string(*max_energy); - if (target_energy) params["target_energy"] = std::to_string(*target_energy); - - if (min_popularity) params["min_popularity"] = std::to_string(*min_popularity); - if (max_popularity) params["max_popularity"] = std::to_string(*max_popularity); - if (target_popularity) params["target_popularity"] = std::to_string(*target_popularity); - - // Add remaining attributes as needed... - - return params; - } -}; + return std::views::join_with(parts, ' ') | + std::ranges::to(); + } -// ============================================================================ -// Create Playlist Parameters -// ============================================================================ + auto ToQueryParams() const + -> std::map override + { + return {}; + } + }; -struct CreatePlaylistParams { - std::string name; - std::optional public_playlist = true; - std::optional collaborative = false; - std::optional description; -}; + // ============================================================================ + // Album Search Filters + // ============================================================================ -// ============================================================================ -// Update Playlist Parameters -// ============================================================================ + struct AlbumSearchFilters : public RequestParams { + public: -struct UpdatePlaylistParams { - std::optional name; - std::optional public_playlist; - std::optional collaborative; - std::optional description; -}; + std::optional album; + std::optional artist; + std::optional year; + std::optional genre; + std::optional upc; -// ============================================================================ -// Playlist Track Operations -// ============================================================================ + auto ToQueryString() const -> std::string + { + std::vector parts; -struct AddTracksToPlaylistParams { - std::vector uris; - std::optional position; -}; + if (album) { + parts.push_back(std::format("album:{}", *album)); + } + if (artist) { + parts.push_back(std::format("artist:{}", *artist)); + } + if (year) { + parts.push_back(std::format("year:{}", *year)); + } + if (genre) { + parts.push_back(std::format("genre:{}", *genre)); + } + if (upc) { + parts.push_back(std::format("upc:{}", *upc)); + } -struct RemoveTracksFromPlaylistParams { - std::vector uris; - std::optional snapshot_id; -}; + return std::views::join_with(parts, ' ') | + std::ranges::to(); + } -struct ReorderPlaylistParams { - int range_start; - int insert_before; - std::optional range_length = 1; - std::optional snapshot_id; -}; + auto ToQueryParams() const + -> std::map override + { + return {}; + } + }; -struct ReplacePlaylistTracksParams { - std::vector uris; -}; + // ============================================================================ + // Artist Search Filters + // ============================================================================ -// ============================================================================ -// Playback Control Parameters -// ============================================================================ + struct ArtistSearchFilters : public RequestParams { + public: -struct PlayParams { - std::optional context_uri; - std::optional> uris; - std::optional> offset; - std::optional position_ms; -}; + std::optional artist; + std::optional genre; -struct TransferPlaybackParams { - std::vector device_ids; - std::optional play; -}; + auto ToQueryString() const -> std::string + { + std::vector parts; -struct QueueParams { - std::string uri; - std::optional device_id; -}; -struct RequestBody { - std::vector ids; -}; + if (artist) { + parts.push_back(std::format("artist:{}", *artist)); + } + if (genre) { + parts.push_back(std::format("genre:{}", *genre)); + } -// ============================================================================ -// Follow Parameters -// ============================================================================ - struct ErrorResponse { - struct Error { - int status; - std::string message; - } error; - }; -enum class FollowType { - Artist, - User -}; + return std::views::join_with(parts, ' ') | + std::ranges::to(); + } -inline auto FollowTypeToString(FollowType type) -> std::string { - return type == FollowType::Artist ? "artist" : "user"; -} + auto ToQueryParams() const + -> std::map override + { + return {}; + } + }; -struct FollowParams { - FollowType type; - std::vector ids; -}; + // ============================================================================ + // Album Tracks Parameters + // ============================================================================ -struct UnfollowParams { - FollowType type; - std::vector ids; -}; + struct AlbumTracksParams : public RequestParams { + public: -struct CheckFollowingParams { - FollowType type; - std::vector ids; -}; + std::optional limit = 20; + std::optional offset = 0; + std::optional market; -struct FollowPlaylistParams { - std::optional public_playlist = true; -}; + auto ToQueryParams() const + -> std::map override + { + std::map params; + if (limit) { + params["limit"] = std::to_string(*limit); + } + if (offset) { + params["offset"] = std::to_string(*offset); + } + if (market) { + params["market"] = *market; + } + return params; + } + }; -} // namespace Spotify::Request \ No newline at end of file + // ============================================================================ + // Artist Albums Parameters + // ============================================================================ + + struct ArtistAlbumsParams : public RequestParams { + public: + + std::optional> include_groups; + std::optional market; + std::optional limit = 20; + std::optional offset = 0; + + auto ToQueryParams() const + -> std::map override + { + std::map params; + + if (include_groups && !include_groups->empty()) { + params["include_groups"] = + std::views::join_with(*include_groups, ',') | + std::ranges::to(); + } + if (market) { + params["market"] = *market; + } + if (limit) { + params["limit"] = std::to_string(*limit); + } + if (offset) { + params["offset"] = std::to_string(*offset); + } + + return params; + } + }; + + // ============================================================================ + // Top Items Parameters + // ============================================================================ + + struct TopItemsParams : public RequestParams { + public: + + std::optional time_range = TimeRange::MediumTerm; + std::optional limit = 20; + std::optional offset = 0; + + auto ToQueryParams() const + -> std::map override + { + std::map params; + + if (time_range) { + params["time_range"] = TimeRangeToString(*time_range); + } + if (limit) { + params["limit"] = std::to_string(*limit); + } + if (offset) { + params["offset"] = std::to_string(*offset); + } + + return params; + } + }; + + // ============================================================================ + // Recommendation Parameters + // ============================================================================ + + struct RecommendationParams : public RequestParams { + public: + + std::optional> seed_artists; + std::optional> seed_genres; + std::optional> seed_tracks; + std::optional limit = 20; + std::optional market; + + // Tunable attributes + std::optional min_acousticness; + std::optional max_acousticness; + std::optional target_acousticness; + + std::optional min_danceability; + std::optional max_danceability; + std::optional target_danceability; + + std::optional min_duration_ms; + std::optional max_duration_ms; + std::optional target_duration_ms; + + std::optional min_energy; + std::optional max_energy; + std::optional target_energy; + + std::optional min_instrumentalness; + std::optional max_instrumentalness; + std::optional target_instrumentalness; + + std::optional min_key; + std::optional max_key; + std::optional target_key; + + std::optional min_liveness; + std::optional max_liveness; + std::optional target_liveness; + + std::optional min_loudness; + std::optional max_loudness; + std::optional target_loudness; + + std::optional min_mode; + std::optional max_mode; + std::optional target_mode; + + std::optional min_popularity; + std::optional max_popularity; + std::optional target_popularity; + + std::optional min_speechiness; + std::optional max_speechiness; + std::optional target_speechiness; + + std::optional min_tempo; + std::optional max_tempo; + std::optional target_tempo; + + std::optional min_time_signature; + std::optional max_time_signature; + std::optional target_time_signature; + + std::optional min_valence; + std::optional max_valence; + std::optional target_valence; + + auto ToQueryParams() const + -> std::map override + { + std::map params; + + if (seed_artists && !seed_artists->empty()) { + params["seed_artists"] = + std::views::join_with(*seed_artists, ',') | + std::ranges::to(); + } + if (seed_genres && !seed_genres->empty()) { + params["seed_genres"] = + std::views::join_with(*seed_genres, ',') | + std::ranges::to(); + } + if (seed_tracks && !seed_tracks->empty()) { + params["seed_tracks"] = + std::views::join_with(*seed_tracks, ',') | + std::ranges::to(); + } + + if (limit) { + params["limit"] = std::to_string(*limit); + } + if (market) { + params["market"] = *market; + } + + // Add all tunable attributes + if (min_acousticness) { + params["min_acousticness"] = + std::to_string(*min_acousticness); + } + if (max_acousticness) { + params["max_acousticness"] = + std::to_string(*max_acousticness); + } + if (target_acousticness) { + params["target_acousticness"] = + std::to_string(*target_acousticness); + } + + if (min_danceability) { + params["min_danceability"] = + std::to_string(*min_danceability); + } + if (max_danceability) { + params["max_danceability"] = + std::to_string(*max_danceability); + } + if (target_danceability) { + params["target_danceability"] = + std::to_string(*target_danceability); + } + + if (min_energy) { + params["min_energy"] = std::to_string(*min_energy); + } + if (max_energy) { + params["max_energy"] = std::to_string(*max_energy); + } + if (target_energy) { + params["target_energy"] = std::to_string(*target_energy); + } + + if (min_popularity) { + params["min_popularity"] = std::to_string(*min_popularity); + } + if (max_popularity) { + params["max_popularity"] = std::to_string(*max_popularity); + } + if (target_popularity) { + params["target_popularity"] = + std::to_string(*target_popularity); + } + + // Add remaining attributes as needed... + + return params; + } + }; + + // ============================================================================ + // Create Playlist Parameters + // ============================================================================ + + struct CreatePlaylistParams { + std::string name; + std::optional public_playlist = true; + std::optional collaborative = false; + std::optional description; + }; + + // ============================================================================ + // Update Playlist Parameters + // ============================================================================ + + struct UpdatePlaylistParams { + std::optional name; + std::optional public_playlist; + std::optional collaborative; + std::optional description; + }; + + // ============================================================================ + // Playlist Track Operations + // ============================================================================ + + struct AddTracksToPlaylistParams { + std::vector uris; + std::optional position; + }; + + struct RemoveTracksFromPlaylistParams { + std::vector uris; + std::optional snapshot_id; + }; + + struct ReorderPlaylistParams { + int range_start; + int insert_before; + std::optional range_length = 1; + std::optional snapshot_id; + }; + + struct ReplacePlaylistTracksParams { + std::vector uris; + }; + + // ============================================================================ + // Playback Control Parameters + // ============================================================================ + + struct PlayParams { + std::optional context_uri; + std::optional> uris; + std::optional> offset; + std::optional position_ms; + }; + + struct TransferPlaybackParams { + std::vector device_ids; + std::optional play; + }; + + struct QueueParams { + std::string uri; + std::optional device_id; + }; + struct RequestBody { + std::vector ids; + }; + + // ============================================================================ + // Follow Parameters + // ============================================================================ + struct ErrorResponse { + struct Error { + int status; + std::string message; + } error; + }; + enum class FollowType { Artist, User }; + + inline auto FollowTypeToString(FollowType type) -> std::string + { + return type == FollowType::Artist ? "artist" : "user"; + } + + struct FollowParams { + FollowType type; + std::vector ids; + }; + + struct UnfollowParams { + FollowType type; + std::vector ids; + }; + + struct CheckFollowingParams { + FollowType type; + std::vector ids; + }; + + struct FollowPlaylistParams { + std::optional public_playlist = true; + }; + +} // namespace Spotify::Request diff --git a/include/Core/Spotify/Types/Album.hpp b/include/Core/Spotify/Types/Album.hpp index af64923..c846708 100644 --- a/include/Core/Spotify/Types/Album.hpp +++ b/include/Core/Spotify/Types/Album.hpp @@ -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 available_markets; - ExternalUrls external_urls; - std::string href; - std::string id; - std::vector images; - std::string name; - std::string release_date; - std::string release_date_precision; - std::optional restrictions; - std::string type; - std::string uri; - std::vector 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 available_markets; + ExternalUrls external_urls; + std::string href; + std::string id; + std::vector images; + std::string name; + std::string release_date; + std::string release_date_precision; + std::optional restrictions; + std::string type; + std::string uri; + std::vector 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 copyrights; - ExternalIds external_ids; - std::vector 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& { 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 albums; - }; + struct SimplifiedAlbum : AlbumBase { + }; + + // ============================================================================ + // Full Album + // ============================================================================ + + struct Album : AlbumBase { + std::vector copyrights; + ExternalIds external_ids; + std::vector 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 & + { + 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 albums; + }; } // namespace Spotify // ============================================================================ // Glaze Metadata // ============================================================================ -template <> -struct glz::meta { - 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 { + 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 { - using T = Spotify::AlbumsResponse; - static constexpr auto value = object( - "albums", &T::albums - ); +template <> struct glz::meta { + using T = Spotify::AlbumsResponse; + static constexpr auto value = object("albums", &T::albums); }; -template <> -struct glz::meta { - 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 { + 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 { - using T = Spotify::SavedAlbum; - static constexpr auto value = object( - "added_at", &T::added_at, - "album", &T::album - ); +template <> struct glz::meta { + using T = Spotify::SavedAlbum; + static constexpr auto value = + object("added_at", &T::added_at, "album", &T::album); }; diff --git a/include/Core/Spotify/Types/Artist.hpp b/include/Core/Spotify/Types/Artist.hpp index 1c7ca79..91fd62d 100644 --- a/include/Core/Spotify/Types/Artist.hpp +++ b/include/Core/Spotify/Types/Artist.hpp @@ -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 genres; - std::vector images; - int popularity; - - auto GetPopularity() const -> int { return popularity; } - auto GetGenres() const -> const std::vector& { return genres; } -}; + // ============================================================================ + // Simplified Artist + // ============================================================================ -struct ArtistsResponse { - std::vector artists; - }; + struct SimplifiedArtist : ArtistBase { + }; + + // ============================================================================ + // Full Artist + // ============================================================================ + + struct Artist : ArtistBase { + Followers followers; + std::vector genres; + std::vector images; + int popularity; + + auto GetPopularity() const -> int { return popularity; } + auto GetGenres() const -> const std::vector & + { + return genres; + } + }; + + struct ArtistsResponse { + std::vector artists; + }; } // namespace Spotify // ============================================================================ // Glaze Metadata // ============================================================================ -template <> -struct glz::meta { - 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 { + 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 { - 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 { + 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); }; diff --git a/include/Core/Spotify/Types/Common.hpp b/include/Core/Spotify/Types/Common.hpp index 8931705..18a388d 100644 --- a/include/Core/Spotify/Types/Common.hpp +++ b/include/Core/Spotify/Types/Common.hpp @@ -1,185 +1,152 @@ #pragma once -#include -#include -#include #include +#include +#include +#include -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 height; - std::optional width; -}; + struct Image { + std::string url; + std::optional height; + std::optional width; + }; -struct ExternalUrls { - std::string spotify; -}; + struct ExternalUrls { + std::string spotify; + }; -struct ExternalIds { - std::optional isrc; - std::optional ean; - std::optional upc; -}; + struct ExternalIds { + std::optional isrc; + std::optional ean; + std::optional upc; + }; -struct Followers { - std::optional href; - int total; -}; + struct Followers { + std::optional 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 -struct PagingObject { - std::string href; - int limit; - std::optional next; - int offset; - std::optional previous; - int total; - std::vector items; -}; + auto GetReason() const -> RestrictionReason + { + if (reason == "market") { + return RestrictionReason::Market; + } + if (reason == "product") { + return RestrictionReason::Product; + } + return RestrictionReason::Explicit; + } + }; -template -struct CursorPagingObject { - std::string href; - int limit; - std::optional next; - std::optional cursors; - int total; - std::vector items; -}; + // ============================================================================ + // Paging Objects + // ============================================================================ + + template struct PagingObject { + std::string href; + int limit; + std::optional next; + int offset; + std::optional previous; + int total; + std::vector items; + }; + + template struct CursorPagingObject { + std::string href; + int limit; + std::optional next; + std::optional cursors; + int total; + std::vector items; + }; } // namespace Spotify // ============================================================================ // Glaze Metadata for Common Types // ============================================================================ -template <> -struct glz::meta { - using T = Spotify::Image; - static constexpr auto value = object( - "url", &T::url, - "height", &T::height, - "width", &T::width - ); +template <> struct glz::meta { + using T = Spotify::Image; + static constexpr auto value = + object("url", &T::url, "height", &T::height, "width", &T::width); }; -template <> -struct glz::meta { - using T = Spotify::ExternalUrls; - static constexpr auto value = object("spotify", &T::spotify); +template <> struct glz::meta { + using T = Spotify::ExternalUrls; + static constexpr auto value = object("spotify", &T::spotify); }; -template <> -struct glz::meta { - using T = Spotify::ExternalIds; - static constexpr auto value = object( - "isrc", &T::isrc, - "ean", &T::ean, - "upc", &T::upc - ); +template <> struct glz::meta { + using T = Spotify::ExternalIds; + static constexpr auto value = + object("isrc", &T::isrc, "ean", &T::ean, "upc", &T::upc); }; -template <> -struct glz::meta { - using T = Spotify::Followers; - static constexpr auto value = object( - "href", &T::href, - "total", &T::total - ); +template <> struct glz::meta { + using T = Spotify::Followers; + static constexpr auto value = + object("href", &T::href, "total", &T::total); }; -template <> -struct glz::meta { - using T = Spotify::Copyright; - static constexpr auto value = object( - "text", &T::text, - "type", &T::type - ); +template <> struct glz::meta { + using T = Spotify::Copyright; + static constexpr auto value = + object("text", &T::text, "type", &T::type); }; -template <> -struct glz::meta { - using T = Spotify::Restrictions; - static constexpr auto value = object("reason", &T::reason); +template <> struct glz::meta { + using T = Spotify::Restrictions; + static constexpr auto value = object("reason", &T::reason); }; -template -struct glz::meta> { - using Type = Spotify::PagingObject; - 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 struct glz::meta> { + using Type = Spotify::PagingObject; + 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 -struct glz::meta> { - using Type = Spotify::CursorPagingObject; - static constexpr auto value = object( - "href", &Type::href, - "limit", &Type::limit, - "next", &Type::next, - "cursors", &Type::cursors, - "total", &Type::total, - "items", &Type::items - ); +template struct glz::meta> { + using Type = Spotify::CursorPagingObject; + static constexpr auto value = + object("href", &Type::href, "limit", &Type::limit, "next", + &Type::next, "cursors", &Type::cursors, "total", + &Type::total, "items", &Type::items); }; diff --git a/include/Core/Spotify/Types/Other.hpp b/include/Core/Spotify/Types/Other.hpp index 6346a7f..685bd7a 100644 --- a/include/Core/Spotify/Types/Other.hpp +++ b/include/Core/Spotify/Types/Other.hpp @@ -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 #include #include -namespace Spotify { +namespace Spotify +{ -// ============================================================================ -// Category -// ============================================================================ + // ============================================================================ + // Category + // ============================================================================ -struct Category { - std::string href; - std::vector 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 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 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 href; + std::string id; + int initialPoolSize; + std::string type; -struct Recommendations { - std::vector seeds; - std::vector tracks; - - auto GetTracks() const -> const std::vector& { return tracks; } - auto GetSeeds() const -> const std::vector& { 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> tracks; - std::optional> artists; - std::optional> albums; - std::optional> playlists; - - auto GetTracks() const -> const std::optional>& { return tracks; } - auto GetArtists() const -> const std::optional>& { return artists; } - auto GetAlbums() const -> const std::optional>& { return albums; } - auto GetPlaylists() const -> const std::optional>& { return playlists; } -}; + struct Recommendations { + std::vector seeds; + std::vector tracks; + + auto GetTracks() const -> const std::vector& + { + return tracks; + } + auto GetSeeds() const -> const std::vector& + { + return seeds; + } + }; + + // ============================================================================ + // Search Results + // ============================================================================ + + struct SearchResults { + std::optional> tracks; + std::optional> artists; + std::optional> albums; + std::optional> playlists; + + auto GetTracks() const -> const std::optional>& + { + return tracks; + } + auto GetArtists() const + -> const std::optional>& + { + return artists; + } + auto GetAlbums() const + -> const std::optional>& + { + return albums; + } + auto GetPlaylists() const + -> const std::optional>& + { + return playlists; + } + }; } // namespace Spotify // ============================================================================ // Glaze Metadata // ============================================================================ -template <> -struct glz::meta { - 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 { + 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 { - 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 { + 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 { - using T = Spotify::Recommendations; - static constexpr auto value = object( - "seeds", &T::seeds, - "tracks", &T::tracks - ); +template <> struct glz::meta { + using T = Spotify::Recommendations; + static constexpr auto value = + object("seeds", &T::seeds, "tracks", &T::tracks); }; -template <> -struct glz::meta { - 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 { + using T = Spotify::SearchResults; + static constexpr auto value = + object("tracks", &T::tracks, "artists", &T::artists, "albums", + &T::albums, "playlists", &T::playlists); }; - diff --git a/include/Core/Spotify/Types/Player.hpp b/include/Core/Spotify/Types/Player.hpp index 668adb9..e1a54c4 100644 --- a/include/Core/Spotify/Types/Player.hpp +++ b/include/Core/Spotify/Types/Player.hpp @@ -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 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& { 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 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& + { + 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; - int timestamp; - int progress_ms; - bool is_playing; - std::optional 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& { 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; + int timestamp; + int progress_ms; + bool is_playing; + std::optional 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& + { + 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 { - 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 { + 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 { - 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 { + 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 { - 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 { + 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); }; diff --git a/include/Core/Spotify/Types/Playlist.hpp b/include/Core/Spotify/Types/Playlist.hpp index 83743f0..ea4268f 100644 --- a/include/Core/Spotify/Types/Playlist.hpp +++ b/include/Core/Spotify/Types/Playlist.hpp @@ -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 added_at; - std::optional added_by; - bool is_local; - Track track; - - auto GetTrack() const -> const Track& { return track; } - auto GetAddedAt() const -> const std::optional& { return added_at; } - auto IsLocal() const -> bool { return is_local; } -}; + struct PlaylistTrack { + std::optional added_at; + std::optional added_by; + bool is_local; + Track track; -// ============================================================================ -// Playlist Base -// ============================================================================ + auto GetTrack() const -> const Track & { return track; } + auto GetAddedAt() const -> const std::optional & + { + return added_at; + } + auto IsLocal() const -> bool { return is_local; } + }; -class PlaylistBase { -public: - bool collaborative; - std::optional description; - ExternalUrls external_urls; - std::string href; - std::string id; - std::vector images; - std::string name; - SimplifiedArtist owner; - bool public_playlist; - std::optional 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& { 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 description; + ExternalUrls external_urls; + std::string href; + std::string id; + std::vector images; + std::string name; + SimplifiedArtist owner; + bool public_playlist; + std::optional 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 & + { + 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 { - 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 { + 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 { - using T = Spotify::SimplifiedPlaylist::TracksInfo; - static constexpr auto value = object( - "href", &T::href, - "total", &T::total - ); +template <> struct glz::meta { + using T = Spotify::SimplifiedPlaylist::TracksInfo; + static constexpr auto value = + object("href", &T::href, "total", &T::total); }; -template <> -struct glz::meta { - 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 { + 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 { - 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 { + 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); }; diff --git a/include/Core/Spotify/Types/Track.hpp b/include/Core/Spotify/Types/Track.hpp index ea7ac2d..3da9d55 100644 --- a/include/Core/Spotify/Types/Track.hpp +++ b/include/Core/Spotify/Types/Track.hpp @@ -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 artists; - std::vector 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 linked_from; - std::optional restrictions; - std::string name; - std::optional 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& { return artists; } -}; + class TrackBase + { + public: -// ============================================================================ -// Simplified Track -// ============================================================================ + std::vector artists; + std::vector 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 linked_from; + std::optional restrictions; + std::string name; + std::optional 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 & + { + 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(key); } - auto GetMode() const -> MusicalMode { return static_cast(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 pitches; - std::vector timbre; -}; + enum class MusicalMode { Minor = 0, Major = 1 }; -struct AudioAnalysis { - std::vector bars; - std::vector beats; - std::vector
sections; - std::vector segments; - std::vector tatums; - - auto GetBars() const -> const std::vector& { return bars; } - auto GetBeats() const -> const std::vector& { return beats; } - auto GetSections() const -> const std::vector
& { 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 tracks; - }; + auto GetKey() const -> MusicalKey + { + return static_cast(key); + } + auto GetMode() const -> MusicalMode + { + return static_cast(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 pitches; + std::vector timbre; + }; + + struct AudioAnalysis { + std::vector bars; + std::vector beats; + std::vector
sections; + std::vector segments; + std::vector tatums; + + auto GetBars() const -> const std::vector & + { + return bars; + } + auto GetBeats() const -> const std::vector & + { + return beats; + } + auto GetSections() const -> const std::vector
& + { + return sections; + } + }; + + struct TracksResponse { + std::vector tracks; + }; } // namespace Spotify // ============================================================================ // Glaze Metadata // ============================================================================ -template <> -struct glz::meta { - 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 { + 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 { - 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 { + 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 { - using T = Spotify::SavedTrack; - static constexpr auto value = object( - "added_at", &T::added_at, - "track", &T::track - ); +template <> struct glz::meta { + using T = Spotify::SavedTrack; + static constexpr auto value = + object("added_at", &T::added_at, "track", &T::track); }; -template <> -struct glz::meta { - 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 { + 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 { - using T = Spotify::TimeInterval; - static constexpr auto value = object( - "start", &T::start, - "duration", &T::duration, - "confidence", &T::confidence - ); +template <> struct glz::meta { + using T = Spotify::TimeInterval; + static constexpr auto value = + object("start", &T::start, "duration", &T::duration, "confidence", + &T::confidence); }; -template <> -struct glz::meta { - 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 { + 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 { - 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 { + 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 { - 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 { + using T = Spotify::AudioAnalysis; + static constexpr auto value = object( + "bars", &T::bars, "beats", &T::beats, "sections", &T::sections, + "segments", &T::segments, "tatums", &T::tatums); }; diff --git a/include/Core/Spotify/Types/User.hpp b/include/Core/Spotify/Types/User.hpp index a88d839..7826f38 100644 --- a/include/Core/Spotify/Types/User.hpp +++ b/include/Core/Spotify/Types/User.hpp @@ -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 country; - std::optional display_name; - std::optional email; - std::optional external_urls; - std::optional followers; - std::string href; - std::string id; - std::optional> images; - std::optional product; - std::string type; - std::string uri; - - auto GetId() const -> const std::string& { return id; } - auto GetDisplayName() const -> const std::optional& { return display_name; } - auto GetEmail() const -> const std::optional& { 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 country; + std::optional display_name; + std::optional email; + std::optional external_urls; + std::optional followers; + std::string href; + std::string id; + std::optional> images; + std::optional product; + std::string type; + std::string uri; + + auto GetId() const -> const std::string& { return id; } + auto GetDisplayName() const -> const std::optional& + { + return display_name; + } + auto GetEmail() const -> const std::optional& + { + 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 { - 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 { + 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); }; diff --git a/include/Core/Youtube/Client.hpp b/include/Core/Youtube/Client.hpp index 8fd2609..f13b011 100644 --- a/include/Core/Youtube/Client.hpp +++ b/include/Core/Youtube/Client.hpp @@ -14,290 +14,312 @@ #include // Assumed available per your reference #include // Project (Assuming similar structure to your Spotify bot) -#include #include #include +#include -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 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 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 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 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 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 items; -}; -// ============================================================================ -// InnerTube (Player) Data Types -// ============================================================================ + // API Response Wrappers + template 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 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 formats; // Mixed video+audio - std::vector - adaptiveFormats; // Separate streams (we want audio from here) -}; + struct StreamingData { + std::string expiresInSeconds; + std::vector formats; // Mixed video+audio + std::vector + 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 using Result = std::expected; -// ============================================================================ -// Request Parameters -// ============================================================================ + struct ApiError { + int status; + std::string message; + std::string reason; + }; + struct GoogleError { + struct Inner { + int code; + std::string message; + } error; + }; + template using Result = std::expected; + // ============================================================================ + // Request Parameters + // ============================================================================ -struct SearchParams { - std::string q; - std::vector 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 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; + // 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; - // https://developers.google.com/youtube/v3/docs/search/list - auto Search(const SearchParams ¶ms) -> Result>; + // ======================================================================== + // Search API + // ======================================================================== - // ======================================================================== - // Videos API - // ======================================================================== + // https://developers.google.com/youtube/v3/docs/search/list + auto Search(const SearchParams ¶ms) + -> Result>; - // https://developers.google.com/youtube/v3/docs/videos/list - auto GetVideo(const std::string &id, - const std::string &part = "snippet,contentDetails,statistics") - -> Result