Format and .clang-format

This commit is contained in:
faumaray committed 2026-01-19 19:52:30 +03:00
1 parent 6aed7b0027
commit b94b634a87
47 files changed
+42341 -39711

No files matched your search

+272
View File
@@ -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
+321 -261
View File
@@ -1,321 +1,381 @@
#pragma once
#include <iostream>
#include <fstream>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <deque>
#include <filesystem>
#include <format>
#include <print>
#include <chrono>
#include <source_location>
#include <fstream>
#include <iostream>
#include <mutex>
#include <thread>
#include <print>
#include <source_location>
#include <string>
#include <deque>
#include <condition_variable>
#include <atomic>
#include <thread>
#include <unordered_map>
#include <ts6bot/Config.hpp>
#include "Singleton.hpp"
class Logger : public Singleton<Logger> {
friend class Singleton<Logger>;
class Logger : public Singleton<Logger>
{
friend class Singleton<Logger>;
// ANSI Color codes
struct Colors {
static constexpr auto RESET = "\033[0m";
static constexpr auto TRACE = "\033[37m"; // White
static constexpr auto DEBUG = "\033[36m"; // Cyan
static constexpr auto INFO = "\033[32m"; // Green
static constexpr auto WARNING = "\033[33m"; // Yellow
static constexpr auto ERROR = "\033[31m"; // Red
static constexpr auto CRITICAL = "\033[1;31m"; // Bold Red
};
// ANSI Color codes
struct Colors {
static constexpr auto RESET = "\033[0m";
static constexpr auto TRACE = "\033[37m"; // White
static constexpr auto DEBUG = "\033[36m"; // Cyan
static constexpr auto INFO = "\033[32m"; // Green
static constexpr auto WARNING = "\033[33m"; // Yellow
static constexpr auto ERROR = "\033[31m"; // Red
static constexpr auto CRITICAL = "\033[1;31m"; // Bold Red
};
// Internal structure to hold log data in the queue
struct LogEntry {
std::chrono::system_clock::time_point timestamp;
std::thread::id threadId;
std::source_location sourceLoc;
ts6bot::LogLevel level;
std::string message; // Pre-formatted user message
};
// Internal structure to hold log data in the queue
struct LogEntry {
std::chrono::system_clock::time_point timestamp;
std::thread::id threadId;
std::source_location sourceLoc;
ts6bot::LogLevel level;
std::string message; // Pre-formatted user message
};
public:
explicit Logger(const ts6bot::LogLevel logLevel = ts6bot::LogLevel::Info)
: m_minLevel(logLevel), m_exit(false)
{
// 1. Setup File Sinks (Synchronous init)
try {
namespace fs = std::filesystem;
const fs::path logDir = "logs";
if (!fs::exists(logDir)) fs::create_directories(logDir);
public:
// Time for filename (UTC)
const auto now = std::chrono::system_clock::now();
auto now_utc = std::chrono::zoned_time{std::chrono::locate_zone("UTC"), now};
std::string timestamp = std::format("{:%Y-%m-%d_%H-%M-%S}", now_utc);
explicit Logger(
const ts6bot::LogLevel logLevel = ts6bot::LogLevel::Info)
: m_minLevel(logLevel), m_exit(false)
{
// 1. Setup File Sinks (Synchronous init)
try {
namespace fs = std::filesystem;
const fs::path logDir = "logs";
if (!fs::exists(logDir)) {
fs::create_directories(logDir);
}
// Open trace file (all logs)
std::string traceFilename = std::format("trace_{}.log", timestamp);
m_logFiles[ts6bot::LogLevel::Trace].open(logDir / traceFilename, std::ios::out | std::ios::app);
// Time for filename (UTC)
const auto now = std::chrono::system_clock::now();
auto now_utc = std::chrono::zoned_time{
std::chrono::locate_zone("UTC"), now};
std::string timestamp =
std::format("{:%Y-%m-%d_%H-%M-%S}", now_utc);
// Open error file
std::string errorFilename = std::format("error_{}.log", timestamp);
m_logFiles[ts6bot::LogLevel::Error].open(logDir / errorFilename, std::ios::out | std::ios::app);
// Open trace file (all logs)
std::string traceFilename =
std::format("trace_{}.log", timestamp);
m_logFiles[ts6bot::LogLevel::Trace].open(
logDir / traceFilename, std::ios::out | std::ios::app);
// Open warning file
std::string warningFilename = std::format("warning_{}.log", timestamp);
m_logFiles[ts6bot::LogLevel::Warning].open(logDir / warningFilename, std::ios::out | std::ios::app);
// Open error file
std::string errorFilename =
std::format("error_{}.log", timestamp);
m_logFiles[ts6bot::LogLevel::Error].open(
logDir / errorFilename, std::ios::out | std::ios::app);
// Open critical file
std::string criticalFilename = std::format("critical_{}.log", timestamp);
m_logFiles[ts6bot::LogLevel::Critical].open(logDir / criticalFilename, std::ios::out | std::ios::app);
// Open warning file
std::string warningFilename =
std::format("warning_{}.log", timestamp);
m_logFiles[ts6bot::LogLevel::Warning].open(
logDir / warningFilename, std::ios::out | std::ios::app);
// Check if files opened successfully
for (const auto& [level, file] : m_logFiles) {
if (!file.is_open()) {
std::println(std::cerr, "Logger Error: Failed to open log file for level: {}", levelToString(level));
}
}
} catch (const std::exception& e) {
std::println(std::cerr, "Logger Initialization Error: {}", e.what());
}
// Open critical file
std::string criticalFilename =
std::format("critical_{}.log", timestamp);
m_logFiles[ts6bot::LogLevel::Critical].open(
logDir / criticalFilename, std::ios::out | std::ios::app);
// 2. Start Worker Thread
m_workerThread = std::jthread([this](const std::stop_token &st) {
this->workerLoop(st);
});
}
// Check if files opened successfully
for (const auto &[level, file] : m_logFiles) {
if (!file.is_open()) {
std::println(std::cerr,
"Logger Error: Failed to open log file "
"for level: {}",
levelToString(level));
}
}
} catch (const std::exception &e) {
std::println(std::cerr, "Logger Initialization Error: {}",
e.what());
}
~Logger() override {
// Signal exit and wake up worker
m_exit = true;
m_cv.notify_one();
// m_workerThread destructor will wait for join automatically
// 2. Start Worker Thread
m_workerThread = std::jthread(
[this](const std::stop_token &st) { this->workerLoop(st); });
}
// Close all log files
for (auto &file: m_logFiles | std::views::values) {
if (file.is_open()) {
file.close();
}
}
}
~Logger() override
{
// Signal exit and wake up worker
m_exit = true;
m_cv.notify_one();
// m_workerThread destructor will wait for join automatically
// --- Public Logging API ---
// Close all log files
for (auto &file : m_logFiles | std::views::values) {
if (file.is_open()) {
file.close();
}
}
}
// Generic log function
template <typename... Args>
void log(const ts6bot::LogLevel level, const std::source_location& loc, std::format_string<Args...> fmt, Args&&... args) {
if (level < m_minLevel || level == ts6bot::LogLevel::None) return;
// --- Public Logging API ---
try {
// 1. Capture context immediately
// Generic log function
template <typename... Args>
void log(const ts6bot::LogLevel level, const std::source_location &loc,
std::format_string<Args...> fmt, Args &&...args)
{
if (level < m_minLevel || level == ts6bot::LogLevel::None) {
return;
}
// 3. Push to Queue
{
LogEntry entry{
.timestamp = std::chrono::system_clock::now(),
.threadId = std::this_thread::get_id(),
.sourceLoc = loc,
.level = level,
// 2. Format message immediately (capture by value) to avoid dangling references
.message = std::format(fmt, std::forward<Args>(args)...)
};
std::lock_guard lock(m_queueMutex);
m_logQueue.push_back(std::move(entry));
}
m_cv.notify_one();
try {
// 1. Capture context immediately
} catch (const std::exception& e) {
// Fallback if formatting fails
std::println(std::cerr, "Logging Error: {}", e.what());
}
}
// 3. Push to Queue
{
LogEntry entry{
.timestamp = std::chrono::system_clock::now(),
.threadId = std::this_thread::get_id(),
.sourceLoc = loc,
.level = level,
// 2. Format message immediately (capture by value) to
// avoid dangling references
.message =
std::format(fmt, std::forward<Args>(args)...)};
std::lock_guard lock(m_queueMutex);
m_logQueue.push_back(std::move(entry));
}
m_cv.notify_one();
// Convenience Wrappers
template <typename... Args>
void trace(std::format_string<Args...> fmt, Args&&... args) {
log(ts6bot::LogLevel::Trace, std::source_location::current(), fmt, std::forward<Args>(args)...);
}
} catch (const std::exception &e) {
// Fallback if formatting fails
std::println(std::cerr, "Logging Error: {}", e.what());
}
}
template <typename... Args>
void info(std::format_string<Args...> fmt, Args&&... args) {
log(ts6bot::LogLevel::Info, std::source_location::current(), fmt, std::forward<Args>(args)...);
}
// Convenience Wrappers
template <typename... Args>
void trace(std::format_string<Args...> fmt, Args &&...args)
{
log(ts6bot::LogLevel::Trace, std::source_location::current(), fmt,
std::forward<Args>(args)...);
}
template <typename... Args>
void error(std::format_string<Args...> fmt, Args&&... args) {
log(ts6bot::LogLevel::Error, std::source_location::current(), fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void info(std::format_string<Args...> fmt, Args &&...args)
{
log(ts6bot::LogLevel::Info, std::source_location::current(), fmt,
std::forward<Args>(args)...);
}
template <typename... Args>
void warn(std::format_string<Args...> fmt, Args&&... args) {
log(ts6bot::LogLevel::Warning, std::source_location::current(), fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void error(std::format_string<Args...> fmt, Args &&...args)
{
log(ts6bot::LogLevel::Error, std::source_location::current(), fmt,
std::forward<Args>(args)...);
}
template <typename... Args>
void debug(std::format_string<Args...> fmt, Args&&... args) {
log(ts6bot::LogLevel::Debug, std::source_location::current(), fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void warn(std::format_string<Args...> fmt, Args &&...args)
{
log(ts6bot::LogLevel::Warning, std::source_location::current(), fmt,
std::forward<Args>(args)...);
}
template <typename... Args>
void critical(std::format_string<Args...> fmt, Args&&... args) {
log(ts6bot::LogLevel::Critical, std::source_location::current(), fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void debug(std::format_string<Args...> fmt, Args &&...args)
{
log(ts6bot::LogLevel::Debug, std::source_location::current(), fmt,
std::forward<Args>(args)...);
}
void SetLogLevel(const ts6bot::LogLevel level) { m_minLevel = level; }
template <typename... Args>
void critical(std::format_string<Args...> fmt, Args &&...args)
{
log(ts6bot::LogLevel::Critical, std::source_location::current(),
fmt, std::forward<Args>(args)...);
}
private:
// --- Backend Worker ---
void workerLoop(std::stop_token st) {
while (!st.stop_requested() || !isQueueEmpty()) {
std::unique_lock lock(m_queueMutex);
void SetLogLevel(const ts6bot::LogLevel level) { m_minLevel = level; }
// Wait until data is available or stop is requested
m_cv.wait(lock, [this, &st] {
return !m_logQueue.empty() || st.stop_requested() || m_exit;
});
private:
if (m_logQueue.empty()) {
if (st.stop_requested() || m_exit) break;
continue;
}
// --- Backend Worker ---
void workerLoop(std::stop_token st)
{
while (!st.stop_requested() || !isQueueEmpty()) {
std::unique_lock lock(m_queueMutex);
// Swap queue to local buffer to minimize lock time
std::deque<LogEntry> localQueue;
std::swap(localQueue, m_logQueue);
lock.unlock();
// Wait until data is available or stop is requested
m_cv.wait(lock, [this, &st] {
return !m_logQueue.empty() || st.stop_requested() || m_exit;
});
// Process Batch
for (const auto& entry : localQueue) {
writeLog(entry);
}
}
}
if (m_logQueue.empty()) {
if (st.stop_requested() || m_exit) {
break;
}
continue;
}
bool isQueueEmpty() {
std::lock_guard lock(m_queueMutex);
return m_logQueue.empty();
}
// Swap queue to local buffer to minimize lock time
std::deque<LogEntry> localQueue;
std::swap(localQueue, m_logQueue);
lock.unlock();
void writeLog(const LogEntry& entry) {
// Format: "HH:MM:SS.nanoseconds [thread_id] /path/to/file.cpp:line LOG_LEVEL message"
// Process Batch
for (const auto &entry : localQueue) {
writeLog(entry);
}
}
}
auto utc_time = std::chrono::zoned_time{std::chrono::locate_zone("UTC"), entry.timestamp};
bool isQueueEmpty()
{
std::lock_guard lock(m_queueMutex);
return m_logQueue.empty();
}
// Extract nanoseconds
const auto duration = entry.timestamp.time_since_epoch();
const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration);
const auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(duration - seconds);
void writeLog(const LogEntry &entry)
{
// Format: "HH:MM:SS.nanoseconds [thread_id] /path/to/file.cpp:line
// LOG_LEVEL message"
// Format source location
std::string sourceLocation = std::format("{}:{}",
entry.sourceLoc.file_name(),
entry.sourceLoc.line());
auto utc_time = std::chrono::zoned_time{
std::chrono::locate_zone("UTC"), entry.timestamp};
// Get thread ID as integer
std::ostringstream threadIdStream;
threadIdStream << entry.threadId;
std::string threadIdStr = threadIdStream.str();
// Extract nanoseconds
const auto duration = entry.timestamp.time_since_epoch();
const auto seconds =
std::chrono::duration_cast<std::chrono::seconds>(duration);
const auto nanoseconds =
std::chrono::duration_cast<std::chrono::nanoseconds>(duration -
seconds);
// Construct log without colors (for file)
const std::string fileLog = std::format("{:%H:%M:%S}.{:09} [{}] {:<28} {:<9} {}\n",
utc_time,
nanoseconds.count(),
threadIdStr,
sourceLocation,
levelToString(entry.level),
entry.message
);
// Format source location
std::string sourceLocation = std::format(
"{}:{}", entry.sourceLoc.file_name(), entry.sourceLoc.line());
// Construct colored log (for console)
const char* color = getColorForLevel(entry.level);
std::string consoleLog = std::format("{}{:%H:%M:%S}.{:09}{} [{}] {:<28} {}{:<9}{} {}\n",
color,
utc_time,
nanoseconds.count(),
Colors::RESET,
threadIdStr,
sourceLocation,
color,
levelToString(entry.level),
Colors::RESET,
entry.message
);
// Get thread ID as integer
std::ostringstream threadIdStream;
threadIdStream << entry.threadId;
std::string threadIdStr = threadIdStream.str();
// Print to Console with colors
std::print(std::cout, "{}", consoleLog);
// Construct log without colors (for file)
const std::string fileLog = std::format(
"{:%H:%M:%S}.{:09} [{}] {:<28} {:<9} {}\n", utc_time,
nanoseconds.count(), threadIdStr, sourceLocation,
levelToString(entry.level), entry.message);
// Write to trace file (all logs) - no colors
if (m_logFiles.at(ts6bot::LogLevel::Trace).is_open()) {
m_logFiles.at(ts6bot::LogLevel::Trace) << fileLog;
m_logFiles.at(ts6bot::LogLevel::Trace).flush();
}
// Construct colored log (for console)
const char *color = getColorForLevel(entry.level);
std::string consoleLog = std::format(
"{}{:%H:%M:%S}.{:09}{} [{}] {:<28} {}{:<9}{} {}\n", color,
utc_time, nanoseconds.count(), Colors::RESET, threadIdStr,
sourceLocation, color, levelToString(entry.level),
Colors::RESET, entry.message);
// Write to specific level files - no colors
if (entry.level == ts6bot::LogLevel::Error && m_logFiles.at(ts6bot::LogLevel::Error).is_open()) {
m_logFiles.at(ts6bot::LogLevel::Error) << fileLog;
m_logFiles.at(ts6bot::LogLevel::Error).flush();
}
else if (entry.level == ts6bot::LogLevel::Warning && m_logFiles.at(ts6bot::LogLevel::Warning).is_open()) {
m_logFiles.at(ts6bot::LogLevel::Warning) << fileLog;
m_logFiles.at(ts6bot::LogLevel::Warning).flush();
}
else if (entry.level == ts6bot::LogLevel::Critical && m_logFiles.at(ts6bot::LogLevel::Critical).is_open()) {
m_logFiles.at(ts6bot::LogLevel::Critical) << fileLog;
m_logFiles.at(ts6bot::LogLevel::Critical).flush();
}
}
// Print to Console with colors
std::print(std::cout, "{}", consoleLog);
static const char* getColorForLevel(const ts6bot::LogLevel level) {
switch (level) {
case ts6bot::LogLevel::Trace: return Colors::TRACE;
case ts6bot::LogLevel::Debug: return Colors::DEBUG;
case ts6bot::LogLevel::Info: return Colors::INFO;
case ts6bot::LogLevel::Warning: return Colors::WARNING;
case ts6bot::LogLevel::Error: return Colors::ERROR;
case ts6bot::LogLevel::Critical: return Colors::CRITICAL;
default: return Colors::RESET;
}
}
// Write to trace file (all logs) - no colors
if (m_logFiles.at(ts6bot::LogLevel::Trace).is_open()) {
m_logFiles.at(ts6bot::LogLevel::Trace) << fileLog;
m_logFiles.at(ts6bot::LogLevel::Trace).flush();
}
static std::string_view levelToString(const ts6bot::LogLevel level) {
switch (level) {
case ts6bot::LogLevel::Trace: return "TRACE";
case ts6bot::LogLevel::Debug: return "DEBUG";
case ts6bot::LogLevel::Info: return "INFO";
case ts6bot::LogLevel::Warning: return "WARNING";
case ts6bot::LogLevel::Error: return "ERROR";
case ts6bot::LogLevel::Critical: return "CRITICAL";
default: return "UNKNOWN";
}
}
// Write to specific level files - no colors
if (entry.level == ts6bot::LogLevel::Error &&
m_logFiles.at(ts6bot::LogLevel::Error).is_open()) {
m_logFiles.at(ts6bot::LogLevel::Error) << fileLog;
m_logFiles.at(ts6bot::LogLevel::Error).flush();
} else if (entry.level == ts6bot::LogLevel::Warning &&
m_logFiles.at(ts6bot::LogLevel::Warning).is_open()) {
m_logFiles.at(ts6bot::LogLevel::Warning) << fileLog;
m_logFiles.at(ts6bot::LogLevel::Warning).flush();
} else if (entry.level == ts6bot::LogLevel::Critical &&
m_logFiles.at(ts6bot::LogLevel::Critical).is_open()) {
m_logFiles.at(ts6bot::LogLevel::Critical) << fileLog;
m_logFiles.at(ts6bot::LogLevel::Critical).flush();
}
}
private:
ts6bot::LogLevel m_minLevel;
std::unordered_map<ts6bot::LogLevel, std::ofstream> m_logFiles;
static const char *getColorForLevel(const ts6bot::LogLevel level)
{
switch (level) {
case ts6bot::LogLevel::Trace:
return Colors::TRACE;
case ts6bot::LogLevel::Debug:
return Colors::DEBUG;
case ts6bot::LogLevel::Info:
return Colors::INFO;
case ts6bot::LogLevel::Warning:
return Colors::WARNING;
case ts6bot::LogLevel::Error:
return Colors::ERROR;
case ts6bot::LogLevel::Critical:
return Colors::CRITICAL;
default:
return Colors::RESET;
}
}
// Concurrency
std::deque<LogEntry> m_logQueue;
std::mutex m_queueMutex;
std::condition_variable m_cv;
std::jthread m_workerThread;
std::atomic<bool> m_exit;
static std::string_view levelToString(const ts6bot::LogLevel level)
{
switch (level) {
case ts6bot::LogLevel::Trace:
return "TRACE";
case ts6bot::LogLevel::Debug:
return "DEBUG";
case ts6bot::LogLevel::Info:
return "INFO";
case ts6bot::LogLevel::Warning:
return "WARNING";
case ts6bot::LogLevel::Error:
return "ERROR";
case ts6bot::LogLevel::Critical:
return "CRITICAL";
default:
return "UNKNOWN";
}
}
private:
ts6bot::LogLevel m_minLevel;
std::unordered_map<ts6bot::LogLevel, std::ofstream> m_logFiles;
// Concurrency
std::deque<LogEntry> m_logQueue;
std::mutex m_queueMutex;
std::condition_variable m_cv;
std::jthread m_workerThread;
std::atomic<bool> m_exit;
};
#define LOG_IF_ALIVE(level, fmt, ...) \
do { \
if (Logger::isAlive()) { \
Logger::getInstance()->log(level, std::source_location::current(), fmt __VA_OPT__(,) __VA_ARGS__); \
} \
} while (0)
#define LOG_IF_ALIVE(level, fmt, ...) \
do { \
if (Logger::isAlive()) { \
Logger::getInstance()->log(level, std::source_location::current(), \
fmt __VA_OPT__(, ) __VA_ARGS__); \
} \
} while (0)
// --- Public API Macros ---
#define LOG_TRACE(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Trace, fmt __VA_OPT__(,) __VA_ARGS__)
#define LOG_DEBUG(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Debug, fmt __VA_OPT__(,) __VA_ARGS__)
#define LOG_INFO(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Info, fmt __VA_OPT__(,) __VA_ARGS__)
#define LOG_WARN(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Warning, fmt __VA_OPT__(,) __VA_ARGS__)
#define LOG_ERROR(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Error, fmt __VA_OPT__(,) __VA_ARGS__)
#define LOG_CRITICAL(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Critical, fmt __VA_OPT__(,) __VA_ARGS__)
#define LOG_TRACE(fmt, ...) \
LOG_IF_ALIVE(ts6bot::LogLevel::Trace, fmt __VA_OPT__(, ) __VA_ARGS__)
#define LOG_DEBUG(fmt, ...) \
LOG_IF_ALIVE(ts6bot::LogLevel::Debug, fmt __VA_OPT__(, ) __VA_ARGS__)
#define LOG_INFO(fmt, ...) \
LOG_IF_ALIVE(ts6bot::LogLevel::Info, fmt __VA_OPT__(, ) __VA_ARGS__)
#define LOG_WARN(fmt, ...) \
LOG_IF_ALIVE(ts6bot::LogLevel::Warning, fmt __VA_OPT__(, ) __VA_ARGS__)
#define LOG_ERROR(fmt, ...) \
LOG_IF_ALIVE(ts6bot::LogLevel::Error, fmt __VA_OPT__(, ) __VA_ARGS__)
#define LOG_CRITICAL(fmt, ...) \
LOG_IF_ALIVE(ts6bot::LogLevel::Critical, fmt __VA_OPT__(, ) __VA_ARGS__)
+625 -395
View File
File diff suppressed because it is too large. Load diff
+63 -57
View File
@@ -1,79 +1,85 @@
#pragma once
#include <glaze/core/common.hpp>
#include <optional>
#include <string>
#include <teamspeak/public_definitions.h>
#include <utility>
#include <vector>
#include <glaze/core/common.hpp>
namespace definitions {
namespace definitions
{
struct StreamInfo {
std::string url;
int itag = 0;
std::string mimeType;
int bitrate = 0;
int width = 0;
int height = 0;
};
struct StreamInfo {
std::string url;
int itag = 0;
std::string mimeType;
int bitrate = 0;
int width = 0;
int height = 0;
};
struct Streams {
StreamInfo audio;
StreamInfo video;
};
struct Streams {
StreamInfo audio;
StreamInfo video;
};
struct QueueItem {
std::string name;
std::string videoId;
std::string shortUrl;
std::string length;
std::string requester;
std::optional<Streams> streams;
struct QueueItem {
std::string name;
std::string videoId;
std::string shortUrl;
std::string length;
std::string requester;
std::optional<Streams> streams;
QueueItem() = default;
QueueItem() = default;
QueueItem(std::string name, std::string videoId,
std::string shortUrl, std::string length,
std::string requested_by,
const std::optional<Streams> &streams)
: name{std::move(name)}, videoId(std::move(videoId)),
shortUrl(std::move(shortUrl)), length(std::move(length)),
requester{std::move(requested_by)}, streams{streams}
{
}
};
QueueItem(std::string name, std::string videoId,std::string shortUrl,std::string length, std::string requested_by, const std::optional<Streams> & streams)
: name{std::move(name)}, videoId(std::move(videoId)),shortUrl(std::move(shortUrl)), length(std::move(length)), requester{std::move(requested_by)}, streams{streams} {}
};
struct SearchResultItem {
std::string name;
std::string length;
std::string thumbnail;
std::string viewCount;
std::string url;
std::string shortUrl;
std::string videoId;
};
struct SearchResultItem {
std::string name;
std::string length;
std::string thumbnail;
std::string viewCount;
std::string url;
std::string shortUrl;
std::string videoId;
};
struct PluginState {
std::vector<QueueItem> queue;
std::vector<anyID> onlineSubscribers;
std::vector<anyID> offlineSubscribers;
std::uint64_t serverConnection;
bool wasPlaying = false;
};
}
struct PluginState {
std::vector<QueueItem> queue;
std::vector<anyID> onlineSubscribers;
std::vector<anyID> offlineSubscribers;
std::uint64_t serverConnection;
bool wasPlaying = false;
};
} // namespace definitions
template <> struct glz::meta<definitions::StreamInfo> {
using T = definitions::StreamInfo;
static constexpr auto value =
object("url", &T::url, "itag", &T::itag, "mimeType", &T::mimeType,
"bitrate", &T::bitrate, "width", &T::width, "height", &T::height);
using T = definitions::StreamInfo;
static constexpr auto value = object(
"url", &T::url, "itag", &T::itag, "mimeType", &T::mimeType,
"bitrate", &T::bitrate, "width", &T::width, "height", &T::height);
};
template <> struct glz::meta<definitions::Streams> {
using T = definitions::Streams;
static constexpr auto value =
object("audio", &T::audio, "video", &T::video);
using T = definitions::Streams;
static constexpr auto value =
object("audio", &T::audio, "video", &T::video);
};
template <> struct glz::meta<definitions::QueueItem> {
using T = definitions::QueueItem;
static constexpr auto value =
object("name", &T::name, "videoId", &T::videoId, "shortUrl", &T::shortUrl, "length", &T::length, "requester", &T::requester,
"streams", &T::streams);
};
using T = definitions::QueueItem;
static constexpr auto value =
object("name", &T::name, "videoId", &T::videoId, "shortUrl",
&T::shortUrl, "length", &T::length, "requester",
&T::requester, "streams", &T::streams);
};
+76 -60
View File
@@ -1,77 +1,93 @@
#pragma once
#include <concepts>
#include <memory>
#include <mutex>
#include <concepts>
#include <utility>
/**
* @brief C++26 Smart Singleton for DLL Hot-Reloading.
* Uses shared_ptr to ensure memory safety across thread boundaries
* Uses shared_ptr to ensure memory safety across thread boundaries
* during forceful destruction and DLL unloads.
*/
template <typename T>
class Singleton {
private:
// This "Token" trick allows std::shared_ptr to create the object
// even if T's constructor is private/protected.
struct ConstructorProxy : public T {
template<typename... Args>
ConstructorProxy(Args&&... args) : T(std::forward<Args>(args)...) {}
};
public:
// Delete copy/move
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
template <typename T> class Singleton
{
private:
template <typename... Args>
static std::shared_ptr<T> init(Args&&... args) {
auto ptr = m_instance.load(std::memory_order_acquire);
if (ptr) return ptr;
// This "Token" trick allows std::shared_ptr to create the object
// even if T's constructor is private/protected.
struct ConstructorProxy : public T {
template <typename... Args>
ConstructorProxy(Args &&...args)
: T(std::forward<Args>(args)...)
{
}
};
std::lock_guard lock(m_lifecycle_mutex);
ptr = m_instance.load(std::memory_order_relaxed);
if (!ptr) {
// We wrap T in ConstructorProxy so 'new' works here,
// but the resulting shared_ptr is still shared_ptr<T>.
ptr = std::make_shared<ConstructorProxy>(std::forward<Args>(args)...);
m_instance.store(ptr, std::memory_order_release);
}
return ptr;
}
public:
/**
* @brief Access the existing instance.
* @throws std::runtime_error if init() hasn't been called yet.
*/
static std::shared_ptr<T> getInstance() {
auto ptr = m_instance.load(std::memory_order_acquire);
if (!ptr) {
throw std::runtime_error("Singleton accessed via get() before init()!");
}
return ptr;
}
// Delete copy/move
Singleton(const Singleton &) = delete;
Singleton &operator=(const Singleton &) = delete;
/**
* @brief Safe destruction for DLL unloading.
* Shared_ptr ensures that threads currently using the instance
* don't crash; the memory is freed only when the last reference drops.
*/
static void destroyInstance() {
std::lock_guard lock(m_lifecycle_mutex);
m_instance.store(nullptr, std::memory_order_release);
}
template <typename... Args>
static std::shared_ptr<T> init(Args &&...args)
{
auto ptr = m_instance.load(std::memory_order_acquire);
if (ptr) {
return ptr;
}
static bool isAlive() {
return m_instance.load(std::memory_order_acquire) != nullptr;
}
std::lock_guard lock(m_lifecycle_mutex);
ptr = m_instance.load(std::memory_order_relaxed);
if (!ptr) {
// We wrap T in ConstructorProxy so 'new' works here,
// but the resulting shared_ptr is still shared_ptr<T>.
ptr = std::make_shared<ConstructorProxy>(
std::forward<Args>(args)...);
m_instance.store(ptr, std::memory_order_release);
}
return ptr;
}
protected:
Singleton() = default;
virtual ~Singleton() = default;
/**
* @brief Access the existing instance.
* @throws std::runtime_error if init() hasn't been called yet.
*/
static std::shared_ptr<T> getInstance()
{
auto ptr = m_instance.load(std::memory_order_acquire);
if (!ptr) {
throw std::runtime_error(
"Singleton accessed via get() before init()!");
}
return ptr;
}
private:
// atomic<shared_ptr> is a C++20 feature, perfect for C++26
static inline std::atomic<std::shared_ptr<T>> m_instance{nullptr};
static inline std::mutex m_lifecycle_mutex;
};
/**
* @brief Safe destruction for DLL unloading.
* Shared_ptr ensures that threads currently using the instance
* don't crash; the memory is freed only when the last reference drops.
*/
static void destroyInstance()
{
std::lock_guard lock(m_lifecycle_mutex);
m_instance.store(nullptr, std::memory_order_release);
}
static bool isAlive()
{
return m_instance.load(std::memory_order_acquire) != nullptr;
}
protected:
Singleton() = default;
virtual ~Singleton() = default;
private:
// atomic<shared_ptr> is a C++20 feature, perfect for C++26
static inline std::atomic<std::shared_ptr<T>> m_instance{nullptr};
static inline std::mutex m_lifecycle_mutex;
};
+34 -24
View File
@@ -1,30 +1,40 @@
#include <vector>
#include <functional>
#include <algorithm>
#include <functional>
#include <mutex>
#include <vector>
class SingletonManager {
public:
// Priority: Higher numbers are destroyed LAST (e.g., Logger = 100)
static void registerShutdown(const int priority, const std::function<void()> &shutdownFunc) {
m_registry.push_back({priority, shutdownFunc});
// Sort so that high priority stays at the end (destroyed last)
std::ranges::sort(m_registry, [](const auto& a, const auto& b) {
return a.priority < b.priority;
});
}
class SingletonManager
{
public:
static void shutdownAll() {
// Destroy in reverse priority (highest priority first? No, usually reverse order of arrival)
// Here we destroy from lowest priority to highest.
for (auto& [priority, func] : m_registry) {
std::cerr << priority << ": " << &func << std::endl;
func();
}
m_registry.clear();
}
// Priority: Higher numbers are destroyed LAST (e.g., Logger = 100)
static void registerShutdown(const int priority,
const std::function<void()>& shutdownFunc)
{
m_registry.push_back({priority, shutdownFunc});
// Sort so that high priority stays at the end (destroyed last)
std::ranges::sort(m_registry, [](const auto& a, const auto& b) {
return a.priority < b.priority;
});
}
private:
struct Entry { int priority; std::function<void()> func; };
static inline std::vector<Entry> m_registry;
static void shutdownAll()
{
// Destroy in reverse priority (highest priority first? No, usually
// reverse order of arrival) Here we destroy from lowest priority to
// highest.
for (auto& [priority, func] : m_registry) {
std::cerr << priority << ": " << &func << std::endl;
func();
}
m_registry.clear();
}
private:
struct Entry {
int priority;
std::function<void()> func;
};
static inline std::vector<Entry> m_registry;
};
+262 -223
View File
@@ -14,319 +14,358 @@
#include <memory>
#include <string>
namespace Spotify {
namespace Spotify
{
// ============================================================================
// Error Handling
// ============================================================================
// ============================================================================
// Error Handling
// ============================================================================
struct ApiError {
int status;
std::string message;
std::string reason;
struct ApiError {
int status;
std::string message;
std::string reason;
auto GetStatus() const -> int { return status; }
auto GetMessage() const -> const std::string & { return message; }
};
auto GetStatus() const -> int { return status; }
auto GetMessage() const -> const std::string & { return message; }
};
template <typename T> using Result = std::expected<T, ApiError>;
template <typename T> using Result = std::expected<T, ApiError>;
// ============================================================================
// HTTP Client Implementation Details
// ============================================================================
// ============================================================================
// HTTP Client Implementation Details
// ============================================================================
struct CurlDeleter {
void operator()(CURL *ptr) const {
if (ptr)
curl_easy_cleanup(ptr);
}
};
struct CurlDeleter {
void operator()(CURL *ptr) const
{
if (ptr) {
curl_easy_cleanup(ptr);
}
}
};
enum class HttpMethod { GET, POST, PUT, DELETE };
enum class HttpMethod { GET, POST, PUT, DELETE };
// ============================================================================
// Main Spotify Client
// ============================================================================
// ============================================================================
// Main Spotify Client
// ============================================================================
class Client {
public:
Client(std::string accessToken);
~Client() = default;
class Client
{
public:
// Configuration
void SetVerbose(bool verbose) { m_Verbose = verbose; }
void SetProxy(ProxyConfig config) { m_Proxy = std::move(config); }
void SetAccessToken(std::string token) { m_AccessToken = std::move(token); }
Client(std::string accessToken);
~Client() = default;
// ========================================================================
// Albums API
// ========================================================================
// Configuration
void SetVerbose(bool verbose) { m_Verbose = verbose; }
void SetProxy(ProxyConfig config) { m_Proxy = std::move(config); }
void SetAccessToken(std::string token)
{
m_AccessToken = std::move(token);
}
auto GetAlbum(const std::string &id, std::optional<std::string> market = {})
-> Result<Album>;
// ========================================================================
// Albums API
// ========================================================================
auto GetAlbums(const std::vector<std::string> &ids,
std::optional<std::string> market = {})
-> Result<std::vector<Album>>;
auto GetAlbum(const std::string &id,
std::optional<std::string> market = {})
-> Result<Album>;
auto GetAlbumTracks(const std::string &id,
const Request::AlbumTracksParams &params = {})
-> Result<PagingObject<SimplifiedTrack>>;
auto GetAlbums(const std::vector<std::string> &ids,
std::optional<std::string> market = {})
-> Result<std::vector<Album>>;
auto GetSavedAlbums(const Request::PaginationParams &params = {})
-> Result<PagingObject<SavedAlbum>>;
auto GetAlbumTracks(const std::string &id,
const Request::AlbumTracksParams &params = {})
-> Result<PagingObject<SimplifiedTrack>>;
auto SaveAlbums(const std::vector<std::string> &ids) -> Result<void>;
auto GetSavedAlbums(const Request::PaginationParams &params = {})
-> Result<PagingObject<SavedAlbum>>;
auto RemoveSavedAlbums(const std::vector<std::string> &ids) -> Result<void>;
auto SaveAlbums(const std::vector<std::string> &ids)
-> Result<void>;
auto CheckSavedAlbums(const std::vector<std::string> &ids)
-> Result<std::vector<bool>>;
auto RemoveSavedAlbums(const std::vector<std::string> &ids)
-> Result<void>;
auto GetNewReleases(const Request::PaginationParams &params = {})
-> Result<PagingObject<SimplifiedAlbum>>;
auto CheckSavedAlbums(const std::vector<std::string> &ids)
-> Result<std::vector<bool>>;
// ========================================================================
// Artists API
// ========================================================================
auto GetNewReleases(const Request::PaginationParams &params = {})
-> Result<PagingObject<SimplifiedAlbum>>;
auto GetArtist(const std::string &id) -> Result<Artist>;
// ========================================================================
// Artists API
// ========================================================================
auto GetArtists(const std::vector<std::string> &ids)
-> Result<std::vector<Artist>>;
auto GetArtist(const std::string &id) -> Result<Artist>;
auto GetArtistAlbums(const std::string &id,
const Request::ArtistAlbumsParams &params = {})
-> Result<PagingObject<SimplifiedAlbum>>;
auto GetArtists(const std::vector<std::string> &ids)
-> Result<std::vector<Artist>>;
auto GetArtistTopTracks(const std::string &id, const std::string &market)
-> Result<std::vector<Track>>;
auto GetArtistAlbums(const std::string &id,
const Request::ArtistAlbumsParams &params = {})
-> Result<PagingObject<SimplifiedAlbum>>;
auto GetArtistRelatedArtists(const std::string &id)
-> Result<std::vector<Artist>>;
auto GetArtistTopTracks(const std::string &id,
const std::string &market)
-> Result<std::vector<Track>>;
// ========================================================================
// Tracks API
// ========================================================================
auto GetArtistRelatedArtists(const std::string &id)
-> Result<std::vector<Artist>>;
auto GetTrack(const std::string &id, std::optional<std::string> market = {})
-> Result<Track>;
// ========================================================================
// Tracks API
// ========================================================================
auto GetTracks(const std::vector<std::string> &ids,
std::optional<std::string> market = {})
-> Result<std::vector<Track>>;
auto GetTrack(const std::string &id,
std::optional<std::string> market = {})
-> Result<Track>;
auto GetSavedTracks(const Request::PaginationParams &params = {})
-> Result<PagingObject<SavedTrack>>;
auto GetTracks(const std::vector<std::string> &ids,
std::optional<std::string> market = {})
-> Result<std::vector<Track>>;
auto SaveTracks(const std::vector<std::string> &ids) -> Result<void>;
auto GetSavedTracks(const Request::PaginationParams &params = {})
-> Result<PagingObject<SavedTrack>>;
auto RemoveSavedTracks(const std::vector<std::string> &ids) -> Result<void>;
auto SaveTracks(const std::vector<std::string> &ids)
-> Result<void>;
auto CheckSavedTracks(const std::vector<std::string> &ids)
-> Result<std::vector<bool>>;
auto RemoveSavedTracks(const std::vector<std::string> &ids)
-> Result<void>;
auto GetAudioFeatures(const std::string &id) -> Result<AudioFeatures>;
auto CheckSavedTracks(const std::vector<std::string> &ids)
-> Result<std::vector<bool>>;
auto GetAudioFeaturesForTracks(const std::vector<std::string> &ids)
-> Result<std::vector<AudioFeatures>>;
auto GetAudioFeatures(const std::string &id)
-> Result<AudioFeatures>;
auto GetAudioAnalysis(const std::string &id) -> Result<AudioAnalysis>;
auto GetAudioFeaturesForTracks(const std::vector<std::string> &ids)
-> Result<std::vector<AudioFeatures>>;
auto GetRecommendations(const Request::RecommendationParams &params)
-> Result<Recommendations>;
auto GetAudioAnalysis(const std::string &id)
-> Result<AudioAnalysis>;
// ========================================================================
// Search API
// ========================================================================
auto GetRecommendations(const Request::RecommendationParams &params)
-> Result<Recommendations>;
auto Search(const Request::SearchParams &params) -> Result<SearchResults>;
// ========================================================================
// Search API
// ========================================================================
auto SearchTracks(const Request::TrackSearchFilters &filters,
const Request::PaginationParams &params = {})
-> Result<PagingObject<Track>>;
auto Search(const Request::SearchParams &params)
-> Result<SearchResults>;
auto SearchAlbums(const Request::AlbumSearchFilters &filters,
const Request::PaginationParams &params = {})
-> Result<PagingObject<SimplifiedAlbum>>;
auto SearchTracks(const Request::TrackSearchFilters &filters,
const Request::PaginationParams &params = {})
-> Result<PagingObject<Track>>;
auto SearchArtists(const Request::ArtistSearchFilters &filters,
const Request::PaginationParams &params = {})
-> Result<PagingObject<Artist>>;
auto SearchAlbums(const Request::AlbumSearchFilters &filters,
const Request::PaginationParams &params = {})
-> Result<PagingObject<SimplifiedAlbum>>;
// ========================================================================
// Playlists API
// ========================================================================
auto SearchArtists(const Request::ArtistSearchFilters &filters,
const Request::PaginationParams &params = {})
-> Result<PagingObject<Artist>>;
auto GetPlaylist(const std::string &id,
std::optional<std::string> market = {}) -> Result<Playlist>;
// ========================================================================
// Playlists API
// ========================================================================
auto GetPlaylistTracks(const std::string &id,
const Request::PaginationParams &params = {})
-> Result<PagingObject<PlaylistTrack>>;
auto GetPlaylist(const std::string &id,
std::optional<std::string> market = {})
-> Result<Playlist>;
auto CreatePlaylist(const std::string &user_id,
const Request::CreatePlaylistParams &params)
-> Result<Playlist>;
auto GetPlaylistTracks(const std::string &id,
const Request::PaginationParams &params = {})
-> Result<PagingObject<PlaylistTrack>>;
auto UpdatePlaylist(const std::string &id,
const Request::UpdatePlaylistParams &params)
-> Result<void>;
auto CreatePlaylist(const std::string &user_id,
const Request::CreatePlaylistParams &params)
-> Result<Playlist>;
auto AddTracksToPlaylist(const std::string &id,
const Request::AddTracksToPlaylistParams &params)
-> Result<std::string>;
auto UpdatePlaylist(const std::string &id,
const Request::UpdatePlaylistParams &params)
-> Result<void>;
auto RemoveTracksFromPlaylist(
const std::string &id,
const Request::RemoveTracksFromPlaylistParams &params)
-> Result<std::string>;
auto AddTracksToPlaylist(
const std::string &id,
const Request::AddTracksToPlaylistParams &params)
-> Result<std::string>;
auto ReorderPlaylistTracks(const std::string &id,
const Request::ReorderPlaylistParams &params)
-> Result<std::string>;
auto RemoveTracksFromPlaylist(
const std::string &id,
const Request::RemoveTracksFromPlaylistParams &params)
-> Result<std::string>;
auto ReplacePlaylistTracks(const std::string &id,
const Request::ReplacePlaylistTracksParams &params)
-> Result<void>;
auto ReorderPlaylistTracks(
const std::string &id,
const Request::ReorderPlaylistParams &params)
-> Result<std::string>;
auto GetCurrentUserPlaylists(const Request::PaginationParams &params = {})
-> Result<PagingObject<SimplifiedPlaylist>>;
auto ReplacePlaylistTracks(
const std::string &id,
const Request::ReplacePlaylistTracksParams &params)
-> Result<void>;
auto GetUserPlaylists(const std::string &user_id,
const Request::PaginationParams &params = {})
-> Result<PagingObject<SimplifiedPlaylist>>;
auto GetCurrentUserPlaylists(
const Request::PaginationParams &params = {})
-> Result<PagingObject<SimplifiedPlaylist>>;
auto GetFeaturedPlaylists(const Request::PaginationParams &params = {})
-> Result<PagingObject<SimplifiedPlaylist>>;
auto GetUserPlaylists(const std::string &user_id,
const Request::PaginationParams &params = {})
-> Result<PagingObject<SimplifiedPlaylist>>;
auto GetCategoryPlaylists(const std::string &category_id,
const Request::PaginationParams &params = {})
-> Result<PagingObject<SimplifiedPlaylist>>;
auto GetFeaturedPlaylists(
const Request::PaginationParams &params = {})
-> Result<PagingObject<SimplifiedPlaylist>>;
// ========================================================================
// User API
// ========================================================================
auto GetCategoryPlaylists(
const std::string &category_id,
const Request::PaginationParams &params = {})
-> Result<PagingObject<SimplifiedPlaylist>>;
auto GetCurrentUser() -> Result<User>;
// ========================================================================
// User API
// ========================================================================
auto GetUser(const std::string &user_id) -> Result<User>;
auto GetCurrentUser() -> Result<User>;
auto GetTopArtists(const Request::TopItemsParams &params = {})
-> Result<PagingObject<Artist>>;
auto GetUser(const std::string &user_id) -> Result<User>;
auto GetTopTracks(const Request::TopItemsParams &params = {})
-> Result<PagingObject<Track>>;
auto GetTopArtists(const Request::TopItemsParams &params = {})
-> Result<PagingObject<Artist>>;
// ========================================================================
// Follow API
// ========================================================================
auto GetTopTracks(const Request::TopItemsParams &params = {})
-> Result<PagingObject<Track>>;
auto FollowArtistsOrUsers(const Request::FollowParams &params)
-> Result<void>;
// ========================================================================
// Follow API
// ========================================================================
auto UnfollowArtistsOrUsers(const Request::UnfollowParams &params)
-> Result<void>;
auto FollowArtistsOrUsers(const Request::FollowParams &params)
-> Result<void>;
auto CheckFollowingArtistsOrUsers(const Request::CheckFollowingParams &params)
-> Result<std::vector<bool>>;
auto UnfollowArtistsOrUsers(const Request::UnfollowParams &params)
-> Result<void>;
auto GetFollowedArtists(std::optional<int> limit = {},
std::optional<std::string> after = {})
-> Result<CursorPagingObject<Artist>>;
auto CheckFollowingArtistsOrUsers(
const Request::CheckFollowingParams &params)
-> Result<std::vector<bool>>;
auto FollowPlaylist(const std::string &playlist_id,
const Request::FollowPlaylistParams &params = {})
-> Result<void>;
auto GetFollowedArtists(std::optional<int> limit = {},
std::optional<std::string> after = {})
-> Result<CursorPagingObject<Artist>>;
auto UnfollowPlaylist(const std::string &playlist_id) -> Result<void>;
auto
FollowPlaylist(const std::string &playlist_id,
const Request::FollowPlaylistParams &params = {})
-> Result<void>;
auto CheckFollowingPlaylist(const std::string &playlist_id,
const std::vector<std::string> &user_ids)
-> Result<std::vector<bool>>;
auto UnfollowPlaylist(const std::string &playlist_id)
-> Result<void>;
// ========================================================================
// Player API
// ========================================================================
auto
CheckFollowingPlaylist(const std::string &playlist_id,
const std::vector<std::string> &user_ids)
-> Result<std::vector<bool>>;
auto GetPlaybackState(std::optional<std::string> market = {})
-> Result<PlaybackState>;
// ========================================================================
// Player API
// ========================================================================
auto GetAvailableDevices() -> Result<std::vector<Device>>;
auto GetPlaybackState(std::optional<std::string> market = {})
-> Result<PlaybackState>;
auto GetCurrentlyPlayingTrack(std::optional<std::string> market = {})
-> Result<PlaybackState>;
auto GetAvailableDevices() -> Result<std::vector<Device>>;
auto StartOrResumePlayback(const Request::PlayParams &params,
std::optional<std::string> device_id = {})
-> Result<void>;
auto
GetCurrentlyPlayingTrack(std::optional<std::string> market = {})
-> Result<PlaybackState>;
auto PausePlayback(std::optional<std::string> device_id = {}) -> Result<void>;
auto
StartOrResumePlayback(const Request::PlayParams &params,
std::optional<std::string> device_id = {})
-> Result<void>;
auto SkipToNext(std::optional<std::string> device_id = {}) -> Result<void>;
auto PausePlayback(std::optional<std::string> device_id = {})
-> Result<void>;
auto SkipToPrevious(std::optional<std::string> device_id = {})
-> Result<void>;
auto SkipToNext(std::optional<std::string> device_id = {})
-> Result<void>;
auto SeekToPosition(int position_ms,
std::optional<std::string> device_id = {})
-> Result<void>;
auto SkipToPrevious(std::optional<std::string> device_id = {})
-> Result<void>;
auto SetRepeatMode(RepeatMode mode, std::optional<std::string> device_id = {})
-> Result<void>;
auto SeekToPosition(int position_ms,
std::optional<std::string> device_id = {})
-> Result<void>;
auto SetPlaybackVolume(int volume_percent,
std::optional<std::string> device_id = {})
-> Result<void>;
auto SetRepeatMode(RepeatMode mode,
std::optional<std::string> device_id = {})
-> Result<void>;
auto TogglePlaybackShuffle(bool state,
std::optional<std::string> device_id = {})
-> Result<void>;
auto SetPlaybackVolume(int volume_percent,
std::optional<std::string> device_id = {})
-> Result<void>;
auto TransferPlayback(const Request::TransferPlaybackParams &params)
-> Result<void>;
auto
TogglePlaybackShuffle(bool state,
std::optional<std::string> device_id = {})
-> Result<void>;
auto AddToQueue(const Request::QueueParams &params) -> Result<void>;
auto TransferPlayback(const Request::TransferPlaybackParams &params)
-> Result<void>;
auto GetRecentlyPlayedTracks(std::optional<int> limit = {},
std::optional<int64_t> after = {},
std::optional<int64_t> before = {})
-> Result<CursorPagingObject<PlaylistTrack>>;
auto AddToQueue(const Request::QueueParams &params) -> Result<void>;
// ========================================================================
// Browse API
// ========================================================================
auto GetRecentlyPlayedTracks(std::optional<int> limit = {},
std::optional<int64_t> after = {},
std::optional<int64_t> before = {})
-> Result<CursorPagingObject<PlaylistTrack>>;
auto GetCategories(const Request::PaginationParams &params = {})
-> Result<PagingObject<Category>>;
// ========================================================================
// Browse API
// ========================================================================
auto GetCategory(const std::string &category_id,
std::optional<std::string> locale = {}) -> Result<Category>;
auto GetCategories(const Request::PaginationParams &params = {})
-> Result<PagingObject<Category>>;
auto GetAvailableGenreSeeds() -> Result<std::vector<std::string>>;
auto GetCategory(const std::string &category_id,
std::optional<std::string> locale = {})
-> Result<Category>;
auto GetAvailableMarkets() -> Result<std::vector<std::string>>;
auto GetAvailableGenreSeeds() -> Result<std::vector<std::string>>;
private:
std::string m_AccessToken;
ProxyConfig m_Proxy;
bool m_Verbose = false;
auto GetAvailableMarkets() -> Result<std::vector<std::string>>;
auto PerformRequest(const std::string &url,
HttpMethod method = HttpMethod::GET,
const std::string &body = "",
const std::vector<std::string> &extra_headers = {})
-> Result<std::string>;
private:
static auto WriteCallback(void *contents, size_t size, size_t nmemb,
std::string *out) -> size_t;
std::string m_AccessToken;
ProxyConfig m_Proxy;
bool m_Verbose = false;
auto BuildUrl(const std::string &endpoint,
const std::map<std::string, std::string> &params = {}) const
-> std::string;
auto BuildUrl(const std::string &endpoint,
const Request::RequestParams &params) const -> std::string;
auto UrlEncode(const std::string &value) const -> std::string;
};
auto PerformRequest(
const std::string &url,
HttpMethod method = HttpMethod::GET,
const std::string &body = "",
const std::vector<std::string> &extra_headers = {})
-> Result<std::string>;
static auto WriteCallback(void *contents, size_t size, size_t nmemb,
std::string *out) -> size_t;
auto BuildUrl(const std::string &endpoint,
const std::map<std::string, std::string> &params = {})
const -> std::string;
auto BuildUrl(const std::string &endpoint,
const Request::RequestParams &params) const
-> std::string;
auto UrlEncode(const std::string &value) const -> std::string;
};
} // namespace Spotify
+24 -17
View File
@@ -4,25 +4,32 @@
#include <optional>
#include <string>
namespace Spotify {
namespace Spotify
{
struct CallbackResult {
std::string code;
std::string state;
std::string error;
};
struct CallbackResult {
std::string code;
std::string state;
std::string error;
};
class HttpCallbackServer {
public:
HttpCallbackServer(std::string host, uint16_t port, std::string path);
class HttpCallbackServer
{
public:
// Wait for one callback request or timeout. Returns std::nullopt on timeout.
std::optional<CallbackResult> WaitForCallback(std::chrono::milliseconds timeout);
HttpCallbackServer(std::string host, uint16_t port,
std::string path);
private:
std::string m_Host;
uint16_t m_Port;
std::string m_Path;
};
// Wait for one callback request or timeout. Returns std::nullopt on
// timeout.
std::optional<CallbackResult>
WaitForCallback(std::chrono::milliseconds timeout);
} // namespace ts6bot
private:
std::string m_Host;
uint16_t m_Port;
std::string m_Path;
};
} // namespace Spotify
+43 -33
View File
@@ -11,47 +11,57 @@
#include <Spotify/Client.hpp> // for ProxyConfig + CurlDeleter + ProxyType
namespace Spotify {
namespace Spotify
{
struct TokenSet {
std::string access_token;
std::string token_type;
std::string scope;
std::string refresh_token;
std::int64_t expires_at_utc{}; // unix seconds
struct TokenSet {
std::string access_token;
std::string token_type;
std::string scope;
std::string refresh_token;
std::int64_t expires_at_utc{}; // unix seconds
bool IsExpired(std::chrono::seconds skew = std::chrono::seconds{60}) const;
};
bool IsExpired(std::chrono::seconds skew = std::chrono::seconds{
60}) const;
};
class PkceAuth {
public:
PkceAuth(std::string clientId, std::string redirectUri, std::filesystem::path tokenCachePath);
class PkceAuth
{
public:
void SetProxy(ProxyConfig p) { m_Proxy = std::move(p); }
void SetVerbose(bool v) { m_Verbose = v; }
PkceAuth(std::string clientId,
std::string redirectUri,
std::filesystem::path tokenCachePath);
// One-time interactive step: prints URL and waits for redirect; stores refresh token.
void AuthorizeAndStore(const std::vector<std::string>& scopes,
std::chrono::milliseconds timeout = std::chrono::minutes(5));
void SetProxy(ProxyConfig p) { m_Proxy = std::move(p); }
void SetVerbose(bool v) { m_Verbose = v; }
// Headless: load from cache and refresh if needed.
TokenSet LoadOrRefresh();
// One-time interactive step: prints URL and waits for redirect;
// stores refresh token.
void AuthorizeAndStore(
const std::vector<std::string>& scopes,
std::chrono::milliseconds timeout = std::chrono::minutes(5));
private:
std::string m_ClientId;
std::string m_RedirectUri;
std::filesystem::path m_TokenCachePath;
ProxyConfig m_Proxy;
bool m_Verbose = false;
// Headless: load from cache and refresh if needed.
TokenSet LoadOrRefresh();
TokenSet ExchangeCodeForToken(const std::string& code, const std::string& codeVerifier);
TokenSet RefreshAccessToken(const TokenSet& current);
private:
void Save(const TokenSet& t) const;
std::optional<TokenSet> Load() const;
std::string m_ClientId;
std::string m_RedirectUri;
std::filesystem::path m_TokenCachePath;
ProxyConfig m_Proxy;
bool m_Verbose = false;
static std::int64_t NowUnixSeconds();
friend TokenSet;
};
TokenSet ExchangeCodeForToken(const std::string& code,
const std::string& codeVerifier);
TokenSet RefreshAccessToken(const TokenSet& current);
} // namespace ts6bot
void Save(const TokenSet& t) const;
std::optional<TokenSet> Load() const;
static std::int64_t NowUnixSeconds();
friend TokenSet;
};
} // namespace Spotify
File diff suppressed because it is too large. Load diff
+141 -150
View File
@@ -1,178 +1,169 @@
#pragma once
#include "Spotify/Types/Common.hpp"
#include "Spotify/Types/Artist.hpp"
#include "Spotify/Types/Common.hpp"
namespace Spotify {
namespace Spotify
{
// ============================================================================
// Album Group Enum
// ============================================================================
// ============================================================================
// Album Group Enum
// ============================================================================
enum class AlbumGroup {
Album,
Single,
AppearsOn,
Compilation
};
enum class AlbumGroup { Album, Single, AppearsOn, Compilation };
inline auto AlbumGroupToString(AlbumGroup group) -> std::string {
switch (group) {
case AlbumGroup::Album: return "album";
case AlbumGroup::Single: return "single";
case AlbumGroup::AppearsOn: return "appears_on";
case AlbumGroup::Compilation: return "compilation";
}
return "";
}
inline auto AlbumGroupToString(AlbumGroup group) -> std::string
{
switch (group) {
case AlbumGroup::Album:
return "album";
case AlbumGroup::Single:
return "single";
case AlbumGroup::AppearsOn:
return "appears_on";
case AlbumGroup::Compilation:
return "compilation";
}
return "";
}
// ============================================================================
// Album Base
// ============================================================================
// ============================================================================
// Album Base
// ============================================================================
class AlbumBase {
public:
std::string album_type;
int total_tracks;
std::vector<std::string> available_markets;
ExternalUrls external_urls;
std::string href;
std::string id;
std::vector<Image> images;
std::string name;
std::string release_date;
std::string release_date_precision;
std::optional<Restrictions> restrictions;
std::string type;
std::string uri;
std::vector<SimplifiedArtist> artists;
bool is_playable;
virtual ~AlbumBase() = default;
auto GetId() const -> const std::string& { return id; }
auto GetName() const -> const std::string& { return name; }
auto GetUri() const -> const std::string& { return uri; }
auto GetReleaseDate() const -> const std::string& { return release_date; }
auto GetTotalTracks() const -> int { return total_tracks; }
auto GetAlbumType() const -> AlbumType {
if (album_type == "album") return AlbumType::Album;
if (album_type == "single") return AlbumType::Single;
return AlbumType::Compilation;
}
auto GetReleaseDatePrecision() const -> ReleaseDatePrecision {
if (release_date_precision == "year") return ReleaseDatePrecision::Year;
if (release_date_precision == "month") return ReleaseDatePrecision::Month;
return ReleaseDatePrecision::Day;
}
};
class AlbumBase
{
public:
// ============================================================================
// Simplified Album
// ============================================================================
std::string album_type;
int total_tracks;
std::vector<std::string> available_markets;
ExternalUrls external_urls;
std::string href;
std::string id;
std::vector<Image> images;
std::string name;
std::string release_date;
std::string release_date_precision;
std::optional<Restrictions> restrictions;
std::string type;
std::string uri;
std::vector<SimplifiedArtist> artists;
bool is_playable;
struct SimplifiedAlbum : AlbumBase {
};
virtual ~AlbumBase() = default;
// ============================================================================
// Full Album
// ============================================================================
auto GetId() const -> const std::string & { return id; }
auto GetName() const -> const std::string & { return name; }
auto GetUri() const -> const std::string & { return uri; }
auto GetReleaseDate() const -> const std::string &
{
return release_date;
}
auto GetTotalTracks() const -> int { return total_tracks; }
struct Album : AlbumBase {
std::vector<Copyright> copyrights;
ExternalIds external_ids;
std::vector<std::string> genres;
std::string label;
int popularity;
auto GetPopularity() const -> int { return popularity; }
auto GetLabel() const -> const std::string& { return label; }
auto GetGenres() const -> const std::vector<std::string>& { return genres; }
};
auto GetAlbumType() const -> AlbumType
{
if (album_type == "album") {
return AlbumType::Album;
}
if (album_type == "single") {
return AlbumType::Single;
}
return AlbumType::Compilation;
}
// ============================================================================
// Saved Album
// ============================================================================
auto GetReleaseDatePrecision() const -> ReleaseDatePrecision
{
if (release_date_precision == "year") {
return ReleaseDatePrecision::Year;
}
if (release_date_precision == "month") {
return ReleaseDatePrecision::Month;
}
return ReleaseDatePrecision::Day;
}
};
struct SavedAlbum {
std::string added_at;
Album album;
auto GetAlbum() const -> const Album& { return album; }
auto GetAddedAt() const -> const std::string& { return added_at; }
};
// ============================================================================
// Simplified Album
// ============================================================================
struct AlbumsResponse {
std::vector<Album> albums;
};
struct SimplifiedAlbum : AlbumBase {
};
// ============================================================================
// Full Album
// ============================================================================
struct Album : AlbumBase {
std::vector<Copyright> copyrights;
ExternalIds external_ids;
std::vector<std::string> genres;
std::string label;
int popularity;
auto GetPopularity() const -> int { return popularity; }
auto GetLabel() const -> const std::string & { return label; }
auto GetGenres() const -> const std::vector<std::string> &
{
return genres;
}
};
// ============================================================================
// Saved Album
// ============================================================================
struct SavedAlbum {
std::string added_at;
Album album;
auto GetAlbum() const -> const Album & { return album; }
auto GetAddedAt() const -> const std::string & { return added_at; }
};
struct AlbumsResponse {
std::vector<Album> albums;
};
} // namespace Spotify
// ============================================================================
// Glaze Metadata
// ============================================================================
template <>
struct glz::meta<Spotify::SimplifiedAlbum> {
using T = Spotify::SimplifiedAlbum;
static constexpr auto value = object(
"album_type", &T::album_type,
"total_tracks", &T::total_tracks,
"available_markets", &T::available_markets,
"external_urls", &T::external_urls,
"href", &T::href,
"id", &T::id,
"images", &T::images,
"name", &T::name,
"release_date", &T::release_date,
"release_date_precision", &T::release_date_precision,
"restrictions", &T::restrictions,
"type", &T::type,
"uri", &T::uri,
"artists", &T::artists,
"is_playable", &T::is_playable
);
template <> struct glz::meta<Spotify::SimplifiedAlbum> {
using T = Spotify::SimplifiedAlbum;
static constexpr auto value = object(
"album_type", &T::album_type, "total_tracks", &T::total_tracks,
"available_markets", &T::available_markets, "external_urls",
&T::external_urls, "href", &T::href, "id", &T::id, "images",
&T::images, "name", &T::name, "release_date", &T::release_date,
"release_date_precision", &T::release_date_precision,
"restrictions", &T::restrictions, "type", &T::type, "uri", &T::uri,
"artists", &T::artists, "is_playable", &T::is_playable);
};
template <>
struct glz::meta<Spotify::AlbumsResponse> {
using T = Spotify::AlbumsResponse;
static constexpr auto value = object(
"albums", &T::albums
);
template <> struct glz::meta<Spotify::AlbumsResponse> {
using T = Spotify::AlbumsResponse;
static constexpr auto value = object("albums", &T::albums);
};
template <>
struct glz::meta<Spotify::Album> {
using T = Spotify::Album;
static constexpr auto value = object(
"album_type", &T::album_type,
"total_tracks", &T::total_tracks,
"available_markets", &T::available_markets,
"external_urls", &T::external_urls,
"href", &T::href,
"id", &T::id,
"images", &T::images,
"name", &T::name,
"release_date", &T::release_date,
"release_date_precision", &T::release_date_precision,
"restrictions", &T::restrictions,
"type", &T::type,
"uri", &T::uri,
"artists", &T::artists,
"copyrights", &T::copyrights,
"external_ids", &T::external_ids,
"genres", &T::genres,
"label", &T::label,
"popularity", &T::popularity
);
template <> struct glz::meta<Spotify::Album> {
using T = Spotify::Album;
static constexpr auto value = object(
"album_type", &T::album_type, "total_tracks", &T::total_tracks,
"available_markets", &T::available_markets, "external_urls",
&T::external_urls, "href", &T::href, "id", &T::id, "images",
&T::images, "name", &T::name, "release_date", &T::release_date,
"release_date_precision", &T::release_date_precision,
"restrictions", &T::restrictions, "type", &T::type, "uri", &T::uri,
"artists", &T::artists, "copyrights", &T::copyrights,
"external_ids", &T::external_ids, "genres", &T::genres, "label",
&T::label, "popularity", &T::popularity);
};
template <>
struct glz::meta<Spotify::SavedAlbum> {
using T = Spotify::SavedAlbum;
static constexpr auto value = object(
"added_at", &T::added_at,
"album", &T::album
);
template <> struct glz::meta<Spotify::SavedAlbum> {
using T = Spotify::SavedAlbum;
static constexpr auto value =
object("added_at", &T::added_at, "album", &T::album);
};
+57 -65
View File
@@ -1,84 +1,76 @@
#pragma once
#include "Spotify/Types/Common.hpp"
namespace Spotify {
namespace Spotify
{
// ============================================================================
// Artist Base
// ============================================================================
// ============================================================================
// Artist Base
// ============================================================================
class ArtistBase {
public:
ExternalUrls external_urls;
std::string href;
std::string id;
std::string name;
std::string type;
std::string uri;
virtual ~ArtistBase() = default;
auto GetId() const -> const std::string& { return id; }
auto GetName() const -> const std::string& { return name; }
auto GetUri() const -> const std::string& { return uri; }
};
class ArtistBase
{
public:
// ============================================================================
// Simplified Artist
// ============================================================================
ExternalUrls external_urls;
std::string href;
std::string id;
std::string name;
std::string type;
std::string uri;
struct SimplifiedArtist : ArtistBase {
};
virtual ~ArtistBase() = default;
// ============================================================================
// Full Artist
// ============================================================================
auto GetId() const -> const std::string & { return id; }
auto GetName() const -> const std::string & { return name; }
auto GetUri() const -> const std::string & { return uri; }
};
struct Artist : ArtistBase {
Followers followers;
std::vector<std::string> genres;
std::vector<Image> images;
int popularity;
auto GetPopularity() const -> int { return popularity; }
auto GetGenres() const -> const std::vector<std::string>& { return genres; }
};
// ============================================================================
// Simplified Artist
// ============================================================================
struct ArtistsResponse {
std::vector<Artist> artists;
};
struct SimplifiedArtist : ArtistBase {
};
// ============================================================================
// Full Artist
// ============================================================================
struct Artist : ArtistBase {
Followers followers;
std::vector<std::string> genres;
std::vector<Image> images;
int popularity;
auto GetPopularity() const -> int { return popularity; }
auto GetGenres() const -> const std::vector<std::string> &
{
return genres;
}
};
struct ArtistsResponse {
std::vector<Artist> artists;
};
} // namespace Spotify
// ============================================================================
// Glaze Metadata
// ============================================================================
template <>
struct glz::meta<Spotify::SimplifiedArtist> {
using T = Spotify::SimplifiedArtist;
static constexpr auto value = object(
"external_urls", &T::external_urls,
"href", &T::href,
"id", &T::id,
"name", &T::name,
"type", &T::type,
"uri", &T::uri
);
template <> struct glz::meta<Spotify::SimplifiedArtist> {
using T = Spotify::SimplifiedArtist;
static constexpr auto value =
object("external_urls", &T::external_urls, "href", &T::href, "id",
&T::id, "name", &T::name, "type", &T::type, "uri", &T::uri);
};
template <>
struct glz::meta<Spotify::Artist> {
using T = Spotify::Artist;
static constexpr auto value = object(
"external_urls", &T::external_urls,
"followers", &T::followers,
"genres", &T::genres,
"href", &T::href,
"id", &T::id,
"images", &T::images,
"name", &T::name,
"popularity", &T::popularity,
"type", &T::type,
"uri", &T::uri
);
template <> struct glz::meta<Spotify::Artist> {
using T = Spotify::Artist;
static constexpr auto value =
object("external_urls", &T::external_urls, "followers",
&T::followers, "genres", &T::genres, "href", &T::href, "id",
&T::id, "images", &T::images, "name", &T::name, "popularity",
&T::popularity, "type", &T::type, "uri", &T::uri);
};
+113 -146
View File
@@ -1,185 +1,152 @@
#pragma once
#include <string>
#include <optional>
#include <vector>
#include <glaze/glaze.hpp>
#include <optional>
#include <string>
#include <vector>
namespace Spotify {
namespace Spotify
{
// ============================================================================
// Common Enums
// ============================================================================
// ============================================================================
// Common Enums
// ============================================================================
enum class AlbumType {
Album,
Single,
Compilation
};
enum class AlbumType { Album, Single, Compilation };
enum class ReleaseDatePrecision {
Year,
Month,
Day
};
enum class ReleaseDatePrecision { Year, Month, Day };
enum class CopyrightType {
Copyright, // "C"
Performance // "P"
};
enum class CopyrightType {
Copyright, // "C"
Performance // "P"
};
enum class RestrictionReason {
Market,
Product,
Explicit
};
enum class RestrictionReason { Market, Product, Explicit };
// ============================================================================
// Core Structures
// ============================================================================
// ============================================================================
// Core Structures
// ============================================================================
struct Image {
std::string url;
std::optional<int> height;
std::optional<int> width;
};
struct Image {
std::string url;
std::optional<int> height;
std::optional<int> width;
};
struct ExternalUrls {
std::string spotify;
};
struct ExternalUrls {
std::string spotify;
};
struct ExternalIds {
std::optional<std::string> isrc;
std::optional<std::string> ean;
std::optional<std::string> upc;
};
struct ExternalIds {
std::optional<std::string> isrc;
std::optional<std::string> ean;
std::optional<std::string> upc;
};
struct Followers {
std::optional<std::string> href;
int total;
};
struct Followers {
std::optional<std::string> href;
int total;
};
struct Copyright {
std::string text;
std::string type;
auto GetType() const -> CopyrightType {
return type == "C" ? CopyrightType::Copyright : CopyrightType::Performance;
}
};
struct Copyright {
std::string text;
std::string type;
struct Restrictions {
std::string reason;
auto GetReason() const -> RestrictionReason {
if (reason == "market") return RestrictionReason::Market;
if (reason == "product") return RestrictionReason::Product;
return RestrictionReason::Explicit;
}
};
auto GetType() const -> CopyrightType
{
return type == "C" ? CopyrightType::Copyright
: CopyrightType::Performance;
}
};
// ============================================================================
// Paging Objects
// ============================================================================
struct Restrictions {
std::string reason;
template<typename T>
struct PagingObject {
std::string href;
int limit;
std::optional<std::string> next;
int offset;
std::optional<std::string> previous;
int total;
std::vector<T> items;
};
auto GetReason() const -> RestrictionReason
{
if (reason == "market") {
return RestrictionReason::Market;
}
if (reason == "product") {
return RestrictionReason::Product;
}
return RestrictionReason::Explicit;
}
};
template<typename T>
struct CursorPagingObject {
std::string href;
int limit;
std::optional<std::string> next;
std::optional<std::string> cursors;
int total;
std::vector<T> items;
};
// ============================================================================
// Paging Objects
// ============================================================================
template <typename T> struct PagingObject {
std::string href;
int limit;
std::optional<std::string> next;
int offset;
std::optional<std::string> previous;
int total;
std::vector<T> items;
};
template <typename T> struct CursorPagingObject {
std::string href;
int limit;
std::optional<std::string> next;
std::optional<std::string> cursors;
int total;
std::vector<T> items;
};
} // namespace Spotify
// ============================================================================
// Glaze Metadata for Common Types
// ============================================================================
template <>
struct glz::meta<Spotify::Image> {
using T = Spotify::Image;
static constexpr auto value = object(
"url", &T::url,
"height", &T::height,
"width", &T::width
);
template <> struct glz::meta<Spotify::Image> {
using T = Spotify::Image;
static constexpr auto value =
object("url", &T::url, "height", &T::height, "width", &T::width);
};
template <>
struct glz::meta<Spotify::ExternalUrls> {
using T = Spotify::ExternalUrls;
static constexpr auto value = object("spotify", &T::spotify);
template <> struct glz::meta<Spotify::ExternalUrls> {
using T = Spotify::ExternalUrls;
static constexpr auto value = object("spotify", &T::spotify);
};
template <>
struct glz::meta<Spotify::ExternalIds> {
using T = Spotify::ExternalIds;
static constexpr auto value = object(
"isrc", &T::isrc,
"ean", &T::ean,
"upc", &T::upc
);
template <> struct glz::meta<Spotify::ExternalIds> {
using T = Spotify::ExternalIds;
static constexpr auto value =
object("isrc", &T::isrc, "ean", &T::ean, "upc", &T::upc);
};
template <>
struct glz::meta<Spotify::Followers> {
using T = Spotify::Followers;
static constexpr auto value = object(
"href", &T::href,
"total", &T::total
);
template <> struct glz::meta<Spotify::Followers> {
using T = Spotify::Followers;
static constexpr auto value =
object("href", &T::href, "total", &T::total);
};
template <>
struct glz::meta<Spotify::Copyright> {
using T = Spotify::Copyright;
static constexpr auto value = object(
"text", &T::text,
"type", &T::type
);
template <> struct glz::meta<Spotify::Copyright> {
using T = Spotify::Copyright;
static constexpr auto value =
object("text", &T::text, "type", &T::type);
};
template <>
struct glz::meta<Spotify::Restrictions> {
using T = Spotify::Restrictions;
static constexpr auto value = object("reason", &T::reason);
template <> struct glz::meta<Spotify::Restrictions> {
using T = Spotify::Restrictions;
static constexpr auto value = object("reason", &T::reason);
};
template <typename T>
struct glz::meta<Spotify::PagingObject<T>> {
using Type = Spotify::PagingObject<T>;
static constexpr auto value = object(
"href", &Type::href,
"limit", &Type::limit,
"next", &Type::next,
"offset", &Type::offset,
"previous", &Type::previous,
"total", &Type::total,
"items", &Type::items
);
template <typename T> struct glz::meta<Spotify::PagingObject<T>> {
using Type = Spotify::PagingObject<T>;
static constexpr auto value = object(
"href", &Type::href, "limit", &Type::limit, "next", &Type::next,
"offset", &Type::offset, "previous", &Type::previous, "total",
&Type::total, "items", &Type::items);
};
template <typename T>
struct glz::meta<Spotify::CursorPagingObject<T>> {
using Type = Spotify::CursorPagingObject<T>;
static constexpr auto value = object(
"href", &Type::href,
"limit", &Type::limit,
"next", &Type::next,
"cursors", &Type::cursors,
"total", &Type::total,
"items", &Type::items
);
template <typename T> struct glz::meta<Spotify::CursorPagingObject<T>> {
using Type = Spotify::CursorPagingObject<T>;
static constexpr auto value =
object("href", &Type::href, "limit", &Type::limit, "next",
&Type::next, "cursors", &Type::cursors, "total",
&Type::total, "items", &Type::items);
};
+110 -103
View File
@@ -1,133 +1,140 @@
#pragma once
#include "Spotify/Types/Common.hpp"
#include "Spotify/Types/Track.hpp"
#include "Spotify/Types/Artist.hpp"
#include "Spotify/Types/Album.hpp"
#include "Spotify/Types/Artist.hpp"
#include "Spotify/Types/Common.hpp"
#include "Spotify/Types/Playlist.hpp"
#include "Spotify/Types/Track.hpp"
#include <optional>
#include <string>
#include <vector>
namespace Spotify {
namespace Spotify
{
// ============================================================================
// Category
// ============================================================================
// ============================================================================
// Category
// ============================================================================
struct Category {
std::string href;
std::vector<Image> icons;
std::string id;
std::string name;
auto GetId() const -> const std::string& { return id; }
auto GetName() const -> const std::string& { return name; }
};
struct Category {
std::string href;
std::vector<Image> icons;
std::string id;
std::string name;
// ============================================================================
// Recommendation Seed
// ============================================================================
auto GetId() const -> const std::string& { return id; }
auto GetName() const -> const std::string& { return name; }
};
enum class SeedType {
Artist,
Track,
Genre
};
// ============================================================================
// Recommendation Seed
// ============================================================================
inline auto StringToSeedType(const std::string& str) -> SeedType {
if (str == "ARTIST") return SeedType::Artist;
if (str == "TRACK") return SeedType::Track;
return SeedType::Genre;
}
enum class SeedType { Artist, Track, Genre };
struct RecommendationSeed {
int afterFilteringSize;
int afterRelinkingSize;
std::optional<std::string> href;
std::string id;
int initialPoolSize;
std::string type;
auto GetId() const -> const std::string& { return id; }
auto GetSeedType() const -> SeedType {
return StringToSeedType(type);
}
};
inline auto StringToSeedType(const std::string& str) -> SeedType
{
if (str == "ARTIST") {
return SeedType::Artist;
}
if (str == "TRACK") {
return SeedType::Track;
}
return SeedType::Genre;
}
// ============================================================================
// Recommendations Response
// ============================================================================
struct RecommendationSeed {
int afterFilteringSize;
int afterRelinkingSize;
std::optional<std::string> href;
std::string id;
int initialPoolSize;
std::string type;
struct Recommendations {
std::vector<RecommendationSeed> seeds;
std::vector<Track> tracks;
auto GetTracks() const -> const std::vector<Track>& { return tracks; }
auto GetSeeds() const -> const std::vector<RecommendationSeed>& { return seeds; }
};
auto GetId() const -> const std::string& { return id; }
auto GetSeedType() const -> SeedType
{
return StringToSeedType(type);
}
};
// ============================================================================
// Search Results
// ============================================================================
// ============================================================================
// Recommendations Response
// ============================================================================
struct SearchResults {
std::optional<PagingObject<Track>> tracks;
std::optional<PagingObject<Artist>> artists;
std::optional<PagingObject<SimplifiedAlbum>> albums;
std::optional<PagingObject<SimplifiedPlaylist>> playlists;
auto GetTracks() const -> const std::optional<PagingObject<Track>>& { return tracks; }
auto GetArtists() const -> const std::optional<PagingObject<Artist>>& { return artists; }
auto GetAlbums() const -> const std::optional<PagingObject<SimplifiedAlbum>>& { return albums; }
auto GetPlaylists() const -> const std::optional<PagingObject<SimplifiedPlaylist>>& { return playlists; }
};
struct Recommendations {
std::vector<RecommendationSeed> seeds;
std::vector<Track> tracks;
auto GetTracks() const -> const std::vector<Track>&
{
return tracks;
}
auto GetSeeds() const -> const std::vector<RecommendationSeed>&
{
return seeds;
}
};
// ============================================================================
// Search Results
// ============================================================================
struct SearchResults {
std::optional<PagingObject<Track>> tracks;
std::optional<PagingObject<Artist>> artists;
std::optional<PagingObject<SimplifiedAlbum>> albums;
std::optional<PagingObject<SimplifiedPlaylist>> playlists;
auto GetTracks() const -> const std::optional<PagingObject<Track>>&
{
return tracks;
}
auto GetArtists() const
-> const std::optional<PagingObject<Artist>>&
{
return artists;
}
auto GetAlbums() const
-> const std::optional<PagingObject<SimplifiedAlbum>>&
{
return albums;
}
auto GetPlaylists() const
-> const std::optional<PagingObject<SimplifiedPlaylist>>&
{
return playlists;
}
};
} // namespace Spotify
// ============================================================================
// Glaze Metadata
// ============================================================================
template <>
struct glz::meta<Spotify::Category> {
using T = Spotify::Category;
static constexpr auto value = object(
"href", &T::href,
"icons", &T::icons,
"id", &T::id,
"name", &T::name
);
template <> struct glz::meta<Spotify::Category> {
using T = Spotify::Category;
static constexpr auto value =
object("href", &T::href, "icons", &T::icons, "id", &T::id, "name",
&T::name);
};
template <>
struct glz::meta<Spotify::RecommendationSeed> {
using T = Spotify::RecommendationSeed;
static constexpr auto value = object(
"afterFilteringSize", &T::afterFilteringSize,
"afterRelinkingSize", &T::afterRelinkingSize,
"href", &T::href,
"id", &T::id,
"initialPoolSize", &T::initialPoolSize,
"type", &T::type
);
template <> struct glz::meta<Spotify::RecommendationSeed> {
using T = Spotify::RecommendationSeed;
static constexpr auto value = object(
"afterFilteringSize", &T::afterFilteringSize, "afterRelinkingSize",
&T::afterRelinkingSize, "href", &T::href, "id", &T::id,
"initialPoolSize", &T::initialPoolSize, "type", &T::type);
};
template <>
struct glz::meta<Spotify::Recommendations> {
using T = Spotify::Recommendations;
static constexpr auto value = object(
"seeds", &T::seeds,
"tracks", &T::tracks
);
template <> struct glz::meta<Spotify::Recommendations> {
using T = Spotify::Recommendations;
static constexpr auto value =
object("seeds", &T::seeds, "tracks", &T::tracks);
};
template <>
struct glz::meta<Spotify::SearchResults> {
using T = Spotify::SearchResults;
static constexpr auto value = object(
"tracks", &T::tracks,
"artists", &T::artists,
"albums", &T::albums,
"playlists", &T::playlists
);
template <> struct glz::meta<Spotify::SearchResults> {
using T = Spotify::SearchResults;
static constexpr auto value =
object("tracks", &T::tracks, "artists", &T::artists, "albums",
&T::albums, "playlists", &T::playlists);
};
+213 -184
View File
@@ -2,217 +2,246 @@
#include "Spotify/Types/Common.hpp"
#include "Spotify/Types/Track.hpp"
namespace Spotify {
namespace Spotify
{
// ============================================================================
// Device Type Enum
// ============================================================================
// ============================================================================
// Device Type Enum
// ============================================================================
enum class DeviceType {
Computer,
Smartphone,
Speaker,
TV,
AVR,
STB,
AudioDongle,
GameConsole,
CastVideo,
CastAudio,
Automobile,
Unknown
};
enum class DeviceType {
Computer,
Smartphone,
Speaker,
TV,
AVR,
STB,
AudioDongle,
GameConsole,
CastVideo,
CastAudio,
Automobile,
Unknown
};
inline auto StringToDeviceType(const std::string& str) -> DeviceType {
if (str == "Computer") return DeviceType::Computer;
if (str == "Smartphone") return DeviceType::Smartphone;
if (str == "Speaker") return DeviceType::Speaker;
if (str == "TV") return DeviceType::TV;
if (str == "AVR") return DeviceType::AVR;
if (str == "STB") return DeviceType::STB;
if (str == "AudioDongle") return DeviceType::AudioDongle;
if (str == "GameConsole") return DeviceType::GameConsole;
if (str == "CastVideo") return DeviceType::CastVideo;
if (str == "CastAudio") return DeviceType::CastAudio;
if (str == "Automobile") return DeviceType::Automobile;
return DeviceType::Unknown;
}
inline auto StringToDeviceType(const std::string& str) -> DeviceType
{
if (str == "Computer") {
return DeviceType::Computer;
}
if (str == "Smartphone") {
return DeviceType::Smartphone;
}
if (str == "Speaker") {
return DeviceType::Speaker;
}
if (str == "TV") {
return DeviceType::TV;
}
if (str == "AVR") {
return DeviceType::AVR;
}
if (str == "STB") {
return DeviceType::STB;
}
if (str == "AudioDongle") {
return DeviceType::AudioDongle;
}
if (str == "GameConsole") {
return DeviceType::GameConsole;
}
if (str == "CastVideo") {
return DeviceType::CastVideo;
}
if (str == "CastAudio") {
return DeviceType::CastAudio;
}
if (str == "Automobile") {
return DeviceType::Automobile;
}
return DeviceType::Unknown;
}
// ============================================================================
// Repeat Mode Enum
// ============================================================================
// ============================================================================
// Repeat Mode Enum
// ============================================================================
enum class RepeatMode {
Off,
Track,
Context
};
enum class RepeatMode { Off, Track, Context };
inline auto RepeatModeToString(RepeatMode mode) -> std::string {
switch (mode) {
case RepeatMode::Off: return "off";
case RepeatMode::Track: return "track";
case RepeatMode::Context: return "context";
}
return "off";
}
inline auto RepeatModeToString(RepeatMode mode) -> std::string
{
switch (mode) {
case RepeatMode::Off:
return "off";
case RepeatMode::Track:
return "track";
case RepeatMode::Context:
return "context";
}
return "off";
}
inline auto StringToRepeatMode(const std::string& str) -> RepeatMode {
if (str == "track") return RepeatMode::Track;
if (str == "context") return RepeatMode::Context;
return RepeatMode::Off;
}
inline auto StringToRepeatMode(const std::string& str) -> RepeatMode
{
if (str == "track") {
return RepeatMode::Track;
}
if (str == "context") {
return RepeatMode::Context;
}
return RepeatMode::Off;
}
// ============================================================================
// Context Type Enum
// ============================================================================
// ============================================================================
// Context Type Enum
// ============================================================================
enum class ContextType {
Artist,
Playlist,
Album,
Show,
Collection
};
enum class ContextType { Artist, Playlist, Album, Show, Collection };
inline auto StringToContextType(const std::string& str) -> ContextType {
if (str == "artist") return ContextType::Artist;
if (str == "playlist") return ContextType::Playlist;
if (str == "album") return ContextType::Album;
if (str == "show") return ContextType::Show;
return ContextType::Collection;
}
inline auto StringToContextType(const std::string& str) -> ContextType
{
if (str == "artist") {
return ContextType::Artist;
}
if (str == "playlist") {
return ContextType::Playlist;
}
if (str == "album") {
return ContextType::Album;
}
if (str == "show") {
return ContextType::Show;
}
return ContextType::Collection;
}
// ============================================================================
// Currently Playing Type Enum
// ============================================================================
// ============================================================================
// Currently Playing Type Enum
// ============================================================================
enum class CurrentlyPlayingType {
Track,
Episode,
Ad,
Unknown
};
enum class CurrentlyPlayingType { Track, Episode, Ad, Unknown };
inline auto StringToCurrentlyPlayingType(const std::string& str) -> CurrentlyPlayingType {
if (str == "track") return CurrentlyPlayingType::Track;
if (str == "episode") return CurrentlyPlayingType::Episode;
if (str == "ad") return CurrentlyPlayingType::Ad;
return CurrentlyPlayingType::Unknown;
}
inline auto StringToCurrentlyPlayingType(const std::string& str)
-> CurrentlyPlayingType
{
if (str == "track") {
return CurrentlyPlayingType::Track;
}
if (str == "episode") {
return CurrentlyPlayingType::Episode;
}
if (str == "ad") {
return CurrentlyPlayingType::Ad;
}
return CurrentlyPlayingType::Unknown;
}
// ============================================================================
// Device
// ============================================================================
// ============================================================================
// Device
// ============================================================================
struct Device {
std::optional<std::string> id;
bool is_active;
bool is_private_session;
bool is_restricted;
std::string name;
std::string type;
int volume_percent;
auto GetId() const -> const std::optional<std::string>& { return id; }
auto GetName() const -> const std::string& { return name; }
auto IsActive() const -> bool { return is_active; }
auto GetVolume() const -> int { return volume_percent; }
auto GetDeviceType() const -> DeviceType {
return StringToDeviceType(type);
}
};
struct Device {
std::optional<std::string> id;
bool is_active;
bool is_private_session;
bool is_restricted;
std::string name;
std::string type;
int volume_percent;
// ============================================================================
// Context
// ============================================================================
auto GetId() const -> const std::optional<std::string>&
{
return id;
}
auto GetName() const -> const std::string& { return name; }
auto IsActive() const -> bool { return is_active; }
auto GetVolume() const -> int { return volume_percent; }
struct Context {
std::string type;
std::string href;
ExternalUrls external_urls;
std::string uri;
auto GetUri() const -> const std::string& { return uri; }
auto GetContextType() const -> ContextType {
return StringToContextType(type);
}
};
auto GetDeviceType() const -> DeviceType
{
return StringToDeviceType(type);
}
};
// ============================================================================
// Playback State
// ============================================================================
// ============================================================================
// Context
// ============================================================================
struct PlaybackState {
Device device;
std::string repeat_state;
bool shuffle_state;
std::optional<Context> context;
int timestamp;
int progress_ms;
bool is_playing;
std::optional<Track> item;
std::string currently_playing_type;
auto GetDevice() const -> const Device& { return device; }
auto IsPlaying() const -> bool { return is_playing; }
auto IsShuffled() const -> bool { return shuffle_state; }
auto GetProgressMs() const -> int { return progress_ms; }
auto GetCurrentTrack() const -> const std::optional<Track>& { return item; }
auto GetRepeatMode() const -> RepeatMode {
return StringToRepeatMode(repeat_state);
}
auto GetCurrentlyPlayingType() const -> CurrentlyPlayingType {
return StringToCurrentlyPlayingType(currently_playing_type);
}
};
struct Context {
std::string type;
std::string href;
ExternalUrls external_urls;
std::string uri;
auto GetUri() const -> const std::string& { return uri; }
auto GetContextType() const -> ContextType
{
return StringToContextType(type);
}
};
// ============================================================================
// Playback State
// ============================================================================
struct PlaybackState {
Device device;
std::string repeat_state;
bool shuffle_state;
std::optional<Context> context;
int timestamp;
int progress_ms;
bool is_playing;
std::optional<Track> item;
std::string currently_playing_type;
auto GetDevice() const -> const Device& { return device; }
auto IsPlaying() const -> bool { return is_playing; }
auto IsShuffled() const -> bool { return shuffle_state; }
auto GetProgressMs() const -> int { return progress_ms; }
auto GetCurrentTrack() const -> const std::optional<Track>&
{
return item;
}
auto GetRepeatMode() const -> RepeatMode
{
return StringToRepeatMode(repeat_state);
}
auto GetCurrentlyPlayingType() const -> CurrentlyPlayingType
{
return StringToCurrentlyPlayingType(currently_playing_type);
}
};
} // namespace Spotify
// ============================================================================
// Glaze Metadata
// ============================================================================
template <>
struct glz::meta<Spotify::Device> {
using T = Spotify::Device;
static constexpr auto value = object(
"id", &T::id,
"is_active", &T::is_active,
"is_private_session", &T::is_private_session,
"is_restricted", &T::is_restricted,
"name", &T::name,
"type", &T::type,
"volume_percent", &T::volume_percent
);
template <> struct glz::meta<Spotify::Device> {
using T = Spotify::Device;
static constexpr auto value = object(
"id", &T::id, "is_active", &T::is_active, "is_private_session",
&T::is_private_session, "is_restricted", &T::is_restricted, "name",
&T::name, "type", &T::type, "volume_percent", &T::volume_percent);
};
template <>
struct glz::meta<Spotify::Context> {
using T = Spotify::Context;
static constexpr auto value = object(
"type", &T::type,
"href", &T::href,
"external_urls", &T::external_urls,
"uri", &T::uri
);
template <> struct glz::meta<Spotify::Context> {
using T = Spotify::Context;
static constexpr auto value =
object("type", &T::type, "href", &T::href, "external_urls",
&T::external_urls, "uri", &T::uri);
};
template <>
struct glz::meta<Spotify::PlaybackState> {
using T = Spotify::PlaybackState;
static constexpr auto value = object(
"device", &T::device,
"repeat_state", &T::repeat_state,
"shuffle_state", &T::shuffle_state,
"context", &T::context,
"timestamp", &T::timestamp,
"progress_ms", &T::progress_ms,
"is_playing", &T::is_playing,
"item", &T::item,
"currently_playing_type", &T::currently_playing_type
);
template <> struct glz::meta<Spotify::PlaybackState> {
using T = Spotify::PlaybackState;
static constexpr auto value =
object("device", &T::device, "repeat_state", &T::repeat_state,
"shuffle_state", &T::shuffle_state, "context", &T::context,
"timestamp", &T::timestamp, "progress_ms", &T::progress_ms,
"is_playing", &T::is_playing, "item", &T::item,
"currently_playing_type", &T::currently_playing_type);
};
+96 -114
View File
@@ -1,139 +1,121 @@
#pragma once
#include "Spotify/Types/Common.hpp"
#include "Spotify/Types/Artist.hpp"
#include "Spotify/Types/Common.hpp"
#include "Spotify/Types/Track.hpp"
namespace Spotify {
namespace Spotify
{
// ============================================================================
// Playlist Track
// ============================================================================
// ============================================================================
// Playlist Track
// ============================================================================
struct PlaylistTrack {
std::optional<std::string> added_at;
std::optional<SimplifiedArtist> added_by;
bool is_local;
Track track;
auto GetTrack() const -> const Track& { return track; }
auto GetAddedAt() const -> const std::optional<std::string>& { return added_at; }
auto IsLocal() const -> bool { return is_local; }
};
struct PlaylistTrack {
std::optional<std::string> added_at;
std::optional<SimplifiedArtist> added_by;
bool is_local;
Track track;
// ============================================================================
// Playlist Base
// ============================================================================
auto GetTrack() const -> const Track & { return track; }
auto GetAddedAt() const -> const std::optional<std::string> &
{
return added_at;
}
auto IsLocal() const -> bool { return is_local; }
};
class PlaylistBase {
public:
bool collaborative;
std::optional<std::string> description;
ExternalUrls external_urls;
std::string href;
std::string id;
std::vector<Image> images;
std::string name;
SimplifiedArtist owner;
bool public_playlist;
std::optional<std::string> snapshot_id;
std::string type;
std::string uri;
virtual ~PlaylistBase() = default;
auto GetId() const -> const std::string& { return id; }
auto GetName() const -> const std::string& { return name; }
auto GetUri() const -> const std::string& { return uri; }
auto GetOwner() const -> const SimplifiedArtist& { return owner; }
auto IsPublic() const -> bool { return public_playlist; }
auto IsCollaborative() const -> bool { return collaborative; }
auto GetSnapshotId() const -> const std::optional<std::string>& { return snapshot_id; }
};
// ============================================================================
// Playlist Base
// ============================================================================
// ============================================================================
// Simplified Playlist
// ============================================================================
class PlaylistBase
{
public:
struct SimplifiedPlaylist : PlaylistBase {
struct TracksInfo {
std::string href;
int total;
} tracks;
auto GetTotalTracks() const -> int { return tracks.total; }
};
bool collaborative;
std::optional<std::string> description;
ExternalUrls external_urls;
std::string href;
std::string id;
std::vector<Image> images;
std::string name;
SimplifiedArtist owner;
bool public_playlist;
std::optional<std::string> snapshot_id;
std::string type;
std::string uri;
// ============================================================================
// Full Playlist
// ============================================================================
virtual ~PlaylistBase() = default;
struct Playlist : PlaylistBase {
Followers followers;
auto GetFollowers() const -> const Followers& { return followers; }
};
auto GetId() const -> const std::string & { return id; }
auto GetName() const -> const std::string & { return name; }
auto GetUri() const -> const std::string & { return uri; }
auto GetOwner() const -> const SimplifiedArtist & { return owner; }
auto IsPublic() const -> bool { return public_playlist; }
auto IsCollaborative() const -> bool { return collaborative; }
auto GetSnapshotId() const -> const std::optional<std::string> &
{
return snapshot_id;
}
};
// ============================================================================
// Simplified Playlist
// ============================================================================
struct SimplifiedPlaylist : PlaylistBase {
struct TracksInfo {
std::string href;
int total;
} tracks;
auto GetTotalTracks() const -> int { return tracks.total; }
};
// ============================================================================
// Full Playlist
// ============================================================================
struct Playlist : PlaylistBase {
Followers followers;
auto GetFollowers() const -> const Followers & { return followers; }
};
} // namespace Spotify
// ============================================================================
// Glaze Metadata
// ============================================================================
template <>
struct glz::meta<Spotify::PlaylistTrack> {
using T = Spotify::PlaylistTrack;
static constexpr auto value = object(
"added_at", &T::added_at,
"added_by", &T::added_by,
"is_local", &T::is_local,
"track", &T::track
);
template <> struct glz::meta<Spotify::PlaylistTrack> {
using T = Spotify::PlaylistTrack;
static constexpr auto value =
object("added_at", &T::added_at, "added_by", &T::added_by,
"is_local", &T::is_local, "track", &T::track);
};
template <>
struct glz::meta<Spotify::SimplifiedPlaylist::TracksInfo> {
using T = Spotify::SimplifiedPlaylist::TracksInfo;
static constexpr auto value = object(
"href", &T::href,
"total", &T::total
);
template <> struct glz::meta<Spotify::SimplifiedPlaylist::TracksInfo> {
using T = Spotify::SimplifiedPlaylist::TracksInfo;
static constexpr auto value =
object("href", &T::href, "total", &T::total);
};
template <>
struct glz::meta<Spotify::SimplifiedPlaylist> {
using T = Spotify::SimplifiedPlaylist;
static constexpr auto value = object(
"collaborative", &T::collaborative,
"description", &T::description,
"external_urls", &T::external_urls,
"href", &T::href,
"id", &T::id,
"images", &T::images,
"name", &T::name,
"owner", &T::owner,
"public", &T::public_playlist,
"snapshot_id", &T::snapshot_id,
"tracks", &T::tracks,
"type", &T::type,
"uri", &T::uri
);
template <> struct glz::meta<Spotify::SimplifiedPlaylist> {
using T = Spotify::SimplifiedPlaylist;
static constexpr auto value = object(
"collaborative", &T::collaborative, "description", &T::description,
"external_urls", &T::external_urls, "href", &T::href, "id", &T::id,
"images", &T::images, "name", &T::name, "owner", &T::owner,
"public", &T::public_playlist, "snapshot_id", &T::snapshot_id,
"tracks", &T::tracks, "type", &T::type, "uri", &T::uri);
};
template <>
struct glz::meta<Spotify::Playlist> {
using T = Spotify::Playlist;
static constexpr auto value = object(
"collaborative", &T::collaborative,
"description", &T::description,
"external_urls", &T::external_urls,
"followers", &T::followers,
"href", &T::href,
"id", &T::id,
"images", &T::images,
"name", &T::name,
"owner", &T::owner,
"public", &T::public_playlist,
"snapshot_id", &T::snapshot_id,
"type", &T::type,
"uri", &T::uri
);
template <> struct glz::meta<Spotify::Playlist> {
using T = Spotify::Playlist;
static constexpr auto value = object(
"collaborative", &T::collaborative, "description", &T::description,
"external_urls", &T::external_urls, "followers", &T::followers,
"href", &T::href, "id", &T::id, "images", &T::images, "name",
&T::name, "owner", &T::owner, "public", &T::public_playlist,
"snapshot_id", &T::snapshot_id, "type", &T::type, "uri", &T::uri);
};
+243 -276
View File
@@ -1,318 +1,285 @@
#pragma once
#include "Spotify/Types/Common.hpp"
#include "Spotify/Types/Artist.hpp"
#include "Spotify/Types/Album.hpp"
#include "Spotify/Types/Artist.hpp"
#include "Spotify/Types/Common.hpp"
namespace Spotify {
namespace Spotify
{
// ============================================================================
// Track Base
// ============================================================================
// ============================================================================
// Track Base
// ============================================================================
class TrackBase {
public:
std::vector<SimplifiedArtist> artists;
std::vector<std::string> available_markets;
int disc_number;
int duration_ms;
bool explicit_content;
ExternalUrls external_urls;
std::string href;
std::string id;
bool is_playable;
std::optional<std::string> linked_from;
std::optional<Restrictions> restrictions;
std::string name;
std::optional<std::string> preview_url;
int track_number;
std::string type;
std::string uri;
bool is_local;
virtual ~TrackBase() = default;
auto GetId() const -> const std::string& { return id; }
auto GetName() const -> const std::string& { return name; }
auto GetUri() const -> const std::string& { return uri; }
auto GetDurationMs() const -> int { return duration_ms; }
auto GetTrackNumber() const -> int { return track_number; }
auto IsExplicit() const -> bool { return explicit_content; }
auto IsLocal() const -> bool { return is_local; }
auto GetArtists() const -> const std::vector<SimplifiedArtist>& { return artists; }
};
class TrackBase
{
public:
// ============================================================================
// Simplified Track
// ============================================================================
std::vector<SimplifiedArtist> artists;
std::vector<std::string> available_markets;
int disc_number;
int duration_ms;
bool explicit_content;
ExternalUrls external_urls;
std::string href;
std::string id;
bool is_playable;
std::optional<std::string> linked_from;
std::optional<Restrictions> restrictions;
std::string name;
std::optional<std::string> preview_url;
int track_number;
std::string type;
std::string uri;
bool is_local;
struct SimplifiedTrack : TrackBase {
};
virtual ~TrackBase() = default;
// ============================================================================
// Full Track
// ============================================================================
auto GetId() const -> const std::string & { return id; }
auto GetName() const -> const std::string & { return name; }
auto GetUri() const -> const std::string & { return uri; }
auto GetDurationMs() const -> int { return duration_ms; }
auto GetTrackNumber() const -> int { return track_number; }
auto IsExplicit() const -> bool { return explicit_content; }
auto IsLocal() const -> bool { return is_local; }
auto GetArtists() const -> const std::vector<SimplifiedArtist> &
{
return artists;
}
};
struct Track : TrackBase {
SimplifiedAlbum album;
ExternalIds external_ids;
int popularity;
auto GetAlbum() const -> const SimplifiedAlbum& { return album; }
auto GetPopularity() const -> int { return popularity; }
};
// ============================================================================
// Simplified Track
// ============================================================================
// ============================================================================
// Saved Track
// ============================================================================
struct SimplifiedTrack : TrackBase {
};
struct SavedTrack {
std::string added_at;
Track track;
auto GetTrack() const -> const Track& { return track; }
auto GetAddedAt() const -> const std::string& { return added_at; }
};
// ============================================================================
// Full Track
// ============================================================================
// ============================================================================
// Audio Features
// ============================================================================
struct Track : TrackBase {
SimplifiedAlbum album;
ExternalIds external_ids;
int popularity;
enum class MusicalKey {
C = 0, CSharp = 1, D = 2, DSharp = 3,
E = 4, F = 5, FSharp = 6, G = 7,
GSharp = 8, A = 9, ASharp = 10, B = 11
};
auto GetAlbum() const -> const SimplifiedAlbum & { return album; }
auto GetPopularity() const -> int { return popularity; }
};
enum class MusicalMode {
Minor = 0,
Major = 1
};
// ============================================================================
// Saved Track
// ============================================================================
struct AudioFeatures {
float acousticness;
std::string analysis_url;
float danceability;
int duration_ms;
float energy;
std::string id;
float instrumentalness;
int key;
float liveness;
float loudness;
int mode;
float speechiness;
float tempo;
int time_signature;
std::string track_href;
std::string type;
std::string uri;
float valence;
auto GetKey() const -> MusicalKey { return static_cast<MusicalKey>(key); }
auto GetMode() const -> MusicalMode { return static_cast<MusicalMode>(mode); }
auto GetAcousticness() const -> float { return acousticness; }
auto GetDanceability() const -> float { return danceability; }
auto GetEnergy() const -> float { return energy; }
auto GetValence() const -> float { return valence; }
auto GetTempo() const -> float { return tempo; }
};
struct SavedTrack {
std::string added_at;
Track track;
// ============================================================================
// Audio Analysis
// ============================================================================
auto GetTrack() const -> const Track & { return track; }
auto GetAddedAt() const -> const std::string & { return added_at; }
};
struct TimeInterval {
float start;
float duration;
float confidence;
};
// ============================================================================
// Audio Features
// ============================================================================
struct Section {
float start;
float duration;
float confidence;
float loudness;
float tempo;
float tempo_confidence;
int key;
float key_confidence;
int mode;
float mode_confidence;
int time_signature;
float time_signature_confidence;
};
enum class MusicalKey {
C = 0,
CSharp = 1,
D = 2,
DSharp = 3,
E = 4,
F = 5,
FSharp = 6,
G = 7,
GSharp = 8,
A = 9,
ASharp = 10,
B = 11
};
struct Segment {
float start;
float duration;
float confidence;
float loudness_start;
float loudness_max;
float loudness_max_time;
float loudness_end;
std::vector<float> pitches;
std::vector<float> timbre;
};
enum class MusicalMode { Minor = 0, Major = 1 };
struct AudioAnalysis {
std::vector<TimeInterval> bars;
std::vector<TimeInterval> beats;
std::vector<Section> sections;
std::vector<Segment> segments;
std::vector<TimeInterval> tatums;
auto GetBars() const -> const std::vector<TimeInterval>& { return bars; }
auto GetBeats() const -> const std::vector<TimeInterval>& { return beats; }
auto GetSections() const -> const std::vector<Section>& { return sections; }
};
struct AudioFeatures {
float acousticness;
std::string analysis_url;
float danceability;
int duration_ms;
float energy;
std::string id;
float instrumentalness;
int key;
float liveness;
float loudness;
int mode;
float speechiness;
float tempo;
int time_signature;
std::string track_href;
std::string type;
std::string uri;
float valence;
struct TracksResponse {
std::vector<Track> tracks;
};
auto GetKey() const -> MusicalKey
{
return static_cast<MusicalKey>(key);
}
auto GetMode() const -> MusicalMode
{
return static_cast<MusicalMode>(mode);
}
auto GetAcousticness() const -> float { return acousticness; }
auto GetDanceability() const -> float { return danceability; }
auto GetEnergy() const -> float { return energy; }
auto GetValence() const -> float { return valence; }
auto GetTempo() const -> float { return tempo; }
};
// ============================================================================
// Audio Analysis
// ============================================================================
struct TimeInterval {
float start;
float duration;
float confidence;
};
struct Section {
float start;
float duration;
float confidence;
float loudness;
float tempo;
float tempo_confidence;
int key;
float key_confidence;
int mode;
float mode_confidence;
int time_signature;
float time_signature_confidence;
};
struct Segment {
float start;
float duration;
float confidence;
float loudness_start;
float loudness_max;
float loudness_max_time;
float loudness_end;
std::vector<float> pitches;
std::vector<float> timbre;
};
struct AudioAnalysis {
std::vector<TimeInterval> bars;
std::vector<TimeInterval> beats;
std::vector<Section> sections;
std::vector<Segment> segments;
std::vector<TimeInterval> tatums;
auto GetBars() const -> const std::vector<TimeInterval> &
{
return bars;
}
auto GetBeats() const -> const std::vector<TimeInterval> &
{
return beats;
}
auto GetSections() const -> const std::vector<Section> &
{
return sections;
}
};
struct TracksResponse {
std::vector<Track> tracks;
};
} // namespace Spotify
// ============================================================================
// Glaze Metadata
// ============================================================================
template <>
struct glz::meta<Spotify::SimplifiedTrack> {
using T = Spotify::SimplifiedTrack;
static constexpr auto value = object(
"artists", &T::artists,
"available_markets", &T::available_markets,
"disc_number", &T::disc_number,
"duration_ms", &T::duration_ms,
"explicit", &T::explicit_content,
"external_urls", &T::external_urls,
"href", &T::href,
"id", &T::id,
"is_playable", &T::is_playable,
"linked_from", &T::linked_from,
"restrictions", &T::restrictions,
"name", &T::name,
"preview_url", &T::preview_url,
"track_number", &T::track_number,
"type", &T::type,
"uri", &T::uri,
"is_local", &T::is_local
);
template <> struct glz::meta<Spotify::SimplifiedTrack> {
using T = Spotify::SimplifiedTrack;
static constexpr auto value = object(
"artists", &T::artists, "available_markets", &T::available_markets,
"disc_number", &T::disc_number, "duration_ms", &T::duration_ms,
"explicit", &T::explicit_content, "external_urls",
&T::external_urls, "href", &T::href, "id", &T::id, "is_playable",
&T::is_playable, "linked_from", &T::linked_from, "restrictions",
&T::restrictions, "name", &T::name, "preview_url", &T::preview_url,
"track_number", &T::track_number, "type", &T::type, "uri", &T::uri,
"is_local", &T::is_local);
};
template <>
struct glz::meta<Spotify::Track> {
using T = Spotify::Track;
static constexpr auto value = object(
"album", &T::album,
"artists", &T::artists,
"available_markets", &T::available_markets,
"disc_number", &T::disc_number,
"duration_ms", &T::duration_ms,
"explicit", &T::explicit_content,
"external_ids", &T::external_ids,
"external_urls", &T::external_urls,
"href", &T::href,
"id", &T::id,
"is_playable", &T::is_playable,
"linked_from", &T::linked_from,
"restrictions", &T::restrictions,
"name", &T::name,
"popularity", &T::popularity,
"preview_url", &T::preview_url,
"track_number", &T::track_number,
"type", &T::type,
"uri", &T::uri,
"is_local", &T::is_local
);
template <> struct glz::meta<Spotify::Track> {
using T = Spotify::Track;
static constexpr auto value = object(
"album", &T::album, "artists", &T::artists, "available_markets",
&T::available_markets, "disc_number", &T::disc_number,
"duration_ms", &T::duration_ms, "explicit", &T::explicit_content,
"external_ids", &T::external_ids, "external_urls",
&T::external_urls, "href", &T::href, "id", &T::id, "is_playable",
&T::is_playable, "linked_from", &T::linked_from, "restrictions",
&T::restrictions, "name", &T::name, "popularity", &T::popularity,
"preview_url", &T::preview_url, "track_number", &T::track_number,
"type", &T::type, "uri", &T::uri, "is_local", &T::is_local);
};
template <>
struct glz::meta<Spotify::SavedTrack> {
using T = Spotify::SavedTrack;
static constexpr auto value = object(
"added_at", &T::added_at,
"track", &T::track
);
template <> struct glz::meta<Spotify::SavedTrack> {
using T = Spotify::SavedTrack;
static constexpr auto value =
object("added_at", &T::added_at, "track", &T::track);
};
template <>
struct glz::meta<Spotify::AudioFeatures> {
using T = Spotify::AudioFeatures;
static constexpr auto value = object(
"acousticness", &T::acousticness,
"analysis_url", &T::analysis_url,
"danceability", &T::danceability,
"duration_ms", &T::duration_ms,
"energy", &T::energy,
"id", &T::id,
"instrumentalness", &T::instrumentalness,
"key", &T::key,
"liveness", &T::liveness,
"loudness", &T::loudness,
"mode", &T::mode,
"speechiness", &T::speechiness,
"tempo", &T::tempo,
"time_signature", &T::time_signature,
"track_href", &T::track_href,
"type", &T::type,
"uri", &T::uri,
"valence", &T::valence
);
template <> struct glz::meta<Spotify::AudioFeatures> {
using T = Spotify::AudioFeatures;
static constexpr auto value = object(
"acousticness", &T::acousticness, "analysis_url", &T::analysis_url,
"danceability", &T::danceability, "duration_ms", &T::duration_ms,
"energy", &T::energy, "id", &T::id, "instrumentalness",
&T::instrumentalness, "key", &T::key, "liveness", &T::liveness,
"loudness", &T::loudness, "mode", &T::mode, "speechiness",
&T::speechiness, "tempo", &T::tempo, "time_signature",
&T::time_signature, "track_href", &T::track_href, "type", &T::type,
"uri", &T::uri, "valence", &T::valence);
};
template <>
struct glz::meta<Spotify::TimeInterval> {
using T = Spotify::TimeInterval;
static constexpr auto value = object(
"start", &T::start,
"duration", &T::duration,
"confidence", &T::confidence
);
template <> struct glz::meta<Spotify::TimeInterval> {
using T = Spotify::TimeInterval;
static constexpr auto value =
object("start", &T::start, "duration", &T::duration, "confidence",
&T::confidence);
};
template <>
struct glz::meta<Spotify::Section> {
using T = Spotify::Section;
static constexpr auto value = object(
"start", &T::start,
"duration", &T::duration,
"confidence", &T::confidence,
"loudness", &T::loudness,
"tempo", &T::tempo,
"tempo_confidence", &T::tempo_confidence,
"key", &T::key,
"key_confidence", &T::key_confidence,
"mode", &T::mode,
"mode_confidence", &T::mode_confidence,
"time_signature", &T::time_signature,
"time_signature_confidence", &T::time_signature_confidence
);
template <> struct glz::meta<Spotify::Section> {
using T = Spotify::Section;
static constexpr auto value =
object("start", &T::start, "duration", &T::duration, "confidence",
&T::confidence, "loudness", &T::loudness, "tempo", &T::tempo,
"tempo_confidence", &T::tempo_confidence, "key", &T::key,
"key_confidence", &T::key_confidence, "mode", &T::mode,
"mode_confidence", &T::mode_confidence, "time_signature",
&T::time_signature, "time_signature_confidence",
&T::time_signature_confidence);
};
template <>
struct glz::meta<Spotify::Segment> {
using T = Spotify::Segment;
static constexpr auto value = object(
"start", &T::start,
"duration", &T::duration,
"confidence", &T::confidence,
"loudness_start", &T::loudness_start,
"loudness_max", &T::loudness_max,
"loudness_max_time", &T::loudness_max_time,
"loudness_end", &T::loudness_end,
"pitches", &T::pitches,
"timbre", &T::timbre
);
template <> struct glz::meta<Spotify::Segment> {
using T = Spotify::Segment;
static constexpr auto value =
object("start", &T::start, "duration", &T::duration, "confidence",
&T::confidence, "loudness_start", &T::loudness_start,
"loudness_max", &T::loudness_max, "loudness_max_time",
&T::loudness_max_time, "loudness_end", &T::loudness_end,
"pitches", &T::pitches, "timbre", &T::timbre);
};
template <>
struct glz::meta<Spotify::AudioAnalysis> {
using T = Spotify::AudioAnalysis;
static constexpr auto value = object(
"bars", &T::bars,
"beats", &T::beats,
"sections", &T::sections,
"segments", &T::segments,
"tatums", &T::tatums
);
template <> struct glz::meta<Spotify::AudioAnalysis> {
using T = Spotify::AudioAnalysis;
static constexpr auto value = object(
"bars", &T::bars, "beats", &T::beats, "sections", &T::sections,
"segments", &T::segments, "tatums", &T::tatums);
};
+66 -62
View File
@@ -1,77 +1,81 @@
#pragma once
#include "Spotify/Types/Common.hpp"
namespace Spotify {
namespace Spotify
{
// ============================================================================
// User Product Type
// ============================================================================
// ============================================================================
// User Product Type
// ============================================================================
enum class Product {
Premium,
Free,
Open,
Unknown
};
enum class Product { Premium, Free, Open, Unknown };
inline auto StringToProductType(const std::string& str) -> Product {
if (str == "premium") return Product::Premium;
if (str == "free") return Product::Free;
if (str == "open") return Product::Open;
return Product::Unknown;
}
inline auto StringToProductType(const std::string& str) -> Product
{
if (str == "premium") {
return Product::Premium;
}
if (str == "free") {
return Product::Free;
}
if (str == "open") {
return Product::Open;
}
return Product::Unknown;
}
// ============================================================================
// User
// ============================================================================
// ============================================================================
// User
// ============================================================================
struct User {
std::optional<std::string> country;
std::optional<std::string> display_name;
std::optional<std::string> email;
std::optional<ExternalUrls> external_urls;
std::optional<Followers> followers;
std::string href;
std::string id;
std::optional<std::vector<Image>> images;
std::optional<std::string> product;
std::string type;
std::string uri;
auto GetId() const -> const std::string& { return id; }
auto GetDisplayName() const -> const std::optional<std::string>& { return display_name; }
auto GetEmail() const -> const std::optional<std::string>& { return email; }
auto GetUri() const -> const std::string& { return uri; }
auto GetProductType() const -> Product {
if (!product) return Product::Unknown;
return StringToProductType(*product);
}
auto IsPremium() const -> bool {
return GetProductType() == Product::Premium;
}
};
struct User {
std::optional<std::string> country;
std::optional<std::string> display_name;
std::optional<std::string> email;
std::optional<ExternalUrls> external_urls;
std::optional<Followers> followers;
std::string href;
std::string id;
std::optional<std::vector<Image>> images;
std::optional<std::string> product;
std::string type;
std::string uri;
auto GetId() const -> const std::string& { return id; }
auto GetDisplayName() const -> const std::optional<std::string>&
{
return display_name;
}
auto GetEmail() const -> const std::optional<std::string>&
{
return email;
}
auto GetUri() const -> const std::string& { return uri; }
auto GetProductType() const -> Product
{
if (!product) {
return Product::Unknown;
}
return StringToProductType(*product);
}
auto IsPremium() const -> bool
{
return GetProductType() == Product::Premium;
}
};
} // namespace Spotify
// ============================================================================
// Glaze Metadata
// ============================================================================
template <>
struct glz::meta<Spotify::User> {
using T = Spotify::User;
static constexpr auto value = object(
"country", &T::country,
"display_name", &T::display_name,
"email", &T::email,
"external_urls", &T::external_urls,
"followers", &T::followers,
"href", &T::href,
"id", &T::id,
"images", &T::images,
"product", &T::product,
"type", &T::type,
"uri", &T::uri
);
template <> struct glz::meta<Spotify::User> {
using T = Spotify::User;
static constexpr auto value = object(
"country", &T::country, "display_name", &T::display_name, "email",
&T::email, "external_urls", &T::external_urls, "followers",
&T::followers, "href", &T::href, "id", &T::id, "images", &T::images,
"product", &T::product, "type", &T::type, "uri", &T::uri);
};
+270 -248
View File
@@ -14,290 +14,312 @@
#include <glaze/glaze.hpp> // Assumed available per your reference
#include <quickjs.h>
// Project (Assuming similar structure to your Spotify bot)
#include <ts6bot/Proxy.hpp>
#include <Logger.hpp>
#include <PluginDefinitions.hpp>
#include <ts6bot/Proxy.hpp>
namespace YouTube {
namespace YouTube
{
// ============================================================================
// Data Types (Simplified for immediate usage)
// ============================================================================
// ============================================================================
// Data Types (Simplified for immediate usage)
// ============================================================================
struct Thumbnail {
std::string url;
int width;
int height;
};
struct Thumbnail {
std::string url;
int width;
int height;
};
struct Snippet {
std::string publishedAt;
std::string channelId;
std::string title;
std::string description;
std::string channelTitle;
std::map<std::string, Thumbnail> thumbnails;
std::string liveBroadcastContent;
std::string publishTime;
};
struct PlayListResourceId {
std::string kind;
std::string videoId;
};
struct PlayListSnippet{
std::string publishedAt;
std::string channelId;
std::string title;
std::string description;
std::map<std::string, Thumbnail> thumbnails;
std::string channelTitle;
std::string playlistId;
int position;
PlayListResourceId resourceId;
std::string videoOwnerChannelTitle;
std::string videoOwnerChannelId;
};
struct Snippet {
std::string publishedAt;
std::string channelId;
std::string title;
std::string description;
std::string channelTitle;
std::map<std::string, Thumbnail> thumbnails;
std::string liveBroadcastContent;
std::string publishTime;
};
struct PlayListResourceId {
std::string kind;
std::string videoId;
};
struct PlayListSnippet {
std::string publishedAt;
std::string channelId;
std::string title;
std::string description;
std::map<std::string, Thumbnail> thumbnails;
std::string channelTitle;
std::string playlistId;
int position;
PlayListResourceId resourceId;
std::string videoOwnerChannelTitle;
std::string videoOwnerChannelId;
};
struct ResourceId {
std::string kind;
std::string videoId;
std::string channelId;
std::string playlistId;
};
struct ResourceId {
std::string kind;
std::string videoId;
std::string channelId;
std::string playlistId;
};
// Search results use a wrapper for ID, Videos use a string ID
struct SearchResultId {
std::string kind;
std::string videoId;
std::string channelId;
std::string playlistId;
};
// Search results use a wrapper for ID, Videos use a string ID
struct SearchResultId {
std::string kind;
std::string videoId;
std::string channelId;
std::string playlistId;
};
struct VideoContentDetails {
std::string duration;
std::string dimension;
std::string definition;
};
struct VideoContentDetails {
std::string duration;
std::string dimension;
std::string definition;
};
struct VideoStatistics {
std::string viewCount;
std::string likeCount;
std::string commentCount;
};
struct VideoStatistics {
std::string viewCount;
std::string likeCount;
std::string commentCount;
};
// Main Resource Types
struct Video {
std::string kind;
std::string id;
Snippet snippet;
VideoContentDetails contentDetails;
VideoStatistics statistics;
};
// Main Resource Types
struct Video {
std::string kind;
std::string id;
Snippet snippet;
VideoContentDetails contentDetails;
VideoStatistics statistics;
};
struct SearchResult {
std::string kind;
std::string etag;
SearchResultId id;
Snippet snippet;
};
struct SearchResult {
std::string kind;
std::string etag;
SearchResultId id;
Snippet snippet;
};
struct SearchPlaylistResult {
std::string kind;
std::string etag;
std::string id;
PlayListSnippet snippet;
};
struct SearchPlaylistResult {
std::string kind;
std::string etag;
std::string id;
PlayListSnippet snippet;
};
// API Response Wrappers
template <typename T> struct PageResult {
std::string kind;
std::string etag;
std::string nextPageToken;
std::string prevPageToken;
std::string regionCode;
struct PageInfo {
int totalResults;
int resultsPerPage;
} pageInfo;
std::vector<T> items;
};
// ============================================================================
// InnerTube (Player) Data Types
// ============================================================================
// API Response Wrappers
template <typename T> struct PageResult {
std::string kind;
std::string etag;
std::string nextPageToken;
std::string prevPageToken;
std::string regionCode;
struct PageInfo {
int totalResults;
int resultsPerPage;
} pageInfo;
std::vector<T> items;
};
// ============================================================================
// InnerTube (Player) Data Types
// ============================================================================
struct AudioFormat {
int itag;
std::string url; // Direct URL (if unencrypted)
std::string signatureCipher; // Encrypted signature (if present, url is empty)
std::string mimeType;
int bitrate;
std::string qualityLabel;
};
struct AudioFormat {
int itag;
std::string url; // Direct URL (if unencrypted)
std::string signatureCipher; // Encrypted signature (if present, url
// is empty)
std::string mimeType;
int bitrate;
std::string qualityLabel;
};
struct StreamingData {
std::string expiresInSeconds;
std::vector<AudioFormat> formats; // Mixed video+audio
std::vector<AudioFormat>
adaptiveFormats; // Separate streams (we want audio from here)
};
struct StreamingData {
std::string expiresInSeconds;
std::vector<AudioFormat> formats; // Mixed video+audio
std::vector<AudioFormat>
adaptiveFormats; // Separate streams (we want audio from here)
};
struct PlayerResponse {
StreamingData streamingData;
// ... other fields like playabilityStatus ignored for brevity
};
// ============================================================================
// Error Handling
// ============================================================================
struct PlayerResponse {
StreamingData streamingData;
// ... other fields like playabilityStatus ignored for brevity
};
// ============================================================================
// Error Handling
// ============================================================================
struct ApiError {
int status;
std::string message;
std::string reason;
};
struct GoogleError {
struct Inner {
int code;
std::string message;
} error;
};
template <typename T> using Result = std::expected<T, ApiError>;
// ============================================================================
// Request Parameters
// ============================================================================
struct ApiError {
int status;
std::string message;
std::string reason;
};
struct GoogleError {
struct Inner {
int code;
std::string message;
} error;
};
template <typename T> using Result = std::expected<T, ApiError>;
// ============================================================================
// Request Parameters
// ============================================================================
struct SearchParams {
std::string q;
std::vector<std::string> type = {"video"}; // video, channel, playlist
std::string part = "snippet";
int maxResults = 5;
std::string order = "relevance";
std::string pageToken = "";
std::string videoDuration = "any"; // any, long, medium, short
bool rawQuery = false; // Set to true to preserve -, |, etc. in query
};
struct ShortenResponse {
std::string shortUrl;
};
// ============================================================================
// Main YouTube Client
// ============================================================================
struct SearchParams {
std::string q;
std::vector<std::string> type = {
"video"}; // video, channel, playlist
std::string part = "snippet";
int maxResults = 5;
std::string order = "relevance";
std::string pageToken = "";
std::string videoDuration = "any"; // any, long, medium, short
bool rawQuery =
false; // Set to true to preserve -, |, etc. in query
};
struct ShortenResponse {
std::string shortUrl;
};
// ============================================================================
// Main YouTube Client
// ============================================================================
struct CurlDeleter {
void operator()(CURL *ptr) const {
if (ptr)
curl_easy_cleanup(ptr);
}
};
struct CurlDeleter {
void operator()(CURL *ptr) const
{
if (ptr) {
curl_easy_cleanup(ptr);
}
}
};
enum class HttpMethod { GET, POST, PUT, DELETE };
enum class HttpMethod { GET, POST, PUT, DELETE };
class Client {
public:
// YouTube typically uses API Keys for public data, OAuth for user data.
// Pass "" as accessToken if only using API Key.
Client(std::string apiKey, std::string accessToken = "");
~Client();
auto GetBestStreams(const std::string &videoId)
-> Result<::definitions::Streams>; // Configuration
void SetVerbose(bool verbose) { m_Verbose = verbose; }
void SetProxy(ProxyConfig config) { m_Proxy = std::move(config); }
void SetAccessToken(std::string token) { m_AccessToken = std::move(token); }
void SetApiKey(std::string key) { m_ApiKey = std::move(key); }
class Client
{
public:
auto ShortUrl(const std::string& url) const -> Result<std::string>;
// YouTube typically uses API Keys for public data, OAuth for user
// data. Pass "" as accessToken if only using API Key.
Client(std::string apiKey, std::string accessToken = "");
~Client();
auto GetBestStreams(const std::string &videoId)
-> Result<::definitions::Streams>; // Configuration
void SetVerbose(bool verbose) { m_Verbose = verbose; }
void SetProxy(ProxyConfig config) { m_Proxy = std::move(config); }
void SetAccessToken(std::string token)
{
m_AccessToken = std::move(token);
}
void SetApiKey(std::string key) { m_ApiKey = std::move(key); }
// ========================================================================
// Search API
// ========================================================================
auto ShortUrl(const std::string &url) const -> Result<std::string>;
// https://developers.google.com/youtube/v3/docs/search/list
auto Search(const SearchParams &params) -> Result<PageResult<SearchResult>>;
// ========================================================================
// Search API
// ========================================================================
// ========================================================================
// Videos API
// ========================================================================
// https://developers.google.com/youtube/v3/docs/search/list
auto Search(const SearchParams &params)
-> Result<PageResult<SearchResult>>;
// https://developers.google.com/youtube/v3/docs/videos/list
auto GetVideo(const std::string &id,
const std::string &part = "snippet,contentDetails,statistics")
-> Result<Video>;
// ========================================================================
// Videos API
// ========================================================================
auto GetVideos(const std::vector<std::string> &ids,
const std::string &part = "snippet,contentDetails,statistics")
-> Result<std::vector<Video>>;
// https://developers.google.com/youtube/v3/docs/videos/list
auto GetVideo(
const std::string &id,
const std::string &part = "snippet,contentDetails,statistics")
-> Result<Video>;
// ========================================================================
// Channels API
// ========================================================================
auto GetVideos(
const std::vector<std::string> &ids,
const std::string &part = "snippet,contentDetails,statistics")
-> Result<std::vector<Video>>;
// https://developers.google.com/youtube/v3/docs/channels/list
auto GetChannel(const std::string &id,
const std::string &part = "snippet,statistics")
-> Result<std::string>; // Returns raw JSON for brevity in this example
// ========================================================================
// Channels API
// ========================================================================
// ========================================================================
// Playlists API
// ========================================================================
// https://developers.google.com/youtube/v3/docs/channels/list
auto GetChannel(const std::string &id,
const std::string &part = "snippet,statistics")
-> Result<std::string>; // Returns raw JSON for brevity in this
// example
// https://developers.google.com/youtube/v3/docs/playlistItems/list
auto GetPlaylistItems(const std::string &playlistId,
const std::string &pageToken = "")
-> Result<PageResult<SearchPlaylistResult>>; // Reusing SearchResult as structure
// is similar enough for snippet
auto GetPlaylistVideos(const std::string& playlistId) -> Result<std::vector<Video>>;
// ========================================================================
// Player API (The "Extraction" Logic)
// ========================================================================
// ========================================================================
// Playlists API
// ========================================================================
// Returns a raw https://googlevideo.com/... URL for the audio stream.
// Returns error if the video is region locked or requires signature
// deciphering.
auto GetAudioStreamUrl(const std::string &videoId) -> Result<std::string>;
// https://developers.google.com/youtube/v3/docs/playlistItems/list
auto GetPlaylistItems(const std::string &playlistId,
const std::string &pageToken = "")
-> Result<PageResult<
SearchPlaylistResult>>; // Reusing SearchResult as structure
// is similar enough for snippet
auto GetPlaylistVideos(const std::string &playlistId)
-> Result<std::vector<Video>>;
// ========================================================================
// Player API (The "Extraction" Logic)
// ========================================================================
auto ExtractVideoId(std::string_view url) const -> std::optional<std::string>;
// Returns a raw https://googlevideo.com/... URL for the audio
// stream. Returns error if the video is region locked or requires
// signature deciphering.
auto GetAudioStreamUrl(const std::string &videoId)
-> Result<std::string>;
private:
std::string m_ApiKey;
std::string m_AccessToken;
ProxyConfig m_Proxy;
bool m_Verbose = false;
const std::string m_BaseUrl = "https://www.googleapis.com/youtube/v3";
JSRuntime *m_rt;
JSContext *m_ctx;
std::string m_preprocessedPlayer;
auto ExtractVideoId(std::string_view url) const
-> std::optional<std::string>;
// Helper methods for the solver logic
void InitSolver();
void SetPlayerJs(const std::string &js);
std::string SolveChallenge(const std::string &challenge,
const std::string &type);
auto PerformRequest(
const std::string &purl, const std::string &endpoint,
const cpr::Parameters &params = {},
const cpr::Header &headers =
{{"Content-Type", "application/json"},
{"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}},
HttpMethod method = HttpMethod::GET, const std::string &body = "")
-> Result<std::string>;
private:
auto PerformRequest(
const std::string &endpoint, const cpr::Parameters &params = {},
const cpr::Header &headers =
{{"Content-Type", "application/json"},
{"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}},
HttpMethod method = HttpMethod::GET, const std::string &body = "")
-> Result<std::string>;
// Helper specifically for the internal YouTube API (different Base URL)
auto PerformInternalRequest(const std::string &endpoint,
const std::string &jsonBody)
-> Result<std::string>;
static auto WriteCallback(void *contents, size_t size, size_t nmemb,
std::string *out) -> size_t;
auto UrlEncode(std::string_view value) const -> std::string;
auto UrlEncodePreservingOperators(std::string_view query) const
-> std::string;
};
std::string m_ApiKey;
std::string m_AccessToken;
ProxyConfig m_Proxy;
bool m_Verbose = false;
const std::string m_BaseUrl =
"https://www.googleapis.com/youtube/v3";
JSRuntime *m_rt;
JSContext *m_ctx;
std::string m_preprocessedPlayer;
// Helper methods for the solver logic
void InitSolver();
void SetPlayerJs(const std::string &js);
std::string SolveChallenge(const std::string &challenge,
const std::string &type);
auto PerformRequest(
const std::string &purl, const std::string &endpoint,
const cpr::Parameters &params = {},
const cpr::Header &headers =
{{"Content-Type", "application/json"},
{"User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36"}},
HttpMethod method = HttpMethod::GET,
const std::string &body = "") -> Result<std::string>;
auto PerformRequest(
const std::string &endpoint, const cpr::Parameters &params = {},
const cpr::Header &headers =
{{"Content-Type", "application/json"},
{"User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36"}},
HttpMethod method = HttpMethod::GET,
const std::string &body = "") -> Result<std::string>;
// Helper specifically for the internal YouTube API (different Base
// URL)
auto PerformInternalRequest(const std::string &endpoint,
const std::string &jsonBody)
-> Result<std::string>;
static auto WriteCallback(void *contents, size_t size, size_t nmemb,
std::string *out) -> size_t;
auto UrlEncode(std::string_view value) const -> std::string;
auto UrlEncodePreservingOperators(std::string_view query) const
-> std::string;
};
} // namespace YouTube
+6 -5
View File
@@ -1,10 +1,11 @@
#pragma once
#include <string_view>
namespace YouTube::Internal {
namespace YouTube::Internal
{
// Replace the comment with the actual content of yt.solver.lib.js
static constexpr std::string_view SOLVER_LIB_JS = R"js(
// Replace the comment with the actual content of yt.solver.lib.js
static constexpr std::string_view SOLVER_LIB_JS = R"js(
/*!
* SPDX-License-Identifier: Unlicense
* This file was automatically generated by https://github.com/yt-dlp/ejs
@@ -13230,8 +13231,8 @@ var lib = (function (exports) {
})({});
)js";
// Replace the comment with the actual content of yt.solver.core.js
static constexpr std::string_view SOLVER_CORE_JS = R"js(
// Replace the comment with the actual content of yt.solver.core.js
static constexpr std::string_view SOLVER_CORE_JS = R"js(
var jsc = (function (meriyah, astring) {
'use strict';
// ... (Paste full content of yt.solver.core.js here) ...
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+35 -32
View File
@@ -17,37 +17,40 @@ extern "C" {
#include <libswresample/swresample.h>
}
enum class DecodeStatus { Idle, Processing, Completed, Failed, Cancelled };
class AudioDecoder {
public:
struct AudioData {
std::vector<short> buffer;
int samples = 0;
int channels = 0;
int sampleRate = 0;
};
std::deque<std::vector<short>> m_chunkQueue;
std::mutex m_queueMtx;
std::condition_variable m_cv;
std::atomic<bool> m_isDecodingFinished{false};
AudioDecoder();
~AudioDecoder();
void StartDecode(const std::string &url, int targetSampleRate);
void Cancel() { m_cancelRequested = true; }
DecodeStatus GetStatus() const { return m_status; }
AudioData GetResult() { return std::move(m_result); }
bool GetNextChunk(std::vector<short> &outChunk, bool blocking = false);
bool IsFinished() const { return m_finished.load(); }
class AudioDecoder
{
public:
private:
void Cleanup();
void InternalDecode(std::string url, int targetSampleRate);
std::atomic<DecodeStatus> m_status{DecodeStatus::Idle};
std::atomic<bool> m_cancelRequested{false};
std::jthread m_thread;
std::mutex m_logMtx;
AudioData m_result;
std::atomic<bool> m_finished{false};
AVFormatContext *m_formatCtx = nullptr;
AVCodecContext *m_codecCtx = nullptr;
SwrContext *m_swrCtx = nullptr;
struct AudioData {
std::vector<short> buffer;
int samples = 0;
int channels = 0;
int sampleRate = 0;
};
std::deque<std::vector<short>> m_chunkQueue;
std::mutex m_queueMtx;
std::condition_variable m_cv;
std::atomic<bool> m_isDecodingFinished{false};
AudioDecoder();
~AudioDecoder();
void StartDecode(const std::string &url, int targetSampleRate);
void Cancel() { m_cancelRequested = true; }
DecodeStatus GetStatus() const { return m_status; }
AudioData GetResult() { return std::move(m_result); }
bool GetNextChunk(std::vector<short> &outChunk, bool blocking = false);
bool IsFinished() const { return m_finished.load(); }
private:
void Cleanup();
void InternalDecode(std::string url, int targetSampleRate);
std::atomic<DecodeStatus> m_status{DecodeStatus::Idle};
std::atomic<bool> m_cancelRequested{false};
std::jthread m_thread;
std::mutex m_logMtx;
AudioData m_result;
std::atomic<bool> m_finished{false};
AVFormatContext *m_formatCtx = nullptr;
AVCodecContext *m_codecCtx = nullptr;
SwrContext *m_swrCtx = nullptr;
};
+88 -90
View File
@@ -8,121 +8,119 @@
#include "Singleton.hpp"
namespace ts6bot {
namespace ts6bot
{
enum class LogLevel {
Trace,
Debug,
Info,
Warning,
Error,
Critical,
None
};
enum class LogLevel { Trace, Debug, Info, Warning, Error, Critical, None };
struct ServerQueryConfig {
std::string host{"127.0.0.1"};
uint16_t port{
10022}; // ServerQuery SSH default :contentReference[oaicite:6]{index=6}
std::string username{"serveradmin"};
std::string password{};
int virtual_server_id{1};
std::string nickname{"ts6bot"};
};
struct ServerQueryConfig {
std::string host{"127.0.0.1"};
uint16_t port{10022}; // ServerQuery SSH default
// :contentReference[oaicite:6]{index=6}
std::string username{"serveradmin"};
std::string password{};
int virtual_server_id{1};
std::string nickname{"ts6bot"};
};
struct AfkConfig {
bool enabled{true};
int idle_seconds{600};
std::uint64_t afk_channel_id{0};
int poll_interval_ms{5000};
};
struct AfkConfig {
bool enabled{true};
int idle_seconds{600};
std::uint64_t afk_channel_id{0};
int poll_interval_ms{5000};
};
struct MusicConfig {
bool enabled{true};
std::string youtubeApiToken;
};
struct MusicConfig {
bool enabled{true};
std::string youtubeApiToken;
};
struct ProxyConfiguration : public ProxyConfig {
bool enabled{false};
};
struct ProxyConfiguration : public ProxyConfig {
bool enabled{false};
};
struct Config {
std::string nickname;
std::string host;
std::string channel;
std::string password;
LogLevel loggingLevel;
AfkConfig afk{};
MusicConfig music{};
ProxyConfiguration proxy{};
};
struct Config {
std::string nickname;
std::string host;
std::string channel;
std::string password;
LogLevel loggingLevel;
AfkConfig afk{};
MusicConfig music{};
ProxyConfiguration proxy{};
};
class Configuration : public Singleton<Configuration> {
friend class Singleton<Configuration>;
public:
const Config getConfig() const noexcept { return m_config; }
class Configuration : public Singleton<Configuration>
{
friend class Singleton<Configuration>;
Configuration(std::string path) {
auto config = Config();
std::string buffer;
auto ec = glz::read_file_json(config, path, buffer);
if (ec) {
std::string descriptive_error = glz::format_error(ec, buffer);
std::cerr << "Not found configuration in " << path << " using default"
<< std::endl;
std::cerr << descriptive_error << std::endl;
std::cerr << ec.ec << std::endl;
m_config = Config();
}
this->m_config = config;
}
public:
Config m_config{};
};
const Config getConfig() const noexcept { return m_config; }
// Glaze meta (explicit, stable)
Configuration(std::string path)
{
auto config = Config();
std::string buffer;
auto ec = glz::read_file_json(config, path, buffer);
if (ec) {
std::string descriptive_error =
glz::format_error(ec, buffer);
std::cerr << "Not found configuration in " << path
<< " using default" << std::endl;
std::cerr << descriptive_error << std::endl;
std::cerr << ec.ec << std::endl;
m_config = Config();
}
this->m_config = config;
}
Config m_config{};
};
// Glaze meta (explicit, stable)
} // namespace ts6bot
template <> struct glz::meta<ProxyType> {
using enum ProxyType;
static constexpr auto value = enumerate(HTTP, SOCKS5, SOCKS5_HOSTNAME);
using enum ProxyType;
static constexpr auto value = enumerate(HTTP, SOCKS5, SOCKS5_HOSTNAME);
};
template <> struct glz::meta<ts6bot::LogLevel> {
using enum ts6bot::LogLevel;
static constexpr auto value =
enumerate(Critical, Error, Warning, Info, Trace);
using enum ts6bot::LogLevel;
static constexpr auto value =
enumerate(Critical, Error, Warning, Info, Trace);
};
template <> struct glz::meta<ts6bot::ServerQueryConfig> {
using T = ts6bot::ServerQueryConfig;
static constexpr auto value =
object("host", &T::host, "port", &T::port, "username", &T::username,
"password", &T::password, "virtual_server_id",
&T::virtual_server_id, "nickname", &T::nickname);
using T = ts6bot::ServerQueryConfig;
static constexpr auto value =
object("host", &T::host, "port", &T::port, "username", &T::username,
"password", &T::password, "virtual_server_id",
&T::virtual_server_id, "nickname", &T::nickname);
};
template <> struct glz::meta<ts6bot::AfkConfig> {
using T = ts6bot::AfkConfig;
static constexpr auto value =
object("enabled", &T::enabled, "idle_seconds", &T::idle_seconds,
"afk_channel_id", &T::afk_channel_id, "poll_interval_ms",
&T::poll_interval_ms);
using T = ts6bot::AfkConfig;
static constexpr auto value =
object("enabled", &T::enabled, "idle_seconds", &T::idle_seconds,
"afk_channel_id", &T::afk_channel_id, "poll_interval_ms",
&T::poll_interval_ms);
};
template <> struct glz::meta<ts6bot::MusicConfig> {
using T = ts6bot::MusicConfig;
static constexpr auto value =
object("enabled", &T::enabled, "youtubeApiToken", &T::youtubeApiToken);
using T = ts6bot::MusicConfig;
static constexpr auto value = object(
"enabled", &T::enabled, "youtubeApiToken", &T::youtubeApiToken);
};
template <> struct glz::meta<ts6bot::ProxyConfiguration> {
using T = ts6bot::ProxyConfiguration;
static constexpr auto value =
object("url", &T::url, "username", &T::username, "password", &T::password,
"type", &T::type, "enabled", &T::enabled);
using T = ts6bot::ProxyConfiguration;
static constexpr auto value =
object("url", &T::url, "username", &T::username, "password",
&T::password, "type", &T::type, "enabled", &T::enabled);
};
template <> struct glz::meta<ts6bot::Config> {
using T = ts6bot::Config;
static constexpr auto value =
object("nickname", &T::nickname, "host", &T::host, "channel", &T::channel,
"password", &T::password, "loggingLevel", &T::loggingLevel, "afk",
&T::afk, "music", &T::music, "proxy", &T::proxy);
using T = ts6bot::Config;
static constexpr auto value = object(
"nickname", &T::nickname, "host", &T::host, "channel", &T::channel,
"password", &T::password, "loggingLevel", &T::loggingLevel, "afk",
&T::afk, "music", &T::music, "proxy", &T::proxy);
};
+10 -9
View File
@@ -6,18 +6,19 @@
#include <string>
#include <vector>
namespace ts6bot::crypto {
namespace ts6bot::crypto
{
// RFC 7636: length 43..128, chars [A-Z a-z 0-9 - . _ ~]
std::string GenerateCodeVerifier(std::size_t length = 64);
// RFC 7636: length 43..128, chars [A-Z a-z 0-9 - . _ ~]
std::string GenerateCodeVerifier(std::size_t length = 64);
// Random state value (base64url, no padding).
std::string GenerateState(std::size_t bytes = 16);
// Random state value (base64url, no padding).
std::string GenerateState(std::size_t bytes = 16);
std::vector<std::uint8_t> Sha256(std::span<const std::uint8_t> data);
std::vector<std::uint8_t> Sha256(std::span<const char> data);
std::vector<std::uint8_t> Sha256(std::span<const std::uint8_t> data);
std::vector<std::uint8_t> Sha256(std::span<const char> data);
// Base64url encode without padding.
std::string Base64UrlEncode(std::span<const std::uint8_t> data);
// Base64url encode without padding.
std::string Base64UrlEncode(std::span<const std::uint8_t> data);
} // namespace ts6bot::crypto
+91 -71
View File
@@ -16,85 +16,105 @@
#include <ts3_functions.h>
#include <ts6bot/AudioDecoder.hpp>
#include <vector>
class MusicManager {
public:
explicit MusicManager(std::shared_ptr<TS3Functions> functions, std::uint64_t serverConnectionHandlerID = 0);
~MusicManager();
class MusicManager
{
public:
struct Music {
std::string name;
std::string shortUrl;
std::string length;
std::string videoId;
std::string requestedBy;
YouTube::Result<definitions::Streams> streams;
};
explicit MusicManager(std::shared_ptr<TS3Functions> functions,
std::uint64_t serverConnectionHandlerID = 0);
~MusicManager();
// Playback Control
void stop();
void skip();
void forceSkip();
void setStopAfterCurrent(bool val) { m_stopAfterCurrent = val; }
bool isIdle() const { return m_isIdle; }
std::uint64_t getServerConnectionHandlerID() const
{return m_serverConnectionHandlerID; }
void setServerConnectionHandlerID(std::uint64_t id) { m_serverConnectionHandlerID = id; }
// Subscription (Whisper) Management
void subscribe(anyID id);
void moveSubscriberToOffline(anyID id);
void moveSubscriberToOnline(anyID id);
void addSubscriberToOnline(anyID id);
void addSubscriberToOffline(anyID id);
void unSubscribe(anyID id);
std::set<uint64_t> getOnlineSubscribers() const;
std::set<uint64_t> getOfflineSubscribers() const;
// Queue Management
std::vector<Music> getQueue() const;
std::optional<Music> getCurrent() const { return m_current; }
void removeFromQueue(std::size_t index);
void removeFromQueue(const std::string &name);
void addToQueueDirect(const std::string& vid, const std::string& title, const std::string& shortUrl, const std::string& length, const std::string& req, std::optional<definitions::Streams> streams);
void checkQueueAndPlay();
struct Music {
std::string name;
std::string shortUrl;
std::string length;
std::string videoId;
std::string requestedBy;
YouTube::Result<definitions::Streams> streams;
};
// Youtube / Search
std::vector<definitions::SearchResultItem> search(std::string name, int maxResults = 5) const;
void playUrl(std::string url, const std::string &requester = "");
void playPlaylist(const std::string& playlistId, const std::string& requester);
// Helper to extract playlist ID from URL
std::optional<std::string> extractPlaylistId(std::string_view url);
// Selection Logic
// Stores the results for a specific user to select later
void storePendingSearch(anyID clientId,
const std::vector<definitions::SearchResultItem> &results);
bool selectSearchResult(anyID clientId, int index, const std::string& requesterName);
// Playback Control
void stop();
void skip();
void forceSkip();
void setStopAfterCurrent(bool val) { m_stopAfterCurrent = val; }
bool isIdle() const { return m_isIdle; }
std::uint64_t getServerConnectionHandlerID() const
{
return m_serverConnectionHandlerID;
}
void setServerConnectionHandlerID(std::uint64_t id)
{
m_serverConnectionHandlerID = id;
}
// Subscription (Whisper) Management
bool subscribe(anyID id);
void moveSubscriberToOffline(anyID id);
void moveSubscriberToOnline(anyID id);
bool addSubscriberToOnline(anyID id);
bool addSubscriberToOffline(anyID id);
bool unSubscribe(anyID id);
std::set<uint64_t> getOnlineSubscribers() const;
std::set<uint64_t> getOfflineSubscribers() const;
// Queue Management
std::vector<Music> getQueue() const;
std::optional<Music> getCurrent() const { return m_current; }
void removeFromQueue(std::size_t index);
void removeFromQueue(const std::string& name);
void addToQueueDirect(const std::string& vid,
const std::string& title,
const std::string& shortUrl,
const std::string& length,
const std::string& req,
std::optional<definitions::Streams>
streams);
void checkQueueAndPlay();
private:
void loop(std::stop_token st);
static std::string formatDuration(const std::string &isoDuration);
void updateWhisperList();
// Youtube / Search
std::vector<definitions::SearchResultItem>
search(std::string name, int maxResults = 5) const;
bool playUrl(std::string url, const std::string& requester = "");
bool playPlaylist(const std::string& playlistId,
const std::string& requester);
// Helper to extract playlist ID from URL
std::optional<std::string> extractPlaylistId(std::string_view url);
// Selection Logic
// Stores the results for a specific user to select later
void storePendingSearch(
anyID clientId,
const std::vector<definitions::SearchResultItem>& results);
bool selectSearchResult(anyID clientId,
int index,
const std::string& requesterName);
std::shared_ptr<TS3Functions> m_functions{nullptr};
std::unique_ptr<AudioDecoder> m_microphone{nullptr};
std::unique_ptr<YouTube::Client> m_client{nullptr};
private:
void loop(std::stop_token st);
static std::string formatDuration(const std::string& isoDuration);
void updateWhisperList();
std::atomic<bool> m_stopAfterCurrent{false};
std::atomic<bool> m_isIdle{true};
std::shared_ptr<TS3Functions> m_functions{nullptr};
std::unique_ptr<AudioDecoder> m_microphone{nullptr};
std::unique_ptr<YouTube::Client> m_client{nullptr};
std::deque<Music> m_queue{};
mutable std::mutex m_queueMtx;
std::condition_variable m_cv;
std::atomic<bool> m_stopAfterCurrent{false};
std::atomic<bool> m_isIdle{true};
std::set<anyID> m_onlineSubscribers;
std::set<anyID> m_offlineSubscribers;
// Playback Control
std::atomic_bool m_skipRequested{false};
std::deque<Music> m_queue{};
mutable std::mutex m_queueMtx;
std::condition_variable m_cv;
std::atomic<float> m_volume{0.5f}; // Default 50%
std::uint64_t m_serverConnectionHandlerID = 0;
std::optional<Music> m_current;
std::mutex m_subMtx;
std::map<anyID, std::vector<definitions::SearchResultItem>> m_pendingSearches;
std::mutex m_pendingMtx;
std::jthread m_worker;
std::set<anyID> m_onlineSubscribers;
std::set<anyID> m_offlineSubscribers;
// Playback Control
std::atomic_bool m_skipRequested{false};
std::atomic<float> m_volume{0.5f}; // Default 50%
std::uint64_t m_serverConnectionHandlerID = 0;
std::optional<Music> m_current;
std::mutex m_subMtx;
std::map<anyID, std::vector<definitions::SearchResultItem>>
m_pendingSearches;
std::mutex m_pendingMtx;
std::jthread m_worker;
};
+8 -8
View File
@@ -2,13 +2,13 @@
#include <string>
enum class ProxyType {
HTTP,
SOCKS5,
SOCKS5_HOSTNAME // Use this to let the proxy resolve the DNS
HTTP,
SOCKS5,
SOCKS5_HOSTNAME // Use this to let the proxy resolve the DNS
};
struct ProxyConfig {
std::string url;
ProxyType type = ProxyType::SOCKS5_HOSTNAME;
std::string username = "";
std::string password = "";
};
std::string url;
ProxyType type = ProxyType::SOCKS5_HOSTNAME;
std::string username = "";
std::string password = "";
};
+13 -12
View File
@@ -3,20 +3,21 @@
#include <cstdint>
#include <string>
namespace ts6bot::url {
namespace ts6bot::url
{
// Percent-encode a string for use as a query parameter value.
std::string EncodeComponent(const std::string& s);
// Percent-encode a string for use as a query parameter value.
std::string EncodeComponent(const std::string& s);
struct HttpUrl {
std::string host;
uint16_t port{};
std::string path; // begins with '/'
};
struct HttpUrl {
std::string host;
uint16_t port{};
std::string path; // begins with '/'
};
// Minimal parser for redirect URIs.
// Supports: http://<host>:<port>/<path>
// Throws std::runtime_error on invalid input.
HttpUrl ParseHttpUrl(const std::string& httpUrl);
// Minimal parser for redirect URIs.
// Supports: http://<host>:<port>/<path>
// Throws std::runtime_error on invalid input.
HttpUrl ParseHttpUrl(const std::string& httpUrl);
} // namespace ts6bot::url
+378 -341
View File
@@ -8,353 +8,390 @@
// --- STATE STRUCTURES (Serialized by Glaze) ---
// --- THE INTERFACE ---
class IEchoionPlugin {
public:
virtual ~IEchoionPlugin() = default;
class IEchoionPlugin
{
public:
// Lifecycle
virtual void Initialize(bool start = true) = 0;
virtual void Shutdown() = 0;
virtual ~IEchoionPlugin() = default;
// Hot Reload State
virtual std::string SerializeState() = 0;
virtual void DeserializeState(const std::string &jsonState) = 0;
// Lifecycle
virtual void Initialize(bool start = true) = 0;
virtual void Shutdown() = 0;
// Graceful Update
virtual void RequestGracefulStop() = 0; // "Finish current track then stop"
virtual bool IsStopped() = 0; // "I am idle, threads joined, safe to unload"
// Hot Reload State
virtual std::string SerializeState() = 0;
virtual void DeserializeState(const std::string &jsonState) = 0;
// Events
virtual void onConnectStatusChangeEvent(uint64 serverConnectionHandlerID,
int newStatus,
unsigned int errorNumber) = 0;
virtual void onNewChannelEvent(uint64 serverConnectionHandlerID,
uint64 channelID, uint64 channelParentID) = 0;
virtual void
onNewChannelCreatedEvent(uint64 serverConnectionHandlerID, uint64 channelID,
uint64 channelParentID, anyID invokerID,
const char *invokerName,
const char *invokerUniqueIdentifier) = 0;
virtual void onDelChannelEvent(uint64 serverConnectionHandlerID,
uint64 channelID, anyID invokerID,
const char *invokerName,
const char *invokerUniqueIdentifier) = 0;
virtual void onChannelMoveEvent(uint64 serverConnectionHandlerID,
uint64 channelID, uint64 newChannelParentID,
anyID invokerID, const char *invokerName,
const char *invokerUniqueIdentifier) = 0;
virtual void onUpdateChannelEvent(uint64 serverConnectionHandlerID,
uint64 channelID) = 0;
virtual void
onUpdateChannelEditedEvent(uint64 serverConnectionHandlerID, uint64 channelID,
anyID invokerID, const char *invokerName,
const char *invokerUniqueIdentifier) = 0;
virtual void onUpdateClientEvent(uint64 serverConnectionHandlerID,
anyID clientID, anyID invokerID,
const char *invokerName,
const char *invokerUniqueIdentifier) = 0;
virtual void onClientMoveEvent(uint64 serverConnectionHandlerID,
anyID clientID, uint64 oldChannelID,
uint64 newChannelID, int visibility,
const char *moveMessage) = 0;
virtual void onClientMoveSubscriptionEvent(uint64 serverConnectionHandlerID,
anyID clientID,
uint64 oldChannelID,
uint64 newChannelID,
int visibility) = 0;
virtual void onClientMoveTimeoutEvent(uint64 serverConnectionHandlerID,
anyID clientID, uint64 oldChannelID,
uint64 newChannelID, int visibility,
const char *timeoutMessage) = 0;
virtual void onClientMoveMovedEvent(uint64 serverConnectionHandlerID,
anyID clientID, uint64 oldChannelID,
uint64 newChannelID, int visibility,
anyID moverID, const char *moverName,
const char *moverUniqueIdentifier,
const char *moveMessage) = 0;
virtual void onClientKickFromChannelEvent(uint64 serverConnectionHandlerID,
anyID clientID, uint64 oldChannelID,
uint64 newChannelID, int visibility,
anyID kickerID,
const char *kickerName,
const char *kickerUniqueIdentifier,
const char *kickMessage) = 0;
virtual void onClientKickFromServerEvent(uint64 serverConnectionHandlerID,
anyID clientID, uint64 oldChannelID,
uint64 newChannelID, int visibility,
anyID kickerID,
const char *kickerName,
const char *kickerUniqueIdentifier,
const char *kickMessage) = 0;
virtual void onClientIDsEvent(uint64 serverConnectionHandlerID,
const char *uniqueClientIdentifier,
anyID clientID, const char *clientName) = 0;
virtual void onClientIDsFinishedEvent(uint64 serverConnectionHandlerID) = 0;
virtual void onServerEditedEvent(uint64 serverConnectionHandlerID,
anyID editerID, const char *editerName,
const char *editerUniqueIdentifier) = 0;
virtual void onServerUpdatedEvent(uint64 serverConnectionHandlerID) = 0;
virtual int onServerErrorEvent(uint64 serverConnectionHandlerID,
const char *errorMessage, unsigned int error,
const char *returnCode,
const char *extraMessage) = 0;
virtual void onServerStopEvent(uint64 serverConnectionHandlerID,
const char *shutdownMessage) = 0;
virtual int onTextMessageEvent(uint64 serverConnectionHandlerID,
anyID targetMode, anyID toID, anyID fromID,
const char *fromName,
const char *fromUniqueIdentifier,
const char *message, int ffIgnored) = 0;
virtual void onTalkStatusChangeEvent(uint64 serverConnectionHandlerID,
int status, int isReceivedWhisper,
anyID clientID) = 0;
virtual void onConnectionInfoEvent(uint64 serverConnectionHandlerID,
anyID clientID) = 0;
virtual void
onServerConnectionInfoEvent(uint64 serverConnectionHandlerID) = 0;
virtual void onChannelSubscribeEvent(uint64 serverConnectionHandlerID,
uint64 channelID) = 0;
virtual void
onChannelSubscribeFinishedEvent(uint64 serverConnectionHandlerID) = 0;
virtual void onChannelUnsubscribeEvent(uint64 serverConnectionHandlerID,
uint64 channelID) = 0;
virtual void
onChannelUnsubscribeFinishedEvent(uint64 serverConnectionHandlerID) = 0;
virtual void onChannelDescriptionUpdateEvent(uint64 serverConnectionHandlerID,
uint64 channelID) = 0;
virtual void onChannelPasswordChangedEvent(uint64 serverConnectionHandlerID,
uint64 channelID) = 0;
virtual void
onPlaybackShutdownCompleteEvent(uint64 serverConnectionHandlerID) = 0;
virtual void onSoundDeviceListChangedEvent(const char *modeID,
int playOrCap) = 0;
virtual void onEditPlaybackVoiceDataEvent(uint64 serverConnectionHandlerID,
anyID clientID, short *samples,
int sampleCount, int channels) = 0;
virtual void onEditPostProcessVoiceDataEvent(
uint64 serverConnectionHandlerID, anyID clientID, short *samples,
int sampleCount, int channels, const unsigned int *channelSpeakerArray,
unsigned int *channelFillMask) = 0;
virtual void onEditMixedPlaybackVoiceDataEvent(
uint64 serverConnectionHandlerID, short *samples, int sampleCount,
int channels, const unsigned int *channelSpeakerArray,
unsigned int *channelFillMask) = 0;
virtual void onEditCapturedVoiceDataEvent(uint64 serverConnectionHandlerID,
short *samples, int sampleCount,
int channels, int *edited) = 0;
virtual void
onCustom3dRolloffCalculationClientEvent(uint64 serverConnectionHandlerID,
anyID clientID, float distance,
float *volume) = 0;
virtual void
onCustom3dRolloffCalculationWaveEvent(uint64 serverConnectionHandlerID,
uint64 waveHandle, float distance,
float *volume) = 0;
virtual void onUserLoggingMessageEvent(const char *logMessage, int logLevel,
const char *logChannel, uint64 logID,
const char *logTime,
const char *completeLogString) = 0;
// Graceful Update
virtual void
RequestGracefulStop() = 0; // "Finish current track then stop"
virtual bool
IsStopped() = 0; // "I am idle, threads joined, safe to unload"
/* Clientlib rare */
virtual 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) = 0;
virtual int onClientPokeEvent(uint64 serverConnectionHandlerID,
anyID fromClientID, const char *pokerName,
const char *pokerUniqueIdentity,
const char *message, int ffIgnored) = 0;
virtual void onClientSelfVariableUpdateEvent(uint64 serverConnectionHandlerID,
int flag, const char *oldValue,
const char *newValue) = 0;
virtual void onFileListEvent(uint64 serverConnectionHandlerID,
uint64 channelID, const char *path,
const char *name, uint64 size, uint64 datetime,
int type, uint64 incompletesize,
const char *returnCode) = 0;
virtual void onFileListFinishedEvent(uint64 serverConnectionHandlerID,
uint64 channelID, const char *path) = 0;
virtual void onFileInfoEvent(uint64 serverConnectionHandlerID,
uint64 channelID, const char *name, uint64 size,
uint64 datetime) = 0;
virtual void onServerGroupListEvent(uint64 serverConnectionHandlerID,
uint64 serverGroupID, const char *name,
int type, int iconID, int saveDB) = 0;
virtual void
onServerGroupListFinishedEvent(uint64 serverConnectionHandlerID) = 0;
virtual void onServerGroupByClientIDEvent(uint64 serverConnectionHandlerID,
const char *name,
uint64 serverGroupList,
uint64 clientDatabaseID) = 0;
virtual void onServerGroupPermListEvent(uint64 serverConnectionHandlerID,
uint64 serverGroupID,
unsigned int permissionID,
int permissionValue,
int permissionNegated,
int permissionSkip) = 0;
virtual void
onServerGroupPermListFinishedEvent(uint64 serverConnectionHandlerID,
uint64 serverGroupID) = 0;
virtual void onServerGroupClientListEvent(uint64 serverConnectionHandlerID,
uint64 serverGroupID,
uint64 clientDatabaseID,
const char *clientNameIdentifier,
const char *clientUniqueID) = 0;
virtual void onChannelGroupListEvent(uint64 serverConnectionHandlerID,
uint64 channelGroupID, const char *name,
int type, int iconID, int saveDB) = 0;
virtual void
onChannelGroupListFinishedEvent(uint64 serverConnectionHandlerID) = 0;
virtual void onChannelGroupPermListEvent(uint64 serverConnectionHandlerID,
uint64 channelGroupID,
unsigned int permissionID,
int permissionValue,
int permissionNegated,
int permissionSkip) = 0;
virtual void
onChannelGroupPermListFinishedEvent(uint64 serverConnectionHandlerID,
uint64 channelGroupID) = 0;
virtual void
onChannelPermListEvent(uint64 serverConnectionHandlerID, uint64 channelID,
unsigned int permissionID, int permissionValue,
int permissionNegated, int permissionSkip) = 0;
virtual void onChannelPermListFinishedEvent(uint64 serverConnectionHandlerID,
uint64 channelID) = 0;
virtual void onClientPermListEvent(uint64 serverConnectionHandlerID,
uint64 clientDatabaseID,
unsigned int permissionID,
int permissionValue, int permissionNegated,
int permissionSkip) = 0;
virtual void onClientPermListFinishedEvent(uint64 serverConnectionHandlerID,
uint64 clientDatabaseID) = 0;
virtual void
onChannelClientPermListEvent(uint64 serverConnectionHandlerID,
uint64 channelID, uint64 clientDatabaseID,
unsigned int permissionID, int permissionValue,
int permissionNegated, int permissionSkip) = 0;
virtual void
onChannelClientPermListFinishedEvent(uint64 serverConnectionHandlerID,
uint64 channelID,
uint64 clientDatabaseID) = 0;
virtual void onClientChannelGroupChangedEvent(
uint64 serverConnectionHandlerID, uint64 channelGroupID, uint64 channelID,
anyID clientID, anyID invokerClientID, const char *invokerName,
const char *invokerUniqueIdentity) = 0;
virtual int onServerPermissionErrorEvent(uint64 serverConnectionHandlerID,
const char *errorMessage,
unsigned int error,
const char *returnCode,
unsigned int failedPermissionID) = 0;
virtual void onPermissionListGroupEndIDEvent(uint64 serverConnectionHandlerID,
unsigned int groupEndID) = 0;
virtual void onPermissionListEvent(uint64 serverConnectionHandlerID,
unsigned int permissionID,
const char *permissionName,
const char *permissionDescription) = 0;
virtual void
onPermissionListFinishedEvent(uint64 serverConnectionHandlerID) = 0;
virtual void onPermissionOverviewEvent(
uint64 serverConnectionHandlerID, uint64 clientDatabaseID,
uint64 channelID, int overviewType, uint64 overviewID1,
uint64 overviewID2, unsigned int permissionID, int permissionValue,
int permissionNegated, int permissionSkip) = 0;
virtual void
onPermissionOverviewFinishedEvent(uint64 serverConnectionHandlerID) = 0;
virtual void onServerGroupClientAddedEvent(
uint64 serverConnectionHandlerID, anyID clientID, const char *clientName,
const char *clientUniqueIdentity, uint64 serverGroupID,
anyID invokerClientID, const char *invokerName,
const char *invokerUniqueIdentity) = 0;
virtual void onServerGroupClientDeletedEvent(
uint64 serverConnectionHandlerID, anyID clientID, const char *clientName,
const char *clientUniqueIdentity, uint64 serverGroupID,
anyID invokerClientID, const char *invokerName,
const char *invokerUniqueIdentity) = 0;
virtual void onClientNeededPermissionsEvent(uint64 serverConnectionHandlerID,
unsigned int permissionID,
int permissionValue) = 0;
virtual void
onClientNeededPermissionsFinishedEvent(uint64 serverConnectionHandlerID) = 0;
virtual void onFileTransferStatusEvent(anyID transferID, unsigned int status,
const char *statusMessage,
uint64 remotefileSize,
uint64 serverConnectionHandlerID) = 0;
virtual void onClientChatClosedEvent(uint64 serverConnectionHandlerID,
anyID clientID,
const char *clientUniqueIdentity) = 0;
virtual void onClientChatComposingEvent(uint64 serverConnectionHandlerID,
anyID clientID,
const char *clientUniqueIdentity) = 0;
virtual void onServerLogEvent(uint64 serverConnectionHandlerID,
const char *logMsg) = 0;
virtual void onServerLogFinishedEvent(uint64 serverConnectionHandlerID,
uint64 lastPos, uint64 fileSize) = 0;
virtual void onMessageListEvent(uint64 serverConnectionHandlerID,
uint64 messageID,
const char *fromClientUniqueIdentity,
const char *subject, uint64 timestamp,
int flagRead) = 0;
virtual void onMessageGetEvent(uint64 serverConnectionHandlerID,
uint64 messageID,
const char *fromClientUniqueIdentity,
const char *subject, const char *message,
uint64 timestamp) = 0;
virtual void onClientDBIDfromUIDEvent(uint64 serverConnectionHandlerID,
const char *uniqueClientIdentifier,
uint64 clientDatabaseID) = 0;
virtual void onClientNamefromUIDEvent(uint64 serverConnectionHandlerID,
const char *uniqueClientIdentifier,
uint64 clientDatabaseID,
const char *clientNickName) = 0;
virtual void onClientNamefromDBIDEvent(uint64 serverConnectionHandlerID,
const char *uniqueClientIdentifier,
uint64 clientDatabaseID,
const char *clientNickName) = 0;
virtual void onComplainListEvent(uint64 serverConnectionHandlerID,
uint64 targetClientDatabaseID,
const char *targetClientNickName,
uint64 fromClientDatabaseID,
const char *fromClientNickName,
const char *complainReason,
uint64 timestamp) = 0;
virtual 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) = 0;
virtual void
onClientServerQueryLoginPasswordEvent(uint64 serverConnectionHandlerID,
const char *loginPassword) = 0;
virtual void onPluginCommandEvent(uint64 serverConnectionHandlerID,
const char *pluginName,
const char *pluginCommand,
anyID invokerClientID,
const char *invokerName,
const char *invokerUniqueIdentity) = 0;
virtual void onIncomingClientQueryEvent(uint64 serverConnectionHandlerID,
const char *commandText) = 0;
virtual 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) = 0;
// Events
virtual void
onConnectStatusChangeEvent(uint64 serverConnectionHandlerID,
int newStatus,
unsigned int errorNumber) = 0;
virtual void onNewChannelEvent(uint64 serverConnectionHandlerID,
uint64 channelID,
uint64 channelParentID) = 0;
virtual void
onNewChannelCreatedEvent(uint64 serverConnectionHandlerID,
uint64 channelID, uint64 channelParentID,
anyID invokerID, const char *invokerName,
const char *invokerUniqueIdentifier) = 0;
virtual void onDelChannelEvent(uint64 serverConnectionHandlerID,
uint64 channelID, anyID invokerID,
const char *invokerName,
const char *invokerUniqueIdentifier) = 0;
virtual void
onChannelMoveEvent(uint64 serverConnectionHandlerID,
uint64 channelID, uint64 newChannelParentID,
anyID invokerID, const char *invokerName,
const char *invokerUniqueIdentifier) = 0;
virtual void onUpdateChannelEvent(uint64 serverConnectionHandlerID,
uint64 channelID) = 0;
virtual void onUpdateChannelEditedEvent(
uint64 serverConnectionHandlerID, uint64 channelID, anyID invokerID,
const char *invokerName, const char *invokerUniqueIdentifier) = 0;
virtual void onUpdateClientEvent(
uint64 serverConnectionHandlerID, anyID clientID, anyID invokerID,
const char *invokerName, const char *invokerUniqueIdentifier) = 0;
virtual void onClientMoveEvent(uint64 serverConnectionHandlerID,
anyID clientID, uint64 oldChannelID,
uint64 newChannelID, int visibility,
const char *moveMessage) = 0;
virtual void
onClientMoveSubscriptionEvent(uint64 serverConnectionHandlerID,
anyID clientID,
uint64 oldChannelID,
uint64 newChannelID,
int visibility) = 0;
virtual void onClientMoveTimeoutEvent(uint64 serverConnectionHandlerID,
anyID clientID,
uint64 oldChannelID,
uint64 newChannelID,
int visibility,
const char *timeoutMessage) = 0;
virtual void onClientMoveMovedEvent(uint64 serverConnectionHandlerID,
anyID clientID, uint64 oldChannelID,
uint64 newChannelID, int visibility,
anyID moverID,
const char *moverName,
const char *moverUniqueIdentifier,
const char *moveMessage) = 0;
virtual void onClientKickFromChannelEvent(
uint64 serverConnectionHandlerID, anyID clientID,
uint64 oldChannelID, uint64 newChannelID, int visibility,
anyID kickerID, const char *kickerName,
const char *kickerUniqueIdentifier, const char *kickMessage) = 0;
virtual void onClientKickFromServerEvent(
uint64 serverConnectionHandlerID, anyID clientID,
uint64 oldChannelID, uint64 newChannelID, int visibility,
anyID kickerID, const char *kickerName,
const char *kickerUniqueIdentifier, const char *kickMessage) = 0;
virtual void onClientIDsEvent(uint64 serverConnectionHandlerID,
const char *uniqueClientIdentifier,
anyID clientID,
const char *clientName) = 0;
virtual void
onClientIDsFinishedEvent(uint64 serverConnectionHandlerID) = 0;
virtual void
onServerEditedEvent(uint64 serverConnectionHandlerID,
anyID editerID, const char *editerName,
const char *editerUniqueIdentifier) = 0;
virtual void onServerUpdatedEvent(uint64 serverConnectionHandlerID) = 0;
virtual int onServerErrorEvent(uint64 serverConnectionHandlerID,
const char *errorMessage,
unsigned int error,
const char *returnCode,
const char *extraMessage) = 0;
virtual void onServerStopEvent(uint64 serverConnectionHandlerID,
const char *shutdownMessage) = 0;
virtual int onTextMessageEvent(uint64 serverConnectionHandlerID,
anyID targetMode, anyID toID,
anyID fromID, const char *fromName,
const char *fromUniqueIdentifier,
const char *message, int ffIgnored) = 0;
virtual void onTalkStatusChangeEvent(uint64 serverConnectionHandlerID,
int status, int isReceivedWhisper,
anyID clientID) = 0;
virtual void onConnectionInfoEvent(uint64 serverConnectionHandlerID,
anyID clientID) = 0;
virtual void
onServerConnectionInfoEvent(uint64 serverConnectionHandlerID) = 0;
virtual void onChannelSubscribeEvent(uint64 serverConnectionHandlerID,
uint64 channelID) = 0;
virtual void onChannelSubscribeFinishedEvent(
uint64 serverConnectionHandlerID) = 0;
virtual void onChannelUnsubscribeEvent(uint64 serverConnectionHandlerID,
uint64 channelID) = 0;
virtual void onChannelUnsubscribeFinishedEvent(
uint64 serverConnectionHandlerID) = 0;
virtual void
onChannelDescriptionUpdateEvent(uint64 serverConnectionHandlerID,
uint64 channelID) = 0;
virtual void
onChannelPasswordChangedEvent(uint64 serverConnectionHandlerID,
uint64 channelID) = 0;
virtual void onPlaybackShutdownCompleteEvent(
uint64 serverConnectionHandlerID) = 0;
virtual void onSoundDeviceListChangedEvent(const char *modeID,
int playOrCap) = 0;
virtual void
onEditPlaybackVoiceDataEvent(uint64 serverConnectionHandlerID,
anyID clientID, short *samples,
int sampleCount, int channels) = 0;
virtual void onEditPostProcessVoiceDataEvent(
uint64 serverConnectionHandlerID, anyID clientID, short *samples,
int sampleCount, int channels,
const unsigned int *channelSpeakerArray,
unsigned int *channelFillMask) = 0;
virtual void onEditMixedPlaybackVoiceDataEvent(
uint64 serverConnectionHandlerID, short *samples, int sampleCount,
int channels, const unsigned int *channelSpeakerArray,
unsigned int *channelFillMask) = 0;
virtual void
onEditCapturedVoiceDataEvent(uint64 serverConnectionHandlerID,
short *samples, int sampleCount,
int channels, int *edited) = 0;
virtual void onCustom3dRolloffCalculationClientEvent(
uint64 serverConnectionHandlerID, anyID clientID, float distance,
float *volume) = 0;
virtual void onCustom3dRolloffCalculationWaveEvent(
uint64 serverConnectionHandlerID, uint64 waveHandle, float distance,
float *volume) = 0;
virtual void
onUserLoggingMessageEvent(const char *logMessage, int logLevel,
const char *logChannel, uint64 logID,
const char *logTime,
const char *completeLogString) = 0;
/* Client UI callbacks */
virtual void onAvatarUpdated(uint64 serverConnectionHandlerID, anyID clientID,
const char *avatarPath) = 0;
virtual void onMenuItemEvent(uint64 serverConnectionHandlerID,
enum PluginMenuType type, int menuItemID,
uint64 selectedItemID) = 0;
virtual void onHotkeyEvent(const char *keyword) = 0;
virtual void onHotkeyRecordedEvent(const char *keyword, const char *key) = 0;
virtual void
onClientDisplayNameChanged(uint64 serverConnectionHandlerID, anyID clientID,
const char *displayName,
const char *uniqueClientIdentifier) = 0;
/* Clientlib rare */
virtual 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) = 0;
virtual int onClientPokeEvent(uint64 serverConnectionHandlerID,
anyID fromClientID, const char *pokerName,
const char *pokerUniqueIdentity,
const char *message, int ffIgnored) = 0;
virtual void
onClientSelfVariableUpdateEvent(uint64 serverConnectionHandlerID,
int flag, const char *oldValue,
const char *newValue) = 0;
virtual void onFileListEvent(uint64 serverConnectionHandlerID,
uint64 channelID, const char *path,
const char *name, uint64 size,
uint64 datetime, int type,
uint64 incompletesize,
const char *returnCode) = 0;
virtual void onFileListFinishedEvent(uint64 serverConnectionHandlerID,
uint64 channelID,
const char *path) = 0;
virtual void onFileInfoEvent(uint64 serverConnectionHandlerID,
uint64 channelID, const char *name,
uint64 size, uint64 datetime) = 0;
virtual void onServerGroupListEvent(uint64 serverConnectionHandlerID,
uint64 serverGroupID,
const char *name, int type,
int iconID, int saveDB) = 0;
virtual void onServerGroupListFinishedEvent(
uint64 serverConnectionHandlerID) = 0;
virtual void
onServerGroupByClientIDEvent(uint64 serverConnectionHandlerID,
const char *name,
uint64 serverGroupList,
uint64 clientDatabaseID) = 0;
virtual void
onServerGroupPermListEvent(uint64 serverConnectionHandlerID,
uint64 serverGroupID,
unsigned int permissionID,
int permissionValue,
int permissionNegated,
int permissionSkip) = 0;
virtual void
onServerGroupPermListFinishedEvent(uint64 serverConnectionHandlerID,
uint64 serverGroupID) = 0;
virtual void
onServerGroupClientListEvent(uint64 serverConnectionHandlerID,
uint64 serverGroupID,
uint64 clientDatabaseID,
const char *clientNameIdentifier,
const char *clientUniqueID) = 0;
virtual void onChannelGroupListEvent(uint64 serverConnectionHandlerID,
uint64 channelGroupID,
const char *name, int type,
int iconID, int saveDB) = 0;
virtual void onChannelGroupListFinishedEvent(
uint64 serverConnectionHandlerID) = 0;
virtual void
onChannelGroupPermListEvent(uint64 serverConnectionHandlerID,
uint64 channelGroupID,
unsigned int permissionID,
int permissionValue,
int permissionNegated,
int permissionSkip) = 0;
virtual void onChannelGroupPermListFinishedEvent(
uint64 serverConnectionHandlerID, uint64 channelGroupID) = 0;
virtual void onChannelPermListEvent(uint64 serverConnectionHandlerID,
uint64 channelID,
unsigned int permissionID,
int permissionValue,
int permissionNegated,
int permissionSkip) = 0;
virtual void
onChannelPermListFinishedEvent(uint64 serverConnectionHandlerID,
uint64 channelID) = 0;
virtual void onClientPermListEvent(uint64 serverConnectionHandlerID,
uint64 clientDatabaseID,
unsigned int permissionID,
int permissionValue,
int permissionNegated,
int permissionSkip) = 0;
virtual void
onClientPermListFinishedEvent(uint64 serverConnectionHandlerID,
uint64 clientDatabaseID) = 0;
virtual void onChannelClientPermListEvent(
uint64 serverConnectionHandlerID, uint64 channelID,
uint64 clientDatabaseID, unsigned int permissionID,
int permissionValue, int permissionNegated, int permissionSkip) = 0;
virtual void onChannelClientPermListFinishedEvent(
uint64 serverConnectionHandlerID,
uint64 channelID,
uint64 clientDatabaseID) = 0;
virtual void onClientChannelGroupChangedEvent(
uint64 serverConnectionHandlerID, uint64 channelGroupID,
uint64 channelID, anyID clientID, anyID invokerClientID,
const char *invokerName, const char *invokerUniqueIdentity) = 0;
virtual int
onServerPermissionErrorEvent(uint64 serverConnectionHandlerID,
const char *errorMessage,
unsigned int error,
const char *returnCode,
unsigned int failedPermissionID) = 0;
virtual void
onPermissionListGroupEndIDEvent(uint64 serverConnectionHandlerID,
unsigned int groupEndID) = 0;
virtual void
onPermissionListEvent(uint64 serverConnectionHandlerID,
unsigned int permissionID,
const char *permissionName,
const char *permissionDescription) = 0;
virtual void
onPermissionListFinishedEvent(uint64 serverConnectionHandlerID) = 0;
virtual void onPermissionOverviewEvent(
uint64 serverConnectionHandlerID, uint64 clientDatabaseID,
uint64 channelID, int overviewType, uint64 overviewID1,
uint64 overviewID2, unsigned int permissionID, int permissionValue,
int permissionNegated, int permissionSkip) = 0;
virtual void onPermissionOverviewFinishedEvent(
uint64 serverConnectionHandlerID) = 0;
virtual void onServerGroupClientAddedEvent(
uint64 serverConnectionHandlerID, anyID clientID,
const char *clientName, const char *clientUniqueIdentity,
uint64 serverGroupID, anyID invokerClientID,
const char *invokerName, const char *invokerUniqueIdentity) = 0;
virtual void onServerGroupClientDeletedEvent(
uint64 serverConnectionHandlerID, anyID clientID,
const char *clientName, const char *clientUniqueIdentity,
uint64 serverGroupID, anyID invokerClientID,
const char *invokerName, const char *invokerUniqueIdentity) = 0;
virtual void
onClientNeededPermissionsEvent(uint64 serverConnectionHandlerID,
unsigned int permissionID,
int permissionValue) = 0;
virtual void onClientNeededPermissionsFinishedEvent(
uint64 serverConnectionHandlerID) = 0;
virtual void onFileTransferStatusEvent(
anyID transferID, unsigned int status, const char *statusMessage,
uint64 remotefileSize, uint64 serverConnectionHandlerID) = 0;
virtual void
onClientChatClosedEvent(uint64 serverConnectionHandlerID,
anyID clientID,
const char *clientUniqueIdentity) = 0;
virtual void
onClientChatComposingEvent(uint64 serverConnectionHandlerID,
anyID clientID,
const char *clientUniqueIdentity) = 0;
virtual void onServerLogEvent(uint64 serverConnectionHandlerID,
const char *logMsg) = 0;
virtual void onServerLogFinishedEvent(uint64 serverConnectionHandlerID,
uint64 lastPos,
uint64 fileSize) = 0;
virtual void onMessageListEvent(uint64 serverConnectionHandlerID,
uint64 messageID,
const char *fromClientUniqueIdentity,
const char *subject, uint64 timestamp,
int flagRead) = 0;
virtual void onMessageGetEvent(uint64 serverConnectionHandlerID,
uint64 messageID,
const char *fromClientUniqueIdentity,
const char *subject, const char *message,
uint64 timestamp) = 0;
virtual void
onClientDBIDfromUIDEvent(uint64 serverConnectionHandlerID,
const char *uniqueClientIdentifier,
uint64 clientDatabaseID) = 0;
virtual void
onClientNamefromUIDEvent(uint64 serverConnectionHandlerID,
const char *uniqueClientIdentifier,
uint64 clientDatabaseID,
const char *clientNickName) = 0;
virtual void
onClientNamefromDBIDEvent(uint64 serverConnectionHandlerID,
const char *uniqueClientIdentifier,
uint64 clientDatabaseID,
const char *clientNickName) = 0;
virtual void onComplainListEvent(uint64 serverConnectionHandlerID,
uint64 targetClientDatabaseID,
const char *targetClientNickName,
uint64 fromClientDatabaseID,
const char *fromClientNickName,
const char *complainReason,
uint64 timestamp) = 0;
virtual 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) = 0;
virtual void onClientServerQueryLoginPasswordEvent(
uint64 serverConnectionHandlerID, const char *loginPassword) = 0;
virtual void
onPluginCommandEvent(uint64 serverConnectionHandlerID,
const char *pluginName,
const char *pluginCommand,
anyID invokerClientID,
const char *invokerName,
const char *invokerUniqueIdentity) = 0;
virtual void
onIncomingClientQueryEvent(uint64 serverConnectionHandlerID,
const char *commandText) = 0;
virtual 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) = 0;
/* Client UI callbacks */
virtual void onAvatarUpdated(uint64 serverConnectionHandlerID,
anyID clientID,
const char *avatarPath) = 0;
virtual void onMenuItemEvent(uint64 serverConnectionHandlerID,
enum PluginMenuType type, int menuItemID,
uint64 selectedItemID) = 0;
virtual void onHotkeyEvent(const char *keyword) = 0;
virtual void onHotkeyRecordedEvent(const char *keyword,
const char *key) = 0;
virtual void
onClientDisplayNameChanged(uint64 serverConnectionHandlerID,
anyID clientID, const char *displayName,
const char *uniqueClientIdentifier) = 0;
};
typedef IEchoionPlugin *(*CreatePluginFunc)(const TS3Functions* funcs);
typedef IEchoionPlugin *(*CreatePluginFunc)(const TS3Functions *funcs);
typedef void (*DestroyPluginFunc)(const IEchoionPlugin *);
+52 -42
View File
@@ -1,49 +1,59 @@
#pragma once
#include <csignal>
#include <functional>
#include <thread>
#include <csignal>
class SignalShutdown {
public:
explicit SignalShutdown(std::function<void()> onShutdown)
: m_OnShutdown(std::move(onShutdown))
{
// Block signals in this thread (and thus in subsequently created threads)
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGINT);
sigaddset(&set, SIGTERM);
sigaddset(&set, SIGHUP);
sigaddset(&set, SIGQUIT);
pthread_sigmask(SIG_BLOCK, &set, nullptr);
class SignalShutdown
{
public:
m_Thread = std::jthread([this, set]() mutable {
while (m_Running) {
int sig = 0;
if (sigwait(&set, &sig) == 0) {
if (!m_Running) break;
if (m_OnShutdown) m_OnShutdown();
// After requesting shutdown once, allow main to exit
break;
}
}
});
}
~SignalShutdown() {
m_Running = false;
// Send a signal to unblock sigwait if desired; easiest is detach-safe join
if (m_Thread.joinable()) {
// If main exits without signals, thread may still be blocked in sigwait.
// In that case, process teardown ends it anyway; but we prefer not to hang.
// So we simply detach.
m_Thread.detach();
}
}
explicit SignalShutdown(std::function<void()> onShutdown)
: m_OnShutdown(std::move(onShutdown))
{
// Block signals in this thread (and thus in subsequently created
// threads)
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGINT);
sigaddset(&set, SIGTERM);
sigaddset(&set, SIGHUP);
sigaddset(&set, SIGQUIT);
pthread_sigmask(SIG_BLOCK, &set, nullptr);
SignalShutdown(const SignalShutdown&) = delete;
SignalShutdown& operator=(const SignalShutdown&) = delete;
m_Thread = std::jthread([this, set]() mutable {
while (m_Running) {
int sig = 0;
if (sigwait(&set, &sig) == 0) {
if (!m_Running) {
break;
}
if (m_OnShutdown) {
m_OnShutdown();
}
// After requesting shutdown once, allow main to exit
break;
}
}
});
}
~SignalShutdown()
{
m_Running = false;
// Send a signal to unblock sigwait if desired; easiest is
// detach-safe join
if (m_Thread.joinable()) {
// If main exits without signals, thread may still be blocked in
// sigwait. In that case, process teardown ends it anyway; but
// we prefer not to hang. So we simply detach.
m_Thread.detach();
}
}
private:
std::function<void()> m_OnShutdown;
std::jthread m_Thread;
bool m_Running = true;
SignalShutdown(const SignalShutdown&) = delete;
SignalShutdown& operator=(const SignalShutdown&) = delete;
private:
std::function<void()> m_OnShutdown;
std::jthread m_Thread;
bool m_Running = true;
};
+45 -22
View File
@@ -3,51 +3,74 @@
/* Return values for ts3plugin_offersConfigure */
enum PluginConfigureOffer {
PLUGIN_OFFERS_NO_CONFIGURE = 0, /* Plugin does not implement ts3plugin_configure */
PLUGIN_OFFERS_CONFIGURE_NEW_THREAD, /* Plugin does implement ts3plugin_configure and requests to run this function in an own thread */
PLUGIN_OFFERS_CONFIGURE_QT_THREAD /* Plugin does implement ts3plugin_configure and requests to run this function in the Qt GUI thread */
PLUGIN_OFFERS_NO_CONFIGURE =
0, /* Plugin does not implement ts3plugin_configure */
PLUGIN_OFFERS_CONFIGURE_NEW_THREAD, /* Plugin does implement
ts3plugin_configure and requests to
run this function in an own thread */
PLUGIN_OFFERS_CONFIGURE_QT_THREAD /* Plugin does implement
ts3plugin_configure and requests to run
this function in the Qt GUI thread */
};
enum PluginMessageTarget { PLUGIN_MESSAGE_TARGET_SERVER = 0, PLUGIN_MESSAGE_TARGET_CHANNEL };
enum PluginMessageTarget {
PLUGIN_MESSAGE_TARGET_SERVER = 0,
PLUGIN_MESSAGE_TARGET_CHANNEL
};
enum PluginItemType { PLUGIN_SERVER = 0, PLUGIN_CHANNEL, PLUGIN_CLIENT };
enum PluginMenuType { PLUGIN_MENU_TYPE_GLOBAL = 0, PLUGIN_MENU_TYPE_CHANNEL, PLUGIN_MENU_TYPE_CLIENT };
enum PluginMenuType {
PLUGIN_MENU_TYPE_GLOBAL = 0,
PLUGIN_MENU_TYPE_CHANNEL,
PLUGIN_MENU_TYPE_CLIENT
};
#define PLUGIN_MENU_BUFSZ 128
struct PluginMenuItem {
enum PluginMenuType type;
int id;
char text[PLUGIN_MENU_BUFSZ];
char icon[PLUGIN_MENU_BUFSZ];
enum PluginMenuType type;
int id;
char text[PLUGIN_MENU_BUFSZ];
char icon[PLUGIN_MENU_BUFSZ];
};
#define PLUGIN_HOTKEY_BUFSZ 128
struct PluginHotkey {
char keyword[PLUGIN_HOTKEY_BUFSZ];
char description[PLUGIN_HOTKEY_BUFSZ];
char keyword[PLUGIN_HOTKEY_BUFSZ];
char description[PLUGIN_HOTKEY_BUFSZ];
};
struct PluginBookmarkList;
struct PluginBookmarkItem {
char* name;
unsigned char isFolder;
unsigned char reserved[3];
union {
char* uuid;
struct PluginBookmarkList* folder;
};
char* name;
unsigned char isFolder;
unsigned char reserved[3];
union {
char* uuid;
struct PluginBookmarkList* folder;
};
};
struct PluginBookmarkList {
int itemcount;
struct PluginBookmarkItem items[1]; //should be 0 but compiler complains
int itemcount;
struct PluginBookmarkItem items[1]; // should be 0 but compiler
// complains
};
enum PluginGuiProfile { PLUGIN_GUI_SOUND_CAPTURE = 0, PLUGIN_GUI_SOUND_PLAYBACK, PLUGIN_GUI_HOTKEY, PLUGIN_GUI_SOUNDPACK, PLUGIN_GUI_IDENTITY };
enum PluginGuiProfile {
PLUGIN_GUI_SOUND_CAPTURE = 0,
PLUGIN_GUI_SOUND_PLAYBACK,
PLUGIN_GUI_HOTKEY,
PLUGIN_GUI_SOUNDPACK,
PLUGIN_GUI_IDENTITY
};
enum PluginConnectTab { PLUGIN_CONNECT_TAB_NEW = 0, PLUGIN_CONNECT_TAB_CURRENT, PLUGIN_CONNECT_TAB_NEW_IF_CURRENT_CONNECTED };
enum PluginConnectTab {
PLUGIN_CONNECT_TAB_NEW = 0,
PLUGIN_CONNECT_TAB_CURRENT,
PLUGIN_CONNECT_TAB_NEW_IF_CURRENT_CONNECTED
};
#endif
+21 -14
View File
@@ -2,22 +2,29 @@
#define TEAMLOG_LOGTYPES_H
enum LogTypes {
LogType_NONE = 0x0000, ///< Logging is disabled
LogType_FILE = 0x0001, ///< Log to regular log file
LogType_CONSOLE = 0x0002, ///< Log to standard output / error
LogType_USERLOGGING = 0x0004, ///< User defined logging. Will call the \ref ServerLibFunctions.onUserLoggingMessageEvent callback for every message to be logged
LogType_NO_NETLOGGING = 0x0008, ///< Not used
LogType_DATABASE = 0x0010, ///< Log to database (deprecated, server only, no effect in SDK)
LogType_SYSLOG = 0x0020, ///< Log to syslog (only available on Linux)
LogType_NONE = 0x0000, ///< Logging is disabled
LogType_FILE = 0x0001, ///< Log to regular log file
LogType_CONSOLE = 0x0002, ///< Log to standard output / error
LogType_USERLOGGING =
0x0004, ///< User defined logging. Will call the \ref
///< ServerLibFunctions.onUserLoggingMessageEvent
///< callback for every message to be logged
LogType_NO_NETLOGGING = 0x0008, ///< Not used
LogType_DATABASE =
0x0010, ///< Log to database (deprecated, server only, no effect in SDK)
LogType_SYSLOG = 0x0020, ///< Log to syslog (only available on Linux)
};
enum LogLevel {
LogLevel_CRITICAL = 0, ///< these messages stop the program
LogLevel_ERROR, ///< everything that is really bad, but not so bad we need to shut down
LogLevel_WARNING, ///< everything that *might* be bad
LogLevel_DEBUG, ///< output that might help find a problem
LogLevel_INFO, ///< informational output, like "starting database version x.y.z"
LogLevel_DEVEL ///< developer only output (will not be displayed in release mode)
LogLevel_CRITICAL = 0, ///< these messages stop the program
LogLevel_ERROR, ///< everything that is really bad, but not so bad we need
///< to shut down
LogLevel_WARNING, ///< everything that *might* be bad
LogLevel_DEBUG, ///< output that might help find a problem
LogLevel_INFO, ///< informational output, like "starting database version
///< x.y.z"
LogLevel_DEVEL ///< developer only output (will not be displayed in release
///< mode)
};
#endif //TEAMLOG_LOGTYPES_H
#endif // TEAMLOG_LOGTYPES_H
File diff suppressed because it is too large. Load diff
+377 -182
View File
@@ -1,200 +1,395 @@
#ifndef PUBLIC_ERRORS_H
#define PUBLIC_ERRORS_H
//The idea here is: the values are 2 bytes wide, the first byte identifies the group, the second the count within that group
// The idea here is: the values are 2 bytes wide, the first byte identifies the
// group, the second the count within that group
enum Ts3ErrorType {
//general
ERROR_ok = 0x0000, ///< Indicates success.
ERROR_undefined = 0x0001,
ERROR_not_implemented = 0x0002, ///< The attempted operation is not available in this context
ERROR_ok_no_update = 0x0003, ///< Indicates success, but no change occurred. Returned for example upon flushing (e.g. using \ref ts3client_flushChannelUpdates) when all indicated changes already matched the current state.
ERROR_dont_notify = 0x0004,
ERROR_lib_time_limit_reached = 0x0005,
ERROR_out_of_memory = 0x0006, ///< Not enough system memory to perform operation
ERROR_canceled = 0x0007,
// general
ERROR_ok = 0x0000, ///< Indicates success.
ERROR_undefined = 0x0001,
ERROR_not_implemented =
0x0002, ///< The attempted operation is not available in this context
ERROR_ok_no_update =
0x0003, ///< Indicates success, but no change occurred. Returned for
///< example upon flushing (e.g. using \ref
///< ts3client_flushChannelUpdates) when all indicated changes
///< already matched the current state.
ERROR_dont_notify = 0x0004,
ERROR_lib_time_limit_reached = 0x0005,
ERROR_out_of_memory =
0x0006, ///< Not enough system memory to perform operation
ERROR_canceled = 0x0007,
//dunno
ERROR_command_not_found = 0x0100,
ERROR_unable_to_bind_network_port = 0x0101, ///< Unspecified failure to create a listening port
ERROR_no_network_port_available = 0x0102, ///< Failure to initialize a listening port for FileTransfer
ERROR_port_already_in_use = 0x0103, ///< Specified port is already in use by a different application
// dunno
ERROR_command_not_found = 0x0100,
ERROR_unable_to_bind_network_port =
0x0101, ///< Unspecified failure to create a listening port
ERROR_no_network_port_available =
0x0102, ///< Failure to initialize a listening port for FileTransfer
ERROR_port_already_in_use =
0x0103, ///< Specified port is already in use by a different application
//client
ERROR_client_invalid_id = 0x0200, ///< Client no longer connected
ERROR_client_nickname_inuse = 0x0201, ///< Client name is already in use. Client names must be unique
ERROR_client_protocol_limit_reached = 0x0203, ///< Too many clients on the server
ERROR_client_invalid_type = 0x0204, ///< Function called for normal clients that is only available for query clients or vice versa
ERROR_client_already_subscribed = 0x0205, ///< Attempting to subscribe to a channel already subscribed to
ERROR_client_not_logged_in = 0x0206,
ERROR_client_could_not_validate_identity = 0x0207, ///< Identity not valid or insufficient security level
ERROR_client_invalid_password = 0x0208,
ERROR_client_version_outdated = 0x020a, ///< Server requires newer client version as determined by the min_client_version properties
ERROR_client_is_flooding = 0x020c, ///< Triggered flood protection. Further information is supplied in the extra message if applicable.
ERROR_client_hacked = 0x020d,
ERROR_client_cannot_verify_now = 0x020e,
ERROR_client_login_not_permitted = 0x020f,
ERROR_client_not_subscribed = 0x0210, ///< Action is only available on subscribed channels
// client
ERROR_client_invalid_id = 0x0200, ///< Client no longer connected
ERROR_client_nickname_inuse =
0x0201, ///< Client name is already in use. Client names must be unique
ERROR_client_protocol_limit_reached =
0x0203, ///< Too many clients on the server
ERROR_client_invalid_type =
0x0204, ///< Function called for normal clients that is only available
///< for query clients or vice versa
ERROR_client_already_subscribed =
0x0205, ///< Attempting to subscribe to a channel already subscribed to
ERROR_client_not_logged_in = 0x0206,
ERROR_client_could_not_validate_identity =
0x0207, ///< Identity not valid or insufficient security level
ERROR_client_invalid_password = 0x0208,
ERROR_client_version_outdated =
0x020a, ///< Server requires newer client version as determined by the
///< min_client_version properties
ERROR_client_is_flooding =
0x020c, ///< Triggered flood protection. Further information is supplied
///< in the extra message if applicable.
ERROR_client_hacked = 0x020d,
ERROR_client_cannot_verify_now = 0x020e,
ERROR_client_login_not_permitted = 0x020f,
ERROR_client_not_subscribed =
0x0210, ///< Action is only available on subscribed channels
//channel
ERROR_channel_invalid_id = 0x0300, ///< Channel does not exist on the server (any longer)
ERROR_channel_protocol_limit_reached = 0x0301, ///< Too many channels on the server
ERROR_channel_already_in = 0x0302, ///< Attempting to move a client or channel to its current channel
ERROR_channel_name_inuse = 0x0303, ///< Channel name is already taken by another channel. Channel names must be unique
ERROR_channel_not_empty = 0x0304, ///< Attempting to delete a channel with clients or sub channels in it
ERROR_channel_can_not_delete_default = 0x0305, ///< Default channel cannot be deleted. Set a new default channel first (see \ref ts3client_setChannelVariableAsInt or \ref ts3server_setChannelVariableAsInt )
ERROR_channel_default_require_permanent = 0x0306, ///< Attempt to set a non permanent channel as default channel. Set channel to permanent first (see \ref ts3client_setChannelVariableAsInt or \ref ts3server_setChannelVariableAsInt )
ERROR_channel_invalid_flags = 0x0307, ///< Invalid combination of \ref ChannelProperties, trying to remove \ref CHANNEL_FLAG_DEFAULT or set a password on the default channel
ERROR_channel_parent_not_permanent = 0x0308, ///< Attempt to move a permanent channel into a non-permanent one, or set a channel to be permanent that is a sub channel of a non-permanent one
ERROR_channel_maxclients_reached = 0x0309, ///< Channel is full as determined by its \ref CHANNEL_MAXCLIENTS setting
ERROR_channel_maxfamily_reached = 0x030a, ///< Channel tree is full as determined by its \ref CHANNEL_MAXFAMILYCLIENTS setting
ERROR_channel_invalid_order = 0x030b, ///< Invalid value for the \ref CHANNEL_ORDER property. The specified channel must exist on the server and be on the same level.
ERROR_channel_no_filetransfer_supported = 0x030c, ///< Invalid \ref CHANNEL_FILEPATH set for the channel
ERROR_channel_invalid_password = 0x030d, ///< Channel has a password not matching the password supplied in the call
// used in public_rare_errors = 0x030e,
ERROR_channel_invalid_security_hash = 0x030f,
// channel
ERROR_channel_invalid_id =
0x0300, ///< Channel does not exist on the server (any longer)
ERROR_channel_protocol_limit_reached =
0x0301, ///< Too many channels on the server
ERROR_channel_already_in = 0x0302, ///< Attempting to move a client or
///< channel to its current channel
ERROR_channel_name_inuse =
0x0303, ///< Channel name is already taken by another channel. Channel
///< names must be unique
ERROR_channel_not_empty = 0x0304, ///< Attempting to delete a channel with
///< clients or sub channels in it
ERROR_channel_can_not_delete_default =
0x0305, ///< Default channel cannot be deleted. Set a new default
///< channel first (see \ref ts3client_setChannelVariableAsInt
///< or \ref ts3server_setChannelVariableAsInt )
ERROR_channel_default_require_permanent =
0x0306, ///< Attempt to set a non permanent channel as default channel.
///< Set channel to permanent first (see \ref
///< ts3client_setChannelVariableAsInt or \ref
///< ts3server_setChannelVariableAsInt )
ERROR_channel_invalid_flags =
0x0307, ///< Invalid combination of \ref ChannelProperties, trying to
///< remove \ref CHANNEL_FLAG_DEFAULT or set a password on the
///< default channel
ERROR_channel_parent_not_permanent =
0x0308, ///< Attempt to move a permanent channel into a non-permanent
///< one, or set a channel to be permanent that is a sub channel
///< of a non-permanent one
ERROR_channel_maxclients_reached =
0x0309, ///< Channel is full as determined by its \ref
///< CHANNEL_MAXCLIENTS setting
ERROR_channel_maxfamily_reached =
0x030a, ///< Channel tree is full as determined by its \ref
///< CHANNEL_MAXFAMILYCLIENTS setting
ERROR_channel_invalid_order =
0x030b, ///< Invalid value for the \ref CHANNEL_ORDER property. The
///< specified channel must exist on the server and be on the
///< same level.
ERROR_channel_no_filetransfer_supported =
0x030c, ///< Invalid \ref CHANNEL_FILEPATH set for the channel
ERROR_channel_invalid_password =
0x030d, ///< Channel has a password not matching the password supplied
///< in the call
// used in public_rare_errors = 0x030e,
ERROR_channel_invalid_security_hash = 0x030f,
//server
ERROR_server_invalid_id = 0x0400, ///< Chosen virtual server does not exist or is offline
ERROR_server_running = 0x0401, ///< attempting to delete a server that is running. Stop the server before deleting it.
ERROR_server_is_shutting_down = 0x0402, ///< Client disconnected because the server is going offline
ERROR_server_maxclients_reached = 0x0403, ///< Given in the onConnectStatusChange event when the server has reached its maximum number of clients as defined by the \ref VIRTUALSERVER_MAXCLIENTS property
ERROR_server_invalid_password = 0x0404, ///< Specified server password is wrong. Provide the correct password in the \ref ts3client_startConnection / \ref ts3client_startConnectionWithChannelID call.
ERROR_server_is_virtual = 0x0407, ///< Server is in virtual status. The attempted action is not possible in this state. Start the virtual server first.
ERROR_server_is_not_running = 0x0409, ///< Attempting to stop a server that is not online.
ERROR_server_is_booting = 0x040a, // Not used
ERROR_server_status_invalid = 0x040b,
ERROR_server_version_outdated = 0x040d, ///< Attempt to connect to an outdated server version. The server needs to be updated.
ERROR_server_duplicate_running = 0x040e, ///< This server is already running within the instance. Each virtual server may only exist once.
// server
ERROR_server_invalid_id =
0x0400, ///< Chosen virtual server does not exist or is offline
ERROR_server_running =
0x0401, ///< attempting to delete a server that is running. Stop the
///< server before deleting it.
ERROR_server_is_shutting_down =
0x0402, ///< Client disconnected because the server is going offline
ERROR_server_maxclients_reached =
0x0403, ///< Given in the onConnectStatusChange event when the server
///< has reached its maximum number of clients as defined by the
///< \ref VIRTUALSERVER_MAXCLIENTS property
ERROR_server_invalid_password =
0x0404, ///< Specified server password is wrong. Provide the correct
///< password in the \ref ts3client_startConnection / \ref
///< ts3client_startConnectionWithChannelID call.
ERROR_server_is_virtual =
0x0407, ///< Server is in virtual status. The attempted action is not
///< possible in this state. Start the virtual server first.
ERROR_server_is_not_running =
0x0409, ///< Attempting to stop a server that is not online.
ERROR_server_is_booting = 0x040a, // Not used
ERROR_server_status_invalid = 0x040b,
ERROR_server_version_outdated =
0x040d, ///< Attempt to connect to an outdated server version. The
///< server needs to be updated.
ERROR_server_duplicate_running =
0x040e, ///< This server is already running within the instance. Each
///< virtual server may only exist once.
//parameter
ERROR_parameter_quote = 0x0600, // Not used
ERROR_parameter_invalid_count = 0x0601, ///< Attempt to flush changes without previously calling set*VariableAs* since the last flush
ERROR_parameter_invalid = 0x0602, ///< At least one of the supplied parameters did not meet the criteria for that parameter
ERROR_parameter_not_found = 0x0603, ///< Failure to supply all the necessary parameters
ERROR_parameter_convert = 0x0604, ///< Invalid type supplied for a parameter, such as passing a string (ie. "five") that expects a number.
ERROR_parameter_invalid_size = 0x0605, ///< Value out of allowed range. Such as strings are too long/short or numeric values outside allowed range
ERROR_parameter_missing = 0x0606, ///< Neglecting to specify a required parameter
ERROR_parameter_checksum = 0x0607, ///< Attempting to deploy a modified snapshot
// parameter
ERROR_parameter_quote = 0x0600, // Not used
ERROR_parameter_invalid_count =
0x0601, ///< Attempt to flush changes without previously calling
///< set*VariableAs* since the last flush
ERROR_parameter_invalid =
0x0602, ///< At least one of the supplied parameters did not meet the
///< criteria for that parameter
ERROR_parameter_not_found =
0x0603, ///< Failure to supply all the necessary parameters
ERROR_parameter_convert =
0x0604, ///< Invalid type supplied for a parameter, such as passing a
///< string (ie. "five") that expects a number.
ERROR_parameter_invalid_size =
0x0605, ///< Value out of allowed range. Such as strings are too
///< long/short or numeric values outside allowed range
ERROR_parameter_missing =
0x0606, ///< Neglecting to specify a required parameter
ERROR_parameter_checksum =
0x0607, ///< Attempting to deploy a modified snapshot
//unsorted, need further investigation
ERROR_vs_critical = 0x0700, ///< Failure to create default channel
ERROR_connection_lost = 0x0701, ///< Generic error with the connection.
ERROR_not_connected = 0x0702, ///< Attempting to call functions with a serverConnectionHandler that is not connected. You can use \ref ts3client_getConnectionStatus to check whether the connection handler is connected to a server
ERROR_no_cached_connection_info = 0x0703, ///< Attempting to query connection information (bandwidth usage, ping, etc) without requesting them first using \ref ts3client_requestConnectionInfo
ERROR_currently_not_possible = 0x0704, ///< Requested information is not currently available. You may have to call \ref ts3client_requestClientVariables or \ref ts3client_requestServerVariables
ERROR_failed_connection_initialisation = 0x0705, ///< No TeamSpeak server running on the specified IP address and port
ERROR_could_not_resolve_hostname = 0x0706, ///< Failure to resolve the specified hostname to an IP address
ERROR_invalid_server_connection_handler_id = 0x0707, ///< Attempting to perform actions on a non-existent server connection handler
ERROR_could_not_initialise_input_manager = 0x0708, // Not used
ERROR_clientlibrary_not_initialised = 0x0709, ///< Calling client library functions without successfully calling \ref ts3client_initClientLib before
ERROR_serverlibrary_not_initialised = 0x070a, ///< Calling server library functions without successfully calling \ref ts3server_initServerLib before
ERROR_whisper_too_many_targets = 0x070b, ///< Using a whisper list that contain more clients than the servers \ref VIRTUALSERVER_MIN_CLIENTS_IN_CHANNEL_BEFORE_FORCED_SILENCE property
ERROR_whisper_no_targets = 0x070c, ///< The active whisper list is empty or no clients matched the whisper list (e.g. all channels in the list are empty)
ERROR_connection_ip_protocol_missing = 0x070d, ///< Invalid or unsupported protocol (e.g. attempting an IPv6 connection on an IPv4 only machine)
ERROR_handshake_failed = 0x070e,
ERROR_illegal_server_license = 0x070f,
// unsorted, need further investigation
ERROR_vs_critical = 0x0700, ///< Failure to create default channel
ERROR_connection_lost = 0x0701, ///< Generic error with the connection.
ERROR_not_connected =
0x0702, ///< Attempting to call functions with a serverConnectionHandler
///< that is not connected. You can use \ref
///< ts3client_getConnectionStatus to check whether the
///< connection handler is connected to a server
ERROR_no_cached_connection_info =
0x0703, ///< Attempting to query connection information (bandwidth
///< usage, ping, etc) without requesting them first using \ref
///< ts3client_requestConnectionInfo
ERROR_currently_not_possible =
0x0704, ///< Requested information is not currently available. You may
///< have to call \ref ts3client_requestClientVariables or \ref
///< ts3client_requestServerVariables
ERROR_failed_connection_initialisation =
0x0705, ///< No TeamSpeak server running on the specified IP address and
///< port
ERROR_could_not_resolve_hostname =
0x0706, ///< Failure to resolve the specified hostname to an IP address
ERROR_invalid_server_connection_handler_id =
0x0707, ///< Attempting to perform actions on a non-existent server
///< connection handler
ERROR_could_not_initialise_input_manager = 0x0708, // Not used
ERROR_clientlibrary_not_initialised =
0x0709, ///< Calling client library functions without successfully
///< calling \ref ts3client_initClientLib before
ERROR_serverlibrary_not_initialised =
0x070a, ///< Calling server library functions without successfully
///< calling \ref ts3server_initServerLib before
ERROR_whisper_too_many_targets =
0x070b, ///< Using a whisper list that contain more clients than the
///< servers \ref
///< VIRTUALSERVER_MIN_CLIENTS_IN_CHANNEL_BEFORE_FORCED_SILENCE
///< property
ERROR_whisper_no_targets =
0x070c, ///< The active whisper list is empty or no clients matched the
///< whisper list (e.g. all channels in the list are empty)
ERROR_connection_ip_protocol_missing =
0x070d, ///< Invalid or unsupported protocol (e.g. attempting an IPv6
///< connection on an IPv4 only machine)
ERROR_handshake_failed = 0x070e,
ERROR_illegal_server_license = 0x070f,
//file transfer
ERROR_file_invalid_name = 0x0800, ///< Invalid UTF8 string or not a valid file
ERROR_file_invalid_permissions = 0x0801, ///< Permissions prevent opening the file
ERROR_file_already_exists = 0x0802, ///< Target path already exists as a directory
ERROR_file_not_found = 0x0803, ///< Attempt to access or move non existing file
ERROR_file_io_error = 0x0804, ///< Generic file input / output error
ERROR_file_invalid_transfer_id = 0x0805, ///< Attempt to get information about a file transfer after it has already been cleaned up. File transfer information is not available indefinitely after the transfer completed
ERROR_file_invalid_path = 0x0806, ///< specified path contains invalid characters or does not start with "/"
ERROR_file_no_files_available = 0x0807, // Not used
ERROR_file_overwrite_excludes_resume = 0x0808, ///< File overwrite and resume are mutually exclusive. Only one or neither can be 1.
ERROR_file_invalid_size = 0x0809, ///< Attempt to write more bytes than claimed file size.
ERROR_file_already_in_use = 0x080a, ///< File is currently not available, try again later.
ERROR_file_could_not_open_connection = 0x080b, ///< Generic failure in file transfer connection / other party did not conform to file transfer protocol
ERROR_file_no_space_left_on_device = 0x080c, ///< Operating system reports hard disk is full. May be caused by quota limitations.
ERROR_file_exceeds_file_system_maximum_size = 0x080d, ///< File is too large for the file system of the target device.
ERROR_file_transfer_connection_timeout = 0x080e, // Not used
ERROR_file_connection_lost = 0x080f, ///< File input / output timeout or connection failure
ERROR_file_exceeds_supplied_size = 0x0810, // Not used
ERROR_file_transfer_complete = 0x0811, ///< Indicates successful completion
ERROR_file_transfer_canceled = 0x0812, ///< Transfer was cancelled through @ref ts3client_haltTransfer
ERROR_file_transfer_interrupted = 0x0813, ///< Transfer failed because the server is shutting down, or network connection issues
ERROR_file_transfer_server_quota_exceeded = 0x0814, ///< Transfer terminated due to server bandwidth quota being exceeded. No client can transfer files.
ERROR_file_transfer_client_quota_exceeded = 0x0815, ///< Attempt to transfer more data than allowed by this clients' bandwidth quota. Other clients may continue to transfer files.
ERROR_file_transfer_reset = 0x0816, // Not used
ERROR_file_transfer_limit_reached = 0x0817, ///< Too many file transfers are in progress. Try again later
ERROR_file_invalid_storage_class = 0x0818, // TODO: Invalid storage class for HTTP FileTransfer (what is a storage class?)
ERROR_file_invalid_dimension = 0x0819, ///< Avatar image exceeds maximum width or height accepted by the server.
ERROR_file_transfer_channel_quota_exceeded = 0x081a, ///< Transfer failed because the channel quota was exceeded. Uploading to this channel is not possible, but other channels may be fine.
// file transfer
ERROR_file_invalid_name =
0x0800, ///< Invalid UTF8 string or not a valid file
ERROR_file_invalid_permissions =
0x0801, ///< Permissions prevent opening the file
ERROR_file_already_exists =
0x0802, ///< Target path already exists as a directory
ERROR_file_not_found =
0x0803, ///< Attempt to access or move non existing file
ERROR_file_io_error = 0x0804, ///< Generic file input / output error
ERROR_file_invalid_transfer_id =
0x0805, ///< Attempt to get information about a file transfer after it
///< has already been cleaned up. File transfer information is
///< not available indefinitely after the transfer completed
ERROR_file_invalid_path = 0x0806, ///< specified path contains invalid
///< characters or does not start with "/"
ERROR_file_no_files_available = 0x0807, // Not used
ERROR_file_overwrite_excludes_resume =
0x0808, ///< File overwrite and resume are mutually exclusive. Only one
///< or neither can be 1.
ERROR_file_invalid_size =
0x0809, ///< Attempt to write more bytes than claimed file size.
ERROR_file_already_in_use =
0x080a, ///< File is currently not available, try again later.
ERROR_file_could_not_open_connection =
0x080b, ///< Generic failure in file transfer connection / other party
///< did not conform to file transfer protocol
ERROR_file_no_space_left_on_device =
0x080c, ///< Operating system reports hard disk is full. May be caused
///< by quota limitations.
ERROR_file_exceeds_file_system_maximum_size =
0x080d, ///< File is too large for the file system of the target device.
ERROR_file_transfer_connection_timeout = 0x080e, // Not used
ERROR_file_connection_lost =
0x080f, ///< File input / output timeout or connection failure
ERROR_file_exceeds_supplied_size = 0x0810, // Not used
ERROR_file_transfer_complete = 0x0811, ///< Indicates successful completion
ERROR_file_transfer_canceled =
0x0812, ///< Transfer was cancelled through @ref ts3client_haltTransfer
ERROR_file_transfer_interrupted =
0x0813, ///< Transfer failed because the server is shutting down, or
///< network connection issues
ERROR_file_transfer_server_quota_exceeded =
0x0814, ///< Transfer terminated due to server bandwidth quota being
///< exceeded. No client can transfer files.
ERROR_file_transfer_client_quota_exceeded =
0x0815, ///< Attempt to transfer more data than allowed by this clients'
///< bandwidth quota. Other clients may continue to transfer
///< files.
ERROR_file_transfer_reset = 0x0816, // Not used
ERROR_file_transfer_limit_reached =
0x0817, ///< Too many file transfers are in progress. Try again later
ERROR_file_invalid_storage_class =
0x0818, // TODO: Invalid storage class for HTTP FileTransfer (what is a
// storage class?)
ERROR_file_invalid_dimension =
0x0819, ///< Avatar image exceeds maximum width or height accepted by
///< the server.
ERROR_file_transfer_channel_quota_exceeded =
0x081a, ///< Transfer failed because the channel quota was exceeded.
///< Uploading to this channel is not possible, but other
///< channels may be fine.
//sound
ERROR_sound_preprocessor_disabled = 0x0900, ///< Cannot set or query pre processor variables with preprocessing disabled
ERROR_sound_internal_preprocessor = 0x0901,
ERROR_sound_internal_encoder = 0x0902,
ERROR_sound_internal_playback = 0x0903,
ERROR_sound_no_capture_device_available = 0x0904, ///< No audio capture devices are available
ERROR_sound_no_playback_device_available = 0x0905, ///< No audio playback devices are available
ERROR_sound_could_not_open_capture_device = 0x0906, ///< Error accessing audio device, or audio device does not support the requested mode
ERROR_sound_could_not_open_playback_device = 0x0907, ///< Error accessing audio device, or audio device does not support the requested mode
ERROR_sound_handler_has_device = 0x0908, ///< Attempt to open a sound device on a connection handler which already has an open device. Close the already open device first using \ref ts3client_closeCaptureDevice or \ref ts3client_closePlaybackDevice
ERROR_sound_invalid_capture_device = 0x0909, ///< Attempt to use a device for capture that does not support capturing audio
ERROR_sound_invalid_playback_device = 0x090a, ///< Attempt to use a device for playback that does not support playback of audio
ERROR_sound_invalid_wave = 0x090b, ///< Attempt to use a non WAV file in \ref ts3client_playWaveFile or \ref ts3client_playWaveFileHandle
ERROR_sound_unsupported_wave = 0x090c, ///< Unsupported wave file used in \ref ts3client_playWaveFile or \ref ts3client_playWaveFileHandle.
ERROR_sound_open_wave = 0x090d, ///< Failure to open the specified sound file
ERROR_sound_internal_capture = 0x090e,
ERROR_sound_device_in_use = 0x090f, ///< Attempt to unregister a custom device that is being used. Close the device first using \ref ts3client_closeCaptureDevice or \ref ts3client_closePlaybackDevice
ERROR_sound_device_already_registerred = 0x0910, ///< Attempt to register a custom device with a device id that has already been used in a previous call. Device ids must be unique.
ERROR_sound_unknown_device = 0x0911, ///< Attempt to open, close, unregister or use a device which is not known. Custom devices must be registered before being used (see \ref ts3client_registerCustomDevice)
ERROR_sound_unsupported_frequency = 0x0912,
ERROR_sound_invalid_channel_count = 0x0913, ///< Invalid device audio channel count, must be > 0
ERROR_sound_read_wave = 0x0914, ///< Failure to read sound samples from an opened wave file. Is this a valid wave file?
ERROR_sound_need_more_data = 0x0915, // for internal purposes only
ERROR_sound_device_busy = 0x0916, // for internal purposes only
ERROR_sound_no_data = 0x0917, ///< Indicates there is currently no data for playback, e.g. nobody is speaking right now.
ERROR_sound_channel_mask_mismatch = 0x0918, ///< Opening a device with an unsupported channel count
// sound
ERROR_sound_preprocessor_disabled =
0x0900, ///< Cannot set or query pre processor variables with
///< preprocessing disabled
ERROR_sound_internal_preprocessor = 0x0901,
ERROR_sound_internal_encoder = 0x0902,
ERROR_sound_internal_playback = 0x0903,
ERROR_sound_no_capture_device_available =
0x0904, ///< No audio capture devices are available
ERROR_sound_no_playback_device_available =
0x0905, ///< No audio playback devices are available
ERROR_sound_could_not_open_capture_device =
0x0906, ///< Error accessing audio device, or audio device does not
///< support the requested mode
ERROR_sound_could_not_open_playback_device =
0x0907, ///< Error accessing audio device, or audio device does not
///< support the requested mode
ERROR_sound_handler_has_device =
0x0908, ///< Attempt to open a sound device on a connection handler
///< which already has an open device. Close the already open
///< device first using \ref ts3client_closeCaptureDevice or
///< \ref ts3client_closePlaybackDevice
ERROR_sound_invalid_capture_device =
0x0909, ///< Attempt to use a device for capture that does not support
///< capturing audio
ERROR_sound_invalid_playback_device =
0x090a, ///< Attempt to use a device for playback that does not support
///< playback of audio
ERROR_sound_invalid_wave =
0x090b, ///< Attempt to use a non WAV file in \ref
///< ts3client_playWaveFile or \ref ts3client_playWaveFileHandle
ERROR_sound_unsupported_wave =
0x090c, ///< Unsupported wave file used in \ref ts3client_playWaveFile
///< or \ref ts3client_playWaveFileHandle.
ERROR_sound_open_wave =
0x090d, ///< Failure to open the specified sound file
ERROR_sound_internal_capture = 0x090e,
ERROR_sound_device_in_use =
0x090f, ///< Attempt to unregister a custom device that is being used.
///< Close the device first using \ref
///< ts3client_closeCaptureDevice or \ref
///< ts3client_closePlaybackDevice
ERROR_sound_device_already_registerred =
0x0910, ///< Attempt to register a custom device with a device id that
///< has already been used in a previous call. Device ids must
///< be unique.
ERROR_sound_unknown_device =
0x0911, ///< Attempt to open, close, unregister or use a device which is
///< not known. Custom devices must be registered before being
///< used (see \ref ts3client_registerCustomDevice)
ERROR_sound_unsupported_frequency = 0x0912,
ERROR_sound_invalid_channel_count =
0x0913, ///< Invalid device audio channel count, must be > 0
ERROR_sound_read_wave =
0x0914, ///< Failure to read sound samples from an opened wave file. Is
///< this a valid wave file?
ERROR_sound_need_more_data = 0x0915, // for internal purposes only
ERROR_sound_device_busy = 0x0916, // for internal purposes only
ERROR_sound_no_data =
0x0917, ///< Indicates there is currently no data for playback, e.g.
///< nobody is speaking right now.
ERROR_sound_channel_mask_mismatch =
0x0918, ///< Opening a device with an unsupported channel count
//permissions
ERROR_permissions_client_insufficient = 0x0a08, ///< Not enough permissions to perform the requested activity
ERROR_permissions = 0x0a0c, ///< Permissions to use sound device not granted by operating system, e.g. Windows denied microphone access.
// permissions
ERROR_permissions_client_insufficient =
0x0a08, ///< Not enough permissions to perform the requested activity
ERROR_permissions =
0x0a0c, ///< Permissions to use sound device not granted by operating
///< system, e.g. Windows denied microphone access.
//accounting
ERROR_accounting_virtualserver_limit_reached = 0x0b00, ///< Attempt to use more virtual servers than allowed by the license
ERROR_accounting_slot_limit_reached = 0x0b01, ///< Attempt to set more slots than allowed by the license
ERROR_accounting_license_file_not_found = 0x0b02, // Not used
ERROR_accounting_license_date_not_ok = 0x0b03, ///< License expired or not valid yet
ERROR_accounting_unable_to_connect_to_server = 0x0b04, ///< Failure to communicate with accounting backend
ERROR_accounting_unknown_error = 0x0b05, ///< Failure to write update license file
ERROR_accounting_server_error = 0x0b06, // Not used
ERROR_accounting_instance_limit_reached = 0x0b07, ///< More than one process of the server is running
ERROR_accounting_instance_check_error = 0x0b08, ///< Shared memory access failure.
ERROR_accounting_license_file_invalid = 0x0b09, ///< License is not a TeamSpeak license
ERROR_accounting_running_elsewhere = 0x0b0a, ///< A copy of this server is already running in another instance. Each server may only exist once.
ERROR_accounting_instance_duplicated = 0x0b0b, ///< A copy of this server is running already in this process. Each server may only exist once.
ERROR_accounting_already_started = 0x0b0c, ///< Attempt to start a server that is already running
ERROR_accounting_not_started = 0x0b0d,
ERROR_accounting_to_many_starts = 0x0b0e, ///< Starting instance / virtual servers too often in too short a time period
// accounting
ERROR_accounting_virtualserver_limit_reached =
0x0b00, ///< Attempt to use more virtual servers than allowed by the
///< license
ERROR_accounting_slot_limit_reached =
0x0b01, ///< Attempt to set more slots than allowed by the license
ERROR_accounting_license_file_not_found = 0x0b02, // Not used
ERROR_accounting_license_date_not_ok =
0x0b03, ///< License expired or not valid yet
ERROR_accounting_unable_to_connect_to_server =
0x0b04, ///< Failure to communicate with accounting backend
ERROR_accounting_unknown_error =
0x0b05, ///< Failure to write update license file
ERROR_accounting_server_error = 0x0b06, // Not used
ERROR_accounting_instance_limit_reached =
0x0b07, ///< More than one process of the server is running
ERROR_accounting_instance_check_error =
0x0b08, ///< Shared memory access failure.
ERROR_accounting_license_file_invalid =
0x0b09, ///< License is not a TeamSpeak license
ERROR_accounting_running_elsewhere =
0x0b0a, ///< A copy of this server is already running in another
///< instance. Each server may only exist once.
ERROR_accounting_instance_duplicated =
0x0b0b, ///< A copy of this server is running already in this process.
///< Each server may only exist once.
ERROR_accounting_already_started =
0x0b0c, ///< Attempt to start a server that is already running
ERROR_accounting_not_started = 0x0b0d,
ERROR_accounting_to_many_starts =
0x0b0e, ///< Starting instance / virtual servers too often in too short
///< a time period
//provisioning server
/// @cond HAS_PROVISIONING
ERROR_provisioning_invalid_password = 0x1100,
ERROR_provisioning_invalid_request = 0x1101,
ERROR_provisioning_no_slots_available = 0x1102,
ERROR_provisioning_pool_missing = 0x1103,
ERROR_provisioning_pool_unknown = 0x1104,
ERROR_provisioning_unknown_ip_location = 0x1105,
ERROR_provisioning_internal_tries_exceeded = 0x1106,
ERROR_provisioning_too_many_slots_requested = 0x1107,
ERROR_provisioning_too_many_reserved = 0x1108,
ERROR_provisioning_could_not_connect = 0x1109,
ERROR_provisioning_auth_server_not_connected = 0x1110,
ERROR_provisioning_auth_data_too_large = 0x1111,
ERROR_provisioning_already_initialized = 0x1112,
ERROR_provisioning_not_initialized = 0x1113,
ERROR_provisioning_connecting = 0x1114,
ERROR_provisioning_already_connected = 0x1115,
ERROR_provisioning_not_connected = 0x1116,
ERROR_provisioning_io_error = 0x1117,
ERROR_provisioning_invalid_timeout = 0x1118,
ERROR_provisioning_ts3server_not_found = 0x1119,
ERROR_provisioning_no_permission = 0x111A,
/// @endcond
// provisioning server
/// @cond HAS_PROVISIONING
ERROR_provisioning_invalid_password = 0x1100,
ERROR_provisioning_invalid_request = 0x1101,
ERROR_provisioning_no_slots_available = 0x1102,
ERROR_provisioning_pool_missing = 0x1103,
ERROR_provisioning_pool_unknown = 0x1104,
ERROR_provisioning_unknown_ip_location = 0x1105,
ERROR_provisioning_internal_tries_exceeded = 0x1106,
ERROR_provisioning_too_many_slots_requested = 0x1107,
ERROR_provisioning_too_many_reserved = 0x1108,
ERROR_provisioning_could_not_connect = 0x1109,
ERROR_provisioning_auth_server_not_connected = 0x1110,
ERROR_provisioning_auth_data_too_large = 0x1111,
ERROR_provisioning_already_initialized = 0x1112,
ERROR_provisioning_not_initialized = 0x1113,
ERROR_provisioning_connecting = 0x1114,
ERROR_provisioning_already_connected = 0x1115,
ERROR_provisioning_not_connected = 0x1116,
ERROR_provisioning_io_error = 0x1117,
ERROR_provisioning_invalid_timeout = 0x1118,
ERROR_provisioning_ts3server_not_found = 0x1119,
ERROR_provisioning_no_permission = 0x111A,
/// @endcond
};
#endif
@@ -1,108 +1,109 @@
#ifndef PUBLIC_ERRORS__RARE_H
#define PUBLIC_ERRORS__RARE_H
//The idea here is: the values are 2 bytes wide, the first byte identifies the group, the second the count within that group
// The idea here is: the values are 2 bytes wide, the first byte identifies the
// group, the second the count within that group
enum Ts3RareErrorType {
//client
ERROR_client_too_many_clones_connected = 0x0209,
ERROR_client_is_online = 0x020b,
// client
ERROR_client_too_many_clones_connected = 0x0209,
ERROR_client_is_online = 0x020b,
//channel
ERROR_channel_is_private_channel = 0x030e,
//note 0x030f is defined in public_errors;
// channel
ERROR_channel_is_private_channel = 0x030e,
// note 0x030f is defined in public_errors;
//database
ERROR_database = 0x0500,
ERROR_database_empty_result = 0x0501,
ERROR_database_duplicate_entry = 0x0502,
ERROR_database_no_modifications = 0x0503,
ERROR_database_constraint = 0x0504,
ERROR_database_reinvoke = 0x0505,
// database
ERROR_database = 0x0500,
ERROR_database_empty_result = 0x0501,
ERROR_database_duplicate_entry = 0x0502,
ERROR_database_no_modifications = 0x0503,
ERROR_database_constraint = 0x0504,
ERROR_database_reinvoke = 0x0505,
//permissions
ERROR_permission_invalid_group_id = 0x0a00,
ERROR_permission_duplicate_entry = 0x0a01,
ERROR_permission_invalid_perm_id = 0x0a02,
ERROR_permission_empty_result = 0x0a03,
ERROR_permission_default_group_forbidden = 0x0a04,
ERROR_permission_invalid_size = 0x0a05,
ERROR_permission_invalid_value = 0x0a06,
ERROR_permissions_group_not_empty = 0x0a07,
ERROR_permissions_insufficient_group_power = 0x0a09,
ERROR_permissions_insufficient_permission_power = 0x0a0a,
ERROR_permission_template_group_is_used = 0x0a0b,
//0x0a0c is in public_errors.h
ERROR_permission_used_by_integration = 0x0a0d,
// permissions
ERROR_permission_invalid_group_id = 0x0a00,
ERROR_permission_duplicate_entry = 0x0a01,
ERROR_permission_invalid_perm_id = 0x0a02,
ERROR_permission_empty_result = 0x0a03,
ERROR_permission_default_group_forbidden = 0x0a04,
ERROR_permission_invalid_size = 0x0a05,
ERROR_permission_invalid_value = 0x0a06,
ERROR_permissions_group_not_empty = 0x0a07,
ERROR_permissions_insufficient_group_power = 0x0a09,
ERROR_permissions_insufficient_permission_power = 0x0a0a,
ERROR_permission_template_group_is_used = 0x0a0b,
// 0x0a0c is in public_errors.h
ERROR_permission_used_by_integration = 0x0a0d,
//server
ERROR_server_deployment_active = 0x0405,
ERROR_server_unable_to_stop_own_server = 0x0406,
ERROR_server_wrong_machineid = 0x0408,
ERROR_server_modal_quit = 0x040c,
ERROR_server_time_difference_too_large = 0x040f,
ERROR_server_blacklisted = 0x0410,
ERROR_server_shutdown = 0x0411,
// server
ERROR_server_deployment_active = 0x0405,
ERROR_server_unable_to_stop_own_server = 0x0406,
ERROR_server_wrong_machineid = 0x0408,
ERROR_server_modal_quit = 0x040c,
ERROR_server_time_difference_too_large = 0x040f,
ERROR_server_blacklisted = 0x0410,
ERROR_server_shutdown = 0x0411,
//messages
ERROR_message_invalid_id = 0x0c00,
// messages
ERROR_message_invalid_id = 0x0c00,
//ban
ERROR_ban_invalid_id = 0x0d00,
ERROR_connect_failed_banned = 0x0d01,
ERROR_rename_failed_banned = 0x0d02,
ERROR_ban_flooding = 0x0d03,
// ban
ERROR_ban_invalid_id = 0x0d00,
ERROR_connect_failed_banned = 0x0d01,
ERROR_rename_failed_banned = 0x0d02,
ERROR_ban_flooding = 0x0d03,
//tts
ERROR_tts_unable_to_initialize = 0x0e00,
// tts
ERROR_tts_unable_to_initialize = 0x0e00,
//privilege key
ERROR_privilege_key_invalid = 0x0f00,
// privilege key
ERROR_privilege_key_invalid = 0x0f00,
//voip
ERROR_voip_pjsua = 0x1000,
ERROR_voip_already_initialized = 0x1001,
ERROR_voip_too_many_accounts = 0x1002,
ERROR_voip_invalid_account = 0x1003,
ERROR_voip_internal_error = 0x1004,
ERROR_voip_invalid_connectionId = 0x1005,
ERROR_voip_cannot_answer_initiated_call = 0x1006,
ERROR_voip_not_initialized = 0x1007,
// voip
ERROR_voip_pjsua = 0x1000,
ERROR_voip_already_initialized = 0x1001,
ERROR_voip_too_many_accounts = 0x1002,
ERROR_voip_invalid_account = 0x1003,
ERROR_voip_internal_error = 0x1004,
ERROR_voip_invalid_connectionId = 0x1005,
ERROR_voip_cannot_answer_initiated_call = 0x1006,
ERROR_voip_not_initialized = 0x1007,
//mytsid - client
ERROR_invalid_mytsid_data = 0x1200,
ERROR_invalid_integration = 0x1201,
ERROR_mytsid_needed = 0x1202,
// mytsid - client
ERROR_invalid_mytsid_data = 0x1200,
ERROR_invalid_integration = 0x1201,
ERROR_mytsid_needed = 0x1202,
//ed25519
ERROR_ed25519_rng_fail = 0x1300,
ERROR_ed25519_signature_invalid = 0x1301,
ERROR_ed25519_invalid_key = 0x1302,
ERROR_ed25519_unable_to_create_valid_key = 0x1303,
ERROR_ed25519_out_of_memory = 0x1304,
ERROR_ed25519_exists = 0x1305,
ERROR_ed25519_read_beyond_eof = 0x1306,
ERROR_ed25519_write_beyond_eof = 0x1307,
ERROR_ed25519_version = 0x1308,
ERROR_ed25519_invalid = 0x1309,
ERROR_ed25519_invalid_date = 0x130A,
ERROR_ed25519_unauthorized = 0x130B,
ERROR_ed25519_invalid_type = 0x130C,
ERROR_ed25519_address_nomatch = 0x130D,
ERROR_ed25519_not_valid_yet = 0x130E,
ERROR_ed25519_expired = 0x130F,
ERROR_ed25519_index_out_of_range = 0x1310,
ERROR_ed25519_invalid_size = 0x1311,
// ed25519
ERROR_ed25519_rng_fail = 0x1300,
ERROR_ed25519_signature_invalid = 0x1301,
ERROR_ed25519_invalid_key = 0x1302,
ERROR_ed25519_unable_to_create_valid_key = 0x1303,
ERROR_ed25519_out_of_memory = 0x1304,
ERROR_ed25519_exists = 0x1305,
ERROR_ed25519_read_beyond_eof = 0x1306,
ERROR_ed25519_write_beyond_eof = 0x1307,
ERROR_ed25519_version = 0x1308,
ERROR_ed25519_invalid = 0x1309,
ERROR_ed25519_invalid_date = 0x130A,
ERROR_ed25519_unauthorized = 0x130B,
ERROR_ed25519_invalid_type = 0x130C,
ERROR_ed25519_address_nomatch = 0x130D,
ERROR_ed25519_not_valid_yet = 0x130E,
ERROR_ed25519_expired = 0x130F,
ERROR_ed25519_index_out_of_range = 0x1310,
ERROR_ed25519_invalid_size = 0x1311,
//api key
ERROR_apikey_outofscope = 0x1400,
ERROR_apikey_crypto_error = 0x1401,
ERROR_apikey_invalid = 0x1402,
ERROR_apikey_invalid_id = 0x1403,
ERROR_apikey_missing = 0x1404,
// api key
ERROR_apikey_outofscope = 0x1400,
ERROR_apikey_crypto_error = 0x1401,
ERROR_apikey_invalid = 0x1402,
ERROR_apikey_invalid_id = 0x1403,
ERROR_apikey_missing = 0x1404,
//homebase
ERROR_homebase_no_slots_available = 0x1500,
// homebase
ERROR_homebase_no_slots_available = 0x1500,
};
#endif
@@ -3,7 +3,7 @@
#include "public_definitions.h"
//limited length, measured in characters
// limited length, measured in characters
#define TS3_MAX_SIZE_CLIENT_NICKNAME_NONSDK 30
#define TS3_MIN_SIZE_CLIENT_NICKNAME_NONSDK 3
#define TS3_MAX_SIZE_AWAY_MESSAGE 80
@@ -18,351 +18,507 @@
#define TS3_MAX_SIZE_OFFLINE_MESSAGE_SUBJECT 200
#define TS3_MAX_SIZE_USER_TAG 100
//limited length, measured in bytes (utf8 encoded)
// limited length, measured in bytes (utf8 encoded)
#define TS3_MAX_SIZE_PLUGIN_COMMAND 1024 * 8
#define TS3_MAX_SIZE_VIRTUALSERVER_HOSTBANNER_GFX_URL 2000
enum GroupShowNameTreeMode {
GroupShowNameTreeMode_NONE = 0, //dont group show name
GroupShowNameTreeMode_BEFORE, //show group name before client name
GroupShowNameTreeMode_BEHIND //show group name behind client name
GroupShowNameTreeMode_NONE = 0, // dont group show name
GroupShowNameTreeMode_BEFORE, // show group name before client name
GroupShowNameTreeMode_BEHIND // show group name behind client name
};
enum PluginTargetMode {
PluginCommandTarget_CURRENT_CHANNEL = 0, //send plugincmd to all clients in current channel
PluginCommandTarget_SERVER, //send plugincmd to all clients on server
PluginCommandTarget_CLIENT, //send plugincmd to all given client ids
PluginCommandTarget_CURRENT_CHANNEL_SUBSCRIBED_CLIENTS, //send plugincmd to all subscribed clients in current channel
PluginCommandTarget_MAX
PluginCommandTarget_CURRENT_CHANNEL =
0, // send plugincmd to all clients in current channel
PluginCommandTarget_SERVER, // send plugincmd to all clients on server
PluginCommandTarget_CLIENT, // send plugincmd to all given client ids
PluginCommandTarget_CURRENT_CHANNEL_SUBSCRIBED_CLIENTS, // send plugincmd to
// all subscribed
// clients in
// current channel
PluginCommandTarget_MAX
};
enum {
SERVER_BINDING_VIRTUALSERVER = 0,
SERVER_BINDING_SERVERQUERY = 1,
SERVER_BINDING_FILETRANSFER = 2,
SERVER_BINDING_VIRTUALSERVER = 0,
SERVER_BINDING_SERVERQUERY = 1,
SERVER_BINDING_FILETRANSFER = 2,
};
enum HostMessageMode {
HostMessageMode_NONE = 0, //dont display anything
HostMessageMode_LOG, //display message inside log
HostMessageMode_MODAL, //display message inside a modal dialog
HostMessageMode_MODALQUIT //display message inside a modal dialog and quit/close server/connection
HostMessageMode_NONE = 0, // dont display anything
HostMessageMode_LOG, // display message inside log
HostMessageMode_MODAL, // display message inside a modal dialog
HostMessageMode_MODALQUIT // display message inside a modal dialog and
// quit/close server/connection
};
enum HostBannerMode {
HostBannerMode_NO_ADJUST = 0, //Do not adjust
HostBannerMode_ADJUST_IGNORE_ASPECT, //Adjust but ignore aspect ratio
HostBannerMode_ADJUST_KEEP_ASPECT, //Adjust and keep aspect ratio
HostBannerMode_NO_ADJUST = 0, // Do not adjust
HostBannerMode_ADJUST_IGNORE_ASPECT, // Adjust but ignore aspect ratio
HostBannerMode_ADJUST_KEEP_ASPECT, // Adjust and keep aspect ratio
};
enum ClientType {
ClientType_NORMAL = 0,
ClientType_SERVERQUERY,
ClientType_NORMAL = 0,
ClientType_SERVERQUERY,
};
enum AwayStatus {
AWAY_NONE = 0,
AWAY_ZZZ,
AWAY_NONE = 0,
AWAY_ZZZ,
};
enum CommandLinePropertiesRare {
#ifdef SERVER
COMMANDLINE_CREATE_DEFAULT_VIRTUALSERVER = 0, //create default virtualserver
COMMANDLINE_MACHINE_ID, //machine id (starts only virtualserver with given machineID
COMMANDLINE_DEFAULT_VOICE_PORT,
COMMANDLINE_VOICE_IP,
COMMANDLINE_THREADS_VOICE_UDP,
COMMANDLINE_LICENSEPATH,
COMMANDLINE_YAMLFILE,
COMMANDLINE_CREATE_DEFAULT_VIRTUALSERVER =
0, // create default virtualserver
COMMANDLINE_MACHINE_ID, // machine id (starts only virtualserver with given
// machineID
COMMANDLINE_DEFAULT_VOICE_PORT,
COMMANDLINE_VOICE_IP,
COMMANDLINE_THREADS_VOICE_UDP,
COMMANDLINE_LICENSEPATH,
COMMANDLINE_YAMLFILE,
#ifndef TEAMSPEAK_SDK
COMMANDLINE_FILETRANSFER_PORT,
COMMANDLINE_FILETRANSFER_IP,
COMMANDLINE_QUERY_PORT,
COMMANDLINE_QUERY_IP,
COMMANDLINE_QUERY_IP_ALLOWLIST,
COMMANDLINE_QUERY_IP_DENYLIST,
COMMANDLINE_CLEAR_DATABASE,
COMMANDLINE_SERVERADMIN_PASSWORD,
COMMANDLINE_DBPLUGIN,
COMMANDLINE_DBPLUGINPARAMETER,
COMMANDLINE_DBSQLPATH,
COMMANDLINE_DBSQLCREATEPATH,
COMMANDLINE_DBCONNECTIONS,
COMMANDLINE_LOGPATH,
COMMANDLINE_CREATEINIFILE,
COMMANDLINE_INIFILE,
COMMANDLINE_LOGQUERYCOMMANDS,
COMMANDLINE_DBCLIENTKEEPDAYS,
COMMANDLINE_NO_PERMISSION_UPDATE,
COMMANDLINE_OPEN_WIN_CONSOLE,
COMMANDLINE_NO_PASSWORD_DIALOG,
COMMANDLINE_LOGAPPEND,
COMMANDLINE_QUERY_SKIPBRUTEFORCECHECK,
COMMANDLINE_QUERY_BUFFER_MB,
COMMANDLINE_FILETRANSFER_PORT,
COMMANDLINE_FILETRANSFER_IP,
COMMANDLINE_QUERY_PORT,
COMMANDLINE_QUERY_IP,
COMMANDLINE_QUERY_IP_ALLOWLIST,
COMMANDLINE_QUERY_IP_DENYLIST,
COMMANDLINE_CLEAR_DATABASE,
COMMANDLINE_SERVERADMIN_PASSWORD,
COMMANDLINE_DBPLUGIN,
COMMANDLINE_DBPLUGINPARAMETER,
COMMANDLINE_DBSQLPATH,
COMMANDLINE_DBSQLCREATEPATH,
COMMANDLINE_DBCONNECTIONS,
COMMANDLINE_LOGPATH,
COMMANDLINE_CREATEINIFILE,
COMMANDLINE_INIFILE,
COMMANDLINE_LOGQUERYCOMMANDS,
COMMANDLINE_DBCLIENTKEEPDAYS,
COMMANDLINE_NO_PERMISSION_UPDATE,
COMMANDLINE_OPEN_WIN_CONSOLE,
COMMANDLINE_NO_PASSWORD_DIALOG,
COMMANDLINE_LOGAPPEND,
COMMANDLINE_QUERY_SKIPBRUTEFORCECHECK,
COMMANDLINE_QUERY_BUFFER_MB,
#endif
COMMANDLINE_HTTP_PROXY,
COMMANDLINE_HTTP_PROXY,
#ifndef TEAMSPEAK_SDK
COMMANDLINE_LICENSE_ACCEPTED,
COMMANDLINE_SERVERQUERYDOCS_PATH,
COMMANDLINE_QUERY_SSH_IP,
COMMANDLINE_QUERY_SSH_PORT,
COMMANDLINE_QUERY_PROTOCOLS,
COMMANDLINE_QUERY_SSH_RSA_HOST_KEY,
COMMANDLINE_QUERY_TIMEOUT,
COMMANDLINE_VERSION,
COMMANDLINE_CRASHDUMPSPATH,
COMMANDLINE_DAEMON,
COMMANDLINE_PID_FILE,
COMMANDLINE_HINTS_ENABLED,
COMMANDLINE_QUERY_HTTP_IP,
COMMANDLINE_QUERY_HTTP_PORT,
COMMANDLINE_QUERY_HTTPS_IP,
COMMANDLINE_QUERY_HTTPS_PORT,
COMMANDLINE_QUERY_HTTPS_CERTIFICATE_FILE,
COMMANDLINE_QUERY_HTTPS_PRIVATE_KEY_FILE,
COMMANDLINE_QUERY_POOL_SIZE,
COMMANDLINE_MMDBPATH,
COMMANDLINE_LOGQUERYTIMINGINTERVAL,
COMMANDLINE_EVENT_TO_DB_LOGGING,
COMMANDLINE_ADMINISTRATIVE_DOMAIN,
COMMANDLINE_LICENSE_ACCEPTED,
COMMANDLINE_SERVERQUERYDOCS_PATH,
COMMANDLINE_QUERY_SSH_IP,
COMMANDLINE_QUERY_SSH_PORT,
COMMANDLINE_QUERY_PROTOCOLS,
COMMANDLINE_QUERY_SSH_RSA_HOST_KEY,
COMMANDLINE_QUERY_TIMEOUT,
COMMANDLINE_VERSION,
COMMANDLINE_CRASHDUMPSPATH,
COMMANDLINE_DAEMON,
COMMANDLINE_PID_FILE,
COMMANDLINE_HINTS_ENABLED,
COMMANDLINE_QUERY_HTTP_IP,
COMMANDLINE_QUERY_HTTP_PORT,
COMMANDLINE_QUERY_HTTPS_IP,
COMMANDLINE_QUERY_HTTPS_PORT,
COMMANDLINE_QUERY_HTTPS_CERTIFICATE_FILE,
COMMANDLINE_QUERY_HTTPS_PRIVATE_KEY_FILE,
COMMANDLINE_QUERY_POOL_SIZE,
COMMANDLINE_MMDBPATH,
COMMANDLINE_LOGQUERYTIMINGINTERVAL,
COMMANDLINE_EVENT_TO_DB_LOGGING,
COMMANDLINE_ADMINISTRATIVE_DOMAIN,
#endif
COMMANDLINE_WEBRTC_SERVER_ENABLED,
COMMANDLINE_WEBRTC_SERVER_ENABLED,
#else
COMMANDLINE_NOTHING = 0,
COMMANDLINE_NOTHING = 0,
#endif
COMMANDLINE_ENDMARKER_RARE,
COMMANDLINE_ENDMARKER_RARE,
};
enum ServerInstancePropertiesRare {
SERVERINSTANCE_DATABASE_VERSION = 0,
SERVERINSTANCE_FILETRANSFER_PORT,
SERVERINSTANCE_SERVER_ENTROPY,
SERVERINSTANCE_MONTHLY_TIMESTAMP,
SERVERINSTANCE_MAX_DOWNLOAD_TOTAL_BANDWIDTH,
SERVERINSTANCE_MAX_UPLOAD_TOTAL_BANDWIDTH,
SERVERINSTANCE_GUEST_SERVERQUERY_GROUP,
SERVERINSTANCE_SERVERQUERY_FLOOD_COMMANDS, //how many commands we can issue while in the SERVERINSTANCE_SERVERQUERY_FLOOD_TIME window
SERVERINSTANCE_SERVERQUERY_FLOOD_TIME, //time window in seconds for max command execution check
SERVERINSTANCE_SERVERQUERY_BAN_TIME, //how many seconds someone get banned if he floods
SERVERINSTANCE_TEMPLATE_SERVERADMIN_GROUP,
SERVERINSTANCE_TEMPLATE_SERVERDEFAULT_GROUP,
SERVERINSTANCE_TEMPLATE_CHANNELADMIN_GROUP,
SERVERINSTANCE_TEMPLATE_CHANNELDEFAULT_GROUP,
SERVERINSTANCE_PERMISSIONS_VERSION,
SERVERINSTANCE_PENDING_CONNECTIONS_PER_IP,
SERVERINSTANCE_SERVERQUERY_MAX_CONNECTIONS_PER_IP,
SERVERINSTANCE_MAX_HOMEBASES, //How many matrix homebase users this instance can have. -1 for no limit
SERVERINSTANCE_ENDMARKER_RARE,
SERVERINSTANCE_DATABASE_VERSION = 0,
SERVERINSTANCE_FILETRANSFER_PORT,
SERVERINSTANCE_SERVER_ENTROPY,
SERVERINSTANCE_MONTHLY_TIMESTAMP,
SERVERINSTANCE_MAX_DOWNLOAD_TOTAL_BANDWIDTH,
SERVERINSTANCE_MAX_UPLOAD_TOTAL_BANDWIDTH,
SERVERINSTANCE_GUEST_SERVERQUERY_GROUP,
SERVERINSTANCE_SERVERQUERY_FLOOD_COMMANDS, // how many commands we can issue
// while in the
// SERVERINSTANCE_SERVERQUERY_FLOOD_TIME
// window
SERVERINSTANCE_SERVERQUERY_FLOOD_TIME, // time window in seconds for max
// command execution check
SERVERINSTANCE_SERVERQUERY_BAN_TIME, // how many seconds someone get banned
// if he floods
SERVERINSTANCE_TEMPLATE_SERVERADMIN_GROUP,
SERVERINSTANCE_TEMPLATE_SERVERDEFAULT_GROUP,
SERVERINSTANCE_TEMPLATE_CHANNELADMIN_GROUP,
SERVERINSTANCE_TEMPLATE_CHANNELDEFAULT_GROUP,
SERVERINSTANCE_PERMISSIONS_VERSION,
SERVERINSTANCE_PENDING_CONNECTIONS_PER_IP,
SERVERINSTANCE_SERVERQUERY_MAX_CONNECTIONS_PER_IP,
SERVERINSTANCE_MAX_HOMEBASES, // How many matrix homebase users this
// instance can have. -1 for no limit
SERVERINSTANCE_ENDMARKER_RARE,
};
enum VirtualServerPropertiesRare {
VIRTUALSERVER_DUMMY_1 = VIRTUALSERVER_ENDMARKER,
VIRTUALSERVER_DUMMY_2,
VIRTUALSERVER_DUMMY_3,
VIRTUALSERVER_DUMMY_4,
VIRTUALSERVER_DUMMY_5,
VIRTUALSERVER_DUMMY_6,
VIRTUALSERVER_DUMMY_7,
VIRTUALSERVER_DUMMY_8,
VIRTUALSERVER_KEYPAIR, //internal use
VIRTUALSERVER_HOSTMESSAGE, //available when connected, not updated while connected
VIRTUALSERVER_HOSTMESSAGE_MODE, //available when connected, not updated while connected
// VIRTUALSERVER_FILEBASE, // Moved to VirtualServerProperties due to SDK usage
VIRTUALSERVER_DEFAULT_SERVER_GROUP = 25, //the client permissions server group that a new client gets assigned
VIRTUALSERVER_DEFAULT_CHANNEL_GROUP, //the channel permissions group that a new client gets assigned when joining a channel
VIRTUALSERVER_FLAG_PASSWORD, //only available on request (=> requestServerVariables)
VIRTUALSERVER_DEFAULT_CHANNEL_ADMIN_GROUP, //the channel permissions group that a client gets assigned when creating a channel
// VIRTUALSERVER_MAX_DOWNLOAD_TOTAL_BANDWIDTH, // Moved to VirtualServerProperties due to SDK usage
// VIRTUALSERVER_MAX_UPLOAD_TOTAL_BANDWIDTH, // Moved to VirtualServerProperties due to SDK usage
VIRTUALSERVER_HOSTBANNER_URL = 31, //available when connected, always up-to-date
VIRTUALSERVER_HOSTBANNER_GFX_URL, //available when connected, always up-to-date
VIRTUALSERVER_HOSTBANNER_GFX_INTERVAL, //available when connected, always up-to-date
VIRTUALSERVER_COMPLAIN_AUTOBAN_COUNT, //only available on request (=> requestServerVariables)
VIRTUALSERVER_COMPLAIN_AUTOBAN_TIME, //only available on request (=> requestServerVariables)
VIRTUALSERVER_COMPLAIN_REMOVE_TIME, //only available on request (=> requestServerVariables)
VIRTUALSERVER_MIN_CLIENTS_IN_CHANNEL_BEFORE_FORCED_SILENCE, //only available on request (=> requestServerVariables)
VIRTUALSERVER_PRIORITY_SPEAKER_DIMM_MODIFICATOR, //available when connected, always up-to-date
VIRTUALSERVER_ID, //available when connected
VIRTUALSERVER_ANTIFLOOD_POINTS_TICK_REDUCE, //only available on request (=> requestServerVariables)
VIRTUALSERVER_ANTIFLOOD_POINTS_NEEDED_COMMAND_BLOCK, //only available on request (=> requestServerVariables)
VIRTUALSERVER_ANTIFLOOD_POINTS_NEEDED_IP_BLOCK, //only available on request (=> requestServerVariables)
VIRTUALSERVER_CLIENT_CONNECTIONS, //only available on request (=> requestServerVariables)
VIRTUALSERVER_QUERY_CLIENT_CONNECTIONS, //only available on request (=> requestServerVariables)
VIRTUALSERVER_HOSTBUTTON_TOOLTIP, //available when connected, always up-to-date
VIRTUALSERVER_HOSTBUTTON_URL, //available when connected, always up-to-date
VIRTUALSERVER_HOSTBUTTON_GFX_URL, //available when connected, always up-to-date
VIRTUALSERVER_QUERYCLIENTS_ONLINE, //only available on request (=> requestServerVariables)
VIRTUALSERVER_DOWNLOAD_QUOTA, //only available on request (=> requestServerVariables)
VIRTUALSERVER_UPLOAD_QUOTA, //only available on request (=> requestServerVariables)
VIRTUALSERVER_MONTH_BYTES_DOWNLOADED, //only available on request (=> requestServerVariables)
VIRTUALSERVER_MONTH_BYTES_UPLOADED, //only available on request (=> requestServerVariables)
VIRTUALSERVER_TOTAL_BYTES_DOWNLOADED, //only available on request (=> requestServerVariables)
VIRTUALSERVER_TOTAL_BYTES_UPLOADED, //only available on request (=> requestServerVariables)
VIRTUALSERVER_PORT, //only available on request (=> requestServerVariables)
VIRTUALSERVER_AUTOSTART, //only available on request (=> requestServerVariables)
VIRTUALSERVER_MACHINE_ID, //only available on request (=> requestServerVariables)
VIRTUALSERVER_NEEDED_IDENTITY_SECURITY_LEVEL, //only available on request (=> requestServerVariables)
VIRTUALSERVER_LOG_CLIENT, //only available on request (=> requestServerVariables)
VIRTUALSERVER_LOG_QUERY, //only available on request (=> requestServerVariables)
VIRTUALSERVER_LOG_CHANNEL, //only available on request (=> requestServerVariables)
VIRTUALSERVER_LOG_PERMISSIONS, //only available on request (=> requestServerVariables)
VIRTUALSERVER_LOG_SERVER, //only available on request (=> requestServerVariables)
// VIRTUALSERVER_LOG_FILETRANSFER, // Moved to VirtualServerProperties due to SDK usage
VIRTUALSERVER_MIN_CLIENT_VERSION = 65, //only available on request (=> requestServerVariables)
VIRTUALSERVER_NAME_PHONETIC, //available when connected, always up-to-date
VIRTUALSERVER_ICON_ID, //available when connected, always up-to-date
VIRTUALSERVER_RESERVED_SLOTS, //available when connected, always up-to-date
VIRTUALSERVER_TOTAL_PACKETLOSS_SPEECH, //only available on request (=> requestServerVariables)
VIRTUALSERVER_TOTAL_PACKETLOSS_KEEPALIVE, //only available on request (=> requestServerVariables)
VIRTUALSERVER_TOTAL_PACKETLOSS_CONTROL, //only available on request (=> requestServerVariables)
VIRTUALSERVER_TOTAL_PACKETLOSS_TOTAL, //only available on request (=> requestServerVariables)
VIRTUALSERVER_TOTAL_PING, //only available on request (=> requestServerVariables)
VIRTUALSERVER_IP, //internal use | contains comma separated ip list
VIRTUALSERVER_WEBLIST_ENABLED, //only available on request (=> requestServerVariables)
VIRTUALSERVER_AUTOGENERATED_PRIVILEGEKEY, //internal use
VIRTUALSERVER_ASK_FOR_PRIVILEGEKEY, //available when connected
VIRTUALSERVER_HOSTBANNER_MODE, //available when connected, always up-to-date
VIRTUALSERVER_CHANNEL_TEMP_DELETE_DELAY_DEFAULT, //available when connected, always up-to-date
VIRTUALSERVER_MIN_ANDROID_VERSION, //only available on request (=> requestServerVariables)
VIRTUALSERVER_MIN_IOS_VERSION, //only available on request (=> requestServerVariables)
VIRTUALSERVER_MIN_WINPHONE_VERSION, //only available on request (=> requestServerVariables)
VIRTUALSERVER_NICKNAME, //available when connected, always up-to-date
VIRTUALSERVER_ACCOUNTING_TOKEN, //internal use | contains base64 encoded token data
VIRTUALSERVER_PROTOCOL_VERIFY_KEYPAIR, //internal use
VIRTUALSERVER_ANTIFLOOD_POINTS_NEEDED_PLUGIN_BLOCK, //only available on request (=> requestServerVariables)
VIRTUALSERVER_CAPABILITY_EXTENSIONS, //available when connected, not updated while connected
VIRTUALSERVER_STORAGE_QUOTA, // Allowed filetransfer storage on this server (including chat attachments) in megabytes
VIRTUALSERVER_WEBRTC_CERTIFICATE, //internal use
VIRTUALSERVER_WEBRTC_PRIVATE_KEY, //internal use
VIRTUALSERVER_UUID, //the uuid of the server (uuid v5 of VIRTUALSERVER_UNIQUE_IDENTIFIER)
VIRTUALSERVER_ADMINISTRATIVE_DOMAIN, //The domain which is responsible for this teamspeak server (which hosts its .well-known file)
VIRTUALSERVER_CANONICAL_NAME, //The canonical name under which the server is reachable
VIRTUALSERVER_MYTSID_CONNECT_ONLY, //Only clients that have a valid mytsid can connect
VIRTUALSERVER_MAX_HOMEBASES, //How many matrix homebases this virtual server supports. -1 = no limit
VIRTUALSERVER_HOMEBASE_STORAGE_QUOTA, // Allowed filetransfer storage for homebase attachments in megabytes
VIRTUALSERVER_ENDMARKER_RARE
VIRTUALSERVER_DUMMY_1 = VIRTUALSERVER_ENDMARKER,
VIRTUALSERVER_DUMMY_2,
VIRTUALSERVER_DUMMY_3,
VIRTUALSERVER_DUMMY_4,
VIRTUALSERVER_DUMMY_5,
VIRTUALSERVER_DUMMY_6,
VIRTUALSERVER_DUMMY_7,
VIRTUALSERVER_DUMMY_8,
VIRTUALSERVER_KEYPAIR, // internal use
VIRTUALSERVER_HOSTMESSAGE, // available when connected, not updated while
// connected
VIRTUALSERVER_HOSTMESSAGE_MODE, // available when connected, not updated
// while connected VIRTUALSERVER_FILEBASE,
//// Moved to VirtualServerProperties due to
// SDK usage
VIRTUALSERVER_DEFAULT_SERVER_GROUP =
25, // the client permissions server group that a new client gets
// assigned
VIRTUALSERVER_DEFAULT_CHANNEL_GROUP, // the channel permissions group that a
// new client gets assigned when
// joining a channel
VIRTUALSERVER_FLAG_PASSWORD, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_DEFAULT_CHANNEL_ADMIN_GROUP, // the channel permissions group
// that a client gets assigned
// when creating a channel
// VIRTUALSERVER_MAX_DOWNLOAD_TOTAL_BANDWIDTH,
//// Moved to
// VirtualServerProperties due to
// SDK usage
// VIRTUALSERVER_MAX_UPLOAD_TOTAL_BANDWIDTH,
//// Moved to
// VirtualServerProperties due to
// SDK usage
VIRTUALSERVER_HOSTBANNER_URL =
31, // available when connected, always up-to-date
VIRTUALSERVER_HOSTBANNER_GFX_URL, // available when connected, always
// up-to-date
VIRTUALSERVER_HOSTBANNER_GFX_INTERVAL, // available when connected, always
// up-to-date
VIRTUALSERVER_COMPLAIN_AUTOBAN_COUNT, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_COMPLAIN_AUTOBAN_TIME, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_COMPLAIN_REMOVE_TIME, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_MIN_CLIENTS_IN_CHANNEL_BEFORE_FORCED_SILENCE, // only
// available on
// request (=>
// requestServerVariables)
VIRTUALSERVER_PRIORITY_SPEAKER_DIMM_MODIFICATOR, // available when
// connected, always
// up-to-date
VIRTUALSERVER_ID, // available when connected
VIRTUALSERVER_ANTIFLOOD_POINTS_TICK_REDUCE, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_ANTIFLOOD_POINTS_NEEDED_COMMAND_BLOCK, // only available on
// request (=>
// requestServerVariables)
VIRTUALSERVER_ANTIFLOOD_POINTS_NEEDED_IP_BLOCK, // only available on request
// (=>
// requestServerVariables)
VIRTUALSERVER_CLIENT_CONNECTIONS, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_QUERY_CLIENT_CONNECTIONS, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_HOSTBUTTON_TOOLTIP, // available when connected, always
// up-to-date
VIRTUALSERVER_HOSTBUTTON_URL, // available when connected, always up-to-date
VIRTUALSERVER_HOSTBUTTON_GFX_URL, // available when connected, always
// up-to-date
VIRTUALSERVER_QUERYCLIENTS_ONLINE, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_DOWNLOAD_QUOTA, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_UPLOAD_QUOTA, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_MONTH_BYTES_DOWNLOADED, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_MONTH_BYTES_UPLOADED, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_TOTAL_BYTES_DOWNLOADED, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_TOTAL_BYTES_UPLOADED, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_PORT, // only available on request (=> requestServerVariables)
VIRTUALSERVER_AUTOSTART, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_MACHINE_ID, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_NEEDED_IDENTITY_SECURITY_LEVEL, // only available on request
// (=> requestServerVariables)
VIRTUALSERVER_LOG_CLIENT, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_LOG_QUERY, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_LOG_CHANNEL, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_LOG_PERMISSIONS, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_LOG_SERVER, // only available on request (=>
// requestServerVariables)
// VIRTUALSERVER_LOG_FILETRANSFER, // Moved to
// VirtualServerProperties due to SDK usage
VIRTUALSERVER_MIN_CLIENT_VERSION =
65, // only available on request (=> requestServerVariables)
VIRTUALSERVER_NAME_PHONETIC, // available when connected, always up-to-date
VIRTUALSERVER_ICON_ID, // available when connected, always up-to-date
VIRTUALSERVER_RESERVED_SLOTS, // available when connected, always up-to-date
VIRTUALSERVER_TOTAL_PACKETLOSS_SPEECH, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_TOTAL_PACKETLOSS_KEEPALIVE, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_TOTAL_PACKETLOSS_CONTROL, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_TOTAL_PACKETLOSS_TOTAL, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_TOTAL_PING, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_IP, // internal use | contains comma separated ip list
VIRTUALSERVER_WEBLIST_ENABLED, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_AUTOGENERATED_PRIVILEGEKEY, // internal use
VIRTUALSERVER_ASK_FOR_PRIVILEGEKEY, // available when connected
VIRTUALSERVER_HOSTBANNER_MODE, // available when connected, always
// up-to-date
VIRTUALSERVER_CHANNEL_TEMP_DELETE_DELAY_DEFAULT, // available when
// connected, always
// up-to-date
VIRTUALSERVER_MIN_ANDROID_VERSION, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_MIN_IOS_VERSION, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_MIN_WINPHONE_VERSION, // only available on request (=>
// requestServerVariables)
VIRTUALSERVER_NICKNAME, // available when connected, always up-to-date
VIRTUALSERVER_ACCOUNTING_TOKEN, // internal use | contains base64 encoded
// token data
VIRTUALSERVER_PROTOCOL_VERIFY_KEYPAIR, // internal use
VIRTUALSERVER_ANTIFLOOD_POINTS_NEEDED_PLUGIN_BLOCK, // only available on
// request (=>
// requestServerVariables)
VIRTUALSERVER_CAPABILITY_EXTENSIONS, // available when connected, not
// updated while connected
VIRTUALSERVER_STORAGE_QUOTA, // Allowed filetransfer storage on this server
// (including chat attachments) in megabytes
VIRTUALSERVER_WEBRTC_CERTIFICATE, // internal use
VIRTUALSERVER_WEBRTC_PRIVATE_KEY, // internal use
VIRTUALSERVER_UUID, // the uuid of the server (uuid v5 of
// VIRTUALSERVER_UNIQUE_IDENTIFIER)
VIRTUALSERVER_ADMINISTRATIVE_DOMAIN, // The domain which is responsible for
// this teamspeak server (which hosts
// its .well-known file)
VIRTUALSERVER_CANONICAL_NAME, // The canonical name under which the server
// is reachable
VIRTUALSERVER_MYTSID_CONNECT_ONLY, // Only clients that have a valid mytsid
// can connect
VIRTUALSERVER_MAX_HOMEBASES, // How many matrix homebases this virtual
// server supports. -1 = no limit
VIRTUALSERVER_HOMEBASE_STORAGE_QUOTA, // Allowed filetransfer storage for
// homebase attachments in megabytes
VIRTUALSERVER_ENDMARKER_RARE
};
enum ChannelPropertiesRare {
CHANNEL_DUMMY_3 = CHANNEL_ENDMARKER,
CHANNEL_DUMMY_4,
CHANNEL_DUMMY_5,
CHANNEL_DUMMY_6,
CHANNEL_DUMMY_7,
CHANNEL_FLAG_MAXCLIENTS_UNLIMITED, //Available for all channels that are "in view", always up-to-date
CHANNEL_FLAG_MAXFAMILYCLIENTS_UNLIMITED, //Available for all channels that are "in view", always up-to-date
CHANNEL_FLAG_MAXFAMILYCLIENTS_INHERITED, //Available for all channels that are "in view", always up-to-date
CHANNEL_FLAG_ARE_SUBSCRIBED, //Only available client side, stores whether we are subscribed to this channel
CHANNEL_FILEPATH, //not available client side, the folder used for file-transfers for this channel
CHANNEL_NEEDED_TALK_POWER, //Available for all channels that are "in view", always up-to-date
CHANNEL_FORCED_SILENCE, //Available for all channels that are "in view", always up-to-date
CHANNEL_NAME_PHONETIC, //Available for all channels that are "in view", always up-to-date
CHANNEL_ICON_ID, //Available for all channels that are "in view", always up-to-date
CHANNEL_BANNER_GFX_URL, //Available for all channels that are "in view", always up-to-date
CHANNEL_BANNER_MODE, //Available for all channels that are "in view", always up-to-date
CHANNEL_PERMISSION_HINTS,
CHANNEL_STORAGE_QUOTA, // Storage space that is allowed to be used by this channels files (in MiB)
CHANNEL_ENDMARKER_RARE,
CHANNEL_DELETE_DELAY_DEADLINE = 127 //(for clientlibv2) expected delete time in monotonic clock seconds or 0 if nothing is expected
CHANNEL_DUMMY_3 = CHANNEL_ENDMARKER,
CHANNEL_DUMMY_4,
CHANNEL_DUMMY_5,
CHANNEL_DUMMY_6,
CHANNEL_DUMMY_7,
CHANNEL_FLAG_MAXCLIENTS_UNLIMITED, // Available for all channels that are
// "in view", always up-to-date
CHANNEL_FLAG_MAXFAMILYCLIENTS_UNLIMITED, // Available for all channels that
// are "in view", always up-to-date
CHANNEL_FLAG_MAXFAMILYCLIENTS_INHERITED, // Available for all channels that
// are "in view", always up-to-date
CHANNEL_FLAG_ARE_SUBSCRIBED, // Only available client side, stores whether
// we are subscribed to this channel
CHANNEL_FILEPATH, // not available client side, the folder used for
// file-transfers for this channel
CHANNEL_NEEDED_TALK_POWER, // Available for all channels that are "in view",
// always up-to-date
CHANNEL_FORCED_SILENCE, // Available for all channels that are "in view",
// always up-to-date
CHANNEL_NAME_PHONETIC, // Available for all channels that are "in view",
// always up-to-date
CHANNEL_ICON_ID, // Available for all channels that are "in view", always
// up-to-date
CHANNEL_BANNER_GFX_URL, // Available for all channels that are "in view",
// always up-to-date
CHANNEL_BANNER_MODE, // Available for all channels that are "in view",
// always up-to-date
CHANNEL_PERMISSION_HINTS,
CHANNEL_STORAGE_QUOTA, // Storage space that is allowed to be used by this
// channels files (in MiB)
CHANNEL_ENDMARKER_RARE,
CHANNEL_DELETE_DELAY_DEADLINE =
127 //(for clientlibv2) expected delete time in monotonic clock seconds
// or 0 if nothing is expected
};
enum ClientPropertiesRare {
CLIENT_DUMMY_4 = CLIENT_ENDMARKER,
CLIENT_DUMMY_5,
CLIENT_DUMMY_6,
CLIENT_DUMMY_7,
CLIENT_DUMMY_8,
CLIENT_DUMMY_9,
CLIENT_KEY_OFFSET, //internal use
CLIENT_LAST_VAR_REQUEST, //internal use
CLIENT_LOGIN_NAME, //used for serverquery clients, makes no sense on normal clients currently
CLIENT_LOGIN_PASSWORD, //used for serverquery clients, makes no sense on normal clients currently
CLIENT_DATABASE_ID, //automatically up-to-date for any client "in view", only valid with PERMISSION feature, holds database client id
CLIENT_CHANNEL_GROUP_ID, //automatically up-to-date for any client "in view", only valid with PERMISSION feature, holds database client id
CLIENT_SERVERGROUPS, //automatically up-to-date for any client "in view", only valid with PERMISSION feature, holds all servergroups client belongs too
CLIENT_CREATED, //this needs to be requested (=> requestClientVariables), first time this client connected to this server
CLIENT_LASTCONNECTED, //this needs to be requested (=> requestClientVariables), last time this client connected to this server
CLIENT_TOTALCONNECTIONS, //this needs to be requested (=> requestClientVariables), how many times this client connected to this server
CLIENT_AWAY, //automatically up-to-date for any client "in view", this clients away status
CLIENT_AWAY_MESSAGE, //automatically up-to-date for any client "in view", this clients away message
CLIENT_TYPE, //automatically up-to-date for any client "in view", determines if this is a real client or a server-query connection
CLIENT_FLAG_AVATAR, //automatically up-to-date for any client "in view", this client got an avatar
CLIENT_TALK_POWER, //automatically up-to-date for any client "in view", only valid with PERMISSION feature, holds database client id
CLIENT_TALK_REQUEST, //automatically up-to-date for any client "in view", only valid with PERMISSION feature, holds timestamp where client requested to talk
CLIENT_TALK_REQUEST_MSG, //automatically up-to-date for any client "in view", only valid with PERMISSION feature, holds matter for the request
CLIENT_DESCRIPTION, //automatically up-to-date for any client "in view"
CLIENT_IS_TALKER, //automatically up-to-date for any client "in view"
CLIENT_MONTH_BYTES_UPLOADED, //this needs to be requested (=> requestClientVariables)
CLIENT_MONTH_BYTES_DOWNLOADED, //this needs to be requested (=> requestClientVariables)
CLIENT_TOTAL_BYTES_UPLOADED, //this needs to be requested (=> requestClientVariables)
CLIENT_TOTAL_BYTES_DOWNLOADED, //this needs to be requested (=> requestClientVariables)
CLIENT_IS_PRIORITY_SPEAKER, //automatically up-to-date for any client "in view"
CLIENT_UNREAD_MESSAGES, //automatically up-to-date for any client "in view"
CLIENT_NICKNAME_PHONETIC, //automatically up-to-date for any client "in view"
CLIENT_NEEDED_SERVERQUERY_VIEW_POWER, //automatically up-to-date for any client "in view"
CLIENT_DEFAULT_TOKEN, //only usable for ourself, the default token we used to connect on our last connection attempt
CLIENT_ICON_ID, //automatically up-to-date for any client "in view"
CLIENT_IS_CHANNEL_COMMANDER, //automatically up-to-date for any client "in view"
CLIENT_COUNTRY, //automatically up-to-date for any client "in view"
CLIENT_CHANNEL_GROUP_INHERITED_CHANNEL_ID, //automatically up-to-date for any client "in view", only valid with PERMISSION feature, contains channel_id where the channel_group_id is set from
CLIENT_BADGES, //automatically up-to-date for any client "in view", stores icons for partner badges
CLIENT_MYTEAMSPEAK_ID, //automatically up-to-date for any client "in view", stores myteamspeak id
CLIENT_INTEGRATIONS, //automatically up-to-date for any client "in view", stores integrations
CLIENT_ACTIVE_INTEGRATIONS_INFO, //stores info from the myts server and contains the subscription info
CLIENT_MYTS_AVATAR,
CLIENT_SIGNED_BADGES,
CLIENT_PERMISSION_HINTS,
CLIENT_USER_TAG, //automatically up-to-date for any client "in view", stores public chat user tag
CLIENT_ENDMARKER_RARE,
CLIENT_HW_ID = 127 //(for clientlibv2) unique hardware id
CLIENT_DUMMY_4 = CLIENT_ENDMARKER,
CLIENT_DUMMY_5,
CLIENT_DUMMY_6,
CLIENT_DUMMY_7,
CLIENT_DUMMY_8,
CLIENT_DUMMY_9,
CLIENT_KEY_OFFSET, // internal use
CLIENT_LAST_VAR_REQUEST, // internal use
CLIENT_LOGIN_NAME, // used for serverquery clients, makes no sense on normal
// clients currently
CLIENT_LOGIN_PASSWORD, // used for serverquery clients, makes no sense on
// normal clients currently
CLIENT_DATABASE_ID, // automatically up-to-date for any client "in view",
// only valid with PERMISSION feature, holds database
// client id
CLIENT_CHANNEL_GROUP_ID, // automatically up-to-date for any client "in
// view", only valid with PERMISSION feature, holds
// database client id
CLIENT_SERVERGROUPS, // automatically up-to-date for any client "in view",
// only valid with PERMISSION feature, holds all
// servergroups client belongs too
CLIENT_CREATED, // this needs to be requested (=> requestClientVariables),
// first time this client connected to this server
CLIENT_LASTCONNECTED, // this needs to be requested (=>
// requestClientVariables), last time this client
// connected to this server
CLIENT_TOTALCONNECTIONS, // this needs to be requested (=>
// requestClientVariables), how many times this
// client connected to this server
CLIENT_AWAY, // automatically up-to-date for any client "in view", this
// clients away status
CLIENT_AWAY_MESSAGE, // automatically up-to-date for any client "in view",
// this clients away message
CLIENT_TYPE, // automatically up-to-date for any client "in view",
// determines if this is a real client or a server-query
// connection
CLIENT_FLAG_AVATAR, // automatically up-to-date for any client "in view",
// this client got an avatar
CLIENT_TALK_POWER, // automatically up-to-date for any client "in view",
// only valid with PERMISSION feature, holds database
// client id
CLIENT_TALK_REQUEST, // automatically up-to-date for any client "in view",
// only valid with PERMISSION feature, holds timestamp
// where client requested to talk
CLIENT_TALK_REQUEST_MSG, // automatically up-to-date for any client "in
// view", only valid with PERMISSION feature, holds
// matter for the request
CLIENT_DESCRIPTION, // automatically up-to-date for any client "in view"
CLIENT_IS_TALKER, // automatically up-to-date for any client "in view"
CLIENT_MONTH_BYTES_UPLOADED, // this needs to be requested (=>
// requestClientVariables)
CLIENT_MONTH_BYTES_DOWNLOADED, // this needs to be requested (=>
// requestClientVariables)
CLIENT_TOTAL_BYTES_UPLOADED, // this needs to be requested (=>
// requestClientVariables)
CLIENT_TOTAL_BYTES_DOWNLOADED, // this needs to be requested (=>
// requestClientVariables)
CLIENT_IS_PRIORITY_SPEAKER, // automatically up-to-date for any client "in
// view"
CLIENT_UNREAD_MESSAGES, // automatically up-to-date for any client "in view"
CLIENT_NICKNAME_PHONETIC, // automatically up-to-date for any client "in
// view"
CLIENT_NEEDED_SERVERQUERY_VIEW_POWER, // automatically up-to-date for any
// client "in view"
CLIENT_DEFAULT_TOKEN, // only usable for ourself, the default token we used
// to connect on our last connection attempt
CLIENT_ICON_ID, // automatically up-to-date for any client "in view"
CLIENT_IS_CHANNEL_COMMANDER, // automatically up-to-date for any client "in
// view"
CLIENT_COUNTRY, // automatically up-to-date for any client "in view"
CLIENT_CHANNEL_GROUP_INHERITED_CHANNEL_ID, // automatically up-to-date for
// any client "in view", only
// valid with PERMISSION feature,
// contains channel_id where the
// channel_group_id is set from
CLIENT_BADGES, // automatically up-to-date for any client "in view", stores
// icons for partner badges
CLIENT_MYTEAMSPEAK_ID, // automatically up-to-date for any client "in view",
// stores myteamspeak id
CLIENT_INTEGRATIONS, // automatically up-to-date for any client "in view",
// stores integrations
CLIENT_ACTIVE_INTEGRATIONS_INFO, // stores info from the myts server and
// contains the subscription info
CLIENT_MYTS_AVATAR,
CLIENT_SIGNED_BADGES,
CLIENT_PERMISSION_HINTS,
CLIENT_USER_TAG, // automatically up-to-date for any client "in view",
// stores public chat user tag
CLIENT_ENDMARKER_RARE,
CLIENT_HW_ID = 127 //(for clientlibv2) unique hardware id
};
enum BBCodeTags {
BBCodeTag_B = 0x00000001,
BBCodeTag_I = 0x00000002,
BBCodeTag_U = 0x00000004,
BBCodeTag_S = 0x00000008,
BBCodeTag_SUP = 0x00000010,
BBCodeTag_SUB = 0x00000020,
BBCodeTag_COLOR = 0x00000040,
BBCodeTag_SIZE = 0x00000080,
BBCodeTag_group_text = 0x000000FF,
BBCodeTag_B = 0x00000001,
BBCodeTag_I = 0x00000002,
BBCodeTag_U = 0x00000004,
BBCodeTag_S = 0x00000008,
BBCodeTag_SUP = 0x00000010,
BBCodeTag_SUB = 0x00000020,
BBCodeTag_COLOR = 0x00000040,
BBCodeTag_SIZE = 0x00000080,
BBCodeTag_group_text = 0x000000FF,
BBCodeTag_LEFT = 0x00001000,
BBCodeTag_RIGHT = 0x00002000,
BBCodeTag_CENTER = 0x00004000,
BBCodeTag_group_align = 0x00007000,
BBCodeTag_LEFT = 0x00001000,
BBCodeTag_RIGHT = 0x00002000,
BBCodeTag_CENTER = 0x00004000,
BBCodeTag_group_align = 0x00007000,
BBCodeTag_URL = 0x00010000,
BBCodeTag_IMAGE = 0x00020000,
BBCodeTag_HR = 0x00040000,
BBCodeTag_URL = 0x00010000,
BBCodeTag_IMAGE = 0x00020000,
BBCodeTag_HR = 0x00040000,
BBCodeTag_LIST = 0x00100000,
BBCodeTag_LISTITEM = 0x00200000,
BBCodeTag_group_list = 0x00300000,
BBCodeTag_LIST = 0x00100000,
BBCodeTag_LISTITEM = 0x00200000,
BBCodeTag_group_list = 0x00300000,
BBCodeTag_TABLE = 0x00400000,
BBCodeTag_TR = 0x00800000,
BBCodeTag_TH = 0x01000000,
BBCodeTag_TD = 0x02000000,
BBCodeTag_group_table = 0x03C00000,
BBCodeTag_TABLE = 0x00400000,
BBCodeTag_TR = 0x00800000,
BBCodeTag_TH = 0x01000000,
BBCodeTag_TD = 0x02000000,
BBCodeTag_group_table = 0x03C00000,
BBCodeTag_def_simple = BBCodeTag_B | BBCodeTag_I | BBCodeTag_U | BBCodeTag_S | BBCodeTag_SUP | BBCodeTag_SUB | BBCodeTag_COLOR | BBCodeTag_URL,
BBCodeTag_def_simple_Img = BBCodeTag_def_simple | BBCodeTag_IMAGE,
BBCodeTag_def_extended = BBCodeTag_group_text | BBCodeTag_group_align | BBCodeTag_URL | BBCodeTag_IMAGE | BBCodeTag_HR | BBCodeTag_group_list | BBCodeTag_group_table,
BBCodeTag_def_simple = BBCodeTag_B | BBCodeTag_I | BBCodeTag_U |
BBCodeTag_S | BBCodeTag_SUP | BBCodeTag_SUB |
BBCodeTag_COLOR | BBCodeTag_URL,
BBCodeTag_def_simple_Img = BBCodeTag_def_simple | BBCodeTag_IMAGE,
BBCodeTag_def_extended = BBCodeTag_group_text | BBCodeTag_group_align |
BBCodeTag_URL | BBCodeTag_IMAGE | BBCodeTag_HR |
BBCodeTag_group_list | BBCodeTag_group_table,
};
enum LicenseIssue { Blacklisted = 0, Greylisted };
enum MytsDataUnsetFlags {
MytsDataUnsetFlag_None = 0,
MytsDataUnsetFlag_Badges = 1,
MytsDataUnsetFlag_Avatar = 1 << 1,
MytsDataUnsetFlag_None = 0,
MytsDataUnsetFlag_Badges = 1,
MytsDataUnsetFlag_Avatar = 1 << 1,
MytsDataUnsetFlag_All = MytsDataUnsetFlag_Badges | MytsDataUnsetFlag_Avatar // make sure "all" really contains all flags
MytsDataUnsetFlag_All =
MytsDataUnsetFlag_Badges |
MytsDataUnsetFlag_Avatar // make sure "all" really contains all flags
};
typedef int (*ExtraBBCodeValidator)(void* userparam, const char* tag, const char* paramValue, int paramValueSize, const char* childValue, int childValueSize);
typedef const char* (*ExtraBBCodeParamTransform)(void* userparam, const char* tag, const char* paramValue);
typedef int (*ExtraBBCodeValidator)(void* userparam, const char* tag,
const char* paramValue, int paramValueSize,
const char* childValue, int childValueSize);
typedef const char* (*ExtraBBCodeParamTransform)(void* userparam,
const char* tag,
const char* paramValue);
#endif //PUBLIC_RARE_DEFINITIONS_H
#endif // PUBLIC_RARE_DEFINITIONS_H
+652 -263
View File
@@ -10,299 +10,688 @@ extern "C" {
/* Functions exported to plugin from main binary */
struct TS3Functions {
unsigned int (*getClientLibVersion)(char** result);
unsigned int (*getClientLibVersionNumber)(uint64* result);
unsigned int (*spawnNewServerConnectionHandler)(int port, uint64* result);
unsigned int (*destroyServerConnectionHandler)(uint64 serverConnectionHandlerID);
unsigned int (*getClientLibVersion)(char** result);
unsigned int (*getClientLibVersionNumber)(uint64* result);
unsigned int (*spawnNewServerConnectionHandler)(int port,
uint64* result);
unsigned int (*destroyServerConnectionHandler)(
uint64 serverConnectionHandlerID);
/* Error handling */
unsigned int (*getErrorMessage)(unsigned int errorCode, char** error);
/* Error handling */
unsigned int (*getErrorMessage)(unsigned int errorCode, char** error);
/* Memory management */
unsigned int (*freeMemory)(void* pointer);
/* Memory management */
unsigned int (*freeMemory)(void* pointer);
/* Logging */
unsigned int (*logMessage)(const char* logMessage, enum LogLevel severity, const char* channel, uint64 logID);
/* Logging */
unsigned int (*logMessage)(const char* logMessage,
enum LogLevel severity, const char* channel,
uint64 logID);
/* Sound */
unsigned int (*getPlaybackDeviceList)(const char* modeID, char**** result);
unsigned int (*getPlaybackModeList)(char*** result);
unsigned int (*getCaptureDeviceList)(const char* modeID, char**** result);
unsigned int (*getCaptureModeList)(char*** result);
unsigned int (*getDefaultPlaybackDevice)(const char* modeID, char*** result);
unsigned int (*getDefaultPlayBackMode)(char** result);
unsigned int (*getDefaultCaptureDevice)(const char* modeID, char*** result);
unsigned int (*getDefaultCaptureMode)(char** result);
unsigned int (*openPlaybackDevice)(uint64 serverConnectionHandlerID, const char* modeID, const char* playbackDevice);
unsigned int (*openCaptureDevice)(uint64 serverConnectionHandlerID, const char* modeID, const char* captureDevice);
unsigned int (*getCurrentPlaybackDeviceName)(uint64 serverConnectionHandlerID, char** result, int* isDefault);
unsigned int (*getCurrentPlayBackMode)(uint64 serverConnectionHandlerID, char** result);
unsigned int (*getCurrentCaptureDeviceName)(uint64 serverConnectionHandlerID, char** result, int* isDefault);
unsigned int (*getCurrentCaptureMode)(uint64 serverConnectionHandlerID, char** result);
unsigned int (*initiateGracefulPlaybackShutdown)(uint64 serverConnectionHandlerID);
unsigned int (*closePlaybackDevice)(uint64 serverConnectionHandlerID);
unsigned int (*closeCaptureDevice)(uint64 serverConnectionHandlerID);
unsigned int (*activateCaptureDevice)(uint64 serverConnectionHandlerID);
unsigned int (*playWaveFileHandle)(uint64 serverConnectionHandlerID, const char* path, int loop, uint64* waveHandle);
unsigned int (*pauseWaveFileHandle)(uint64 serverConnectionHandlerID, uint64 waveHandle, int pause);
unsigned int (*closeWaveFileHandle)(uint64 serverConnectionHandlerID, uint64 waveHandle);
unsigned int (*playWaveFile)(uint64 serverConnectionHandlerID, const char* path);
unsigned int (*registerCustomDevice)(const char* deviceID, const char* deviceDisplayName, int capFrequency, int capChannels, int playFrequency, int playChannels);
unsigned int (*unregisterCustomDevice)(const char* deviceID);
unsigned int (*processCustomCaptureData)(const char* deviceName, const short* buffer, int samples);
unsigned int (*acquireCustomPlaybackData)(const char* deviceName, short* buffer, int samples);
/* Sound */
unsigned int (*getPlaybackDeviceList)(const char* modeID,
char**** result);
unsigned int (*getPlaybackModeList)(char*** result);
unsigned int (*getCaptureDeviceList)(const char* modeID,
char**** result);
unsigned int (*getCaptureModeList)(char*** result);
unsigned int (*getDefaultPlaybackDevice)(const char* modeID,
char*** result);
unsigned int (*getDefaultPlayBackMode)(char** result);
unsigned int (*getDefaultCaptureDevice)(const char* modeID,
char*** result);
unsigned int (*getDefaultCaptureMode)(char** result);
unsigned int (*openPlaybackDevice)(uint64 serverConnectionHandlerID,
const char* modeID,
const char* playbackDevice);
unsigned int (*openCaptureDevice)(uint64 serverConnectionHandlerID,
const char* modeID,
const char* captureDevice);
unsigned int (*getCurrentPlaybackDeviceName)(
uint64 serverConnectionHandlerID, char** result, int* isDefault);
unsigned int (*getCurrentPlayBackMode)(uint64 serverConnectionHandlerID,
char** result);
unsigned int (*getCurrentCaptureDeviceName)(
uint64 serverConnectionHandlerID, char** result, int* isDefault);
unsigned int (*getCurrentCaptureMode)(uint64 serverConnectionHandlerID,
char** result);
unsigned int (*initiateGracefulPlaybackShutdown)(
uint64 serverConnectionHandlerID);
unsigned int (*closePlaybackDevice)(uint64 serverConnectionHandlerID);
unsigned int (*closeCaptureDevice)(uint64 serverConnectionHandlerID);
unsigned int (*activateCaptureDevice)(uint64 serverConnectionHandlerID);
unsigned int (*playWaveFileHandle)(uint64 serverConnectionHandlerID,
const char* path, int loop,
uint64* waveHandle);
unsigned int (*pauseWaveFileHandle)(uint64 serverConnectionHandlerID,
uint64 waveHandle, int pause);
unsigned int (*closeWaveFileHandle)(uint64 serverConnectionHandlerID,
uint64 waveHandle);
unsigned int (*playWaveFile)(uint64 serverConnectionHandlerID,
const char* path);
unsigned int (*registerCustomDevice)(const char* deviceID,
const char* deviceDisplayName,
int capFrequency, int capChannels,
int playFrequency,
int playChannels);
unsigned int (*unregisterCustomDevice)(const char* deviceID);
unsigned int (*processCustomCaptureData)(const char* deviceName,
const short* buffer,
int samples);
unsigned int (*acquireCustomPlaybackData)(const char* deviceName,
short* buffer, int samples);
/* Preprocessor */
unsigned int (*getPreProcessorInfoValueFloat)(uint64 serverConnectionHandlerID, const char* ident, float* result);
unsigned int (*getPreProcessorConfigValue)(uint64 serverConnectionHandlerID, const char* ident, char** result);
unsigned int (*setPreProcessorConfigValue)(uint64 serverConnectionHandlerID, const char* ident, const char* value);
/* Preprocessor */
unsigned int (*getPreProcessorInfoValueFloat)(
uint64 serverConnectionHandlerID, const char* ident, float* result);
unsigned int (*getPreProcessorConfigValue)(
uint64 serverConnectionHandlerID, const char* ident, char** result);
unsigned int (*setPreProcessorConfigValue)(
uint64 serverConnectionHandlerID, const char* ident,
const char* value);
/* Encoder */
unsigned int (*getEncodeConfigValue)(uint64 serverConnectionHandlerID, const char* ident, char** result);
/* Encoder */
unsigned int (*getEncodeConfigValue)(uint64 serverConnectionHandlerID,
const char* ident, char** result);
/* Playback */
unsigned int (*getPlaybackConfigValueAsFloat)(uint64 serverConnectionHandlerID, const char* ident, float* result);
unsigned int (*setPlaybackConfigValue)(uint64 serverConnectionHandlerID, const char* ident, const char* value);
unsigned int (*setClientVolumeModifier)(uint64 serverConnectionHandlerID, anyID clientID, float value);
/* Playback */
unsigned int (*getPlaybackConfigValueAsFloat)(
uint64 serverConnectionHandlerID, const char* ident, float* result);
unsigned int (*setPlaybackConfigValue)(uint64 serverConnectionHandlerID,
const char* ident,
const char* value);
unsigned int (*setClientVolumeModifier)(
uint64 serverConnectionHandlerID, anyID clientID, float value);
/* Recording status */
unsigned int (*startVoiceRecording)(uint64 serverConnectionHandlerID);
unsigned int (*stopVoiceRecording)(uint64 serverConnectionHandlerID);
/* Recording status */
unsigned int (*startVoiceRecording)(uint64 serverConnectionHandlerID);
unsigned int (*stopVoiceRecording)(uint64 serverConnectionHandlerID);
/* 3d sound positioning */
unsigned int (*systemset3DListenerAttributes)(uint64 serverConnectionHandlerID, const TS3_VECTOR* position, const TS3_VECTOR* forward, const TS3_VECTOR* up);
unsigned int (*set3DWaveAttributes)(uint64 serverConnectionHandlerID, uint64 waveHandle, const TS3_VECTOR* position);
unsigned int (*systemset3DSettings)(uint64 serverConnectionHandlerID, float distanceFactor, float rolloffScale);
unsigned int (*channelset3DAttributes)(uint64 serverConnectionHandlerID, anyID clientID, const TS3_VECTOR* position);
/* 3d sound positioning */
unsigned int (*systemset3DListenerAttributes)(
uint64 serverConnectionHandlerID, const TS3_VECTOR* position,
const TS3_VECTOR* forward, const TS3_VECTOR* up);
unsigned int (*set3DWaveAttributes)(uint64 serverConnectionHandlerID,
uint64 waveHandle,
const TS3_VECTOR* position);
unsigned int (*systemset3DSettings)(uint64 serverConnectionHandlerID,
float distanceFactor,
float rolloffScale);
unsigned int (*channelset3DAttributes)(uint64 serverConnectionHandlerID,
anyID clientID,
const TS3_VECTOR* position);
/* Interaction with the server */
unsigned int (*startConnection)(uint64 serverConnectionHandlerID, const char* identity, const char* ip, unsigned int port, const char* nickname, const char** defaultChannelArray, const char* defaultChannelPassword, const char* serverPassword);
unsigned int (*stopConnection)(uint64 serverConnectionHandlerID, const char* quitMessage);
unsigned int (*requestClientMove)(uint64 serverConnectionHandlerID, anyID clientID, uint64 newChannelID, const char* password, const char* returnCode);
unsigned int (*requestClientVariables)(uint64 serverConnectionHandlerID, anyID clientID, const char* returnCode);
unsigned int (*requestClientKickFromChannel)(uint64 serverConnectionHandlerID, anyID clientID, const char* kickReason, const char* returnCode);
unsigned int (*requestClientKickFromServer)(uint64 serverConnectionHandlerID, anyID clientID, const char* kickReason, const char* returnCode);
unsigned int (*requestChannelDelete)(uint64 serverConnectionHandlerID, uint64 channelID, int force, const char* returnCode);
unsigned int (*requestChannelMove)(uint64 serverConnectionHandlerID, uint64 channelID, uint64 newChannelParentID, uint64 newChannelOrder, const char* returnCode);
unsigned int (*requestSendPrivateTextMsg)(uint64 serverConnectionHandlerID, const char* message, anyID targetClientID, const char* returnCode);
unsigned int (*requestSendChannelTextMsg)(uint64 serverConnectionHandlerID, const char* message, uint64 targetChannelID, const char* returnCode);
unsigned int (*requestSendServerTextMsg)(uint64 serverConnectionHandlerID, const char* message, const char* returnCode);
unsigned int (*requestConnectionInfo)(uint64 serverConnectionHandlerID, anyID clientID, const char* returnCode);
unsigned int (*requestClientSetWhisperList)(uint64 serverConnectionHandlerID, anyID clientID, const uint64* targetChannelIDArray, const anyID* targetClientIDArray, const char* returnCode);
unsigned int (*requestChannelSubscribe)(uint64 serverConnectionHandlerID, const uint64* channelIDArray, const char* returnCode);
unsigned int (*requestChannelSubscribeAll)(uint64 serverConnectionHandlerID, const char* returnCode);
unsigned int (*requestChannelUnsubscribe)(uint64 serverConnectionHandlerID, const uint64* channelIDArray, const char* returnCode);
unsigned int (*requestChannelUnsubscribeAll)(uint64 serverConnectionHandlerID, const char* returnCode);
unsigned int (*requestChannelDescription)(uint64 serverConnectionHandlerID, uint64 channelID, const char* returnCode);
unsigned int (*requestMuteClients)(uint64 serverConnectionHandlerID, const anyID* clientIDArray, const char* returnCode);
unsigned int (*requestUnmuteClients)(uint64 serverConnectionHandlerID, const anyID* clientIDArray, const char* returnCode);
unsigned int (*requestClientPoke)(uint64 serverConnectionHandlerID, anyID clientID, const char* message, const char* returnCode);
unsigned int (*requestClientIDs)(uint64 serverConnectionHandlerID, const char* clientUniqueIdentifier, const char* returnCode);
unsigned int (*clientChatClosed)(uint64 serverConnectionHandlerID, const char* clientUniqueIdentifier, anyID clientID, const char* returnCode);
unsigned int (*clientChatComposing)(uint64 serverConnectionHandlerID, anyID clientID, const char* returnCode);
unsigned int (*requestServerTemporaryPasswordAdd)(uint64 serverConnectionHandlerID, const char* password, const char* description, uint64 duration, uint64 targetChannelID, const char* targetChannelPW, const char* returnCode);
unsigned int (*requestServerTemporaryPasswordDel)(uint64 serverConnectionHandlerID, const char* password, const char* returnCode);
unsigned int (*requestServerTemporaryPasswordList)(uint64 serverConnectionHandlerID, const char* returnCode);
/* Interaction with the server */
unsigned int (*startConnection)(uint64 serverConnectionHandlerID,
const char* identity, const char* ip,
unsigned int port, const char* nickname,
const char** defaultChannelArray,
const char* defaultChannelPassword,
const char* serverPassword);
unsigned int (*stopConnection)(uint64 serverConnectionHandlerID,
const char* quitMessage);
unsigned int (*requestClientMove)(uint64 serverConnectionHandlerID,
anyID clientID, uint64 newChannelID,
const char* password,
const char* returnCode);
unsigned int (*requestClientVariables)(uint64 serverConnectionHandlerID,
anyID clientID,
const char* returnCode);
unsigned int (*requestClientKickFromChannel)(
uint64 serverConnectionHandlerID, anyID clientID,
const char* kickReason, const char* returnCode);
unsigned int (*requestClientKickFromServer)(
uint64 serverConnectionHandlerID, anyID clientID,
const char* kickReason, const char* returnCode);
unsigned int (*requestChannelDelete)(uint64 serverConnectionHandlerID,
uint64 channelID, int force,
const char* returnCode);
unsigned int (*requestChannelMove)(uint64 serverConnectionHandlerID,
uint64 channelID,
uint64 newChannelParentID,
uint64 newChannelOrder,
const char* returnCode);
unsigned int (*requestSendPrivateTextMsg)(
uint64 serverConnectionHandlerID, const char* message,
anyID targetClientID, const char* returnCode);
unsigned int (*requestSendChannelTextMsg)(
uint64 serverConnectionHandlerID, const char* message,
uint64 targetChannelID, const char* returnCode);
unsigned int (*requestSendServerTextMsg)(
uint64 serverConnectionHandlerID, const char* message,
const char* returnCode);
unsigned int (*requestConnectionInfo)(uint64 serverConnectionHandlerID,
anyID clientID,
const char* returnCode);
unsigned int (*requestClientSetWhisperList)(
uint64 serverConnectionHandlerID, anyID clientID,
const uint64* targetChannelIDArray,
const anyID* targetClientIDArray, const char* returnCode);
unsigned int (*requestChannelSubscribe)(
uint64 serverConnectionHandlerID, const uint64* channelIDArray,
const char* returnCode);
unsigned int (*requestChannelSubscribeAll)(
uint64 serverConnectionHandlerID, const char* returnCode);
unsigned int (*requestChannelUnsubscribe)(
uint64 serverConnectionHandlerID, const uint64* channelIDArray,
const char* returnCode);
unsigned int (*requestChannelUnsubscribeAll)(
uint64 serverConnectionHandlerID, const char* returnCode);
unsigned int (*requestChannelDescription)(
uint64 serverConnectionHandlerID, uint64 channelID,
const char* returnCode);
unsigned int (*requestMuteClients)(uint64 serverConnectionHandlerID,
const anyID* clientIDArray,
const char* returnCode);
unsigned int (*requestUnmuteClients)(uint64 serverConnectionHandlerID,
const anyID* clientIDArray,
const char* returnCode);
unsigned int (*requestClientPoke)(uint64 serverConnectionHandlerID,
anyID clientID, const char* message,
const char* returnCode);
unsigned int (*requestClientIDs)(uint64 serverConnectionHandlerID,
const char* clientUniqueIdentifier,
const char* returnCode);
unsigned int (*clientChatClosed)(uint64 serverConnectionHandlerID,
const char* clientUniqueIdentifier,
anyID clientID,
const char* returnCode);
unsigned int (*clientChatComposing)(uint64 serverConnectionHandlerID,
anyID clientID,
const char* returnCode);
unsigned int (*requestServerTemporaryPasswordAdd)(
uint64 serverConnectionHandlerID, const char* password,
const char* description, uint64 duration, uint64 targetChannelID,
const char* targetChannelPW, const char* returnCode);
unsigned int (*requestServerTemporaryPasswordDel)(
uint64 serverConnectionHandlerID, const char* password,
const char* returnCode);
unsigned int (*requestServerTemporaryPasswordList)(
uint64 serverConnectionHandlerID, const char* returnCode);
/* Access clientlib information */
/* Access clientlib information */
/* Query own client ID */
unsigned int (*getClientID)(uint64 serverConnectionHandlerID, anyID* result);
/* Query own client ID */
unsigned int (*getClientID)(uint64 serverConnectionHandlerID,
anyID* result);
/* Client info */
unsigned int (*getClientSelfVariableAsInt)(uint64 serverConnectionHandlerID, size_t flag, int* result);
unsigned int (*getClientSelfVariableAsString)(uint64 serverConnectionHandlerID, size_t flag, char** result);
unsigned int (*setClientSelfVariableAsInt)(uint64 serverConnectionHandlerID, size_t flag, int value);
unsigned int (*setClientSelfVariableAsString)(uint64 serverConnectionHandlerID, size_t flag, const char* value);
unsigned int (*flushClientSelfUpdates)(uint64 serverConnectionHandlerID, const char* returnCode);
unsigned int (*getClientVariableAsInt)(uint64 serverConnectionHandlerID, anyID clientID, size_t flag, int* result);
unsigned int (*getClientVariableAsUInt64)(uint64 serverConnectionHandlerID, anyID clientID, size_t flag, uint64* result);
unsigned int (*getClientVariableAsString)(uint64 serverConnectionHandlerID, anyID clientID, size_t flag, char** result);
unsigned int (*getClientList)(uint64 serverConnectionHandlerID, anyID** result);
unsigned int (*getChannelOfClient)(uint64 serverConnectionHandlerID, anyID clientID, uint64* result);
/* Client info */
unsigned int (*getClientSelfVariableAsInt)(
uint64 serverConnectionHandlerID, size_t flag, int* result);
unsigned int (*getClientSelfVariableAsString)(
uint64 serverConnectionHandlerID, size_t flag, char** result);
unsigned int (*setClientSelfVariableAsInt)(
uint64 serverConnectionHandlerID, size_t flag, int value);
unsigned int (*setClientSelfVariableAsString)(
uint64 serverConnectionHandlerID, size_t flag, const char* value);
unsigned int (*flushClientSelfUpdates)(uint64 serverConnectionHandlerID,
const char* returnCode);
unsigned int (*getClientVariableAsInt)(uint64 serverConnectionHandlerID,
anyID clientID, size_t flag,
int* result);
unsigned int (*getClientVariableAsUInt64)(
uint64 serverConnectionHandlerID, anyID clientID, size_t flag,
uint64* result);
unsigned int (*getClientVariableAsString)(
uint64 serverConnectionHandlerID, anyID clientID, size_t flag,
char** result);
unsigned int (*getClientList)(uint64 serverConnectionHandlerID,
anyID** result);
unsigned int (*getChannelOfClient)(uint64 serverConnectionHandlerID,
anyID clientID, uint64* result);
/* Channel info */
unsigned int (*getChannelVariableAsInt)(uint64 serverConnectionHandlerID, uint64 channelID, size_t flag, int* result);
unsigned int (*getChannelVariableAsUInt64)(uint64 serverConnectionHandlerID, uint64 channelID, size_t flag, uint64* result);
unsigned int (*getChannelVariableAsString)(uint64 serverConnectionHandlerID, uint64 channelID, size_t flag, char** result);
unsigned int (*getChannelIDFromChannelNames)(uint64 serverConnectionHandlerID, char** channelNameArray, uint64* result);
unsigned int (*setChannelVariableAsInt)(uint64 serverConnectionHandlerID, uint64 channelID, size_t flag, int value);
unsigned int (*setChannelVariableAsUInt64)(uint64 serverConnectionHandlerID, uint64 channelID, size_t flag, uint64 value);
unsigned int (*setChannelVariableAsString)(uint64 serverConnectionHandlerID, uint64 channelID, size_t flag, const char* value);
unsigned int (*flushChannelUpdates)(uint64 serverConnectionHandlerID, uint64 channelID, const char* returnCode);
unsigned int (*flushChannelCreation)(uint64 serverConnectionHandlerID, uint64 channelParentID, const char* returnCode);
unsigned int (*getChannelList)(uint64 serverConnectionHandlerID, uint64** result);
unsigned int (*getChannelClientList)(uint64 serverConnectionHandlerID, uint64 channelID, anyID** result);
unsigned int (*getParentChannelOfChannel)(uint64 serverConnectionHandlerID, uint64 channelID, uint64* result);
/* Channel info */
unsigned int (*getChannelVariableAsInt)(
uint64 serverConnectionHandlerID, uint64 channelID, size_t flag,
int* result);
unsigned int (*getChannelVariableAsUInt64)(
uint64 serverConnectionHandlerID, uint64 channelID, size_t flag,
uint64* result);
unsigned int (*getChannelVariableAsString)(
uint64 serverConnectionHandlerID, uint64 channelID, size_t flag,
char** result);
unsigned int (*getChannelIDFromChannelNames)(
uint64 serverConnectionHandlerID, char** channelNameArray,
uint64* result);
unsigned int (*setChannelVariableAsInt)(
uint64 serverConnectionHandlerID, uint64 channelID, size_t flag,
int value);
unsigned int (*setChannelVariableAsUInt64)(
uint64 serverConnectionHandlerID, uint64 channelID, size_t flag,
uint64 value);
unsigned int (*setChannelVariableAsString)(
uint64 serverConnectionHandlerID, uint64 channelID, size_t flag,
const char* value);
unsigned int (*flushChannelUpdates)(uint64 serverConnectionHandlerID,
uint64 channelID,
const char* returnCode);
unsigned int (*flushChannelCreation)(uint64 serverConnectionHandlerID,
uint64 channelParentID,
const char* returnCode);
unsigned int (*getChannelList)(uint64 serverConnectionHandlerID,
uint64** result);
unsigned int (*getChannelClientList)(uint64 serverConnectionHandlerID,
uint64 channelID, anyID** result);
unsigned int (*getParentChannelOfChannel)(
uint64 serverConnectionHandlerID, uint64 channelID, uint64* result);
/* Server info */
unsigned int (*getServerConnectionHandlerList)(uint64** result);
unsigned int (*getServerVariableAsInt)(uint64 serverConnectionHandlerID, size_t flag, int* result);
unsigned int (*getServerVariableAsUInt64)(uint64 serverConnectionHandlerID, size_t flag, uint64* result);
unsigned int (*getServerVariableAsString)(uint64 serverConnectionHandlerID, size_t flag, char** result);
unsigned int (*requestServerVariables)(uint64 serverConnectionHandlerID);
/* Server info */
unsigned int (*getServerConnectionHandlerList)(uint64** result);
unsigned int (*getServerVariableAsInt)(uint64 serverConnectionHandlerID,
size_t flag, int* result);
unsigned int (*getServerVariableAsUInt64)(
uint64 serverConnectionHandlerID, size_t flag, uint64* result);
unsigned int (*getServerVariableAsString)(
uint64 serverConnectionHandlerID, size_t flag, char** result);
unsigned int (*requestServerVariables)(
uint64 serverConnectionHandlerID);
/* Connection info */
unsigned int (*getConnectionStatus)(uint64 serverConnectionHandlerID, int* result);
unsigned int (*getConnectionVariableAsUInt64)(uint64 serverConnectionHandlerID, anyID clientID, size_t flag, uint64* result);
unsigned int (*getConnectionVariableAsDouble)(uint64 serverConnectionHandlerID, anyID clientID, size_t flag, double* result);
unsigned int (*getConnectionVariableAsString)(uint64 serverConnectionHandlerID, anyID clientID, size_t flag, char** result);
unsigned int (*cleanUpConnectionInfo)(uint64 serverConnectionHandlerID, anyID clientID);
/* Connection info */
unsigned int (*getConnectionStatus)(uint64 serverConnectionHandlerID,
int* result);
unsigned int (*getConnectionVariableAsUInt64)(
uint64 serverConnectionHandlerID, anyID clientID, size_t flag,
uint64* result);
unsigned int (*getConnectionVariableAsDouble)(
uint64 serverConnectionHandlerID, anyID clientID, size_t flag,
double* result);
unsigned int (*getConnectionVariableAsString)(
uint64 serverConnectionHandlerID, anyID clientID, size_t flag,
char** result);
unsigned int (*cleanUpConnectionInfo)(uint64 serverConnectionHandlerID,
anyID clientID);
/* Client related */
unsigned int (*requestClientDBIDfromUID)(uint64 serverConnectionHandlerID, const char* clientUniqueIdentifier, const char* returnCode);
unsigned int (*requestClientNamefromUID)(uint64 serverConnectionHandlerID, const char* clientUniqueIdentifier, const char* returnCode);
unsigned int (*requestClientNamefromDBID)(uint64 serverConnectionHandlerID, uint64 clientDatabaseID, const char* returnCode);
unsigned int (*requestClientEditDescription)(uint64 serverConnectionHandlerID, anyID clientID, const char* clientDescription, const char* returnCode);
unsigned int (*requestClientSetIsTalker)(uint64 serverConnectionHandlerID, anyID clientID, int isTalker, const char* returnCode);
unsigned int (*requestIsTalker)(uint64 serverConnectionHandlerID, int isTalkerRequest, const char* isTalkerRequestMessage, const char* returnCode);
/* Client related */
unsigned int (*requestClientDBIDfromUID)(
uint64 serverConnectionHandlerID,
const char* clientUniqueIdentifier, const char* returnCode);
unsigned int (*requestClientNamefromUID)(
uint64 serverConnectionHandlerID,
const char* clientUniqueIdentifier, const char* returnCode);
unsigned int (*requestClientNamefromDBID)(
uint64 serverConnectionHandlerID, uint64 clientDatabaseID,
const char* returnCode);
unsigned int (*requestClientEditDescription)(
uint64 serverConnectionHandlerID, anyID clientID,
const char* clientDescription, const char* returnCode);
unsigned int (*requestClientSetIsTalker)(
uint64 serverConnectionHandlerID, anyID clientID, int isTalker,
const char* returnCode);
unsigned int (*requestIsTalker)(uint64 serverConnectionHandlerID,
int isTalkerRequest,
const char* isTalkerRequestMessage,
const char* returnCode);
/* Plugin related */
unsigned int (*requestSendClientQueryCommand)(uint64 serverConnectionHandlerID, const char* command, const char* returnCode);
/* Plugin related */
unsigned int (*requestSendClientQueryCommand)(
uint64 serverConnectionHandlerID, const char* command,
const char* returnCode);
/* Filetransfer */
unsigned int (*getTransferFileName)(anyID transferID, char** result);
unsigned int (*getTransferFilePath)(anyID transferID, char** result);
unsigned int (*getTransferFileSize)(anyID transferID, uint64* result);
unsigned int (*getTransferFileSizeDone)(anyID transferID, uint64* result);
unsigned int (*isTransferSender)(anyID transferID, int* result); /* 1 == upload, 0 == download */
unsigned int (*getTransferStatus)(anyID transferID, int* result);
unsigned int (*getCurrentTransferSpeed)(anyID transferID, float* result);
unsigned int (*getAverageTransferSpeed)(anyID transferID, float* result);
unsigned int (*getTransferRunTime)(anyID transferID, uint64* result);
unsigned int (*sendFile)(uint64 serverConnectionHandlerID, uint64 channelID, const char* channelPW, const char* file, int overwrite, int resume, const char* sourceDirectory, anyID* result, const char* returnCode);
unsigned int (*requestFile)(uint64 serverConnectionHandlerID, uint64 channelID, const char* channelPW, const char* file, int overwrite, int resume, const char* destinationDirectory, anyID* result, const char* returnCode);
unsigned int (*haltTransfer)(uint64 serverConnectionHandlerID, anyID transferID, int deleteUnfinishedFile, const char* returnCode);
unsigned int (*requestFileList)(uint64 serverConnectionHandlerID, uint64 channelID, const char* channelPW, const char* path, const char* returnCode);
unsigned int (*requestFileInfo)(uint64 serverConnectionHandlerID, uint64 channelID, const char* channelPW, const char* file, const char* returnCode);
unsigned int (*requestDeleteFile)(uint64 serverConnectionHandlerID, uint64 channelID, const char* channelPW, const char** file, const char* returnCode);
unsigned int (*requestCreateDirectory)(uint64 serverConnectionHandlerID, uint64 channelID, const char* channelPW, const char* directoryPath, const char* returnCode);
unsigned int (*requestRenameFile)(uint64 serverConnectionHandlerID, uint64 fromChannelID, const char* channelPW, uint64 toChannelID, const char* toChannelPW, const char* oldFile, const char* newFile, const char* returnCode);
/* Filetransfer */
unsigned int (*getTransferFileName)(anyID transferID, char** result);
unsigned int (*getTransferFilePath)(anyID transferID, char** result);
unsigned int (*getTransferFileSize)(anyID transferID, uint64* result);
unsigned int (*getTransferFileSizeDone)(anyID transferID,
uint64* result);
unsigned int (*isTransferSender)(
anyID transferID, int* result); /* 1 == upload, 0 == download */
unsigned int (*getTransferStatus)(anyID transferID, int* result);
unsigned int (*getCurrentTransferSpeed)(anyID transferID,
float* result);
unsigned int (*getAverageTransferSpeed)(anyID transferID,
float* result);
unsigned int (*getTransferRunTime)(anyID transferID, uint64* result);
unsigned int (*sendFile)(uint64 serverConnectionHandlerID,
uint64 channelID, const char* channelPW,
const char* file, int overwrite, int resume,
const char* sourceDirectory, anyID* result,
const char* returnCode);
unsigned int (*requestFile)(uint64 serverConnectionHandlerID,
uint64 channelID, const char* channelPW,
const char* file, int overwrite, int resume,
const char* destinationDirectory,
anyID* result, const char* returnCode);
unsigned int (*haltTransfer)(uint64 serverConnectionHandlerID,
anyID transferID, int deleteUnfinishedFile,
const char* returnCode);
unsigned int (*requestFileList)(uint64 serverConnectionHandlerID,
uint64 channelID, const char* channelPW,
const char* path,
const char* returnCode);
unsigned int (*requestFileInfo)(uint64 serverConnectionHandlerID,
uint64 channelID, const char* channelPW,
const char* file,
const char* returnCode);
unsigned int (*requestDeleteFile)(uint64 serverConnectionHandlerID,
uint64 channelID,
const char* channelPW,
const char** file,
const char* returnCode);
unsigned int (*requestCreateDirectory)(uint64 serverConnectionHandlerID,
uint64 channelID,
const char* channelPW,
const char* directoryPath,
const char* returnCode);
unsigned int (*requestRenameFile)(
uint64 serverConnectionHandlerID, uint64 fromChannelID,
const char* channelPW, uint64 toChannelID, const char* toChannelPW,
const char* oldFile, const char* newFile, const char* returnCode);
/* Offline message management */
unsigned int (*requestMessageAdd)(uint64 serverConnectionHandlerID, const char* toClientUID, const char* subject, const char* message, const char* returnCode);
unsigned int (*requestMessageDel)(uint64 serverConnectionHandlerID, uint64 messageID, const char* returnCode);
unsigned int (*requestMessageGet)(uint64 serverConnectionHandlerID, uint64 messageID, const char* returnCode);
unsigned int (*requestMessageList)(uint64 serverConnectionHandlerID, const char* returnCode);
unsigned int (*requestMessageUpdateFlag)(uint64 serverConnectionHandlerID, uint64 messageID, int flag, const char* returnCode);
/* Offline message management */
unsigned int (*requestMessageAdd)(uint64 serverConnectionHandlerID,
const char* toClientUID,
const char* subject,
const char* message,
const char* returnCode);
unsigned int (*requestMessageDel)(uint64 serverConnectionHandlerID,
uint64 messageID,
const char* returnCode);
unsigned int (*requestMessageGet)(uint64 serverConnectionHandlerID,
uint64 messageID,
const char* returnCode);
unsigned int (*requestMessageList)(uint64 serverConnectionHandlerID,
const char* returnCode);
unsigned int (*requestMessageUpdateFlag)(
uint64 serverConnectionHandlerID, uint64 messageID, int flag,
const char* returnCode);
/* Interacting with the server - confirming passwords */
unsigned int (*verifyServerPassword)(uint64 serverConnectionHandlerID, const char* serverPassword, const char* returnCode);
unsigned int (*verifyChannelPassword)(uint64 serverConnectionHandlerID, uint64 channelID, const char* channelPassword, const char* returnCode);
/* Interacting with the server - confirming passwords */
unsigned int (*verifyServerPassword)(uint64 serverConnectionHandlerID,
const char* serverPassword,
const char* returnCode);
unsigned int (*verifyChannelPassword)(uint64 serverConnectionHandlerID,
uint64 channelID,
const char* channelPassword,
const char* returnCode);
/* Interacting with the server - banning */
unsigned int (*banclient)(uint64 serverConnectionHandlerID, anyID clientID, uint64 timeInSeconds, const char* banReason, const char* returnCode);
unsigned int (*banadd)(uint64 serverConnectionHandlerID, const char* ipRegExp, const char* nameRegexp, const char* uniqueIdentity, const char* mytsID, uint64 timeInSeconds, const char* banReason, const char* returnCode);
unsigned int (*banclientdbid)(uint64 serverConnectionHandlerID, uint64 clientDBID, uint64 timeInSeconds, const char* banReason, const char* returnCode);
unsigned int (*bandel)(uint64 serverConnectionHandlerID, uint64 banID, const char* returnCode);
unsigned int (*bandelall)(uint64 serverConnectionHandlerID, const char* returnCode);
unsigned int (*requestBanList)(uint64 serverConnectionHandlerID, uint64 start, unsigned int duration, const char* returnCode);
/* Interacting with the server - banning */
unsigned int (*banclient)(uint64 serverConnectionHandlerID,
anyID clientID, uint64 timeInSeconds,
const char* banReason,
const char* returnCode);
unsigned int (*banadd)(uint64 serverConnectionHandlerID,
const char* ipRegExp, const char* nameRegexp,
const char* uniqueIdentity, const char* mytsID,
uint64 timeInSeconds, const char* banReason,
const char* returnCode);
unsigned int (*banclientdbid)(uint64 serverConnectionHandlerID,
uint64 clientDBID, uint64 timeInSeconds,
const char* banReason,
const char* returnCode);
unsigned int (*bandel)(uint64 serverConnectionHandlerID, uint64 banID,
const char* returnCode);
unsigned int (*bandelall)(uint64 serverConnectionHandlerID,
const char* returnCode);
unsigned int (*requestBanList)(uint64 serverConnectionHandlerID,
uint64 start, unsigned int duration,
const char* returnCode);
/* Interacting with the server - complain */
unsigned int (*requestComplainAdd)(uint64 serverConnectionHandlerID, uint64 targetClientDatabaseID, const char* complainReason, const char* returnCode);
unsigned int (*requestComplainDel)(uint64 serverConnectionHandlerID, uint64 targetClientDatabaseID, uint64 fromClientDatabaseID, const char* returnCode);
unsigned int (*requestComplainDelAll)(uint64 serverConnectionHandlerID, uint64 targetClientDatabaseID, const char* returnCode);
unsigned int (*requestComplainList)(uint64 serverConnectionHandlerID, uint64 targetClientDatabaseID, const char* returnCode);
/* Interacting with the server - complain */
unsigned int (*requestComplainAdd)(uint64 serverConnectionHandlerID,
uint64 targetClientDatabaseID,
const char* complainReason,
const char* returnCode);
unsigned int (*requestComplainDel)(uint64 serverConnectionHandlerID,
uint64 targetClientDatabaseID,
uint64 fromClientDatabaseID,
const char* returnCode);
unsigned int (*requestComplainDelAll)(uint64 serverConnectionHandlerID,
uint64 targetClientDatabaseID,
const char* returnCode);
unsigned int (*requestComplainList)(uint64 serverConnectionHandlerID,
uint64 targetClientDatabaseID,
const char* returnCode);
/* Permissions */
unsigned int (*requestServerGroupList)(uint64 serverConnectionHandlerID, const char* returnCode);
unsigned int (*requestServerGroupAdd)(uint64 serverConnectionHandlerID, const char* groupName, int groupType, const char* returnCode);
unsigned int (*requestServerGroupDel)(uint64 serverConnectionHandlerID, uint64 serverGroupID, int force, const char* returnCode);
unsigned int (*requestServerGroupAddClient)(uint64 serverConnectionHandlerID, uint64 serverGroupID, uint64 clientDatabaseID, const char* returnCode);
unsigned int (*requestServerGroupDelClient)(uint64 serverConnectionHandlerID, uint64 serverGroupID, uint64 clientDatabaseID, const char* returnCode);
unsigned int (*requestServerGroupsByClientID)(uint64 serverConnectionHandlerID, uint64 clientDatabaseID, const char* returnCode);
unsigned int (*requestServerGroupAddPerm)(uint64 serverConnectionHandlerID, uint64 serverGroupID, int continueonerror, const unsigned int* permissionIDArray, const int* permissionValueArray, const int* permissionNegatedArray,
const int* permissionSkipArray, int arraySize, const char* returnCode);
unsigned int (*requestServerGroupDelPerm)(uint64 serverConnectionHandlerID, uint64 serverGroupID, int continueOnError, const unsigned int* permissionIDArray, int arraySize, const char* returnCode);
unsigned int (*requestServerGroupPermList)(uint64 serverConnectionHandlerID, uint64 serverGroupID, const char* returnCode);
unsigned int (*requestServerGroupClientList)(uint64 serverConnectionHandlerID, uint64 serverGroupID, int withNames, const char* returnCode);
unsigned int (*requestChannelGroupList)(uint64 serverConnectionHandlerID, const char* returnCode);
unsigned int (*requestChannelGroupAdd)(uint64 serverConnectionHandlerID, const char* groupName, int groupType, const char* returnCode);
unsigned int (*requestChannelGroupDel)(uint64 serverConnectionHandlerID, uint64 channelGroupID, int force, const char* returnCode);
unsigned int (*requestChannelGroupAddPerm)(uint64 serverConnectionHandlerID, uint64 channelGroupID, int continueonerror, const unsigned int* permissionIDArray, const int* permissionValueArray, int arraySize, const char* returnCode);
unsigned int (*requestChannelGroupDelPerm)(uint64 serverConnectionHandlerID, uint64 channelGroupID, int continueOnError, const unsigned int* permissionIDArray, int arraySize, const char* returnCode);
unsigned int (*requestChannelGroupPermList)(uint64 serverConnectionHandlerID, uint64 channelGroupID, const char* returnCode);
unsigned int (*requestSetClientChannelGroup)(uint64 serverConnectionHandlerID, const uint64* channelGroupIDArray, const uint64* channelIDArray, const uint64* clientDatabaseIDArray, int arraySize, const char* returnCode);
unsigned int (*requestChannelAddPerm)(uint64 serverConnectionHandlerID, uint64 channelID, const unsigned int* permissionIDArray, const int* permissionValueArray, int arraySize, const char* returnCode);
unsigned int (*requestChannelDelPerm)(uint64 serverConnectionHandlerID, uint64 channelID, const unsigned int* permissionIDArray, int arraySize, const char* returnCode);
unsigned int (*requestChannelPermList)(uint64 serverConnectionHandlerID, uint64 channelID, const char* returnCode);
unsigned int (*requestClientAddPerm)(uint64 serverConnectionHandlerID, uint64 clientDatabaseID, const unsigned int* permissionIDArray, const int* permissionValueArray, const int* permissionSkipArray, int arraySize, const char* returnCode);
unsigned int (*requestClientDelPerm)(uint64 serverConnectionHandlerID, uint64 clientDatabaseID, const unsigned int* permissionIDArray, int arraySize, const char* returnCode);
unsigned int (*requestClientPermList)(uint64 serverConnectionHandlerID, uint64 clientDatabaseID, const char* returnCode);
unsigned int (*requestChannelClientAddPerm)(uint64 serverConnectionHandlerID, uint64 channelID, uint64 clientDatabaseID, const unsigned int* permissionIDArray, const int* permissionValueArray, int arraySize, const char* returnCode);
unsigned int (*requestChannelClientDelPerm)(uint64 serverConnectionHandlerID, uint64 channelID, uint64 clientDatabaseID, const unsigned int* permissionIDArray, int arraySize, const char* returnCode);
unsigned int (*requestChannelClientPermList)(uint64 serverConnectionHandlerID, uint64 channelID, uint64 clientDatabaseID, const char* returnCode);
unsigned int (*privilegeKeyUse)(uint64 serverConnectionHandler, const char* tokenKey, const char* returnCode);
unsigned int (*requestPermissionList)(uint64 serverConnectionHandler, const char* returnCode);
unsigned int (*requestPermissionOverview)(uint64 serverConnectionHandler, uint64 clientDBID, uint64 channelID, const char* returnCode);
/* Permissions */
unsigned int (*requestServerGroupList)(uint64 serverConnectionHandlerID,
const char* returnCode);
unsigned int (*requestServerGroupAdd)(uint64 serverConnectionHandlerID,
const char* groupName,
int groupType,
const char* returnCode);
unsigned int (*requestServerGroupDel)(uint64 serverConnectionHandlerID,
uint64 serverGroupID, int force,
const char* returnCode);
unsigned int (*requestServerGroupAddClient)(
uint64 serverConnectionHandlerID, uint64 serverGroupID,
uint64 clientDatabaseID, const char* returnCode);
unsigned int (*requestServerGroupDelClient)(
uint64 serverConnectionHandlerID, uint64 serverGroupID,
uint64 clientDatabaseID, const char* returnCode);
unsigned int (*requestServerGroupsByClientID)(
uint64 serverConnectionHandlerID, uint64 clientDatabaseID,
const char* returnCode);
unsigned int (*requestServerGroupAddPerm)(
uint64 serverConnectionHandlerID, uint64 serverGroupID,
int continueonerror, const unsigned int* permissionIDArray,
const int* permissionValueArray, const int* permissionNegatedArray,
const int* permissionSkipArray, int arraySize,
const char* returnCode);
unsigned int (*requestServerGroupDelPerm)(
uint64 serverConnectionHandlerID, uint64 serverGroupID,
int continueOnError, const unsigned int* permissionIDArray,
int arraySize, const char* returnCode);
unsigned int (*requestServerGroupPermList)(
uint64 serverConnectionHandlerID, uint64 serverGroupID,
const char* returnCode);
unsigned int (*requestServerGroupClientList)(
uint64 serverConnectionHandlerID, uint64 serverGroupID,
int withNames, const char* returnCode);
unsigned int (*requestChannelGroupList)(
uint64 serverConnectionHandlerID, const char* returnCode);
unsigned int (*requestChannelGroupAdd)(uint64 serverConnectionHandlerID,
const char* groupName,
int groupType,
const char* returnCode);
unsigned int (*requestChannelGroupDel)(uint64 serverConnectionHandlerID,
uint64 channelGroupID, int force,
const char* returnCode);
unsigned int (*requestChannelGroupAddPerm)(
uint64 serverConnectionHandlerID, uint64 channelGroupID,
int continueonerror, const unsigned int* permissionIDArray,
const int* permissionValueArray, int arraySize,
const char* returnCode);
unsigned int (*requestChannelGroupDelPerm)(
uint64 serverConnectionHandlerID, uint64 channelGroupID,
int continueOnError, const unsigned int* permissionIDArray,
int arraySize, const char* returnCode);
unsigned int (*requestChannelGroupPermList)(
uint64 serverConnectionHandlerID, uint64 channelGroupID,
const char* returnCode);
unsigned int (*requestSetClientChannelGroup)(
uint64 serverConnectionHandlerID, const uint64* channelGroupIDArray,
const uint64* channelIDArray, const uint64* clientDatabaseIDArray,
int arraySize, const char* returnCode);
unsigned int (*requestChannelAddPerm)(
uint64 serverConnectionHandlerID, uint64 channelID,
const unsigned int* permissionIDArray,
const int* permissionValueArray, int arraySize,
const char* returnCode);
unsigned int (*requestChannelDelPerm)(
uint64 serverConnectionHandlerID, uint64 channelID,
const unsigned int* permissionIDArray, int arraySize,
const char* returnCode);
unsigned int (*requestChannelPermList)(uint64 serverConnectionHandlerID,
uint64 channelID,
const char* returnCode);
unsigned int (*requestClientAddPerm)(
uint64 serverConnectionHandlerID, uint64 clientDatabaseID,
const unsigned int* permissionIDArray,
const int* permissionValueArray, const int* permissionSkipArray,
int arraySize, const char* returnCode);
unsigned int (*requestClientDelPerm)(
uint64 serverConnectionHandlerID, uint64 clientDatabaseID,
const unsigned int* permissionIDArray, int arraySize,
const char* returnCode);
unsigned int (*requestClientPermList)(uint64 serverConnectionHandlerID,
uint64 clientDatabaseID,
const char* returnCode);
unsigned int (*requestChannelClientAddPerm)(
uint64 serverConnectionHandlerID, uint64 channelID,
uint64 clientDatabaseID, const unsigned int* permissionIDArray,
const int* permissionValueArray, int arraySize,
const char* returnCode);
unsigned int (*requestChannelClientDelPerm)(
uint64 serverConnectionHandlerID, uint64 channelID,
uint64 clientDatabaseID, const unsigned int* permissionIDArray,
int arraySize, const char* returnCode);
unsigned int (*requestChannelClientPermList)(
uint64 serverConnectionHandlerID, uint64 channelID,
uint64 clientDatabaseID, const char* returnCode);
unsigned int (*privilegeKeyUse)(uint64 serverConnectionHandler,
const char* tokenKey,
const char* returnCode);
unsigned int (*requestPermissionList)(uint64 serverConnectionHandler,
const char* returnCode);
unsigned int (*requestPermissionOverview)(
uint64 serverConnectionHandler, uint64 clientDBID, uint64 channelID,
const char* returnCode);
/* Helper Functions */
unsigned int (*clientPropertyStringToFlag)(const char* clientPropertyString, size_t* resultFlag);
unsigned int (*channelPropertyStringToFlag)(const char* channelPropertyString, size_t* resultFlag);
unsigned int (*serverPropertyStringToFlag)(const char* serverPropertyString, size_t* resultFlag);
/* Helper Functions */
unsigned int (*clientPropertyStringToFlag)(
const char* clientPropertyString, size_t* resultFlag);
unsigned int (*channelPropertyStringToFlag)(
const char* channelPropertyString, size_t* resultFlag);
unsigned int (*serverPropertyStringToFlag)(
const char* serverPropertyString, size_t* resultFlag);
/* Client functions */
void (*getAppPath)(char* path, size_t maxLen);
void (*getResourcesPath)(char* path, size_t maxLen);
void (*getConfigPath)(char* path, size_t maxLen);
void (*getPluginPath)(char* path, size_t maxLen, const char* pluginID);
uint64 (*getCurrentServerConnectionHandlerID)(void);
void (*printMessage)(uint64 serverConnectionHandlerID, const char* message, enum PluginMessageTarget messageTarget);
void (*printMessageToCurrentTab)(const char* message);
void (*urlsToBB)(const char* text, char* result, size_t maxLen);
void (*sendPluginCommand)(uint64 serverConnectionHandlerID, const char* pluginID, const char* command, int targetMode, const anyID* targetIDs, const char* returnCode);
void (*getDirectories)(const char* path, char* result, size_t maxLen);
unsigned int (*getServerConnectInfo)(uint64 scHandlerID, char* host, unsigned short* port, char* password, size_t maxLen);
unsigned int (*getChannelConnectInfo)(uint64 scHandlerID, uint64 channelID, char* path, char* password, size_t maxLen);
void (*createReturnCode)(const char* pluginID, char* returnCode, size_t maxLen);
unsigned int (*requestInfoUpdate)(uint64 scHandlerID, enum PluginItemType itemType, uint64 itemID);
uint64 (*getServerVersion)(uint64 scHandlerID);
unsigned int (*isWhispering)(uint64 scHandlerID, anyID clientID, int* result);
unsigned int (*isReceivingWhisper)(uint64 scHandlerID, anyID clientID, int* result);
unsigned int (*getAvatar)(uint64 scHandlerID, anyID clientID, char* result, size_t maxLen);
void (*setPluginMenuEnabled)(const char* pluginID, int menuID, int enabled);
void (*showHotkeySetup)(void);
void (*requestHotkeyInputDialog)(const char* pluginID, const char* keyword, int isDown, void* qParentWindow);
unsigned int (*getHotkeyFromKeyword)(const char* pluginID, const char** keywords, char** hotkeys, size_t arrayLen, size_t hotkeyBufSize);
unsigned int (*getClientDisplayName)(uint64 scHandlerID, anyID clientID, char* result, size_t maxLen);
unsigned int (*getBookmarkList)(struct PluginBookmarkList** list);
unsigned int (*getProfileList)(enum PluginGuiProfile profile, int* defaultProfileIdx, char*** result);
unsigned int (*guiConnect)(enum PluginConnectTab connectTab, const char* serverLabel, const char* serverAddress, const char* serverPassword, const char* nickname, const char* channel, const char* channelPassword, const char* captureProfile,
const char* playbackProfile, const char* hotkeyProfile, const char* soundProfile, const char* userIdentity, const char* oneTimeKey, const char* phoneticName, uint64* scHandlerID);
unsigned int (*guiConnectBookmark)(enum PluginConnectTab connectTab, const char* bookmarkuuid, uint64* scHandlerID);
unsigned int (*createBookmark)(const char* bookmarkuuid, const char* serverLabel, const char* serverAddress, const char* serverPassword, const char* nickname, const char* channel, const char* channelPassword, const char* captureProfile,
const char* playbackProfile, const char* hotkeyProfile, const char* soundProfile, const char* uniqueUserId, const char* oneTimeKey, const char* phoneticName);
unsigned int (*getPermissionIDByName)(uint64 serverConnectionHandlerID, const char* permissionName, unsigned int* result);
unsigned int (*getClientNeededPermission)(uint64 serverConnectionHandlerID, const char* permissionName, int* result);
void (*notifyKeyEvent)(const char* pluginID, const char* keyIdentifier, int up_down);
/* Client functions */
void (*getAppPath)(char* path, size_t maxLen);
void (*getResourcesPath)(char* path, size_t maxLen);
void (*getConfigPath)(char* path, size_t maxLen);
void (*getPluginPath)(char* path, size_t maxLen, const char* pluginID);
uint64 (*getCurrentServerConnectionHandlerID)(void);
void (*printMessage)(uint64 serverConnectionHandlerID,
const char* message,
enum PluginMessageTarget messageTarget);
void (*printMessageToCurrentTab)(const char* message);
void (*urlsToBB)(const char* text, char* result, size_t maxLen);
void (*sendPluginCommand)(uint64 serverConnectionHandlerID,
const char* pluginID, const char* command,
int targetMode, const anyID* targetIDs,
const char* returnCode);
void (*getDirectories)(const char* path, char* result, size_t maxLen);
unsigned int (*getServerConnectInfo)(uint64 scHandlerID, char* host,
unsigned short* port,
char* password, size_t maxLen);
unsigned int (*getChannelConnectInfo)(uint64 scHandlerID,
uint64 channelID, char* path,
char* password, size_t maxLen);
void (*createReturnCode)(const char* pluginID, char* returnCode,
size_t maxLen);
unsigned int (*requestInfoUpdate)(uint64 scHandlerID,
enum PluginItemType itemType,
uint64 itemID);
uint64 (*getServerVersion)(uint64 scHandlerID);
unsigned int (*isWhispering)(uint64 scHandlerID, anyID clientID,
int* result);
unsigned int (*isReceivingWhisper)(uint64 scHandlerID, anyID clientID,
int* result);
unsigned int (*getAvatar)(uint64 scHandlerID, anyID clientID,
char* result, size_t maxLen);
void (*setPluginMenuEnabled)(const char* pluginID, int menuID,
int enabled);
void (*showHotkeySetup)(void);
void (*requestHotkeyInputDialog)(const char* pluginID,
const char* keyword, int isDown,
void* qParentWindow);
unsigned int (*getHotkeyFromKeyword)(const char* pluginID,
const char** keywords,
char** hotkeys, size_t arrayLen,
size_t hotkeyBufSize);
unsigned int (*getClientDisplayName)(uint64 scHandlerID, anyID clientID,
char* result, size_t maxLen);
unsigned int (*getBookmarkList)(struct PluginBookmarkList** list);
unsigned int (*getProfileList)(enum PluginGuiProfile profile,
int* defaultProfileIdx, char*** result);
unsigned int (*guiConnect)(
enum PluginConnectTab connectTab, const char* serverLabel,
const char* serverAddress, const char* serverPassword,
const char* nickname, const char* channel,
const char* channelPassword, const char* captureProfile,
const char* playbackProfile, const char* hotkeyProfile,
const char* soundProfile, const char* userIdentity,
const char* oneTimeKey, const char* phoneticName,
uint64* scHandlerID);
unsigned int (*guiConnectBookmark)(enum PluginConnectTab connectTab,
const char* bookmarkuuid,
uint64* scHandlerID);
unsigned int (*createBookmark)(
const char* bookmarkuuid, const char* serverLabel,
const char* serverAddress, const char* serverPassword,
const char* nickname, const char* channel,
const char* channelPassword, const char* captureProfile,
const char* playbackProfile, const char* hotkeyProfile,
const char* soundProfile, const char* uniqueUserId,
const char* oneTimeKey, const char* phoneticName);
unsigned int (*getPermissionIDByName)(uint64 serverConnectionHandlerID,
const char* permissionName,
unsigned int* result);
unsigned int (*getClientNeededPermission)(
uint64 serverConnectionHandlerID, const char* permissionName,
int* result);
void (*notifyKeyEvent)(const char* pluginID, const char* keyIdentifier,
int up_down);
/* Single-Track/Multi-Track recording */
unsigned int (*startRecording)(uint64 serverConnectionHandlerID, int multitrack, int noFileSelector, const char* path);
unsigned int (*stopRecording)(uint64 serverConnectionHandlerID);
/* Single-Track/Multi-Track recording */
unsigned int (*startRecording)(uint64 serverConnectionHandlerID,
int multitrack, int noFileSelector,
const char* path);
unsigned int (*stopRecording)(uint64 serverConnectionHandlerID);
/* Convenience functions */
unsigned int (*requestClientsMove)(uint64 serverConnectionHandlerID, const anyID* clientIDArray, uint64 newChannelID, const char* password, const char* returnCode);
unsigned int (*requestClientsKickFromChannel)(uint64 serverConnectionHandlerID, const anyID* clientIDArray, const char* kickReason, const char* returnCode);
unsigned int (*requestClientsKickFromServer)(uint64 serverConnectionHandlerID, const anyID* clientIDArray, const char* kickReason, const char* returnCode);
unsigned int (*requestMuteClientsTemporary)(uint64 serverConnectionHandlerID, const anyID* clientIDArray, const char* returnCode);
unsigned int (*requestUnmuteClientsTemporary)(uint64 serverConnectionHandlerID, const anyID* clientIDArray, const char* returnCode);
unsigned int (*getPermissionNameByID)(uint64 scHandlerID, unsigned int permissionID, char* result, size_t max_len);
unsigned int (*clientPropertyFlagToString)(size_t clientPropertyFlag, char** resultString);
unsigned int (*channelPropertyFlagToString)(size_t channelPropertyFlag, char** resultString);
unsigned int (*serverPropertyFlagToString)(size_t serverPropertyFlag, char** resultString);
/* Convenience functions */
unsigned int (*requestClientsMove)(uint64 serverConnectionHandlerID,
const anyID* clientIDArray,
uint64 newChannelID,
const char* password,
const char* returnCode);
unsigned int (*requestClientsKickFromChannel)(
uint64 serverConnectionHandlerID, const anyID* clientIDArray,
const char* kickReason, const char* returnCode);
unsigned int (*requestClientsKickFromServer)(
uint64 serverConnectionHandlerID, const anyID* clientIDArray,
const char* kickReason, const char* returnCode);
unsigned int (*requestMuteClientsTemporary)(
uint64 serverConnectionHandlerID, const anyID* clientIDArray,
const char* returnCode);
unsigned int (*requestUnmuteClientsTemporary)(
uint64 serverConnectionHandlerID, const anyID* clientIDArray,
const char* returnCode);
unsigned int (*getPermissionNameByID)(uint64 scHandlerID,
unsigned int permissionID,
char* result, size_t max_len);
unsigned int (*clientPropertyFlagToString)(size_t clientPropertyFlag,
char** resultString);
unsigned int (*channelPropertyFlagToString)(size_t channelPropertyFlag,
char** resultString);
unsigned int (*serverPropertyFlagToString)(size_t serverPropertyFlag,
char** resultString);
/* Server editing */
unsigned int (*setServerVariableAsInt)(uint64 serverConnectionHandlerID, size_t flag, int value);
unsigned int (*setServerVariableAsUInt64)(uint64 serverConnectionHandlerID, size_t flag, uint64 value);
unsigned int (*setServerVariableAsDouble)(uint64 serverConnectionHandlerID, size_t flag, double value);
unsigned int (*setServerVariableAsString)(uint64 serverConnectionHandlerID, size_t flag, const char* value);
unsigned int (*flushServerUpdates)(uint64 serverConnectionHandlerID, const char* returnCode);
/* Server editing */
unsigned int (*setServerVariableAsInt)(uint64 serverConnectionHandlerID,
size_t flag, int value);
unsigned int (*setServerVariableAsUInt64)(
uint64 serverConnectionHandlerID, size_t flag, uint64 value);
unsigned int (*setServerVariableAsDouble)(
uint64 serverConnectionHandlerID, size_t flag, double value);
unsigned int (*setServerVariableAsString)(
uint64 serverConnectionHandlerID, size_t flag, const char* value);
unsigned int (*flushServerUpdates)(uint64 serverConnectionHandlerID,
const char* returnCode);
/* Server/Channel group helper functions */
unsigned int (*getServerGroupIDByName)(uint64 serverConnectionHandlerID, const char* groupName, unsigned int* result);
unsigned int (*getServerGroupNameByID)(uint64 scHandlerID, unsigned int groupID, char* result, size_t max_len);
unsigned int (*getChannelGroupIDByName)(uint64 serverConnectionHandlerID, const char* groupName, unsigned int* result);
unsigned int (*getChannelGroupNameByID)(uint64 scHandlerID, unsigned int groupID, char* result, size_t max_len);
/* Server/Channel group helper functions */
unsigned int (*getServerGroupIDByName)(uint64 serverConnectionHandlerID,
const char* groupName,
unsigned int* result);
unsigned int (*getServerGroupNameByID)(uint64 scHandlerID,
unsigned int groupID,
char* result, size_t max_len);
unsigned int (*getChannelGroupIDByName)(
uint64 serverConnectionHandlerID, const char* groupName,
unsigned int* result);
unsigned int (*getChannelGroupNameByID)(uint64 scHandlerID,
unsigned int groupID,
char* result, size_t max_len);
};
#ifdef __cplusplus
+200 -178
View File
@@ -6,220 +6,242 @@
AudioDecoder::AudioDecoder() { av_log_set_level(AV_LOG_WARNING); }
AudioDecoder::~AudioDecoder() {
Cancel();
if (m_thread.joinable())
m_thread.join();
Cleanup();
AudioDecoder::~AudioDecoder()
{
Cancel();
if (m_thread.joinable()) {
m_thread.join();
}
Cleanup();
}
void AudioDecoder::Cleanup() {
if (m_swrCtx) {
swr_free(&m_swrCtx);
m_swrCtx = nullptr;
}
if (m_codecCtx) {
avcodec_free_context(&m_codecCtx);
m_codecCtx = nullptr;
}
if (m_formatCtx) {
avformat_close_input(&m_formatCtx);
m_formatCtx = nullptr;
}
void AudioDecoder::Cleanup()
{
if (m_swrCtx) {
swr_free(&m_swrCtx);
m_swrCtx = nullptr;
}
if (m_codecCtx) {
avcodec_free_context(&m_codecCtx);
m_codecCtx = nullptr;
}
if (m_formatCtx) {
avformat_close_input(&m_formatCtx);
m_formatCtx = nullptr;
}
}
bool AudioDecoder::GetNextChunk(std::vector<short> &outChunk, bool blocking) {
std::unique_lock lock(m_queueMtx);
bool AudioDecoder::GetNextChunk(std::vector<short> &outChunk, bool blocking)
{
std::unique_lock lock(m_queueMtx);
if (blocking) {
m_cv.wait(lock, [&] { return !m_chunkQueue.empty() || m_finished.load(); });
}
if (blocking) {
m_cv.wait(lock,
[&] { return !m_chunkQueue.empty() || m_finished.load(); });
}
if (m_chunkQueue.empty())
return false;
if (m_chunkQueue.empty()) {
return false;
}
outChunk = std::move(m_chunkQueue.front());
m_chunkQueue.pop_front();
return true;
outChunk = std::move(m_chunkQueue.front());
m_chunkQueue.pop_front();
return true;
}
void AudioDecoder::StartDecode(const std::string &url, int targetSampleRate) {
Cancel();
if (m_thread.joinable()) {
m_thread.join();
}
// Clear previous data
{
std::lock_guard<std::mutex> lock(m_queueMtx);
m_chunkQueue.clear();
}
void AudioDecoder::StartDecode(const std::string &url, int targetSampleRate)
{
Cancel();
if (m_thread.joinable()) {
m_thread.join();
}
// Clear previous data
{
std::lock_guard<std::mutex> lock(m_queueMtx);
m_chunkQueue.clear();
}
m_isDecodingFinished = false;
m_finished = false; // <--- ADD THIS LINE
m_status = DecodeStatus::Processing;
m_cancelRequested = false;
m_thread =
std::jthread(&AudioDecoder::InternalDecode, this, url, targetSampleRate);
m_isDecodingFinished = false;
m_finished = false; // <--- ADD THIS LINE
m_status = DecodeStatus::Processing;
m_cancelRequested = false;
m_thread = std::jthread(&AudioDecoder::InternalDecode, this, url,
targetSampleRate);
}
void AudioDecoder::InternalDecode(std::string url, int targetSampleRate) {
void AudioDecoder::InternalDecode(std::string url, int targetSampleRate)
{
auto config = ts6bot::Configuration::getInstance()->getConfig();
AVPacket *pkt = nullptr;
AVFrame *frame = nullptr;
uint8_t *outputBuffer = nullptr;
auto config = ts6bot::Configuration::getInstance()->getConfig();
AVPacket *pkt = nullptr;
AVFrame *frame = nullptr;
uint8_t *outputBuffer = nullptr;
AVDictionary *formatOpts = nullptr;
AVDictionary *formatOpts = nullptr;
try {
// Example: SOCKS5 without authentication
av_dict_set(&formatOpts, "proxy",
std::format("socks5h://{}:{}@{}", config.proxy.username,
config.proxy.password, config.proxy.url)
.c_str(),
0);
av_dict_set(&formatOpts, "protocol_whitelist",
"file,http,https,tls,tcp,udp,crypto,httpproxy,socks,socks5", 0);
try {
// Example: SOCKS5 without authentication
av_dict_set(&formatOpts, "proxy",
std::format("socks5h://{}:{}@{}", config.proxy.username,
config.proxy.password, config.proxy.url)
.c_str(),
0);
av_dict_set(&formatOpts, "protocol_whitelist",
"file,http,https,tls,tcp,udp,crypto,httpproxy,socks,socks5",
0);
// Strongly recommended for YouTube
av_dict_set(&formatOpts, "user_agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/120.0.0.0 Safari/537.36",
0);
// Optional but recommended for network streams
av_dict_set(&formatOpts, "timeout", "15000000",
0); // 5 seconds (microseconds)
av_dict_set(&formatOpts, "reconnect", "1", 0);
av_dict_set(&formatOpts, "reconnect_streamed", "1", 0);
av_dict_set(&formatOpts, "reconnect_delay_max", "5", 0);
av_dict_set(&formatOpts, "analyzeduration", "20000000", 0); // 20 seconds
av_dict_set(&formatOpts, "probesize", "10240000", 0); // 10 MB buffer for header probing
// Reset state flags
m_isDecodingFinished = false;
// 1. Open Input & Find Stream
// Strongly recommended for YouTube
av_dict_set(&formatOpts, "user_agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/120.0.0.0 Safari/537.36",
0);
// Optional but recommended for network streams
av_dict_set(&formatOpts, "timeout", "15000000",
0); // 5 seconds (microseconds)
av_dict_set(&formatOpts, "reconnect", "1", 0);
av_dict_set(&formatOpts, "reconnect_streamed", "1", 0);
av_dict_set(&formatOpts, "reconnect_delay_max", "5", 0);
av_dict_set(&formatOpts, "analyzeduration", "20000000",
0); // 20 seconds
av_dict_set(&formatOpts, "probesize", "10240000",
0); // 10 MB buffer for header probing
// Reset state flags
m_isDecodingFinished = false;
// 1. Open Input & Find Stream
if (avformat_open_input(&m_formatCtx, url.c_str(), nullptr, &formatOpts) <
0) {
av_dict_free(&formatOpts);
throw std::runtime_error("Failed to open input stream: " + url);
}
if (avformat_find_stream_info(m_formatCtx, nullptr) < 0)
throw std::runtime_error("Failed to find stream info");
if (avformat_open_input(&m_formatCtx, url.c_str(), nullptr,
&formatOpts) < 0) {
av_dict_free(&formatOpts);
throw std::runtime_error("Failed to open input stream: " + url);
}
if (avformat_find_stream_info(m_formatCtx, nullptr) < 0) {
throw std::runtime_error("Failed to find stream info");
}
const AVCodec *decoder = nullptr;
int streamIdx = av_find_best_stream(m_formatCtx, AVMEDIA_TYPE_AUDIO, -1, -1,
&decoder, 0);
if (streamIdx < 0)
throw std::runtime_error("No audio stream found");
const AVCodec *decoder = nullptr;
int streamIdx = av_find_best_stream(m_formatCtx, AVMEDIA_TYPE_AUDIO, -1,
-1, &decoder, 0);
if (streamIdx < 0) {
throw std::runtime_error("No audio stream found");
}
// 2. Setup Multithreaded Decoder
m_codecCtx = avcodec_alloc_context3(decoder);
avcodec_parameters_to_context(m_codecCtx,
m_formatCtx->streams[streamIdx]->codecpar);
// 2. Setup Multithreaded Decoder
m_codecCtx = avcodec_alloc_context3(decoder);
avcodec_parameters_to_context(
m_codecCtx, m_formatCtx->streams[streamIdx]->codecpar);
m_codecCtx->thread_count = 0; // Auto-detect CPU cores
m_codecCtx->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE;
m_codecCtx->thread_count = 0; // Auto-detect CPU cores
m_codecCtx->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE;
if (avcodec_open2(m_codecCtx, decoder, nullptr) < 0)
throw std::runtime_error("Failed to open codec");
if (avcodec_open2(m_codecCtx, decoder, nullptr) < 0) {
throw std::runtime_error("Failed to open codec");
}
// 3. Setup Resampler (Stereo S16 PCM)
AVChannelLayout outLayout;
av_channel_layout_default(&outLayout, 2);
// 3. Setup Resampler (Stereo S16 PCM)
AVChannelLayout outLayout;
av_channel_layout_default(&outLayout, 2);
swr_alloc_set_opts2(&m_swrCtx, &outLayout, AV_SAMPLE_FMT_S16,
targetSampleRate, &m_codecCtx->ch_layout,
m_codecCtx->sample_fmt, m_codecCtx->sample_rate, 0,
nullptr);
if (m_codecCtx->sample_rate != targetSampleRate) {
av_opt_set_int(m_swrCtx, "linear_interp", 1, 0);
av_opt_set_int(m_swrCtx, "filter_size", 256, 0);
}
swr_init(m_swrCtx);
swr_alloc_set_opts2(&m_swrCtx, &outLayout, AV_SAMPLE_FMT_S16,
targetSampleRate, &m_codecCtx->ch_layout,
m_codecCtx->sample_fmt, m_codecCtx->sample_rate, 0,
nullptr);
if (m_codecCtx->sample_rate != targetSampleRate) {
av_opt_set_int(m_swrCtx, "linear_interp", 1, 0);
av_opt_set_int(m_swrCtx, "filter_size", 256, 0);
}
swr_init(m_swrCtx);
// 4. Allocate Resources
pkt = av_packet_alloc();
frame = av_frame_alloc();
int maxSamples = 4096;
av_samples_alloc(&outputBuffer, nullptr, 2, maxSamples, AV_SAMPLE_FMT_S16,
0);
// 4. Allocate Resources
pkt = av_packet_alloc();
frame = av_frame_alloc();
int maxSamples = 4096;
av_samples_alloc(&outputBuffer, nullptr, 2, maxSamples,
AV_SAMPLE_FMT_S16, 0);
LOG_DEBUG("Decoder initialized. Starting stream...");
while (!m_cancelRequested) {
int readRet = av_read_frame(m_formatCtx, pkt);
if (readRet == AVERROR_EOF)
break;
if (readRet < 0)
throw std::runtime_error("read error");
LOG_DEBUG("Decoder initialized. Starting stream...");
while (!m_cancelRequested) {
int readRet = av_read_frame(m_formatCtx, pkt);
if (readRet == AVERROR_EOF) {
break;
}
if (readRet < 0) {
throw std::runtime_error("read error");
}
if (pkt->stream_index == streamIdx) {
avcodec_send_packet(m_codecCtx, pkt);
if (pkt->stream_index == streamIdx) {
avcodec_send_packet(m_codecCtx, pkt);
while (!m_cancelRequested) {
int ret = avcodec_receive_frame(m_codecCtx, frame);
if (ret == AVERROR(EAGAIN))
break;
if (ret < 0)
continue;
while (!m_cancelRequested) {
int ret = avcodec_receive_frame(m_codecCtx, frame);
if (ret == AVERROR(EAGAIN)) {
break;
}
if (ret < 0) {
continue;
}
int outSamples =
swr_convert(m_swrCtx, &outputBuffer, maxSamples,
(const uint8_t **)frame->data, frame->nb_samples);
int outSamples = swr_convert(
m_swrCtx, &outputBuffer, maxSamples,
(const uint8_t **)frame->data, frame->nb_samples);
if (outSamples > 0) {
std::vector<short> chunk(outSamples * 2);
memcpy(chunk.data(), outputBuffer, outSamples * 2 * sizeof(short));
if (outSamples > 0) {
std::vector<short> chunk(outSamples * 2);
memcpy(chunk.data(), outputBuffer,
outSamples * 2 * sizeof(short));
{
std::lock_guard lock(m_queueMtx);
m_chunkQueue.push_back(std::move(chunk));
}
m_cv.notify_one();
}
}
}
av_packet_unref(pkt);
}
/* ---------- FINAL FLUSH (CRITICAL FIX) ---------- */
{
std::lock_guard lock(m_queueMtx);
m_chunkQueue.push_back(std::move(chunk));
}
m_cv.notify_one();
}
}
}
av_packet_unref(pkt);
}
/* ---------- FINAL FLUSH (CRITICAL FIX) ---------- */
avcodec_send_packet(m_codecCtx, nullptr);
while (!m_cancelRequested) {
int ret = avcodec_receive_frame(m_codecCtx, frame);
if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
break;
if (ret < 0)
throw std::runtime_error("flush decode error");
avcodec_send_packet(m_codecCtx, nullptr);
while (!m_cancelRequested) {
int ret = avcodec_receive_frame(m_codecCtx, frame);
if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN)) {
break;
}
if (ret < 0) {
throw std::runtime_error("flush decode error");
}
int outSamples =
swr_convert(m_swrCtx, &outputBuffer, maxSamples,
(const uint8_t **)frame->data, frame->nb_samples);
int outSamples =
swr_convert(m_swrCtx, &outputBuffer, maxSamples,
(const uint8_t **)frame->data, frame->nb_samples);
if (outSamples > 0) {
std::vector<short> chunk(outSamples * 2);
memcpy(chunk.data(), outputBuffer, outSamples * 2 * sizeof(short));
if (outSamples > 0) {
std::vector<short> chunk(outSamples * 2);
memcpy(chunk.data(), outputBuffer,
outSamples * 2 * sizeof(short));
{
std::lock_guard lock(m_queueMtx);
m_chunkQueue.push_back(std::move(chunk));
}
m_cv.notify_one();
}
}
{
std::lock_guard lock(m_queueMtx);
m_chunkQueue.push_back(std::move(chunk));
}
m_cv.notify_one();
}
}
m_status =
m_cancelRequested ? DecodeStatus::Cancelled : DecodeStatus::Completed;
m_status = m_cancelRequested ? DecodeStatus::Cancelled
: DecodeStatus::Completed;
} catch (...) {
m_status = DecodeStatus::Failed;
}
} catch (...) {
m_status = DecodeStatus::Failed;
}
Cleanup();
Cleanup();
m_finished = true;
m_cv.notify_all();
m_finished = true;
m_cv.notify_all();
av_freep(&outputBuffer);
av_frame_free(&frame);
av_packet_free(&pkt);
LOG_DEBUG("Internal thread exited.");
av_freep(&outputBuffer);
av_frame_free(&frame);
av_packet_free(&pkt);
LOG_DEBUG("Internal thread exited.");
}
+101 -83
View File
@@ -5,101 +5,119 @@
#include <stdexcept>
namespace ts6bot::crypto {
namespace ts6bot::crypto
{
static void rand_bytes(std::span<std::uint8_t> out) {
if (out.empty()) return;
if (RAND_bytes(out.data(), static_cast<int>(out.size())) != 1) {
throw std::runtime_error("RAND_bytes failed");
}
}
static void rand_bytes(std::span<std::uint8_t> out)
{
if (out.empty()) {
return;
}
if (RAND_bytes(out.data(), static_cast<int>(out.size())) != 1) {
throw std::runtime_error("RAND_bytes failed");
}
}
std::string GenerateCodeVerifier(std::size_t length) {
if (length < 43 || length > 128) {
throw std::runtime_error("code_verifier length must be 43..128");
}
std::string GenerateCodeVerifier(std::size_t length)
{
if (length < 43 || length > 128) {
throw std::runtime_error("code_verifier length must be 43..128");
}
static constexpr char kAlphabet[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
"-._~";
static constexpr char kAlphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
"-._~";
std::vector<std::uint8_t> rnd(length);
rand_bytes(rnd);
std::vector<std::uint8_t> rnd(length);
rand_bytes(rnd);
std::string out;
out.reserve(length);
for (std::uint8_t b : rnd) {
out.push_back(kAlphabet[b % (sizeof(kAlphabet) - 1)]);
}
return out;
}
std::string out;
out.reserve(length);
for (std::uint8_t b : rnd) {
out.push_back(kAlphabet[b % (sizeof(kAlphabet) - 1)]);
}
return out;
}
std::string Base64UrlEncode(std::span<const std::uint8_t> data) {
static constexpr char tbl[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string Base64UrlEncode(std::span<const std::uint8_t> data)
{
static constexpr char tbl[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string out;
out.reserve(((data.size() + 2) / 3) * 4);
std::string out;
out.reserve(((data.size() + 2) / 3) * 4);
std::size_t i = 0;
while (i + 3 <= data.size()) {
std::uint32_t n = (static_cast<std::uint32_t>(data[i]) << 16) |
(static_cast<std::uint32_t>(data[i + 1]) << 8) |
(static_cast<std::uint32_t>(data[i + 2]));
out.push_back(tbl[(n >> 18) & 63]);
out.push_back(tbl[(n >> 12) & 63]);
out.push_back(tbl[(n >> 6) & 63]);
out.push_back(tbl[n & 63]);
i += 3;
}
std::size_t i = 0;
while (i + 3 <= data.size()) {
std::uint32_t n = (static_cast<std::uint32_t>(data[i]) << 16) |
(static_cast<std::uint32_t>(data[i + 1]) << 8) |
(static_cast<std::uint32_t>(data[i + 2]));
out.push_back(tbl[(n >> 18) & 63]);
out.push_back(tbl[(n >> 12) & 63]);
out.push_back(tbl[(n >> 6) & 63]);
out.push_back(tbl[n & 63]);
i += 3;
}
std::size_t rem = data.size() - i;
if (rem == 1) {
std::uint32_t n = (static_cast<std::uint32_t>(data[i]) << 16);
out.push_back(tbl[(n >> 18) & 63]);
out.push_back(tbl[(n >> 12) & 63]);
out.push_back('=');
out.push_back('=');
} else if (rem == 2) {
std::uint32_t n = (static_cast<std::uint32_t>(data[i]) << 16) |
(static_cast<std::uint32_t>(data[i + 1]) << 8);
out.push_back(tbl[(n >> 18) & 63]);
out.push_back(tbl[(n >> 12) & 63]);
out.push_back(tbl[(n >> 6) & 63]);
out.push_back('=');
}
std::size_t rem = data.size() - i;
if (rem == 1) {
std::uint32_t n = (static_cast<std::uint32_t>(data[i]) << 16);
out.push_back(tbl[(n >> 18) & 63]);
out.push_back(tbl[(n >> 12) & 63]);
out.push_back('=');
out.push_back('=');
} else if (rem == 2) {
std::uint32_t n = (static_cast<std::uint32_t>(data[i]) << 16) |
(static_cast<std::uint32_t>(data[i + 1]) << 8);
out.push_back(tbl[(n >> 18) & 63]);
out.push_back(tbl[(n >> 12) & 63]);
out.push_back(tbl[(n >> 6) & 63]);
out.push_back('=');
}
// base64url + no padding
for (char& c : out) {
if (c == '+') c = '-';
else if (c == '/') c = '_';
}
while (!out.empty() && out.back() == '=') out.pop_back();
return out;
}
// base64url + no padding
for (char& c : out) {
if (c == '+') {
c = '-';
} else if (c == '/') {
c = '_';
}
}
while (!out.empty() && out.back() == '=') {
out.pop_back();
}
return out;
}
std::string GenerateState(std::size_t bytes) {
std::vector<std::uint8_t> rnd(bytes);
rand_bytes(rnd);
return Base64UrlEncode(rnd);
}
std::string GenerateState(std::size_t bytes)
{
std::vector<std::uint8_t> rnd(bytes);
rand_bytes(rnd);
return Base64UrlEncode(rnd);
}
std::vector<std::uint8_t> Sha256(std::span<const std::uint8_t> data) {
std::vector<std::uint8_t> out(SHA256_DIGEST_LENGTH);
SHA256_CTX ctx;
if (SHA256_Init(&ctx) != 1) throw std::runtime_error("SHA256_Init failed");
if (!data.empty() && SHA256_Update(&ctx, data.data(), data.size()) != 1) {
throw std::runtime_error("SHA256_Update failed");
}
if (SHA256_Final(out.data(), &ctx) != 1) throw std::runtime_error("SHA256_Final failed");
return out;
}
std::vector<std::uint8_t> Sha256(std::span<const std::uint8_t> data)
{
std::vector<std::uint8_t> out(SHA256_DIGEST_LENGTH);
SHA256_CTX ctx;
if (SHA256_Init(&ctx) != 1) {
throw std::runtime_error("SHA256_Init failed");
}
if (!data.empty() &&
SHA256_Update(&ctx, data.data(), data.size()) != 1) {
throw std::runtime_error("SHA256_Update failed");
}
if (SHA256_Final(out.data(), &ctx) != 1) {
throw std::runtime_error("SHA256_Final failed");
}
return out;
}
std::vector<std::uint8_t> Sha256(std::span<const char> data) {
auto* ptr = reinterpret_cast<const std::uint8_t*>(data.data());
return Sha256(std::span{ptr, data.size()});
}
std::vector<std::uint8_t> Sha256(std::span<const char> data)
{
auto* ptr = reinterpret_cast<const std::uint8_t*>(data.data());
return Sha256(std::span{ptr, data.size()});
}
} // namespace ts6bot::crypto
+465 -385
View File
@@ -1,7 +1,7 @@
#include "ts6bot/MusicManager.hpp"
#include "Youtube/Client.hpp"
#include "teamspeak/public_errors.h"
#include "ts6bot/Config.hpp"
#include "ts6bot/MusicManager.hpp"
#include <chrono>
#include <format>
#include <glaze/json/read.hpp>
@@ -13,494 +13,574 @@
#include "Logger.hpp"
MusicManager::MusicManager(std::shared_ptr<TS3Functions> functions, std::uint64_t serverConnectionHandlerID)
: m_functions(std::move(functions)), m_serverConnectionHandlerID(serverConnectionHandlerID) {
auto config = ts6bot::Configuration::getInstance()->getConfig();
m_client = std::make_unique<YouTube::Client>(config.music.youtubeApiToken);
m_client->SetProxy(static_cast<ProxyConfig>(config.proxy));
MusicManager::MusicManager(std::shared_ptr<TS3Functions> functions,
std::uint64_t serverConnectionHandlerID)
: m_functions(std::move(functions)),
m_serverConnectionHandlerID(serverConnectionHandlerID)
{
auto config = ts6bot::Configuration::getInstance()->getConfig();
m_client = std::make_unique<YouTube::Client>(config.music.youtubeApiToken);
m_client->SetProxy(static_cast<ProxyConfig>(config.proxy));
if (const auto err = m_functions->registerCustomDevice("custom", "custom", 192000, 2,
192000, 2);
err != ERROR_ok) {
char *errorMsg = nullptr;
m_functions->getErrorMessage(err, &errorMsg);
LOG_ERROR("Unable to register custom device: {}", errorMsg);
m_functions->freeMemory(errorMsg);
}
if (const auto err = m_functions->registerCustomDevice(
"custom", "custom", 192000, 2, 192000, 2);
err != ERROR_ok) {
char *errorMsg = nullptr;
m_functions->getErrorMessage(err, &errorMsg);
LOG_ERROR("Unable to register custom device: {}", errorMsg);
m_functions->freeMemory(errorMsg);
}
m_worker = std::jthread([this](const std::stop_token &st) { this->loop(st); });
m_worker =
std::jthread([this](const std::stop_token &st) { this->loop(st); });
}
MusicManager::~MusicManager() {
{
std::lock_guard lock(m_queueMtx);
m_worker.request_stop();
}
m_cv.notify_all(); // Wake up the thread so it can see the stop request
MusicManager::~MusicManager()
{
{
std::lock_guard lock(m_queueMtx);
m_worker.request_stop();
}
m_cv.notify_all(); // Wake up the thread so it can see the stop request
if (m_worker.joinable()) {
m_worker.join(); // Explicitly wait for it to finish before deleting members
}
if (m_worker.joinable()) {
m_worker
.join(); // Explicitly wait for it to finish before deleting members
}
if (m_microphone) {
m_microphone->Cancel();
}
if (m_microphone) {
m_microphone->Cancel();
}
}
// ============================================================================
// Search Implementation
// ============================================================================
std::string MusicManager::formatDuration(const std::string &isoDuration) {
// Regex for ISO 8601 Duration (e.g., PT1H2M10S, PT4M, PT30S)
std::regex re(R"(PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)");
std::smatch match;
if (std::regex_match(isoDuration, match, re)) {
int hours = match[1].length() ? std::stoi(match[1]) : 0;
int minutes = match[2].length() ? std::stoi(match[2]) : 0;
int seconds = match[3].length() ? std::stoi(match[3]) : 0;
std::string MusicManager::formatDuration(const std::string &isoDuration)
{
// Regex for ISO 8601 Duration (e.g., PT1H2M10S, PT4M, PT30S)
std::regex re(R"(PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)");
std::smatch match;
if (std::regex_match(isoDuration, match, re)) {
int hours = match[1].length() ? std::stoi(match[1]) : 0;
int minutes = match[2].length() ? std::stoi(match[2]) : 0;
int seconds = match[3].length() ? std::stoi(match[3]) : 0;
if (hours > 0) {
return std::format("{}:{}:{:02}", hours, minutes, seconds);
} else {
return std::format("{}:{:02}", minutes, seconds);
}
}
return isoDuration; // Fallback
if (hours > 0) {
return std::format("{}:{}:{:02}", hours, minutes, seconds);
} else {
return std::format("{}:{:02}", minutes, seconds);
}
}
return isoDuration; // Fallback
}
std::vector<definitions::SearchResultItem> MusicManager::search(std::string name,
int maxResults) const {
YouTube::SearchParams params;
params.q = std::move(name);
params.maxResults = maxResults;
params.type = {"video"};
std::vector<definitions::SearchResultItem>
MusicManager::search(std::string name, int maxResults) const
{
YouTube::SearchParams params;
params.q = std::move(name);
params.maxResults = maxResults;
params.type = {"video"};
auto searchRes = m_client->Search(params);
if (!searchRes) {
LOG_ERROR("Search failed: {} - {}", searchRes.error().status, searchRes.error().message);
return {};
}
auto searchRes = m_client->Search(params);
if (!searchRes) {
LOG_ERROR("Search failed: {} - {}", searchRes.error().status,
searchRes.error().message);
return {};
}
std::vector<std::string> videoIds;
for (const auto &item : searchRes->items) {
videoIds.push_back(item.id.videoId);
}
std::vector<std::string> videoIds;
for (const auto &item : searchRes->items) {
videoIds.push_back(item.id.videoId);
}
if (videoIds.empty())
return {};
if (videoIds.empty()) {
return {};
}
auto videosRes = m_client->GetVideos(videoIds);
std::vector<definitions::SearchResultItem> resultItems;
auto videosRes = m_client->GetVideos(videoIds);
std::vector<definitions::SearchResultItem> resultItems;
if (!videosRes) {
LOG_WARN("Failed to fetch video details, using snippets.");
for (const auto &item : searchRes->items) {
auto shortUrl = m_client->ShortUrl("https://youtube.com/watch?v=" +
item.id.videoId);
if (!videosRes) {
LOG_WARN("Failed to fetch video details, using snippets.");
for (const auto &item : searchRes->items) {
auto shortUrl = m_client->ShortUrl("https://youtube.com/watch?v=" + item.id.videoId);
resultItems.push_back(
{.name = item.snippet.title,
.length = "??:??",
.thumbnail = item.snippet.thumbnails.empty()
? ""
: item.snippet.thumbnails.begin()->second.url,
.viewCount = "N/A",
.url = "https://youtube.com/watch?v=" + item.id.videoId,
.shortUrl = shortUrl.value_or(""),
.videoId = item.id.videoId});
}
return resultItems;
}
resultItems.push_back(
{.name = item.snippet.title,
.length = "??:??",
.thumbnail = item.snippet.thumbnails.empty() ? "" : item.snippet.thumbnails.begin()->second.url,
.viewCount = "N/A",
.url = "https://youtube.com/watch?v=" + item.id.videoId,
.shortUrl = shortUrl.value_or(""),
.videoId = item.id.videoId});
}
return resultItems;
}
for (const auto &video : *videosRes) {
std::string thumbUrl;
if (!video.snippet.thumbnails.empty()) {
if (video.snippet.thumbnails.contains("high")) {
thumbUrl = video.snippet.thumbnails.at("high").url;
} else {
thumbUrl = video.snippet.thumbnails.begin()->second.url;
}
}
auto shortUrl =
m_client->ShortUrl("https://youtube.com/watch?v=" + video.id);
for (const auto &video : *videosRes) {
std::string thumbUrl;
if (!video.snippet.thumbnails.empty()) {
if (video.snippet.thumbnails.contains("high"))
thumbUrl = video.snippet.thumbnails.at("high").url;
else
thumbUrl = video.snippet.thumbnails.begin()->second.url;
}
auto shortUrl = m_client->ShortUrl("https://youtube.com/watch?v=" + video.id);
resultItems.push_back(
{.name = video.snippet.title,
.length = formatDuration(video.contentDetails.duration),
.thumbnail = thumbUrl,
.viewCount = video.statistics.viewCount,
.url = "https://youtube.com/watch?v=" + video.id,
.shortUrl = shortUrl.value_or(""),
.videoId = video.id});
}
resultItems.push_back(
{.name = video.snippet.title,
.length = formatDuration(video.contentDetails.duration),
.thumbnail = thumbUrl,
.viewCount = video.statistics.viewCount,
.url = "https://youtube.com/watch?v=" + video.id,
.shortUrl = shortUrl.value_or(""),
.videoId = video.id});
}
return resultItems;
return resultItems;
}
// ============================================================================
// Playback & Queue
// ============================================================================
std::optional<std::string> MusicManager::extractPlaylistId(std::string_view url) {
static const std::regex pl_pattern(R"(list=([a-zA-Z0-9_-]+))", std::regex::icase);
std::cmatch match;
if (std::regex_search(url.data(), match, pl_pattern)) {
return match[1].str();
}
return std::nullopt;
std::optional<std::string> MusicManager::extractPlaylistId(std::string_view url)
{
static const std::regex pl_pattern(R"(list=([a-zA-Z0-9_-]+))",
std::regex::icase);
std::cmatch match;
if (std::regex_search(url.data(), match, pl_pattern)) {
return match[1].str();
}
return std::nullopt;
}
void MusicManager::playPlaylist(const std::string& playlistId, const std::string& requester) {
LOG_INFO("Fetching playlist: {}", playlistId);
bool MusicManager::playPlaylist(const std::string &playlistId,
const std::string &requester)
{
LOG_INFO("Fetching playlist: {}", playlistId);
auto videos = m_client->GetPlaylistVideos(playlistId);
if (!videos || videos->empty()) {
LOG_ERROR("Failed to load playlist items for {}", playlistId);
return;
}
auto videos = m_client->GetPlaylistVideos(playlistId);
if (!videos || videos->empty()) {
LOG_ERROR("Failed to load playlist items for {}", playlistId);
return false;
}
std::lock_guard lock(m_queueMtx);
for (const auto& video : *videos) {
// Optimization: We skip calling m_client->ShortUrl() here
// to prevent hitting rate limits on large playlists.
std::string shortUrl;
if (const auto url = m_client->ShortUrl("https://youtube.com/watch?v=" + video.id); url) {
shortUrl = url.value_or("");
}
auto vid = Music{ .name = video.snippet.title,
.shortUrl = shortUrl, // Set to empty to save requests
.length = formatDuration(video.contentDetails.duration),
.videoId = video.id,
.requestedBy = requester,
.streams = definitions::Streams() // Will be resolved by the loop thread when played
};
m_queue.emplace_back(vid);
}
std::lock_guard lock(m_queueMtx);
for (const auto &video : *videos) {
// Optimization: We skip calling m_client->ShortUrl() here
// to prevent hitting rate limits on large playlists.
std::string shortUrl;
if (const auto url =
m_client->ShortUrl("https://youtube.com/watch?v=" + video.id);
url) {
shortUrl = url.value_or("");
}
auto vid = Music{
.name = video.snippet.title,
.shortUrl = shortUrl, // Set to empty to save requests
.length = formatDuration(video.contentDetails.duration),
.videoId = video.id,
.requestedBy = requester,
.streams = definitions::Streams() // Will be resolved by the loop
// thread when played
};
m_queue.emplace_back(vid);
}
LOG_INFO("Added {} videos from playlist to queue.", videos->size());
m_cv.notify_one();
LOG_INFO("Added {} videos from playlist to queue.", videos->size());
m_cv.notify_one();
return true;
}
void MusicManager::playUrl(std::string url, const std::string &requester) {
const auto videoIdOpt = m_client->ExtractVideoId(url);
if (!videoIdOpt) {
LOG_WARN("Invalid YouTube URI: {}", url);
return;
}
bool MusicManager::playUrl(std::string url, const std::string &requester)
{
const auto videoIdOpt = m_client->ExtractVideoId(url);
if (!videoIdOpt) {
LOG_WARN("Invalid YouTube URI: {}", url);
return false;
}
const std::string& vid = *videoIdOpt;
std::string title = "Unknown Title";
std::string shortUrl;
std::string length;
if (const auto videoInfo = m_client->GetVideo(vid, "snippet,contentDetails")) {
title = videoInfo->snippet.title;
length = formatDuration(videoInfo->contentDetails.duration);
}
if (const auto url = m_client->ShortUrl("https://youtube.com/watch?v=" + vid)) {
shortUrl = url.value_or("");
}
{
std::lock_guard lock(m_queueMtx);
// Fetch streams immediately (Note: This might be blocking, consider doing it in the loop if UI hangs)
m_queue.push_back({.name = title,
.shortUrl = shortUrl,
.length =length,
.videoId = vid,
.requestedBy = requester,
.streams = m_client->GetBestStreams(vid)});
}
LOG_INFO("Added to queue: {}", title);
m_cv.notify_one(); // Wake up loop
const std::string &vid = *videoIdOpt;
std::string title = "Unknown Title";
std::string shortUrl;
std::string length;
if (const auto videoInfo =
m_client->GetVideo(vid, "snippet,contentDetails")) {
title = videoInfo->snippet.title;
length = formatDuration(videoInfo->contentDetails.duration);
}
if (const auto url =
m_client->ShortUrl("https://youtube.com/watch?v=" + vid)) {
shortUrl = url.value_or("");
}
{
std::lock_guard lock(m_queueMtx);
// Fetch streams immediately (Note: This might be blocking, consider
// doing it in the loop if UI hangs)
m_queue.push_back({.name = title,
.shortUrl = shortUrl,
.length = length,
.videoId = vid,
.requestedBy = requester,
.streams = m_client->GetBestStreams(vid)});
}
LOG_INFO("Added to queue: {}", title);
m_cv.notify_one(); // Wake up loop
return true;
}
void MusicManager::addToQueueDirect(const std::string& vid, const std::string& title,const std::string& shortUrl, const std::string& length,
const std::string& req, std::optional<definitions::Streams> streams) {
std::lock_guard lock(m_queueMtx);
Music m;
m.name = title;
m.videoId = vid;
m.requestedBy = req;
m.shortUrl = shortUrl;
m.length = length;
if(streams) {
m.streams = YouTube::Result<definitions::Streams>(streams.value());
}
m_queue.push_back(std::move(m));
void MusicManager::addToQueueDirect(const std::string &vid,
const std::string &title,
const std::string &shortUrl,
const std::string &length,
const std::string &req,
std::optional<definitions::Streams>
streams)
{
std::lock_guard lock(m_queueMtx);
Music m;
m.name = title;
m.videoId = vid;
m.requestedBy = req;
m.shortUrl = shortUrl;
m.length = length;
if (streams) {
m.streams = YouTube::Result<definitions::Streams>(streams.value());
}
m_queue.push_back(std::move(m));
}
void MusicManager::skip() {
m_skipRequested = true;
if (m_microphone) {
m_microphone->Cancel();
}
void MusicManager::skip()
{
m_skipRequested = true;
if (m_microphone) {
m_microphone->Cancel();
}
}
void MusicManager::forceSkip() {
{
std::lock_guard lock(m_queueMtx);
m_queue.clear();
}
skip();
void MusicManager::forceSkip()
{
{
std::lock_guard lock(m_queueMtx);
m_queue.clear();
}
skip();
}
void MusicManager::stop() {
// If we want to stop completely (not just clear queue)
forceSkip();
void MusicManager::stop()
{
// If we want to stop completely (not just clear queue)
forceSkip();
}
std::vector<MusicManager::Music> MusicManager::getQueue() const {
std::lock_guard lock(m_queueMtx);
return {m_queue.begin(), m_queue.end()};
std::vector<MusicManager::Music> MusicManager::getQueue() const
{
std::lock_guard lock(m_queueMtx);
return {m_queue.begin(), m_queue.end()};
}
void MusicManager::checkQueueAndPlay() {
m_cv.notify_one();
void MusicManager::checkQueueAndPlay() { m_cv.notify_one(); }
void MusicManager::removeFromQueue(const std::size_t index)
{
std::lock_guard lock(m_queueMtx);
if (index < m_queue.size()) {
m_queue.erase(m_queue.begin() + index);
}
}
void MusicManager::removeFromQueue(const std::size_t index) {
std::lock_guard lock(m_queueMtx);
if (index < m_queue.size()) {
m_queue.erase(m_queue.begin() + index);
}
}
void MusicManager::removeFromQueue(const std::string &name) {
std::lock_guard lock(m_queueMtx);
std::erase_if(m_queue, [&](const Music &m) { return m.name == name; });
void MusicManager::removeFromQueue(const std::string &name)
{
std::lock_guard lock(m_queueMtx);
std::erase_if(m_queue, [&](const Music &m) { return m.name == name; });
}
// ============================================================================
// Main Loop
// ============================================================================
void MusicManager::loop(std::stop_token st) {
// Initial setup delay
std::this_thread::sleep_for(std::chrono::seconds(5));
void MusicManager::loop(std::stop_token st)
{
// Initial setup delay
std::this_thread::sleep_for(std::chrono::seconds(5));
auto config = ts6bot::Configuration::getInstance()->getConfig();
if (m_serverConnectionHandlerID == 0) {
// Connect GUI Tab
if (auto err = m_functions->guiConnect(
PLUGIN_CONNECT_TAB_CURRENT, "current", config.host.c_str(),
config.password.c_str(), config.nickname.c_str(),
config.channel.c_str(), "", "", "", "", "", "", "", "",
&m_serverConnectionHandlerID);
err != ERROR_ok) {
char* msg; m_functions->getErrorMessage(err, &msg);
LOG_ERROR("GUI Connect failed: {}", msg);
m_functions->freeMemory(msg);
}
}
// Setup Devices
m_functions->closeCaptureDevice(m_serverConnectionHandlerID);
m_functions->closePlaybackDevice(m_serverConnectionHandlerID);
auto config = ts6bot::Configuration::getInstance()->getConfig();
if (m_serverConnectionHandlerID == 0) {
// Connect GUI Tab
if (auto err = m_functions->guiConnect(
PLUGIN_CONNECT_TAB_CURRENT, "current", config.host.c_str(),
config.password.c_str(), config.nickname.c_str(),
config.channel.c_str(), "", "", "", "", "", "", "", "",
&m_serverConnectionHandlerID);
err != ERROR_ok) {
char *msg;
m_functions->getErrorMessage(err, &msg);
LOG_ERROR("GUI Connect failed: {}", msg);
m_functions->freeMemory(msg);
}
}
// Setup Devices
m_functions->closeCaptureDevice(m_serverConnectionHandlerID);
m_functions->closePlaybackDevice(m_serverConnectionHandlerID);
if(m_functions->openCaptureDevice(m_serverConnectionHandlerID, "custom", "custom") != ERROR_ok)
LOG_ERROR("Failed to open Capture Device");
if (m_functions->openCaptureDevice(m_serverConnectionHandlerID, "custom",
"custom") != ERROR_ok) {
LOG_ERROR("Failed to open Capture Device");
}
if(m_functions->openPlaybackDevice(m_serverConnectionHandlerID, "custom", "custom") != ERROR_ok)
LOG_ERROR("Failed to open Playback Device");
m_microphone = std::make_unique<AudioDecoder>();
if (m_functions->openPlaybackDevice(m_serverConnectionHandlerID, "custom",
"custom") != ERROR_ok) {
LOG_ERROR("Failed to open Playback Device");
}
m_microphone = std::make_unique<AudioDecoder>();
constexpr int SAMPLE_RATE = 192000;
constexpr int CHANNEL_COUNT = 2;
constexpr int CHUNK_MS = 20;
constexpr size_t SHORTS_PER_CHUNK = (SAMPLE_RATE * CHANNEL_COUNT * CHUNK_MS) / 1000;
constexpr size_t MAX_BUFFER_SHORTS = SHORTS_PER_CHUNK * 50;
constexpr int SAMPLE_RATE = 192000;
constexpr int CHANNEL_COUNT = 2;
constexpr int CHUNK_MS = 20;
constexpr size_t SHORTS_PER_CHUNK =
(SAMPLE_RATE * CHANNEL_COUNT * CHUNK_MS) / 1000;
constexpr size_t MAX_BUFFER_SHORTS = SHORTS_PER_CHUNK * 50;
while (!st.stop_requested()) {
m_isIdle = true;
while (!st.stop_requested()) {
m_isIdle = true;
// 1. Wait for Track
{
std::unique_lock lock(m_queueMtx);
m_cv.wait(lock, [&] { return !m_queue.empty() || st.stop_requested(); });
// 1. Wait for Track
{
std::unique_lock lock(m_queueMtx);
m_cv.wait(lock,
[&] { return !m_queue.empty() || st.stop_requested(); });
if (st.stop_requested()) break;
if (st.stop_requested()) {
break;
}
m_current = m_queue.front();
m_queue.pop_front();
}
m_isIdle = false;
// 2. Resolve Streams if needed (Hot reload might have provided them, new search might not)
if (!m_current->streams || m_current->streams->audio.url.empty()) {
LOG_INFO("Resolving streams for {}", m_current->name);
m_current->streams = m_client->GetBestStreams(m_current->videoId);
}
m_current = m_queue.front();
m_queue.pop_front();
}
m_isIdle = false;
// 2. Resolve Streams if needed (Hot reload might have provided them,
// new search might not)
if (!m_current->streams || m_current->streams->audio.url.empty()) {
LOG_INFO("Resolving streams for {}", m_current->name);
m_current->streams = m_client->GetBestStreams(m_current->videoId);
}
if (!m_current->streams || m_current->streams->audio.url.empty()) {
LOG_ERROR("Failed to get stream for {}", m_current->name);
m_current = std::nullopt;
continue;
}
if (!m_current->streams || m_current->streams->audio.url.empty()) {
LOG_ERROR("Failed to get stream for {}", m_current->name);
m_current = std::nullopt;
continue;
}
LOG_INFO("Now Playing: {}", m_current->name);
LOG_INFO("Now Playing: {}", m_current->name);
// 3. Start Decoding
m_microphone->StartDecode(m_current->streams->audio.url, SAMPLE_RATE);
// 3. Start Decoding
m_microphone->StartDecode(m_current->streams->audio.url, SAMPLE_RATE);
std::vector<short> localAudioBuffer;
auto next = std::chrono::steady_clock::now();
m_skipRequested = false;
std::vector<short> localAudioBuffer;
auto next = std::chrono::steady_clock::now();
m_skipRequested = false;
// 4. Playback Loop
while (!st.stop_requested() && !m_skipRequested) {
// 4. Playback Loop
while (!st.stop_requested() && !m_skipRequested) {
// Pull Data
if (localAudioBuffer.size() < MAX_BUFFER_SHORTS) {
std::vector<short> incomingChunk;
if (m_microphone->GetNextChunk(incomingChunk)) {
localAudioBuffer.insert(localAudioBuffer.end(), incomingChunk.begin(), incomingChunk.end());
}
}
// Pull Data
if (localAudioBuffer.size() < MAX_BUFFER_SHORTS) {
std::vector<short> incomingChunk;
if (m_microphone->GetNextChunk(incomingChunk)) {
localAudioBuffer.insert(localAudioBuffer.end(),
incomingChunk.begin(),
incomingChunk.end());
}
}
// Check Subscribers (Pause if none)
bool hasSubscribers = false;
{
std::lock_guard lock(m_subMtx);
hasSubscribers = !m_onlineSubscribers.empty();
}
// Check Subscribers (Pause if none)
bool hasSubscribers = false;
{
std::lock_guard lock(m_subMtx);
hasSubscribers = !m_onlineSubscribers.empty();
}
if (!hasSubscribers) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
next = std::chrono::steady_clock::now(); // Reset timing so we don't fast-forward
continue;
}
if (!hasSubscribers) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
next = std::chrono::steady_clock::now(); // Reset timing so we
// don't fast-forward
continue;
}
// Send Audio
if (localAudioBuffer.size() >= SHORTS_PER_CHUNK) {
float volMult = std::pow(m_volume.load(), 3.0f);
short chunkToSend[SHORTS_PER_CHUNK];
// Send Audio
if (localAudioBuffer.size() >= SHORTS_PER_CHUNK) {
float volMult = std::pow(m_volume.load(), 3.0f);
short chunkToSend[SHORTS_PER_CHUNK];
for (size_t i = 0; i < SHORTS_PER_CHUNK; ++i) {
int val = static_cast<int>(localAudioBuffer[i] * volMult);
chunkToSend[i] = static_cast<short>(std::clamp(val, -32768, 32767));
}
for (size_t i = 0; i < SHORTS_PER_CHUNK; ++i) {
int val = static_cast<int>(localAudioBuffer[i] * volMult);
chunkToSend[i] =
static_cast<short>(std::clamp(val, -32768, 32767));
}
localAudioBuffer.erase(localAudioBuffer.begin(), localAudioBuffer.begin() + SHORTS_PER_CHUNK);
localAudioBuffer.erase(localAudioBuffer.begin(),
localAudioBuffer.begin() +
SHORTS_PER_CHUNK);
if (m_functions->processCustomCaptureData("custom", chunkToSend, (int)(SHORTS_PER_CHUNK / CHANNEL_COUNT)) != ERROR_ok) {
// Device error handling?
}
if (m_functions->processCustomCaptureData(
"custom", chunkToSend,
(int)(SHORTS_PER_CHUNK / CHANNEL_COUNT)) != ERROR_ok) {
// Device error handling?
}
// Precision Timing
next += std::chrono::milliseconds(CHUNK_MS);
std::this_thread::sleep_until(next);
} else {
// Buffer Underrun or End of Stream?
std::vector<short> incoming;
if (m_microphone->GetNextChunk(incoming, true)) { // Blocking wait
localAudioBuffer.insert(localAudioBuffer.end(), incoming.begin(), incoming.end());
continue;
}
// Precision Timing
next += std::chrono::milliseconds(CHUNK_MS);
std::this_thread::sleep_until(next);
} else {
// Buffer Underrun or End of Stream?
std::vector<short> incoming;
if (m_microphone->GetNextChunk(incoming,
true)) { // Blocking wait
localAudioBuffer.insert(localAudioBuffer.end(),
incoming.begin(), incoming.end());
continue;
}
bool decoderEmpty;
{
std::lock_guard lock(m_microphone->m_queueMtx);
decoderEmpty = m_microphone->m_chunkQueue.empty();
}
bool decoderEmpty;
{
std::lock_guard lock(m_microphone->m_queueMtx);
decoderEmpty = m_microphone->m_chunkQueue.empty();
}
if (m_microphone->IsFinished() && decoderEmpty) {
// Drain remaining
if (!localAudioBuffer.empty()) {
localAudioBuffer.resize(SHORTS_PER_CHUNK, 0); // Pad silence
continue; // Send padded chunk
}
break; // Done
}
}
}
if (m_microphone->IsFinished() && decoderEmpty) {
// Drain remaining
if (!localAudioBuffer.empty()) {
localAudioBuffer.resize(SHORTS_PER_CHUNK,
0); // Pad silence
continue; // Send padded chunk
}
break; // Done
}
}
}
m_microphone->Cancel();
LOG_INFO("Finished track: {}", m_current->name);
m_current = std::nullopt;
m_microphone->Cancel();
LOG_INFO("Finished track: {}", m_current->name);
m_current = std::nullopt;
// Check for Graceful Stop (Update)
if (m_stopAfterCurrent) {
LOG_INFO("Graceful stop requested. Stopping main loop.");
break;
}
}
// Check for Graceful Stop (Update)
if (m_stopAfterCurrent) {
LOG_INFO("Graceful stop requested. Stopping main loop.");
break;
}
}
m_isIdle = true;
m_isIdle = true;
}
// Stubs for Subscription (Logic not fully defined in prompt, basic stub
// provided)
// ============================================================================
void MusicManager::subscribe(const anyID id) {
addSubscriberToOnline(id);
bool MusicManager::subscribe(const anyID id)
{
return addSubscriberToOnline(id);
}
void MusicManager::addSubscriberToOnline(anyID id) {
std::lock_guard lock(m_subMtx);
m_offlineSubscribers.erase(id);
m_onlineSubscribers.insert(id);
updateWhisperList();
LOG_INFO("User {} added to Online Subscribers", id);
bool MusicManager::addSubscriberToOnline(anyID id)
{
std::lock_guard lock(m_subMtx);
m_offlineSubscribers.erase(id);
auto [it, isInserted] = m_onlineSubscribers.insert(id);
updateWhisperList();
LOG_INFO("User {} added to Online Subscribers", id);
return isInserted;
}
void MusicManager::addSubscriberToOffline(const anyID id) {
std::lock_guard lock(m_subMtx);
m_onlineSubscribers.erase(id);
m_offlineSubscribers.insert(id);
updateWhisperList();
LOG_INFO("User {} added to Offline Subscribers", id);
bool MusicManager::addSubscriberToOffline(const anyID id)
{
std::lock_guard lock(m_subMtx);
m_onlineSubscribers.erase(id);
auto [it, isInserted] = m_offlineSubscribers.insert(id);
updateWhisperList();
LOG_INFO("User {} added to Offline Subscribers", id);
return isInserted;
}
void MusicManager::moveSubscriberToOffline(const anyID id) {
if (m_onlineSubscribers.contains(id)) {
addSubscriberToOffline(id);
}
void MusicManager::moveSubscriberToOffline(const anyID id)
{
if (m_onlineSubscribers.contains(id)) {
addSubscriberToOffline(id);
}
}
void MusicManager::moveSubscriberToOnline(const anyID id) {
if (m_offlineSubscribers.contains(id)) {
addSubscriberToOnline(id);
}
void MusicManager::moveSubscriberToOnline(const anyID id)
{
if (m_offlineSubscribers.contains(id)) {
addSubscriberToOnline(id);
}
}
void MusicManager::unSubscribe(anyID id) {
std::lock_guard lock(m_subMtx);
m_onlineSubscribers.erase(id);
m_offlineSubscribers.erase(id);
updateWhisperList();
LOG_INFO("User {} Unsubscribed", id);
bool MusicManager::unSubscribe(anyID id)
{
std::lock_guard lock(m_subMtx);
auto online = m_onlineSubscribers.erase(id);
auto offline = m_offlineSubscribers.erase(id);
updateWhisperList();
LOG_INFO("User {} Unsubscribed", id);
return online != 0 || offline != 0;
}
std::set<uint64_t> MusicManager::getOnlineSubscribers() const {
std::lock_guard lock(const_cast<std::mutex&>(m_subMtx));
return {m_onlineSubscribers.begin(), m_onlineSubscribers.end()};
std::set<uint64_t> MusicManager::getOnlineSubscribers() const
{
std::lock_guard lock(const_cast<std::mutex &>(m_subMtx));
return {m_onlineSubscribers.begin(), m_onlineSubscribers.end()};
}
std::set<uint64_t> MusicManager::getOfflineSubscribers() const {
std::lock_guard lock(const_cast<std::mutex&>(m_subMtx));
return {m_offlineSubscribers.begin(), m_offlineSubscribers.end()};
std::set<uint64_t> MusicManager::getOfflineSubscribers() const
{
std::lock_guard lock(const_cast<std::mutex &>(m_subMtx));
return {m_offlineSubscribers.begin(), m_offlineSubscribers.end()};
}
void MusicManager::updateWhisperList() {
if (!m_functions || m_serverConnectionHandlerID == 0)
return;
void MusicManager::updateWhisperList()
{
if (!m_functions || m_serverConnectionHandlerID == 0) {
return;
}
// We only whisper to ONLINE subscribers
std::vector<anyID> clientList(m_onlineSubscribers.begin(), m_onlineSubscribers.end());
clientList.push_back(0);
// We only whisper to ONLINE subscribers
std::vector<anyID> clientList(m_onlineSubscribers.begin(),
m_onlineSubscribers.end());
clientList.push_back(0);
anyID myID = 0;
if (m_functions->getClientID(m_serverConnectionHandlerID, &myID) != ERROR_ok) {
return;
}
anyID myID = 0;
if (m_functions->getClientID(m_serverConnectionHandlerID, &myID) !=
ERROR_ok) {
return;
}
m_functions->requestClientSetWhisperList(m_serverConnectionHandlerID, myID,
nullptr, clientList.data(), "");
m_functions->requestClientSetWhisperList(m_serverConnectionHandlerID, myID,
nullptr, clientList.data(), "");
}
void MusicManager::storePendingSearch(const anyID clientId, const std::vector<definitions::SearchResultItem> &results) {
std::lock_guard lock(m_pendingMtx);
m_pendingSearches[clientId] = results;
void MusicManager::storePendingSearch(
const anyID clientId,
const std::vector<definitions::SearchResultItem> &results)
{
std::lock_guard lock(m_pendingMtx);
m_pendingSearches[clientId] = results;
}
bool MusicManager::selectSearchResult(const anyID clientId, const int index, const std::string& requesterName) {
std::lock_guard lock(m_pendingMtx);
const auto it = m_pendingSearches.find(clientId);
if (it == m_pendingSearches.end())
return false;
bool MusicManager::selectSearchResult(const anyID clientId, const int index,
const std::string &requesterName)
{
std::lock_guard lock(m_pendingMtx);
const auto it = m_pendingSearches.find(clientId);
if (it == m_pendingSearches.end()) {
return false;
}
if (int vecIndex = index - 1; vecIndex >= 0 && vecIndex < static_cast<int>(it->second.size())) {
playUrl(it->second[vecIndex].url, requesterName);
m_pendingSearches.erase(it);
return true;
}
return false;
if (int vecIndex = index - 1;
vecIndex >= 0 && vecIndex < static_cast<int>(it->second.size())) {
m_pendingSearches.erase(it);
return playUrl(it->second[vecIndex].url, requesterName);
}
return false;
}
+284 -209
View File
@@ -2,219 +2,294 @@
#include "Logger.hpp"
void EchoionCore::Initialize(bool start)
{
// Init Logger
Logger::init(ts6bot::LogLevel::Trace);
LOG_INFO("Core Initializing...");
void EchoionCore::Initialize(bool start) {
// Init Logger
Logger::init(ts6bot::LogLevel::Trace);
LOG_INFO("Core Initializing...");
// Config
char path[512];
m_ts3->getConfigPath(path, 512);
// Services
auto cfg = ts6bot::Configuration::init(std::string(path) + "bot.json")
->getConfig();
// Config
char path[512];
m_ts3->getConfigPath(path, 512);
// Services
auto cfg = ts6bot::Configuration::init(std::string(path) + "bot.json")->getConfig();
if (start) {
m_musicManager = std::make_unique<MusicManager>(m_ts3);
}
}
void EchoionCore::Shutdown() {
if (m_musicManager) {
m_musicManager->stop();
m_musicManager.reset();
}
ts6bot::Configuration::destroyInstance();
Logger::destroyInstance();
}
// --- HOT RELOAD ---
void EchoionCore::RequestGracefulStop() {
if (m_musicManager)
m_musicManager->setStopAfterCurrent(true);
}
bool EchoionCore::IsStopped() {
return !m_musicManager || m_musicManager->isIdle();
}
std::string EchoionCore::SerializeState() {
if (!m_musicManager)
return "{}";
definitions::PluginState state;
auto q = m_musicManager->getQueue();
for (const auto &i : q) {
std::optional<definitions::Streams> streams = (i.streams.has_value() ? std::optional(i.streams.value()) : std::nullopt);
auto temp = definitions::QueueItem(i.name, i.videoId,i.shortUrl,i.length, i.requestedBy, streams);
state.queue.push_back(temp);
}
auto subs = m_musicManager->getOnlineSubscribers();
auto offsubs = m_musicManager->getOfflineSubscribers();
state.onlineSubscribers.assign(subs.begin(), subs.end());
state.offlineSubscribers.assign(offsubs.begin(), offsubs.end());
state.serverConnection = m_musicManager->getServerConnectionHandlerID();
std::string buf;
glz::write_json(state, buf);
return buf;
}
void EchoionCore::DeserializeState(const std::string &jsonState) {
definitions::PluginState state;
if (auto err = glz::read_json(state, jsonState); !err) {
if (!m_musicManager)
m_musicManager = std::make_unique<MusicManager>(m_ts3, state.serverConnection);
for (auto s : state.onlineSubscribers)
m_musicManager->addSubscriberToOnline(s);
for (auto s : state.offlineSubscribers)
m_musicManager->addSubscriberToOffline(s);
for (const auto &item : state.queue) {
m_musicManager->addToQueueDirect(item.videoId, item.name, item.shortUrl, item.length,
item.requester, item.streams);
}
m_musicManager->setServerConnectionHandlerID(state.serverConnection);
m_musicManager->checkQueueAndPlay();
}
}
int EchoionCore::onTextMessageEvent(uint64 serverConnectionHandlerID, anyID targetMode, anyID toID, anyID fromID,
const char *fromName, const char *fromUniqueIdentifier, const char *message,
int ffIgnored) {
if (!m_musicManager)
return 1;
auto reply = [this](const uint64 sc, const anyID toId, const std::string &text) {
const char* returnCode = nullptr;
this->m_ts3->requestSendPrivateTextMsg(sc, text.c_str(), toId,returnCode);
};
// 1. Only react to Direct Messages (Private Chats)
if (targetMode != TextMessageTarget_CLIENT) {
return 0;
}
// 2. Ignore own messages
anyID myID;
this->m_ts3->getClientID(serverConnectionHandlerID, &myID);
if (fromID == myID)
return 0;
std::string msgStr = message;
if (msgStr.empty() || msgStr[0] != '.')
return 0;
std::stringstream ss(msgStr);
std::string command;
ss >> command;
std::string args;
std::getline(ss, args);
if (!args.empty() && args[0] == ' ')
args.erase(0, 1);
if (command == ".play") {
if (args.find("http") == 0) {
this->m_musicManager->playUrl(args, fromName);
this->m_ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, "Added URL to queue.", fromID,
nullptr);
} else {
auto results = this->m_musicManager->search(args, 5);
if (results.empty()) {
this->m_ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, "No results found.", fromID,
nullptr);
} else if (results.size() == 1) {
this->m_musicManager->playUrl(results[0].url, fromName);
this->m_ts3->requestSendPrivateTextMsg(
serverConnectionHandlerID, std::format("Playing: [{}]({})", results[0].name, results[0].shortUrl).c_str(), fromID, nullptr);
} else {
this->m_musicManager->storePendingSearch(fromID, results);
std::string list = "Multiple results found. Use .select <number>:\n";
for (size_t i = 0; i < results.size(); ++i) {
list += std::format("{}. [{}]({}) [{}]\n",(i+1), results[i].name, results[i].shortUrl, results[i].length);
}
this->m_ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, list.c_str(), fromID, nullptr);
}
}
} else if (command == ".playlist") {
if (args.find("http") == 0) {
if (auto plId = this->m_musicManager->extractPlaylistId(args)) {
this->m_musicManager->playPlaylist(*plId, fromName);
this->m_ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, "Added PlayList to queue.", fromID,
nullptr);
}
}
} else if (command == ".select") {
try {
int idx = std::stoi(args);
if (this->m_musicManager->selectSearchResult(fromID, idx, fromName)) {
this->m_ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, "Selected song added to queue.",
fromID, nullptr);
} else {
this->m_ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, "Invalid selection.", fromID,
nullptr);
}
} catch (...) {
this->m_ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, "Please provide a valid number.",
fromID, nullptr);
}
} else if (command == ".stop") {
this->m_musicManager->stop();
reply(serverConnectionHandlerID, fromID, "Playback stopped and queue cleared.");
} else if (command == ".skip" || command == ".next") {
this->m_musicManager->skip();
reply(serverConnectionHandlerID, fromID, "Skipped current track.");
} else if (command == ".queue" || command == ".list") {
auto q = this->m_musicManager->getQueue();
auto current = this->m_musicManager->getCurrent();
std::string str =
current ? std::format("Now playing: [{}]({}) [{}]\n\n", current.value().name, current.value().shortUrl,current.value().length)
:
"";
if (q.empty() && str.empty())
reply(serverConnectionHandlerID, fromID, "Queue is empty");
for (auto i = 0; i < q.size(); i++) {
LOG_DEBUG("Adding to list {}", q.at(i).name);
str += std::format("{}. [{}]({}) [{}]\n", i+1, q.at(i).name, q.at(i).shortUrl, q.at(i).length);
}
reply(serverConnectionHandlerID, fromID, str);
} else if (command == ".sub") {
this->m_musicManager->subscribe(fromID);
reply(serverConnectionHandlerID, fromID, "You are now subscribed to the music bot.");
} else if (command == ".unsub") {
this->m_musicManager->unSubscribe(fromID);
reply(serverConnectionHandlerID, fromID, "Unsubscribed.");
} else if (command == ".help") {
reply(serverConnectionHandlerID, fromID,
".play <ссылка или название>\n.select "
"<#>\n.playlist <ссылка в которой есть \"list=\">\n.stop\n.skip\\next\n.queue\\list\n.sub\n"
".unsub");
}
return 0;
if (start) {
m_musicManager = std::make_unique<MusicManager>(m_ts3);
}
}
void EchoionCore::onClientMoveEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, uint64 newChannelID,
int visibility, const char *moveMessage) {
void EchoionCore::Shutdown()
{
if (m_musicManager) {
m_musicManager->stop();
m_musicManager.reset();
}
ts6bot::Configuration::destroyInstance();
Logger::destroyInstance();
}
if (!m_musicManager)
return;
anyID myID;
this->m_ts3->getClientID(serverConnectionHandlerID, &myID);
if (clientID == myID)
return;
// --- HOT RELOAD ---
void EchoionCore::RequestGracefulStop()
{
if (m_musicManager) {
m_musicManager->setStopAfterCurrent(true);
}
}
if (newChannelID == 0) {
if (m_musicManager) {
m_musicManager->moveSubscriberToOffline(clientID);
return;
}
}
bool EchoionCore::IsStopped()
{
return !m_musicManager || m_musicManager->isIdle();
}
if (oldChannelID == 0) {
if (m_musicManager) {
m_musicManager->moveSubscriberToOnline(clientID);
return;
}
}
}
std::string EchoionCore::SerializeState()
{
if (!m_musicManager) {
return "{}";
}
definitions::PluginState state;
auto q = m_musicManager->getQueue();
for (const auto &i : q) {
std::optional<definitions::Streams> streams =
(i.streams.has_value() ? std::optional(i.streams.value())
: std::nullopt);
auto temp = definitions::QueueItem(i.name, i.videoId, i.shortUrl,
i.length, i.requestedBy, streams);
state.queue.push_back(temp);
}
auto subs = m_musicManager->getOnlineSubscribers();
auto offsubs = m_musicManager->getOfflineSubscribers();
state.onlineSubscribers.assign(subs.begin(), subs.end());
state.offlineSubscribers.assign(offsubs.begin(), offsubs.end());
state.serverConnection = m_musicManager->getServerConnectionHandlerID();
std::string buf;
glz::write_json(state, buf);
return buf;
}
void EchoionCore::DeserializeState(const std::string &jsonState)
{
definitions::PluginState state;
if (auto err = glz::read_json(state, jsonState); !err) {
if (!m_musicManager) {
m_musicManager =
std::make_unique<MusicManager>(m_ts3, state.serverConnection);
}
for (auto s : state.onlineSubscribers) {
m_musicManager->addSubscriberToOnline(s);
}
for (auto s : state.offlineSubscribers) {
m_musicManager->addSubscriberToOffline(s);
}
for (const auto &item : state.queue) {
m_musicManager->addToQueueDirect(item.videoId, item.name,
item.shortUrl, item.length,
item.requester, item.streams);
}
m_musicManager->setServerConnectionHandlerID(state.serverConnection);
m_musicManager->checkQueueAndPlay();
}
}
int EchoionCore::onTextMessageEvent(uint64 serverConnectionHandlerID,
anyID targetMode, anyID toID, anyID fromID,
const char *fromName,
const char *fromUniqueIdentifier,
const char *message, int ffIgnored)
{
if (!m_musicManager) {
return 1;
}
auto reply = [this](const uint64 sc, const anyID toId,
const std::string &text) {
const char *returnCode = nullptr;
this->m_ts3->requestSendPrivateTextMsg(sc, text.c_str(), toId,
returnCode);
};
// 1. Only react to Direct Messages (Private Chats)
if (targetMode != TextMessageTarget_CLIENT) {
return 0;
}
// 2. Ignore own messages
anyID myID;
this->m_ts3->getClientID(serverConnectionHandlerID, &myID);
if (fromID == myID) {
return 0;
}
std::string msgStr = message;
if (msgStr.empty() || msgStr[0] != '.') {
return 0;
}
std::stringstream ss(msgStr);
std::string command;
ss >> command;
std::string args;
std::getline(ss, args);
if (!args.empty() && args[0] == ' ') {
args.erase(0, 1);
}
if (command == ".play") {
if (args.find("http") == 0) {
if (this->m_musicManager->playUrl(args, fromName)) {
this->m_ts3->requestSendPrivateTextMsg(
serverConnectionHandlerID, "Added URL to queue.", fromID,
nullptr);
} else {
this->m_ts3->requestSendPrivateTextMsg(
serverConnectionHandlerID, "Not added", fromID, nullptr);
}
} else {
auto results = this->m_musicManager->search(args, 5);
if (results.empty()) {
this->m_ts3->requestSendPrivateTextMsg(
serverConnectionHandlerID, "No results found.", fromID,
nullptr);
} else if (results.size() == 1) {
if (this->m_musicManager->playUrl(results[0].url, fromName)) {
this->m_ts3->requestSendPrivateTextMsg(
serverConnectionHandlerID,
std::format("Added: [{}]({})", results[0].name,
results[0].shortUrl)
.c_str(),
fromID, nullptr);
} else {
this->m_ts3->requestSendPrivateTextMsg(
serverConnectionHandlerID,
std::format("Failed to add: [{}]({})", results[0].name,
results[0].shortUrl)
.c_str(),
fromID, nullptr);
}
} else {
this->m_musicManager->storePendingSearch(fromID, results);
std::string list =
"Multiple results found. Use .select <number>:\n";
for (size_t i = 0; i < results.size(); ++i) {
list += std::format("{}. [{}]({}) [{}]\n", (i + 1),
results[i].name, results[i].shortUrl,
results[i].length);
}
this->m_ts3->requestSendPrivateTextMsg(
serverConnectionHandlerID, list.c_str(), fromID, nullptr);
}
}
} else if (command == ".playlist") {
if (args.find("http") == 0) {
if (auto plId = this->m_musicManager->extractPlaylistId(args)) {
if (this->m_musicManager->playPlaylist(*plId, fromName)) {
this->m_ts3->requestSendPrivateTextMsg(
serverConnectionHandlerID, "Added PlayList to queue.",
fromID, nullptr);
} else {
this->m_ts3->requestSendPrivateTextMsg(
serverConnectionHandlerID, "Not added", fromID,
nullptr);
}
}
}
} else if (command == ".select") {
try {
int idx = std::stoi(args);
if (this->m_musicManager->selectSearchResult(fromID, idx,
fromName)) {
this->m_ts3->requestSendPrivateTextMsg(
serverConnectionHandlerID, "Selected song added to queue.",
fromID, nullptr);
} else {
this->m_ts3->requestSendPrivateTextMsg(
serverConnectionHandlerID, "Invalid selection.", fromID,
nullptr);
}
} catch (...) {
this->m_ts3->requestSendPrivateTextMsg(
serverConnectionHandlerID, "Please provide a valid number.",
fromID, nullptr);
}
} else if (command == ".stop") {
this->m_musicManager->stop();
reply(serverConnectionHandlerID, fromID,
"Playback stopped and queue cleared.");
} else if (command == ".skip" || command == ".next") {
this->m_musicManager->skip();
reply(serverConnectionHandlerID, fromID, "Skipped current track.");
} else if (command == ".queue" || command == ".list") {
auto q = this->m_musicManager->getQueue();
auto current = this->m_musicManager->getCurrent();
std::string str =
current
? std::format("Now playing: [{}]({}) [{}]\n\n",
current.value().name, current.value().shortUrl,
current.value().length)
: "";
if (q.empty() && str.empty()) {
reply(serverConnectionHandlerID, fromID, "Queue is empty");
}
for (auto i = 0; i < q.size(); i++) {
LOG_DEBUG("Adding to list {}", q.at(i).name);
str += std::format("{}. [{}]({}) [{}]\n", i + 1, q.at(i).name,
q.at(i).shortUrl, q.at(i).length);
}
reply(serverConnectionHandlerID, fromID, str);
} else if (command == ".sub") {
if (this->m_musicManager->subscribe(fromID)) {
reply(serverConnectionHandlerID, fromID,
"You are now subscribed to the music bot.");
} else {
reply(serverConnectionHandlerID, fromID,
"Already subscribed to the music bot.");
}
} else if (command == ".unsub") {
if (this->m_musicManager->unSubscribe(fromID)) {
reply(serverConnectionHandlerID, fromID, "Unsubscribed.");
} else {
reply(serverConnectionHandlerID, fromID, "Not subscribed.");
}
} else if (command == ".help") {
reply(serverConnectionHandlerID, fromID,
".play <ссылка или название>\n.select "
"<#>\n.playlist <ссылка в которой есть "
"\"list=\">\n.stop\n.skip\\next\n.queue\\list\n.sub\n"
".unsub");
}
return 0;
}
void EchoionCore::onClientMoveEvent(uint64 serverConnectionHandlerID,
anyID clientID, uint64 oldChannelID,
uint64 newChannelID, int visibility,
const char *moveMessage)
{
if (!m_musicManager) {
return;
}
anyID myID;
this->m_ts3->getClientID(serverConnectionHandlerID, &myID);
if (clientID == myID) {
return;
}
if (newChannelID == 0) {
if (m_musicManager) {
m_musicManager->moveSubscriberToOffline(clientID);
return;
}
}
if (oldChannelID == 0) {
if (m_musicManager) {
m_musicManager->moveSubscriberToOnline(clientID);
return;
}
}
}
File diff suppressed because it is too large. Load diff
+169 -121
View File
@@ -12,145 +12,193 @@
#include <string_view>
#include <unordered_map>
namespace Spotify {
namespace Spotify
{
HttpCallbackServer::HttpCallbackServer(std::string host, uint16_t port, std::string path)
: m_Host(std::move(host)), m_Port(port), m_Path(std::move(path)) {
if (m_Path.empty() || m_Path[0] != '/') m_Path = "/" + m_Path;
}
HttpCallbackServer::HttpCallbackServer(std::string host, uint16_t port,
std::string path)
: m_Host(std::move(host)), m_Port(port), m_Path(std::move(path))
{
if (m_Path.empty() || m_Path[0] != '/') {
m_Path = "/" + m_Path;
}
}
static std::unordered_map<std::string, std::string> parse_query(std::string_view q) {
std::unordered_map<std::string, std::string> out;
while (!q.empty()) {
auto amp = q.find('&');
auto part = q.substr(0, amp);
if (amp == std::string_view::npos) q = {};
else q = q.substr(amp + 1);
static std::unordered_map<std::string, std::string>
parse_query(std::string_view q)
{
std::unordered_map<std::string, std::string> out;
while (!q.empty()) {
auto amp = q.find('&');
auto part = q.substr(0, amp);
if (amp == std::string_view::npos) {
q = {};
} else {
q = q.substr(amp + 1);
}
if (part.empty()) continue;
auto eq = part.find('=');
std::string k = (eq == std::string_view::npos) ? std::string(part) : std::string(part.substr(0, eq));
std::string v = (eq == std::string_view::npos) ? std::string() : std::string(part.substr(eq + 1));
// NOTE: not percent-decoding (Spotify returns base64url-ish values).
out.emplace(std::move(k), std::move(v));
}
return out;
}
if (part.empty()) {
continue;
}
auto eq = part.find('=');
std::string k = (eq == std::string_view::npos)
? std::string(part)
: std::string(part.substr(0, eq));
std::string v = (eq == std::string_view::npos)
? std::string()
: std::string(part.substr(eq + 1));
// NOTE: not percent-decoding (Spotify returns base64url-ish
// values).
out.emplace(std::move(k), std::move(v));
}
return out;
}
static void write_all(int fd, std::string_view s) {
while (!s.empty()) {
ssize_t n = ::send(fd, s.data(), s.size(), 0);
if (n < 0) {
if (errno == EINTR) continue;
break;
}
s.remove_prefix(static_cast<std::size_t>(n));
}
}
static void write_all(int fd, std::string_view s)
{
while (!s.empty()) {
ssize_t n = ::send(fd, s.data(), s.size(), 0);
if (n < 0) {
if (errno == EINTR) {
continue;
}
break;
}
s.remove_prefix(static_cast<std::size_t>(n));
}
}
std::optional<CallbackResult> HttpCallbackServer::WaitForCallback(std::chrono::milliseconds timeout) {
int listenFd = ::socket(AF_INET, SOCK_STREAM, 0);
if (listenFd < 0) throw std::runtime_error("socket() failed");
std::optional<CallbackResult>
HttpCallbackServer::WaitForCallback(std::chrono::milliseconds timeout)
{
int listenFd = ::socket(AF_INET, SOCK_STREAM, 0);
if (listenFd < 0) {
throw std::runtime_error("socket() failed");
}
int one = 1;
::setsockopt(listenFd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
int one = 1;
::setsockopt(listenFd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(m_Port);
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(m_Port);
if (m_Host == "localhost") {
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
} else {
if (::inet_pton(AF_INET, m_Host.c_str(), &addr.sin_addr) != 1) {
::close(listenFd);
throw std::runtime_error("Only IPv4 hosts supported for redirect_uri (use 127.0.0.1)");
}
}
if (m_Host == "localhost") {
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
} else {
if (::inet_pton(AF_INET, m_Host.c_str(), &addr.sin_addr) != 1) {
::close(listenFd);
throw std::runtime_error("Only IPv4 hosts supported for "
"redirect_uri (use 127.0.0.1)");
}
}
if (::bind(listenFd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != 0) {
int e = errno;
::close(listenFd);
throw std::runtime_error(std::string("bind() failed: ") + std::strerror(e));
}
if (::listen(listenFd, 1) != 0) {
int e = errno;
::close(listenFd);
throw std::runtime_error(std::string("listen() failed: ") + std::strerror(e));
}
if (::bind(listenFd, reinterpret_cast<sockaddr *>(&addr),
sizeof(addr)) != 0) {
int e = errno;
::close(listenFd);
throw std::runtime_error(std::string("bind() failed: ") +
std::strerror(e));
}
if (::listen(listenFd, 1) != 0) {
int e = errno;
::close(listenFd);
throw std::runtime_error(std::string("listen() failed: ") +
std::strerror(e));
}
pollfd pfd{listenFd, POLLIN, 0};
int pr = ::poll(&pfd, 1, static_cast<int>(timeout.count()));
if (pr <= 0) {
::close(listenFd);
return std::nullopt;
}
pollfd pfd{listenFd, POLLIN, 0};
int pr = ::poll(&pfd, 1, static_cast<int>(timeout.count()));
if (pr <= 0) {
::close(listenFd);
return std::nullopt;
}
int clientFd = ::accept(listenFd, nullptr, nullptr);
::close(listenFd);
if (clientFd < 0) return std::nullopt;
int clientFd = ::accept(listenFd, nullptr, nullptr);
::close(listenFd);
if (clientFd < 0) {
return std::nullopt;
}
std::string req;
req.reserve(2048);
char buf[2048];
while (true) {
ssize_t n = ::recv(clientFd, buf, sizeof(buf), 0);
if (n <= 0) break;
req.append(buf, buf + n);
if (req.find("\r\n\r\n") != std::string::npos) break;
if (req.size() > 8192) break;
}
std::string req;
req.reserve(2048);
char buf[2048];
while (true) {
ssize_t n = ::recv(clientFd, buf, sizeof(buf), 0);
if (n <= 0) {
break;
}
req.append(buf, buf + n);
if (req.find("\r\n\r\n") != std::string::npos) {
break;
}
if (req.size() > 8192) {
break;
}
}
CallbackResult res;
CallbackResult res;
// Parse request line: GET /path?query HTTP/1.1
std::string_view sv{req};
auto lineEnd = sv.find("\r\n");
if (lineEnd != std::string_view::npos) {
auto line = sv.substr(0, lineEnd);
if (line.starts_with("GET ")) {
line.remove_prefix(4);
auto sp = line.find(' ');
auto target = line.substr(0, sp);
// Parse request line: GET /path?query HTTP/1.1
std::string_view sv{req};
auto lineEnd = sv.find("\r\n");
if (lineEnd != std::string_view::npos) {
auto line = sv.substr(0, lineEnd);
if (line.starts_with("GET ")) {
line.remove_prefix(4);
auto sp = line.find(' ');
auto target = line.substr(0, sp);
auto qm = target.find('?');
std::string_view path = (qm == std::string_view::npos) ? target : target.substr(0, qm);
std::string_view query = (qm == std::string_view::npos) ? std::string_view{} : target.substr(qm + 1);
auto qm = target.find('?');
std::string_view path = (qm == std::string_view::npos)
? target
: target.substr(0, qm);
std::string_view query = (qm == std::string_view::npos)
? std::string_view{}
: target.substr(qm + 1);
if (path == m_Path) {
auto kv = parse_query(query);
if (auto it = kv.find("code"); it != kv.end()) res.code = it->second;
if (auto it = kv.find("state"); it != kv.end()) res.state = it->second;
if (auto it = kv.find("error"); it != kv.end()) res.error = it->second;
} else {
res.error = "invalid_path";
}
} else {
res.error = "unsupported_method";
}
} else {
res.error = "malformed_request";
}
if (path == m_Path) {
auto kv = parse_query(query);
if (auto it = kv.find("code"); it != kv.end()) {
res.code = it->second;
}
if (auto it = kv.find("state"); it != kv.end()) {
res.state = it->second;
}
if (auto it = kv.find("error"); it != kv.end()) {
res.error = it->second;
}
} else {
res.error = "invalid_path";
}
} else {
res.error = "unsupported_method";
}
} else {
res.error = "malformed_request";
}
std::string body;
if (!res.error.empty()) {
body = "<html><body><h2>Authorization failed</h2><p>" + res.error + "</p></body></html>";
} else {
body = "<html><body><h2>Authorization received</h2><p>You can close this window.</p></body></html>";
}
std::string body;
if (!res.error.empty()) {
body = "<html><body><h2>Authorization failed</h2><p>" + res.error +
"</p></body></html>";
} else {
body = "<html><body><h2>Authorization received</h2><p>You can "
"close this window.</p></body></html>";
}
std::string hdr =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=utf-8\r\n"
"Connection: close\r\n"
"Content-Length: " + std::to_string(body.size()) + "\r\n\r\n";
std::string hdr = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=utf-8\r\n"
"Connection: close\r\n"
"Content-Length: " +
std::to_string(body.size()) + "\r\n\r\n";
write_all(clientFd, hdr);
write_all(clientFd, body);
::shutdown(clientFd, SHUT_RDWR);
::close(clientFd);
write_all(clientFd, hdr);
write_all(clientFd, body);
::shutdown(clientFd, SHUT_RDWR);
::close(clientFd);
return res;
}
return res;
}
} // namespace ts6bot
} // namespace Spotify
+254 -183
View File
@@ -1,7 +1,7 @@
#include <Spotify/PkceAuth.hpp>
#include <ts6bot/Crypto.hpp>
#include <Spotify/HttpCallbackServer.hpp>
#include <ts6bot/Crypto.hpp>
#include <ts6bot/Url.hpp>
#include <curl/curl.h>
@@ -12,233 +12,304 @@
#include <sstream>
#include <stdexcept>
namespace Spotify {
namespace Spotify
{
static size_t write_cb(void* contents, size_t size, size_t nmemb, void* userp) {
auto* s = reinterpret_cast<std::string*>(userp);
s->append(reinterpret_cast<const char*>(contents), size * nmemb);
return size * nmemb;
}
static size_t write_cb(void* contents, size_t size, size_t nmemb,
void* userp)
{
auto* s = reinterpret_cast<std::string*>(userp);
s->append(reinterpret_cast<const char*>(contents), size * nmemb);
return size * nmemb;
}
static std::string http_request(const std::string& url,
const std::string& header,
const std::string& postBody,
const ProxyConfig& proxy) {
std::unique_ptr<CURL, CurlDeleter> curl(curl_easy_init());
if (!curl) throw std::runtime_error("curl_easy_init failed");
static std::string http_request(const std::string& url,
const std::string& header,
const std::string& postBody,
const ProxyConfig& proxy)
{
std::unique_ptr<CURL, CurlDeleter> curl(curl_easy_init());
if (!curl) {
throw std::runtime_error("curl_easy_init failed");
}
std::string response;
curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_cb);
curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &response);
curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);
std::string response;
curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_cb);
curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &response);
curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);
if (!proxy.url.empty()) {
curl_easy_setopt(curl.get(), CURLOPT_PROXY, proxy.url.c_str());
long curlProxyType = (proxy.type == ProxyType::SOCKS5_HOSTNAME) ? CURLPROXY_SOCKS5_HOSTNAME : CURLPROXY_SOCKS5;
curl_easy_setopt(curl.get(), CURLOPT_PROXYTYPE, curlProxyType);
if (!proxy.url.empty()) {
curl_easy_setopt(curl.get(), CURLOPT_PROXY, proxy.url.c_str());
long curlProxyType = (proxy.type == ProxyType::SOCKS5_HOSTNAME)
? CURLPROXY_SOCKS5_HOSTNAME
: CURLPROXY_SOCKS5;
curl_easy_setopt(curl.get(), CURLOPT_PROXYTYPE, curlProxyType);
if (!proxy.username.empty()) {
curl_easy_setopt(curl.get(), CURLOPT_SOCKS5_AUTH, (long)CURLAUTH_BASIC);
std::string authStr = proxy.username + ":" + proxy.password;
curl_easy_setopt(curl.get(), CURLOPT_PROXYUSERPWD, authStr.c_str());
}
}
if (!proxy.username.empty()) {
curl_easy_setopt(curl.get(), CURLOPT_SOCKS5_AUTH,
(long)CURLAUTH_BASIC);
std::string authStr = proxy.username + ":" + proxy.password;
curl_easy_setopt(curl.get(), CURLOPT_PROXYUSERPWD,
authStr.c_str());
}
}
struct curl_slist* headers = nullptr;
if (!header.empty()) {
headers = curl_slist_append(headers, header.c_str());
curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, headers);
}
struct curl_slist* headers = nullptr;
if (!header.empty()) {
headers = curl_slist_append(headers, header.c_str());
curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, headers);
}
if (!postBody.empty()) {
curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, postBody.c_str());
}
if (!postBody.empty()) {
curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, postBody.c_str());
}
CURLcode res = curl_easy_perform(curl.get());
if (headers) curl_slist_free_all(headers);
CURLcode res = curl_easy_perform(curl.get());
if (headers) {
curl_slist_free_all(headers);
}
if (res != CURLE_OK) {
throw std::runtime_error(std::string("curl error: ") + curl_easy_strerror(res));
}
if (res != CURLE_OK) {
throw std::runtime_error(std::string("curl error: ") +
curl_easy_strerror(res));
}
long httpCode = 0;
curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &httpCode);
if (httpCode < 200 || httpCode >= 300) {
std::ostringstream oss;
oss << "HTTP " << httpCode << " from " << url << "\n" << response;
throw std::runtime_error(oss.str());
}
long httpCode = 0;
curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &httpCode);
if (httpCode < 200 || httpCode >= 300) {
std::ostringstream oss;
oss << "HTTP " << httpCode << " from " << url << "\n" << response;
throw std::runtime_error(oss.str());
}
return response;
}
return response;
}
bool TokenSet::IsExpired(std::chrono::seconds skew) const {
const auto now = std::chrono::seconds{PkceAuth::NowUnixSeconds()};
const auto exp = std::chrono::seconds{expires_at_utc};
return now + skew >= exp;
}
bool TokenSet::IsExpired(std::chrono::seconds skew) const
{
const auto now = std::chrono::seconds{PkceAuth::NowUnixSeconds()};
const auto exp = std::chrono::seconds{expires_at_utc};
return now + skew >= exp;
}
std::int64_t PkceAuth::NowUnixSeconds() {
using namespace std::chrono;
return duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
}
std::int64_t PkceAuth::NowUnixSeconds()
{
using namespace std::chrono;
return duration_cast<seconds>(system_clock::now().time_since_epoch())
.count();
}
PkceAuth::PkceAuth(std::string clientId, std::string redirectUri, std::filesystem::path tokenCachePath)
: m_ClientId(std::move(clientId)), m_RedirectUri(std::move(redirectUri)), m_TokenCachePath(std::move(tokenCachePath)) {}
PkceAuth::PkceAuth(std::string clientId, std::string redirectUri,
std::filesystem::path tokenCachePath)
: m_ClientId(std::move(clientId)),
m_RedirectUri(std::move(redirectUri)),
m_TokenCachePath(std::move(tokenCachePath))
{
}
void PkceAuth::AuthorizeAndStore(const std::vector<std::string>& scopes, std::chrono::milliseconds timeout) {
auto redir = ts6bot::url::ParseHttpUrl(m_RedirectUri);
void PkceAuth::AuthorizeAndStore(const std::vector<std::string>& scopes,
std::chrono::milliseconds timeout)
{
auto redir = ts6bot::url::ParseHttpUrl(m_RedirectUri);
const std::string codeVerifier = ts6bot::crypto::GenerateCodeVerifier(64);
const auto hashed = ts6bot::crypto::Sha256(std::span{codeVerifier.data(), codeVerifier.size()});
const std::string codeChallenge = ts6bot::crypto::Base64UrlEncode(hashed);
const std::string state = ts6bot::crypto::GenerateState(16);
const std::string codeVerifier =
ts6bot::crypto::GenerateCodeVerifier(64);
const auto hashed = ts6bot::crypto::Sha256(
std::span{codeVerifier.data(), codeVerifier.size()});
const std::string codeChallenge =
ts6bot::crypto::Base64UrlEncode(hashed);
const std::string state = ts6bot::crypto::GenerateState(16);
std::string scopeStr;
for (std::size_t i = 0; i < scopes.size(); ++i) {
if (i) scopeStr += ' ';
scopeStr += scopes[i];
}
std::string scopeStr;
for (std::size_t i = 0; i < scopes.size(); ++i) {
if (i) {
scopeStr += ' ';
}
scopeStr += scopes[i];
}
std::string authUrl = "https://accounts.spotify.com/authorize";
authUrl += "?response_type=code";
authUrl += "&client_id=" + ts6bot::url::EncodeComponent(m_ClientId);
authUrl += "&redirect_uri=" + ts6bot::url::EncodeComponent(m_RedirectUri);
authUrl += "&state=" + ts6bot::url::EncodeComponent(state);
if (!scopeStr.empty()) {
authUrl += "&scope=" + ts6bot::url::EncodeComponent(scopeStr);
}
authUrl += "&code_challenge_method=S256";
authUrl += "&code_challenge=" + ts6bot::url::EncodeComponent(codeChallenge);
std::string authUrl = "https://accounts.spotify.com/authorize";
authUrl += "?response_type=code";
authUrl += "&client_id=" + ts6bot::url::EncodeComponent(m_ClientId);
authUrl +=
"&redirect_uri=" + ts6bot::url::EncodeComponent(m_RedirectUri);
authUrl += "&state=" + ts6bot::url::EncodeComponent(state);
if (!scopeStr.empty()) {
authUrl += "&scope=" + ts6bot::url::EncodeComponent(scopeStr);
}
authUrl += "&code_challenge_method=S256";
authUrl +=
"&code_challenge=" + ts6bot::url::EncodeComponent(codeChallenge);
std::println("\nOpen this URL and approve access:\n{}\n", authUrl);
std::println("Waiting for callback on {}:{}{} (timeout: {}s)...",
redir.host, redir.port, redir.path, timeout.count() / 1000);
std::println("\nOpen this URL and approve access:\n{}\n", authUrl);
std::println("Waiting for callback on {}:{}{} (timeout: {}s)...",
redir.host, redir.port, redir.path,
timeout.count() / 1000);
HttpCallbackServer srv(redir.host, redir.port, redir.path);
auto cb = srv.WaitForCallback(timeout);
if (!cb) throw std::runtime_error("Timed out waiting for OAuth redirect");
HttpCallbackServer srv(redir.host, redir.port, redir.path);
auto cb = srv.WaitForCallback(timeout);
if (!cb) {
throw std::runtime_error("Timed out waiting for OAuth redirect");
}
if (!cb->error.empty()) throw std::runtime_error("Spotify authorization failed: " + cb->error);
if (cb->state != state) throw std::runtime_error("OAuth state mismatch");
if (cb->code.empty()) throw std::runtime_error("No authorization code in callback");
if (!cb->error.empty()) {
throw std::runtime_error("Spotify authorization failed: " +
cb->error);
}
if (cb->state != state) {
throw std::runtime_error("OAuth state mismatch");
}
if (cb->code.empty()) {
throw std::runtime_error("No authorization code in callback");
}
auto tokens = ExchangeCodeForToken(cb->code, codeVerifier);
Save(tokens);
auto tokens = ExchangeCodeForToken(cb->code, codeVerifier);
Save(tokens);
if (m_Verbose) {
std::println("Saved token cache: {}", m_TokenCachePath.string());
std::println("Access expires_at_utc: {}", tokens.expires_at_utc);
}
}
if (m_Verbose) {
std::println("Saved token cache: {}", m_TokenCachePath.string());
std::println("Access expires_at_utc: {}", tokens.expires_at_utc);
}
}
TokenSet PkceAuth::ExchangeCodeForToken(const std::string& code, const std::string& codeVerifier) {
const std::string tokenUrl = "https://accounts.spotify.com/api/token";
TokenSet PkceAuth::ExchangeCodeForToken(const std::string& code,
const std::string& codeVerifier)
{
const std::string tokenUrl = "https://accounts.spotify.com/api/token";
std::string body;
body += "client_id=" + ts6bot::url::EncodeComponent(m_ClientId);
body += "&grant_type=authorization_code";
body += "&code=" + ts6bot::url::EncodeComponent(code);
body += "&redirect_uri=" + ts6bot::url::EncodeComponent(m_RedirectUri);
body += "&code_verifier=" + ts6bot::url::EncodeComponent(codeVerifier);
std::string body;
body += "client_id=" + ts6bot::url::EncodeComponent(m_ClientId);
body += "&grant_type=authorization_code";
body += "&code=" + ts6bot::url::EncodeComponent(code);
body += "&redirect_uri=" + ts6bot::url::EncodeComponent(m_RedirectUri);
body += "&code_verifier=" + ts6bot::url::EncodeComponent(codeVerifier);
auto resp = http_request(tokenUrl, "Content-Type: application/x-www-form-urlencoded", body, m_Proxy);
auto j = nlohmann::json::parse(resp);
auto resp = http_request(
tokenUrl, "Content-Type: application/x-www-form-urlencoded", body,
m_Proxy);
auto j = nlohmann::json::parse(resp);
TokenSet out;
out.access_token = j.value("access_token", "");
out.token_type = j.value("token_type", "Bearer");
out.scope = j.value("scope", "");
out.refresh_token = j.value("refresh_token", "");
int expiresIn = j.value("expires_in", 0);
TokenSet out;
out.access_token = j.value("access_token", "");
out.token_type = j.value("token_type", "Bearer");
out.scope = j.value("scope", "");
out.refresh_token = j.value("refresh_token", "");
int expiresIn = j.value("expires_in", 0);
if (out.access_token.empty() || expiresIn <= 0) {
throw std::runtime_error("Token exchange returned no access_token/expires_in\n" + resp);
}
if (out.access_token.empty() || expiresIn <= 0) {
throw std::runtime_error(
"Token exchange returned no access_token/expires_in\n" + resp);
}
out.expires_at_utc = NowUnixSeconds() + expiresIn;
return out;
}
out.expires_at_utc = NowUnixSeconds() + expiresIn;
return out;
}
TokenSet PkceAuth::RefreshAccessToken(const TokenSet& current) {
if (current.refresh_token.empty()) throw std::runtime_error("No refresh_token; run auth-init");
TokenSet PkceAuth::RefreshAccessToken(const TokenSet& current)
{
if (current.refresh_token.empty()) {
throw std::runtime_error("No refresh_token; run auth-init");
}
const std::string tokenUrl = "https://accounts.spotify.com/api/token";
std::string body;
body += "grant_type=refresh_token";
body += "&refresh_token=" + ts6bot::url::EncodeComponent(current.refresh_token);
body += "&client_id=" + ts6bot::url::EncodeComponent(m_ClientId); // required for PKCE refresh
const std::string tokenUrl = "https://accounts.spotify.com/api/token";
std::string body;
body += "grant_type=refresh_token";
body += "&refresh_token=" +
ts6bot::url::EncodeComponent(current.refresh_token);
body += "&client_id=" + ts6bot::url::EncodeComponent(
m_ClientId); // required for PKCE refresh
auto resp = http_request(tokenUrl, "Content-Type: application/x-www-form-urlencoded", body, m_Proxy);
auto j = nlohmann::json::parse(resp);
auto resp = http_request(
tokenUrl, "Content-Type: application/x-www-form-urlencoded", body,
m_Proxy);
auto j = nlohmann::json::parse(resp);
TokenSet out = current;
out.access_token = j.value("access_token", "");
out.token_type = j.value("token_type", out.token_type);
out.scope = j.value("scope", out.scope);
int expiresIn = j.value("expires_in", 0);
TokenSet out = current;
out.access_token = j.value("access_token", "");
out.token_type = j.value("token_type", out.token_type);
out.scope = j.value("scope", out.scope);
int expiresIn = j.value("expires_in", 0);
// Spotify may omit refresh_token on refresh; keep old one
if (auto rt = j.value("refresh_token", ""); !rt.empty()) out.refresh_token = rt;
// Spotify may omit refresh_token on refresh; keep old one
if (auto rt = j.value("refresh_token", ""); !rt.empty()) {
out.refresh_token = rt;
}
if (out.access_token.empty() || expiresIn <= 0) {
throw std::runtime_error("Refresh returned no access_token/expires_in\n" + resp);
}
if (out.access_token.empty() || expiresIn <= 0) {
throw std::runtime_error(
"Refresh returned no access_token/expires_in\n" + resp);
}
out.expires_at_utc = NowUnixSeconds() + expiresIn;
return out;
}
out.expires_at_utc = NowUnixSeconds() + expiresIn;
return out;
}
void PkceAuth::Save(const TokenSet& t) const {
std::filesystem::create_directories(m_TokenCachePath.parent_path());
void PkceAuth::Save(const TokenSet& t) const
{
std::filesystem::create_directories(m_TokenCachePath.parent_path());
nlohmann::json j;
j["access_token"] = t.access_token;
j["token_type"] = t.token_type;
j["scope"] = t.scope;
j["refresh_token"] = t.refresh_token;
j["expires_at_utc"] = t.expires_at_utc;
nlohmann::json j;
j["access_token"] = t.access_token;
j["token_type"] = t.token_type;
j["scope"] = t.scope;
j["refresh_token"] = t.refresh_token;
j["expires_at_utc"] = t.expires_at_utc;
auto tmp = m_TokenCachePath;
tmp += ".tmp";
auto tmp = m_TokenCachePath;
tmp += ".tmp";
{
std::ofstream f(tmp, std::ios::binary | std::ios::trunc);
if (!f) throw std::runtime_error("Failed to write token cache: " + tmp.string());
f << j.dump(2);
}
std::filesystem::rename(tmp, m_TokenCachePath);
}
{
std::ofstream f(tmp, std::ios::binary | std::ios::trunc);
if (!f) {
throw std::runtime_error("Failed to write token cache: " +
tmp.string());
}
f << j.dump(2);
}
std::filesystem::rename(tmp, m_TokenCachePath);
}
std::optional<TokenSet> PkceAuth::Load() const {
std::ifstream f(m_TokenCachePath, std::ios::binary);
if (!f) return std::nullopt;
std::optional<TokenSet> PkceAuth::Load() const
{
std::ifstream f(m_TokenCachePath, std::ios::binary);
if (!f) {
return std::nullopt;
}
nlohmann::json j;
f >> j;
nlohmann::json j;
f >> j;
TokenSet t;
t.access_token = j.value("access_token", "");
t.token_type = j.value("token_type", "Bearer");
t.scope = j.value("scope", "");
t.refresh_token = j.value("refresh_token", "");
t.expires_at_utc = j.value("expires_at_utc", 0LL);
TokenSet t;
t.access_token = j.value("access_token", "");
t.token_type = j.value("token_type", "Bearer");
t.scope = j.value("scope", "");
t.refresh_token = j.value("refresh_token", "");
t.expires_at_utc = j.value("expires_at_utc", 0LL);
if (t.access_token.empty() || t.expires_at_utc <= 0) return std::nullopt;
return t;
}
if (t.access_token.empty() || t.expires_at_utc <= 0) {
return std::nullopt;
}
return t;
}
TokenSet PkceAuth::LoadOrRefresh() {
auto loaded = Load();
if (!loaded) throw std::runtime_error("No token cache found; run auth-init");
TokenSet PkceAuth::LoadOrRefresh()
{
auto loaded = Load();
if (!loaded) {
throw std::runtime_error("No token cache found; run auth-init");
}
if (!loaded->IsExpired()) return *loaded;
if (!loaded->IsExpired()) {
return *loaded;
}
if (m_Verbose) std::println("Access token expired; refreshing...");
auto refreshed = RefreshAccessToken(*loaded);
Save(refreshed);
return refreshed;
}
if (m_Verbose) {
std::println("Access token expired; refreshing...");
}
auto refreshed = RefreshAccessToken(*loaded);
Save(refreshed);
return refreshed;
}
} // namespace ts6bot
} // namespace Spotify
+66 -44
View File
@@ -4,61 +4,83 @@
#include <stdexcept>
#include <string_view>
namespace ts6bot::url {
namespace ts6bot::url
{
std::string EncodeComponent(const std::string& s) {
CURL* h = curl_easy_init();
if (!h) throw std::runtime_error("curl_easy_init failed");
std::string EncodeComponent(const std::string& s)
{
CURL* h = curl_easy_init();
if (!h) {
throw std::runtime_error("curl_easy_init failed");
}
char* esc = curl_easy_escape(h, s.c_str(), static_cast<int>(s.size()));
curl_easy_cleanup(h);
char* esc = curl_easy_escape(h, s.c_str(), static_cast<int>(s.size()));
curl_easy_cleanup(h);
if (!esc) throw std::runtime_error("curl_easy_escape failed");
if (!esc) {
throw std::runtime_error("curl_easy_escape failed");
}
std::string out{esc};
curl_free(esc);
return out;
}
std::string out{esc};
curl_free(esc);
return out;
}
static bool starts_with(std::string_view s, std::string_view p) {
return s.size() >= p.size() && s.substr(0, p.size()) == p;
}
static bool starts_with(std::string_view s, std::string_view p)
{
return s.size() >= p.size() && s.substr(0, p.size()) == p;
}
HttpUrl ParseHttpUrl(const std::string& httpUrl) {
std::string_view s{httpUrl};
if (!starts_with(s, "http://")) {
throw std::runtime_error("redirect_uri must start with http://");
}
s.remove_prefix(7);
HttpUrl ParseHttpUrl(const std::string& httpUrl)
{
std::string_view s{httpUrl};
if (!starts_with(s, "http://")) {
throw std::runtime_error("redirect_uri must start with http://");
}
s.remove_prefix(7);
// host[:port][/path]
auto slash = s.find('/');
std::string_view hostPort = (slash == std::string_view::npos) ? s : s.substr(0, slash);
std::string_view path = (slash == std::string_view::npos) ? std::string_view{"/"} : s.substr(slash);
// host[:port][/path]
auto slash = s.find('/');
std::string_view hostPort =
(slash == std::string_view::npos) ? s : s.substr(0, slash);
std::string_view path = (slash == std::string_view::npos)
? std::string_view{"/"}
: s.substr(slash);
auto colon = hostPort.rfind(':');
if (colon == std::string_view::npos) {
throw std::runtime_error("redirect_uri must include explicit :port");
}
auto colon = hostPort.rfind(':');
if (colon == std::string_view::npos) {
throw std::runtime_error(
"redirect_uri must include explicit :port");
}
HttpUrl out;
out.host = std::string(hostPort.substr(0, colon));
if (out.host.empty()) throw std::runtime_error("redirect_uri host empty");
HttpUrl out;
out.host = std::string(hostPort.substr(0, colon));
if (out.host.empty()) {
throw std::runtime_error("redirect_uri host empty");
}
auto portSv = hostPort.substr(colon + 1);
if (portSv.empty()) throw std::runtime_error("redirect_uri port empty");
auto portSv = hostPort.substr(colon + 1);
if (portSv.empty()) {
throw std::runtime_error("redirect_uri port empty");
}
unsigned long port = 0;
for (char c : portSv) {
if (c < '0' || c > '9') throw std::runtime_error("redirect_uri port not numeric");
port = port * 10 + static_cast<unsigned long>(c - '0');
if (port > 65535) throw std::runtime_error("redirect_uri port out of range");
}
unsigned long port = 0;
for (char c : portSv) {
if (c < '0' || c > '9') {
throw std::runtime_error("redirect_uri port not numeric");
}
port = port * 10 + static_cast<unsigned long>(c - '0');
if (port > 65535) {
throw std::runtime_error("redirect_uri port out of range");
}
}
out.port = static_cast<uint16_t>(port);
out.path = std::string(path);
if (out.path.empty() || out.path[0] != '/') out.path = "/" + out.path;
return out;
}
out.port = static_cast<uint16_t>(port);
out.path = std::string(path);
if (out.path.empty() || out.path[0] != '/') {
out.path = "/" + out.path;
}
return out;
}
} // namespace ts6bot::url
File diff suppressed because it is too large. Load diff
+893 -774
View File
File diff suppressed because it is too large. Load diff