Initial commit
This commit is contained in:
commit
b4073ddf1e
20 files changed
+2747
No files matched your search
+272
@@ -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
|
||||
@@ -0,0 +1,4 @@
|
||||
*build*
|
||||
.cache
|
||||
.idea
|
||||
AGENTS.md
|
||||
@@ -0,0 +1,47 @@
|
||||
cmake_minimum_required(VERSION 3.28)
|
||||
project(EchoionApi VERSION 1.0.0 LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# Create header-only interface library for API
|
||||
add_library(EchoionApi INTERFACE)
|
||||
|
||||
add_library(Echoion::Api ALIAS EchoionApi)
|
||||
|
||||
target_include_directories(EchoionApi INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
# Require glaze for JSON serialization (header-only)
|
||||
find_package(glaze CONFIG REQUIRED)
|
||||
target_link_libraries(EchoionApi INTERFACE glaze::glaze)
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
target_link_libraries(EchoionApi INTERFACE Threads::Threads)
|
||||
|
||||
# Compiler-specific options (interface library, so use INTERFACE)
|
||||
if(MSVC)
|
||||
target_compile_options(EchoionApi INTERFACE /W4 /WX-)
|
||||
else()
|
||||
target_compile_options(EchoionApi INTERFACE -Wall -Wextra -Wpedantic)
|
||||
endif()
|
||||
|
||||
# Installation (header-only library, no archive)
|
||||
include(GNUInstallDirs)
|
||||
install(TARGETS EchoionApi
|
||||
EXPORT EchoionApiTargets
|
||||
)
|
||||
|
||||
install(EXPORT EchoionApiTargets
|
||||
FILE EchoionApiTargets.cmake
|
||||
NAMESPACE Echoion::
|
||||
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/EchoionApi
|
||||
)
|
||||
|
||||
install(DIRECTORY include/
|
||||
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
|
||||
)
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
// Main Echoion API header - includes all types
|
||||
|
||||
#include "echoion/api/Types.hpp"
|
||||
#include "echoion/api/AudioTypes.hpp"
|
||||
#include "echoion/api/TrackTypes.hpp"
|
||||
#include "echoion/api/NetworkTypes.hpp"
|
||||
#include "echoion/api/PluginTypes.hpp"
|
||||
#include "echoion/api/ConfigTypes.hpp"
|
||||
// Note: ConfigManager is deprecated - config is now passed from Plugin to Core via initialize()
|
||||
#include "echoion/api/RpcTypes.hpp"
|
||||
#include "echoion/api/YouTubeTypes.hpp"
|
||||
#include "echoion/api/LoggerInterface.hpp"
|
||||
#include "echoion/api/CoreInterface.hpp"
|
||||
#include "echoion/api/MemoryPool.hpp"
|
||||
#include "echoion/api/Cache.hpp"
|
||||
#include "echoion/api/EventBus.hpp"
|
||||
#include "echoion/api/Database.hpp"
|
||||
#include "echoion/api/Export.hpp"
|
||||
@@ -0,0 +1,113 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "MemoryPool.hpp"
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
enum class AudioFormat : uint8_t {
|
||||
Unknown = 0,
|
||||
MP3,
|
||||
AAC,
|
||||
Opus,
|
||||
Vorbis,
|
||||
FLAC,
|
||||
WAV
|
||||
};
|
||||
|
||||
enum class AudioQuality : uint8_t {
|
||||
Low = 0, // 64-96 kbps
|
||||
Medium, // 128-160 kbps
|
||||
High, // 192-256 kbps
|
||||
VeryHigh, // 320 kbps
|
||||
Lossless // FLAC or equivalent
|
||||
};
|
||||
|
||||
// Hardware acceleration types
|
||||
enum class HwAccelType : uint8_t {
|
||||
None = 0,
|
||||
CUDA, // NVIDIA CUDA
|
||||
VAAPI, // Video Acceleration API (Linux)
|
||||
DXVA2, // DirectX Video Acceleration 2 (Windows)
|
||||
D3D11VA, // Direct3D 11 Video Acceleration
|
||||
VideoToolbox, // Apple VideoToolbox
|
||||
Vulkan // Vulkan Video
|
||||
};
|
||||
|
||||
struct AudioFrame {
|
||||
std::vector<uint8_t> data;
|
||||
std::chrono::milliseconds pts;
|
||||
std::chrono::milliseconds duration;
|
||||
bool isKeyFrame;
|
||||
};
|
||||
|
||||
struct AudioStreamInfo {
|
||||
AudioFormat format;
|
||||
uint32_t sampleRate;
|
||||
uint32_t channels;
|
||||
uint32_t bitrate;
|
||||
std::chrono::milliseconds duration;
|
||||
std::optional<AudioQuality> quality;
|
||||
bool hwAccelerated = false;
|
||||
HwAccelType hwAccelType = HwAccelType::None;
|
||||
};
|
||||
|
||||
// Zero-copy decoded audio using pooled memory
|
||||
struct DecodedAudio {
|
||||
// Use pooled buffer instead of std::vector for zero-copy
|
||||
PooledPtr<float> pooledSamples;
|
||||
|
||||
// Non-owning view into the data
|
||||
FloatAudioView view;
|
||||
|
||||
uint32_t sampleRate;
|
||||
uint32_t channels;
|
||||
std::chrono::milliseconds timestamp;
|
||||
|
||||
// Backwards compatibility - creates a copy
|
||||
[[nodiscard]] std::vector<float> getSamples() const {
|
||||
if (view.empty()) {
|
||||
return {};
|
||||
}
|
||||
return std::vector<float>(view.data(), view.data() + view.size());
|
||||
}
|
||||
|
||||
// Check if valid
|
||||
[[nodiscard]] bool isValid() const {
|
||||
return !view.empty();
|
||||
}
|
||||
|
||||
// Apply volume in-place
|
||||
void applyVolume(float volume) {
|
||||
view.applyGain(volume);
|
||||
}
|
||||
};
|
||||
|
||||
// Hardware acceleration configuration
|
||||
struct HwAccelConfig {
|
||||
HwAccelType type = HwAccelType::None;
|
||||
int deviceIndex = -1; // -1 for auto-select
|
||||
std::optional<std::string> deviceName;
|
||||
|
||||
[[nodiscard]] bool isEnabled() const {
|
||||
return type != HwAccelType::None;
|
||||
}
|
||||
};
|
||||
|
||||
// Audio processing options
|
||||
struct AudioProcessOptions {
|
||||
float volume = 1.0f;
|
||||
bool normalize = false;
|
||||
bool highPassFilter = false; // Remove DC offset
|
||||
float highPassFreq = 20.0f; // Hz
|
||||
bool limiter = false; // Prevent clipping
|
||||
float limiterThreshold = 0.95f;
|
||||
};
|
||||
|
||||
using AudioBuffer = std::vector<uint8_t>;
|
||||
using AudioFramePtr = std::shared_ptr<AudioFrame>;
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,389 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "NetworkTypes.hpp"
|
||||
#include "TrackTypes.hpp"
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <chrono>
|
||||
#include <optional>
|
||||
#include <functional>
|
||||
#include <list>
|
||||
#include <memory>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// Cache entry with metadata
|
||||
template<typename T>
|
||||
struct CacheEntry {
|
||||
T value;
|
||||
std::chrono::system_clock::time_point created;
|
||||
std::chrono::system_clock::time_point lastAccessed;
|
||||
std::chrono::milliseconds ttl;
|
||||
uint64_t accessCount = 0;
|
||||
size_t size = 0; // Approximate memory size
|
||||
|
||||
[[nodiscard]] bool isExpired() const {
|
||||
auto now = std::chrono::system_clock::now();
|
||||
return (now - created) > ttl;
|
||||
}
|
||||
};
|
||||
|
||||
// Cache statistics
|
||||
struct CacheStats {
|
||||
size_t hits = 0;
|
||||
size_t misses = 0;
|
||||
size_t evictions = 0;
|
||||
size_t inserts = 0;
|
||||
size_t currentSize = 0;
|
||||
size_t maxSize = 0;
|
||||
size_t memoryUsage = 0;
|
||||
double hitRate() const {
|
||||
auto total = hits + misses;
|
||||
return total > 0 ? static_cast<double>(hits) / total : 0.0;
|
||||
}
|
||||
};
|
||||
|
||||
// Eviction policy
|
||||
enum class EvictionPolicy {
|
||||
LRU, // Least Recently Used
|
||||
LFU, // Least Frequently Used
|
||||
FIFO, // First In First Out
|
||||
TTL // Time To Live only
|
||||
};
|
||||
|
||||
// LRU Cache implementation
|
||||
template<typename Key, typename Value>
|
||||
class LruCache {
|
||||
public:
|
||||
using Entry = CacheEntry<Value>;
|
||||
using Loader = std::function<std::optional<Value>(const Key&)>;
|
||||
|
||||
explicit LruCache(size_t maxSize = 1000,
|
||||
std::chrono::milliseconds defaultTtl = std::chrono::minutes(5),
|
||||
EvictionPolicy policy = EvictionPolicy::LRU)
|
||||
: maxSize_(maxSize)
|
||||
, defaultTtl_(defaultTtl)
|
||||
, policy_(policy) {}
|
||||
|
||||
// Get value from cache (with optional loader for cache-aside pattern)
|
||||
[[nodiscard]] std::optional<Value> get(const Key& key, Loader loader = nullptr) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
|
||||
auto it = cache_.find(key);
|
||||
if (it != cache_.end()) {
|
||||
// Check if expired
|
||||
if (it->second.entry.isExpired()) {
|
||||
// Remove expired entry
|
||||
memoryUsage_ -= it->second.entry.size;
|
||||
removeFromOrder(it->second.orderIt);
|
||||
cache_.erase(it);
|
||||
stats_.evictions++;
|
||||
lock.unlock();
|
||||
stats_.misses++;
|
||||
|
||||
// Try to load if loader provided
|
||||
if (loader) {
|
||||
auto value = loader(key);
|
||||
if (value) {
|
||||
put(key, *value);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Update access info
|
||||
it->second.entry.lastAccessed = std::chrono::system_clock::now();
|
||||
it->second.entry.accessCount++;
|
||||
|
||||
// Move to front (MRU) for LRU policy
|
||||
if (policy_ == EvictionPolicy::LRU) {
|
||||
order_.splice(order_.begin(), order_, it->second.orderIt);
|
||||
}
|
||||
|
||||
stats_.hits++;
|
||||
return it->second.entry.value;
|
||||
}
|
||||
|
||||
lock.unlock();
|
||||
stats_.misses++;
|
||||
|
||||
// Try to load if loader provided
|
||||
if (loader) {
|
||||
auto value = loader(key);
|
||||
if (value) {
|
||||
put(key, *value);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Put value into cache
|
||||
void put(const Key& key, const Value& value,
|
||||
std::optional<std::chrono::milliseconds> ttl = std::nullopt,
|
||||
size_t estimatedSize = 0) {
|
||||
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
|
||||
// Check if key already exists
|
||||
auto it = cache_.find(key);
|
||||
if (it != cache_.end()) {
|
||||
// Update existing entry
|
||||
memoryUsage_ -= it->second.entry.size;
|
||||
it->second.entry.value = value;
|
||||
it->second.entry.created = std::chrono::system_clock::now();
|
||||
it->second.entry.lastAccessed = it->second.entry.created;
|
||||
it->second.entry.ttl = ttl.value_or(defaultTtl_);
|
||||
it->second.entry.size = estimatedSize;
|
||||
memoryUsage_ += estimatedSize;
|
||||
|
||||
// Move to front for LRU
|
||||
if (policy_ == EvictionPolicy::LRU) {
|
||||
order_.splice(order_.begin(), order_, it->second.orderIt);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Evict entries if necessary
|
||||
while (cache_.size() >= maxSize_ ||
|
||||
(maxMemory_ > 0 && memoryUsage_ + estimatedSize > maxMemory_)) {
|
||||
if (!evictOne()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Insert new entry
|
||||
order_.push_front(key);
|
||||
Entry entry{
|
||||
.value = value,
|
||||
.created = std::chrono::system_clock::now(),
|
||||
.lastAccessed = entry.created,
|
||||
.ttl = ttl.value_or(defaultTtl_),
|
||||
.accessCount = 1,
|
||||
.size = estimatedSize
|
||||
};
|
||||
|
||||
cache_[key] = {
|
||||
.entry = std::move(entry),
|
||||
.orderIt = order_.begin()
|
||||
};
|
||||
|
||||
memoryUsage_ += estimatedSize;
|
||||
stats_.inserts++;
|
||||
stats_.currentSize = cache_.size();
|
||||
}
|
||||
|
||||
// Remove specific key
|
||||
bool remove(const Key& key) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
|
||||
auto it = cache_.find(key);
|
||||
if (it == cache_.end()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
memoryUsage_ -= it->second.entry.size;
|
||||
removeFromOrder(it->second.orderIt);
|
||||
cache_.erase(it);
|
||||
stats_.currentSize = cache_.size();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Clear all entries
|
||||
void clear() {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
cache_.clear();
|
||||
order_.clear();
|
||||
memoryUsage_ = 0;
|
||||
stats_.currentSize = 0;
|
||||
}
|
||||
|
||||
// Check if key exists (without updating access)
|
||||
[[nodiscard]] bool contains(const Key& key) const {
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
return cache_.find(key) != cache_.end();
|
||||
}
|
||||
|
||||
// Get cache statistics
|
||||
[[nodiscard]] CacheStats getStats() const {
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
CacheStats stats = stats_;
|
||||
stats.currentSize = cache_.size();
|
||||
stats.maxSize = maxSize_;
|
||||
stats.memoryUsage = memoryUsage_;
|
||||
return stats;
|
||||
}
|
||||
|
||||
// Reset statistics
|
||||
void resetStats() {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
stats_ = CacheStats{};
|
||||
}
|
||||
|
||||
// Set max size
|
||||
void setMaxSize(size_t maxSize) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
maxSize_ = maxSize;
|
||||
|
||||
// Evict if necessary
|
||||
while (cache_.size() > maxSize_) {
|
||||
if (!evictOne()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Set max memory (0 = unlimited)
|
||||
void setMaxMemory(size_t maxMemory) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
maxMemory_ = maxMemory;
|
||||
|
||||
// Evict if necessary
|
||||
if (maxMemory_ > 0) {
|
||||
while (memoryUsage_ > maxMemory_) {
|
||||
if (!evictOne()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove expired entries
|
||||
size_t purgeExpired() {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
size_t count = 0;
|
||||
|
||||
auto now = std::chrono::system_clock::now();
|
||||
for (auto it = cache_.begin(); it != cache_.end();) {
|
||||
if ((now - it->second.entry.created) > it->second.entry.ttl) {
|
||||
memoryUsage_ -= it->second.entry.size;
|
||||
removeFromOrder(it->second.orderIt);
|
||||
it = cache_.erase(it);
|
||||
count++;
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
stats_.evictions += count;
|
||||
stats_.currentSize = cache_.size();
|
||||
return count;
|
||||
}
|
||||
|
||||
private:
|
||||
struct Node {
|
||||
Entry entry;
|
||||
typename std::list<Key>::iterator orderIt;
|
||||
};
|
||||
|
||||
bool evictOne() {
|
||||
if (order_.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Key keyToEvict;
|
||||
|
||||
switch (policy_) {
|
||||
case EvictionPolicy::LRU:
|
||||
case EvictionPolicy::FIFO:
|
||||
// Evict from back (oldest/least recently used)
|
||||
keyToEvict = order_.back();
|
||||
break;
|
||||
|
||||
case EvictionPolicy::LFU: {
|
||||
// Find least frequently used
|
||||
auto minAccess = std::numeric_limits<uint64_t>::max();
|
||||
for (const auto& [key, node] : cache_) {
|
||||
if (node.entry.accessCount < minAccess) {
|
||||
minAccess = node.entry.accessCount;
|
||||
keyToEvict = key;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case EvictionPolicy::TTL: {
|
||||
// Find soonest to expire
|
||||
auto now = std::chrono::system_clock::now();
|
||||
auto minRemaining = std::chrono::milliseconds::max();
|
||||
for (const auto& [key, node] : cache_) {
|
||||
auto remaining = node.entry.ttl - (now - node.entry.created);
|
||||
if (remaining < minRemaining) {
|
||||
minRemaining = remaining;
|
||||
keyToEvict = key;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
auto it = cache_.find(keyToEvict);
|
||||
if (it != cache_.end()) {
|
||||
memoryUsage_ -= it->second.entry.size;
|
||||
removeFromOrder(it->second.orderIt);
|
||||
cache_.erase(it);
|
||||
stats_.evictions++;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void removeFromOrder(typename std::list<Key>::iterator it) {
|
||||
order_.erase(it);
|
||||
}
|
||||
|
||||
mutable std::shared_mutex mutex_;
|
||||
std::unordered_map<Key, Node> cache_;
|
||||
std::list<Key> order_; // For LRU/FIFO ordering
|
||||
|
||||
size_t maxSize_;
|
||||
size_t maxMemory_ = 0;
|
||||
size_t memoryUsage_ = 0;
|
||||
std::chrono::milliseconds defaultTtl_;
|
||||
EvictionPolicy policy_;
|
||||
|
||||
mutable CacheStats stats_;
|
||||
};
|
||||
|
||||
// Type aliases for common cache types
|
||||
using StringCache = LruCache<std::string, std::string>;
|
||||
using HttpCache = LruCache<std::string, HttpResponse>;
|
||||
using TrackCache = LruCache<std::string, TrackInfo>;
|
||||
|
||||
// Cache manager for multiple cache types
|
||||
class CacheManager {
|
||||
public:
|
||||
static CacheManager& instance();
|
||||
|
||||
void initialize();
|
||||
void shutdown();
|
||||
|
||||
// Get specific caches
|
||||
[[nodiscard]] HttpCache& httpCache() { return httpCache_; }
|
||||
[[nodiscard]] TrackCache& trackCache() { return trackCache_; }
|
||||
[[nodiscard]] StringCache& metadataCache() { return metadataCache_; }
|
||||
|
||||
// Purge all expired entries
|
||||
void purgeAllExpired();
|
||||
|
||||
// Clear all caches
|
||||
void clearAll();
|
||||
|
||||
// Get combined stats
|
||||
[[nodiscard]] std::unordered_map<std::string, CacheStats> getAllStats() const;
|
||||
|
||||
private:
|
||||
CacheManager() = default;
|
||||
|
||||
HttpCache httpCache_{100, std::chrono::minutes(5)};
|
||||
TrackCache trackCache_{500, std::chrono::hours(1)};
|
||||
StringCache metadataCache_{1000, std::chrono::minutes(30)};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,96 @@
|
||||
#pragma once
|
||||
|
||||
#include "ConfigTypes.hpp"
|
||||
#include <filesystem>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <optional>
|
||||
#include <functional>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
/**
|
||||
* @brief DEPRECATED: Global configuration manager
|
||||
*
|
||||
* This singleton pattern does NOT work across shared library boundaries.
|
||||
* Each shared library (Plugin and Core) gets its own instance.
|
||||
*
|
||||
* NEW ARCHITECTURE:
|
||||
* - Plugin loads config using ConfigLoader
|
||||
- Plugin passes config to Core via CoreLoader::setConfig() -> Core::initialize()
|
||||
* - Core stores config locally, updates via Core::updateConfig()
|
||||
* - Config reload: Core calls plugin->reloadConfig() -> Core::updateConfig()
|
||||
*
|
||||
* This header is kept for backward compatibility but should not be used.
|
||||
*/
|
||||
class ConfigManager {
|
||||
public:
|
||||
using ConfigChangedCallback = std::function<void(const AppConfig&)>;
|
||||
|
||||
// Get singleton instance
|
||||
static ConfigManager& instance();
|
||||
|
||||
// Delete copy/move
|
||||
ConfigManager(const ConfigManager&) = delete;
|
||||
ConfigManager& operator=(const ConfigManager&) = delete;
|
||||
|
||||
// Initialize with config file path (call once at startup)
|
||||
[[nodiscard]] bool initialize(const std::filesystem::path& configPath);
|
||||
|
||||
// Initialize with default path (~/.config/echoion/config.json)
|
||||
[[nodiscard]] bool initialize();
|
||||
|
||||
// Get current config (thread-safe)
|
||||
[[nodiscard]] AppConfig getConfig() const;
|
||||
|
||||
// Get config by reference (faster, but hold lock briefly)
|
||||
template<typename Func>
|
||||
auto withConfig(Func&& func) const -> decltype(func(std::declval<const AppConfig&>())) {
|
||||
std::shared_lock lock(mutex_);
|
||||
return func(config_);
|
||||
}
|
||||
|
||||
// Reload configuration from file
|
||||
[[nodiscard]] bool reload();
|
||||
|
||||
// Save current configuration to file
|
||||
[[nodiscard]] bool save();
|
||||
|
||||
// Update config (and optionally save)
|
||||
void updateConfig(const AppConfig& config, bool saveToFile = true);
|
||||
|
||||
// Check if initialized
|
||||
[[nodiscard]] bool isInitialized() const;
|
||||
|
||||
// Get config file path
|
||||
[[nodiscard]] std::filesystem::path getConfigPath() const;
|
||||
|
||||
// Get default config path (~/.config/echoion/config.json)
|
||||
[[nodiscard]] static std::filesystem::path getDefaultConfigPath();
|
||||
|
||||
// Subscribe to config changes
|
||||
void onConfigChanged(ConfigChangedCallback callback);
|
||||
|
||||
// Create default config file if it doesn't exist
|
||||
[[nodiscard]] bool createDefaultConfigIfNeeded();
|
||||
|
||||
private:
|
||||
ConfigManager() = default;
|
||||
~ConfigManager() = default;
|
||||
|
||||
mutable std::shared_mutex mutex_;
|
||||
AppConfig config_;
|
||||
std::filesystem::path configPath_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
std::vector<ConfigChangedCallback> callbacks_;
|
||||
mutable std::mutex callbackMutex_;
|
||||
|
||||
void notifyCallbacks();
|
||||
[[nodiscard]] bool loadFromFileInternal();
|
||||
[[nodiscard]] bool saveToFileInternal();
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
|
||||
// Convenience macro for accessing config
|
||||
#define ECHOION_CONFIG (::Echoion::Api::ConfigManager::instance().getConfig())
|
||||
@@ -0,0 +1,93 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "NetworkTypes.hpp"
|
||||
#include "echoion/api/AudioTypes.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <variant>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
using ConfigValue = std::variant<
|
||||
std::monostate,
|
||||
bool,
|
||||
int64_t,
|
||||
double,
|
||||
std::string,
|
||||
std::vector<std::string>
|
||||
>;
|
||||
|
||||
struct ConfigEntry {
|
||||
std::string key;
|
||||
ConfigValue value;
|
||||
std::string description;
|
||||
bool isSecret;
|
||||
std::optional<ConfigValue> defaultValue;
|
||||
std::optional<std::string> category;
|
||||
};
|
||||
|
||||
struct BotConfig {
|
||||
std::string botName = "Echoion";
|
||||
std::string commandPrefix = "!";
|
||||
float defaultVolume = 0.5f;
|
||||
bool autoReconnect = true;
|
||||
std::chrono::milliseconds reconnectDelay = 5000ms;
|
||||
uint32_t maxReconnectAttempts = 5;
|
||||
std::optional<ProxyConfig> proxy;
|
||||
std::optional<std::string> youtubeApiKey;
|
||||
AudioQuality preferredQuality = AudioQuality::High;
|
||||
bool allowPlaylistImports = true;
|
||||
uint32_t maxQueueSize = 100;
|
||||
std::chrono::milliseconds trackTimeout = 30000ms;
|
||||
uint16_t rpcPort = 8765; // WebSocket RPC server port for Desktop/API clients
|
||||
|
||||
// YouTube cookie file path for yt-dlp authentication
|
||||
// See: https://github.com/yt-dlp/yt-dlp/wiki/Extractors#exporting-youtube-cookies
|
||||
std::optional<std::string> youtubeCookiesPath;
|
||||
|
||||
// Alternative: use cookies from browser directly
|
||||
// e.g., "chrome", "firefox", "safari", "edge"
|
||||
std::optional<std::string> cookiesFromBrowser;
|
||||
};
|
||||
|
||||
struct ServerConfig {
|
||||
std::string address;
|
||||
uint16_t port;
|
||||
std::string serverPassword;
|
||||
std::string nickname;
|
||||
std::optional<std::string> defaultChannelId;
|
||||
std::optional<std::string> channelPassword;
|
||||
std::vector<uint64_t> adminGroups;
|
||||
std::vector<uint64_t> djGroups;
|
||||
std::vector<uint64_t> bannedGroups;
|
||||
};
|
||||
|
||||
struct AdminCredentials {
|
||||
std::string username;
|
||||
std::string passwordHash;
|
||||
std::optional<std::string> salt;
|
||||
std::vector<std::string> permissions;
|
||||
std::chrono::system_clock::time_point createdAt;
|
||||
std::optional<std::chrono::system_clock::time_point> lastLogin;
|
||||
bool isActive;
|
||||
};
|
||||
|
||||
struct SecurityConfig {
|
||||
bool requireAuthForAdmin = true;
|
||||
uint32_t maxLoginAttempts = 5;
|
||||
std::chrono::milliseconds lockoutDuration = 300000ms;
|
||||
std::chrono::milliseconds sessionTimeout = 3600000ms;
|
||||
bool enableAuditLog = true;
|
||||
};
|
||||
|
||||
struct AppConfig {
|
||||
BotConfig bot;
|
||||
ServerConfig server;
|
||||
SecurityConfig security;
|
||||
std::map<std::string, ConfigEntry> custom;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,163 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "TrackTypes.hpp"
|
||||
#include "PluginTypes.hpp"
|
||||
#include "ConfigTypes.hpp"
|
||||
#include "RpcTypes.hpp"
|
||||
#include "NetworkTypes.hpp"
|
||||
#include <filesystem>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <functional>
|
||||
#include <expected>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// Forward declarations
|
||||
class IAudioDecoder;
|
||||
class IMusicManager;
|
||||
class ICommandManager;
|
||||
class IPluginInterface;
|
||||
class ICoreInterface;
|
||||
|
||||
// Network client interface
|
||||
class INetworkClient {
|
||||
public:
|
||||
virtual ~INetworkClient() = default;
|
||||
|
||||
// Initialize with optional proxy
|
||||
virtual Result<void> initialize(const std::optional<ProxyConfig>& proxy = std::nullopt) = 0;
|
||||
virtual void shutdown() = 0;
|
||||
|
||||
// Synchronous requests
|
||||
[[nodiscard]] virtual Result<HttpResponse> get(std::string_view url,
|
||||
const std::vector<HttpHeader>& headers = {}) = 0;
|
||||
[[nodiscard]] virtual Result<HttpResponse> post(std::string_view url,
|
||||
std::string_view body, const std::vector<HttpHeader>& headers = {}) = 0;
|
||||
[[nodiscard]] virtual Result<HttpResponse> request(const HttpRequest& req) = 0;
|
||||
|
||||
// Asynchronous requests
|
||||
[[nodiscard]] virtual std::future<Result<HttpResponse>> getAsync(std::string_view url,
|
||||
const std::vector<HttpHeader>& headers = {}) = 0;
|
||||
[[nodiscard]] virtual std::future<Result<HttpResponse>> postAsync(std::string_view url,
|
||||
std::string_view body, const std::vector<HttpHeader>& headers = {}) = 0;
|
||||
[[nodiscard]] virtual std::future<Result<HttpResponse>> requestAsync(const HttpRequest& req) = 0;
|
||||
|
||||
// Proxy configuration
|
||||
virtual void setProxy(const std::optional<ProxyConfig>& proxy) = 0;
|
||||
[[nodiscard]] virtual std::optional<ProxyConfig> getProxy() const = 0;
|
||||
virtual void clearProxy() = 0;
|
||||
|
||||
// Retry configuration
|
||||
virtual void setRetryConfig(const RetryConfig& config) = 0;
|
||||
[[nodiscard]] virtual RetryConfig getRetryConfig() const = 0;
|
||||
};
|
||||
|
||||
// Plugin interface that the core will use
|
||||
class IPluginInterface {
|
||||
public:
|
||||
virtual ~IPluginInterface() = default;
|
||||
|
||||
// Lifecycle
|
||||
virtual Result<void> initialize() = 0;
|
||||
virtual Result<void> shutdown() = 0;
|
||||
|
||||
// Client operations
|
||||
[[nodiscard]] virtual Result<std::vector<ClientInfo>> getClients() const = 0;
|
||||
[[nodiscard]] virtual Result<std::optional<ClientInfo>> getClient(uint64_t clientId) const = 0;
|
||||
virtual Result<void> moveClient(uint64_t clientId, uint64_t channelId) = 0;
|
||||
virtual Result<void> kickClient(uint64_t clientId, const std::string& reason) = 0;
|
||||
|
||||
// Channel operations
|
||||
[[nodiscard]] virtual Result<std::vector<ChannelInfo>> getChannels() const = 0;
|
||||
[[nodiscard]] virtual Result<std::optional<ChannelInfo>> getChannel(uint64_t channelId) const = 0;
|
||||
|
||||
// Messaging
|
||||
virtual Result<void> sendTextMessage(uint64_t targetId, const std::string& message) = 0;
|
||||
virtual Result<void> sendChannelMessage(uint64_t channelId, const std::string& message) = 0;
|
||||
virtual Result<void> sendServerMessage(const std::string& message) = 0;
|
||||
|
||||
// Audio
|
||||
virtual Result<void> sendAudioData(const std::span<const uint8_t>& data) = 0;
|
||||
virtual Result<void> setWhisperList(const std::vector<uint64_t>& clientIds) = 0;
|
||||
|
||||
// Server connection
|
||||
virtual Result<void> connectToServer(const ServerConfig& config) = 0;
|
||||
virtual Result<void> disconnectFromServer() = 0;
|
||||
[[nodiscard]] virtual bool isConnected() const = 0;
|
||||
virtual Result<void> reconnect() = 0;
|
||||
|
||||
// Event subscription
|
||||
virtual void registerEventCallback(const EventCallback& callback) = 0;
|
||||
virtual void unregisterEventCallback(const EventCallback& callback) = 0;
|
||||
};
|
||||
|
||||
using PluginInterfacePtr = std::shared_ptr<IPluginInterface>;
|
||||
|
||||
// Core interface that the plugin will use to communicate with the core
|
||||
class ICoreInterface {
|
||||
public:
|
||||
virtual ~ICoreInterface() = default;
|
||||
|
||||
// Lifecycle
|
||||
// Plugin passes config file path, Core loads config internally (no AppConfig dependency in Plugin)
|
||||
virtual Result<void> initialize(const std::filesystem::path& configPath) = 0;
|
||||
virtual Result<void> shutdown() = 0;
|
||||
virtual bool isInitialized() const noexcept = 0;
|
||||
|
||||
// Playback control
|
||||
virtual Result<void> play(const TrackInfo& track) = 0;
|
||||
virtual Result<void> pause() = 0;
|
||||
virtual Result<void> resume() = 0;
|
||||
virtual Result<void> stop() = 0;
|
||||
virtual Result<void> skip(uint32_t count = 1) = 0;
|
||||
virtual Result<void> seek(std::chrono::milliseconds position) = 0;
|
||||
virtual Result<void> setVolume(float volume) = 0;
|
||||
|
||||
// Queue management
|
||||
virtual Result<uint64_t> queueTrack(const TrackInfo& track, uint64_t clientId) = 0;
|
||||
virtual Result<void> removeFromQueue(uint64_t queueId) = 0;
|
||||
virtual Result<void> clearQueue() = 0;
|
||||
[[nodiscard]] virtual Result<std::vector<QueueEntry>> getQueue() const = 0;
|
||||
virtual Result<void> moveInQueue(uint64_t queueId, uint32_t newPosition) = 0;
|
||||
|
||||
// Track info
|
||||
[[nodiscard]] virtual Result<std::optional<QueueEntry>> getCurrentTrack() const = 0;
|
||||
[[nodiscard]] virtual Result<PlaybackState> getPlaybackState() const = 0;
|
||||
|
||||
// Playlist
|
||||
virtual Result<void> loadPlaylist(const std::string& playlistId, uint64_t clientId) = 0;
|
||||
virtual Result<std::vector<PlaylistInfo>> getPlaylists() const = 0;
|
||||
|
||||
// Configuration
|
||||
virtual Result<void> updateConfig(const AppConfig& config) = 0;
|
||||
[[nodiscard]] virtual Result<AppConfig> getConfig() const = 0;
|
||||
|
||||
// Hot reload
|
||||
virtual Result<HotReloadState> prepareForHotReload() = 0;
|
||||
virtual Result<void> restoreAfterHotReload(const HotReloadState& state) = 0;
|
||||
|
||||
// Event handling
|
||||
virtual void registerEventCallback(const EventCallback& callback) = 0;
|
||||
virtual void unregisterEventCallback(const EventCallback& callback) = 0;
|
||||
|
||||
// Plugin event processing
|
||||
virtual Result<void> onPluginEvent(const PluginEvent& event) = 0;
|
||||
|
||||
// Status
|
||||
[[nodiscard]] virtual std::string getVersion() const = 0;
|
||||
[[nodiscard]] virtual std::chrono::system_clock::time_point getUptime() const = 0;
|
||||
|
||||
// Plugin interface
|
||||
virtual void setPluginInterface(PluginInterfacePtr pluginInterface) = 0;
|
||||
|
||||
// Trigger auto-connect (call after setPluginInterface)
|
||||
virtual void triggerAutoConnect() = 0;
|
||||
};
|
||||
|
||||
using CoreInterfacePtr = std::shared_ptr<ICoreInterface>;
|
||||
using CoreCreateFunc = std::function<CoreInterfacePtr()>;
|
||||
using CoreDestroyFunc = std::function<void(ICoreInterface*)>;
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,210 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "TrackTypes.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <optional>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// Forward declaration
|
||||
class DatabaseImpl;
|
||||
|
||||
// Database configuration
|
||||
struct DatabaseConfig {
|
||||
std::string path = "echoion.db";
|
||||
bool walMode = true; // Write-Ahead Logging for better concurrency
|
||||
int maxConnections = 4;
|
||||
std::chrono::seconds busyTimeout{5000};
|
||||
};
|
||||
|
||||
// Playlist with tracks
|
||||
struct Playlist {
|
||||
uint64_t id;
|
||||
std::string name;
|
||||
std::string description;
|
||||
uint64_t createdBy;
|
||||
std::chrono::system_clock::time_point createdAt;
|
||||
std::chrono::system_clock::time_point updatedAt;
|
||||
std::vector<TrackInfo> tracks;
|
||||
bool isPublic = false;
|
||||
};
|
||||
|
||||
// Playback history entry
|
||||
struct PlaybackHistoryEntry {
|
||||
uint64_t id;
|
||||
TrackInfo track;
|
||||
uint64_t playedBy;
|
||||
std::chrono::system_clock::time_point playedAt;
|
||||
std::chrono::milliseconds duration; // How long it played
|
||||
bool completed = false; // Did it play to the end
|
||||
};
|
||||
|
||||
// User favorites
|
||||
struct FavoriteTrack {
|
||||
TrackInfo track;
|
||||
uint64_t userId;
|
||||
std::chrono::system_clock::time_point addedAt;
|
||||
};
|
||||
|
||||
// Statistics
|
||||
struct PlaybackStatistics {
|
||||
uint64_t totalPlays = 0;
|
||||
uint64_t totalTracks = 0;
|
||||
uint64_t totalPlaytimeMs = 0;
|
||||
std::optional<TrackInfo> mostPlayedTrack;
|
||||
uint64_t mostPlayedCount = 0;
|
||||
};
|
||||
|
||||
// Main database interface
|
||||
class Database {
|
||||
public:
|
||||
Database();
|
||||
~Database();
|
||||
|
||||
// Non-copyable
|
||||
Database(const Database&) = delete;
|
||||
Database& operator=(const Database&) = delete;
|
||||
|
||||
// Initialization
|
||||
Api::Result<void> initialize(const DatabaseConfig& config = {});
|
||||
void shutdown();
|
||||
[[nodiscard]] bool isInitialized() const;
|
||||
|
||||
// Migrations
|
||||
Api::Result<void> migrate(); // Run pending migrations
|
||||
[[nodiscard]] int getCurrentVersion() const;
|
||||
|
||||
// ===== Playlists =====
|
||||
|
||||
// Create a new playlist
|
||||
[[nodiscard]] Api::Result<uint64_t> createPlaylist(
|
||||
const std::string& name,
|
||||
const std::string& description,
|
||||
uint64_t createdBy,
|
||||
bool isPublic = false);
|
||||
|
||||
// Get playlist by ID
|
||||
[[nodiscard]] Api::Result<std::optional<Playlist>> getPlaylist(uint64_t id);
|
||||
|
||||
// Get all playlists for a user
|
||||
[[nodiscard]] Api::Result<std::vector<Playlist>> getUserPlaylists(uint64_t userId);
|
||||
|
||||
// Update playlist
|
||||
Api::Result<void> updatePlaylist(uint64_t id,
|
||||
const std::optional<std::string>& name = std::nullopt,
|
||||
const std::optional<std::string>& description = std::nullopt,
|
||||
const std::optional<bool>& isPublic = std::nullopt);
|
||||
|
||||
// Delete playlist
|
||||
Api::Result<void> deletePlaylist(uint64_t id);
|
||||
|
||||
// Add track to playlist
|
||||
Api::Result<void> addTrackToPlaylist(uint64_t playlistId,
|
||||
const TrackInfo& track, uint32_t position = 0);
|
||||
|
||||
// Remove track from playlist
|
||||
Api::Result<void> removeTrackFromPlaylist(uint64_t playlistId, uint64_t trackId);
|
||||
|
||||
// Reorder playlist tracks
|
||||
Api::Result<void> reorderPlaylistTrack(uint64_t playlistId,
|
||||
uint64_t trackId, uint32_t newPosition);
|
||||
|
||||
// ===== Playback History =====
|
||||
|
||||
// Record a playback
|
||||
Api::Result<void> recordPlayback(const TrackInfo& track,
|
||||
uint64_t playedBy,
|
||||
std::chrono::milliseconds duration,
|
||||
bool completed);
|
||||
|
||||
// Get playback history for a user
|
||||
[[nodiscard]] Api::Result<std::vector<PlaybackHistoryEntry>> getPlaybackHistory(
|
||||
uint64_t userId,
|
||||
size_t limit = 100,
|
||||
size_t offset = 0);
|
||||
|
||||
// Get recently played tracks
|
||||
[[nodiscard]] Api::Result<std::vector<TrackInfo>> getRecentlyPlayed(
|
||||
uint64_t userId,
|
||||
size_t limit = 20);
|
||||
|
||||
// ===== Favorites =====
|
||||
|
||||
// Add track to favorites
|
||||
Api::Result<void> addFavorite(uint64_t userId, const TrackInfo& track);
|
||||
|
||||
// Remove track from favorites
|
||||
Api::Result<void> removeFavorite(uint64_t userId, const std::string& trackUrl);
|
||||
|
||||
// Check if track is favorited
|
||||
[[nodiscard]] Api::Result<bool> isFavorite(uint64_t userId, const std::string& trackUrl);
|
||||
|
||||
// Get all favorites for a user
|
||||
[[nodiscard]] Api::Result<std::vector<FavoriteTrack>> getFavorites(uint64_t userId);
|
||||
|
||||
// ===== Statistics =====
|
||||
|
||||
// Get playback statistics
|
||||
[[nodiscard]] Api::Result<PlaybackStatistics> getStatistics(
|
||||
uint64_t userId,
|
||||
std::optional<std::chrono::system_clock::time_point> since = std::nullopt);
|
||||
|
||||
// Get most played tracks
|
||||
[[nodiscard]] Api::Result<std::vector<std::pair<TrackInfo, uint64_t>>> getMostPlayed(
|
||||
uint64_t userId,
|
||||
size_t limit = 10);
|
||||
|
||||
// ===== Subscriptions =====
|
||||
|
||||
// Add a subscriber
|
||||
Api::Result<void> addSubscriber(uint64_t clientId);
|
||||
|
||||
// Remove a subscriber
|
||||
Api::Result<void> removeSubscriber(uint64_t clientId);
|
||||
|
||||
// Check if client is subscribed
|
||||
[[nodiscard]] Api::Result<bool> isSubscriber(uint64_t clientId);
|
||||
|
||||
// Get all subscribers
|
||||
[[nodiscard]] Api::Result<std::vector<uint64_t>> getAllSubscribers();
|
||||
|
||||
// Get subscriber count
|
||||
[[nodiscard]] Api::Result<size_t> getSubscriberCount();
|
||||
|
||||
// ===== Cache Management =====
|
||||
|
||||
// Clear old history (keep last N entries)
|
||||
Api::Result<void> trimHistory(size_t keepCount = 10000);
|
||||
|
||||
// Clear all data for a user
|
||||
Api::Result<void> clearUserData(uint64_t userId);
|
||||
|
||||
// Vacuum database (reclaim space)
|
||||
Api::Result<void> vacuum();
|
||||
|
||||
// ===== Raw Query (for advanced use) =====
|
||||
|
||||
using RowCallback = std::function<void(const std::vector<std::optional<std::string>>&)>;
|
||||
Api::Result<void> executeQuery(const std::string& sql, RowCallback callback = nullptr);
|
||||
|
||||
private:
|
||||
std::unique_ptr<DatabaseImpl> impl_;
|
||||
};
|
||||
|
||||
// Database manager (singleton)
|
||||
class DatabaseManager {
|
||||
public:
|
||||
static Database& instance();
|
||||
|
||||
static Api::Result<void> initialize(const DatabaseConfig& config = {});
|
||||
static void shutdown();
|
||||
|
||||
private:
|
||||
DatabaseManager() = default;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,269 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "echoion/api/ConfigTypes.hpp"
|
||||
#include "echoion/api/PluginTypes.hpp"
|
||||
#include "echoion/api/TrackTypes.hpp"
|
||||
#include <functional>
|
||||
#include <typeindex>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <queue>
|
||||
#include <thread>
|
||||
#include <condition_variable>
|
||||
#include <atomic>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// Base event interface
|
||||
struct IEvent {
|
||||
virtual ~IEvent() = default;
|
||||
virtual std::type_index getType() const = 0;
|
||||
std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now();
|
||||
};
|
||||
|
||||
// Typed event wrapper
|
||||
template<typename T>
|
||||
struct Event : IEvent {
|
||||
T data;
|
||||
|
||||
explicit Event(T d) : data(std::move(d)) {}
|
||||
|
||||
std::type_index getType() const override {
|
||||
return std::type_index(typeid(T));
|
||||
}
|
||||
};
|
||||
|
||||
// Event handler type
|
||||
template<typename T>
|
||||
using EventHandler = std::function<void(const T&)>;
|
||||
|
||||
// Subscription token for unsubscribing
|
||||
class SubscriptionToken {
|
||||
public:
|
||||
using Id = uint64_t;
|
||||
|
||||
SubscriptionToken() = default;
|
||||
explicit SubscriptionToken(Id id, std::type_index type,
|
||||
std::weak_ptr<std::function<void(const std::shared_ptr<IEvent>&)>> handler)
|
||||
: id_(id), type_(type), handler_(std::move(handler)) {}
|
||||
|
||||
[[nodiscard]] bool isValid() const { return id_ != 0; }
|
||||
[[nodiscard]] Id getId() const { return id_; }
|
||||
[[nodiscard]] std::type_index getType() const { return type_; }
|
||||
|
||||
private:
|
||||
Id id_ = 0;
|
||||
std::type_index type_ = std::type_index(typeid(void));
|
||||
std::weak_ptr<std::function<void(const std::shared_ptr<IEvent>&)>> handler_;
|
||||
|
||||
friend class EventBus;
|
||||
};
|
||||
|
||||
// Event bus for decoupled communication
|
||||
class EventBus {
|
||||
public:
|
||||
EventBus();
|
||||
~EventBus();
|
||||
|
||||
// Delete copy/move
|
||||
EventBus(const EventBus&) = delete;
|
||||
EventBus& operator=(const EventBus&) = delete;
|
||||
EventBus(EventBus&&) = delete;
|
||||
EventBus& operator=(EventBus&&) = delete;
|
||||
|
||||
// Start processing events
|
||||
void start();
|
||||
void stop();
|
||||
|
||||
// Publish an event (thread-safe)
|
||||
template<typename T>
|
||||
void publish(T event) {
|
||||
auto evt = std::make_shared<Event<T>>(std::move(event));
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(queueMutex_);
|
||||
eventQueue_.push(evt);
|
||||
}
|
||||
queueCv_.notify_one();
|
||||
}
|
||||
|
||||
// Subscribe to events (thread-safe)
|
||||
template<typename T>
|
||||
[[nodiscard]] SubscriptionToken subscribe(EventHandler<T> handler) {
|
||||
auto wrappedHandler = std::make_shared<std::function<void(const std::shared_ptr<IEvent>&)>>(
|
||||
[h = std::move(handler)](const std::shared_ptr<IEvent>& evt) {
|
||||
if (auto typedEvt = std::dynamic_pointer_cast<Event<T>>(evt)) {
|
||||
h(typedEvt->data);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
std::type_index type(typeid(T));
|
||||
auto id = nextId_++;
|
||||
|
||||
{
|
||||
std::unique_lock<std::shared_mutex> lock(handlersMutex_);
|
||||
handlers_[type][id] = wrappedHandler;
|
||||
}
|
||||
|
||||
return SubscriptionToken(id, type, wrappedHandler);
|
||||
}
|
||||
|
||||
// Unsubscribe from events
|
||||
void unsubscribe(const SubscriptionToken& token);
|
||||
|
||||
// Process a single event immediately (for synchronous processing)
|
||||
void processOne();
|
||||
|
||||
// Wait for and process one event (blocking)
|
||||
bool waitAndProcessOne(std::chrono::milliseconds timeout);
|
||||
|
||||
// Clear all pending events
|
||||
void clearQueue();
|
||||
|
||||
// Get number of pending events
|
||||
[[nodiscard]] size_t getPendingEventCount() const;
|
||||
|
||||
private:
|
||||
void processEvents();
|
||||
|
||||
mutable std::shared_mutex handlersMutex_;
|
||||
std::unordered_map<std::type_index, std::unordered_map<SubscriptionToken::Id,
|
||||
std::shared_ptr<std::function<void(const std::shared_ptr<IEvent>&)>>>> handlers_;
|
||||
|
||||
mutable std::mutex queueMutex_;
|
||||
std::queue<std::shared_ptr<IEvent>> eventQueue_;
|
||||
std::condition_variable queueCv_;
|
||||
|
||||
std::atomic<bool> running_{false};
|
||||
std::atomic<bool> stopRequested_{false};
|
||||
std::jthread eventThread_;
|
||||
|
||||
std::atomic<SubscriptionToken::Id> nextId_{1};
|
||||
};
|
||||
|
||||
// Global event bus singleton
|
||||
class GlobalEventBus {
|
||||
public:
|
||||
[[nodiscard]] static EventBus& instance();
|
||||
|
||||
private:
|
||||
GlobalEventBus() = default;
|
||||
};
|
||||
|
||||
// Common event types for Echoion
|
||||
namespace Events {
|
||||
|
||||
// Playback events
|
||||
struct PlaybackStarted {
|
||||
TrackInfo track;
|
||||
uint64_t clientId;
|
||||
};
|
||||
|
||||
struct PlaybackPaused {
|
||||
std::chrono::milliseconds position;
|
||||
};
|
||||
|
||||
struct PlaybackResumed {
|
||||
std::chrono::milliseconds position;
|
||||
};
|
||||
|
||||
struct PlaybackStopped {};
|
||||
|
||||
struct TrackFinished {
|
||||
TrackInfo track;
|
||||
bool autoSkipped;
|
||||
};
|
||||
|
||||
struct VolumeChanged {
|
||||
float oldVolume;
|
||||
float newVolume;
|
||||
uint64_t changedByClientId;
|
||||
};
|
||||
|
||||
// Queue events
|
||||
struct TrackQueued {
|
||||
TrackInfo track;
|
||||
uint64_t queueId;
|
||||
uint64_t addedByClientId;
|
||||
uint32_t position;
|
||||
};
|
||||
|
||||
struct TrackRemoved {
|
||||
uint64_t queueId;
|
||||
uint64_t removedByClientId;
|
||||
};
|
||||
|
||||
struct QueueCleared {
|
||||
uint64_t clearedByClientId;
|
||||
};
|
||||
|
||||
struct QueueShuffled {
|
||||
uint64_t triggeredByClientId;
|
||||
};
|
||||
|
||||
// Connection events
|
||||
struct ClientConnected {
|
||||
ClientInfo client;
|
||||
};
|
||||
|
||||
struct ClientDisconnected {
|
||||
uint64_t clientId;
|
||||
std::string reason;
|
||||
};
|
||||
|
||||
struct ChannelChanged {
|
||||
uint64_t clientId;
|
||||
uint64_t oldChannelId;
|
||||
uint64_t newChannelId;
|
||||
};
|
||||
|
||||
// Error events
|
||||
struct PlaybackError {
|
||||
ErrorCode code;
|
||||
std::string message;
|
||||
std::optional<TrackInfo> track;
|
||||
};
|
||||
|
||||
struct NetworkError {
|
||||
std::string url;
|
||||
ErrorCode code;
|
||||
std::string message;
|
||||
};
|
||||
|
||||
// Configuration events
|
||||
struct ConfigReloaded {
|
||||
BotConfig newConfig;
|
||||
};
|
||||
|
||||
struct ConfigChanged {
|
||||
std::string key;
|
||||
std::string oldValue;
|
||||
std::string newValue;
|
||||
};
|
||||
|
||||
// Cache events
|
||||
struct CacheHit {
|
||||
std::string key;
|
||||
std::string type;
|
||||
};
|
||||
|
||||
struct CacheMiss {
|
||||
std::string key;
|
||||
std::string type;
|
||||
};
|
||||
|
||||
struct CacheEvicted {
|
||||
std::string key;
|
||||
std::string reason;
|
||||
};
|
||||
|
||||
} // namespace Events
|
||||
|
||||
// Helper macros for event publishing/subscribing
|
||||
#define ECHOION_PUBLISH(event) Echoion::Api::GlobalEventBus::instance().publish(event)
|
||||
#define ECHOION_SUBSCRIBE(type, handler) Echoion::Api::GlobalEventBus::instance().subscribe<type>(handler)
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,39 @@
|
||||
#pragma once
|
||||
|
||||
#include "CoreInterface.hpp"
|
||||
|
||||
// Platform-specific export macros
|
||||
#ifdef _WIN32
|
||||
#ifdef ECHOION_API_EXPORT
|
||||
#define ECHOION_API __declspec(dllexport)
|
||||
#else
|
||||
#define ECHOION_API __declspec(dllimport)
|
||||
#endif
|
||||
#else
|
||||
#define ECHOION_API __attribute__((visibility("default")))
|
||||
#endif
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// Version information
|
||||
constexpr uint32_t VERSION_MAJOR = 1;
|
||||
constexpr uint32_t VERSION_MINOR = 0;
|
||||
constexpr uint32_t VERSION_PATCH = 0;
|
||||
constexpr const char* VERSION_STRING = "1.0.0";
|
||||
|
||||
// API export functions
|
||||
extern "C" {
|
||||
// Create a new core instance
|
||||
ECHOION_API CoreInterfacePtr CreateCore();
|
||||
|
||||
// Destroy a core instance
|
||||
ECHOION_API void DestroyCore(ICoreInterface* core);
|
||||
|
||||
// Get API version
|
||||
ECHOION_API const char* GetApiVersion();
|
||||
|
||||
// Check if API is compatible
|
||||
ECHOION_API bool IsApiCompatible(uint32_t major, uint32_t minor);
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,104 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include <string>
|
||||
#include <functional>
|
||||
#include <source_location>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// Logger interface for the user's custom logger implementation
|
||||
class ILogger {
|
||||
public:
|
||||
virtual ~ILogger() = default;
|
||||
|
||||
// Core logging method
|
||||
virtual void log(LogLevel level, std::string_view message,
|
||||
std::source_location location = std::source_location::current()) = 0;
|
||||
|
||||
// Convenience methods
|
||||
virtual void debug(std::string_view message,
|
||||
std::source_location location = std::source_location::current()) {
|
||||
log(LogLevel::Debug, message, location);
|
||||
}
|
||||
|
||||
virtual void info(std::string_view message,
|
||||
std::source_location location = std::source_location::current()) {
|
||||
log(LogLevel::Info, message, location);
|
||||
}
|
||||
|
||||
virtual void warning(std::string_view message,
|
||||
std::source_location location = std::source_location::current()) {
|
||||
log(LogLevel::Warning, message, location);
|
||||
}
|
||||
|
||||
virtual void error(std::string_view message,
|
||||
std::source_location location = std::source_location::current()) {
|
||||
log(LogLevel::Error, message, location);
|
||||
}
|
||||
|
||||
virtual void critical(std::string_view message,
|
||||
std::source_location location = std::source_location::current()) {
|
||||
log(LogLevel::Critical, message, location);
|
||||
}
|
||||
|
||||
// Template method for formatted logging
|
||||
template<typename... Args>
|
||||
void logf(LogLevel level, std::format_string<Args...> fmt, Args&&... args,
|
||||
std::source_location location = std::source_location::current()) {
|
||||
log(level, std::format(fmt, std::forward<Args>(args)...), location);
|
||||
}
|
||||
|
||||
// Set minimum log level
|
||||
virtual void setMinLevel(LogLevel level) = 0;
|
||||
[[nodiscard]] virtual LogLevel getMinLevel() const = 0;
|
||||
|
||||
// Register log callback
|
||||
using LogCallback = std::function<void(const LogEntry&)>;
|
||||
virtual void registerCallback(const LogCallback& callback) = 0;
|
||||
virtual void unregisterCallback(const LogCallback& callback) = 0;
|
||||
};
|
||||
|
||||
using LoggerPtr = std::shared_ptr<ILogger>;
|
||||
|
||||
// Global logger accessor
|
||||
class LoggerRegistry {
|
||||
public:
|
||||
static LoggerRegistry& instance() {
|
||||
static LoggerRegistry instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
void setLogger(LoggerPtr logger) { logger_ = std::move(logger); }
|
||||
[[nodiscard]] LoggerPtr getLogger() const { return logger_; }
|
||||
|
||||
[[nodiscard]] bool hasLogger() const noexcept { return static_cast<bool>(logger_); }
|
||||
|
||||
private:
|
||||
LoggerRegistry() = default;
|
||||
LoggerPtr logger_;
|
||||
};
|
||||
|
||||
// Convenience macros
|
||||
#define ECHOION_LOG_DEBUG(msg) \
|
||||
do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \
|
||||
logger->debug(msg); } while(0)
|
||||
|
||||
#define ECHOION_LOG_INFO(msg) \
|
||||
do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \
|
||||
logger->info(msg); } while(0)
|
||||
|
||||
#define ECHOION_LOG_WARNING(msg) \
|
||||
do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \
|
||||
logger->warning(msg); } while(0)
|
||||
|
||||
#define ECHOION_LOG_ERROR(msg) \
|
||||
do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \
|
||||
logger->error(msg); } while(0)
|
||||
|
||||
#define ECHOION_LOG_CRITICAL(msg) \
|
||||
do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \
|
||||
logger->critical(msg); } while(0)
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,287 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <atomic>
|
||||
#include <cstring>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// Custom allocator for audio buffers
|
||||
template<typename T>
|
||||
class MemoryPool {
|
||||
public:
|
||||
explicit MemoryPool(size_t blockSize, size_t initialBlocks = 64)
|
||||
: blockSize_(blockSize)
|
||||
, capacity_(initialBlocks) {
|
||||
|
||||
// Pre-allocate memory
|
||||
storage_.resize(blockSize_ * capacity_);
|
||||
|
||||
// Initialize free list
|
||||
for (size_t i = 0; i < capacity_; ++i) {
|
||||
freeList_.push(&storage_[i * blockSize_]);
|
||||
}
|
||||
|
||||
available_.store(capacity_, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
~MemoryPool() = default;
|
||||
|
||||
// Non-copyable, non-movable
|
||||
MemoryPool(const MemoryPool&) = delete;
|
||||
MemoryPool& operator=(const MemoryPool&) = delete;
|
||||
MemoryPool(MemoryPool&&) = delete;
|
||||
MemoryPool& operator=(MemoryPool&&) = delete;
|
||||
|
||||
// Allocate a block
|
||||
[[nodiscard]] T* acquire() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (freeList_.empty()) {
|
||||
// Grow pool if needed
|
||||
grow();
|
||||
}
|
||||
|
||||
if (freeList_.empty()) {
|
||||
return nullptr; // Out of memory
|
||||
}
|
||||
|
||||
T* block = freeList_.front();
|
||||
freeList_.pop();
|
||||
available_.fetch_sub(1, std::memory_order_relaxed);
|
||||
|
||||
return block;
|
||||
}
|
||||
|
||||
// Release a block back to pool
|
||||
void release(T* block) {
|
||||
if (!block) return;
|
||||
|
||||
// Verify block belongs to this pool
|
||||
if (!contains(block)) {
|
||||
return; // Or assert/panic
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
freeList_.push(block);
|
||||
available_.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
// Get available blocks count
|
||||
[[nodiscard]] size_t available() const {
|
||||
return available_.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
// Get total capacity
|
||||
[[nodiscard]] size_t capacity() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return capacity_;
|
||||
}
|
||||
|
||||
// Get block size
|
||||
[[nodiscard]] size_t blockSize() const {
|
||||
return blockSize_;
|
||||
}
|
||||
|
||||
// Reserve additional blocks
|
||||
void reserve(size_t additionalBlocks) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
size_t oldCapacity = capacity_;
|
||||
size_t newCapacity = capacity_ + additionalBlocks;
|
||||
|
||||
storage_.resize(blockSize_ * newCapacity);
|
||||
|
||||
// Add new blocks to free list
|
||||
for (size_t i = oldCapacity; i < newCapacity; ++i) {
|
||||
freeList_.push(&storage_[i * blockSize_]);
|
||||
}
|
||||
|
||||
capacity_ = newCapacity;
|
||||
available_.fetch_add(additionalBlocks, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
private:
|
||||
[[nodiscard]] bool contains(const T* block) const {
|
||||
return block >= &storage_[0] &&
|
||||
block <= &storage_[(capacity_ - 1) * blockSize_];
|
||||
}
|
||||
|
||||
void grow() {
|
||||
// Double the capacity
|
||||
size_t additionalBlocks = capacity_;
|
||||
reserve(additionalBlocks);
|
||||
}
|
||||
|
||||
size_t blockSize_;
|
||||
size_t capacity_;
|
||||
std::vector<T> storage_;
|
||||
std::queue<T*> freeList_;
|
||||
mutable std::mutex mutex_;
|
||||
std::atomic<size_t> available_;
|
||||
};
|
||||
|
||||
// Smart pointer for pooled memory
|
||||
template<typename T>
|
||||
class PooledPtr {
|
||||
public:
|
||||
PooledPtr() = default;
|
||||
|
||||
PooledPtr(T* ptr, MemoryPool<T>* pool)
|
||||
: ptr_(ptr), pool_(pool) {}
|
||||
|
||||
~PooledPtr() {
|
||||
reset();
|
||||
}
|
||||
|
||||
// Move semantics only
|
||||
PooledPtr(PooledPtr&& other) noexcept
|
||||
: ptr_(other.ptr_), pool_(other.pool_) {
|
||||
other.ptr_ = nullptr;
|
||||
other.pool_ = nullptr;
|
||||
}
|
||||
|
||||
PooledPtr& operator=(PooledPtr&& other) noexcept {
|
||||
if (this != &other) {
|
||||
reset();
|
||||
ptr_ = other.ptr_;
|
||||
pool_ = other.pool_;
|
||||
other.ptr_ = nullptr;
|
||||
other.pool_ = nullptr;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Delete copy
|
||||
PooledPtr(const PooledPtr&) = delete;
|
||||
PooledPtr& operator=(const PooledPtr&) = delete;
|
||||
|
||||
[[nodiscard]] T* get() const { return ptr_; }
|
||||
[[nodiscard]] T& operator*() const { return *ptr_; }
|
||||
[[nodiscard]] T* operator->() const { return ptr_; }
|
||||
[[nodiscard]] explicit operator bool() const { return ptr_ != nullptr; }
|
||||
|
||||
[[nodiscard]] T* release() {
|
||||
T* tmp = ptr_;
|
||||
ptr_ = nullptr;
|
||||
pool_ = nullptr;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
if (ptr_ && pool_) {
|
||||
pool_->release(ptr_);
|
||||
}
|
||||
ptr_ = nullptr;
|
||||
pool_ = nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
T* ptr_ = nullptr;
|
||||
MemoryPool<T>* pool_ = nullptr;
|
||||
};
|
||||
|
||||
// Specialized audio buffer pool
|
||||
class AudioBufferPool {
|
||||
public:
|
||||
static constexpr size_t DEFAULT_BUFFER_SIZE = 1920; // 48000Hz * 2ch * 20ms
|
||||
static constexpr size_t DEFAULT_POOL_SIZE = 256; // ~7.5MB for float buffers
|
||||
|
||||
static AudioBufferPool& instance();
|
||||
|
||||
void initialize(size_t bufferSize = DEFAULT_BUFFER_SIZE,
|
||||
size_t poolSize = DEFAULT_POOL_SIZE);
|
||||
void shutdown();
|
||||
|
||||
// Get a buffer (returns nullptr if pool exhausted)
|
||||
[[nodiscard]] PooledPtr<float> acquireBuffer();
|
||||
|
||||
// Get buffer size
|
||||
[[nodiscard]] size_t getBufferSize() const { return bufferSize_; }
|
||||
|
||||
// Get stats
|
||||
[[nodiscard]] size_t getAvailableBuffers() const;
|
||||
[[nodiscard]] size_t getTotalBuffers() const;
|
||||
|
||||
private:
|
||||
AudioBufferPool() = default;
|
||||
|
||||
std::unique_ptr<MemoryPool<float>> pool_;
|
||||
size_t bufferSize_ = DEFAULT_BUFFER_SIZE;
|
||||
};
|
||||
|
||||
// Zero-copy audio buffer view
|
||||
template<typename T>
|
||||
class AudioBufferView {
|
||||
public:
|
||||
AudioBufferView() = default;
|
||||
|
||||
AudioBufferView(T* data, size_t size, size_t channels = 2)
|
||||
: data_(data), size_(size), channels_(channels) {}
|
||||
|
||||
[[nodiscard]] T* data() { return data_; }
|
||||
[[nodiscard]] const T* data() const { return data_; }
|
||||
[[nodiscard]] size_t size() const { return size_; }
|
||||
[[nodiscard]] size_t channels() const { return channels_; }
|
||||
[[nodiscard]] size_t samplesPerChannel() const { return size_ / channels_; }
|
||||
|
||||
[[nodiscard]] T* channel(size_t ch) {
|
||||
return data_ + ch;
|
||||
}
|
||||
|
||||
[[nodiscard]] T& sample(size_t frame, size_t ch) {
|
||||
return data_[frame * channels_ + ch];
|
||||
}
|
||||
|
||||
[[nodiscard]] const T& sample(size_t frame, size_t ch) const {
|
||||
return data_[frame * channels_ + ch];
|
||||
}
|
||||
|
||||
// Span for single channel
|
||||
[[nodiscard]] std::span<T> getChannelSpan(size_t ch) {
|
||||
return std::span<T>(data_ + ch, size_, channels_);
|
||||
}
|
||||
|
||||
// Span for all data
|
||||
[[nodiscard]] std::span<T> getSpan() {
|
||||
return std::span<T>(data_, size_);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool empty() const { return data_ == nullptr || size_ == 0; }
|
||||
|
||||
void clear() {
|
||||
if (data_) {
|
||||
std::memset(data_, 0, size_ * sizeof(T));
|
||||
}
|
||||
}
|
||||
|
||||
// Apply gain in-place
|
||||
void applyGain(float gain) {
|
||||
if (!data_) return;
|
||||
for (size_t i = 0; i < size_; ++i) {
|
||||
data_[i] *= gain;
|
||||
}
|
||||
}
|
||||
|
||||
// Mix another buffer into this one
|
||||
void mix(const AudioBufferView& other, float gain = 1.0f) {
|
||||
if (!data_ || !other.data_) return;
|
||||
size_t mixSize = std::min(size_, other.size_);
|
||||
for (size_t i = 0; i < mixSize; ++i) {
|
||||
data_[i] += other.data_[i] * gain;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
T* data_ = nullptr;
|
||||
size_t size_ = 0;
|
||||
size_t channels_ = 2;
|
||||
};
|
||||
|
||||
using FloatAudioView = AudioBufferView<float>;
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,145 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <chrono>
|
||||
#include <cctype>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
enum class HttpMethod : uint8_t {
|
||||
GET = 0,
|
||||
POST,
|
||||
PUT,
|
||||
DELETE,
|
||||
PATCH,
|
||||
HEAD,
|
||||
OPTIONS
|
||||
};
|
||||
|
||||
enum class ProxyType : uint8_t {
|
||||
HTTP = 0,
|
||||
SOCKS5
|
||||
};
|
||||
|
||||
struct ProxyConfig {
|
||||
ProxyType type = ProxyType::HTTP;
|
||||
std::string host;
|
||||
uint16_t port;
|
||||
std::optional<std::string> username;
|
||||
std::optional<std::string> password;
|
||||
std::optional<std::chrono::milliseconds> timeout;
|
||||
|
||||
[[nodiscard]] bool isValid() const noexcept {
|
||||
return !host.empty() && port > 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool requiresAuth() const noexcept {
|
||||
return username.has_value() && password.has_value();
|
||||
}
|
||||
|
||||
[[nodiscard]] bool isSocks5() const noexcept {
|
||||
return type == ProxyType::SOCKS5;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool operator==(const ProxyConfig& other) const = default;
|
||||
[[nodiscard]] bool operator!=(const ProxyConfig& other) const = default;
|
||||
};
|
||||
|
||||
struct HttpHeader {
|
||||
std::string name;
|
||||
std::string value;
|
||||
};
|
||||
|
||||
struct HttpRequest {
|
||||
std::string url;
|
||||
HttpMethod method = HttpMethod::GET;
|
||||
std::vector<HttpHeader> headers;
|
||||
std::optional<std::vector<uint8_t>> body;
|
||||
std::optional<ProxyConfig> proxy;
|
||||
std::chrono::milliseconds timeout = 30000ms;
|
||||
bool followRedirects = true;
|
||||
uint32_t maxRedirects = 10;
|
||||
};
|
||||
|
||||
struct HttpResponse {
|
||||
int32_t statusCode;
|
||||
// Using vector to support multiple headers with same name (e.g., Set-Cookie)
|
||||
std::vector<std::pair<std::string, std::string>> headers;
|
||||
std::string body;
|
||||
std::chrono::milliseconds responseTime;
|
||||
std::optional<std::string> contentType;
|
||||
bool fromCache = false;
|
||||
|
||||
[[nodiscard]] bool isSuccess() const noexcept {
|
||||
return statusCode >= 200 && statusCode < 300;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool isRedirect() const noexcept {
|
||||
return statusCode >= 300 && statusCode < 400;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool isError() const noexcept {
|
||||
return statusCode >= 400 || statusCode == 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string bodyAsString() const {
|
||||
return std::string(body.begin(), body.end());
|
||||
}
|
||||
|
||||
// Helper to get first header value by name (case-insensitive)
|
||||
[[nodiscard]] std::optional<std::string> getHeader(std::string_view name) const {
|
||||
for (const auto& [key, value] : headers) {
|
||||
if (key.size() == name.size()) {
|
||||
bool match = true;
|
||||
for (size_t i = 0; i < key.size(); ++i) {
|
||||
if (std::tolower(static_cast<unsigned char>(key[i])) !=
|
||||
std::tolower(static_cast<unsigned char>(name[i]))) {
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (match) return value;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Helper to get all header values by name (case-insensitive) - useful for Set-Cookie
|
||||
[[nodiscard]] std::vector<std::string> getHeaders(std::string_view name) const {
|
||||
std::vector<std::string> result;
|
||||
for (const auto& [key, value] : headers) {
|
||||
if (key.size() == name.size()) {
|
||||
bool match = true;
|
||||
for (size_t i = 0; i < key.size(); ++i) {
|
||||
if (std::tolower(static_cast<unsigned char>(key[i])) !=
|
||||
std::tolower(static_cast<unsigned char>(name[i]))) {
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (match) result.push_back(value);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
struct RateLimitInfo {
|
||||
uint32_t limit;
|
||||
uint32_t remaining;
|
||||
std::optional<std::chrono::system_clock::time_point> resetTime;
|
||||
};
|
||||
|
||||
struct RetryConfig {
|
||||
uint32_t maxRetries = 3;
|
||||
std::chrono::milliseconds initialDelay = 1000ms;
|
||||
std::chrono::milliseconds maxDelay = 30000ms;
|
||||
float backoffMultiplier = 2.0f;
|
||||
std::vector<int32_t> retryableStatusCodes = {408, 429, 500, 502, 503, 504};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,107 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "TrackTypes.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
enum class PluginEventType : uint8_t {
|
||||
// Connection events
|
||||
ClientConnected = 0,
|
||||
ClientDisconnected,
|
||||
ClientMoved,
|
||||
|
||||
// Chat events
|
||||
TextMessageReceived,
|
||||
|
||||
// Audio events
|
||||
VoiceDataReceived,
|
||||
|
||||
// Bot control events
|
||||
PlayRequested,
|
||||
PauseRequested,
|
||||
SkipRequested,
|
||||
StopRequested,
|
||||
|
||||
// Queue events
|
||||
TrackQueued,
|
||||
TrackRemoved,
|
||||
QueueCleared,
|
||||
QueueUpdated,
|
||||
|
||||
// State events
|
||||
PlaybackStarted,
|
||||
PlaybackPaused,
|
||||
PlaybackResumed,
|
||||
PlaybackStopped,
|
||||
TrackFinished,
|
||||
TrackSkipped,
|
||||
VolumeChanged,
|
||||
SeekPosition,
|
||||
|
||||
// System events
|
||||
HotReloadRequested,
|
||||
HotReloadCompleted,
|
||||
ConfigurationChanged
|
||||
};
|
||||
|
||||
struct PluginEvent {
|
||||
PluginEventType type;
|
||||
std::optional<std::string> clientName;
|
||||
uint64_t clientId;
|
||||
std::optional<uint64_t> targetChannelId;
|
||||
std::optional<std::string> message;
|
||||
std::optional<TrackInfo> trackInfo;
|
||||
std::optional<float> volume;
|
||||
std::optional<int> queuePosition;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
struct ClientInfo {
|
||||
uint64_t id;
|
||||
std::string nickname;
|
||||
std::optional<std::string> uniqueIdentifier;
|
||||
uint64_t channelId;
|
||||
bool isTalking;
|
||||
bool isMuted;
|
||||
bool isDeafened;
|
||||
std::vector<uint64_t> serverGroups;
|
||||
};
|
||||
|
||||
struct ChannelInfo {
|
||||
uint64_t id;
|
||||
std::string name;
|
||||
std::optional<uint64_t> parentId;
|
||||
uint64_t order;
|
||||
bool isDefault;
|
||||
bool hasPassword;
|
||||
uint32_t maxClients;
|
||||
uint32_t currentClients;
|
||||
};
|
||||
|
||||
struct ServerInfo {
|
||||
uint64_t id;
|
||||
std::string name;
|
||||
std::string welcomeMessage;
|
||||
uint32_t maxClients;
|
||||
uint32_t currentClients;
|
||||
uint64_t defaultChannelId;
|
||||
};
|
||||
|
||||
using EventCallback = std::function<void(const PluginEvent&)>;
|
||||
using CommandHandler = std::function<void(uint64_t clientId, const std::vector<std::string>& args)>;
|
||||
|
||||
struct CommandInfo {
|
||||
std::string name;
|
||||
std::string description;
|
||||
std::vector<std::string> aliases;
|
||||
std::optional<std::string> usage;
|
||||
bool requiresAdmin;
|
||||
CommandHandler handler;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,105 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "TrackTypes.hpp"
|
||||
#include "PluginTypes.hpp"
|
||||
#include "ConfigTypes.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <optional>
|
||||
#include <functional>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
enum class RpcMethod : uint8_t {
|
||||
// Playback control
|
||||
Play = 0,
|
||||
Pause,
|
||||
Resume,
|
||||
Stop,
|
||||
Skip,
|
||||
Seek,
|
||||
SetVolume,
|
||||
|
||||
// Queue management
|
||||
QueueTrack,
|
||||
RemoveFromQueue,
|
||||
ClearQueue,
|
||||
GetQueue,
|
||||
MoveInQueue,
|
||||
|
||||
// Track info
|
||||
GetCurrentTrack,
|
||||
GetTrackInfo,
|
||||
SearchTracks,
|
||||
|
||||
// Playlist
|
||||
LoadPlaylist,
|
||||
SavePlaylist,
|
||||
GetPlaylists,
|
||||
DeletePlaylist,
|
||||
|
||||
// Configuration
|
||||
GetConfig,
|
||||
SetConfig,
|
||||
ReloadConfig,
|
||||
|
||||
// Plugin/Core management
|
||||
GetStatus,
|
||||
HotReload,
|
||||
Shutdown,
|
||||
|
||||
// Admin
|
||||
Authenticate,
|
||||
Logout,
|
||||
GetAuditLog,
|
||||
ManageUsers
|
||||
};
|
||||
|
||||
struct RpcRequest {
|
||||
uint64_t id;
|
||||
RpcMethod method;
|
||||
std::optional<std::string> params;
|
||||
std::optional<std::string> authToken;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
struct RpcResponse {
|
||||
uint64_t requestId;
|
||||
bool success;
|
||||
std::optional<std::string> result;
|
||||
std::optional<std::string> error; // JSON string: {"code":N,"message":"...","source":"..."}
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
struct RpcNotification {
|
||||
std::string event;
|
||||
std::optional<std::string> data;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
using RpcHandler = std::function<RpcResponse(const RpcRequest&)>;
|
||||
|
||||
struct RpcEndpoint {
|
||||
RpcMethod method;
|
||||
std::string name;
|
||||
std::string description;
|
||||
bool requiresAuth;
|
||||
RpcHandler handler;
|
||||
};
|
||||
|
||||
// Hot reload state preservation
|
||||
struct HotReloadState {
|
||||
PlaybackState playback;
|
||||
std::vector<QueueEntry> queue;
|
||||
std::optional<std::string> currentStreamUrl;
|
||||
std::chrono::milliseconds playbackPosition;
|
||||
BotConfig config;
|
||||
std::map<std::string, std::string> sessionData;
|
||||
|
||||
[[nodiscard]] bool shouldPreservePlayback() const noexcept {
|
||||
return playback.isPlaying && playback.currentTrack.has_value();
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "AudioTypes.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <chrono>
|
||||
#include <optional>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
enum class TrackSource : uint8_t {
|
||||
Unknown = 0,
|
||||
YouTube,
|
||||
SoundCloud,
|
||||
Spotify,
|
||||
LocalFile,
|
||||
URL
|
||||
};
|
||||
|
||||
struct TrackInfo {
|
||||
std::string id;
|
||||
std::string title;
|
||||
std::string artist;
|
||||
std::string album;
|
||||
std::optional<std::string> thumbnailUrl;
|
||||
std::optional<std::chrono::milliseconds> duration;
|
||||
TrackSource source;
|
||||
std::string originalUrl;
|
||||
std::optional<std::string> streamUrl;
|
||||
std::optional<AudioStreamInfo> audioInfo;
|
||||
std::chrono::system_clock::time_point addedAt;
|
||||
std::string requestedBy;
|
||||
};
|
||||
|
||||
struct PlaylistInfo {
|
||||
std::string id;
|
||||
std::string name;
|
||||
std::string description;
|
||||
std::optional<std::string> thumbnailUrl;
|
||||
std::string owner;
|
||||
std::vector<TrackInfo> tracks;
|
||||
std::chrono::system_clock::time_point createdAt;
|
||||
std::chrono::system_clock::time_point updatedAt;
|
||||
};
|
||||
|
||||
struct QueueEntry {
|
||||
uint64_t queueId;
|
||||
TrackInfo track;
|
||||
std::chrono::system_clock::time_point addedAt;
|
||||
std::string addedBy;
|
||||
bool isPlaying;
|
||||
std::optional<std::chrono::milliseconds> position;
|
||||
};
|
||||
|
||||
struct PlaybackState {
|
||||
std::optional<QueueEntry> currentTrack;
|
||||
std::vector<QueueEntry> queue;
|
||||
bool isPlaying;
|
||||
bool isPaused;
|
||||
std::chrono::milliseconds position;
|
||||
std::chrono::milliseconds buffered;
|
||||
float volume;
|
||||
bool repeat;
|
||||
bool shuffle;
|
||||
std::chrono::system_clock::time_point lastUpdate;
|
||||
};
|
||||
|
||||
struct SearchResult {
|
||||
std::vector<TrackInfo> tracks;
|
||||
std::vector<PlaylistInfo> playlists;
|
||||
std::string query;
|
||||
std::optional<std::string> nextPageToken;
|
||||
uint32_t totalResults;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,73 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <optional>
|
||||
#include <chrono>
|
||||
#include <expected>
|
||||
#include <format>
|
||||
#include <thread>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
enum class ErrorCode : uint32_t {
|
||||
Success = 0,
|
||||
InvalidArgument,
|
||||
NotFound,
|
||||
AlreadyExists,
|
||||
NetworkError,
|
||||
ParseError,
|
||||
AudioError,
|
||||
PluginError,
|
||||
InvalidUrl,
|
||||
NotAuthenticated,
|
||||
Unauthorized,
|
||||
PermissionDenied,
|
||||
ServiceUnavailable,
|
||||
DatabaseError,
|
||||
NotSupported,
|
||||
UnknownError
|
||||
};
|
||||
|
||||
struct Error {
|
||||
ErrorCode code;
|
||||
std::string message;
|
||||
std::string source;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
|
||||
Error() = default;
|
||||
Error(ErrorCode c, std::string_view msg, std::string_view src = "")
|
||||
: code(c), message(msg), source(src), timestamp(std::chrono::system_clock::now()) {}
|
||||
|
||||
[[nodiscard]] std::string toString() const {
|
||||
return std::format("[{}] {} (from: {})",
|
||||
static_cast<uint32_t>(code), message, source);
|
||||
}
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
using Result = std::expected<T, Error>;
|
||||
|
||||
enum class LogLevel : uint8_t {
|
||||
Debug = 0,
|
||||
Info,
|
||||
Warning,
|
||||
Error,
|
||||
Critical
|
||||
};
|
||||
|
||||
struct LogEntry {
|
||||
LogLevel level;
|
||||
std::string message;
|
||||
std::string source;
|
||||
std::string sourceFile;
|
||||
uint32_t sourceLine = 0;
|
||||
std::string function;
|
||||
std::thread::id threadId;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,134 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "TrackTypes.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <optional>
|
||||
#include <chrono>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// YouTube-specific types for the extracted client algorithm
|
||||
|
||||
struct YouTubeFormat {
|
||||
std::string itag;
|
||||
std::string mimeType;
|
||||
std::optional<std::string> url;
|
||||
std::optional<std::string> signatureCipher;
|
||||
int32_t bitrate;
|
||||
int32_t width;
|
||||
int32_t height;
|
||||
std::optional<std::string> qualityLabel;
|
||||
std::optional<std::string> audioQuality;
|
||||
int32_t audioSampleRate;
|
||||
int32_t audioChannels;
|
||||
bool hasVideo;
|
||||
bool hasAudio;
|
||||
};
|
||||
|
||||
struct YouTubeVideoDetails {
|
||||
std::string videoId;
|
||||
std::string title;
|
||||
std::string author;
|
||||
std::optional<std::chrono::seconds> lengthSeconds;
|
||||
std::vector<YouTubeFormat> formats;
|
||||
std::vector<YouTubeFormat> adaptiveFormats;
|
||||
std::optional<std::string> playerJsUrl;
|
||||
std::optional<std::string> streamingData;
|
||||
};
|
||||
|
||||
struct YouTubeSearchResult {
|
||||
std::string videoId;
|
||||
std::string title;
|
||||
std::string channelTitle;
|
||||
std::optional<std::chrono::seconds> duration;
|
||||
std::optional<std::string> thumbnailUrl;
|
||||
std::string publishedAt;
|
||||
uint64_t viewCount;
|
||||
};
|
||||
|
||||
struct YouTubePlaylistItem {
|
||||
std::string videoId;
|
||||
std::string title;
|
||||
std::optional<std::chrono::seconds> duration;
|
||||
std::optional<std::string> thumbnailUrl;
|
||||
};
|
||||
|
||||
struct YouTubePlaylist {
|
||||
std::string playlistId;
|
||||
std::string title;
|
||||
std::string author;
|
||||
std::vector<YouTubePlaylistItem> videos;
|
||||
std::optional<std::string> continuationToken;
|
||||
};
|
||||
|
||||
struct YouTubePlayerConfig {
|
||||
std::string innertubeApiKey;
|
||||
std::string innertubeClientName;
|
||||
std::string innertubeClientVersion;
|
||||
std::string contextClientName;
|
||||
std::string contextClientVersion;
|
||||
std::string visitorData;
|
||||
std::optional<std::string> poToken;
|
||||
};
|
||||
|
||||
struct YouTubeClientContext {
|
||||
std::string hl = "en";
|
||||
std::string gl = "US";
|
||||
std::string clientName = "WEB";
|
||||
std::string clientVersion;
|
||||
std::optional<std::string> visitorData;
|
||||
std::optional<std::string> userAgent;
|
||||
};
|
||||
|
||||
// Convert YouTube types to generic TrackInfo
|
||||
[[nodiscard]] inline TrackInfo ConvertToTrackInfo(const YouTubeVideoDetails& details) {
|
||||
TrackInfo info;
|
||||
info.id = details.videoId;
|
||||
info.title = details.title;
|
||||
info.artist = details.author;
|
||||
if (details.lengthSeconds.has_value()) {
|
||||
info.duration = std::chrono::milliseconds(*details.lengthSeconds * 1000);
|
||||
}
|
||||
info.source = TrackSource::YouTube;
|
||||
info.originalUrl = "https://youtube.com/watch?v=" + details.videoId;
|
||||
return info;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline TrackInfo ConvertToTrackInfo(const YouTubeSearchResult& result) {
|
||||
TrackInfo info;
|
||||
info.id = result.videoId;
|
||||
info.title = result.title;
|
||||
info.artist = result.channelTitle;
|
||||
if (result.duration.has_value()) {
|
||||
info.duration = std::chrono::milliseconds(*result.duration * 1000);
|
||||
}
|
||||
info.thumbnailUrl = result.thumbnailUrl;
|
||||
info.source = TrackSource::YouTube;
|
||||
info.originalUrl = "https://youtube.com/watch?v=" + result.videoId;
|
||||
return info;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline PlaylistInfo ConvertToPlaylistInfo(const YouTubePlaylist& playlist) {
|
||||
PlaylistInfo info;
|
||||
info.id = playlist.playlistId;
|
||||
info.name = playlist.title;
|
||||
info.owner = playlist.author;
|
||||
// Convert playlist items to tracks
|
||||
for (const auto& item : playlist.videos) {
|
||||
TrackInfo track;
|
||||
track.id = item.videoId;
|
||||
track.title = item.title;
|
||||
track.source = TrackSource::YouTube;
|
||||
track.originalUrl = "https://youtube.com/watch?v=" + item.videoId;
|
||||
if (item.duration.has_value()) {
|
||||
track.duration = std::chrono::milliseconds(*item.duration * 1000);
|
||||
}
|
||||
track.thumbnailUrl = item.thumbnailUrl;
|
||||
info.tracks.push_back(std::move(track));
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api
|
||||
Reference in new issue
Block a user