Merge branch 'eventbust' into 'main'
Migrate core infrastructure to VoidLibrary See merge request void/echoioncore!1
This commit is contained in:
commit
d74a69aa34
65 files changed
+16109
-12011
No files matched your search
+84
-36
@@ -1,4 +1,4 @@
|
|||||||
cmake_minimum_required(VERSION 3.28)
|
cmake_minimum_required(VERSION 4.0.0)
|
||||||
project(EchoionCore VERSION 1.0.0 LANGUAGES CXX)
|
project(EchoionCore VERSION 1.0.0 LANGUAGES CXX)
|
||||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
|
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
|
||||||
set(CMAKE_CXX_STANDARD 26)
|
set(CMAKE_CXX_STANDARD 26)
|
||||||
@@ -6,38 +6,39 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
|||||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||||
add_definitions(-DECHOION_API_EXPORT)
|
add_definitions(-DECHOION_API_EXPORT)
|
||||||
|
file(GLOB_RECURSE CORE_SOURCES
|
||||||
add_library(EchoionCore SHARED
|
CONFIGURE_DEPENDS
|
||||||
src/Logger.cpp
|
"src/**.cpp"
|
||||||
src/NetworkClient.cpp
|
|
||||||
src/SignatureCipher.cpp
|
|
||||||
src/YouTubeClient.cpp
|
|
||||||
src/YtDlpManager.cpp
|
|
||||||
src/UrlShortener.cpp
|
|
||||||
src/AudioDecoder.cpp
|
|
||||||
src/CommandManager.cpp
|
|
||||||
src/MusicManager.cpp
|
|
||||||
src/SubscriptionManager.cpp
|
|
||||||
src/Core.cpp
|
|
||||||
src/Export.cpp
|
|
||||||
src/EventBus.cpp
|
|
||||||
src/Cache.cpp
|
|
||||||
src/MemoryPool.cpp
|
|
||||||
src/Database.cpp
|
|
||||||
src/RpcServer.cpp
|
|
||||||
src/ConfigLoader.cpp
|
|
||||||
)
|
)
|
||||||
|
add_library(EchoionCore SHARED ${CORE_SOURCES})
|
||||||
|
|
||||||
add_library(Echoion::Core ALIAS EchoionCore)
|
add_library(Echoion::Core ALIAS EchoionCore)
|
||||||
|
|
||||||
target_include_directories(EchoionCore PUBLIC
|
target_include_directories(EchoionCore PUBLIC
|
||||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||||
|
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/../EchoionApi/include/echoion/api/config>
|
||||||
$<INSTALL_INTERFACE:include>
|
$<INSTALL_INTERFACE:include>
|
||||||
)
|
)
|
||||||
|
|
||||||
target_link_libraries(EchoionCore PUBLIC Echoion::Api)
|
# Core uses all API modules
|
||||||
|
target_link_libraries(EchoionCore PUBLIC
|
||||||
|
Echoion::ApiBase
|
||||||
|
Echoion::ApiAudio
|
||||||
|
Echoion::ApiTrack
|
||||||
|
Echoion::ApiNetwork
|
||||||
|
Echoion::ApiPlugin
|
||||||
|
Echoion::ApiConfig
|
||||||
|
Echoion::ApiRpc
|
||||||
|
Echoion::ApiYouTube
|
||||||
|
Echoion::ApiLogger
|
||||||
|
Echoion::ApiEventBus
|
||||||
|
Echoion::ApiDatabase
|
||||||
|
Echoion::ApiOpaque
|
||||||
|
Echoion::ApiPluginInterface
|
||||||
|
Echoion::ApiCoreInterface
|
||||||
|
Echoion::ApiUtils
|
||||||
|
)
|
||||||
|
|
||||||
find_package(glaze CONFIG REQUIRED)
|
|
||||||
find_package(PkgConfig REQUIRED)
|
find_package(PkgConfig REQUIRED)
|
||||||
pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET
|
pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET
|
||||||
libavformat
|
libavformat
|
||||||
@@ -52,6 +53,21 @@ CPMAddPackage(
|
|||||||
GIT_TAG v0.11.0
|
GIT_TAG v0.11.0
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# quickjs-ng v0.11.0 compiles its C sources with -Werror, which trips newer GCC
|
||||||
|
# diagnostics (e.g. -Wmaybe-uninitialized / -Wdiscarded-qualifiers under GCC 16+).
|
||||||
|
# It is a vendored third-party dependency, so relax -Werror on every target it
|
||||||
|
# defines (qjs, qjsc, qjs-libc, ...) rather than guessing target names.
|
||||||
|
if(quickjs_SOURCE_DIR)
|
||||||
|
get_property(_qjs_targets DIRECTORY "${quickjs_SOURCE_DIR}"
|
||||||
|
PROPERTY BUILDSYSTEM_TARGETS)
|
||||||
|
foreach(_qjs_target ${_qjs_targets})
|
||||||
|
get_target_property(_qjs_type ${_qjs_target} TYPE)
|
||||||
|
if(NOT _qjs_type STREQUAL "INTERFACE_LIBRARY")
|
||||||
|
target_compile_options(${_qjs_target} PRIVATE -Wno-error)
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
endif()
|
||||||
|
|
||||||
set(AddBoost.cmake_VERSION 3.7.3)
|
set(AddBoost.cmake_VERSION 3.7.3)
|
||||||
CPMAddPackage(
|
CPMAddPackage(
|
||||||
NAME AddBoost.cmake
|
NAME AddBoost.cmake
|
||||||
@@ -68,19 +84,25 @@ add_boost(
|
|||||||
BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED EchoionCore
|
BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED EchoionCore
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
find_package(Threads REQUIRED)
|
find_package(Threads REQUIRED)
|
||||||
find_package(OpenSSL REQUIRED)
|
find_package(OpenSSL REQUIRED)
|
||||||
find_package(SQLite3 REQUIRED)
|
find_package(SQLite3 REQUIRED)
|
||||||
find_package(TBB REQUIRED)
|
find_package(TBB REQUIRED)
|
||||||
|
|
||||||
target_link_libraries(EchoionCore
|
target_link_libraries(EchoionCore
|
||||||
PUBLIC
|
PUBLIC
|
||||||
PkgConfig::LIBAV
|
PkgConfig::LIBAV
|
||||||
TBB::tbb
|
TBB::tbb
|
||||||
SQLite::SQLite3
|
SQLite::SQLite3
|
||||||
|
# VoidLibrary modules (migration target — replacing in-house infra)
|
||||||
|
Void::Data
|
||||||
|
Void::Functional
|
||||||
|
Void::System
|
||||||
|
Void::Log
|
||||||
|
Void::Async
|
||||||
|
Void::Containers
|
||||||
|
Void::Resilience
|
||||||
PRIVATE
|
PRIVATE
|
||||||
glaze::glaze
|
|
||||||
Threads::Threads
|
Threads::Threads
|
||||||
qjs
|
qjs
|
||||||
Boost::beast
|
Boost::beast
|
||||||
@@ -88,7 +110,6 @@ target_link_libraries(EchoionCore
|
|||||||
Boost::asio
|
Boost::asio
|
||||||
OpenSSL::SSL
|
OpenSSL::SSL
|
||||||
OpenSSL::Crypto
|
OpenSSL::Crypto
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if(MSVC)
|
if(MSVC)
|
||||||
@@ -107,19 +128,46 @@ set_target_properties(EchoionCore PROPERTIES
|
|||||||
ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib
|
ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib
|
||||||
)
|
)
|
||||||
|
|
||||||
# PackageProject.cmake configuration
|
# Export EchoionCore
|
||||||
packageProject(
|
target_include_directories(EchoionCore PUBLIC
|
||||||
NAME EchoionCore
|
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||||
|
$<INSTALL_INTERFACE:include>
|
||||||
|
)
|
||||||
|
|
||||||
|
install(TARGETS EchoionCore
|
||||||
|
EXPORT EchoionCoreTargets
|
||||||
|
RUNTIME DESTINATION bin
|
||||||
|
LIBRARY DESTINATION lib
|
||||||
|
ARCHIVE DESTINATION lib
|
||||||
|
INCLUDES DESTINATION include
|
||||||
|
)
|
||||||
|
|
||||||
|
install(EXPORT EchoionCoreTargets
|
||||||
|
FILE EchoionCoreTargets.cmake
|
||||||
|
NAMESPACE Echoion::
|
||||||
|
DESTINATION lib/cmake/EchoionCore
|
||||||
|
)
|
||||||
|
|
||||||
|
# Package config files
|
||||||
|
include(CMakePackageConfigHelpers)
|
||||||
|
write_basic_package_version_file(
|
||||||
|
"${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfigVersion.cmake"
|
||||||
VERSION ${PROJECT_VERSION}
|
VERSION ${PROJECT_VERSION}
|
||||||
NAMESPACE Echoion
|
|
||||||
BINARY_DIR ${PROJECT_BINARY_DIR}
|
|
||||||
INCLUDE_DIR ${PROJECT_SOURCE_DIR}/include
|
|
||||||
INCLUDE_DESTINATION include
|
|
||||||
COMPATIBILITY SameMajorVersion
|
COMPATIBILITY SameMajorVersion
|
||||||
DISABLE_VERSION_SUFFIX YES
|
)
|
||||||
|
|
||||||
|
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfig.cmake"
|
||||||
|
"include(\"\${CMAKE_CURRENT_LIST_DIR}/EchoionCoreTargets.cmake\")
|
||||||
|
include(CMakeFindDependencyMacro)
|
||||||
|
find_dependency(EchoionApi)
|
||||||
|
")
|
||||||
|
|
||||||
|
install(FILES
|
||||||
|
"${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfig.cmake"
|
||||||
|
"${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfigVersion.cmake"
|
||||||
|
DESTINATION lib/cmake/EchoionCore
|
||||||
)
|
)
|
||||||
|
|
||||||
# Optional: Bundle FFmpeg libraries for distribution
|
|
||||||
option(BUNDLE_FFMPEG "Bundle FFmpeg libraries with installation" OFF)
|
option(BUNDLE_FFMPEG "Bundle FFmpeg libraries with installation" OFF)
|
||||||
if(BUNDLE_FFMPEG)
|
if(BUNDLE_FFMPEG)
|
||||||
include(cmake/BundleFFmpeg.cmake)
|
include(cmake/BundleFFmpeg.cmake)
|
||||||
|
|||||||
@@ -1,146 +1,169 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <echoion/api.hpp>
|
#include "NetworkTypes.hpp"
|
||||||
#include <thread>
|
#include <AudioTypes.hpp>
|
||||||
#include <mutex>
|
#include <Types.hpp>
|
||||||
#include <condition_variable>
|
|
||||||
#include <queue>
|
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <span>
|
#include <condition_variable>
|
||||||
|
#include <mutex>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
|
#include <queue>
|
||||||
|
#include <span>
|
||||||
|
#include <thread>
|
||||||
|
|
||||||
// Forward declarations for FFmpeg
|
// Forward declarations for FFmpeg
|
||||||
extern "C" {
|
extern "C" {
|
||||||
struct AVFormatContext;
|
struct AVFormatContext;
|
||||||
struct AVCodecContext;
|
struct AVCodecContext;
|
||||||
struct AVFrame;
|
struct AVFrame;
|
||||||
struct AVPacket;
|
struct AVPacket;
|
||||||
struct SwrContext;
|
struct SwrContext;
|
||||||
struct AVBufferRef;
|
struct AVBufferRef;
|
||||||
}
|
}
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class AudioDecoder {
|
class AudioDecoder
|
||||||
public:
|
{
|
||||||
AudioDecoder();
|
public:
|
||||||
~AudioDecoder();
|
|
||||||
|
|
||||||
// Initialize decoder with optional hardware acceleration
|
AudioDecoder();
|
||||||
Api::Result<void> initialize(const Api::HwAccelConfig& hwConfig = {});
|
~AudioDecoder();
|
||||||
void shutdown();
|
|
||||||
|
|
||||||
// Open audio source (URL or file path)
|
// Initialize decoder with optional hardware acceleration
|
||||||
Api::Result<void> openSource(const std::string& url);
|
Api::Result<void>
|
||||||
void closeSource();
|
initialize(const Api::HwAccelConfig& hwConfig = {});
|
||||||
|
void shutdown();
|
||||||
|
|
||||||
// Decode audio - returns zero-copy pooled buffer
|
// Open audio source (URL or file path)
|
||||||
[[nodiscard]] Api::Result<Api::DecodedAudio> decodeFrame();
|
Api::Result<void> openSource(const std::string& url);
|
||||||
|
void closeSource();
|
||||||
// Seek to position
|
|
||||||
Api::Result<void> seek(std::chrono::milliseconds position);
|
|
||||||
|
|
||||||
// Get audio info
|
// Decode audio - returns zero-copy pooled buffer
|
||||||
[[nodiscard]] Api::Result<Api::AudioStreamInfo> getStreamInfo() const;
|
[[nodiscard]] Api::Result<Api::DecodedAudio> decodeFrame();
|
||||||
|
|
||||||
// Get current position
|
|
||||||
[[nodiscard]] std::chrono::milliseconds getPosition() const;
|
|
||||||
|
|
||||||
// Check if decoder has more data
|
|
||||||
[[nodiscard]] bool hasMoreData() const;
|
|
||||||
|
|
||||||
// Set output format
|
// Seek to position
|
||||||
void setOutputFormat(uint32_t sampleRate, uint32_t channels);
|
Api::Result<void> seek(std::chrono::milliseconds position);
|
||||||
|
|
||||||
// Set proxy configuration for network requests
|
// Get audio info
|
||||||
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
|
[[nodiscard]] Api::Result<Api::AudioStreamInfo>
|
||||||
|
getStreamInfo() const;
|
||||||
// Hardware acceleration
|
|
||||||
[[nodiscard]] bool isHardwareAccelerated() const { return hwAccelEnabled_; }
|
|
||||||
[[nodiscard]] Api::HwAccelType getHwAccelType() const { return hwAccelType_; }
|
|
||||||
|
|
||||||
// Enable/disable zero-copy mode
|
|
||||||
void setZeroCopyEnabled(bool enabled) { zeroCopyEnabled_ = enabled; }
|
|
||||||
[[nodiscard]] bool isZeroCopyEnabled() const { return zeroCopyEnabled_; }
|
|
||||||
|
|
||||||
// Get decoder statistics
|
|
||||||
struct Stats {
|
|
||||||
uint64_t framesDecoded = 0;
|
|
||||||
uint64_t framesDropped = 0;
|
|
||||||
uint64_t bytesDecoded = 0;
|
|
||||||
std::chrono::milliseconds totalDecodeTime{0};
|
|
||||||
double averageDecodeTimeMs = 0.0;
|
|
||||||
bool hwAccelerationActive = false;
|
|
||||||
};
|
|
||||||
[[nodiscard]] Stats getStats() const;
|
|
||||||
|
|
||||||
// Get next S16 chunk (like reference implementation)
|
|
||||||
bool getNextChunk(std::vector<int16_t>& outChunk, bool blocking = false);
|
|
||||||
|
|
||||||
// Check if decode is finished
|
|
||||||
[[nodiscard]] bool isFinished() const { return eof_.load(); }
|
|
||||||
|
|
||||||
private:
|
// Get current position
|
||||||
void decodeThread();
|
[[nodiscard]] std::chrono::milliseconds getPosition() const;
|
||||||
Api::Result<void> readPacket();
|
|
||||||
Api::Result<Api::DecodedAudio> convertFrame();
|
|
||||||
void cleanupFfmpeg();
|
|
||||||
|
|
||||||
// Hardware acceleration setup
|
|
||||||
Api::Result<void> initializeHardwareAccel(const Api::HwAccelConfig& config);
|
|
||||||
void cleanupHardwareAccel();
|
|
||||||
|
|
||||||
// Frame conversion (returns int16 for direct playback)
|
// Check if decoder has more data
|
||||||
Api::Result<Api::DecodedAudio> convertFramePooled();
|
[[nodiscard]] bool hasMoreData() const;
|
||||||
|
|
||||||
// FFmpeg contexts
|
// Set output format
|
||||||
AVFormatContext* formatContext_ = nullptr;
|
void setOutputFormat(uint32_t sampleRate, uint32_t channels);
|
||||||
AVCodecContext* codecContext_ = nullptr;
|
|
||||||
AVFrame* frame_ = nullptr;
|
|
||||||
AVPacket* packet_ = nullptr;
|
|
||||||
SwrContext* swrContext_ = nullptr;
|
|
||||||
uint8_t* outputBuffer_ = nullptr; // For S16 output like reference
|
|
||||||
|
|
||||||
// Hardware acceleration
|
|
||||||
AVBufferRef* hwDeviceContext_ = nullptr;
|
|
||||||
AVBufferRef* hwFramesContext_ = nullptr;
|
|
||||||
bool hwAccelEnabled_ = false;
|
|
||||||
Api::HwAccelType hwAccelType_ = Api::HwAccelType::None;
|
|
||||||
bool zeroCopyEnabled_ = true;
|
|
||||||
|
|
||||||
// Stream info
|
// Set proxy configuration for network requests
|
||||||
int audioStreamIndex_ = -1;
|
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
|
||||||
Api::AudioStreamInfo streamInfo_;
|
|
||||||
|
|
||||||
// Output format
|
|
||||||
uint32_t outputSampleRate_ = 192000;
|
|
||||||
uint32_t outputChannels_ = 2;
|
|
||||||
|
|
||||||
// Threading
|
// Hardware acceleration
|
||||||
std::jthread decodeThread_;
|
[[nodiscard]] bool isHardwareAccelerated() const
|
||||||
mutable std::mutex mutex_;
|
{
|
||||||
std::condition_variable cv_;
|
return hwAccelEnabled_;
|
||||||
std::queue<Api::DecodedAudio> decodedQueue_;
|
}
|
||||||
static constexpr size_t MAX_QUEUE_SIZE = 50;
|
[[nodiscard]] Api::HwAccelType getHwAccelType() const
|
||||||
|
{
|
||||||
// S16 audio queue (like reference) - avoids float conversion
|
return hwAccelType_;
|
||||||
std::deque<std::vector<int16_t>> int16Queue_;
|
}
|
||||||
static constexpr size_t MAX_INT16_QUEUE_SIZE = 100;
|
|
||||||
|
|
||||||
// State
|
// Enable/disable zero-copy mode
|
||||||
std::atomic<bool> initialized_{false};
|
void setZeroCopyEnabled(bool enabled)
|
||||||
std::atomic<bool> decoding_{false};
|
{
|
||||||
std::atomic<bool> eof_{false};
|
zeroCopyEnabled_ = enabled;
|
||||||
std::atomic<bool> shouldExit_{false}; // For FFmpeg interrupt callback
|
}
|
||||||
std::chrono::milliseconds currentPosition_{0};
|
[[nodiscard]] bool isZeroCopyEnabled() const
|
||||||
std::string currentUrl_;
|
{
|
||||||
|
return zeroCopyEnabled_;
|
||||||
|
}
|
||||||
|
|
||||||
std::atomic<uint32_t> streamSampleRate_{48000};
|
// Get decoder statistics
|
||||||
std::optional<Api::ProxyConfig> proxyConfig_;
|
struct Stats {
|
||||||
|
uint64_t framesDecoded = 0;
|
||||||
// Statistics
|
uint64_t framesDropped = 0;
|
||||||
mutable std::mutex statsMutex_;
|
uint64_t bytesDecoded = 0;
|
||||||
Stats stats_;
|
std::chrono::milliseconds totalDecodeTime{0};
|
||||||
};
|
double averageDecodeTimeMs = 0.0;
|
||||||
|
bool hwAccelerationActive = false;
|
||||||
|
};
|
||||||
|
[[nodiscard]] Stats getStats() const;
|
||||||
|
|
||||||
|
// Get next S16 chunk (like reference implementation)
|
||||||
|
bool getNextChunk(std::vector<int16_t>& outChunk,
|
||||||
|
bool blocking = false);
|
||||||
|
|
||||||
|
// Check if decode is finished
|
||||||
|
[[nodiscard]] bool isFinished() const { return eof_.load(); }
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
void decodeThread();
|
||||||
|
Api::Result<void> readPacket();
|
||||||
|
Api::Result<Api::DecodedAudio> convertFrame();
|
||||||
|
void cleanupFfmpeg();
|
||||||
|
|
||||||
|
// Hardware acceleration setup
|
||||||
|
Api::Result<void>
|
||||||
|
initializeHardwareAccel(const Api::HwAccelConfig& config);
|
||||||
|
void cleanupHardwareAccel();
|
||||||
|
|
||||||
|
// Frame conversion (returns int16 for direct playback)
|
||||||
|
Api::Result<Api::DecodedAudio> convertFramePooled();
|
||||||
|
|
||||||
|
// FFmpeg contexts
|
||||||
|
AVFormatContext* formatContext_ = nullptr;
|
||||||
|
AVCodecContext* codecContext_ = nullptr;
|
||||||
|
AVFrame* frame_ = nullptr;
|
||||||
|
AVPacket* packet_ = nullptr;
|
||||||
|
SwrContext* swrContext_ = nullptr;
|
||||||
|
uint8_t* outputBuffer_ = nullptr; // For S16 output like reference
|
||||||
|
|
||||||
|
// Hardware acceleration
|
||||||
|
AVBufferRef* hwDeviceContext_ = nullptr;
|
||||||
|
AVBufferRef* hwFramesContext_ = nullptr;
|
||||||
|
bool hwAccelEnabled_ = false;
|
||||||
|
Api::HwAccelType hwAccelType_ = Api::HwAccelType::None;
|
||||||
|
bool zeroCopyEnabled_ = true;
|
||||||
|
|
||||||
|
// Stream info
|
||||||
|
int audioStreamIndex_ = -1;
|
||||||
|
Api::AudioStreamInfo streamInfo_;
|
||||||
|
|
||||||
|
// Output format
|
||||||
|
uint32_t outputSampleRate_ = 192000;
|
||||||
|
uint32_t outputChannels_ = 2;
|
||||||
|
|
||||||
|
// Threading
|
||||||
|
std::jthread decodeThread_;
|
||||||
|
mutable std::mutex mutex_;
|
||||||
|
std::condition_variable cv_;
|
||||||
|
std::queue<Api::DecodedAudio> decodedQueue_;
|
||||||
|
static constexpr size_t MAX_QUEUE_SIZE = 50;
|
||||||
|
|
||||||
|
// S16 audio queue (like reference) - avoids float conversion
|
||||||
|
std::deque<std::vector<int16_t>> int16Queue_;
|
||||||
|
static constexpr size_t MAX_INT16_QUEUE_SIZE = 100;
|
||||||
|
|
||||||
|
// State
|
||||||
|
std::atomic<bool> initialized_{false};
|
||||||
|
std::atomic<bool> decoding_{false};
|
||||||
|
std::atomic<bool> eof_{false};
|
||||||
|
std::atomic<bool> shouldExit_{
|
||||||
|
false}; // For FFmpeg interrupt callback
|
||||||
|
std::chrono::milliseconds currentPosition_{0};
|
||||||
|
std::string currentUrl_;
|
||||||
|
|
||||||
|
std::atomic<uint32_t> streamSampleRate_{48000};
|
||||||
|
std::optional<Api::ProxyConfig> proxyConfig_;
|
||||||
|
|
||||||
|
// Statistics
|
||||||
|
mutable std::mutex statsMutex_;
|
||||||
|
Stats stats_;
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "commands/Command.hpp"
|
#include "commands/Command.hpp"
|
||||||
#include "echoion/api/ConfigTypes.hpp"
|
#include <ConfigTypes.hpp>
|
||||||
|
#include <PluginTypes.hpp>
|
||||||
|
#include <Types.hpp>
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <condition_variable>
|
#include <condition_variable>
|
||||||
#include <echoion/api.hpp>
|
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <future>
|
#include <future>
|
||||||
#include <map>
|
#include <map>
|
||||||
@@ -15,151 +16,163 @@
|
|||||||
#include <thread>
|
#include <thread>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class MusicManager;
|
class MusicManager;
|
||||||
|
|
||||||
// Function to check if client has permission (set by Core)
|
// Function to check if client has permission (set by Core)
|
||||||
using PermissionCheckFunc = std::function<bool(uint64_t clientId, CommandCategory category)>;
|
using PermissionCheckFunc =
|
||||||
|
std::function<bool(uint64_t clientId, CommandCategory category)>;
|
||||||
/**
|
|
||||||
* @brief Manages command registration and dispatch.
|
|
||||||
*
|
|
||||||
* Usage:
|
|
||||||
* CommandManager mgr;
|
|
||||||
* mgr.registerCommand<PlayCommand>("play");
|
|
||||||
* mgr.dispatch(clientId, "play song name", musicManager, replyFunc);
|
|
||||||
*/
|
|
||||||
class CommandManager {
|
|
||||||
public:
|
|
||||||
CommandManager();
|
|
||||||
~CommandManager();
|
|
||||||
|
|
||||||
// Shutdown the command manager (stops thread pool)
|
|
||||||
void shutdown();
|
|
||||||
|
|
||||||
// Disable copy
|
|
||||||
CommandManager(const CommandManager&) = delete;
|
|
||||||
CommandManager& operator=(const CommandManager&) = delete;
|
|
||||||
|
|
||||||
// Enable move
|
|
||||||
CommandManager(CommandManager&&) = default;
|
|
||||||
CommandManager& operator=(CommandManager&&) = default;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Registers a command class.
|
|
||||||
* @tparam T The command class (must inherit Command).
|
|
||||||
* @param primaryName The primary name/trigger (e.g., "play").
|
|
||||||
*/
|
|
||||||
template <typename T>
|
|
||||||
void registerCommand(const std::string& primaryName) {
|
|
||||||
auto cmd = std::make_shared<T>();
|
|
||||||
|
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
|
||||||
|
|
||||||
// Register primary name
|
|
||||||
commands_[primaryName] = cmd;
|
|
||||||
uniqueCommands_.push_back({primaryName, cmd});
|
|
||||||
|
|
||||||
// Register aliases automatically from the class itself
|
|
||||||
for (auto alias : cmd->getAliases()) {
|
|
||||||
commands_[std::string(alias)] = cmd;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Dispatches a command message to the appropriate handler (ASYNC).
|
* @brief Manages command registration and dispatch.
|
||||||
* Commands are executed in a thread pool, allowing multiple users to
|
*
|
||||||
* use the bot simultaneously without blocking.
|
* Usage:
|
||||||
* @param clientId The client ID who invoked the command.
|
* CommandManager mgr;
|
||||||
* @param message The full message (including prefix, e.g., "!play song").
|
* mgr.registerCommand<PlayCommand>("play");
|
||||||
* @param musicManager Weak pointer to the MusicManager.
|
* mgr.dispatch(clientId, "play song name", musicManager, replyFunc);
|
||||||
* @param replyFunc Function to call to send a reply.
|
|
||||||
* @param invokerName Name of the invoking user.
|
|
||||||
* @return true if a command was found and queued for execution, false
|
|
||||||
* otherwise.
|
|
||||||
*/
|
*/
|
||||||
[[nodiscard]] bool dispatch(uint64_t clientId,
|
class CommandManager
|
||||||
std::string_view message,
|
{
|
||||||
std::weak_ptr<MusicManager> musicManager,
|
public:
|
||||||
std::function<void(std::string_view)> replyFunc,
|
|
||||||
std::string_view invokerName = "");
|
|
||||||
|
|
||||||
/**
|
CommandManager();
|
||||||
* @brief Executes a command synchronously (for internal use).
|
~CommandManager();
|
||||||
* Prefer using dispatch() for normal command handling.
|
|
||||||
*/
|
|
||||||
[[nodiscard]] bool
|
|
||||||
dispatchSync(uint64_t clientId,
|
|
||||||
std::string_view message,
|
|
||||||
std::weak_ptr<MusicManager> musicManager,
|
|
||||||
std::function<void(std::string_view)> replyFunc,
|
|
||||||
std::string_view invokerName = "");
|
|
||||||
|
|
||||||
[[nodiscard]] bool hasCommand(std::string_view name) const;
|
// Shutdown the command manager (stops thread pool)
|
||||||
[[nodiscard]] std::optional<CommandPtr> getCommand(std::string_view name) const;
|
void shutdown();
|
||||||
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>> getAllCommands() const;
|
|
||||||
|
|
||||||
// Get commands visible to a specific client (for help)
|
|
||||||
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>> getVisibleCommands(uint64_t clientId) const;
|
|
||||||
|
|
||||||
// Check if client can execute a command
|
|
||||||
[[nodiscard]] bool canExecuteCommand(uint64_t clientId, const CommandPtr& cmd) const;
|
|
||||||
|
|
||||||
void setPrefix(std::string_view prefix);
|
// Disable copy
|
||||||
[[nodiscard]] std::string_view getPrefix() const { return prefix_; }
|
CommandManager(const CommandManager&) = delete;
|
||||||
|
CommandManager& operator=(const CommandManager&) = delete;
|
||||||
// Set permission check function
|
|
||||||
void setPermissionCheckFunc(PermissionCheckFunc func);
|
|
||||||
// Set server config for permission checks
|
|
||||||
void setServerConfig(const Api::AppConfig& config);
|
|
||||||
|
|
||||||
private:
|
// Enable move
|
||||||
struct CommandEntry {
|
CommandManager(CommandManager&&) = default;
|
||||||
std::string primaryName;
|
CommandManager& operator=(CommandManager&&) = default;
|
||||||
CommandPtr instance;
|
|
||||||
};
|
|
||||||
|
|
||||||
void registerBuiltinCommands();
|
/**
|
||||||
|
* @brief Registers a command class.
|
||||||
// Internal Help Command (defined in .cpp to access registry)
|
* @tparam T The command class (must inherit Command).
|
||||||
class HelpCommand;
|
* @param primaryName The primary name/trigger (e.g., "play").
|
||||||
void registerHelpCommand();
|
*/
|
||||||
|
template <typename T>
|
||||||
|
void registerCommand(const std::string& primaryName)
|
||||||
|
{
|
||||||
|
auto cmd = std::make_shared<T>();
|
||||||
|
|
||||||
std::string prefix_ = "!";
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
|
||||||
// Map for fast lookup: "play" -> PlayCommand
|
|
||||||
std::map<std::string, CommandPtr, std::less<>> commands_;
|
|
||||||
|
|
||||||
// List for generating help: {"play", PlayCommand}
|
|
||||||
std::vector<CommandEntry> uniqueCommands_;
|
|
||||||
|
|
||||||
mutable std::mutex mutex_;
|
|
||||||
|
|
||||||
// Permission checking
|
|
||||||
PermissionCheckFunc permissionCheck_;
|
|
||||||
std::optional<Api::AppConfig> serverConfig_;
|
|
||||||
|
|
||||||
// Async command execution
|
// Register primary name
|
||||||
struct CommandTask {
|
commands_[primaryName] = cmd;
|
||||||
uint64_t clientId;
|
uniqueCommands_.push_back({primaryName, cmd});
|
||||||
std::string message;
|
|
||||||
std::weak_ptr<MusicManager> musicManager;
|
|
||||||
std::function<void(std::string_view)> replyFunc;
|
|
||||||
std::string invokerName;
|
|
||||||
};
|
|
||||||
|
|
||||||
void startThreadPool();
|
// Register aliases automatically from the class itself
|
||||||
void processCommandQueue();
|
for (auto alias : cmd->getAliases()) {
|
||||||
void executeCommandAsync(CommandTask task);
|
commands_[std::string(alias)] = cmd;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::jthread> workerThreads_;
|
/**
|
||||||
std::queue<CommandTask> commandQueue_;
|
* @brief Dispatches a command message to the appropriate handler
|
||||||
std::mutex queueMutex_;
|
* (ASYNC). Commands are executed in a thread pool, allowing
|
||||||
std::condition_variable queueCv_;
|
* multiple users to use the bot simultaneously without blocking.
|
||||||
std::atomic<bool> shutdown_{false};
|
* @param clientId The client ID who invoked the command.
|
||||||
static constexpr size_t THREAD_POOL_SIZE =
|
* @param message The full message (including prefix, e.g., "!play
|
||||||
4; // Handle up to 4 concurrent commands
|
* song").
|
||||||
|
* @param musicManager Weak pointer to the MusicManager.
|
||||||
|
* @param replyFunc Function to call to send a reply.
|
||||||
|
* @param invokerName Name of the invoking user.
|
||||||
|
* @return true if a command was found and queued for execution,
|
||||||
|
* false otherwise.
|
||||||
|
*/
|
||||||
|
[[nodiscard]] bool
|
||||||
|
dispatch(uint64_t clientId,
|
||||||
|
std::string_view message,
|
||||||
|
std::weak_ptr<MusicManager> musicManager,
|
||||||
|
std::function<void(std::string_view)> replyFunc,
|
||||||
|
std::string_view invokerName = "");
|
||||||
|
|
||||||
}; // namespace Echoion::Core
|
/**
|
||||||
|
* @brief Executes a command synchronously (for internal use).
|
||||||
|
* Prefer using dispatch() for normal command handling.
|
||||||
|
*/
|
||||||
|
[[nodiscard]] bool
|
||||||
|
dispatchSync(uint64_t clientId,
|
||||||
|
std::string_view message,
|
||||||
|
std::weak_ptr<MusicManager> musicManager,
|
||||||
|
std::function<void(std::string_view)> replyFunc,
|
||||||
|
std::string_view invokerName = "");
|
||||||
|
|
||||||
|
[[nodiscard]] bool hasCommand(std::string_view name) const;
|
||||||
|
[[nodiscard]] std::optional<CommandPtr>
|
||||||
|
getCommand(std::string_view name) const;
|
||||||
|
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>>
|
||||||
|
getAllCommands() const;
|
||||||
|
|
||||||
|
// Get commands visible to a specific client (for help)
|
||||||
|
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>>
|
||||||
|
getVisibleCommands(uint64_t clientId) const;
|
||||||
|
|
||||||
|
// Check if client can execute a command
|
||||||
|
[[nodiscard]] bool canExecuteCommand(uint64_t clientId,
|
||||||
|
const CommandPtr& cmd) const;
|
||||||
|
|
||||||
|
void setPrefix(std::string_view prefix);
|
||||||
|
[[nodiscard]] std::string_view getPrefix() const { return prefix_; }
|
||||||
|
|
||||||
|
// Set permission check function
|
||||||
|
void setPermissionCheckFunc(PermissionCheckFunc func);
|
||||||
|
// Set server config for permission checks
|
||||||
|
void setServerConfig(const Api::AppConfig& config);
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct CommandEntry {
|
||||||
|
std::string primaryName;
|
||||||
|
CommandPtr instance;
|
||||||
|
};
|
||||||
|
|
||||||
|
void registerBuiltinCommands();
|
||||||
|
|
||||||
|
// Internal Help Command (defined in .cpp to access registry)
|
||||||
|
class HelpCommand;
|
||||||
|
void registerHelpCommand();
|
||||||
|
|
||||||
|
std::string prefix_ = "!";
|
||||||
|
|
||||||
|
// Map for fast lookup: "play" -> PlayCommand
|
||||||
|
std::map<std::string, CommandPtr, std::less<>> commands_;
|
||||||
|
|
||||||
|
// List for generating help: {"play", PlayCommand}
|
||||||
|
std::vector<CommandEntry> uniqueCommands_;
|
||||||
|
|
||||||
|
mutable std::mutex mutex_;
|
||||||
|
|
||||||
|
// Permission checking
|
||||||
|
PermissionCheckFunc permissionCheck_;
|
||||||
|
std::optional<Api::AppConfig> serverConfig_;
|
||||||
|
|
||||||
|
// Async command execution
|
||||||
|
struct CommandTask {
|
||||||
|
uint64_t clientId;
|
||||||
|
std::string message;
|
||||||
|
std::weak_ptr<MusicManager> musicManager;
|
||||||
|
std::function<void(std::string_view)> replyFunc;
|
||||||
|
std::string invokerName;
|
||||||
|
};
|
||||||
|
|
||||||
|
void startThreadPool();
|
||||||
|
void processCommandQueue();
|
||||||
|
void executeCommandAsync(CommandTask task);
|
||||||
|
|
||||||
|
std::vector<std::jthread> workerThreads_;
|
||||||
|
std::queue<CommandTask> commandQueue_;
|
||||||
|
std::mutex queueMutex_;
|
||||||
|
std::condition_variable queueCv_;
|
||||||
|
std::atomic<bool> shutdown_{false};
|
||||||
|
static constexpr size_t THREAD_POOL_SIZE =
|
||||||
|
4; // Handle up to 4 concurrent commands
|
||||||
|
|
||||||
|
}; // namespace Echoion::Core
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -1,30 +1,132 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <echoion/api.hpp>
|
#include <ConfigTypes.hpp>
|
||||||
|
#include <Types.hpp>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
// Configuration loader for JSON config files (internal to Core)
|
// JSON structures for configuration (public for use by Core)
|
||||||
class ConfigLoader {
|
struct BotConfigJson {
|
||||||
public:
|
std::string botName = "Echoion";
|
||||||
// Load configuration from JSON file
|
std::string commandPrefix = "!";
|
||||||
[[nodiscard]] static Api::Result<Api::AppConfig> loadFromFile(const std::filesystem::path& path);
|
float defaultVolume = 0.5f;
|
||||||
|
uint32_t maxQueueSize = 100;
|
||||||
// Save configuration to JSON file
|
uint32_t trackTimeout = 30000;
|
||||||
[[nodiscard]] static Api::Result<void> saveToFile(const std::filesystem::path& path, const Api::AppConfig& config);
|
bool autoReconnect = true;
|
||||||
|
uint32_t reconnectDelay = 5000;
|
||||||
// Get default configuration path
|
uint32_t maxReconnectAttempts = 5;
|
||||||
[[nodiscard]] static std::filesystem::path getDefaultConfigPath();
|
std::string preferredQuality = "High";
|
||||||
|
bool allowPlaylistImports = true;
|
||||||
// Create default configuration
|
};
|
||||||
[[nodiscard]] static Api::AppConfig createDefaultConfig();
|
|
||||||
|
|
||||||
private:
|
struct YouTubeConfigJson {
|
||||||
// Parse quality string to enum
|
std::optional<std::string> youtubeApiKey;
|
||||||
[[nodiscard]] static Api::AudioQuality parseQuality(const std::string& str);
|
std::optional<std::string> youtubeCookiesPath;
|
||||||
[[nodiscard]] static std::string qualityToString(Api::AudioQuality quality);
|
std::optional<std::string> cookiesFromBrowser;
|
||||||
};
|
uint32_t ytDlpMaxConcurrent = 4;
|
||||||
|
bool ytDlpAsyncEnabled = true;
|
||||||
|
bool enableUrlShortening = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct NetworkConfigJson {
|
||||||
|
// Proxy settings (flat structure for backward compatibility)
|
||||||
|
std::string proxyType = "HTTP";
|
||||||
|
std::optional<std::string> proxyHost;
|
||||||
|
std::optional<uint16_t> proxyPort;
|
||||||
|
std::optional<std::string> proxyUsername;
|
||||||
|
std::optional<std::string> proxyPassword;
|
||||||
|
// RPC settings
|
||||||
|
bool rpcEnabled = true;
|
||||||
|
uint16_t rpcPort = 8765;
|
||||||
|
std::string rpcBindAddress = "127.0.0.1";
|
||||||
|
};
|
||||||
|
|
||||||
|
struct TeamSpeakConfigJson {
|
||||||
|
std::string address = "localhost";
|
||||||
|
uint16_t port = 9987;
|
||||||
|
std::string serverPassword = "";
|
||||||
|
std::string nickname = "EchoionBot";
|
||||||
|
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 SecurityConfigJson {
|
||||||
|
bool requireAuthForAdmin = true;
|
||||||
|
uint32_t maxLoginAttempts = 5;
|
||||||
|
uint32_t lockoutDuration = 300000;
|
||||||
|
uint32_t sessionTimeout = 3600000;
|
||||||
|
bool enableAuditLog = true;
|
||||||
|
std::optional<std::string> apiKey;
|
||||||
|
bool allowCors = false;
|
||||||
|
std::vector<std::string> corsOrigins;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct FeaturesConfigJson {
|
||||||
|
bool enableHotReload = true;
|
||||||
|
bool enableAutoReload = false;
|
||||||
|
bool enableAutoUpdateCheck = true;
|
||||||
|
bool autoStartOnSubscribe = true;
|
||||||
|
bool pauseOnEmptySubscribers = true;
|
||||||
|
bool resumeOnSubscriberReturn = true;
|
||||||
|
std::string shuffleMode = "random";
|
||||||
|
std::string repeatMode = "off";
|
||||||
|
uint32_t maxHistorySize = 50;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct AdvancedConfigJson {
|
||||||
|
uint32_t sampleRate = 192000;
|
||||||
|
uint32_t channels = 2;
|
||||||
|
uint32_t bufferSize = 7680;
|
||||||
|
uint32_t commandThreadPoolSize = 4;
|
||||||
|
uint32_t networkThreadPoolSize = 4;
|
||||||
|
uint32_t decoderThreads = 2;
|
||||||
|
bool cacheEnabled = true;
|
||||||
|
std::string cacheMaxSize = "1GB";
|
||||||
|
uint32_t cacheTTL = 86400;
|
||||||
|
uint32_t tempCleanupInterval = 3600;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct AppConfigJson {
|
||||||
|
BotConfigJson bot;
|
||||||
|
YouTubeConfigJson youtube;
|
||||||
|
NetworkConfigJson network;
|
||||||
|
TeamSpeakConfigJson teamspeak;
|
||||||
|
SecurityConfigJson security;
|
||||||
|
FeaturesConfigJson features;
|
||||||
|
AdvancedConfigJson advanced;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Configuration loader for JSON config files (internal to Core)
|
||||||
|
class ConfigLoader
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
// Load configuration from JSON file
|
||||||
|
[[nodiscard]] static Api::Result<Api::AppConfig>
|
||||||
|
loadFromFile(const std::filesystem::path& path);
|
||||||
|
|
||||||
|
// Save configuration to JSON file
|
||||||
|
[[nodiscard]] static Api::Result<void>
|
||||||
|
saveToFile(const std::filesystem::path& path,
|
||||||
|
const Api::AppConfig& config);
|
||||||
|
|
||||||
|
// Get default configuration path
|
||||||
|
[[nodiscard]] static std::filesystem::path getDefaultConfigPath();
|
||||||
|
|
||||||
|
// Create default configuration
|
||||||
|
[[nodiscard]] static Api::AppConfig createDefaultConfig();
|
||||||
|
|
||||||
|
// Parse quality string to enum
|
||||||
|
[[nodiscard]] static Api::AudioQuality
|
||||||
|
parseQuality(const std::string& str);
|
||||||
|
[[nodiscard]] static std::string
|
||||||
|
qualityToString(Api::AudioQuality quality);
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
+155
-85
@@ -1,111 +1,181 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <echoion/api.hpp>
|
|
||||||
#include <echoion/api/Database.hpp>
|
|
||||||
#include "MusicManager.hpp"
|
|
||||||
#include "CommandManager.hpp"
|
#include "CommandManager.hpp"
|
||||||
|
#include "ConfigLoader.hpp"
|
||||||
|
#include "MusicManager.hpp"
|
||||||
#include "NetworkClient.hpp"
|
#include "NetworkClient.hpp"
|
||||||
#include "RpcServer.hpp"
|
#include "RpcServer.hpp"
|
||||||
#include "ConfigLoader.hpp"
|
#include <ConfigTypes.hpp>
|
||||||
#include <thread>
|
#include <CoreInterface.hpp>
|
||||||
#include <mutex>
|
#include <Database.hpp>
|
||||||
|
#include <RpcTypes.hpp>
|
||||||
|
#include <StateBlob.hpp>
|
||||||
|
#include <TrackTypes.hpp>
|
||||||
|
#include <Types.hpp>
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
|
#include <mutex>
|
||||||
|
#include <thread>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
// Main Core implementation of ICoreInterface
|
// Main Core implementation of ICoreInterface
|
||||||
class Core : public Api::ICoreInterface {
|
class Core : public Api::ICoreInterface
|
||||||
public:
|
{
|
||||||
Core();
|
public:
|
||||||
~Core() override;
|
|
||||||
|
|
||||||
// ICoreInterface implementation
|
Core();
|
||||||
Api::Result<void> initialize(const std::filesystem::path& configPath) override;
|
~Core() override;
|
||||||
Api::Result<void> shutdown() override;
|
|
||||||
[[nodiscard]] bool isInitialized() const noexcept override;
|
|
||||||
|
|
||||||
// Playback control
|
// ICoreInterface - Lifecycle
|
||||||
Api::Result<void> play(const Api::TrackInfo& track) override;
|
Api::Result<void>
|
||||||
Api::Result<void> pause() override;
|
initialize(const std::filesystem::path& configPath) override;
|
||||||
Api::Result<void> resume() override;
|
Api::Result<void> shutdown() override;
|
||||||
Api::Result<void> stop() override;
|
[[nodiscard]] bool isInitialized() const noexcept override;
|
||||||
Api::Result<void> skip(uint32_t count) override;
|
|
||||||
Api::Result<void> seek(std::chrono::milliseconds position) override;
|
|
||||||
Api::Result<void> setVolume(float volume) override;
|
|
||||||
|
|
||||||
// Queue management
|
// ICoreInterface - Playback control (decoupled)
|
||||||
Api::Result<uint64_t> queueTrack(const Api::TrackInfo& track, uint64_t clientId) override;
|
Api::Result<void> play(const std::string& trackId) override;
|
||||||
Api::Result<void> removeFromQueue(uint64_t queueId) override;
|
Api::Result<void> pause() override;
|
||||||
Api::Result<void> clearQueue() override;
|
Api::Result<void> resume() override;
|
||||||
[[nodiscard]] Api::Result<std::vector<Api::QueueEntry>> getQueue() const override;
|
Api::Result<void> stop() override;
|
||||||
Api::Result<void> moveInQueue(uint64_t queueId, uint32_t newPosition) override;
|
Api::Result<void> skip(uint32_t count) override;
|
||||||
|
Api::Result<void> seek(std::chrono::milliseconds position) override;
|
||||||
|
Api::Result<void> setVolume(float volume) override;
|
||||||
|
|
||||||
// Track info
|
// ICoreInterface - Queue management (decoupled)
|
||||||
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>> getCurrentTrack() const override;
|
Api::Result<uint64_t> queueTrack(const std::string& trackId,
|
||||||
[[nodiscard]] Api::Result<Api::PlaybackState> getPlaybackState() const override;
|
uint64_t clientId) override;
|
||||||
|
Api::Result<void> removeFromQueue(uint64_t queueId) override;
|
||||||
|
Api::Result<void> clearQueue() override;
|
||||||
|
[[nodiscard]] Api::Result<std::vector<Api::TrackSummary>>
|
||||||
|
getQueueSummaries() const override;
|
||||||
|
Api::Result<void> moveInQueue(uint64_t queueId,
|
||||||
|
uint32_t newPosition) override;
|
||||||
|
|
||||||
// Playlist
|
// ICoreInterface - Track info (decoupled)
|
||||||
Api::Result<void> loadPlaylist(const std::string& playlistId, uint64_t clientId) override;
|
[[nodiscard]] Api::Result<std::optional<Api::TrackSummary>>
|
||||||
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>> getPlaylists() const override;
|
getCurrentTrackSummary() const override;
|
||||||
|
[[nodiscard]] Api::Result<Api::PlaybackSummary>
|
||||||
|
getPlaybackSummary() const override;
|
||||||
|
|
||||||
// Configuration
|
// ICoreInterface - Playlist (decoupled)
|
||||||
Api::Result<void> updateConfig(const Api::AppConfig& config) override;
|
Api::Result<void> loadPlaylist(const std::string& playlistId,
|
||||||
[[nodiscard]] Api::Result<Api::AppConfig> getConfig() const override;
|
uint64_t clientId) override;
|
||||||
// Reload config from disk (stored path from initialize)
|
[[nodiscard]] Api::Result<std::vector<std::string>>
|
||||||
Api::Result<void> reloadConfig();
|
getPlaylistIds() const override;
|
||||||
|
|
||||||
// Hot reload
|
// ICoreInterface - Configuration (decoupled)
|
||||||
Api::Result<Api::HotReloadState> prepareForHotReload() override;
|
Api::Result<void>
|
||||||
Api::Result<void> restoreAfterHotReload(const Api::HotReloadState& state) override;
|
updateConfigJson(const std::string& configJson) override;
|
||||||
|
[[nodiscard]] Api::Result<std::string>
|
||||||
|
getConfigJson() const override;
|
||||||
|
|
||||||
// Event handling
|
// ICoreInterface - Hot reload (decoupled)
|
||||||
void registerEventCallback(const Api::EventCallback& callback) override;
|
[[nodiscard]] Api::Result<std::string>
|
||||||
void unregisterEventCallback(const Api::EventCallback& callback) override;
|
prepareForHotReload() override;
|
||||||
|
Api::Result<void>
|
||||||
|
restoreAfterHotReload(const std::string& state) override;
|
||||||
|
|
||||||
// Plugin event processing
|
// ICoreInterface - Decoupled state management
|
||||||
Api::Result<void> onPluginEvent(const Api::PluginEvent& event) override;
|
[[nodiscard]] Api::StateBlob saveState() override;
|
||||||
|
Api::Result<void>
|
||||||
|
restoreState(const Api::StateBlob& state) override;
|
||||||
|
[[nodiscard]] uint32_t getStateFormatVersion() const override;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
canRestoreStateVersion(uint32_t version) const override;
|
||||||
|
|
||||||
// Status
|
// ICoreInterface - Event handling
|
||||||
[[nodiscard]] std::string getVersion() const override;
|
void registerEventCallback(
|
||||||
[[nodiscard]] std::chrono::system_clock::time_point getUptime() const override;
|
const Api::EventCallback& callback) override;
|
||||||
|
void unregisterEventCallback(
|
||||||
|
const Api::EventCallback& callback) override;
|
||||||
|
|
||||||
// Additional methods for plugin integration
|
// ICoreInterface - Plugin event processing
|
||||||
void setPluginInterface(Api::PluginInterfacePtr pluginInterface) override;
|
Api::Result<void>
|
||||||
void setAudioDataCallback(const MusicManager::AudioDataCallback& callback);
|
onPluginEvent(const Api::PluginEvent& event) override;
|
||||||
void triggerAutoConnect() override;
|
|
||||||
|
|
||||||
private:
|
// ICoreInterface - Status
|
||||||
void onMusicEvent(const Api::PluginEvent& event);
|
[[nodiscard]] std::string getVersion() const override;
|
||||||
void broadcastEvent(const Api::PluginEvent& event);
|
[[nodiscard]] std::chrono::system_clock::time_point
|
||||||
[[nodiscard]] bool isAdmin(uint64_t clientId) const;
|
getUptime() const override;
|
||||||
void updateWhisperList();
|
|
||||||
void setupRpcHandlers();
|
|
||||||
|
|
||||||
// Components
|
// ICoreInterface - Plugin interface
|
||||||
std::shared_ptr<NetworkClient> networkClient_;
|
void setPluginInterface(
|
||||||
std::shared_ptr<MusicManager> musicManager_;
|
Api::PluginInterfacePtr pluginInterface) override;
|
||||||
std::unique_ptr<CommandManager> commandManager_;
|
void triggerAutoConnect() override;
|
||||||
Api::PluginInterfacePtr pluginInterface_;
|
|
||||||
|
|
||||||
// State
|
// ICoreInterface - Advanced (for internal Core-to-Core use)
|
||||||
Api::AppConfig config_; // Config loaded internally
|
[[nodiscard]] Api::Result<Api::OpaqueHandle<Api::TrackInfo>>
|
||||||
std::filesystem::path configPath_; // Path to config file for reload
|
getCurrentTrackHandle() const override;
|
||||||
std::chrono::system_clock::time_point startTime_;
|
[[nodiscard]] Api::Result<
|
||||||
std::atomic<bool> initialized_{false};
|
std::vector<Api::OpaqueHandle<Api::QueueEntry>>>
|
||||||
|
getQueueHandles() const override;
|
||||||
|
[[nodiscard]] Api::Result<Api::AppConfigHandle>
|
||||||
|
getConfigHandle() const override;
|
||||||
|
Api::Result<void>
|
||||||
|
updateConfigFromHandle(Api::AppConfigHandle config) override;
|
||||||
|
|
||||||
// Event callbacks
|
// Additional methods for internal use (not in interface)
|
||||||
std::vector<Api::EventCallback> eventCallbacks_;
|
void setAudioDataCallback(
|
||||||
mutable std::mutex eventMutex_;
|
const MusicManager::AudioDataCallback& callback);
|
||||||
|
Api::Result<void> reloadConfig();
|
||||||
|
|
||||||
// Admin tracking
|
// Internal implementations using full types
|
||||||
std::vector<uint64_t> adminClients_;
|
Api::Result<void> playTrack(const Api::TrackInfo& track);
|
||||||
mutable std::mutex adminMutex_;
|
Api::Result<uint64_t> queueTrackFull(const Api::TrackInfo& track,
|
||||||
|
uint64_t clientId);
|
||||||
// Database for persistence
|
[[nodiscard]] Api::Result<std::vector<Api::QueueEntry>>
|
||||||
std::shared_ptr<Api::Database> database_;
|
getQueue() const;
|
||||||
|
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>>
|
||||||
// RPC server for Desktop/API clients
|
getCurrentTrack() const;
|
||||||
std::shared_ptr<RpcServer> rpcServer_;
|
[[nodiscard]] Api::Result<Api::PlaybackState>
|
||||||
};
|
getPlaybackState() const;
|
||||||
|
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>>
|
||||||
|
getPlaylists() const;
|
||||||
|
Api::Result<void> updateConfig(const Api::AppConfig& config);
|
||||||
|
[[nodiscard]] Api::Result<Api::AppConfig> getConfig() const;
|
||||||
|
[[nodiscard]] Api::Result<Api::HotReloadState>
|
||||||
|
prepareForHotReloadFull();
|
||||||
|
Api::Result<void>
|
||||||
|
restoreAfterHotReloadFull(const Api::HotReloadState& state);
|
||||||
|
|
||||||
|
// Generate RPC tokens for existing subscribers
|
||||||
|
void generateRpcTokensForSubscribers();
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
void onMusicEvent(const Api::PluginEvent& event);
|
||||||
|
void broadcastEvent(const Api::PluginEvent& event);
|
||||||
|
[[nodiscard]] bool isAdmin(uint64_t clientId) const;
|
||||||
|
void updateWhisperList();
|
||||||
|
void setupRpcHandlers();
|
||||||
|
void setupEventBusSubscriptions() const noexcept;
|
||||||
|
|
||||||
|
// Components
|
||||||
|
std::shared_ptr<NetworkClient> networkClient_;
|
||||||
|
std::shared_ptr<MusicManager> musicManager_;
|
||||||
|
std::unique_ptr<CommandManager> commandManager_;
|
||||||
|
Api::PluginInterfacePtr pluginInterface_;
|
||||||
|
|
||||||
|
// State
|
||||||
|
Api::AppConfig config_;
|
||||||
|
std::filesystem::path configPath_;
|
||||||
|
std::chrono::system_clock::time_point startTime_;
|
||||||
|
std::atomic<bool> initialized_{false};
|
||||||
|
|
||||||
|
// Event callbacks
|
||||||
|
std::vector<Api::EventCallback> eventCallbacks_;
|
||||||
|
mutable std::mutex eventMutex_;
|
||||||
|
|
||||||
|
// Admin tracking
|
||||||
|
std::vector<uint64_t> adminClients_;
|
||||||
|
mutable std::mutex adminMutex_;
|
||||||
|
|
||||||
|
// Database for persistence
|
||||||
|
std::shared_ptr<Api::Database> database_;
|
||||||
|
|
||||||
|
// RPC server for Desktop/API clients
|
||||||
|
std::shared_ptr<RpcServer> rpcServer_;
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -1,79 +1,77 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <echoion/api.hpp>
|
#include <LoggerInterface.hpp>
|
||||||
#include <fstream>
|
|
||||||
#include <mutex>
|
|
||||||
#include <queue>
|
|
||||||
#include <thread>
|
|
||||||
#include <condition_variable>
|
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
|
#include <cstdint>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include <chrono>
|
|
||||||
#include <array>
|
|
||||||
#include <map>
|
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Void::Logging
|
||||||
|
{
|
||||||
|
class MultiLogger;
|
||||||
|
} // namespace Void::Logging
|
||||||
|
|
||||||
// Log file info for rotation
|
namespace Echoion::Core
|
||||||
struct LogFileInfo {
|
{
|
||||||
std::filesystem::path path;
|
|
||||||
std::ofstream stream;
|
|
||||||
uint64_t size = 0;
|
|
||||||
std::chrono::system_clock::time_point createdAt;
|
|
||||||
};
|
|
||||||
|
|
||||||
class Logger : public Api::ILogger {
|
// ILogger implementation backed by the Void::Logging framework.
|
||||||
public:
|
//
|
||||||
explicit Logger(std::string_view logDir = "logs", std::string_view baseName = "echoion");
|
// Output is produced by a Void MultiLogger fanning out to:
|
||||||
~Logger() override;
|
// * a ConsoleLogger (stdout),
|
||||||
|
// * a SplitFileLogger writing per-level files (<dir>/<level>.log) plus a
|
||||||
|
// combined <dir>/all.log, each rolling independently by size, and
|
||||||
|
// * a CallbackLogger bridging back to the registered ILogger callbacks.
|
||||||
|
// The ILogger surface (levels, callbacks, console/file toggles, rotation
|
||||||
|
// knobs) is preserved so existing call sites and the ECHOION_LOG_* macros
|
||||||
|
// keep working unchanged.
|
||||||
|
class Logger : public Api::ILogger
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
void log(Api::LogLevel level, std::string_view message,
|
explicit Logger(std::string_view logDir = "logs",
|
||||||
std::source_location location) override;
|
std::string_view baseName = "echoion");
|
||||||
void setMinLevel(Api::LogLevel level) override;
|
~Logger() override;
|
||||||
[[nodiscard]] Api::LogLevel getMinLevel() const override;
|
|
||||||
void registerCallback(const LogCallback& callback) override;
|
|
||||||
void unregisterCallback(const LogCallback& callback) override;
|
|
||||||
|
|
||||||
void flush();
|
void log(Api::LogLevel level, std::string_view message,
|
||||||
void setConsoleOutput(bool enabled);
|
std::source_location location) override;
|
||||||
void setFileOutput(bool enabled);
|
void setMinLevel(Api::LogLevel level) override;
|
||||||
void setMaxFileSize(uint64_t bytes);
|
[[nodiscard]] Api::LogLevel getMinLevel() const override;
|
||||||
void setMaxFiles(uint32_t count);
|
void registerCallback(const LogCallback& callback) override;
|
||||||
|
void unregisterCallback(const LogCallback& callback) override;
|
||||||
|
|
||||||
private:
|
void flush();
|
||||||
void logWorker();
|
void setConsoleOutput(bool enabled);
|
||||||
void rotateIfNeeded(Api::LogLevel level);
|
void setFileOutput(bool enabled);
|
||||||
void openLogFiles();
|
void setMaxFileSize(uint64_t bytes);
|
||||||
void cleanupOldLogs();
|
void setMaxFiles(uint32_t count);
|
||||||
void moveToHistory(const std::filesystem::path& filePath);
|
|
||||||
void ensureHistoryDirExists();
|
|
||||||
[[nodiscard]] std::string formatLogEntry(const Api::LogEntry& entry);
|
|
||||||
[[nodiscard]] std::string levelToString(Api::LogLevel level);
|
|
||||||
[[nodiscard]] std::filesystem::path generateLogFilePath(Api::LogLevel level);
|
|
||||||
[[nodiscard]] std::string formatTimestamp(const std::chrono::system_clock::time_point& tp);
|
|
||||||
void writeToFile(Api::LogLevel level, const std::string& formattedEntry);
|
|
||||||
|
|
||||||
std::filesystem::path logDir_;
|
private:
|
||||||
std::string baseName_;
|
|
||||||
|
// (Re)assemble the Void sink tree from the current toggles/limits.
|
||||||
// Separate files for each level + combined file
|
void rebuildSinks();
|
||||||
std::map<Api::LogLevel, LogFileInfo> levelFiles_;
|
// Fan a Void log entry out to the registered ILogger callbacks.
|
||||||
LogFileInfo combinedFile_;
|
void dispatchToCallbacks(Api::LogLevel level,
|
||||||
|
const std::string& message,
|
||||||
std::mutex fileMutex_;
|
const std::string& file, uint32_t line,
|
||||||
std::mutex queueMutex_;
|
const std::string& function);
|
||||||
std::queue<Api::LogEntry> logQueue_;
|
|
||||||
std::thread workerThread_;
|
std::filesystem::path logDir_;
|
||||||
std::condition_variable cv_;
|
std::string baseName_;
|
||||||
std::atomic<bool> running_{true};
|
|
||||||
std::atomic<Api::LogLevel> minLevel_{Api::LogLevel::Info};
|
std::shared_ptr<Void::Logging::MultiLogger> sink_;
|
||||||
std::atomic<bool> consoleOutput_{true};
|
std::mutex sinkMutex_;
|
||||||
std::atomic<bool> fileOutput_{true};
|
|
||||||
std::atomic<uint64_t> maxFileSize_{10 * 1024 * 1024}; // 10 MB per file
|
std::atomic<Api::LogLevel> minLevel_{Api::LogLevel::Info};
|
||||||
std::atomic<uint32_t> maxFiles_{5};
|
std::atomic<bool> consoleOutput_{true};
|
||||||
std::vector<LogCallback> callbacks_;
|
std::atomic<bool> fileOutput_{true};
|
||||||
std::mutex callbackMutex_;
|
std::atomic<uint64_t> maxFileSize_{10 * 1024 * 1024}; // 10 MB
|
||||||
};
|
std::atomic<uint32_t> maxFiles_{5};
|
||||||
|
|
||||||
|
std::vector<LogCallback> callbacks_;
|
||||||
|
std::mutex callbackMutex_;
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -1,205 +1,271 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <echoion/api.hpp>
|
|
||||||
#include "NetworkClient.hpp"
|
|
||||||
#include "YouTubeClient.hpp"
|
|
||||||
#include "AudioDecoder.hpp"
|
#include "AudioDecoder.hpp"
|
||||||
|
#include "Database.hpp"
|
||||||
|
#include "NetworkClient.hpp"
|
||||||
|
#include "RpcTypes.hpp"
|
||||||
#include "SubscriptionManager.hpp"
|
#include "SubscriptionManager.hpp"
|
||||||
#include <thread>
|
#include "YouTubeClient.hpp"
|
||||||
#include <mutex>
|
#include <ConfigTypes.hpp>
|
||||||
|
#include <TrackTypes.hpp>
|
||||||
|
#include <Types.hpp>
|
||||||
|
#include <atomic>
|
||||||
#include <condition_variable>
|
#include <condition_variable>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <future>
|
||||||
|
#include <mutex>
|
||||||
#include <queue>
|
#include <queue>
|
||||||
#include <random>
|
#include <random>
|
||||||
#include <atomic>
|
|
||||||
#include <future>
|
|
||||||
#include <set>
|
#include <set>
|
||||||
|
#include <shared_mutex>
|
||||||
|
#include <thread>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
#include <filesystem>
|
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class MusicManager {
|
class MusicManager
|
||||||
public:
|
{
|
||||||
MusicManager();
|
public:
|
||||||
~MusicManager();
|
|
||||||
|
|
||||||
Api::Result<void> initialize(const Api::BotConfig& config,
|
MusicManager();
|
||||||
std::shared_ptr<NetworkClient> networkClient,
|
~MusicManager();
|
||||||
std::shared_ptr<Api::Database> database = nullptr);
|
|
||||||
void shutdown();
|
|
||||||
|
|
||||||
[[nodiscard]] Api::Result<std::string> play(const std::string& query, uint64_t clientId);
|
Api::Result<void>
|
||||||
[[nodiscard]] Api::Result<void> pause();
|
initialize(std::shared_ptr<NetworkClient> networkClient,
|
||||||
[[nodiscard]] Api::Result<void> resume();
|
std::shared_ptr<Api::Database> database = nullptr);
|
||||||
[[nodiscard]] Api::Result<void> stop();
|
void shutdown();
|
||||||
[[nodiscard]] Api::Result<void> skip(uint32_t count = 1);
|
|
||||||
[[nodiscard]] Api::Result<void> seek(std::chrono::milliseconds position);
|
|
||||||
[[nodiscard]] Api::Result<void> setVolume(float volume);
|
|
||||||
|
|
||||||
[[nodiscard]] Api::Result<uint64_t> queueTrack(const Api::TrackInfo& track, uint64_t clientId);
|
[[nodiscard]] Api::Result<std::string>
|
||||||
[[nodiscard]] Api::Result<void> removeFromQueue(uint32_t position);
|
play(const std::string& query, uint64_t clientId);
|
||||||
[[nodiscard]] Api::Result<void> clearQueue();
|
[[nodiscard]] Api::Result<void> pause();
|
||||||
[[nodiscard]] Api::Result<std::vector<Api::QueueEntry>> getQueue() const;
|
[[nodiscard]] Api::Result<void> resume();
|
||||||
[[nodiscard]] Api::Result<void> moveInQueue(uint32_t from, uint32_t to);
|
[[nodiscard]] Api::Result<void> stop();
|
||||||
[[nodiscard]] Api::Result<bool> toggleShuffle();
|
[[nodiscard]] Api::Result<void> skip(uint32_t count = 1);
|
||||||
[[nodiscard]] Api::Result<bool> toggleRepeat();
|
[[nodiscard]] Api::Result<void>
|
||||||
|
seek(std::chrono::milliseconds position);
|
||||||
|
[[nodiscard]] Api::Result<void> setVolume(float volume);
|
||||||
|
|
||||||
// Load playlist asynchronously - returns immediately, processes in background
|
[[nodiscard]] Api::Result<uint64_t>
|
||||||
Api::Result<void> loadPlaylist(const std::string& playlistIdOrUrl, uint64_t clientId);
|
queueTrack(const Api::TrackInfo& track, uint64_t clientId);
|
||||||
[[nodiscard]] bool isPlaylistLoading() const { return playlistLoading_.load(); }
|
[[nodiscard]] Api::Result<void> removeFromQueue(uint32_t position);
|
||||||
[[nodiscard]] size_t getPlaylistLoadProgress() const { return playlistLoadedCount_.load(); }
|
[[nodiscard]] Api::Result<void> clearQueue();
|
||||||
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>>
|
[[nodiscard]] Api::Result<std::vector<Api::QueueEntry>>
|
||||||
getPlaylists() const;
|
getQueue() const;
|
||||||
|
[[nodiscard]] Api::Result<void> moveInQueue(uint32_t from,
|
||||||
|
uint32_t to);
|
||||||
|
[[nodiscard]] Api::Result<bool> toggleShuffle();
|
||||||
|
[[nodiscard]] Api::Result<bool> toggleRepeat();
|
||||||
|
[[nodiscard]] Api::Result<void> shuffleQueue();
|
||||||
|
|
||||||
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>>
|
// Load playlist asynchronously - returns immediately, processes in
|
||||||
getCurrentTrack() const;
|
// background
|
||||||
[[nodiscard]] Api::Result<Api::PlaybackState> getPlaybackState() const;
|
Api::Result<void> loadPlaylist(const std::string& playlistIdOrUrl,
|
||||||
[[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const;
|
uint64_t clientId);
|
||||||
|
[[nodiscard]] bool isPlaylistLoading() const
|
||||||
|
{
|
||||||
|
return playlistLoading_.load();
|
||||||
|
}
|
||||||
|
[[nodiscard]] size_t getPlaylistLoadProgress() const
|
||||||
|
{
|
||||||
|
return playlistLoadedCount_.load();
|
||||||
|
}
|
||||||
|
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>>
|
||||||
|
getPlaylists() const;
|
||||||
|
|
||||||
[[nodiscard]] Api::Result<Api::SearchResult> search(const std::string& query);
|
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>>
|
||||||
|
getCurrentTrack() const;
|
||||||
// Search result selection (client-specific)
|
[[nodiscard]] Api::Result<Api::PlaybackState>
|
||||||
void storePendingSearch(uint64_t clientId, const std::vector<Api::TrackInfo>& results);
|
getPlaybackState() const;
|
||||||
[[nodiscard]] std::optional<std::vector<Api::TrackInfo>> getPendingSearch(uint64_t clientId);
|
[[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const;
|
||||||
[[nodiscard]] Api::Result<std::string> selectSearchResult(
|
|
||||||
uint64_t clientId, uint32_t index, const std::string& invokerName);
|
|
||||||
|
|
||||||
// Help command
|
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||||
[[nodiscard]] std::string getHelpText() const;
|
search(const std::string& query);
|
||||||
|
|
||||||
// Subscription management (by client ID - internally uses UID for
|
// Search result selection (client-specific)
|
||||||
// persistence)
|
void storePendingSearch(uint64_t clientId,
|
||||||
[[nodiscard]] Api::Result<std::string> subscribe(uint64_t clientId);
|
const std::vector<Api::TrackInfo>& results);
|
||||||
[[nodiscard]] Api::Result<std::string> unsubscribe(uint64_t clientId);
|
[[nodiscard]] std::optional<std::vector<Api::TrackInfo>>
|
||||||
[[nodiscard]] bool isSubscribed(uint64_t clientId) const;
|
getPendingSearch(uint64_t clientId);
|
||||||
[[nodiscard]] std::set<uint64_t> getSubscribedClients()
|
[[nodiscard]] Api::Result<std::string>
|
||||||
const; // Returns only ONLINE subscribers' client IDs
|
selectSearchResult(uint64_t clientId,
|
||||||
[[nodiscard]] bool hasSubscribers()
|
uint32_t index,
|
||||||
const; // Returns true if any subscribers exist (online or offline)
|
const std::string& invokerName);
|
||||||
[[nodiscard]] bool hasOnlineSubscribers()
|
|
||||||
const; // Returns true only if there are online subscribers
|
|
||||||
[[nodiscard]] std::vector<SubscriptionManager::Subscriber>
|
|
||||||
getSubscribers() const;
|
|
||||||
[[nodiscard]] Api::Result<std::string>
|
|
||||||
unsubscribeByUid(const std::string& uid);
|
|
||||||
[[nodiscard]] Api::Result<std::string> clearAllSubscriptions();
|
|
||||||
|
|
||||||
// Get UIDs of subscribers who are currently online
|
// Help command
|
||||||
[[nodiscard]] std::set<std::string> getOnlineSubscriberUids() const;
|
[[nodiscard]] std::string getHelpText() const;
|
||||||
|
|
||||||
// Called when a client connects to the server
|
// Subscription management (by client ID - internally uses UID for
|
||||||
void onClientConnected(uint64_t clientId);
|
// persistence)
|
||||||
|
[[nodiscard]] Api::Result<std::string> subscribe(uint64_t clientId);
|
||||||
|
[[nodiscard]] Api::Result<std::string>
|
||||||
|
unsubscribe(uint64_t clientId);
|
||||||
|
[[nodiscard]] bool isSubscribed(uint64_t clientId) const;
|
||||||
|
[[nodiscard]] std::set<uint64_t> getSubscribedClients()
|
||||||
|
const; // Returns only ONLINE subscribers' client IDs
|
||||||
|
[[nodiscard]] bool
|
||||||
|
hasSubscribers() const; // Returns true if any subscribers exist
|
||||||
|
// (online or offline)
|
||||||
|
[[nodiscard]] bool hasOnlineSubscribers()
|
||||||
|
const; // Returns true only if there are online subscribers
|
||||||
|
[[nodiscard]] std::vector<SubscriptionManager::Subscriber>
|
||||||
|
getSubscribers() const;
|
||||||
|
[[nodiscard]] Api::Result<std::string>
|
||||||
|
unsubscribeByUid(const std::string& uid);
|
||||||
|
[[nodiscard]] Api::Result<std::string> clearAllSubscriptions();
|
||||||
|
|
||||||
[[nodiscard]] Api::HotReloadState getStateForHotReload() const;
|
// Get UIDs of subscribers who are currently online
|
||||||
[[nodiscard]] Api::Result<void>
|
[[nodiscard]] std::set<std::string> getOnlineSubscriberUids() const;
|
||||||
restoreFromHotReload(const Api::HotReloadState& state);
|
|
||||||
|
|
||||||
using AudioDataCallback = std::function<void(const std::span<const short>)>;
|
// Called when a client connects to the server
|
||||||
void setAudioDataCallback(const AudioDataCallback& callback);
|
void onClientConnected(uint64_t clientId);
|
||||||
|
|
||||||
using SubscriptionChangeCallback = std::function<void()>;
|
[[nodiscard]] Api::HotReloadState getStateForHotReload() const;
|
||||||
void setSubscriptionChangeCallback(const SubscriptionChangeCallback& callback);
|
[[nodiscard]] Api::Result<void>
|
||||||
|
restoreFromHotReload(const Api::HotReloadState& state);
|
||||||
|
|
||||||
using PlaybackStartCallback = std::function<void()>;
|
using AudioDataCallback =
|
||||||
void setPlaybackStartCallback(const PlaybackStartCallback& callback);
|
std::function<void(const std::span<const short>)>;
|
||||||
|
void setAudioDataCallback(const AudioDataCallback& callback);
|
||||||
|
|
||||||
// Callback to resolve client info (UID and nickname) from client ID
|
using SubscriptionChangeCallback = std::function<void()>;
|
||||||
using ClientInfoCallback =
|
void setSubscriptionChangeCallback(
|
||||||
std::function<std::optional<std::pair<std::string, std::string>>(
|
const SubscriptionChangeCallback& callback);
|
||||||
uint64_t clientId)>;
|
|
||||||
void setClientInfoCallback(const ClientInfoCallback& callback);
|
|
||||||
|
|
||||||
// Callback to resolve client ID from UID
|
using PlaybackStartCallback = std::function<void()>;
|
||||||
using UidToClientIdCallback =
|
void
|
||||||
std::function<std::optional<uint64_t>(const std::string& uid)>;
|
setPlaybackStartCallback(const PlaybackStartCallback& callback);
|
||||||
void setUidToClientIdCallback(const UidToClientIdCallback& callback);
|
|
||||||
|
|
||||||
// Callback to resolve nickname from client ID
|
// Callback to resolve client info (UID and nickname) from client ID
|
||||||
using NicknameCallback =
|
using ClientInfoCallback = std::function<std::optional<
|
||||||
std::function<std::optional<std::string>(uint64_t clientId)>;
|
std::pair<std::string, std::string>>(uint64_t clientId)>;
|
||||||
void setNicknameCallback(const NicknameCallback& callback);
|
void setClientInfoCallback(const ClientInfoCallback& callback);
|
||||||
|
|
||||||
// Called when a client leaves the server
|
// Callback to resolve client ID from UID
|
||||||
void onClientDisconnected(uint64_t clientId);
|
using UidToClientIdCallback =
|
||||||
|
std::function<std::optional<uint64_t>(const std::string& uid)>;
|
||||||
|
void
|
||||||
|
setUidToClientIdCallback(const UidToClientIdCallback& callback);
|
||||||
|
|
||||||
private:
|
// Callback to resolve nickname from client ID
|
||||||
void playbackThread();
|
using NicknameCallback =
|
||||||
[[nodiscard]] Api::Result<Api::TrackInfo> resolveQuery(const std::string& query);
|
std::function<std::optional<std::string>(uint64_t clientId)>;
|
||||||
[[nodiscard]] Api::Result<std::string> getStreamUrl(const Api::TrackInfo& track);
|
void setNicknameCallback(const NicknameCallback& callback);
|
||||||
void onTrackFinished();
|
|
||||||
[[nodiscard]] Api::TrackInfo getNextTrack();
|
|
||||||
void shuffleQueue();
|
|
||||||
|
|
||||||
// Download audio through proxy for playback
|
|
||||||
[[nodiscard]] Api::Result<std::string> downloadAudioForPlayback(const std::string& url);
|
|
||||||
void cleanupTempFile(const std::string& filepath);
|
|
||||||
|
|
||||||
// Prefetch next track for seamless transitions
|
|
||||||
void prefetchNextTrack();
|
|
||||||
[[nodiscard]] bool shouldPrefetch() const;
|
|
||||||
static constexpr auto PREFETCH_THRESHOLD = std::chrono::seconds(15); // Start prefetch 15s before end
|
|
||||||
|
|
||||||
// Temporary file tracking
|
|
||||||
std::set<std::string> tempFiles_;
|
|
||||||
mutable std::mutex tempFilesMutex_;
|
|
||||||
|
|
||||||
// Prefetch state for seamless playback
|
|
||||||
struct PrefetchState {
|
|
||||||
std::future<Api::Result<std::string>> streamUrlFuture;
|
|
||||||
std::atomic<bool> isPrefetching{false};
|
|
||||||
std::atomic<bool> hasPrefetched{false};
|
|
||||||
std::optional<std::string> prefetchedUrl;
|
|
||||||
} prefetchState_;
|
|
||||||
|
|
||||||
// Async playlist loading state
|
|
||||||
std::thread playlistLoadThread_;
|
|
||||||
std::atomic<bool> playlistLoading_{false};
|
|
||||||
std::atomic<size_t> playlistLoadedCount_{0};
|
|
||||||
std::atomic<size_t> playlistTotalCount_{0};
|
|
||||||
|
|
||||||
std::shared_ptr<NetworkClient> networkClient_;
|
// Called when a client leaves the server
|
||||||
std::unique_ptr<YouTubeClient> youTubeClient_;
|
void onClientDisconnected(uint64_t clientId);
|
||||||
std::unique_ptr<AudioDecoder> audioDecoder_;
|
|
||||||
std::unique_ptr<SubscriptionManager> subscriptionManager_;
|
|
||||||
|
|
||||||
Api::BotConfig config_;
|
private:
|
||||||
std::vector<Api::QueueEntry> queue_;
|
|
||||||
std::optional<Api::QueueEntry> currentTrack_;
|
|
||||||
bool isPlaying_ = false;
|
|
||||||
bool isPaused_ = false;
|
|
||||||
bool wasPausedForNoSubscribers_ = false; // Track if we auto-paused
|
|
||||||
|
|
||||||
// Accurate playback position tracking
|
|
||||||
std::chrono::milliseconds playbackPosition_{0}; // Current position
|
|
||||||
std::chrono::steady_clock::time_point playbackStartTime_; // When current segment started
|
|
||||||
std::chrono::milliseconds playbackBasePosition_{0}; // Position at start of current segment
|
|
||||||
float volume_ = 0.5f;
|
|
||||||
bool shuffle_ = false;
|
|
||||||
bool repeat_ = false;
|
|
||||||
uint64_t nextQueueId_ = 1;
|
|
||||||
|
|
||||||
std::jthread playbackThread_;
|
void playbackThread();
|
||||||
mutable std::mutex mutex_;
|
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||||
std::condition_variable cv_;
|
resolveQuery(const std::string& query);
|
||||||
std::atomic<bool> playbackThreadRunning_{false}; // True while thread is actively running
|
[[nodiscard]] Api::Result<std::string>
|
||||||
|
getStreamUrl(const Api::TrackInfo& track);
|
||||||
// Pending search results per client (for select command)
|
void onTrackFinished();
|
||||||
std::unordered_map<uint64_t, std::vector<Api::TrackInfo>> pendingSearches_;
|
[[nodiscard]] Api::TrackInfo getNextTrack();
|
||||||
mutable std::mutex pendingSearchMutex_;
|
|
||||||
|
|
||||||
AudioDataCallback audioCallback_;
|
// Generate silence/sine wave to keep audio stream alive during
|
||||||
SubscriptionChangeCallback subscriptionChangeCallback_;
|
// transitions
|
||||||
PlaybackStartCallback playbackStartCallback_;
|
void generateTransitionAudio(std::chrono::milliseconds duration);
|
||||||
ClientInfoCallback clientInfoCallback_;
|
void sendSilenceChunk();
|
||||||
UidToClientIdCallback uidToClientIdCallback_;
|
static constexpr auto TRANSITION_SILENCE_DURATION =
|
||||||
NicknameCallback nicknameCallback_;
|
std::chrono::milliseconds(100);
|
||||||
std::mt19937 rng_{std::random_device{}()};
|
static constexpr auto TRANSITION_FADE_DURATION =
|
||||||
|
std::chrono::milliseconds(50);
|
||||||
|
|
||||||
static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE =
|
// Download audio through proxy for playback
|
||||||
192000; // Match TeamSpeak CODEC_OPUS_MUSIC
|
[[nodiscard]] Api::Result<std::string>
|
||||||
static constexpr uint32_t TEAMSPEAK_CHANNELS = 2;
|
downloadAudioForPlayback(const std::string& url);
|
||||||
static constexpr size_t AUDIO_BUFFER_SIZE = 7680; // 20ms @ 192kHz stereo
|
void cleanupTempFile(const std::string& filepath);
|
||||||
static constexpr uint32_t CONCURRENT_LOAD_THREADS = 4;
|
|
||||||
};
|
// Prefetch next track for seamless transitions
|
||||||
|
void prefetchNextTrack();
|
||||||
|
[[nodiscard]] bool shouldPrefetch() const;
|
||||||
|
static constexpr auto PREFETCH_THRESHOLD =
|
||||||
|
std::chrono::seconds(15); // Start prefetch 15s before end
|
||||||
|
|
||||||
|
// Temporary file tracking
|
||||||
|
std::set<std::string> tempFiles_;
|
||||||
|
mutable std::shared_mutex tempFilesMutex_;
|
||||||
|
|
||||||
|
// Prefetch state for seamless playback
|
||||||
|
struct PrefetchState {
|
||||||
|
std::future<Api::Result<std::string>> streamUrlFuture;
|
||||||
|
std::atomic<bool> isPrefetching{false};
|
||||||
|
std::atomic<bool> hasPrefetched{false};
|
||||||
|
std::optional<std::string> prefetchedUrl;
|
||||||
|
} prefetchState_;
|
||||||
|
|
||||||
|
// Async playlist loading state
|
||||||
|
std::thread playlistLoadThread_;
|
||||||
|
std::atomic<bool> playlistLoading_{false};
|
||||||
|
std::atomic<size_t> playlistLoadedCount_{0};
|
||||||
|
std::atomic<size_t> playlistTotalCount_{0};
|
||||||
|
|
||||||
|
// Auto-start thread for playlist (must be joined, not detached)
|
||||||
|
std::thread playlistAutoStartThread_;
|
||||||
|
|
||||||
|
std::shared_ptr<NetworkClient> networkClient_;
|
||||||
|
std::unique_ptr<YouTubeClient> youTubeClient_;
|
||||||
|
std::unique_ptr<AudioDecoder> audioDecoder_;
|
||||||
|
std::unique_ptr<SubscriptionManager> subscriptionManager_;
|
||||||
|
|
||||||
|
Api::BotConfig config_;
|
||||||
|
std::vector<Api::QueueEntry> queue_;
|
||||||
|
std::optional<Api::QueueEntry> currentTrack_;
|
||||||
|
std::atomic<bool> isPlaying_{false};
|
||||||
|
std::atomic<bool> isPaused_{false};
|
||||||
|
std::atomic<bool> wasPausedForNoSubscribers_{
|
||||||
|
false}; // Track if we auto-paused
|
||||||
|
|
||||||
|
// Accurate playback position tracking
|
||||||
|
std::chrono::milliseconds playbackPosition_{0}; // Current position
|
||||||
|
std::chrono::steady_clock::time_point
|
||||||
|
playbackStartTime_; // When current segment started
|
||||||
|
std::chrono::milliseconds playbackBasePosition_{
|
||||||
|
0}; // Position at start of current segment
|
||||||
|
std::atomic<float> volume_{0.5f};
|
||||||
|
std::atomic<bool> shuffle_{false};
|
||||||
|
std::atomic<bool> repeat_{false};
|
||||||
|
uint64_t nextQueueId_ = 1;
|
||||||
|
|
||||||
|
// Shuffle state - maintains shuffled order of queue indices
|
||||||
|
std::vector<size_t> shuffledIndices_;
|
||||||
|
size_t shuffleIndex_ = 0;
|
||||||
|
void rebuildShuffledIndices();
|
||||||
|
void reshuffleRemaining();
|
||||||
|
|
||||||
|
std::jthread playbackThread_;
|
||||||
|
mutable std::shared_mutex mutex_;
|
||||||
|
std::condition_variable_any cv_;
|
||||||
|
std::atomic<bool> playbackThreadRunning_{
|
||||||
|
false}; // True while thread is actively running
|
||||||
|
|
||||||
|
// Pending search results per client (for select command)
|
||||||
|
std::unordered_map<uint64_t, std::vector<Api::TrackInfo>>
|
||||||
|
pendingSearches_;
|
||||||
|
mutable std::mutex pendingSearchMutex_;
|
||||||
|
|
||||||
|
AudioDataCallback audioCallback_;
|
||||||
|
SubscriptionChangeCallback subscriptionChangeCallback_;
|
||||||
|
PlaybackStartCallback playbackStartCallback_;
|
||||||
|
ClientInfoCallback clientInfoCallback_;
|
||||||
|
UidToClientIdCallback uidToClientIdCallback_;
|
||||||
|
NicknameCallback nicknameCallback_;
|
||||||
|
std::mt19937 rng_{std::random_device{}()};
|
||||||
|
|
||||||
|
// Position tracking for periodic event updates
|
||||||
|
std::chrono::steady_clock::time_point lastPositionUpdate_{};
|
||||||
|
static constexpr auto POSITION_UPDATE_INTERVAL =
|
||||||
|
std::chrono::seconds(1);
|
||||||
|
|
||||||
|
static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE =
|
||||||
|
192000; // Match TeamSpeak CODEC_OPUS_MUSIC
|
||||||
|
static constexpr uint32_t TEAMSPEAK_CHANNELS = 2;
|
||||||
|
static constexpr size_t AUDIO_BUFFER_SIZE =
|
||||||
|
7680; // 20ms @ 192kHz stereo
|
||||||
|
static constexpr uint32_t CONCURRENT_LOAD_THREADS = 4;
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -1,202 +1,238 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "boost/asio/ssl/context.hpp"
|
#include "boost/asio/ssl/context.hpp"
|
||||||
#include <echoion/api.hpp>
|
#include <NetworkInterface.hpp>
|
||||||
#include <glaze/glaze.hpp>
|
#include <NetworkTypes.hpp>
|
||||||
#include <thread>
|
#include <Types.hpp>
|
||||||
#include <mutex>
|
#include <Void/Data/Json.hpp>
|
||||||
#include <future>
|
#include <Void/Data/Reflect.hpp>
|
||||||
#include <queue>
|
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
|
#include <future>
|
||||||
|
#include <mutex>
|
||||||
|
#include <queue>
|
||||||
|
#include <thread>
|
||||||
|
|
||||||
// Boost.Beast includes needed for template function
|
// Boost.Beast includes needed for template function
|
||||||
#include <boost/beast.hpp>
|
#include <boost/beast.hpp>
|
||||||
#include <boost/beast/http.hpp>
|
#include <boost/beast/http.hpp>
|
||||||
|
|
||||||
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
|
// Forward declaration for URL parsing
|
||||||
|
struct UrlComponents;
|
||||||
|
|
||||||
|
class NetworkClient : public Api::INetworkClient
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
NetworkClient();
|
||||||
|
~NetworkClient() override;
|
||||||
|
|
||||||
namespace Echoion::Core {
|
// Initialize with optional proxy
|
||||||
|
Api::Result<void> initialize(
|
||||||
|
const std::optional<Api::ProxyConfig>& proxy = std::nullopt);
|
||||||
|
void shutdown();
|
||||||
|
|
||||||
// Forward declaration for URL parsing
|
// Synchronous requests
|
||||||
struct UrlComponents;
|
[[nodiscard]] Api::Result<Api::HttpResponse>
|
||||||
|
get(std::string_view url,
|
||||||
|
const std::vector<Api::HttpHeader>& headers = {});
|
||||||
|
[[nodiscard]] Api::Result<Api::HttpResponse>
|
||||||
|
post(std::string_view url, std::string_view body,
|
||||||
|
const std::vector<Api::HttpHeader>& headers = {});
|
||||||
|
[[nodiscard]] Api::Result<Api::HttpResponse>
|
||||||
|
request(const Api::HttpRequest& req);
|
||||||
|
|
||||||
class NetworkClient : public Api::INetworkClient {
|
// Asynchronous requests
|
||||||
public:
|
[[nodiscard]] std::future<Api::Result<Api::HttpResponse>>
|
||||||
NetworkClient();
|
getAsync(std::string_view url,
|
||||||
~NetworkClient() override;
|
const std::vector<Api::HttpHeader>& headers = {});
|
||||||
|
[[nodiscard]] std::future<Api::Result<Api::HttpResponse>>
|
||||||
|
postAsync(std::string_view url, std::string_view body,
|
||||||
|
const std::vector<Api::HttpHeader>& headers = {});
|
||||||
|
[[nodiscard]] std::future<Api::Result<Api::HttpResponse>>
|
||||||
|
requestAsync(const Api::HttpRequest& req);
|
||||||
|
|
||||||
// Initialize with optional proxy
|
// Concurrent batch requests
|
||||||
Api::Result<void> initialize(const std::optional<Api::ProxyConfig>& proxy = std::nullopt);
|
[[nodiscard]] std::vector<Api::Result<Api::HttpResponse>>
|
||||||
void shutdown();
|
requestBatch(const std::vector<Api::HttpRequest>& requests);
|
||||||
|
|
||||||
// Synchronous requests
|
// JSON helpers using Void::Json reflection
|
||||||
[[nodiscard]] Api::Result<Api::HttpResponse> get(std::string_view url,
|
template <typename T>
|
||||||
const std::vector<Api::HttpHeader>& headers = {});
|
[[nodiscard]] Api::Result<T>
|
||||||
[[nodiscard]] Api::Result<Api::HttpResponse> post(std::string_view url,
|
getJson(std::string_view url,
|
||||||
std::string_view body, const std::vector<Api::HttpHeader>& headers = {});
|
const std::vector<Api::HttpHeader>& headers = {})
|
||||||
[[nodiscard]] Api::Result<Api::HttpResponse> request(const Api::HttpRequest& req);
|
{
|
||||||
|
auto response = get(url, headers);
|
||||||
|
if (!response) {
|
||||||
|
return std::unexpected(response.error());
|
||||||
|
}
|
||||||
|
return parseJson<T>(response->bodyAsString());
|
||||||
|
}
|
||||||
|
|
||||||
// Asynchronous requests
|
template <typename T, typename Body>
|
||||||
[[nodiscard]] std::future<Api::Result<Api::HttpResponse>> getAsync(std::string_view url,
|
[[nodiscard]] Api::Result<T>
|
||||||
const std::vector<Api::HttpHeader>& headers = {});
|
postJson(std::string_view url, const Body& body,
|
||||||
[[nodiscard]] std::future<Api::Result<Api::HttpResponse>> postAsync(std::string_view url,
|
const std::vector<Api::HttpHeader>& headers = {})
|
||||||
std::string_view body, const std::vector<Api::HttpHeader>& headers = {});
|
{
|
||||||
[[nodiscard]] std::future<Api::Result<Api::HttpResponse>> requestAsync(const Api::HttpRequest& req);
|
std::string jsonBody =
|
||||||
|
Void::Json::serialize(Void::Json::to_json(body));
|
||||||
|
auto response = post(url, jsonBody, headers);
|
||||||
|
if (!response) {
|
||||||
|
return std::unexpected(response.error());
|
||||||
|
}
|
||||||
|
return parseJson<T>(response->bodyAsString());
|
||||||
|
}
|
||||||
|
|
||||||
// Concurrent batch requests
|
private:
|
||||||
[[nodiscard]] std::vector<Api::Result<Api::HttpResponse>> requestBatch(
|
|
||||||
const std::vector<Api::HttpRequest>& requests);
|
|
||||||
|
|
||||||
// JSON helpers using glaze
|
// Parse a response body into a reflectable type T via Void::Json.
|
||||||
template<typename T>
|
template <typename T>
|
||||||
[[nodiscard]] Api::Result<T> getJson(std::string_view url,
|
[[nodiscard]] static Api::Result<T>
|
||||||
const std::vector<Api::HttpHeader>& headers = {}) {
|
parseJson(const std::string& body)
|
||||||
auto response = get(url, headers);
|
{
|
||||||
if (!response) {
|
auto parsed = Void::Json::parse(body);
|
||||||
return std::unexpected(response.error());
|
if (!parsed) {
|
||||||
}
|
return std::unexpected(Api::Error(
|
||||||
|
Api::ErrorCode::ParseError,
|
||||||
T result;
|
std::format("JSON parse error ({}:{}): {}",
|
||||||
auto ec = glz::read_json(result, response->bodyAsString());
|
parsed.error().line, parsed.error().col,
|
||||||
if (ec) {
|
parsed.error().message)));
|
||||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
}
|
||||||
std::format("JSON parse error: {}", glz::format_error(ec, response->bodyAsString()))));
|
auto value = Void::Json::from_json<T>(*parsed);
|
||||||
}
|
if (!value) {
|
||||||
return result;
|
return std::unexpected(Api::Error(
|
||||||
}
|
Api::ErrorCode::ParseError,
|
||||||
|
std::format("JSON decode error: field '{}': {}",
|
||||||
|
value.error().field, value.error().message)));
|
||||||
|
}
|
||||||
|
return std::move(*value);
|
||||||
|
}
|
||||||
|
|
||||||
template<typename T, typename Body>
|
public:
|
||||||
[[nodiscard]] Api::Result<T> postJson(std::string_view url, const Body& body,
|
|
||||||
const std::vector<Api::HttpHeader>& headers = {}) {
|
|
||||||
std::string jsonBody = glz::write_json(body);
|
|
||||||
auto response = post(url, jsonBody, headers);
|
|
||||||
if (!response) {
|
|
||||||
return std::unexpected(response.error());
|
|
||||||
}
|
|
||||||
|
|
||||||
T result;
|
|
||||||
auto ec = glz::read_json(result, response->bodyAsString());
|
|
||||||
if (ec) {
|
|
||||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
|
||||||
std::format("JSON parse error: {}", glz::format_error(ec, response->bodyAsString()))));
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Proxy configuration
|
// Proxy configuration
|
||||||
void setProxy(const std::optional<Api::ProxyConfig>& proxy);
|
void setProxy(const std::optional<Api::ProxyConfig>& proxy);
|
||||||
[[nodiscard]] std::optional<Api::ProxyConfig> getProxy() const;
|
[[nodiscard]] std::optional<Api::ProxyConfig> getProxy() const;
|
||||||
void clearProxy();
|
void clearProxy();
|
||||||
|
|
||||||
// Retry configuration
|
// Retry configuration
|
||||||
void setRetryConfig(const Api::RetryConfig& config);
|
void setRetryConfig(const Api::RetryConfig& config);
|
||||||
[[nodiscard]] Api::RetryConfig getRetryConfig() const;
|
[[nodiscard]] Api::RetryConfig getRetryConfig() const;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Request execution
|
|
||||||
[[nodiscard]] Api::Result<Api::HttpResponse> executeWithRetry(const Api::HttpRequest& req);
|
|
||||||
[[nodiscard]] Api::Result<Api::HttpResponse> executeRequest(const Api::HttpRequest& req);
|
|
||||||
|
|
||||||
// Proxy and direct execution methods
|
|
||||||
[[nodiscard]] Api::HttpResponse executeWithProxy(
|
|
||||||
boost::asio::io_context& ioc,
|
|
||||||
boost::asio::ssl::context& ctx,
|
|
||||||
const UrlComponents& urlComp,
|
|
||||||
const Api::HttpRequest& req,
|
|
||||||
const Api::ProxyConfig& proxy,
|
|
||||||
std::chrono::seconds timeout);
|
|
||||||
|
|
||||||
[[nodiscard]] Api::HttpResponse executeWithHttpProxy(
|
|
||||||
boost::asio::io_context& ioc,
|
|
||||||
boost::asio::ssl::context& ctx,
|
|
||||||
const UrlComponents& urlComp,
|
|
||||||
const Api::HttpRequest& req,
|
|
||||||
const Api::ProxyConfig& proxy,
|
|
||||||
std::chrono::seconds timeout);
|
|
||||||
|
|
||||||
[[nodiscard]] Api::HttpResponse executeWithSocks5Proxy(
|
|
||||||
boost::asio::io_context& ioc,
|
|
||||||
boost::asio::ssl::context& ctx,
|
|
||||||
const UrlComponents& urlComp,
|
|
||||||
const Api::HttpRequest& req,
|
|
||||||
const Api::ProxyConfig& proxy,
|
|
||||||
std::chrono::seconds timeout);
|
|
||||||
|
|
||||||
[[nodiscard]] Api::HttpResponse executeDirect(
|
|
||||||
boost::asio::io_context& ioc,
|
|
||||||
boost::asio::ssl::context& ctx,
|
|
||||||
const UrlComponents& urlComp,
|
|
||||||
const Api::HttpRequest& req,
|
|
||||||
std::chrono::seconds timeout);
|
|
||||||
|
|
||||||
// HTTP request methods
|
|
||||||
// Note: sendHttpsRequest is a template, implemented in header below
|
|
||||||
template<typename Stream>
|
|
||||||
[[nodiscard]] Api::HttpResponse sendHttpsRequest(
|
|
||||||
Stream& stream,
|
|
||||||
const UrlComponents& urlComp,
|
|
||||||
const Api::HttpRequest& req);
|
|
||||||
|
|
||||||
[[nodiscard]] Api::HttpResponse sendHttpRequest(
|
|
||||||
boost::asio::ip::tcp::socket& socket,
|
|
||||||
const UrlComponents& urlComp,
|
|
||||||
const Api::HttpRequest& req);
|
|
||||||
|
|
||||||
[[nodiscard]] Api::HttpResponse sendHttpRequestThroughProxy(
|
|
||||||
boost::asio::ip::tcp::socket& socket,
|
|
||||||
const UrlComponents& urlComp,
|
|
||||||
const Api::HttpRequest& req,
|
|
||||||
const Api::ProxyConfig& proxy);
|
|
||||||
|
|
||||||
// Request/Response building
|
|
||||||
[[nodiscard]] boost::beast::http::request<boost::beast::http::string_body> buildBeastRequest(
|
|
||||||
const UrlComponents& urlComp,
|
|
||||||
const Api::HttpRequest& req);
|
|
||||||
|
|
||||||
[[nodiscard]] Api::HttpResponse convertBeastResponse(
|
|
||||||
const boost::beast::http::response<boost::beast::http::dynamic_body>& beastResponse);
|
|
||||||
|
|
||||||
[[nodiscard]] std::vector<Api::HttpHeader> addDefaultHeaders(const std::vector<Api::HttpHeader>& headers);
|
|
||||||
|
|
||||||
std::optional<Api::ProxyConfig> proxy_;
|
// Request execution
|
||||||
Api::RetryConfig retryConfig_;
|
[[nodiscard]] Api::Result<Api::HttpResponse>
|
||||||
mutable std::mutex mutex_;
|
executeWithRetry(const Api::HttpRequest& req);
|
||||||
std::atomic<bool> initialized_{false};
|
[[nodiscard]] Api::Result<Api::HttpResponse>
|
||||||
std::atomic<uint32_t> requestId_{0};
|
executeRequest(const Api::HttpRequest& req);
|
||||||
|
|
||||||
// Thread pool for async operations
|
|
||||||
std::vector<std::jthread> threadPool_;
|
|
||||||
std::queue<std::packaged_task<Api::Result<Api::HttpResponse>()>> taskQueue_;
|
|
||||||
std::mutex taskMutex_;
|
|
||||||
std::condition_variable taskCv_;
|
|
||||||
std::atomic<bool> stopThreads_{false};
|
|
||||||
static constexpr size_t THREAD_POOL_SIZE = 4;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Template implementation for sendHttpsRequest
|
// Proxy and direct execution methods
|
||||||
template<typename Stream>
|
[[nodiscard]] Api::HttpResponse
|
||||||
Api::HttpResponse NetworkClient::sendHttpsRequest(
|
executeWithProxy(boost::asio::io_context& ioc,
|
||||||
Stream& stream,
|
boost::asio::ssl::context& ctx,
|
||||||
const UrlComponents& urlComp,
|
const UrlComponents& urlComp,
|
||||||
const Api::HttpRequest& req) {
|
const Api::HttpRequest& req,
|
||||||
namespace http = boost::beast::http;
|
const Api::ProxyConfig& proxy,
|
||||||
|
std::chrono::seconds timeout);
|
||||||
// Build request
|
|
||||||
http::request<http::string_body> request = buildBeastRequest(urlComp, req);
|
[[nodiscard]] Api::HttpResponse
|
||||||
|
executeWithHttpProxy(boost::asio::io_context& ioc,
|
||||||
// Send
|
boost::asio::ssl::context& ctx,
|
||||||
http::write(stream, request);
|
const UrlComponents& urlComp,
|
||||||
|
const Api::HttpRequest& req,
|
||||||
// Read response
|
const Api::ProxyConfig& proxy,
|
||||||
boost::beast::flat_buffer buffer;
|
std::chrono::seconds timeout);
|
||||||
http::response<http::dynamic_body> response;
|
|
||||||
http::read(stream, buffer, response);
|
[[nodiscard]] Api::HttpResponse
|
||||||
|
executeWithSocks5Proxy(boost::asio::io_context& ioc,
|
||||||
// Convert to Api::HttpResponse
|
boost::asio::ssl::context& ctx,
|
||||||
return convertBeastResponse(response);
|
const UrlComponents& urlComp,
|
||||||
}
|
const Api::HttpRequest& req,
|
||||||
|
const Api::ProxyConfig& proxy,
|
||||||
|
std::chrono::seconds timeout);
|
||||||
|
|
||||||
|
[[nodiscard]] Api::HttpResponse
|
||||||
|
executeDirect(boost::asio::io_context& ioc,
|
||||||
|
boost::asio::ssl::context& ctx,
|
||||||
|
const UrlComponents& urlComp,
|
||||||
|
const Api::HttpRequest& req,
|
||||||
|
std::chrono::seconds timeout);
|
||||||
|
|
||||||
|
// HTTP request methods
|
||||||
|
// Note: sendHttpsRequest is a template, implemented in header below
|
||||||
|
template <typename Stream>
|
||||||
|
[[nodiscard]] Api::HttpResponse
|
||||||
|
sendHttpsRequest(Stream& stream,
|
||||||
|
const UrlComponents& urlComp,
|
||||||
|
const Api::HttpRequest& req);
|
||||||
|
|
||||||
|
[[nodiscard]] Api::HttpResponse
|
||||||
|
sendHttpRequest(boost::asio::ip::tcp::socket& socket,
|
||||||
|
const UrlComponents& urlComp,
|
||||||
|
const Api::HttpRequest& req);
|
||||||
|
|
||||||
|
[[nodiscard]] Api::HttpResponse sendHttpRequestThroughProxy(
|
||||||
|
boost::asio::ip::tcp::socket& socket,
|
||||||
|
const UrlComponents& urlComp,
|
||||||
|
const Api::HttpRequest& req,
|
||||||
|
const Api::ProxyConfig& proxy);
|
||||||
|
|
||||||
|
// Request/Response building
|
||||||
|
[[nodiscard]] boost::beast::http::request<
|
||||||
|
boost::beast::http::string_body>
|
||||||
|
buildBeastRequest(const UrlComponents& urlComp,
|
||||||
|
const Api::HttpRequest& req);
|
||||||
|
|
||||||
|
[[nodiscard]] Api::HttpResponse convertBeastResponse(
|
||||||
|
const boost::beast::http::response<
|
||||||
|
boost::beast::http::dynamic_body>& beastResponse);
|
||||||
|
|
||||||
|
[[nodiscard]] std::vector<Api::HttpHeader>
|
||||||
|
addDefaultHeaders(const std::vector<Api::HttpHeader>& headers);
|
||||||
|
|
||||||
|
std::optional<Api::ProxyConfig> proxy_;
|
||||||
|
Api::RetryConfig retryConfig_;
|
||||||
|
mutable std::mutex mutex_;
|
||||||
|
std::atomic<bool> initialized_{false};
|
||||||
|
std::atomic<uint32_t> requestId_{0};
|
||||||
|
|
||||||
|
// Thread pool for async operations
|
||||||
|
std::vector<std::jthread> threadPool_;
|
||||||
|
std::queue<std::packaged_task<Api::Result<Api::HttpResponse>()>>
|
||||||
|
taskQueue_;
|
||||||
|
std::mutex taskMutex_;
|
||||||
|
std::condition_variable taskCv_;
|
||||||
|
std::atomic<bool> stopThreads_{false};
|
||||||
|
static constexpr size_t THREAD_POOL_SIZE = 4;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Template implementation for sendHttpsRequest
|
||||||
|
template <typename Stream>
|
||||||
|
Api::HttpResponse
|
||||||
|
NetworkClient::sendHttpsRequest(Stream& stream,
|
||||||
|
const UrlComponents& urlComp,
|
||||||
|
const Api::HttpRequest& req)
|
||||||
|
{
|
||||||
|
namespace http = boost::beast::http;
|
||||||
|
|
||||||
|
// Build request
|
||||||
|
http::request<http::string_body> request =
|
||||||
|
buildBeastRequest(urlComp, req);
|
||||||
|
|
||||||
|
// Send
|
||||||
|
http::write(stream, request);
|
||||||
|
|
||||||
|
// Read response
|
||||||
|
boost::beast::flat_buffer buffer;
|
||||||
|
http::response<http::dynamic_body> response;
|
||||||
|
http::read(stream, buffer, response);
|
||||||
|
|
||||||
|
// Convert to Api::HttpResponse
|
||||||
|
return convertBeastResponse(response);
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -1,81 +1,98 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <echoion/api.hpp>
|
#include <PluginTypes.hpp>
|
||||||
|
#include <RpcTypes.hpp>
|
||||||
|
#include <TrackTypes.hpp>
|
||||||
|
#include <Types.hpp>
|
||||||
#include <boost/asio.hpp>
|
#include <boost/asio.hpp>
|
||||||
#include <boost/beast.hpp>
|
#include <boost/beast.hpp>
|
||||||
#include <boost/beast/websocket.hpp>
|
#include <boost/beast/websocket.hpp>
|
||||||
#include <thread>
|
#include <functional>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <set>
|
#include <set>
|
||||||
#include <functional>
|
#include <thread>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
namespace asio = boost::asio;
|
namespace asio = boost::asio;
|
||||||
namespace beast = boost::beast;
|
namespace beast = boost::beast;
|
||||||
namespace websocket = beast::websocket;
|
namespace websocket = beast::websocket;
|
||||||
|
|
||||||
class RpcServer : public std::enable_shared_from_this<RpcServer> {
|
class RpcServer : public std::enable_shared_from_this<RpcServer>
|
||||||
public:
|
{
|
||||||
using CommandHandler = std::function<Api::Result<std::string>(const std::string& params, uint64_t clientId)>;
|
public:
|
||||||
|
|
||||||
RpcServer();
|
using CommandHandler = std::function<Api::Result<std::string>(
|
||||||
~RpcServer();
|
const std::string& params, uint64_t clientId)>;
|
||||||
|
|
||||||
// Initialize and start the server
|
RpcServer();
|
||||||
Api::Result<void> start(uint16_t port = 8765);
|
~RpcServer();
|
||||||
void stop();
|
|
||||||
[[nodiscard]] bool isRunning() const { return running_; }
|
|
||||||
[[nodiscard]] uint16_t getPort() const { return port_; }
|
|
||||||
|
|
||||||
// Register command handlers
|
// Initialize and start the server
|
||||||
void registerHandler(const std::string& method, CommandHandler handler);
|
Api::Result<void> start(uint16_t port = 8765);
|
||||||
void unregisterHandler(const std::string& method);
|
void stop();
|
||||||
|
[[nodiscard]] bool isRunning() const { return running_; }
|
||||||
|
[[nodiscard]] uint16_t getPort() const { return port_; }
|
||||||
|
|
||||||
// Authentication
|
// Register command handlers
|
||||||
void setAuthToken(const std::string& token);
|
void registerHandler(const std::string& method,
|
||||||
[[nodiscard]] bool authenticate(const std::string& token);
|
CommandHandler handler);
|
||||||
void addAuthenticatedClient(uint64_t clientId);
|
void unregisterHandler(const std::string& method);
|
||||||
void removeAuthenticatedClient(uint64_t clientId);
|
|
||||||
[[nodiscard]] bool isClientAuthenticated(uint64_t clientId);
|
|
||||||
|
|
||||||
// Broadcast events to all connected clients
|
// Authentication
|
||||||
void broadcastEvent(const std::string& event, const std::string& data);
|
void setAuthToken(const std::string& token);
|
||||||
|
[[nodiscard]] bool authenticate(const std::string& token);
|
||||||
|
void addAuthenticatedClient(uint64_t clientId);
|
||||||
|
void removeAuthenticatedClient(uint64_t clientId);
|
||||||
|
[[nodiscard]] bool isClientAuthenticated(uint64_t clientId);
|
||||||
|
|
||||||
// Send event to specific client
|
// Broadcast events to all connected clients
|
||||||
void sendEvent(uint64_t clientId, const std::string& event, const std::string& data);
|
void broadcastEvent(const std::string& event,
|
||||||
|
const std::string& data);
|
||||||
|
|
||||||
private:
|
// Send event to specific client
|
||||||
void acceptLoop();
|
void sendEvent(uint64_t clientId, const std::string& event,
|
||||||
void handleClient(std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws);
|
const std::string& data);
|
||||||
void processMessage(uint64_t clientId, const std::string& message);
|
|
||||||
void sendResponse(uint64_t clientId, const Api::RpcResponse& response);
|
|
||||||
void sendNotification(uint64_t clientId, const Api::RpcNotification& notification);
|
|
||||||
|
|
||||||
asio::io_context ioContext_;
|
private:
|
||||||
std::optional<asio::ip::tcp::acceptor> acceptor_;
|
|
||||||
std::thread serverThread_;
|
|
||||||
std::atomic<bool> running_{false};
|
|
||||||
uint16_t port_ = 8765;
|
|
||||||
|
|
||||||
// Connected clients
|
void acceptLoop();
|
||||||
std::unordered_map<uint64_t, std::shared_ptr<websocket::stream<asio::ip::tcp::socket>>> clients_;
|
void handleClient(
|
||||||
std::mutex clientsMutex_;
|
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws);
|
||||||
std::atomic<uint64_t> nextClientId_{1};
|
void processMessage(uint64_t clientId, const std::string& message);
|
||||||
|
void sendResponse(uint64_t clientId,
|
||||||
// Client threads (for proper cleanup)
|
const Api::RpcResponse& response);
|
||||||
std::vector<std::thread> clientThreads_;
|
void sendNotification(uint64_t clientId,
|
||||||
std::mutex clientThreadsMutex_;
|
const Api::RpcNotification& notification);
|
||||||
|
|
||||||
// Authenticated clients
|
asio::io_context ioContext_;
|
||||||
std::set<uint64_t> authenticatedClients_;
|
std::optional<asio::ip::tcp::acceptor> acceptor_;
|
||||||
std::mutex authMutex_;
|
std::thread serverThread_;
|
||||||
std::string authToken_;
|
std::atomic<bool> running_{false};
|
||||||
|
uint16_t port_ = 8765;
|
||||||
|
|
||||||
// Command handlers
|
// Connected clients
|
||||||
std::unordered_map<std::string, CommandHandler> handlers_;
|
std::unordered_map<
|
||||||
std::mutex handlersMutex_;
|
uint64_t,
|
||||||
};
|
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>>>
|
||||||
|
clients_;
|
||||||
|
std::mutex clientsMutex_;
|
||||||
|
std::atomic<uint64_t> nextClientId_{1};
|
||||||
|
|
||||||
|
// Client threads (for proper cleanup)
|
||||||
|
std::vector<std::thread> clientThreads_;
|
||||||
|
std::mutex clientThreadsMutex_;
|
||||||
|
|
||||||
|
// Authenticated clients
|
||||||
|
std::set<uint64_t> authenticatedClients_;
|
||||||
|
std::mutex authMutex_;
|
||||||
|
std::string authToken_;
|
||||||
|
|
||||||
|
// Command handlers
|
||||||
|
std::unordered_map<std::string, CommandHandler> handlers_;
|
||||||
|
std::mutex handlersMutex_;
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <chrono>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <unordered_map>
|
||||||
|
|
||||||
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
|
// Session management for RPC clients
|
||||||
|
// Supports 100+ concurrent authenticated sessions
|
||||||
|
class SessionManager
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
struct Session {
|
||||||
|
uint64_t clientId;
|
||||||
|
std::string authToken;
|
||||||
|
std::chrono::steady_clock::time_point lastActivity;
|
||||||
|
std::chrono::steady_clock::time_point createdAt;
|
||||||
|
bool isAuthenticated;
|
||||||
|
|
||||||
|
// Optional: store client-specific state
|
||||||
|
struct ClientState {
|
||||||
|
std::optional<std::string> currentPlaylist;
|
||||||
|
float preferredVolume = -1.0f; // -1 = use default
|
||||||
|
// Add more client preferences here
|
||||||
|
};
|
||||||
|
std::optional<ClientState> clientState;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Config {
|
||||||
|
size_t maxSessions = 150; // 100 users + buffer
|
||||||
|
std::chrono::seconds sessionTimeout{3600}; // 1 hour timeout
|
||||||
|
std::chrono::seconds cleanupInterval{
|
||||||
|
300}; // Cleanup every 5 min
|
||||||
|
};
|
||||||
|
|
||||||
|
SessionManager();
|
||||||
|
explicit SessionManager(const Config& config);
|
||||||
|
|
||||||
|
// Initialize session manager
|
||||||
|
bool initialize();
|
||||||
|
void shutdown();
|
||||||
|
|
||||||
|
// Create new session
|
||||||
|
std::string createSession(uint64_t clientId);
|
||||||
|
|
||||||
|
// Authenticate session
|
||||||
|
bool authenticateSession(const std::string& token);
|
||||||
|
|
||||||
|
// Validate and update session
|
||||||
|
bool validateSession(const std::string& token);
|
||||||
|
void updateActivity(const std::string& token);
|
||||||
|
|
||||||
|
// Get session info
|
||||||
|
std::optional<Session> getSession(const std::string& token) const;
|
||||||
|
|
||||||
|
// End session
|
||||||
|
void endSession(const std::string& token);
|
||||||
|
void endSessionByClientId(uint64_t clientId);
|
||||||
|
|
||||||
|
// Get all active sessions
|
||||||
|
std::vector<Session> getAllSessions() const;
|
||||||
|
|
||||||
|
// Get session count
|
||||||
|
size_t getSessionCount() const;
|
||||||
|
|
||||||
|
// Cleanup expired sessions (call periodically)
|
||||||
|
size_t cleanupExpiredSessions();
|
||||||
|
|
||||||
|
// Check if at capacity
|
||||||
|
bool isAtCapacity() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
std::string generateToken();
|
||||||
|
|
||||||
|
Config config_;
|
||||||
|
std::unordered_map<std::string, Session> sessions_;
|
||||||
|
mutable std::mutex mutex_;
|
||||||
|
std::atomic<bool> running_{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Echoion::Core
|
||||||
@@ -1,129 +1,138 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <optional>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include <optional>
|
|
||||||
#include <memory>
|
|
||||||
#include <mutex>
|
|
||||||
#include <filesystem>
|
|
||||||
|
|
||||||
#include <quickjs.h>
|
#include <quickjs.h>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Signature cipher for YouTube stream URLs
|
* Signature cipher for YouTube stream URLs
|
||||||
* Uses QuickJS (when available) to execute the JavaScript decipher functions from player JS
|
* Uses QuickJS (when available) to execute the JavaScript decipher
|
||||||
*
|
* functions from player JS
|
||||||
* Based on yt-dlp's signature extraction logic
|
*
|
||||||
*/
|
* Based on yt-dlp's signature extraction logic
|
||||||
class SignatureCipher {
|
*/
|
||||||
public:
|
class SignatureCipher
|
||||||
SignatureCipher();
|
{
|
||||||
~SignatureCipher();
|
public:
|
||||||
|
|
||||||
// Disable copy, enable move
|
SignatureCipher();
|
||||||
SignatureCipher(const SignatureCipher&) = delete;
|
~SignatureCipher();
|
||||||
SignatureCipher& operator=(const SignatureCipher&) = delete;
|
|
||||||
SignatureCipher(SignatureCipher&&) noexcept;
|
|
||||||
SignatureCipher& operator=(SignatureCipher&&) noexcept;
|
|
||||||
|
|
||||||
/**
|
// Disable copy, enable move
|
||||||
* Initialize the QuickJS solver with core libraries
|
SignatureCipher(const SignatureCipher&) = delete;
|
||||||
* Must be called before using the cipher
|
SignatureCipher& operator=(const SignatureCipher&) = delete;
|
||||||
*/
|
SignatureCipher(SignatureCipher&&) noexcept;
|
||||||
void initialize();
|
SignatureCipher& operator=(SignatureCipher&&) noexcept;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the player JS code and extract decipher functions
|
* Initialize the QuickJS solver with core libraries
|
||||||
* @param playerJsCode The raw player JavaScript code from YouTube
|
* Must be called before using the cipher
|
||||||
* @return true if extraction succeeded
|
*/
|
||||||
*/
|
void initialize();
|
||||||
bool setPlayerJs(std::string_view playerJsCode);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if the cipher is ready (has valid decipher function)
|
* Set the player JS code and extract decipher functions
|
||||||
*/
|
* @param playerJsCode The raw player JavaScript code from YouTube
|
||||||
[[nodiscard]] bool isReady() const;
|
* @return true if extraction succeeded
|
||||||
|
*/
|
||||||
|
bool setPlayerJs(std::string_view playerJsCode);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decipher a signature cipher string
|
* Check if the cipher is ready (has valid decipher function)
|
||||||
* Format: s=ENCODED_SIG&sp=SIG_PARAM&url=ENCODED_URL
|
*/
|
||||||
* @param signatureCipher The signature cipher string
|
[[nodiscard]] bool isReady() const;
|
||||||
* @return The full deciphered URL or empty string on failure
|
|
||||||
*/
|
|
||||||
[[nodiscard]] std::string decipher(std::string_view signatureCipher);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Solve a challenge (signature or n-param) using the preprocessed player
|
* Decipher a signature cipher string
|
||||||
* @param challenge The challenge string to solve
|
* Format: s=ENCODED_SIG&sp=SIG_PARAM&url=ENCODED_URL
|
||||||
* @param type "sig" for signature, "n" for n-parameter
|
* @param signatureCipher The signature cipher string
|
||||||
* @return The solved challenge or empty string on failure
|
* @return The full deciphered URL or empty string on failure
|
||||||
*/
|
*/
|
||||||
[[nodiscard]] std::string solveChallenge(const std::string& challenge, const std::string& type);
|
[[nodiscard]] std::string
|
||||||
|
decipher(std::string_view signatureCipher);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decipher the n-parameter for throttling
|
* Solve a challenge (signature or n-param) using the preprocessed
|
||||||
* @param nParam The encoded n parameter
|
* player
|
||||||
* @return The deciphered n parameter
|
* @param challenge The challenge string to solve
|
||||||
*/
|
* @param type "sig" for signature, "n" for n-parameter
|
||||||
[[nodiscard]] std::string decipherNParam(std::string_view nParam);
|
* @return The solved challenge or empty string on failure
|
||||||
|
*/
|
||||||
|
[[nodiscard]] std::string
|
||||||
|
solveChallenge(const std::string& challenge,
|
||||||
|
const std::string& type);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clear the cipher state
|
* Decipher the n-parameter for throttling
|
||||||
*/
|
* @param nParam The encoded n parameter
|
||||||
void clear();
|
* @return The deciphered n parameter
|
||||||
|
*/
|
||||||
|
[[nodiscard]] std::string decipherNParam(std::string_view nParam);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if cipher has been initialized
|
* Clear the cipher state
|
||||||
*/
|
*/
|
||||||
[[nodiscard]] bool isInitialized() const;
|
void clear();
|
||||||
|
|
||||||
private:
|
/**
|
||||||
/**
|
* Check if cipher has been initialized
|
||||||
* Initialize QuickJS runtime and context with solver libraries
|
*/
|
||||||
*/
|
[[nodiscard]] bool isInitialized() const;
|
||||||
void initSolver();
|
|
||||||
|
|
||||||
/**
|
private:
|
||||||
* Download solver libraries from remote URL
|
|
||||||
* @param url The URL to download from
|
|
||||||
* @return The downloaded JS code or empty string on failure
|
|
||||||
*/
|
|
||||||
[[nodiscard]] std::optional<std::string> downloadSolverLibrary(
|
|
||||||
std::string_view url);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get cache directory for storing solver libraries
|
* Initialize QuickJS runtime and context with solver libraries
|
||||||
*/
|
*/
|
||||||
[[nodiscard]] std::filesystem::path getCacheDir();
|
void initSolver();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Execute JavaScript code in QuickJS and return result
|
* Download solver libraries from remote URL
|
||||||
*/
|
* @param url The URL to download from
|
||||||
[[nodiscard]] std::optional<std::string> executeJS(
|
* @return The downloaded JS code or empty string on failure
|
||||||
std::string_view code,
|
*/
|
||||||
std::string_view filename = "<script>");
|
[[nodiscard]] std::optional<std::string>
|
||||||
|
downloadSolverLibrary(std::string_view url);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cleanup QuickJS resources
|
* Get cache directory for storing solver libraries
|
||||||
*/
|
*/
|
||||||
void cleanupQuickJS();
|
[[nodiscard]] std::filesystem::path getCacheDir();
|
||||||
|
|
||||||
JSRuntime* runtime_ = nullptr;
|
/**
|
||||||
JSContext* context_ = nullptr;
|
* Execute JavaScript code in QuickJS and return result
|
||||||
|
*/
|
||||||
|
[[nodiscard]] std::optional<std::string>
|
||||||
|
executeJS(std::string_view code,
|
||||||
|
std::string_view filename = "<script>");
|
||||||
|
|
||||||
// Player JS code and extracted functions
|
/**
|
||||||
std::string playerJsCode_;
|
* Cleanup QuickJS resources
|
||||||
std::string preprocessedPlayer_;
|
*/
|
||||||
|
void cleanupQuickJS();
|
||||||
|
|
||||||
// State
|
JSRuntime* runtime_ = nullptr;
|
||||||
bool initialized_ = false;
|
JSContext* context_ = nullptr;
|
||||||
bool solverInitialized_ = false;
|
|
||||||
bool hasPlayerJs_ = false;
|
|
||||||
|
|
||||||
mutable std::mutex mutex_;
|
// Player JS code and extracted functions
|
||||||
};
|
std::string playerJsCode_;
|
||||||
|
std::string preprocessedPlayer_;
|
||||||
|
|
||||||
|
// State
|
||||||
|
bool initialized_ = false;
|
||||||
|
bool solverInitialized_ = false;
|
||||||
|
bool hasPlayerJs_ = false;
|
||||||
|
|
||||||
|
mutable std::mutex mutex_;
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -1,64 +1,73 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <echoion/api.hpp>
|
#include "Database.hpp"
|
||||||
|
#include <TrackTypes.hpp>
|
||||||
|
#include <Types.hpp>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
#include <set>
|
#include <set>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <mutex>
|
|
||||||
#include <memory>
|
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Manages user subscriptions to the bot's audio output
|
* Manages user subscriptions to the bot's audio output
|
||||||
* Subscriptions are persisted to database and survive client reloads
|
* Subscriptions are persisted to database and survive client reloads
|
||||||
* Uses unique client UID instead of session-specific client ID
|
* Uses unique client UID instead of session-specific client ID
|
||||||
*/
|
*/
|
||||||
class SubscriptionManager {
|
class SubscriptionManager
|
||||||
public:
|
{
|
||||||
struct Subscriber {
|
public:
|
||||||
std::string uid;
|
|
||||||
std::string nickname;
|
|
||||||
};
|
|
||||||
|
|
||||||
SubscriptionManager();
|
struct Subscriber {
|
||||||
~SubscriptionManager();
|
std::string uid;
|
||||||
|
std::string nickname;
|
||||||
|
};
|
||||||
|
|
||||||
// Initialize and load subscriptions from database
|
SubscriptionManager();
|
||||||
Api::Result<void> initialize(std::shared_ptr<Api::Database> database);
|
~SubscriptionManager();
|
||||||
void shutdown();
|
|
||||||
|
|
||||||
// Subscription management (by UID)
|
// Initialize and load subscriptions from database
|
||||||
bool subscribe(const std::string& uid, const std::string& nickname);
|
Api::Result<void>
|
||||||
bool unsubscribe(const std::string& uid);
|
initialize(std::shared_ptr<Api::Database> database);
|
||||||
bool isSubscribed(const std::string& uid) const;
|
void shutdown();
|
||||||
|
|
||||||
// Get all subscribed UIDs
|
|
||||||
std::vector<std::string> getSubscribedUids() const;
|
|
||||||
|
|
||||||
// Get all subscribers with info
|
|
||||||
std::vector<Subscriber> getSubscribers() const;
|
|
||||||
|
|
||||||
// Get subscriber nickname
|
|
||||||
std::optional<std::string> getSubscriberNickname(const std::string& uid) const;
|
|
||||||
|
|
||||||
// Update nickname for subscriber
|
|
||||||
bool updateNickname(const std::string& uid, const std::string& nickname);
|
|
||||||
|
|
||||||
// Check if anyone is subscribed
|
|
||||||
bool hasSubscribers() const;
|
|
||||||
|
|
||||||
// Get subscriber count
|
|
||||||
size_t getSubscriberCount() const;
|
|
||||||
|
|
||||||
// Clear all subscriptions
|
|
||||||
bool clearAll();
|
|
||||||
|
|
||||||
private:
|
// Subscription management (by UID)
|
||||||
std::set<std::string> subscribedUids_;
|
bool subscribe(const std::string& uid, const std::string& nickname);
|
||||||
mutable std::mutex mutex_;
|
bool unsubscribe(const std::string& uid);
|
||||||
std::shared_ptr<Api::Database> database_;
|
bool isSubscribed(const std::string& uid) const;
|
||||||
bool initialized_ = false;
|
|
||||||
};
|
// Get all subscribed UIDs
|
||||||
|
std::vector<std::string> getSubscribedUids() const;
|
||||||
|
|
||||||
|
// Get all subscribers with info
|
||||||
|
std::vector<Subscriber> getSubscribers() const;
|
||||||
|
|
||||||
|
// Get subscriber nickname
|
||||||
|
std::optional<std::string>
|
||||||
|
getSubscriberNickname(const std::string& uid) const;
|
||||||
|
|
||||||
|
// Update nickname for subscriber
|
||||||
|
bool updateNickname(const std::string& uid,
|
||||||
|
const std::string& nickname);
|
||||||
|
|
||||||
|
// Check if anyone is subscribed
|
||||||
|
bool hasSubscribers() const;
|
||||||
|
|
||||||
|
// Get subscriber count
|
||||||
|
size_t getSubscriberCount() const;
|
||||||
|
|
||||||
|
// Clear all subscriptions
|
||||||
|
bool clearAll();
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
std::set<std::string> subscribedUids_;
|
||||||
|
mutable std::mutex mutex_;
|
||||||
|
std::shared_ptr<Api::Database> database_;
|
||||||
|
bool initialized_ = false;
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -1,50 +1,58 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <echoion/api.hpp>
|
|
||||||
#include "NetworkClient.hpp"
|
#include "NetworkClient.hpp"
|
||||||
#include <string>
|
#include <NetworkTypes.hpp>
|
||||||
#include <optional>
|
#include <Types.hpp>
|
||||||
#include <mutex>
|
|
||||||
#include <unordered_map>
|
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
|
#include <mutex>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <unordered_map>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
// URL shortener service for faumaray.ru
|
// URL shortener service for faumaray.ru
|
||||||
class UrlShortener {
|
class UrlShortener
|
||||||
public:
|
{
|
||||||
explicit UrlShortener(std::shared_ptr<NetworkClient> networkClient);
|
public:
|
||||||
~UrlShortener();
|
|
||||||
|
|
||||||
// Shorten a YouTube URL via faumaray.ru
|
explicit UrlShortener(std::shared_ptr<NetworkClient> networkClient);
|
||||||
// Returns shortened URL in format: https://faumaray.ru/xxxxx
|
~UrlShortener();
|
||||||
[[nodiscard]] Api::Result<std::string> shortenYouTubeUrl(std::string_view videoId);
|
|
||||||
|
|
||||||
// Shorten any URL via faumaray.ru
|
|
||||||
[[nodiscard]] Api::Result<std::string> shortenUrl(std::string_view originalUrl);
|
|
||||||
|
|
||||||
// Get cached shortened URL if available
|
|
||||||
[[nodiscard]] std::optional<std::string> getCachedUrl(std::string_view originalUrl) const;
|
|
||||||
|
|
||||||
// Clear the URL cache
|
|
||||||
void clearCache();
|
|
||||||
|
|
||||||
// Set cache TTL (default: 24 hours)
|
|
||||||
void setCacheTtl(std::chrono::hours ttl);
|
|
||||||
|
|
||||||
private:
|
// Shorten a YouTube URL via faumaray.ru
|
||||||
struct CacheEntry {
|
// Returns shortened URL in format: https://faumaray.ru/xxxxx
|
||||||
std::string shortenedUrl;
|
[[nodiscard]] Api::Result<std::string>
|
||||||
std::chrono::system_clock::time_point timestamp;
|
shortenYouTubeUrl(std::string_view videoId);
|
||||||
};
|
|
||||||
|
// Shorten any URL via faumaray.ru
|
||||||
std::shared_ptr<NetworkClient> networkClient_;
|
[[nodiscard]] Api::Result<std::string>
|
||||||
mutable std::mutex cacheMutex_;
|
shortenUrl(std::string_view originalUrl);
|
||||||
std::unordered_map<std::string, CacheEntry> cache_;
|
|
||||||
std::chrono::hours cacheTtl_{24};
|
// Get cached shortened URL if available
|
||||||
|
[[nodiscard]] std::optional<std::string>
|
||||||
// Clean expired entries from cache
|
getCachedUrl(std::string_view originalUrl) const;
|
||||||
void cleanExpiredCache();
|
|
||||||
};
|
// Clear the URL cache
|
||||||
|
void clearCache();
|
||||||
|
|
||||||
|
// Set cache TTL (default: 24 hours)
|
||||||
|
void setCacheTtl(std::chrono::hours ttl);
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct CacheEntry {
|
||||||
|
std::string shortenedUrl;
|
||||||
|
std::chrono::system_clock::time_point timestamp;
|
||||||
|
};
|
||||||
|
|
||||||
|
std::shared_ptr<NetworkClient> networkClient_;
|
||||||
|
mutable std::mutex cacheMutex_;
|
||||||
|
std::unordered_map<std::string, CacheEntry> cache_;
|
||||||
|
std::chrono::hours cacheTtl_{24};
|
||||||
|
|
||||||
|
// Clean expired entries from cache
|
||||||
|
void cleanExpiredCache();
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -3,8 +3,11 @@
|
|||||||
#include "NetworkClient.hpp"
|
#include "NetworkClient.hpp"
|
||||||
#include "UrlShortener.hpp"
|
#include "UrlShortener.hpp"
|
||||||
#include "YtDlpManager.hpp"
|
#include "YtDlpManager.hpp"
|
||||||
|
#include <NetworkTypes.hpp>
|
||||||
|
#include <TrackTypes.hpp>
|
||||||
|
#include <Types.hpp>
|
||||||
|
#include <YouTubeTypes.hpp>
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <echoion/api.hpp>
|
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <future>
|
#include <future>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
@@ -15,142 +18,159 @@
|
|||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class YouTubeClient {
|
class YouTubeClient
|
||||||
public:
|
{
|
||||||
explicit YouTubeClient(std::shared_ptr<NetworkClient> networkClient);
|
public:
|
||||||
~YouTubeClient();
|
|
||||||
|
|
||||||
// Initialize the client - downloads yt-dlp if needed
|
explicit YouTubeClient(
|
||||||
Api::Result<void> initialize();
|
std::shared_ptr<NetworkClient> networkClient);
|
||||||
void shutdown();
|
~YouTubeClient();
|
||||||
|
|
||||||
// Check if yt-dlp is available
|
// Initialize the client - downloads yt-dlp if needed
|
||||||
[[nodiscard]] bool isAvailable() const;
|
Api::Result<void> initialize();
|
||||||
|
void shutdown();
|
||||||
// Get yt-dlp version
|
|
||||||
[[nodiscard]] std::string getYtDlpVersion() const;
|
|
||||||
|
|
||||||
// Force update yt-dlp
|
|
||||||
Api::Result<void> updateYtDlp();
|
|
||||||
|
|
||||||
// Search for videos using YouTube Data API v3 (or yt-dlp as fallback)
|
// Check if yt-dlp is available
|
||||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
[[nodiscard]] bool isAvailable() const;
|
||||||
search(std::string_view query,
|
|
||||||
std::optional<std::string> pageToken = std::nullopt);
|
|
||||||
|
|
||||||
// Get video details including stream URLs using yt-dlp
|
// Get yt-dlp version
|
||||||
[[nodiscard]] Api::Result<Api::TrackInfo> getVideoInfo(std::string_view videoId);
|
[[nodiscard]] std::string getYtDlpVersion() const;
|
||||||
|
|
||||||
// Get video details asynchronously
|
// Force update yt-dlp
|
||||||
[[nodiscard]] std::future<Api::Result<Api::TrackInfo>>
|
Api::Result<void> updateYtDlp();
|
||||||
getVideoInfoAsync(std::string_view videoId);
|
|
||||||
|
|
||||||
// Get multiple video details concurrently
|
// Search for videos using YouTube Data API v3 (or yt-dlp as
|
||||||
[[nodiscard]] std::vector<Api::Result<Api::TrackInfo>>
|
// fallback)
|
||||||
getVideoInfoBatch(const std::vector<std::string>& videoIds);
|
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||||
|
search(std::string_view query,
|
||||||
|
std::optional<std::string> pageToken = std::nullopt);
|
||||||
|
|
||||||
// Get playlist videos - uses YouTube API v2 if key available, otherwise
|
// Get video details including stream URLs using yt-dlp
|
||||||
// yt-dlp Then resolves each track individually via yt-dlp for full metadata
|
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||||
[[nodiscard]] Api::Result<Api::PlaylistInfo>
|
getVideoInfo(std::string_view videoId);
|
||||||
getPlaylist(std::string_view playlistId);
|
|
||||||
|
|
||||||
// Get playlist videos asynchronously with concurrent track resolution
|
// Get video details asynchronously
|
||||||
[[nodiscard]] std::future<Api::Result<Api::PlaylistInfo>>
|
[[nodiscard]] std::future<Api::Result<Api::TrackInfo>>
|
||||||
getPlaylistAsync(std::string_view playlistId);
|
getVideoInfoAsync(std::string_view videoId);
|
||||||
|
|
||||||
// Stream playlist tracks with callback - calls trackCallback for each track
|
// Get multiple video details concurrently
|
||||||
// as it is resolved, enabling immediate playback of first track
|
[[nodiscard]] std::vector<Api::Result<Api::TrackInfo>>
|
||||||
void getPlaylistStreaming(std::string_view playlistId,
|
getVideoInfoBatch(const std::vector<std::string>& videoIds);
|
||||||
std::function<void(Api::TrackInfo&&)> trackCallback,
|
|
||||||
std::function<void(size_t totalTracks)> onPlaylistInfo = nullptr,
|
|
||||||
std::function<void()> onComplete = nullptr);
|
|
||||||
|
|
||||||
// Extract video ID from various YouTube URL formats (handles redirects for
|
// Get playlist videos - uses YouTube API v2 if key available,
|
||||||
// short URLs)
|
// otherwise yt-dlp Then resolves each track individually via yt-dlp
|
||||||
[[nodiscard]] std::optional<std::string>
|
// for full metadata
|
||||||
extractVideoId(std::string_view url);
|
[[nodiscard]] Api::Result<Api::PlaylistInfo>
|
||||||
[[nodiscard]] static std::optional<std::string>
|
getPlaylist(std::string_view playlistId);
|
||||||
extractPlaylistId(std::string_view url);
|
|
||||||
|
|
||||||
// Check if URL is a YouTube URL
|
// Get playlist videos asynchronously with concurrent track
|
||||||
[[nodiscard]] static bool isYouTubeUrl(std::string_view url);
|
// resolution
|
||||||
|
[[nodiscard]] std::future<Api::Result<Api::PlaylistInfo>>
|
||||||
|
getPlaylistAsync(std::string_view playlistId);
|
||||||
|
|
||||||
// Get stream URL for a video (used by MusicManager)
|
// Stream playlist tracks with callback - calls trackCallback for
|
||||||
[[nodiscard]] Api::Result<std::string> getStreamUrl(std::string_view videoId);
|
// each track as it is resolved, enabling immediate playback of
|
||||||
|
// first track
|
||||||
// Get best audio stream URL using yt-dlp
|
void getPlaylistStreaming(
|
||||||
[[nodiscard]] Api::Result<std::string> getAudioStreamUrl(std::string_view videoId);
|
std::string_view playlistId,
|
||||||
|
std::function<void(Api::TrackInfo&&)>
|
||||||
// Configure cookie options for yt-dlp
|
trackCallback,
|
||||||
void setCookiesPath(const std::string& path);
|
std::function<void(size_t totalTracks)> onPlaylistInfo =
|
||||||
void setCookiesFromBrowser(const std::string& browser);
|
nullptr,
|
||||||
|
std::function<void()> onComplete = nullptr);
|
||||||
|
|
||||||
// Configure proxy for yt-dlp
|
// Extract video ID from various YouTube URL formats (handles
|
||||||
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
|
// redirects for short URLs)
|
||||||
[[nodiscard]] std::optional<Api::ProxyConfig> getProxyConfig() const;
|
[[nodiscard]] std::optional<std::string>
|
||||||
|
extractVideoId(std::string_view url);
|
||||||
|
[[nodiscard]] static std::optional<std::string>
|
||||||
|
extractPlaylistId(std::string_view url);
|
||||||
|
|
||||||
// Set YouTube API key for enhanced playlist resolution (optional)
|
// Check if URL is a YouTube URL
|
||||||
void setApiKey(const std::string& apiKey);
|
[[nodiscard]] static bool isYouTubeUrl(std::string_view url);
|
||||||
[[nodiscard]] bool hasApiKey() const;
|
|
||||||
|
|
||||||
// Configure concurrent resolution settings
|
// Get stream URL for a video (used by MusicManager)
|
||||||
void setMaxConcurrentResolutions(size_t max);
|
[[nodiscard]] Api::Result<std::string>
|
||||||
[[nodiscard]] size_t getMaxConcurrentResolutions() const;
|
getStreamUrl(std::string_view videoId);
|
||||||
|
|
||||||
// Enable/disable URL shortening for track links
|
// Get best audio stream URL using yt-dlp
|
||||||
void setUrlShorteningEnabled(bool enabled);
|
[[nodiscard]] Api::Result<std::string>
|
||||||
[[nodiscard]] bool isUrlShorteningEnabled() const;
|
getAudioStreamUrl(std::string_view videoId);
|
||||||
|
|
||||||
private:
|
// Configure cookie options for yt-dlp
|
||||||
|
void setCookiesPath(const std::string& path);
|
||||||
|
void setCookiesFromBrowser(const std::string& browser);
|
||||||
|
|
||||||
// Internal search implementations
|
// Configure proxy for yt-dlp
|
||||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
|
||||||
searchWithApi(std::string_view query,
|
[[nodiscard]] std::optional<Api::ProxyConfig>
|
||||||
const std::optional<std::string>& pageToken);
|
getProxyConfig() const;
|
||||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
|
||||||
searchWithYtDlp(std::string_view query,
|
|
||||||
const std::optional<std::string>& pageToken);
|
|
||||||
|
|
||||||
// Fetch video durations for search results (batch API call)
|
// Set YouTube API key for enhanced playlist resolution (optional)
|
||||||
void fetchVideoDurations(std::vector<Api::TrackInfo>& tracks,
|
void setApiKey(const std::string& apiKey);
|
||||||
const std::vector<std::string>& videoIds);
|
[[nodiscard]] bool hasApiKey() const;
|
||||||
|
|
||||||
// Parse ISO 8601 duration string
|
// Configure concurrent resolution settings
|
||||||
[[nodiscard]] static std::chrono::seconds
|
void setMaxConcurrentResolutions(size_t max);
|
||||||
parseIso8601Duration(const std::string& duration);
|
[[nodiscard]] size_t getMaxConcurrentResolutions() const;
|
||||||
|
|
||||||
// URL encode/decode helpers
|
// Enable/disable URL shortening for track links
|
||||||
[[nodiscard]] static std::string urlEncode(std::string_view value);
|
void setUrlShorteningEnabled(bool enabled);
|
||||||
[[nodiscard]] static std::string decodeHtmlEntities(std::string_view value);
|
[[nodiscard]] bool isUrlShorteningEnabled() const;
|
||||||
|
|
||||||
// Internal methods for playlist resolution
|
private:
|
||||||
[[nodiscard]] Api::Result<std::vector<Api::YouTubePlaylistItem>>
|
|
||||||
fetchPlaylistItems(std::string_view playlistId);
|
|
||||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
|
||||||
resolveTrackWithYtDlp(const Api::YouTubePlaylistItem& item);
|
|
||||||
|
|
||||||
// Build YouTube API v3 URL for playlist items
|
// Internal search implementations
|
||||||
[[nodiscard]] std::string buildPlaylistApiUrl(
|
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||||
std::string_view playlistId,
|
searchWithApi(std::string_view query,
|
||||||
const std::optional<std::string>& pageToken = std::nullopt) const;
|
const std::optional<std::string>& pageToken);
|
||||||
|
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||||
|
searchWithYtDlp(std::string_view query,
|
||||||
|
const std::optional<std::string>& pageToken);
|
||||||
|
|
||||||
std::shared_ptr<NetworkClient> networkClient_;
|
// Fetch video durations for search results (batch API call)
|
||||||
std::unique_ptr<YtDlpManager> ytDlpManager_;
|
void fetchVideoDurations(std::vector<Api::TrackInfo>& tracks,
|
||||||
std::unique_ptr<UrlShortener> urlShortener_;
|
const std::vector<std::string>& videoIds);
|
||||||
|
|
||||||
std::atomic<bool> initialized_{false};
|
// Parse ISO 8601 duration string
|
||||||
mutable std::mutex mutex_;
|
[[nodiscard]] static std::chrono::seconds
|
||||||
|
parseIso8601Duration(const std::string& duration);
|
||||||
|
|
||||||
// Configuration
|
// URL encode/decode helpers
|
||||||
std::optional<std::string> apiKey_;
|
[[nodiscard]] static std::string urlEncode(std::string_view value);
|
||||||
mutable std::mutex configMutex_;
|
[[nodiscard]] static std::string
|
||||||
size_t maxConcurrentResolutions_ = 4;
|
decodeHtmlEntities(std::string_view value);
|
||||||
bool urlShorteningEnabled_ = true;
|
|
||||||
|
|
||||||
// Populate shortened URLs for tracks
|
// Internal methods for playlist resolution
|
||||||
void populateShortenedUrls(std::vector<Api::TrackInfo>& tracks);
|
[[nodiscard]] Api::Result<std::vector<Api::YouTubePlaylistItem>>
|
||||||
void populateShortenedUrl(Api::TrackInfo& track);
|
fetchPlaylistItems(std::string_view playlistId);
|
||||||
};
|
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||||
|
resolveTrackWithYtDlp(const Api::YouTubePlaylistItem& item);
|
||||||
|
|
||||||
|
// Build YouTube API v3 URL for playlist items
|
||||||
|
[[nodiscard]] std::string buildPlaylistApiUrl(
|
||||||
|
std::string_view playlistId,
|
||||||
|
const std::optional<std::string>& pageToken =
|
||||||
|
std::nullopt) const;
|
||||||
|
|
||||||
|
std::shared_ptr<NetworkClient> networkClient_;
|
||||||
|
std::unique_ptr<YtDlpManager> ytDlpManager_;
|
||||||
|
std::unique_ptr<UrlShortener> urlShortener_;
|
||||||
|
|
||||||
|
std::atomic<bool> initialized_{false};
|
||||||
|
mutable std::mutex mutex_;
|
||||||
|
|
||||||
|
// Configuration
|
||||||
|
std::optional<std::string> apiKey_;
|
||||||
|
mutable std::mutex configMutex_;
|
||||||
|
size_t maxConcurrentResolutions_ = 4;
|
||||||
|
bool urlShorteningEnabled_ = true;
|
||||||
|
|
||||||
|
// Populate shortened URLs for tracks
|
||||||
|
void populateShortenedUrls(std::vector<Api::TrackInfo>& tracks);
|
||||||
|
void populateShortenedUrl(Api::TrackInfo& track);
|
||||||
|
};
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "NetworkClient.hpp"
|
#include "NetworkClient.hpp"
|
||||||
|
#include <TrackTypes.hpp>
|
||||||
|
#include <Types.hpp>
|
||||||
|
#include <YouTubeTypes.hpp>
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <condition_variable>
|
#include <condition_variable>
|
||||||
#include <echoion/api.hpp>
|
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <future>
|
#include <future>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
@@ -12,7 +14,8 @@
|
|||||||
#include <thread>
|
#include <thread>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
struct YtDlpResult {
|
struct YtDlpResult {
|
||||||
std::string output;
|
std::string output;
|
||||||
@@ -21,121 +24,122 @@ namespace Echoion::Core {
|
|||||||
std::chrono::milliseconds executionTime;
|
std::chrono::milliseconds executionTime;
|
||||||
};
|
};
|
||||||
|
|
||||||
class YtDlpManager {
|
class YtDlpManager
|
||||||
public:
|
{
|
||||||
explicit YtDlpManager(std::shared_ptr<NetworkClient> networkClient);
|
public:
|
||||||
~YtDlpManager();
|
|
||||||
|
|
||||||
// Initialize - checks for yt-dlp and downloads if needed
|
explicit YtDlpManager(std::shared_ptr<NetworkClient> networkClient);
|
||||||
Api::Result<void> initialize();
|
~YtDlpManager();
|
||||||
|
|
||||||
// Get the path to the yt-dlp executable
|
|
||||||
[[nodiscard]] std::filesystem::path getExecutablePath() const;
|
|
||||||
|
|
||||||
// Check if yt-dlp is available
|
|
||||||
[[nodiscard]] bool isAvailable() const;
|
|
||||||
|
|
||||||
// Get yt-dlp version
|
|
||||||
[[nodiscard]] std::string getVersion() const;
|
|
||||||
|
|
||||||
// Force update yt-dlp to latest version
|
|
||||||
Api::Result<void> update();
|
|
||||||
|
|
||||||
// Execute yt-dlp with given arguments and return output (synchronous)
|
// Initialize - checks for yt-dlp and downloads if needed
|
||||||
[[nodiscard]] std::string
|
Api::Result<void> initialize();
|
||||||
execute(const std::vector<std::string>& args) const;
|
|
||||||
|
|
||||||
// Execute yt-dlp asynchronously and return a future
|
// Get the path to the yt-dlp executable
|
||||||
[[nodiscard]] std::future<YtDlpResult>
|
[[nodiscard]] std::filesystem::path getExecutablePath() const;
|
||||||
executeAsync(const std::vector<std::string>& args);
|
|
||||||
|
|
||||||
// Execute multiple yt-dlp commands concurrently
|
// Check if yt-dlp is available
|
||||||
[[nodiscard]] std::vector<YtDlpResult>
|
[[nodiscard]] bool isAvailable() const;
|
||||||
executeBatch(const std::vector<std::vector<std::string>>& argsList);
|
|
||||||
|
|
||||||
// Set cookie options for YouTube authentication
|
// Get yt-dlp version
|
||||||
void setCookiesPath(const std::string& path);
|
[[nodiscard]] std::string getVersion() const;
|
||||||
void setCookiesFromBrowser(const std::string& browser);
|
|
||||||
|
|
||||||
// Get cookie arguments for yt-dlp command
|
|
||||||
[[nodiscard]] std::vector<std::string> getCookieArgs() const;
|
|
||||||
|
|
||||||
// Set proxy configuration for yt-dlp
|
// Force update yt-dlp to latest version
|
||||||
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
|
Api::Result<void> update();
|
||||||
[[nodiscard]] std::optional<Api::ProxyConfig> getProxyConfig() const;
|
|
||||||
|
|
||||||
// Configure thread pool size for async operations (default: 4)
|
// Execute yt-dlp with given arguments and return output
|
||||||
void setThreadPoolSize(size_t size);
|
// (synchronous)
|
||||||
[[nodiscard]] size_t getThreadPoolSize() const;
|
[[nodiscard]] std::string
|
||||||
|
execute(const std::vector<std::string>& args) const;
|
||||||
|
|
||||||
private:
|
// Execute yt-dlp asynchronously and return a future
|
||||||
// Get the storage directory for yt-dlp
|
[[nodiscard]] std::future<YtDlpResult>
|
||||||
[[nodiscard]] std::filesystem::path getStorageDir() const;
|
executeAsync(const std::vector<std::string>& args);
|
||||||
|
|
||||||
// Get the executable name based on platform
|
|
||||||
[[nodiscard]] std::string getExecutableName() const;
|
|
||||||
|
|
||||||
// Download yt-dlp from official source
|
|
||||||
Api::Result<void> downloadYtDlp();
|
|
||||||
|
|
||||||
// Make executable executable (Unix only)
|
|
||||||
Api::Result<void> makeExecutable();
|
|
||||||
|
|
||||||
// Check if update is needed (older than 7 days)
|
|
||||||
[[nodiscard]] bool shouldUpdate() const;
|
|
||||||
|
|
||||||
// Get download URL based on platform
|
|
||||||
[[nodiscard]] std::string getDownloadUrl() const;
|
|
||||||
|
|
||||||
// Internal execute implementation
|
// Execute multiple yt-dlp commands concurrently
|
||||||
[[nodiscard]] YtDlpResult
|
[[nodiscard]] std::vector<YtDlpResult> executeBatch(
|
||||||
executeInternal(const std::vector<std::string>& args) const;
|
const std::vector<std::vector<std::string>>& argsList);
|
||||||
|
|
||||||
// Build the full command with all options
|
// Set cookie options for YouTube authentication
|
||||||
[[nodiscard]] std::string
|
void setCookiesPath(const std::string& path);
|
||||||
buildCommand(const std::vector<std::string>& args) const;
|
void setCookiesFromBrowser(const std::string& browser);
|
||||||
|
|
||||||
// Get proxy arguments for yt-dlp command
|
// Get cookie arguments for yt-dlp command
|
||||||
[[nodiscard]] std::vector<std::string> getProxyArgs() const;
|
[[nodiscard]] std::vector<std::string> getCookieArgs() const;
|
||||||
|
|
||||||
// Escape shell argument
|
// Set proxy configuration for yt-dlp
|
||||||
[[nodiscard]] static std::string escapeArg(const std::string& arg);
|
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
|
||||||
|
[[nodiscard]] std::optional<Api::ProxyConfig>
|
||||||
|
getProxyConfig() const;
|
||||||
|
|
||||||
// Thread pool for async operations
|
// Configure thread pool size for async operations (default: 4)
|
||||||
void startThreadPool();
|
void setThreadPoolSize(size_t size);
|
||||||
void stopThreadPool();
|
[[nodiscard]] size_t getThreadPoolSize() const;
|
||||||
void workerThread();
|
|
||||||
|
|
||||||
std::shared_ptr<NetworkClient> networkClient_;
|
private:
|
||||||
std::filesystem::path executablePath_;
|
|
||||||
std::atomic<bool> initialized_{false};
|
|
||||||
mutable std::mutex mutex_;
|
|
||||||
|
|
||||||
// Cookie configuration for YouTube authentication
|
|
||||||
std::optional<std::string> cookiesPath_;
|
|
||||||
std::optional<std::string> cookiesFromBrowser_;
|
|
||||||
|
|
||||||
// Proxy configuration
|
// Get the storage directory for yt-dlp
|
||||||
std::optional<Api::ProxyConfig> proxyConfig_;
|
[[nodiscard]] std::filesystem::path getStorageDir() const;
|
||||||
mutable std::mutex proxyMutex_;
|
|
||||||
|
|
||||||
// Thread pool for async operations
|
// Get the executable name based on platform
|
||||||
size_t threadPoolSize_ = 4;
|
[[nodiscard]] std::string getExecutableName() const;
|
||||||
std::vector<std::jthread> threadPool_;
|
|
||||||
std::queue<std::packaged_task<YtDlpResult()>> taskQueue_;
|
|
||||||
std::mutex taskMutex_;
|
|
||||||
std::condition_variable taskCv_;
|
|
||||||
std::atomic<bool> stopThreads_{false};
|
|
||||||
|
|
||||||
// yt-dlp download URLs
|
// Download yt-dlp from official source
|
||||||
static constexpr std::string_view YTDLP_VERSION_URL =
|
Api::Result<void> downloadYtDlp();
|
||||||
"https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest";
|
|
||||||
static constexpr std::string_view YTDLP_DOWNLOAD_LINUX =
|
// Make executable executable (Unix only)
|
||||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp";
|
Api::Result<void> makeExecutable();
|
||||||
static constexpr std::string_view YTDLP_DOWNLOAD_WINDOWS =
|
|
||||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe";
|
// Check if update is needed (older than 7 days)
|
||||||
static constexpr std::string_view YTDLP_DOWNLOAD_MACOS =
|
[[nodiscard]] bool shouldUpdate() const;
|
||||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos";
|
|
||||||
};
|
// Get download URL based on platform
|
||||||
|
[[nodiscard]] std::string getDownloadUrl() const;
|
||||||
|
|
||||||
|
// Internal execute implementation
|
||||||
|
[[nodiscard]] YtDlpResult
|
||||||
|
executeInternal(const std::vector<std::string>& args) const;
|
||||||
|
|
||||||
|
// Get proxy arguments for yt-dlp command
|
||||||
|
[[nodiscard]] std::vector<std::string> getProxyArgs() const;
|
||||||
|
|
||||||
|
// Thread pool for async operations
|
||||||
|
void startThreadPool();
|
||||||
|
void stopThreadPool();
|
||||||
|
void workerThread();
|
||||||
|
|
||||||
|
std::shared_ptr<NetworkClient> networkClient_;
|
||||||
|
std::filesystem::path executablePath_;
|
||||||
|
std::atomic<bool> initialized_{false};
|
||||||
|
mutable std::mutex mutex_;
|
||||||
|
|
||||||
|
// Cookie configuration for YouTube authentication
|
||||||
|
std::optional<std::string> cookiesPath_;
|
||||||
|
std::optional<std::string> cookiesFromBrowser_;
|
||||||
|
|
||||||
|
// Proxy configuration
|
||||||
|
std::optional<Api::ProxyConfig> proxyConfig_;
|
||||||
|
mutable std::mutex proxyMutex_;
|
||||||
|
|
||||||
|
// Thread pool for async operations
|
||||||
|
size_t threadPoolSize_ = 4;
|
||||||
|
std::vector<std::jthread> threadPool_;
|
||||||
|
std::queue<std::packaged_task<YtDlpResult()>> taskQueue_;
|
||||||
|
std::mutex taskMutex_;
|
||||||
|
std::condition_variable taskCv_;
|
||||||
|
std::atomic<bool> stopThreads_{false};
|
||||||
|
|
||||||
|
// yt-dlp download URLs
|
||||||
|
static constexpr std::string_view YTDLP_VERSION_URL =
|
||||||
|
"https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest";
|
||||||
|
static constexpr std::string_view YTDLP_DOWNLOAD_LINUX =
|
||||||
|
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/"
|
||||||
|
"yt-dlp";
|
||||||
|
static constexpr std::string_view YTDLP_DOWNLOAD_WINDOWS =
|
||||||
|
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/"
|
||||||
|
"yt-dlp.exe";
|
||||||
|
static constexpr std::string_view YTDLP_DOWNLOAD_MACOS =
|
||||||
|
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/"
|
||||||
|
"yt-dlp_macos";
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -4,43 +4,55 @@
|
|||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class ClearCommand : public Command {
|
class ClearCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto result = manager->clearQueue();
|
void execute(const CommandContext& ctx) override
|
||||||
if (!result) {
|
{
|
||||||
ECHOION_LOG_ERROR(std::format("Clear command failed: {}", result.error().message));
|
try {
|
||||||
ctx.reply("Couldn't clear the queue. Please try again.");
|
auto manager = ctx.musicManager.lock();
|
||||||
return;
|
if (!manager) {
|
||||||
}
|
ctx.reply(
|
||||||
|
"The music service is currently unavailable.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
ctx.reply("Queue cleared!");
|
auto result = manager->clearQueue();
|
||||||
} catch (const std::exception& e) {
|
if (!result) {
|
||||||
ECHOION_LOG_ERROR(std::format("Clear command exception: {}", e.what()));
|
ECHOION_LOG_ERROR(
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
std::format("Clear command failed: {}",
|
||||||
}
|
result.error().message));
|
||||||
}
|
ctx.reply(
|
||||||
|
"Couldn't clear the queue. Please try again.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
ctx.reply("Queue cleared!");
|
||||||
return "Clears all tracks from the queue.";
|
} catch (const std::exception& e) {
|
||||||
}
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Clear command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
std::string_view getDescription() const override
|
||||||
return CommandCategory::Queue;
|
{
|
||||||
}
|
return "Clears all tracks from the queue.";
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
CommandCategory getCategory() const override
|
||||||
return {"clr", "empty"};
|
{
|
||||||
}
|
return CommandCategory::Queue;
|
||||||
};
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"clr", "empty"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -1,106 +1,110 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <echoion/api.hpp>
|
#include "echoion/core/MusicManager.hpp"
|
||||||
|
#include <ConfigTypes.hpp>
|
||||||
|
#include <Types.hpp>
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
|
#include <functional>
|
||||||
|
#include <memory>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include <memory>
|
|
||||||
#include <functional>
|
|
||||||
#include "echoion/core/MusicManager.hpp"
|
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class MusicManager;
|
class MusicManager;
|
||||||
|
|
||||||
enum class CommandCategory {
|
enum class CommandCategory { Music, Queue, Playback, Utility, Admin };
|
||||||
Music,
|
|
||||||
Queue,
|
|
||||||
Playback,
|
|
||||||
Utility,
|
|
||||||
Admin
|
|
||||||
};
|
|
||||||
|
|
||||||
inline std::string toString(CommandCategory category) {
|
inline std::string toString(CommandCategory category)
|
||||||
switch (category) {
|
{
|
||||||
case CommandCategory::Music:
|
switch (category) {
|
||||||
return "Music";
|
case CommandCategory::Music:
|
||||||
case CommandCategory::Queue:
|
return "Music";
|
||||||
return "Queue";
|
case CommandCategory::Queue:
|
||||||
case CommandCategory::Playback:
|
return "Queue";
|
||||||
return "Playback";
|
case CommandCategory::Playback:
|
||||||
case CommandCategory::Utility:
|
return "Playback";
|
||||||
return "Utility";
|
case CommandCategory::Utility:
|
||||||
case CommandCategory::Admin:
|
return "Utility";
|
||||||
return "Admin";
|
case CommandCategory::Admin:
|
||||||
}
|
return "Admin";
|
||||||
return "Utility";
|
}
|
||||||
}
|
return "Utility";
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Context passed to every command execution.
|
* @brief Context passed to every command execution.
|
||||||
* Wraps all dependencies required to perform an action.
|
* Wraps all dependencies required to perform an action.
|
||||||
*/
|
*/
|
||||||
struct CommandContext {
|
struct CommandContext {
|
||||||
uint64_t clientId = 0;
|
uint64_t clientId = 0;
|
||||||
std::string prefix;
|
std::string prefix;
|
||||||
std::string args; // Arguments excluding the command name
|
std::string args; // Arguments excluding the command name
|
||||||
std::string_view invokerName;
|
std::string_view invokerName;
|
||||||
|
|
||||||
// Dependencies
|
|
||||||
std::weak_ptr<MusicManager> musicManager;
|
|
||||||
|
|
||||||
// Reply callback - set by CommandManager
|
|
||||||
std::function<void(std::string_view)> replyCallback;
|
|
||||||
|
|
||||||
// Helper to reply to the user
|
|
||||||
void reply(std::string_view message) const {
|
|
||||||
if (replyCallback) {
|
|
||||||
replyCallback(message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
// Dependencies
|
||||||
* @brief Interface that all commands must implement.
|
std::weak_ptr<MusicManager> musicManager;
|
||||||
*/
|
|
||||||
class Command {
|
|
||||||
public:
|
|
||||||
virtual ~Command() = default;
|
|
||||||
|
|
||||||
/**
|
// Reply callback - set by CommandManager
|
||||||
* @brief The logic of the command.
|
std::function<void(std::string_view)> replyCallback;
|
||||||
*/
|
|
||||||
virtual void execute(const CommandContext& ctx) = 0;
|
|
||||||
|
|
||||||
/**
|
// Helper to reply to the user
|
||||||
* @brief Returns the description used for help generation.
|
void reply(std::string_view message) const
|
||||||
*/
|
{
|
||||||
virtual std::string_view getDescription() const = 0;
|
if (replyCallback) {
|
||||||
|
replyCallback(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Returns usage syntax (e.g., "<url>").
|
* @brief Interface that all commands must implement.
|
||||||
*/
|
*/
|
||||||
virtual std::string_view getUsage() const { return ""; }
|
class Command
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
/**
|
virtual ~Command() = default;
|
||||||
* @brief Returns the command category for grouping in help.
|
|
||||||
*/
|
|
||||||
virtual CommandCategory getCategory() const {
|
|
||||||
return CommandCategory::Utility;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Returns aliases for this command.
|
* @brief The logic of the command.
|
||||||
*/
|
*/
|
||||||
virtual std::vector<std::string_view> getAliases() const { return {}; }
|
virtual void execute(const CommandContext& ctx) = 0;
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Returns whether this command requires admin privileges.
|
|
||||||
*/
|
|
||||||
virtual bool requiresAdmin() const { return false; }
|
|
||||||
};
|
|
||||||
|
|
||||||
using CommandPtr = std::shared_ptr<Command>;
|
/**
|
||||||
|
* @brief Returns the description used for help generation.
|
||||||
|
*/
|
||||||
|
virtual std::string_view getDescription() const = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Returns usage syntax (e.g., "<url>").
|
||||||
|
*/
|
||||||
|
virtual std::string_view getUsage() const { return ""; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Returns the command category for grouping in help.
|
||||||
|
*/
|
||||||
|
virtual CommandCategory getCategory() const
|
||||||
|
{
|
||||||
|
return CommandCategory::Utility;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Returns aliases for this command.
|
||||||
|
*/
|
||||||
|
virtual std::vector<std::string_view> getAliases() const
|
||||||
|
{
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Returns whether this command requires admin privileges.
|
||||||
|
*/
|
||||||
|
virtual bool requiresAdmin() const { return false; }
|
||||||
|
};
|
||||||
|
|
||||||
|
using CommandPtr = std::shared_ptr<Command>;
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -1,28 +1,29 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
// New command system - header-only commands
|
// New command system - header-only commands
|
||||||
#include "Command.hpp"
|
|
||||||
#include "PlayCommand.hpp"
|
|
||||||
#include "SelectCommand.hpp"
|
|
||||||
#include "PauseCommand.hpp"
|
|
||||||
#include "ResumeCommand.hpp"
|
|
||||||
#include "StopCommand.hpp"
|
|
||||||
#include "SkipCommand.hpp"
|
|
||||||
#include "SeekCommand.hpp"
|
|
||||||
#include "VolumeCommand.hpp"
|
|
||||||
#include "QueueCommand.hpp"
|
|
||||||
#include "RemoveCommand.hpp"
|
|
||||||
#include "ClearCommand.hpp"
|
#include "ClearCommand.hpp"
|
||||||
|
#include "Command.hpp"
|
||||||
#include "MoveCommand.hpp"
|
#include "MoveCommand.hpp"
|
||||||
#include "ShuffleCommand.hpp"
|
|
||||||
#include "RepeatCommand.hpp"
|
|
||||||
#include "PlaylistCommand.hpp"
|
|
||||||
#include "NowPlayingCommand.hpp"
|
#include "NowPlayingCommand.hpp"
|
||||||
#include "SearchCommand.hpp"
|
#include "PauseCommand.hpp"
|
||||||
|
#include "PlayCommand.hpp"
|
||||||
|
#include "PlaylistCommand.hpp"
|
||||||
|
#include "QueueCommand.hpp"
|
||||||
#include "ReloadCommand.hpp"
|
#include "ReloadCommand.hpp"
|
||||||
#include "ReloadConfigCommand.hpp"
|
#include "ReloadConfigCommand.hpp"
|
||||||
|
#include "RemoveCommand.hpp"
|
||||||
|
#include "RepeatCommand.hpp"
|
||||||
|
#include "ResumeCommand.hpp"
|
||||||
|
#include "RpcInfoCommand.hpp"
|
||||||
|
#include "SearchCommand.hpp"
|
||||||
|
#include "SeekCommand.hpp"
|
||||||
|
#include "SelectCommand.hpp"
|
||||||
|
#include "ShuffleCommand.hpp"
|
||||||
|
#include "SkipCommand.hpp"
|
||||||
|
#include "StopCommand.hpp"
|
||||||
#include "SubscribeCommand.hpp"
|
#include "SubscribeCommand.hpp"
|
||||||
#include "UnsubscribeCommand.hpp"
|
|
||||||
#include "SubscribersCommand.hpp"
|
#include "SubscribersCommand.hpp"
|
||||||
#include "UnsubscribeIdCommand.hpp"
|
|
||||||
#include "UnsubscribeAllCommand.hpp"
|
#include "UnsubscribeAllCommand.hpp"
|
||||||
|
#include "UnsubscribeCommand.hpp"
|
||||||
|
#include "UnsubscribeIdCommand.hpp"
|
||||||
|
#include "VolumeCommand.hpp"
|
||||||
@@ -2,81 +2,98 @@
|
|||||||
|
|
||||||
#include "Command.hpp"
|
#include "Command.hpp"
|
||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
|
||||||
#include <charconv>
|
#include <charconv>
|
||||||
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class MoveCommand : public Command {
|
class MoveCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ctx.args.empty()) {
|
void execute(const CommandContext& ctx) override
|
||||||
ctx.reply("Usage: move <from> <to>\nExample: move 5 1 (moves track 5 to position 1)");
|
{
|
||||||
return;
|
try {
|
||||||
}
|
auto manager = ctx.musicManager.lock();
|
||||||
|
if (!manager) {
|
||||||
|
ctx.reply(
|
||||||
|
"The music service is currently unavailable.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Parse arguments: from and to positions
|
if (ctx.args.empty()) {
|
||||||
uint32_t from = 0, to = 0;
|
ctx.reply("Usage: move <from> <to>\nExample: move 5 1 "
|
||||||
|
"(moves track 5 to position 1)");
|
||||||
auto spacePos = ctx.args.find(' ');
|
return;
|
||||||
if (spacePos == std::string::npos) {
|
}
|
||||||
ctx.reply("Please provide both from and to positions.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto result1 = std::from_chars(ctx.args.data(),
|
// Parse arguments: from and to positions
|
||||||
ctx.args.data() + spacePos,
|
uint32_t from = 0, to = 0;
|
||||||
from);
|
|
||||||
auto result2 = std::from_chars(ctx.args.data() + spacePos + 1,
|
|
||||||
ctx.args.data() + ctx.args.size(),
|
|
||||||
to);
|
|
||||||
|
|
||||||
if (result1.ec != std::errc() || result2.ec != std::errc() || from == 0 || to == 0) {
|
auto spacePos = ctx.args.find(' ');
|
||||||
ctx.reply("Please provide valid position numbers (starting from 1).");
|
if (spacePos == std::string::npos) {
|
||||||
return;
|
ctx.reply("Please provide both from and to positions.");
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
auto moveResult = manager->moveInQueue(from - 1, to - 1); // Convert to 0-based
|
auto result1 = std::from_chars(
|
||||||
if (!moveResult) {
|
ctx.args.data(), ctx.args.data() + spacePos, from);
|
||||||
ECHOION_LOG_ERROR(std::format("Move command failed: {}", moveResult.error().message));
|
auto result2 =
|
||||||
|
std::from_chars(ctx.args.data() + spacePos + 1,
|
||||||
if (moveResult.error().code == Api::ErrorCode::NotFound) {
|
ctx.args.data() + ctx.args.size(),
|
||||||
ctx.reply("One of those positions doesn't exist in the queue.");
|
to);
|
||||||
} else {
|
|
||||||
ctx.reply("Couldn't move that track. Please try again.");
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.reply(std::format("Moved track from position {} to {}.", from, to));
|
if (result1.ec != std::errc() ||
|
||||||
} catch (const std::exception& e) {
|
result2.ec != std::errc() || from == 0 || to == 0) {
|
||||||
ECHOION_LOG_ERROR(std::format("Move command exception: {}", e.what()));
|
ctx.reply("Please provide valid position numbers "
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
"(starting from 1).");
|
||||||
}
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
auto moveResult = manager->moveInQueue(
|
||||||
return "Moves a track to a different position in the queue.";
|
from - 1, to - 1); // Convert to 0-based
|
||||||
}
|
if (!moveResult) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Move command failed: {}",
|
||||||
|
moveResult.error().message));
|
||||||
|
|
||||||
std::string_view getUsage() const override {
|
if (moveResult.error().code ==
|
||||||
return "<from> <to>";
|
Api::ErrorCode::NotFound) {
|
||||||
}
|
ctx.reply("One of those positions doesn't exist in "
|
||||||
|
"the queue.");
|
||||||
|
} else {
|
||||||
|
ctx.reply(
|
||||||
|
"Couldn't move that track. Please try again.");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
ctx.reply(std::format(
|
||||||
return CommandCategory::Queue;
|
"Moved track from position {} to {}.", from, to));
|
||||||
}
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Move command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
std::string_view getDescription() const override
|
||||||
return {"mv"};
|
{
|
||||||
}
|
return "Moves a track to a different position in the queue.";
|
||||||
};
|
}
|
||||||
|
|
||||||
|
std::string_view getUsage() const override { return "<from> <to>"; }
|
||||||
|
|
||||||
|
CommandCategory getCategory() const override
|
||||||
|
{
|
||||||
|
return CommandCategory::Queue;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"mv"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -4,95 +4,113 @@
|
|||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class NowPlayingCommand : public Command {
|
class NowPlayingCommand : public Command
|
||||||
public:
|
|
||||||
void execute(const CommandContext& ctx) override {
|
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto current = manager->getCurrentTrack();
|
|
||||||
if (!current) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("NowPlaying command failed: {}", current.error().message));
|
|
||||||
ctx.reply("Couldn't get current track information.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!current->has_value()) {
|
|
||||||
ctx.reply(std::format(
|
|
||||||
"Nothing is currently playing. Add something with {}play !",
|
|
||||||
ctx.prefix));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const auto& track = current->value();
|
|
||||||
const auto& trackInfo = track.track;
|
|
||||||
std::string displayText = trackInfo.title;
|
|
||||||
if (!trackInfo.artist.empty()) {
|
|
||||||
displayText =
|
|
||||||
std::format("{} by {}", trackInfo.title, trackInfo.artist);
|
|
||||||
}
|
|
||||||
std::string linkText = trackInfo.shortenedUrl.has_value() &&
|
|
||||||
!trackInfo.shortenedUrl->empty()
|
|
||||||
? std::format("[{}]({})", displayText,
|
|
||||||
*trackInfo.shortenedUrl)
|
|
||||||
: displayText;
|
|
||||||
std::string msg = std::format("\xf0\x9f\x8e\xb5 {}", linkText);
|
|
||||||
|
|
||||||
// Show current position / total duration
|
|
||||||
auto playbackState = manager->getPlaybackState();
|
|
||||||
if (playbackState && playbackState->currentTrack.has_value() &&
|
|
||||||
trackInfo.duration.has_value() && trackInfo.duration->count() > 0) {
|
|
||||||
auto position = playbackState->position;
|
|
||||||
msg += std::format(" [{}/{}]",
|
|
||||||
formatDuration(position),
|
|
||||||
formatDuration(*trackInfo.duration));
|
|
||||||
} else if (trackInfo.duration.has_value() && trackInfo.duration->count() > 0) {
|
|
||||||
msg += std::format(" [{}]", formatDuration(*trackInfo.duration));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!track.addedBy.empty()) {
|
|
||||||
msg += std::format(" (requested by {})", track.addedBy);
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.reply(msg);
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("NowPlaying command exception: {}", e.what()));
|
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
|
||||||
return "Shows the currently playing track.";
|
|
||||||
}
|
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
|
||||||
return CommandCategory::Playback;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
|
||||||
return {"np", "current", "playing"};
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
|
|
||||||
static std::string formatDuration(std::chrono::milliseconds duration)
|
|
||||||
{
|
{
|
||||||
auto totalSeconds = duration.count() / 1000;
|
public:
|
||||||
auto hours = totalSeconds / 3600;
|
|
||||||
auto mins = (totalSeconds % 3600) / 60;
|
|
||||||
auto secs = totalSeconds % 60;
|
|
||||||
|
|
||||||
if (hours > 0) {
|
void execute(const CommandContext& ctx) override
|
||||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
{
|
||||||
}
|
try {
|
||||||
return std::format("{}:{:02}", mins, secs);
|
auto manager = ctx.musicManager.lock();
|
||||||
}
|
if (!manager) {
|
||||||
};
|
ctx.reply(
|
||||||
|
"The music service is currently unavailable.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto current = manager->getCurrentTrack();
|
||||||
|
if (!current) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("NowPlaying command failed: {}",
|
||||||
|
current.error().message));
|
||||||
|
ctx.reply("Couldn't get current track information.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!current->has_value()) {
|
||||||
|
ctx.reply(std::format("Nothing is currently playing. "
|
||||||
|
"Add something with {}play !",
|
||||||
|
ctx.prefix));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto& track = current->value();
|
||||||
|
const auto& trackInfo = track.track;
|
||||||
|
std::string displayText = trackInfo.title;
|
||||||
|
if (!trackInfo.artist.empty()) {
|
||||||
|
displayText = std::format("{} by {}", trackInfo.title,
|
||||||
|
trackInfo.artist);
|
||||||
|
}
|
||||||
|
std::string linkText =
|
||||||
|
trackInfo.shortenedUrl.has_value() &&
|
||||||
|
!trackInfo.shortenedUrl->empty()
|
||||||
|
? std::format("[{}]({})", displayText,
|
||||||
|
*trackInfo.shortenedUrl)
|
||||||
|
: displayText;
|
||||||
|
std::string msg =
|
||||||
|
std::format("\xf0\x9f\x8e\xb5 {}", linkText);
|
||||||
|
|
||||||
|
// Show current position / total duration
|
||||||
|
auto playbackState = manager->getPlaybackState();
|
||||||
|
if (playbackState &&
|
||||||
|
playbackState->currentTrack.has_value() &&
|
||||||
|
trackInfo.duration.has_value() &&
|
||||||
|
trackInfo.duration->count() > 0) {
|
||||||
|
auto position = playbackState->position;
|
||||||
|
msg += std::format(" [{}/{}]",
|
||||||
|
formatDuration(position),
|
||||||
|
formatDuration(*trackInfo.duration));
|
||||||
|
} else if (trackInfo.duration.has_value() &&
|
||||||
|
trackInfo.duration->count() > 0) {
|
||||||
|
msg += std::format(" [{}]",
|
||||||
|
formatDuration(*trackInfo.duration));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!track.addedBy.empty()) {
|
||||||
|
msg += std::format(" (requested by {})", track.addedBy);
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.reply(msg);
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(std::format(
|
||||||
|
"NowPlaying command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string_view getDescription() const override
|
||||||
|
{
|
||||||
|
return "Shows the currently playing track.";
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandCategory getCategory() const override
|
||||||
|
{
|
||||||
|
return CommandCategory::Playback;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"np", "current", "playing"};
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
static std::string
|
||||||
|
formatDuration(std::chrono::milliseconds duration)
|
||||||
|
{
|
||||||
|
auto totalSeconds = duration.count() / 1000;
|
||||||
|
auto hours = totalSeconds / 3600;
|
||||||
|
auto mins = (totalSeconds % 3600) / 60;
|
||||||
|
auto secs = totalSeconds % 60;
|
||||||
|
|
||||||
|
if (hours > 0) {
|
||||||
|
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||||
|
}
|
||||||
|
return std::format("{}:{:02}", mins, secs);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -4,48 +4,61 @@
|
|||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class PauseCommand : public Command {
|
class PauseCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto result = manager->pause();
|
void execute(const CommandContext& ctx) override
|
||||||
if (!result) {
|
{
|
||||||
ECHOION_LOG_ERROR(std::format("Pause command failed: {}", result.error().message));
|
try {
|
||||||
|
auto manager = ctx.musicManager.lock();
|
||||||
if (result.error().code == Api::ErrorCode::InvalidArgument) {
|
if (!manager) {
|
||||||
ctx.reply("Nothing is playing right now.");
|
ctx.reply(
|
||||||
} else {
|
"The music service is currently unavailable.");
|
||||||
ctx.reply("Couldn't pause playback. Please try again.");
|
return;
|
||||||
}
|
}
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.reply("Playback paused.");
|
auto result = manager->pause();
|
||||||
} catch (const std::exception& e) {
|
if (!result) {
|
||||||
ECHOION_LOG_ERROR(std::format("Pause command exception: {}", e.what()));
|
ECHOION_LOG_ERROR(
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
std::format("Pause command failed: {}",
|
||||||
}
|
result.error().message));
|
||||||
}
|
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
if (result.error().code ==
|
||||||
return "Pauses the current playback.";
|
Api::ErrorCode::InvalidArgument) {
|
||||||
}
|
ctx.reply("Nothing is playing right now.");
|
||||||
|
} else {
|
||||||
|
ctx.reply(
|
||||||
|
"Couldn't pause playback. Please try again.");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
ctx.reply("Playback paused.");
|
||||||
return CommandCategory::Playback;
|
} catch (const std::exception& e) {
|
||||||
}
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Pause command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
std::string_view getDescription() const override
|
||||||
return {};
|
{
|
||||||
}
|
return "Pauses the current playback.";
|
||||||
};
|
}
|
||||||
|
|
||||||
|
CommandCategory getCategory() const override
|
||||||
|
{
|
||||||
|
return CommandCategory::Playback;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -4,158 +4,186 @@
|
|||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class PlayCommand : public Command {
|
class PlayCommand : public Command
|
||||||
public:
|
|
||||||
void execute(const CommandContext& ctx) override {
|
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable. Please try again later.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ctx.args.empty()) {
|
|
||||||
ctx.reply("Usage: play <url or search query>\nExample: play never gonna give you up");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if it's a direct URL
|
|
||||||
if (ctx.args.find("http") == 0) {
|
|
||||||
auto result = manager->play(ctx.args, ctx.clientId);
|
|
||||||
if (!result) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("Play URL failed '{}': {}",
|
|
||||||
ctx.args, result.error().message));
|
|
||||||
|
|
||||||
switch (result.error().code) {
|
|
||||||
case Api::ErrorCode::NetworkError:
|
|
||||||
ctx.reply("Couldn't connect to that URL. Please check and try again.");
|
|
||||||
break;
|
|
||||||
case Api::ErrorCode::InvalidUrl:
|
|
||||||
ctx.reply("That doesn't look like a valid URL.");
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
ctx.reply("Couldn't play that URL. Please try again.");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// result contains the track title
|
|
||||||
ctx.reply(std::format("Added to queue: {}", *result));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Otherwise, treat as search query
|
|
||||||
auto searchResult = manager->search(ctx.args);
|
|
||||||
if (!searchResult) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("Search failed for '{}': {}",
|
|
||||||
ctx.args, searchResult.error().message));
|
|
||||||
|
|
||||||
if (searchResult.error().code == Api::ErrorCode::NetworkError) {
|
|
||||||
ctx.reply("Couldn't connect to search service. Please check your connection.");
|
|
||||||
} else {
|
|
||||||
ctx.reply("Search failed. Please try again.");
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (searchResult->tracks.empty()) {
|
|
||||||
ctx.reply("No results found. Try different keywords.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single result - play immediately
|
|
||||||
if (searchResult->tracks.size() == 1) {
|
|
||||||
const auto& track = searchResult->tracks[0];
|
|
||||||
auto playResult = manager->queueTrack(track, ctx.clientId);
|
|
||||||
if (!playResult) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("Queue failed: {}", playResult.error().message));
|
|
||||||
ctx.reply("Couldn't add that track. Please try again.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string displayText = track.title;
|
|
||||||
if (!track.artist.empty()) {
|
|
||||||
displayText =
|
|
||||||
std::format("{} by {}", track.title, track.artist);
|
|
||||||
}
|
|
||||||
std::string linkText =
|
|
||||||
track.shortenedUrl.has_value() &&
|
|
||||||
!track.shortenedUrl->empty()
|
|
||||||
? std::format("[{}]({})", displayText,
|
|
||||||
*track.shortenedUrl)
|
|
||||||
: displayText;
|
|
||||||
ctx.reply(std::format("Added to queue: {}", linkText));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Multiple results - store and show list
|
|
||||||
manager->storePendingSearch(ctx.clientId, searchResult->tracks);
|
|
||||||
|
|
||||||
std::string msg = std::format("\xf0\x9f\x94\x8d Multiple results "
|
|
||||||
"found. Use {}select <number>:\n",
|
|
||||||
ctx.prefix);
|
|
||||||
for (size_t i = 0; i < searchResult->tracks.size() && i < 5; ++i) {
|
|
||||||
const auto& track = searchResult->tracks[i];
|
|
||||||
std::string displayText = track.title;
|
|
||||||
if (!track.artist.empty()) {
|
|
||||||
displayText =
|
|
||||||
std::format("{} by {}", track.title, track.artist);
|
|
||||||
}
|
|
||||||
std::string linkText =
|
|
||||||
track.shortenedUrl.has_value() &&
|
|
||||||
!track.shortenedUrl->empty()
|
|
||||||
? std::format("[{}]({})", displayText,
|
|
||||||
*track.shortenedUrl)
|
|
||||||
: displayText;
|
|
||||||
msg += std::format("{}. {}", i + 1, linkText);
|
|
||||||
if (track.duration.has_value()) {
|
|
||||||
msg +=
|
|
||||||
std::format(" [{}]", formatDuration(*track.duration));
|
|
||||||
}
|
|
||||||
msg += "\n";
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.reply(msg);
|
|
||||||
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("Play command exception: {}", e.what()));
|
|
||||||
ctx.reply("Something went wrong while trying to play. Please try again.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
|
||||||
return "Plays a track from URL or searches and lets you select.";
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string_view getUsage() const override {
|
|
||||||
return "<url or search query>";
|
|
||||||
}
|
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
|
||||||
return CommandCategory::Music;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
|
||||||
return {"p", "add"};
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
|
|
||||||
static std::string formatDuration(std::chrono::milliseconds duration)
|
|
||||||
{
|
{
|
||||||
auto totalSeconds = duration.count() / 1000;
|
public:
|
||||||
auto hours = totalSeconds / 3600;
|
|
||||||
auto mins = (totalSeconds % 3600) / 60;
|
|
||||||
auto secs = totalSeconds % 60;
|
|
||||||
|
|
||||||
if (hours > 0) {
|
void execute(const CommandContext& ctx) override
|
||||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
{
|
||||||
}
|
try {
|
||||||
return std::format("{}:{:02}", mins, secs);
|
auto manager = ctx.musicManager.lock();
|
||||||
}
|
if (!manager) {
|
||||||
};
|
ctx.reply("The music service is currently unavailable. "
|
||||||
|
"Please try again later.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ctx.args.empty()) {
|
||||||
|
ctx.reply("Usage: play <url or search query>\nExample: "
|
||||||
|
"play never gonna give you up");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if it's a direct URL
|
||||||
|
if (ctx.args.find("http") == 0) {
|
||||||
|
auto result = manager->play(ctx.args, ctx.clientId);
|
||||||
|
if (!result) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Play URL failed '{}': {}",
|
||||||
|
ctx.args, result.error().message));
|
||||||
|
|
||||||
|
switch (result.error().code) {
|
||||||
|
case Api::ErrorCode::NetworkError:
|
||||||
|
ctx.reply("Couldn't connect to that URL. "
|
||||||
|
"Please check and try again.");
|
||||||
|
break;
|
||||||
|
case Api::ErrorCode::InvalidUrl:
|
||||||
|
ctx.reply(
|
||||||
|
"That doesn't look like a valid URL.");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
ctx.reply("Couldn't play that URL. Please "
|
||||||
|
"try again.");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// result contains the track title
|
||||||
|
ctx.reply(std::format("Added to queue: {}", *result));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise, treat as search query
|
||||||
|
auto searchResult = manager->search(ctx.args);
|
||||||
|
if (!searchResult) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Search failed for '{}': {}", ctx.args,
|
||||||
|
searchResult.error().message));
|
||||||
|
|
||||||
|
if (searchResult.error().code ==
|
||||||
|
Api::ErrorCode::NetworkError) {
|
||||||
|
ctx.reply("Couldn't connect to search service. "
|
||||||
|
"Please check your connection.");
|
||||||
|
} else {
|
||||||
|
ctx.reply("Search failed. Please try again.");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (searchResult->tracks.empty()) {
|
||||||
|
ctx.reply("No results found. Try different keywords.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Single result - play immediately
|
||||||
|
if (searchResult->tracks.size() == 1) {
|
||||||
|
const auto& track = searchResult->tracks[0];
|
||||||
|
auto playResult =
|
||||||
|
manager->queueTrack(track, ctx.clientId);
|
||||||
|
if (!playResult) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Queue failed: {}",
|
||||||
|
playResult.error().message));
|
||||||
|
ctx.reply(
|
||||||
|
"Couldn't add that track. Please try again.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string displayText = track.title;
|
||||||
|
if (!track.artist.empty()) {
|
||||||
|
displayText = std::format("{} by {}", track.title,
|
||||||
|
track.artist);
|
||||||
|
}
|
||||||
|
std::string linkText =
|
||||||
|
track.shortenedUrl.has_value() &&
|
||||||
|
!track.shortenedUrl->empty()
|
||||||
|
? std::format("[{}]({})", displayText,
|
||||||
|
*track.shortenedUrl)
|
||||||
|
: displayText;
|
||||||
|
ctx.reply(std::format("Added to queue: {}", linkText));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Multiple results - store and show list
|
||||||
|
manager->storePendingSearch(ctx.clientId,
|
||||||
|
searchResult->tracks);
|
||||||
|
|
||||||
|
std::string msg =
|
||||||
|
std::format("\xf0\x9f\x94\x8d Multiple results "
|
||||||
|
"found. Use {}select <number>:\n",
|
||||||
|
ctx.prefix);
|
||||||
|
for (size_t i = 0; i < searchResult->tracks.size() && i < 5;
|
||||||
|
++i) {
|
||||||
|
const auto& track = searchResult->tracks[i];
|
||||||
|
std::string displayText = track.title;
|
||||||
|
if (!track.artist.empty()) {
|
||||||
|
displayText = std::format("{} by {}", track.title,
|
||||||
|
track.artist);
|
||||||
|
}
|
||||||
|
std::string linkText =
|
||||||
|
track.shortenedUrl.has_value() &&
|
||||||
|
!track.shortenedUrl->empty()
|
||||||
|
? std::format("[{}]({})", displayText,
|
||||||
|
*track.shortenedUrl)
|
||||||
|
: displayText;
|
||||||
|
msg += std::format("{}. {}", i + 1, linkText);
|
||||||
|
if (track.duration.has_value()) {
|
||||||
|
msg += std::format(" [{}]",
|
||||||
|
formatDuration(*track.duration));
|
||||||
|
}
|
||||||
|
msg += "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.reply(msg);
|
||||||
|
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Play command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong while trying to play. "
|
||||||
|
"Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string_view getDescription() const override
|
||||||
|
{
|
||||||
|
return "Plays a track from URL or searches and lets you "
|
||||||
|
"select.";
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string_view getUsage() const override
|
||||||
|
{
|
||||||
|
return "<url or search query>";
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandCategory getCategory() const override
|
||||||
|
{
|
||||||
|
return CommandCategory::Music;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"p", "add"};
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
static std::string
|
||||||
|
formatDuration(std::chrono::milliseconds duration)
|
||||||
|
{
|
||||||
|
auto totalSeconds = duration.count() / 1000;
|
||||||
|
auto hours = totalSeconds / 3600;
|
||||||
|
auto mins = (totalSeconds % 3600) / 60;
|
||||||
|
auto secs = totalSeconds % 60;
|
||||||
|
|
||||||
|
if (hours > 0) {
|
||||||
|
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||||
|
}
|
||||||
|
return std::format("{}:{:02}", mins, secs);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -5,76 +5,97 @@
|
|||||||
#include <format>
|
#include <format>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class PlaylistCommand : public Command {
|
class PlaylistCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ctx.args.empty()) {
|
void execute(const CommandContext& ctx) override
|
||||||
// List playlists
|
{
|
||||||
auto playlists = manager->getPlaylists();
|
try {
|
||||||
if (!playlists) {
|
auto manager = ctx.musicManager.lock();
|
||||||
ECHOION_LOG_ERROR(std::format("Playlist list failed: {}", playlists.error().message));
|
if (!manager) {
|
||||||
ctx.reply("Couldn't retrieve playlists.");
|
ctx.reply(
|
||||||
return;
|
"The music service is currently unavailable.");
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (playlists->empty()) {
|
if (ctx.args.empty()) {
|
||||||
ctx.reply("No playlists available.");
|
// List playlists
|
||||||
return;
|
auto playlists = manager->getPlaylists();
|
||||||
}
|
if (!playlists) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Playlist list failed: {}",
|
||||||
|
playlists.error().message));
|
||||||
|
ctx.reply("Couldn't retrieve playlists.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
std::stringstream msg;
|
if (playlists->empty()) {
|
||||||
msg << "\xf0\x9f\x93\x81 Available playlists:\n";
|
ctx.reply("No playlists available.");
|
||||||
for (const auto& pl : *playlists) {
|
return;
|
||||||
msg << std::format("- {} ({} tracks)\n", pl.name, pl.tracks.size());
|
}
|
||||||
}
|
|
||||||
|
|
||||||
ctx.reply(msg.str());
|
std::stringstream msg;
|
||||||
} else {
|
msg << "\xf0\x9f\x93\x81 Available playlists:\n";
|
||||||
// Load playlist
|
for (const auto& pl : *playlists) {
|
||||||
auto result = manager->loadPlaylist(std::string(ctx.args), ctx.clientId);
|
msg << std::format("- {} ({} tracks)\n", pl.name,
|
||||||
if (!result) {
|
pl.tracks.size());
|
||||||
ECHOION_LOG_ERROR(std::format("Playlist load failed: {}", result.error().message));
|
}
|
||||||
|
|
||||||
if (result.error().code == Api::ErrorCode::NotFound) {
|
|
||||||
ctx.reply("That playlist doesn't exist.");
|
|
||||||
} else {
|
|
||||||
ctx.reply("Couldn't load the playlist. Please try again.");
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.reply(std::format("Loading playlist '{}'... Tracks will be added to the queue as they are resolved.", ctx.args));
|
ctx.reply(msg.str());
|
||||||
}
|
} else {
|
||||||
} catch (const std::exception& e) {
|
// Load playlist
|
||||||
ECHOION_LOG_ERROR(std::format("Playlist command exception: {}", e.what()));
|
auto result = manager->loadPlaylist(
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
std::string(ctx.args), ctx.clientId);
|
||||||
}
|
if (!result) {
|
||||||
}
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Playlist load failed: {}",
|
||||||
|
result.error().message));
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
if (result.error().code ==
|
||||||
return "Lists or loads a playlist.";
|
Api::ErrorCode::NotFound) {
|
||||||
}
|
ctx.reply("That playlist doesn't exist.");
|
||||||
|
} else {
|
||||||
|
ctx.reply("Couldn't load the playlist. Please "
|
||||||
|
"try again.");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
std::string_view getUsage() const override {
|
ctx.reply(std::format(
|
||||||
return "[playlist name]";
|
"Loading playlist '{}'... Tracks will be added to "
|
||||||
}
|
"the queue as they are resolved.",
|
||||||
|
ctx.args));
|
||||||
|
}
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(std::format(
|
||||||
|
"Playlist command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
std::string_view getDescription() const override
|
||||||
return CommandCategory::Music;
|
{
|
||||||
}
|
return "Lists or loads a playlist.";
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
std::string_view getUsage() const override
|
||||||
return {"pl"};
|
{
|
||||||
}
|
return "[playlist name]";
|
||||||
};
|
}
|
||||||
|
|
||||||
|
CommandCategory getCategory() const override
|
||||||
|
{
|
||||||
|
return CommandCategory::Music;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"pl"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -5,189 +5,200 @@
|
|||||||
#include <format>
|
#include <format>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class QueueCommand : public Command {
|
class QueueCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto current = manager->getCurrentTrack();
|
void execute(const CommandContext& ctx) override
|
||||||
auto queue = manager->getQueue();
|
{
|
||||||
auto state = manager->getPlaybackState();
|
|
||||||
|
|
||||||
if (!queue) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("Queue command failed: {}", queue.error().message));
|
|
||||||
ctx.reply("Couldn't get queue information.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse page number from args (default to 1)
|
|
||||||
int page = 1;
|
|
||||||
if (!ctx.args.empty()) {
|
|
||||||
try {
|
try {
|
||||||
page = std::stoi(std::string(ctx.args));
|
auto manager = ctx.musicManager.lock();
|
||||||
if (page < 1) {
|
if (!manager) {
|
||||||
page = 1;
|
ctx.reply(
|
||||||
|
"The music service is currently unavailable.");
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
} catch (...) {
|
|
||||||
page = 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
constexpr int ITEMS_PER_PAGE = 10;
|
auto current = manager->getCurrentTrack();
|
||||||
int totalPages =
|
auto queue = manager->getQueue();
|
||||||
(static_cast<int>(queue->size()) + ITEMS_PER_PAGE - 1) /
|
auto state = manager->getPlaybackState();
|
||||||
ITEMS_PER_PAGE;
|
|
||||||
if (totalPages == 0) {
|
|
||||||
totalPages = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clamp page to valid range
|
if (!queue) {
|
||||||
if (page > totalPages) {
|
ECHOION_LOG_ERROR(std::format(
|
||||||
page = totalPages;
|
"Queue command failed: {}", queue.error().message));
|
||||||
}
|
ctx.reply("Couldn't get queue information.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
int startIdx = (page - 1) * ITEMS_PER_PAGE;
|
// Parse page number from args (default to 1)
|
||||||
int endIdx = std::min(startIdx + ITEMS_PER_PAGE,
|
int page = 1;
|
||||||
static_cast<int>(queue->size()));
|
if (!ctx.args.empty()) {
|
||||||
|
try {
|
||||||
|
page = std::stoi(std::string(ctx.args));
|
||||||
|
if (page < 1) {
|
||||||
|
page = 1;
|
||||||
|
}
|
||||||
|
} catch (...) {
|
||||||
|
page = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
std::stringstream msg;
|
constexpr int ITEMS_PER_PAGE = 10;
|
||||||
msg << "\xf0\x9f\x93\x9c **Queue** (Page " << page << "/"
|
int totalPages =
|
||||||
<< totalPages << ")\n";
|
(static_cast<int>(queue->size()) + ITEMS_PER_PAGE - 1) /
|
||||||
|
ITEMS_PER_PAGE;
|
||||||
|
if (totalPages == 0) {
|
||||||
|
totalPages = 1;
|
||||||
|
}
|
||||||
|
|
||||||
// Current track
|
// Clamp page to valid range
|
||||||
if (current && current->has_value()) {
|
if (page > totalPages) {
|
||||||
const auto& track = current->value();
|
page = totalPages;
|
||||||
const auto& trackInfo = track.track;
|
}
|
||||||
|
|
||||||
// Build time display: [current/total] or [total]
|
int startIdx = (page - 1) * ITEMS_PER_PAGE;
|
||||||
std::string timeStr;
|
int endIdx = std::min(startIdx + ITEMS_PER_PAGE,
|
||||||
if (trackInfo.duration.has_value() &&
|
static_cast<int>(queue->size()));
|
||||||
trackInfo.duration->count() > 0) {
|
|
||||||
if (state) {
|
std::stringstream msg;
|
||||||
timeStr =
|
msg << "\xf0\x9f\x93\x9c **Queue** (Page " << page << "/"
|
||||||
std::format(" [{}/{}]",
|
<< totalPages << ")\n";
|
||||||
formatDuration(state->position),
|
|
||||||
formatDuration(*trackInfo.duration));
|
// Current track
|
||||||
|
if (current && current->has_value()) {
|
||||||
|
const auto& track = current->value();
|
||||||
|
const auto& trackInfo = track.track;
|
||||||
|
|
||||||
|
// Build time display: [current/total] or [total]
|
||||||
|
std::string timeStr;
|
||||||
|
if (trackInfo.duration.has_value() &&
|
||||||
|
trackInfo.duration->count() > 0) {
|
||||||
|
if (state) {
|
||||||
|
timeStr = std::format(
|
||||||
|
" [{}/{}]",
|
||||||
|
formatDuration(state->position),
|
||||||
|
formatDuration(*trackInfo.duration));
|
||||||
|
} else {
|
||||||
|
timeStr = std::format(
|
||||||
|
" [{}]",
|
||||||
|
formatDuration(*trackInfo.duration));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string displayText = trackInfo.title;
|
||||||
|
if (!trackInfo.artist.empty()) {
|
||||||
|
displayText = std::format(
|
||||||
|
"{} by {}", trackInfo.title, trackInfo.artist);
|
||||||
|
}
|
||||||
|
std::string linkText =
|
||||||
|
trackInfo.shortenedUrl.has_value() &&
|
||||||
|
!trackInfo.shortenedUrl->empty()
|
||||||
|
? std::format("[{}]({}){}", displayText,
|
||||||
|
*trackInfo.shortenedUrl, timeStr)
|
||||||
|
: displayText + timeStr;
|
||||||
|
msg << std::format("\n**Now Playing:** {}\n", linkText);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Queue
|
||||||
|
if (queue->empty()) {
|
||||||
|
msg << std::format(
|
||||||
|
"\nThe queue is empty. Add songs with {}play !",
|
||||||
|
ctx.prefix);
|
||||||
} else {
|
} else {
|
||||||
timeStr = std::format(
|
msg << std::format("\n**Up Next ({} tracks):**\n",
|
||||||
" [{}]", formatDuration(*trackInfo.duration));
|
queue->size());
|
||||||
}
|
for (int i = startIdx; i < endIdx; ++i) {
|
||||||
}
|
const auto& entry = (*queue)[i];
|
||||||
|
const auto& trackInfo = entry.track;
|
||||||
std::string displayText = trackInfo.title;
|
std::string displayText = trackInfo.title;
|
||||||
if (!trackInfo.artist.empty()) {
|
if (!trackInfo.artist.empty()) {
|
||||||
displayText = std::format("{} by {}", trackInfo.title,
|
displayText =
|
||||||
trackInfo.artist);
|
std::format("{} by {}", trackInfo.title,
|
||||||
}
|
trackInfo.artist);
|
||||||
std::string linkText =
|
}
|
||||||
trackInfo.shortenedUrl.has_value() &&
|
std::string linkText =
|
||||||
!trackInfo.shortenedUrl->empty()
|
trackInfo.shortenedUrl.has_value() &&
|
||||||
? std::format("[{}]({}){}", displayText,
|
!trackInfo.shortenedUrl->empty()
|
||||||
*trackInfo.shortenedUrl, timeStr)
|
? std::format(
|
||||||
: displayText + timeStr;
|
"[{}]({}) [{}]", displayText,
|
||||||
msg << std::format("\n**Now Playing:** {}\n", linkText);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Queue
|
|
||||||
if (queue->empty()) {
|
|
||||||
msg << std::format(
|
|
||||||
"\nThe queue is empty. Add songs with {}play !",
|
|
||||||
ctx.prefix);
|
|
||||||
} else {
|
|
||||||
msg << std::format("\n**Up Next ({} tracks):**\n",
|
|
||||||
queue->size());
|
|
||||||
for (int i = startIdx; i < endIdx; ++i) {
|
|
||||||
const auto& entry = (*queue)[i];
|
|
||||||
const auto& trackInfo = entry.track;
|
|
||||||
std::string displayText = trackInfo.title;
|
|
||||||
if (!trackInfo.artist.empty()) {
|
|
||||||
displayText =
|
|
||||||
std::format("{} [{}] by {}", trackInfo.title,
|
|
||||||
formatDuration(*trackInfo.duration),
|
|
||||||
trackInfo.artist);
|
|
||||||
}
|
|
||||||
std::string linkText =
|
|
||||||
trackInfo.shortenedUrl.has_value() &&
|
|
||||||
!trackInfo.shortenedUrl->empty()
|
|
||||||
? std::format("[{}]({}) [{}]", displayText,
|
|
||||||
*trackInfo.shortenedUrl,
|
*trackInfo.shortenedUrl,
|
||||||
formatDuration(*trackInfo.duration))
|
formatDuration(*trackInfo.duration))
|
||||||
: displayText;
|
: displayText;
|
||||||
msg << std::format("{}. {}", i + 1, linkText);
|
msg << std::format("{}. {}", i + 1, linkText);
|
||||||
if (!entry.addedBy.empty()) {
|
if (!entry.addedBy.empty()) {
|
||||||
msg << std::format(" (by {})", entry.addedBy);
|
msg << std::format(" (by {})", entry.addedBy);
|
||||||
|
}
|
||||||
|
msg << "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (totalPages > 1) {
|
||||||
|
msg << std::format(
|
||||||
|
"\nUse {}queue <page> to see more "
|
||||||
|
"(page {} of {})",
|
||||||
|
ctx.prefix, page, totalPages);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
msg << "\n";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (totalPages > 1) {
|
// State indicators
|
||||||
msg << std::format("\nUse {}queue <page> to see more "
|
if (state) {
|
||||||
"(page {} of {})",
|
msg << "\n\n";
|
||||||
ctx.prefix, page, totalPages);
|
if (state->isPaused) {
|
||||||
|
msg << "\xe2\x8f\xb8 Paused | ";
|
||||||
|
}
|
||||||
|
if (state->shuffle) {
|
||||||
|
msg << "\xf0\x9f\x94\x80 Shuffle | ";
|
||||||
|
}
|
||||||
|
if (state->repeat) {
|
||||||
|
msg << "\xf0\x9f\x94\x81 Repeat | ";
|
||||||
|
}
|
||||||
|
msg << std::format(
|
||||||
|
"Volume: {}%",
|
||||||
|
static_cast<int>(state->volume * 100));
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.reply(msg.str());
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Queue command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// State indicators
|
std::string_view getDescription() const override
|
||||||
if (state) {
|
{
|
||||||
msg << "\n\n";
|
return "Shows the current queue and playback status.";
|
||||||
if (state->isPaused) {
|
|
||||||
msg << "\xe2\x8f\xb8 Paused | ";
|
|
||||||
}
|
|
||||||
if (state->shuffle) {
|
|
||||||
msg << "\xf0\x9f\x94\x80 Shuffle | ";
|
|
||||||
}
|
|
||||||
if (state->repeat) {
|
|
||||||
msg << "\xf0\x9f\x94\x81 Repeat | ";
|
|
||||||
}
|
|
||||||
msg << std::format("Volume: {}%", static_cast<int>(state->volume * 100));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx.reply(msg.str());
|
std::string_view getUsage() const override { return "[page]"; }
|
||||||
} catch (const std::exception& e) {
|
|
||||||
ECHOION_LOG_ERROR(
|
|
||||||
std::format("Queue command exception: {}", e.what()));
|
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string_view getDescription() const override
|
CommandCategory getCategory() const override
|
||||||
{
|
{
|
||||||
return "Shows the current queue and playback status.";
|
return CommandCategory::Queue;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string_view getUsage() const override { return "[page]"; }
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"q", "list"};
|
||||||
|
}
|
||||||
|
|
||||||
CommandCategory getCategory() const override
|
private:
|
||||||
{
|
|
||||||
return CommandCategory::Queue;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override
|
static std::string
|
||||||
{
|
formatDuration(std::chrono::milliseconds duration)
|
||||||
return {"q", "list"};
|
{
|
||||||
}
|
auto totalSeconds = duration.count() / 1000;
|
||||||
|
auto hours = totalSeconds / 3600;
|
||||||
|
auto mins = (totalSeconds % 3600) / 60;
|
||||||
|
auto secs = totalSeconds % 60;
|
||||||
|
|
||||||
private:
|
if (hours > 0) {
|
||||||
|
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||||
static std::string formatDuration(std::chrono::milliseconds duration)
|
}
|
||||||
{
|
return std::format("{}:{:02}", mins, secs);
|
||||||
auto totalSeconds = duration.count() / 1000;
|
}
|
||||||
auto hours = totalSeconds / 3600;
|
};
|
||||||
auto mins = (totalSeconds % 3600) / 60;
|
|
||||||
auto secs = totalSeconds % 60;
|
|
||||||
|
|
||||||
if (hours > 0) {
|
|
||||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
|
||||||
}
|
|
||||||
return std::format("{}:{:02}", mins, secs);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -4,31 +4,38 @@
|
|||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class ReloadCommand : public Command {
|
class ReloadCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
// This is a placeholder - actual reload is handled by the plugin
|
|
||||||
ECHOION_LOG_INFO("Reload requested by user");
|
|
||||||
ctx.reply("Reload is handled automatically by the plugin. Use the TS3 plugin menu to reload the core.");
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
void execute(const CommandContext& ctx) override
|
||||||
return "Shows information about reloading the bot.";
|
{
|
||||||
}
|
// This is a placeholder - actual reload is handled by the
|
||||||
|
// plugin
|
||||||
|
ECHOION_LOG_INFO("Reload requested by user");
|
||||||
|
ctx.reply("Reload is handled automatically by the plugin. Use "
|
||||||
|
"the TS3 plugin menu to reload the core.");
|
||||||
|
}
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
std::string_view getDescription() const override
|
||||||
return CommandCategory::Admin;
|
{
|
||||||
}
|
return "Shows information about reloading the bot.";
|
||||||
|
}
|
||||||
|
|
||||||
bool requiresAdmin() const override {
|
CommandCategory getCategory() const override
|
||||||
return true;
|
{
|
||||||
}
|
return CommandCategory::Admin;
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
bool requiresAdmin() const override { return true; }
|
||||||
return {"restart", "r"};
|
|
||||||
}
|
std::vector<std::string_view> getAliases() const override
|
||||||
};
|
{
|
||||||
|
return {"restart", "r"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -1,42 +1,52 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "Command.hpp"
|
#include "Command.hpp"
|
||||||
|
#include "echoion/core/Core.hpp" // For Core::reloadConfig
|
||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include "echoion/core/Core.hpp" // For Core::reloadConfig
|
|
||||||
#include <format>
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class ReloadConfigCommand : public Command {
|
class ReloadConfigCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
// Note: ctx.core is not directly accessible, we need to use the MusicManager's core reference
|
|
||||||
// For now, reply with instructions
|
|
||||||
ctx.reply("Config reload: Please use !reload command or restart the bot for config changes to take effect.");
|
|
||||||
|
|
||||||
// TODO: Add core reference to CommandContext so commands can call Core methods
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("ReloadConfig command exception: {}", e.what()));
|
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
void execute(const CommandContext& ctx) override
|
||||||
return "Reloads the bot configuration from file.";
|
{
|
||||||
}
|
try {
|
||||||
|
// Note: ctx.core is not directly accessible, we need to use
|
||||||
|
// the MusicManager's core reference For now, reply with
|
||||||
|
// instructions
|
||||||
|
ctx.reply(
|
||||||
|
"Config reload: Please use !reload command or restart "
|
||||||
|
"the bot for config changes to take effect.");
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
// TODO: Add core reference to CommandContext so commands
|
||||||
return CommandCategory::Admin;
|
// can call Core methods
|
||||||
}
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(std::format(
|
||||||
|
"ReloadConfig command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
bool requiresAdmin() const override {
|
std::string_view getDescription() const override
|
||||||
return true;
|
{
|
||||||
}
|
return "Reloads the bot configuration from file.";
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
CommandCategory getCategory() const override
|
||||||
return {"reloadcfg", "rlcfg"};
|
{
|
||||||
}
|
return CommandCategory::Admin;
|
||||||
};
|
}
|
||||||
|
|
||||||
|
bool requiresAdmin() const override { return true; }
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"reloadcfg", "rlcfg"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -2,71 +2,88 @@
|
|||||||
|
|
||||||
#include "Command.hpp"
|
#include "Command.hpp"
|
||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
|
||||||
#include <charconv>
|
#include <charconv>
|
||||||
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class RemoveCommand : public Command {
|
class RemoveCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ctx.args.empty()) {
|
void execute(const CommandContext& ctx) override
|
||||||
ctx.reply(std::format("Usage: remove <position>\nUse {}queue "
|
{
|
||||||
"to see track positions.",
|
try {
|
||||||
ctx.prefix));
|
auto manager = ctx.musicManager.lock();
|
||||||
return;
|
if (!manager) {
|
||||||
}
|
ctx.reply(
|
||||||
|
"The music service is currently unavailable.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
uint32_t position = 0;
|
if (ctx.args.empty()) {
|
||||||
auto result = std::from_chars(ctx.args.data(),
|
ctx.reply(
|
||||||
ctx.args.data() + ctx.args.size(),
|
std::format("Usage: remove <position>\nUse {}queue "
|
||||||
position);
|
"to see track positions.",
|
||||||
if (result.ec != std::errc() || position == 0) {
|
ctx.prefix));
|
||||||
ctx.reply("Please provide a valid position number (starting from 1).");
|
return;
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
auto remResult = manager->removeFromQueue(position - 1); // Convert to 0-based
|
uint32_t position = 0;
|
||||||
if (!remResult) {
|
auto result =
|
||||||
ECHOION_LOG_ERROR(std::format("Remove command failed: {}", remResult.error().message));
|
std::from_chars(ctx.args.data(),
|
||||||
|
ctx.args.data() + ctx.args.size(),
|
||||||
if (remResult.error().code == Api::ErrorCode::NotFound) {
|
position);
|
||||||
ctx.reply("That position doesn't exist in the queue.");
|
if (result.ec != std::errc() || position == 0) {
|
||||||
} else {
|
ctx.reply("Please provide a valid position number "
|
||||||
ctx.reply("Couldn't remove that track. Please try again.");
|
"(starting from 1).");
|
||||||
}
|
return;
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
ctx.reply(std::format("Removed track at position {}.", position));
|
auto remResult = manager->removeFromQueue(
|
||||||
} catch (const std::exception& e) {
|
position - 1); // Convert to 0-based
|
||||||
ECHOION_LOG_ERROR(std::format("Remove command exception: {}", e.what()));
|
if (!remResult) {
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
ECHOION_LOG_ERROR(
|
||||||
}
|
std::format("Remove command failed: {}",
|
||||||
}
|
remResult.error().message));
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
if (remResult.error().code ==
|
||||||
return "Removes a track from the queue by position.";
|
Api::ErrorCode::NotFound) {
|
||||||
}
|
ctx.reply(
|
||||||
|
"That position doesn't exist in the queue.");
|
||||||
|
} else {
|
||||||
|
ctx.reply("Couldn't remove that track. Please try "
|
||||||
|
"again.");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
std::string_view getUsage() const override {
|
ctx.reply(
|
||||||
return "<position>";
|
std::format("Removed track at position {}.", position));
|
||||||
}
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Remove command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
std::string_view getDescription() const override
|
||||||
return CommandCategory::Queue;
|
{
|
||||||
}
|
return "Removes a track from the queue by position.";
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
std::string_view getUsage() const override { return "<position>"; }
|
||||||
return {"rm", "delete", "del"};
|
|
||||||
}
|
CommandCategory getCategory() const override
|
||||||
};
|
{
|
||||||
|
return CommandCategory::Queue;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"rm", "delete", "del"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -4,43 +4,55 @@
|
|||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class RepeatCommand : public Command {
|
class RepeatCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto result = manager->toggleRepeat();
|
void execute(const CommandContext& ctx) override
|
||||||
if (!result) {
|
{
|
||||||
ECHOION_LOG_ERROR(std::format("Repeat command failed: {}", result.error().message));
|
try {
|
||||||
ctx.reply("Couldn't toggle repeat. Please try again.");
|
auto manager = ctx.musicManager.lock();
|
||||||
return;
|
if (!manager) {
|
||||||
}
|
ctx.reply(
|
||||||
|
"The music service is currently unavailable.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
ctx.reply(*result ? "\xf0\x9f\x94\x81 Repeat is now ON." : "Repeat is now OFF.");
|
auto result = manager->toggleRepeat();
|
||||||
} catch (const std::exception& e) {
|
if (!result) {
|
||||||
ECHOION_LOG_ERROR(std::format("Repeat command exception: {}", e.what()));
|
ECHOION_LOG_ERROR(
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
std::format("Repeat command failed: {}",
|
||||||
}
|
result.error().message));
|
||||||
}
|
ctx.reply("Couldn't toggle repeat. Please try again.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
ctx.reply(*result ? "\xf0\x9f\x94\x81 Repeat is now ON."
|
||||||
return "Toggles repeat mode for the current track.";
|
: "Repeat is now OFF.");
|
||||||
}
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Repeat command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
std::string_view getDescription() const override
|
||||||
return CommandCategory::Playback;
|
{
|
||||||
}
|
return "Toggles repeat mode for the current track.";
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
CommandCategory getCategory() const override
|
||||||
return {"loop"};
|
{
|
||||||
}
|
return CommandCategory::Playback;
|
||||||
};
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"loop"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -4,48 +4,61 @@
|
|||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class ResumeCommand : public Command {
|
class ResumeCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto result = manager->resume();
|
void execute(const CommandContext& ctx) override
|
||||||
if (!result) {
|
{
|
||||||
ECHOION_LOG_ERROR(std::format("Resume command failed: {}", result.error().message));
|
try {
|
||||||
|
auto manager = ctx.musicManager.lock();
|
||||||
if (result.error().code == Api::ErrorCode::InvalidArgument) {
|
if (!manager) {
|
||||||
ctx.reply("Playback isn't paused right now.");
|
ctx.reply(
|
||||||
} else {
|
"The music service is currently unavailable.");
|
||||||
ctx.reply("Couldn't resume playback. Please try again.");
|
return;
|
||||||
}
|
}
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.reply("Playback resumed.");
|
auto result = manager->resume();
|
||||||
} catch (const std::exception& e) {
|
if (!result) {
|
||||||
ECHOION_LOG_ERROR(std::format("Resume command exception: {}", e.what()));
|
ECHOION_LOG_ERROR(
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
std::format("Resume command failed: {}",
|
||||||
}
|
result.error().message));
|
||||||
}
|
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
if (result.error().code ==
|
||||||
return "Resumes the paused playback.";
|
Api::ErrorCode::InvalidArgument) {
|
||||||
}
|
ctx.reply("Playback isn't paused right now.");
|
||||||
|
} else {
|
||||||
|
ctx.reply(
|
||||||
|
"Couldn't resume playback. Please try again.");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
ctx.reply("Playback resumed.");
|
||||||
return CommandCategory::Playback;
|
} catch (const std::exception& e) {
|
||||||
}
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Resume command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
std::string_view getDescription() const override
|
||||||
return {"unpause", "continue"};
|
{
|
||||||
}
|
return "Resumes the paused playback.";
|
||||||
};
|
}
|
||||||
|
|
||||||
|
CommandCategory getCategory() const override
|
||||||
|
{
|
||||||
|
return CommandCategory::Playback;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"unpause", "continue"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "Command.hpp"
|
||||||
|
|
||||||
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
|
class RpcInfoCommand : public Command
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
void execute(const CommandContext& ctx) override;
|
||||||
|
std::string_view getDescription() const override
|
||||||
|
{
|
||||||
|
return "Get RPC server connection information";
|
||||||
|
}
|
||||||
|
std::string_view getUsage() const override { return ""; }
|
||||||
|
CommandCategory getCategory() const override
|
||||||
|
{
|
||||||
|
return CommandCategory::Utility;
|
||||||
|
}
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"rpc", "api", "remote"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Echoion::Core
|
||||||
@@ -5,110 +5,126 @@
|
|||||||
#include <format>
|
#include <format>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class SearchCommand : public Command {
|
class SearchCommand : public Command
|
||||||
public:
|
|
||||||
void execute(const CommandContext& ctx) override {
|
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ctx.args.empty()) {
|
|
||||||
ctx.reply("Usage: search <query>\nExample: search never gonna give you up");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto result = manager->search(ctx.args);
|
|
||||||
if (!result) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("Search failed for '{}': {}",
|
|
||||||
ctx.args, result.error().message));
|
|
||||||
|
|
||||||
if (result.error().code == Api::ErrorCode::NetworkError) {
|
|
||||||
ctx.reply("Couldn't connect to search service. Please check your connection.");
|
|
||||||
} else {
|
|
||||||
ctx.reply("Search failed. Please try again later.");
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result->tracks.empty()) {
|
|
||||||
ctx.reply("No results found. Try different keywords.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store results for this client so they can use select
|
|
||||||
manager->storePendingSearch(ctx.clientId, result->tracks);
|
|
||||||
|
|
||||||
std::stringstream msg;
|
|
||||||
msg << "\xf0\x9f\x94\x8d Search results for \"" << ctx.args << "\":\n\n";
|
|
||||||
|
|
||||||
for (size_t i = 0; i < result->tracks.size() && i < 5; ++i) {
|
|
||||||
const auto& track = result->tracks[i];
|
|
||||||
// Format as [Title by Artist](shortenedUrl) with duration
|
|
||||||
std::string displayText = track.title;
|
|
||||||
if (!track.artist.empty()) {
|
|
||||||
displayText =
|
|
||||||
std::format("{} by {}", track.title, track.artist);
|
|
||||||
}
|
|
||||||
std::string linkText =
|
|
||||||
track.shortenedUrl.has_value() &&
|
|
||||||
!track.shortenedUrl->empty()
|
|
||||||
? std::format("[{}]({})", displayText,
|
|
||||||
*track.shortenedUrl)
|
|
||||||
: displayText;
|
|
||||||
msg << std::format("{}. {}", i + 1, linkText);
|
|
||||||
if (track.duration.has_value()) {
|
|
||||||
msg << std::format(" [{}]",
|
|
||||||
formatDuration(*track.duration));
|
|
||||||
}
|
|
||||||
msg << "\n";
|
|
||||||
}
|
|
||||||
|
|
||||||
msg << std::format("\nUse {}select <number> to play a result.",
|
|
||||||
ctx.prefix);
|
|
||||||
|
|
||||||
ctx.reply(msg.str());
|
|
||||||
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("Search command exception: {}", e.what()));
|
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
|
||||||
return "Searches for tracks and shows results.";
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string_view getUsage() const override {
|
|
||||||
return "<query>";
|
|
||||||
}
|
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
|
||||||
return CommandCategory::Music;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
|
||||||
return {"find", "s"};
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
|
|
||||||
static std::string formatDuration(std::chrono::milliseconds duration)
|
|
||||||
{
|
{
|
||||||
auto totalSeconds = duration.count() / 1000;
|
public:
|
||||||
auto hours = totalSeconds / 3600;
|
|
||||||
auto mins = (totalSeconds % 3600) / 60;
|
|
||||||
auto secs = totalSeconds % 60;
|
|
||||||
|
|
||||||
if (hours > 0) {
|
void execute(const CommandContext& ctx) override
|
||||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
{
|
||||||
}
|
try {
|
||||||
return std::format("{}:{:02}", mins, secs);
|
auto manager = ctx.musicManager.lock();
|
||||||
}
|
if (!manager) {
|
||||||
};
|
ctx.reply(
|
||||||
|
"The music service is currently unavailable.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ctx.args.empty()) {
|
||||||
|
ctx.reply("Usage: search <query>\nExample: search "
|
||||||
|
"never gonna give you up");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto result = manager->search(ctx.args);
|
||||||
|
if (!result) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Search failed for '{}': {}", ctx.args,
|
||||||
|
result.error().message));
|
||||||
|
|
||||||
|
if (result.error().code ==
|
||||||
|
Api::ErrorCode::NetworkError) {
|
||||||
|
ctx.reply("Couldn't connect to search service. "
|
||||||
|
"Please check your connection.");
|
||||||
|
} else {
|
||||||
|
ctx.reply("Search failed. Please try again later.");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result->tracks.empty()) {
|
||||||
|
ctx.reply("No results found. Try different keywords.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store results for this client so they can use select
|
||||||
|
manager->storePendingSearch(ctx.clientId, result->tracks);
|
||||||
|
|
||||||
|
std::stringstream msg;
|
||||||
|
msg << "\xf0\x9f\x94\x8d Search results for \"" << ctx.args
|
||||||
|
<< "\":\n\n";
|
||||||
|
|
||||||
|
for (size_t i = 0; i < result->tracks.size() && i < 5;
|
||||||
|
++i) {
|
||||||
|
const auto& track = result->tracks[i];
|
||||||
|
// Format as [Title by Artist](shortenedUrl) with
|
||||||
|
// duration
|
||||||
|
std::string displayText = track.title;
|
||||||
|
if (!track.artist.empty()) {
|
||||||
|
displayText = std::format("{} by {}", track.title,
|
||||||
|
track.artist);
|
||||||
|
}
|
||||||
|
std::string linkText =
|
||||||
|
track.shortenedUrl.has_value() &&
|
||||||
|
!track.shortenedUrl->empty()
|
||||||
|
? std::format("[{}]({})", displayText,
|
||||||
|
*track.shortenedUrl)
|
||||||
|
: displayText;
|
||||||
|
msg << std::format("{}. {}", i + 1, linkText);
|
||||||
|
if (track.duration.has_value()) {
|
||||||
|
msg << std::format(" [{}]",
|
||||||
|
formatDuration(*track.duration));
|
||||||
|
}
|
||||||
|
msg << "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
msg << std::format(
|
||||||
|
"\nUse {}select <number> to play a result.",
|
||||||
|
ctx.prefix);
|
||||||
|
|
||||||
|
ctx.reply(msg.str());
|
||||||
|
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Search command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string_view getDescription() const override
|
||||||
|
{
|
||||||
|
return "Searches for tracks and shows results.";
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string_view getUsage() const override { return "<query>"; }
|
||||||
|
|
||||||
|
CommandCategory getCategory() const override
|
||||||
|
{
|
||||||
|
return CommandCategory::Music;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"find", "s"};
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
static std::string
|
||||||
|
formatDuration(std::chrono::milliseconds duration)
|
||||||
|
{
|
||||||
|
auto totalSeconds = duration.count() / 1000;
|
||||||
|
auto hours = totalSeconds / 3600;
|
||||||
|
auto mins = (totalSeconds % 3600) / 60;
|
||||||
|
auto secs = totalSeconds % 60;
|
||||||
|
|
||||||
|
if (hours > 0) {
|
||||||
|
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||||
|
}
|
||||||
|
return std::format("{}:{:02}", mins, secs);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -2,123 +2,147 @@
|
|||||||
|
|
||||||
#include "Command.hpp"
|
#include "Command.hpp"
|
||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
|
||||||
#include <chrono>
|
|
||||||
#include <charconv>
|
#include <charconv>
|
||||||
|
#include <chrono>
|
||||||
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class SeekCommand : public Command {
|
class SeekCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ctx.args.empty()) {
|
void execute(const CommandContext& ctx) override
|
||||||
ctx.reply("Usage: seek <+/-seconds>\nExamples:\n seek +30 (skip forward 30s)\n seek -10 (skip back 10s)\n seek 60 (jump to 1 minute mark)");
|
{
|
||||||
return;
|
try {
|
||||||
}
|
auto manager = ctx.musicManager.lock();
|
||||||
|
if (!manager) {
|
||||||
|
ctx.reply(
|
||||||
|
"The music service is currently unavailable.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Parse the seek argument (supports +30, -10, or absolute 60)
|
if (ctx.args.empty()) {
|
||||||
std::string_view arg = ctx.args;
|
ctx.reply(
|
||||||
bool relative = false;
|
"Usage: seek <+/-seconds>\nExamples:\n seek +30 "
|
||||||
bool forward = true;
|
"(skip forward 30s)\n seek -10 (skip back 10s)\n "
|
||||||
|
"seek 60 (jump to 1 minute mark)");
|
||||||
if (arg.starts_with('+')) {
|
return;
|
||||||
relative = true;
|
}
|
||||||
forward = true;
|
|
||||||
arg = arg.substr(1);
|
|
||||||
} else if (arg.starts_with('-')) {
|
|
||||||
relative = true;
|
|
||||||
forward = false;
|
|
||||||
arg = arg.substr(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
int seconds = 0;
|
// Parse the seek argument (supports +30, -10, or absolute
|
||||||
auto parseResult = std::from_chars(arg.data(),
|
// 60)
|
||||||
arg.data() + arg.size(),
|
std::string_view arg = ctx.args;
|
||||||
seconds);
|
bool relative = false;
|
||||||
if (parseResult.ec != std::errc() || seconds < 0) {
|
bool forward = true;
|
||||||
ctx.reply("Please provide a valid number of seconds.\nExamples: seek +30, seek -10, seek 60");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::chrono::milliseconds targetPosition;
|
if (arg.starts_with('+')) {
|
||||||
std::string positionStr;
|
relative = true;
|
||||||
|
forward = true;
|
||||||
|
arg = arg.substr(1);
|
||||||
|
} else if (arg.starts_with('-')) {
|
||||||
|
relative = true;
|
||||||
|
forward = false;
|
||||||
|
arg = arg.substr(1);
|
||||||
|
}
|
||||||
|
|
||||||
if (relative) {
|
int seconds = 0;
|
||||||
// Get current position from playback state
|
auto parseResult = std::from_chars(
|
||||||
auto state = manager->getPlaybackState();
|
arg.data(), arg.data() + arg.size(), seconds);
|
||||||
if (!state) {
|
if (parseResult.ec != std::errc() || seconds < 0) {
|
||||||
ctx.reply("Unable to get current playback position.");
|
ctx.reply(
|
||||||
return;
|
"Please provide a valid number of "
|
||||||
}
|
"seconds.\nExamples: seek +30, seek -10, seek 60");
|
||||||
|
return;
|
||||||
auto currentPos = state->position;
|
}
|
||||||
if (forward) {
|
|
||||||
targetPosition = currentPos + std::chrono::seconds(seconds);
|
|
||||||
positionStr = std::format("+{}s", seconds);
|
|
||||||
} else {
|
|
||||||
// Seek backward
|
|
||||||
if (currentPos.count() < seconds * 1000) {
|
|
||||||
targetPosition = std::chrono::milliseconds(0);
|
|
||||||
} else {
|
|
||||||
targetPosition = currentPos - std::chrono::seconds(seconds);
|
|
||||||
}
|
|
||||||
positionStr = std::format("-{}s", seconds);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Absolute seek (legacy behavior)
|
|
||||||
targetPosition = std::chrono::seconds(seconds);
|
|
||||||
auto mins = seconds / 60;
|
|
||||||
auto secs = seconds % 60;
|
|
||||||
positionStr = std::format("{}:{:02}", mins, secs);
|
|
||||||
}
|
|
||||||
|
|
||||||
auto result = manager->seek(targetPosition);
|
std::chrono::milliseconds targetPosition;
|
||||||
if (!result) {
|
std::string positionStr;
|
||||||
ECHOION_LOG_ERROR(std::format("Seek command failed: {}", result.error().message));
|
|
||||||
|
|
||||||
if (result.error().code == Api::ErrorCode::InvalidArgument) {
|
|
||||||
ctx.reply("Nothing is playing right now.");
|
|
||||||
} else if (result.error().code == Api::ErrorCode::NotSupported) {
|
|
||||||
ctx.reply("This track doesn't support seeking.");
|
|
||||||
} else {
|
|
||||||
ctx.reply("Couldn't seek. Please try again.");
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (relative) {
|
if (relative) {
|
||||||
ctx.reply(std::format("Seeked {} from current position.", positionStr));
|
// Get current position from playback state
|
||||||
} else {
|
auto state = manager->getPlaybackState();
|
||||||
ctx.reply(std::format("Seeked to position {}.", positionStr));
|
if (!state) {
|
||||||
}
|
ctx.reply(
|
||||||
} catch (const std::exception& e) {
|
"Unable to get current playback position.");
|
||||||
ECHOION_LOG_ERROR(std::format("Seek command exception: {}", e.what()));
|
return;
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
auto currentPos = state->position;
|
||||||
return "Seeks to a position in the current track. Use +seconds to skip forward, -seconds to skip backward.";
|
if (forward) {
|
||||||
}
|
targetPosition =
|
||||||
|
currentPos + std::chrono::seconds(seconds);
|
||||||
|
positionStr = std::format("+{}s", seconds);
|
||||||
|
} else {
|
||||||
|
// Seek backward
|
||||||
|
if (currentPos.count() < seconds * 1000) {
|
||||||
|
targetPosition = std::chrono::milliseconds(0);
|
||||||
|
} else {
|
||||||
|
targetPosition =
|
||||||
|
currentPos - std::chrono::seconds(seconds);
|
||||||
|
}
|
||||||
|
positionStr = std::format("-{}s", seconds);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Absolute seek (legacy behavior)
|
||||||
|
targetPosition = std::chrono::seconds(seconds);
|
||||||
|
auto mins = seconds / 60;
|
||||||
|
auto secs = seconds % 60;
|
||||||
|
positionStr = std::format("{}:{:02}", mins, secs);
|
||||||
|
}
|
||||||
|
|
||||||
std::string_view getUsage() const override {
|
auto result = manager->seek(targetPosition);
|
||||||
return "<+/-seconds>";
|
if (!result) {
|
||||||
}
|
ECHOION_LOG_ERROR(std::format("Seek command failed: {}",
|
||||||
|
result.error().message));
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
if (result.error().code ==
|
||||||
return CommandCategory::Playback;
|
Api::ErrorCode::InvalidArgument) {
|
||||||
}
|
ctx.reply("Nothing is playing right now.");
|
||||||
|
} else if (result.error().code ==
|
||||||
|
Api::ErrorCode::NotSupported) {
|
||||||
|
ctx.reply("This track doesn't support seeking.");
|
||||||
|
} else {
|
||||||
|
ctx.reply("Couldn't seek. Please try again.");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
if (relative) {
|
||||||
return {"jump"};
|
ctx.reply(std::format(
|
||||||
}
|
"Seeked {} from current position.", positionStr));
|
||||||
};
|
} else {
|
||||||
|
ctx.reply(
|
||||||
|
std::format("Seeked to position {}.", positionStr));
|
||||||
|
}
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Seek command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string_view getDescription() const override
|
||||||
|
{
|
||||||
|
return "Seeks to a position in the current track. Use +seconds "
|
||||||
|
"to skip forward, -seconds to skip backward.";
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string_view getUsage() const override
|
||||||
|
{
|
||||||
|
return "<+/-seconds>";
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandCategory getCategory() const override
|
||||||
|
{
|
||||||
|
return CommandCategory::Playback;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"jump"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -2,76 +2,91 @@
|
|||||||
|
|
||||||
#include "Command.hpp"
|
#include "Command.hpp"
|
||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
|
||||||
#include <charconv>
|
#include <charconv>
|
||||||
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class SelectCommand : public Command {
|
class SelectCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ctx.args.empty()) {
|
void execute(const CommandContext& ctx) override
|
||||||
ctx.reply("Usage: select <number>\nSelect a track from your last search results.");
|
{
|
||||||
return;
|
try {
|
||||||
}
|
auto manager = ctx.musicManager.lock();
|
||||||
|
if (!manager) {
|
||||||
|
ctx.reply(
|
||||||
|
"The music service is currently unavailable.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Parse index
|
if (ctx.args.empty()) {
|
||||||
uint32_t index = 0;
|
ctx.reply("Usage: select <number>\nSelect a track from "
|
||||||
auto result = std::from_chars(ctx.args.data(),
|
"your last search results.");
|
||||||
ctx.args.data() + ctx.args.size(),
|
return;
|
||||||
index);
|
}
|
||||||
if (result.ec != std::errc() || index == 0) {
|
|
||||||
ctx.reply("Please provide a valid number (1, 2, 3, etc.).");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string invokerName(ctx.invokerName);
|
// Parse index
|
||||||
auto selectResult = manager->selectSearchResult(ctx.clientId, index, invokerName);
|
uint32_t index = 0;
|
||||||
|
auto result =
|
||||||
if (!selectResult) {
|
std::from_chars(ctx.args.data(),
|
||||||
ECHOION_LOG_ERROR(std::format("Select failed for client {} index {}: {}",
|
ctx.args.data() + ctx.args.size(),
|
||||||
ctx.clientId, index, selectResult.error().message));
|
index);
|
||||||
|
if (result.ec != std::errc() || index == 0) {
|
||||||
if (selectResult.error().code == Api::ErrorCode::NotFound) {
|
ctx.reply(
|
||||||
ctx.reply(std::format("No search results found. Use {}play "
|
"Please provide a valid number (1, 2, 3, etc.).");
|
||||||
"<query> to search first.",
|
return;
|
||||||
ctx.prefix));
|
}
|
||||||
} else {
|
|
||||||
ctx.reply("Couldn't select that track. Please try again.");
|
std::string invokerName(ctx.invokerName);
|
||||||
|
auto selectResult = manager->selectSearchResult(
|
||||||
|
ctx.clientId, index, invokerName);
|
||||||
|
|
||||||
|
if (!selectResult) {
|
||||||
|
ECHOION_LOG_ERROR(std::format(
|
||||||
|
"Select failed for client {} index {}: {}",
|
||||||
|
ctx.clientId, index, selectResult.error().message));
|
||||||
|
|
||||||
|
if (selectResult.error().code ==
|
||||||
|
Api::ErrorCode::NotFound) {
|
||||||
|
ctx.reply(std::format(
|
||||||
|
"No search results found. Use {}play "
|
||||||
|
"<query> to search first.",
|
||||||
|
ctx.prefix));
|
||||||
|
} else {
|
||||||
|
ctx.reply("Couldn't select that track. Please try "
|
||||||
|
"again.");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.reply(*selectResult);
|
||||||
|
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Select command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
}
|
}
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
ctx.reply(*selectResult);
|
std::string_view getDescription() const override
|
||||||
|
{
|
||||||
|
return "Selects a track from your search results.";
|
||||||
|
}
|
||||||
|
|
||||||
} catch (const std::exception& e) {
|
std::string_view getUsage() const override { return "<number>"; }
|
||||||
ECHOION_LOG_ERROR(std::format("Select command exception: {}", e.what()));
|
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
CommandCategory getCategory() const override
|
||||||
return "Selects a track from your search results.";
|
{
|
||||||
}
|
return CommandCategory::Music;
|
||||||
|
}
|
||||||
|
|
||||||
std::string_view getUsage() const override {
|
std::vector<std::string_view> getAliases() const override
|
||||||
return "<number>";
|
{
|
||||||
}
|
return {"sel", "pick", "choose"};
|
||||||
|
}
|
||||||
CommandCategory getCategory() const override {
|
};
|
||||||
return CommandCategory::Music;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
|
||||||
return {"sel", "pick", "choose"};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -4,43 +4,48 @@
|
|||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class ShuffleCommand : public Command {
|
class ShuffleCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto result = manager->toggleShuffle();
|
void execute(const CommandContext& ctx) override
|
||||||
if (!result) {
|
{
|
||||||
ECHOION_LOG_ERROR(std::format("Shuffle command failed: {}", result.error().message));
|
try {
|
||||||
ctx.reply("Couldn't toggle shuffle. Please try again.");
|
auto manager = ctx.musicManager.lock();
|
||||||
return;
|
if (!manager) {
|
||||||
}
|
ctx.reply(
|
||||||
|
"The music service is currently unavailable.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
ctx.reply(*result ? "\xf0\x9f\x94\x80 Shuffle is now ON." : "Shuffle is now OFF.");
|
// Actually shuffle the queue (not just toggle mode)
|
||||||
} catch (const std::exception& e) {
|
manager->shuffleQueue();
|
||||||
ECHOION_LOG_ERROR(std::format("Shuffle command exception: {}", e.what()));
|
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
ctx.reply("\xf0\x9f\x94\x80 Queue shuffled!");
|
||||||
return "Toggles shuffle mode for the queue.";
|
} catch (const std::exception& e) {
|
||||||
}
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Shuffle command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
std::string_view getDescription() const override
|
||||||
return CommandCategory::Queue;
|
{
|
||||||
}
|
return "Toggles shuffle mode for the queue.";
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
CommandCategory getCategory() const override
|
||||||
return {"random"};
|
{
|
||||||
}
|
return CommandCategory::Queue;
|
||||||
};
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"random"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -2,70 +2,81 @@
|
|||||||
|
|
||||||
#include "Command.hpp"
|
#include "Command.hpp"
|
||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
|
||||||
#include <charconv>
|
#include <charconv>
|
||||||
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class SkipCommand : public Command {
|
class SkipCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
uint32_t count = 1;
|
void execute(const CommandContext& ctx) override
|
||||||
if (!ctx.args.empty()) {
|
{
|
||||||
auto result = std::from_chars(ctx.args.data(),
|
try {
|
||||||
ctx.args.data() + ctx.args.size(),
|
auto manager = ctx.musicManager.lock();
|
||||||
count);
|
if (!manager) {
|
||||||
if (result.ec != std::errc() || count == 0) {
|
ctx.reply(
|
||||||
ctx.reply("Please provide a valid number (1 or more).");
|
"The music service is currently unavailable.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
auto result = manager->skip(count);
|
uint32_t count = 1;
|
||||||
if (!result) {
|
if (!ctx.args.empty()) {
|
||||||
ECHOION_LOG_ERROR(std::format("Skip command failed: {}", result.error().message));
|
auto result =
|
||||||
|
std::from_chars(ctx.args.data(),
|
||||||
if (result.error().code == Api::ErrorCode::NotFound) {
|
ctx.args.data() + ctx.args.size(),
|
||||||
ctx.reply("No more tracks in the queue to skip to.");
|
count);
|
||||||
} else {
|
if (result.ec != std::errc() || count == 0) {
|
||||||
ctx.reply("Couldn't skip. Please try again.");
|
ctx.reply(
|
||||||
}
|
"Please provide a valid number (1 or more).");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (count == 1) {
|
auto result = manager->skip(count);
|
||||||
ctx.reply("Skipped to next track.");
|
if (!result) {
|
||||||
} else {
|
ECHOION_LOG_ERROR(std::format("Skip command failed: {}",
|
||||||
ctx.reply(std::format("Skipped {} tracks.", count));
|
result.error().message));
|
||||||
}
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("Skip command exception: {}", e.what()));
|
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
if (result.error().code == Api::ErrorCode::NotFound) {
|
||||||
return "Skips to the next track(s).";
|
ctx.reply(
|
||||||
}
|
"No more tracks in the queue to skip to.");
|
||||||
|
} else {
|
||||||
|
ctx.reply("Couldn't skip. Please try again.");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
std::string_view getUsage() const override {
|
if (count == 1) {
|
||||||
return "[count]";
|
ctx.reply("Skipped to next track.");
|
||||||
}
|
} else {
|
||||||
|
ctx.reply(std::format("Skipped {} tracks.", count));
|
||||||
|
}
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Skip command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
std::string_view getDescription() const override
|
||||||
return CommandCategory::Playback;
|
{
|
||||||
}
|
return "Skips to the next track(s).";
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
std::string_view getUsage() const override { return "[count]"; }
|
||||||
return {"next", "n"};
|
|
||||||
}
|
CommandCategory getCategory() const override
|
||||||
};
|
{
|
||||||
|
return CommandCategory::Playback;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"next", "n"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -4,43 +4,53 @@
|
|||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class StopCommand : public Command {
|
class StopCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto result = manager->stop();
|
void execute(const CommandContext& ctx) override
|
||||||
if (!result) {
|
{
|
||||||
ECHOION_LOG_ERROR(std::format("Stop command failed: {}", result.error().message));
|
try {
|
||||||
ctx.reply("Couldn't stop playback. Please try again.");
|
auto manager = ctx.musicManager.lock();
|
||||||
return;
|
if (!manager) {
|
||||||
}
|
ctx.reply(
|
||||||
|
"The music service is currently unavailable.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
ctx.reply("Playback stopped and queue cleared.");
|
auto result = manager->stop();
|
||||||
} catch (const std::exception& e) {
|
if (!result) {
|
||||||
ECHOION_LOG_ERROR(std::format("Stop command exception: {}", e.what()));
|
ECHOION_LOG_ERROR(std::format("Stop command failed: {}",
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
result.error().message));
|
||||||
}
|
ctx.reply("Couldn't stop playback. Please try again.");
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
ctx.reply("Playback stopped and queue cleared.");
|
||||||
return "Stops playback and clears the queue.";
|
} catch (const std::exception& e) {
|
||||||
}
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Stop command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
std::string_view getDescription() const override
|
||||||
return CommandCategory::Playback;
|
{
|
||||||
}
|
return "Stops playback and clears the queue.";
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
CommandCategory getCategory() const override
|
||||||
return {"s"};
|
{
|
||||||
}
|
return CommandCategory::Playback;
|
||||||
};
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"s"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -4,43 +4,53 @@
|
|||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class SubscribeCommand : public Command {
|
class SubscribeCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto result = manager->subscribe(ctx.clientId);
|
void execute(const CommandContext& ctx) override
|
||||||
if (!result) {
|
{
|
||||||
ECHOION_LOG_ERROR(std::format("Subscribe failed: {}", result.error().message));
|
try {
|
||||||
ctx.reply("Couldn't subscribe you. Please try again.");
|
auto manager = ctx.musicManager.lock();
|
||||||
return;
|
if (!manager) {
|
||||||
}
|
ctx.reply(
|
||||||
|
"The music service is currently unavailable.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
ctx.reply(*result);
|
auto result = manager->subscribe(ctx.clientId);
|
||||||
} catch (const std::exception& e) {
|
if (!result) {
|
||||||
ECHOION_LOG_ERROR(std::format("Subscribe command exception: {}", e.what()));
|
ECHOION_LOG_ERROR(std::format("Subscribe failed: {}",
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
result.error().message));
|
||||||
}
|
ctx.reply("Couldn't subscribe you. Please try again.");
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
ctx.reply(*result);
|
||||||
return "Subscribes to the music bot to receive audio.";
|
} catch (const std::exception& e) {
|
||||||
}
|
ECHOION_LOG_ERROR(std::format(
|
||||||
|
"Subscribe command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
std::string_view getDescription() const override
|
||||||
return CommandCategory::Utility;
|
{
|
||||||
}
|
return "Subscribes to the music bot to receive audio.";
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
CommandCategory getCategory() const override
|
||||||
return {"sub", "join"};
|
{
|
||||||
}
|
return CommandCategory::Utility;
|
||||||
};
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"sub", "join"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -4,43 +4,54 @@
|
|||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class UnsubscribeCommand : public Command {
|
class UnsubscribeCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto result = manager->unsubscribe(ctx.clientId);
|
void execute(const CommandContext& ctx) override
|
||||||
if (!result) {
|
{
|
||||||
ECHOION_LOG_ERROR(std::format("Unsubscribe failed: {}", result.error().message));
|
try {
|
||||||
ctx.reply("Couldn't unsubscribe you. Please try again.");
|
auto manager = ctx.musicManager.lock();
|
||||||
return;
|
if (!manager) {
|
||||||
}
|
ctx.reply(
|
||||||
|
"The music service is currently unavailable.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
ctx.reply(*result);
|
auto result = manager->unsubscribe(ctx.clientId);
|
||||||
} catch (const std::exception& e) {
|
if (!result) {
|
||||||
ECHOION_LOG_ERROR(std::format("Unsubscribe command exception: {}", e.what()));
|
ECHOION_LOG_ERROR(std::format("Unsubscribe failed: {}",
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
result.error().message));
|
||||||
}
|
ctx.reply(
|
||||||
}
|
"Couldn't unsubscribe you. Please try again.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
ctx.reply(*result);
|
||||||
return "Unsubscribes from the music bot.";
|
} catch (const std::exception& e) {
|
||||||
}
|
ECHOION_LOG_ERROR(std::format(
|
||||||
|
"Unsubscribe command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
std::string_view getDescription() const override
|
||||||
return CommandCategory::Utility;
|
{
|
||||||
}
|
return "Unsubscribes from the music bot.";
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
CommandCategory getCategory() const override
|
||||||
return {"unsub", "leave"};
|
{
|
||||||
}
|
return CommandCategory::Utility;
|
||||||
};
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"unsub", "leave"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -2,84 +2,100 @@
|
|||||||
|
|
||||||
#include "Command.hpp"
|
#include "Command.hpp"
|
||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <format>
|
|
||||||
#include <charconv>
|
#include <charconv>
|
||||||
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
class VolumeCommand : public Command {
|
class VolumeCommand : public Command
|
||||||
public:
|
{
|
||||||
void execute(const CommandContext& ctx) override {
|
public:
|
||||||
try {
|
|
||||||
auto manager = ctx.musicManager.lock();
|
|
||||||
if (!manager) {
|
|
||||||
ctx.reply("The music service is currently unavailable.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ctx.args.empty()) {
|
void execute(const CommandContext& ctx) override
|
||||||
// Show current volume
|
{
|
||||||
auto state = manager->getPlaybackState();
|
try {
|
||||||
if (state) {
|
auto manager = ctx.musicManager.lock();
|
||||||
ctx.reply(std::format("Current volume: {}%", static_cast<int>(state->volume * 100)));
|
if (!manager) {
|
||||||
} else {
|
ctx.reply(
|
||||||
ctx.reply("Unable to get current volume.");
|
"The music service is currently unavailable.");
|
||||||
}
|
return;
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Parse volume (0-100)
|
if (ctx.args.empty()) {
|
||||||
int volumePercent = 0;
|
// Show current volume
|
||||||
auto result = std::from_chars(ctx.args.data(),
|
auto state = manager->getPlaybackState();
|
||||||
ctx.args.data() + ctx.args.size(),
|
if (state) {
|
||||||
volumePercent);
|
ctx.reply(std::format(
|
||||||
if (result.ec != std::errc()) {
|
"Current volume: {}%",
|
||||||
ctx.reply("Please provide a valid number (0-100).");
|
static_cast<int>(state->volume * 100)));
|
||||||
return;
|
} else {
|
||||||
}
|
ctx.reply("Unable to get current volume.");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (volumePercent < 0 || volumePercent > 100) {
|
// Parse volume (0-100)
|
||||||
ctx.reply("Volume must be between 0 and 100.");
|
int volumePercent = 0;
|
||||||
return;
|
auto result =
|
||||||
}
|
std::from_chars(ctx.args.data(),
|
||||||
|
ctx.args.data() + ctx.args.size(),
|
||||||
|
volumePercent);
|
||||||
|
if (result.ec != std::errc()) {
|
||||||
|
ctx.reply("Please provide a valid number (0-100).");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
float volume = volumePercent / 100.0f;
|
if (volumePercent < 0 || volumePercent > 100) {
|
||||||
auto volResult = manager->setVolume(volume);
|
ctx.reply("Volume must be between 0 and 100.");
|
||||||
if (!volResult) {
|
return;
|
||||||
ECHOION_LOG_ERROR(std::format("Volume command failed: {}", volResult.error().message));
|
}
|
||||||
ctx.reply("Couldn't change volume. Please try again.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Visual volume indicator
|
float volume = volumePercent / 100.0f;
|
||||||
std::string indicator;
|
auto volResult = manager->setVolume(volume);
|
||||||
int bars = volumePercent / 10;
|
if (!volResult) {
|
||||||
for (int i = 0; i < 10; ++i) {
|
ECHOION_LOG_ERROR(
|
||||||
indicator += (i < bars) ? "\xe2\x96\x88" : "\xe2\x96\x91"; // Full block / Light shade
|
std::format("Volume command failed: {}",
|
||||||
}
|
volResult.error().message));
|
||||||
|
ctx.reply("Couldn't change volume. Please try again.");
|
||||||
ctx.reply(std::format("Volume: {}% {}", volumePercent, indicator));
|
return;
|
||||||
} catch (const std::exception& e) {
|
}
|
||||||
ECHOION_LOG_ERROR(std::format("Volume command exception: {}", e.what()));
|
|
||||||
ctx.reply("Something went wrong. Please try again.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
// Visual volume indicator
|
||||||
return "Sets or shows the playback volume.";
|
std::string indicator;
|
||||||
}
|
int bars = volumePercent / 10;
|
||||||
|
for (int i = 0; i < 10; ++i) {
|
||||||
|
indicator +=
|
||||||
|
(i < bars)
|
||||||
|
? "\xe2\x96\x88"
|
||||||
|
: "\xe2\x96\x91"; // Full block / Light shade
|
||||||
|
}
|
||||||
|
|
||||||
std::string_view getUsage() const override {
|
ctx.reply(std::format(
|
||||||
return "[0-100]";
|
"Volume: {}% {}", volumePercent, indicator));
|
||||||
}
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Volume command exception: {}", e.what()));
|
||||||
|
ctx.reply("Something went wrong. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
CommandCategory getCategory() const override {
|
std::string_view getDescription() const override
|
||||||
return CommandCategory::Playback;
|
{
|
||||||
}
|
return "Sets or shows the playback volume.";
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
std::string_view getUsage() const override { return "[0-100]"; }
|
||||||
return {"vol", "v"};
|
|
||||||
}
|
CommandCategory getCategory() const override
|
||||||
};
|
{
|
||||||
|
return CommandCategory::Playback;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string_view> getAliases() const override
|
||||||
|
{
|
||||||
|
return {"vol", "v"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
#pragma once
|
||||||
|
#include "Types.hpp"
|
||||||
|
#include "echoion/core/state/StateVersions.hpp"
|
||||||
|
#include <cstdint>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
|
// Handles migration between state versions
|
||||||
|
class StateMigration
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
// Migrate from any old version to current
|
||||||
|
static Api::Result<StateV1> migrate(uint32_t fromVersion,
|
||||||
|
const std::string& jsonData);
|
||||||
|
|
||||||
|
// Specific migrations
|
||||||
|
static StateV1 fromV0(const StateV0& v0);
|
||||||
|
|
||||||
|
// Check if migration path exists
|
||||||
|
static bool canMigrate(uint32_t fromVersion);
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
// Migration chain: V0 -> V1 -> V2 -> ...
|
||||||
|
// Each version only knows how to migrate from previous
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Echoion::Core
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
#pragma once
|
||||||
|
#include "StateBlob.hpp"
|
||||||
|
#include "echoion/core/state/StateVersions.hpp"
|
||||||
|
#include <Types.hpp>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
|
class StateSerializer
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
// Current version being used
|
||||||
|
static constexpr uint32_t CURRENT_VERSION = 1;
|
||||||
|
|
||||||
|
// Serialize current state to opaque blob
|
||||||
|
static Api::StateBlob serialize(const StateV1& state);
|
||||||
|
|
||||||
|
// Deserialize blob to current version (handles migration)
|
||||||
|
static Api::Result<StateV1> deserialize(const Api::StateBlob& blob);
|
||||||
|
|
||||||
|
// Check if version is supported
|
||||||
|
static bool isVersionSupported(uint32_t version);
|
||||||
|
|
||||||
|
// Get supported version range
|
||||||
|
static uint32_t getMinimumSupportedVersion();
|
||||||
|
static uint32_t getCurrentVersion();
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
// Extract version from JSON blob
|
||||||
|
static uint32_t extractVersion(const std::string& jsonStr);
|
||||||
|
|
||||||
|
// Helper to get current timestamp
|
||||||
|
static std::string getCurrentTimestampISO8601();
|
||||||
|
|
||||||
|
// Make it accessible to StateMigration
|
||||||
|
friend class StateMigration;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Echoion::Core
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
#pragma once
|
||||||
|
#include "TrackTypes.hpp"
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
|
using namespace Echoion::Api;
|
||||||
|
|
||||||
|
// State V0 - Initial version (placeholder for testing migration)
|
||||||
|
struct StateV0 {
|
||||||
|
std::vector<std::string> trackIds;
|
||||||
|
float volume = 0.5f;
|
||||||
|
};
|
||||||
|
|
||||||
|
// State V1 - Current version with full playback state
|
||||||
|
struct StateV1 {
|
||||||
|
// Playback state
|
||||||
|
struct PlaybackState {
|
||||||
|
TrackInfo currentTrack;
|
||||||
|
int64_t positionMs = 0; // Use int64 for JSON compatibility
|
||||||
|
bool isPlaying = false;
|
||||||
|
bool isPaused = false;
|
||||||
|
float volume = 0.5f;
|
||||||
|
bool shuffle = false;
|
||||||
|
bool repeat = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Queue entry with metadata
|
||||||
|
struct QueueEntryState {
|
||||||
|
TrackInfo track;
|
||||||
|
uint64_t queueId = 0;
|
||||||
|
std::string addedBy;
|
||||||
|
std::string addedAt; // ISO 8601
|
||||||
|
};
|
||||||
|
|
||||||
|
// Session state for RPC clients
|
||||||
|
struct SessionState {
|
||||||
|
uint64_t clientId = 0;
|
||||||
|
std::string authToken;
|
||||||
|
std::string lastActivity; // ISO 8601
|
||||||
|
};
|
||||||
|
|
||||||
|
// Main state
|
||||||
|
PlaybackState playback;
|
||||||
|
bool hasPlayback =
|
||||||
|
false; // Flag to indicate if playback state is valid
|
||||||
|
std::vector<QueueEntryState> queue;
|
||||||
|
std::vector<SessionState> sessions;
|
||||||
|
|
||||||
|
// Version info
|
||||||
|
uint32_t version = 1;
|
||||||
|
std::string savedAt; // ISO 8601
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Echoion::Core
|
||||||
|
|
||||||
|
// StateV0/StateV1 (and the nested PlaybackState/QueueEntryState/SessionState)
|
||||||
|
// are plain reflectable aggregates whose member names are the desired JSON
|
||||||
|
// keys, so Void::Json reflection serializes them with no annotations. The only
|
||||||
|
// non-reflectable member is TrackInfo, which supplies its own
|
||||||
|
// to_json()/from_json() in TrackTypes.hpp.
|
||||||
+704
-570
File diff suppressed because it is too large.
Load diff
@@ -1,46 +0,0 @@
|
|||||||
#include "echoion/api/Cache.hpp"
|
|
||||||
#include "echoion/core/Logger.hpp"
|
|
||||||
|
|
||||||
namespace Echoion::Api {
|
|
||||||
|
|
||||||
CacheManager& CacheManager::instance() {
|
|
||||||
static CacheManager instance;
|
|
||||||
return instance;
|
|
||||||
}
|
|
||||||
|
|
||||||
void CacheManager::initialize() {
|
|
||||||
ECHOION_LOG_INFO("CacheManager initialized");
|
|
||||||
}
|
|
||||||
|
|
||||||
void CacheManager::shutdown() {
|
|
||||||
clearAll();
|
|
||||||
ECHOION_LOG_INFO("CacheManager shutdown");
|
|
||||||
}
|
|
||||||
|
|
||||||
void CacheManager::purgeAllExpired() {
|
|
||||||
size_t totalPurged = 0;
|
|
||||||
totalPurged += httpCache_.purgeExpired();
|
|
||||||
totalPurged += trackCache_.purgeExpired();
|
|
||||||
totalPurged += metadataCache_.purgeExpired();
|
|
||||||
|
|
||||||
if (totalPurged > 0) {
|
|
||||||
ECHOION_LOG_INFO(std::format("Purged {} expired cache entries", totalPurged));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void CacheManager::clearAll() {
|
|
||||||
httpCache_.clear();
|
|
||||||
trackCache_.clear();
|
|
||||||
metadataCache_.clear();
|
|
||||||
ECHOION_LOG_INFO("All caches cleared");
|
|
||||||
}
|
|
||||||
|
|
||||||
std::unordered_map<std::string, CacheStats> CacheManager::getAllStats() const {
|
|
||||||
return {
|
|
||||||
{"http", httpCache_.getStats()},
|
|
||||||
{"track", trackCache_.getStats()},
|
|
||||||
{"metadata", metadataCache_.getStats()}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Echoion::Api
|
|
||||||
+478
-430
@@ -1,468 +1,516 @@
|
|||||||
#include "echoion/api/ConfigTypes.hpp"
|
|
||||||
#include "echoion/core/CommandManager.hpp"
|
#include "echoion/core/CommandManager.hpp"
|
||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include "echoion/core/MusicManager.hpp"
|
#include "echoion/core/MusicManager.hpp"
|
||||||
#include "echoion/core/commands/Command.hpp"
|
#include "echoion/core/commands/Command.hpp"
|
||||||
|
#include <ConfigTypes.hpp>
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <echoion/core/commands/Commands.hpp>
|
#include <echoion/core/commands/Commands.hpp>
|
||||||
#include <format>
|
#include <format>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
// --- Internal Help Command ---
|
// --- Internal Help Command ---
|
||||||
class CommandManager::HelpCommand : public Command {
|
class CommandManager::HelpCommand : public Command
|
||||||
CommandManager& manager_;
|
{
|
||||||
|
CommandManager& manager_;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
explicit HelpCommand(CommandManager& mgr) : manager_(mgr) {}
|
|
||||||
|
|
||||||
void execute(const CommandContext& ctx) override {
|
explicit HelpCommand(CommandManager& mgr) : manager_(mgr) {}
|
||||||
try {
|
|
||||||
auto prefix = manager_.getPrefix();
|
|
||||||
|
|
||||||
std::string helpMsg = std::format("\xf0\x9f\x8e\xb5 **Echoion Bot Help**\n\n");
|
|
||||||
helpMsg += std::format("Prefix: `{}`\n\n", prefix);
|
|
||||||
|
|
||||||
// Get commands visible to this client
|
void execute(const CommandContext& ctx) override
|
||||||
auto visibleCommands = manager_.getVisibleCommands(ctx.clientId);
|
{
|
||||||
|
try {
|
||||||
|
auto prefix = manager_.getPrefix();
|
||||||
|
|
||||||
// Group commands by category
|
std::string helpMsg = std::format(
|
||||||
std::map<CommandCategory, std::vector<std::pair<std::string, CommandPtr>>> grouped;
|
"\xf0\x9f\x8e\xb5 **Echoion Bot Help**\n\n");
|
||||||
|
helpMsg += std::format("Prefix: `{}`\n\n", prefix);
|
||||||
for (const auto& [name, cmd] : visibleCommands) {
|
|
||||||
grouped[cmd->getCategory()].push_back({name, cmd});
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const auto& [cat, cmds] : grouped) {
|
// Get commands visible to this client
|
||||||
helpMsg += std::format("**{} Commands**\n", toString(cat));
|
auto visibleCommands =
|
||||||
|
manager_.getVisibleCommands(ctx.clientId);
|
||||||
|
|
||||||
for (const auto& [name, cmd] : cmds) {
|
// Group commands by category
|
||||||
// Format: prefix!command usage
|
std::map<CommandCategory,
|
||||||
if (!cmd->getUsage().empty()) {
|
std::vector<std::pair<std::string, CommandPtr>>>
|
||||||
helpMsg += std::format("`{}{}` {}\n", prefix, name, cmd->getUsage());
|
grouped;
|
||||||
} else {
|
|
||||||
helpMsg += std::format("`{}{}`\n", prefix, name);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Description
|
for (const auto& [name, cmd] : visibleCommands) {
|
||||||
helpMsg += std::format("> {}\n", cmd->getDescription());
|
grouped[cmd->getCategory()].push_back({name, cmd});
|
||||||
|
}
|
||||||
|
|
||||||
// Aliases
|
for (const auto& [cat, cmds] : grouped) {
|
||||||
auto aliases = cmd->getAliases();
|
helpMsg +=
|
||||||
if (!aliases.empty()) {
|
std::format("**{} Commands**\n", toString(cat));
|
||||||
helpMsg += "> Aliases: ";
|
|
||||||
for (size_t i = 0; i < aliases.size(); ++i) {
|
|
||||||
helpMsg += std::format("`{}{}`", prefix, aliases[i]);
|
|
||||||
if (i < aliases.size() - 1) {
|
|
||||||
helpMsg += ", ";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
helpMsg += "\n";
|
|
||||||
}
|
|
||||||
|
|
||||||
helpMsg += "\n";
|
for (const auto& [name, cmd] : cmds) {
|
||||||
}
|
// Format: prefix!command usage
|
||||||
}
|
if (!cmd->getUsage().empty()) {
|
||||||
|
helpMsg += std::format("`{}{}` {}\n",
|
||||||
|
prefix,
|
||||||
|
name,
|
||||||
|
cmd->getUsage());
|
||||||
|
} else {
|
||||||
|
helpMsg +=
|
||||||
|
std::format("`{}{}`\n", prefix, name);
|
||||||
|
}
|
||||||
|
|
||||||
ctx.reply(helpMsg);
|
// Description
|
||||||
} catch (const std::exception& e) {
|
helpMsg +=
|
||||||
ECHOION_LOG_ERROR(std::format("Help command exception: {}", e.what()));
|
std::format("> {}\n", cmd->getDescription());
|
||||||
ctx.reply("Couldn't generate help. Please try again.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string_view getDescription() const override {
|
// Aliases
|
||||||
return "Shows this help message with all available commands.";
|
auto aliases = cmd->getAliases();
|
||||||
}
|
if (!aliases.empty()) {
|
||||||
|
helpMsg += "> Aliases: ";
|
||||||
|
for (size_t i = 0; i < aliases.size(); ++i) {
|
||||||
|
helpMsg += std::format(
|
||||||
|
"`{}{}`", prefix, aliases[i]);
|
||||||
|
if (i < aliases.size() - 1) {
|
||||||
|
helpMsg += ", ";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
helpMsg += "\n";
|
||||||
|
}
|
||||||
|
|
||||||
std::string_view getUsage() const override { return "[command]"; }
|
helpMsg += "\n";
|
||||||
|
}
|
||||||
CommandCategory getCategory() const override { return CommandCategory::Utility; }
|
}
|
||||||
|
|
||||||
std::vector<std::string_view> getAliases() const override {
|
ctx.reply(helpMsg);
|
||||||
return {"h", "?", "commands"};
|
} catch (const std::exception& e) {
|
||||||
}
|
ECHOION_LOG_ERROR(
|
||||||
};
|
std::format("Help command exception: {}", e.what()));
|
||||||
|
ctx.reply("Couldn't generate help. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// --- Manager Implementation ---
|
std::string_view getDescription() const override
|
||||||
|
{
|
||||||
|
return "Shows this help message with all available commands.";
|
||||||
|
}
|
||||||
|
|
||||||
CommandManager::CommandManager() {
|
std::string_view getUsage() const override { return "[command]"; }
|
||||||
registerBuiltinCommands();
|
|
||||||
registerHelpCommand();
|
|
||||||
startThreadPool();
|
|
||||||
}
|
|
||||||
|
|
||||||
CommandManager::~CommandManager() {
|
CommandCategory getCategory() const override
|
||||||
shutdown();
|
{
|
||||||
}
|
return CommandCategory::Utility;
|
||||||
|
}
|
||||||
|
|
||||||
void CommandManager::shutdown() {
|
std::vector<std::string_view> getAliases() const override
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lock(queueMutex_);
|
return {"h", "?", "commands"};
|
||||||
shutdown_ = true;
|
}
|
||||||
}
|
};
|
||||||
queueCv_.notify_all();
|
|
||||||
|
|
||||||
for (auto& thread : workerThreads_) {
|
|
||||||
if (thread.joinable()) {
|
|
||||||
thread.join();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
workerThreads_.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
void CommandManager::startThreadPool() {
|
// --- Manager Implementation ---
|
||||||
for (size_t i = 0; i < THREAD_POOL_SIZE; ++i) {
|
|
||||||
workerThreads_.emplace_back([this]() {
|
|
||||||
processCommandQueue();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
ECHOION_LOG_INFO(std::format("CommandManager thread pool started with {} workers", THREAD_POOL_SIZE));
|
|
||||||
}
|
|
||||||
|
|
||||||
void CommandManager::processCommandQueue() {
|
CommandManager::CommandManager()
|
||||||
while (true) {
|
{
|
||||||
CommandTask task;
|
registerBuiltinCommands();
|
||||||
{
|
registerHelpCommand();
|
||||||
std::unique_lock<std::mutex> lock(queueMutex_);
|
startThreadPool();
|
||||||
queueCv_.wait(lock, [this] { return shutdown_ || !commandQueue_.empty(); });
|
|
||||||
|
|
||||||
if (shutdown_ && commandQueue_.empty()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
task = std::move(commandQueue_.front());
|
|
||||||
commandQueue_.pop();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Execute the command
|
|
||||||
executeCommandAsync(std::move(task));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void CommandManager::executeCommandAsync(CommandTask task) {
|
|
||||||
try {
|
|
||||||
// Re-parse the command (same logic as dispatch)
|
|
||||||
std::string_view message = task.message;
|
|
||||||
if (!message.starts_with(prefix_)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Skip prefix and trim
|
|
||||||
std::string_view input = message.substr(prefix_.length());
|
|
||||||
size_t start = input.find_first_not_of(" \t");
|
|
||||||
if (start == std::string_view::npos) return;
|
|
||||||
input = input.substr(start);
|
|
||||||
|
|
||||||
// Split command and args
|
|
||||||
size_t spacePos = input.find_first_of(" \t");
|
|
||||||
std::string_view cmdName = (spacePos == std::string_view::npos)
|
|
||||||
? input
|
|
||||||
: input.substr(0, spacePos);
|
|
||||||
|
|
||||||
std::string argsStr;
|
|
||||||
if (spacePos != std::string_view::npos) {
|
|
||||||
size_t argStart = input.find_first_not_of(" \t", spacePos);
|
|
||||||
if (argStart != std::string_view::npos) {
|
|
||||||
argsStr = std::string(input.substr(argStart));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string cmdKey(cmdName);
|
|
||||||
std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower);
|
|
||||||
|
|
||||||
CommandPtr command;
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
|
||||||
auto it = commands_.find(cmdKey);
|
|
||||||
if (it == commands_.end()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
command = it->second;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check permissions
|
|
||||||
if (!canExecuteCommand(task.clientId, command)) {
|
|
||||||
task.replyFunc("You don't have permission to use this command.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Execute command
|
|
||||||
CommandContext ctx{
|
|
||||||
.clientId = task.clientId,
|
|
||||||
.prefix = prefix_,
|
|
||||||
.args = std::move(argsStr),
|
|
||||||
.invokerName = task.invokerName,
|
|
||||||
.musicManager = task.musicManager,
|
|
||||||
.replyCallback = std::move(task.replyFunc)
|
|
||||||
};
|
|
||||||
|
|
||||||
command->execute(ctx);
|
|
||||||
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("Async command execution error: {}", e.what()));
|
|
||||||
try {
|
|
||||||
task.replyFunc("An error occurred while executing the command.");
|
|
||||||
} catch (...) {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool CommandManager::dispatch(
|
|
||||||
uint64_t clientId,
|
|
||||||
std::string_view message,
|
|
||||||
std::weak_ptr<MusicManager> musicManager,
|
|
||||||
std::function<void(std::string_view)> replyFunc,
|
|
||||||
std::string_view invokerName) {
|
|
||||||
|
|
||||||
if (!message.starts_with(prefix_)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Skip prefix and trim leading whitespace
|
|
||||||
std::string_view input = message.substr(prefix_.length());
|
|
||||||
size_t start = input.find_first_not_of(" \t");
|
|
||||||
if (start == std::string_view::npos) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
input = input.substr(start);
|
|
||||||
|
|
||||||
// Split command and arguments
|
|
||||||
size_t spacePos = input.find_first_of(" \t");
|
|
||||||
std::string_view cmdName = (spacePos == std::string_view::npos)
|
|
||||||
? input
|
|
||||||
: input.substr(0, spacePos);
|
|
||||||
|
|
||||||
// Convert to lowercase for lookup
|
|
||||||
std::string cmdKey(cmdName);
|
|
||||||
std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower);
|
|
||||||
|
|
||||||
// Check if command exists
|
|
||||||
CommandPtr command;
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
|
||||||
auto it = commands_.find(cmdKey);
|
|
||||||
if (it == commands_.end()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
command = it->second;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check permissions synchronously (fast check)
|
|
||||||
if (!canExecuteCommand(clientId, command)) {
|
|
||||||
replyFunc("You don't have permission to use this command.");
|
|
||||||
return true; // Command was found but not allowed
|
|
||||||
}
|
|
||||||
|
|
||||||
// Queue the command for async execution
|
|
||||||
CommandTask task{
|
|
||||||
.clientId = clientId,
|
|
||||||
.message = std::string(message),
|
|
||||||
.musicManager = musicManager,
|
|
||||||
.replyFunc = std::move(replyFunc),
|
|
||||||
.invokerName = std::string(invokerName)
|
|
||||||
};
|
|
||||||
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(queueMutex_);
|
|
||||||
if (shutdown_) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
commandQueue_.push(std::move(task));
|
|
||||||
}
|
|
||||||
queueCv_.notify_one();
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool CommandManager::dispatchSync(
|
|
||||||
uint64_t clientId,
|
|
||||||
std::string_view message,
|
|
||||||
std::weak_ptr<MusicManager> musicManager,
|
|
||||||
std::function<void(std::string_view)> replyFunc,
|
|
||||||
std::string_view invokerName) {
|
|
||||||
|
|
||||||
if (!message.starts_with(prefix_)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Skip prefix and trim leading whitespace
|
|
||||||
std::string_view input = message.substr(prefix_.length());
|
|
||||||
size_t start = input.find_first_not_of(" \t");
|
|
||||||
if (start == std::string_view::npos) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
input = input.substr(start);
|
|
||||||
|
|
||||||
// Split command and arguments
|
|
||||||
size_t spacePos = input.find_first_of(" \t");
|
|
||||||
std::string_view cmdName = (spacePos == std::string_view::npos)
|
|
||||||
? input
|
|
||||||
: input.substr(0, spacePos);
|
|
||||||
|
|
||||||
std::string argsStr;
|
|
||||||
if (spacePos != std::string_view::npos) {
|
|
||||||
size_t argStart = input.find_first_not_of(" \t", spacePos);
|
|
||||||
if (argStart != std::string_view::npos) {
|
|
||||||
argsStr = std::string(input.substr(argStart));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert to lowercase for lookup
|
|
||||||
std::string cmdKey(cmdName);
|
|
||||||
std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower);
|
|
||||||
|
|
||||||
CommandPtr command;
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
|
||||||
auto it = commands_.find(cmdKey);
|
|
||||||
if (it == commands_.end()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
command = it->second;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check permissions
|
|
||||||
if (!canExecuteCommand(clientId, command)) {
|
|
||||||
replyFunc("You don't have permission to use this command.");
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
CommandContext ctx{
|
|
||||||
.clientId = clientId,
|
|
||||||
.prefix = prefix_,
|
|
||||||
.args = std::move(argsStr),
|
|
||||||
.invokerName = invokerName,
|
|
||||||
.musicManager = musicManager,
|
|
||||||
.replyCallback = std::move(replyFunc)
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
command->execute(ctx);
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
ECHOION_LOG_ERROR(
|
|
||||||
std::format("Command execution error [{}]: {}", cmdKey, e.what()));
|
|
||||||
ctx.reply("An unexpected error occurred. Our team has been notified.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool CommandManager::hasCommand(std::string_view name) const {
|
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
|
||||||
return commands_.contains(std::string(name));
|
|
||||||
}
|
|
||||||
|
|
||||||
std::optional<CommandPtr> CommandManager::getCommand(std::string_view name) const {
|
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
|
||||||
auto it = commands_.find(std::string(name));
|
|
||||||
if (it != commands_.end()) {
|
|
||||||
return it->second;
|
|
||||||
}
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<std::pair<std::string, CommandPtr>> CommandManager::getAllCommands() const {
|
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
|
||||||
std::vector<std::pair<std::string, CommandPtr>> result;
|
|
||||||
result.reserve(uniqueCommands_.size());
|
|
||||||
for (const auto& entry : uniqueCommands_) {
|
|
||||||
result.emplace_back(entry.primaryName, entry.instance);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<std::pair<std::string, CommandPtr>> CommandManager::getVisibleCommands(uint64_t clientId) const {
|
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
|
||||||
std::vector<std::pair<std::string, CommandPtr>> result;
|
|
||||||
|
|
||||||
for (const auto& entry : uniqueCommands_) {
|
|
||||||
// Only include if client can execute it
|
|
||||||
if (canExecuteCommand(clientId, entry.instance)) {
|
|
||||||
result.emplace_back(entry.primaryName, entry.instance);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool CommandManager::canExecuteCommand(uint64_t clientId, const CommandPtr& cmd) const {
|
|
||||||
if (!cmd->requiresAdmin()) {
|
|
||||||
return true; // Non-admin commands are always allowed
|
|
||||||
}
|
|
||||||
|
|
||||||
// If no server config is set, deny admin commands
|
|
||||||
if (!serverConfig_.has_value()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// If no admin groups configured, deny everyone
|
|
||||||
if (serverConfig_->server.adminGroups.empty()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check permission via callback if set
|
|
||||||
if (permissionCheck_ && (cmd->requiresAdmin() ||
|
|
||||||
cmd->getCategory() == CommandCategory::Admin)) {
|
|
||||||
return permissionCheck_(clientId, cmd->getCategory());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Default: deny admin commands if no checker configured
|
CommandManager::~CommandManager() { shutdown(); }
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
void CommandManager::setPrefix(std::string_view prefix) {
|
void CommandManager::shutdown()
|
||||||
prefix_ = prefix;
|
{
|
||||||
}
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(queueMutex_);
|
||||||
|
shutdown_ = true;
|
||||||
|
}
|
||||||
|
queueCv_.notify_all();
|
||||||
|
|
||||||
void CommandManager::setPermissionCheckFunc(PermissionCheckFunc func) {
|
for (auto& thread : workerThreads_) {
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
if (thread.joinable()) {
|
||||||
permissionCheck_ = std::move(func);
|
thread.join();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
workerThreads_.clear();
|
||||||
|
}
|
||||||
|
|
||||||
void CommandManager::setServerConfig(const Api::AppConfig& config) {
|
void CommandManager::startThreadPool()
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
{
|
||||||
serverConfig_ = config;
|
for (size_t i = 0; i < THREAD_POOL_SIZE; ++i) {
|
||||||
}
|
workerThreads_.emplace_back([this]() { processCommandQueue(); });
|
||||||
|
}
|
||||||
|
ECHOION_LOG_INFO(
|
||||||
|
std::format("CommandManager thread pool started with {} workers",
|
||||||
|
THREAD_POOL_SIZE));
|
||||||
|
}
|
||||||
|
|
||||||
void CommandManager::registerBuiltinCommands() {
|
void CommandManager::processCommandQueue()
|
||||||
registerCommand<PlayCommand>("play");
|
{
|
||||||
registerCommand<SelectCommand>("select");
|
while (true) {
|
||||||
registerCommand<PauseCommand>("pause");
|
CommandTask task;
|
||||||
registerCommand<ResumeCommand>("resume");
|
{
|
||||||
registerCommand<StopCommand>("stop");
|
std::unique_lock<std::mutex> lock(queueMutex_);
|
||||||
registerCommand<SkipCommand>("skip");
|
queueCv_.wait(lock, [this] {
|
||||||
// registerCommand<SeekCommand>("seek");
|
return shutdown_ || !commandQueue_.empty();
|
||||||
registerCommand<VolumeCommand>("volume");
|
});
|
||||||
registerCommand<QueueCommand>("queue");
|
|
||||||
registerCommand<RemoveCommand>("remove");
|
|
||||||
registerCommand<ClearCommand>("clear");
|
|
||||||
registerCommand<MoveCommand>("move");
|
|
||||||
registerCommand<ShuffleCommand>("shuffle");
|
|
||||||
registerCommand<RepeatCommand>("repeat");
|
|
||||||
registerCommand<PlaylistCommand>("playlist");
|
|
||||||
registerCommand<NowPlayingCommand>("np");
|
|
||||||
registerCommand<SearchCommand>("search");
|
|
||||||
registerCommand<ReloadCommand>("reload");
|
|
||||||
registerCommand<ReloadConfigCommand>("reloadconfig");
|
|
||||||
registerCommand<SubscribeCommand>("subscribe");
|
|
||||||
registerCommand<UnsubscribeCommand>("unsubscribe");
|
|
||||||
registerCommand<SubscribersCommand>("subscribers");
|
|
||||||
registerCommand<UnsubscribeIdCommand>("unsubscribeid");
|
|
||||||
registerCommand<UnsubscribeAllCommand>("unsubscribeall");
|
|
||||||
}
|
|
||||||
|
|
||||||
void CommandManager::registerHelpCommand() {
|
if (shutdown_ && commandQueue_.empty()) {
|
||||||
auto helpCmd = std::make_shared<HelpCommand>(*this);
|
return;
|
||||||
|
}
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
|
||||||
|
task = std::move(commandQueue_.front());
|
||||||
commands_["help"] = helpCmd;
|
commandQueue_.pop();
|
||||||
uniqueCommands_.push_back({"help", helpCmd});
|
}
|
||||||
|
|
||||||
for (auto alias : helpCmd->getAliases()) {
|
// Execute the command
|
||||||
commands_[std::string(alias)] = helpCmd;
|
executeCommandAsync(std::move(task));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void CommandManager::executeCommandAsync(CommandTask task)
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
// Re-parse the command (same logic as dispatch)
|
||||||
|
std::string_view message = task.message;
|
||||||
|
if (!message.starts_with(prefix_)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip prefix and trim
|
||||||
|
std::string_view input = message.substr(prefix_.length());
|
||||||
|
size_t start = input.find_first_not_of(" \t");
|
||||||
|
if (start == std::string_view::npos) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
input = input.substr(start);
|
||||||
|
|
||||||
|
// Split command and args
|
||||||
|
size_t spacePos = input.find_first_of(" \t");
|
||||||
|
std::string_view cmdName = (spacePos == std::string_view::npos)
|
||||||
|
? input
|
||||||
|
: input.substr(0, spacePos);
|
||||||
|
|
||||||
|
std::string argsStr;
|
||||||
|
if (spacePos != std::string_view::npos) {
|
||||||
|
size_t argStart = input.find_first_not_of(" \t", spacePos);
|
||||||
|
if (argStart != std::string_view::npos) {
|
||||||
|
argsStr = std::string(input.substr(argStart));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string cmdKey(cmdName);
|
||||||
|
std::transform(
|
||||||
|
cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower);
|
||||||
|
|
||||||
|
CommandPtr command;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
auto it = commands_.find(cmdKey);
|
||||||
|
if (it == commands_.end()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
command = it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check permissions
|
||||||
|
if (!canExecuteCommand(task.clientId, command)) {
|
||||||
|
task.replyFunc(
|
||||||
|
"You don't have permission to use this command.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Execute command
|
||||||
|
CommandContext ctx{.clientId = task.clientId,
|
||||||
|
.prefix = prefix_,
|
||||||
|
.args = std::move(argsStr),
|
||||||
|
.invokerName = task.invokerName,
|
||||||
|
.musicManager = task.musicManager,
|
||||||
|
.replyCallback = std::move(task.replyFunc)};
|
||||||
|
|
||||||
|
command->execute(ctx);
|
||||||
|
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Async command execution error: {}", e.what()));
|
||||||
|
try {
|
||||||
|
task.replyFunc(
|
||||||
|
"An error occurred while executing the command.");
|
||||||
|
} catch (...) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommandManager::dispatch(uint64_t clientId,
|
||||||
|
std::string_view message,
|
||||||
|
std::weak_ptr<MusicManager>
|
||||||
|
musicManager,
|
||||||
|
std::function<void(std::string_view)>
|
||||||
|
replyFunc,
|
||||||
|
std::string_view invokerName)
|
||||||
|
{
|
||||||
|
|
||||||
|
if (!message.starts_with(prefix_)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip prefix and trim leading whitespace
|
||||||
|
std::string_view input = message.substr(prefix_.length());
|
||||||
|
size_t start = input.find_first_not_of(" \t");
|
||||||
|
if (start == std::string_view::npos) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
input = input.substr(start);
|
||||||
|
|
||||||
|
// Split command and arguments
|
||||||
|
size_t spacePos = input.find_first_of(" \t");
|
||||||
|
std::string_view cmdName = (spacePos == std::string_view::npos)
|
||||||
|
? input
|
||||||
|
: input.substr(0, spacePos);
|
||||||
|
|
||||||
|
// Convert to lowercase for lookup
|
||||||
|
std::string cmdKey(cmdName);
|
||||||
|
std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower);
|
||||||
|
|
||||||
|
// Check if command exists
|
||||||
|
CommandPtr command;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
auto it = commands_.find(cmdKey);
|
||||||
|
if (it == commands_.end()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
command = it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check permissions synchronously (fast check)
|
||||||
|
if (!canExecuteCommand(clientId, command)) {
|
||||||
|
replyFunc("You don't have permission to use this command.");
|
||||||
|
return true; // Command was found but not allowed
|
||||||
|
}
|
||||||
|
|
||||||
|
// Queue the command for async execution
|
||||||
|
CommandTask task{.clientId = clientId,
|
||||||
|
.message = std::string(message),
|
||||||
|
.musicManager = musicManager,
|
||||||
|
.replyFunc = std::move(replyFunc),
|
||||||
|
.invokerName = std::string(invokerName)};
|
||||||
|
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(queueMutex_);
|
||||||
|
if (shutdown_) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
commandQueue_.push(std::move(task));
|
||||||
|
}
|
||||||
|
queueCv_.notify_one();
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommandManager::dispatchSync(uint64_t clientId,
|
||||||
|
std::string_view message,
|
||||||
|
std::weak_ptr<MusicManager>
|
||||||
|
musicManager,
|
||||||
|
std::function<void(std::string_view)>
|
||||||
|
replyFunc,
|
||||||
|
std::string_view invokerName)
|
||||||
|
{
|
||||||
|
|
||||||
|
if (!message.starts_with(prefix_)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip prefix and trim leading whitespace
|
||||||
|
std::string_view input = message.substr(prefix_.length());
|
||||||
|
size_t start = input.find_first_not_of(" \t");
|
||||||
|
if (start == std::string_view::npos) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
input = input.substr(start);
|
||||||
|
|
||||||
|
// Split command and arguments
|
||||||
|
size_t spacePos = input.find_first_of(" \t");
|
||||||
|
std::string_view cmdName = (spacePos == std::string_view::npos)
|
||||||
|
? input
|
||||||
|
: input.substr(0, spacePos);
|
||||||
|
|
||||||
|
std::string argsStr;
|
||||||
|
if (spacePos != std::string_view::npos) {
|
||||||
|
size_t argStart = input.find_first_not_of(" \t", spacePos);
|
||||||
|
if (argStart != std::string_view::npos) {
|
||||||
|
argsStr = std::string(input.substr(argStart));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert to lowercase for lookup
|
||||||
|
std::string cmdKey(cmdName);
|
||||||
|
std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower);
|
||||||
|
|
||||||
|
CommandPtr command;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
auto it = commands_.find(cmdKey);
|
||||||
|
if (it == commands_.end()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
command = it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check permissions
|
||||||
|
if (!canExecuteCommand(clientId, command)) {
|
||||||
|
replyFunc("You don't have permission to use this command.");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandContext ctx{.clientId = clientId,
|
||||||
|
.prefix = prefix_,
|
||||||
|
.args = std::move(argsStr),
|
||||||
|
.invokerName = invokerName,
|
||||||
|
.musicManager = musicManager,
|
||||||
|
.replyCallback = std::move(replyFunc)};
|
||||||
|
|
||||||
|
try {
|
||||||
|
command->execute(ctx);
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(std::format(
|
||||||
|
"Command execution error [{}]: {}", cmdKey, e.what()));
|
||||||
|
ctx.reply(
|
||||||
|
"An unexpected error occurred. Our team has been notified.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommandManager::hasCommand(std::string_view name) const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
return commands_.contains(std::string(name));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<CommandPtr>
|
||||||
|
CommandManager::getCommand(std::string_view name) const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
auto it = commands_.find(std::string(name));
|
||||||
|
if (it != commands_.end()) {
|
||||||
|
return it->second;
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::pair<std::string, CommandPtr>>
|
||||||
|
CommandManager::getAllCommands() const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
std::vector<std::pair<std::string, CommandPtr>> result;
|
||||||
|
result.reserve(uniqueCommands_.size());
|
||||||
|
for (const auto& entry : uniqueCommands_) {
|
||||||
|
result.emplace_back(entry.primaryName, entry.instance);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::pair<std::string, CommandPtr>>
|
||||||
|
CommandManager::getVisibleCommands(uint64_t clientId) const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
std::vector<std::pair<std::string, CommandPtr>> result;
|
||||||
|
|
||||||
|
for (const auto& entry : uniqueCommands_) {
|
||||||
|
// Only include if client can execute it
|
||||||
|
if (canExecuteCommand(clientId, entry.instance)) {
|
||||||
|
result.emplace_back(entry.primaryName, entry.instance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommandManager::canExecuteCommand(uint64_t clientId,
|
||||||
|
const CommandPtr& cmd) const
|
||||||
|
{
|
||||||
|
if (!cmd->requiresAdmin()) {
|
||||||
|
return true; // Non-admin commands are always allowed
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no server config is set, deny admin commands
|
||||||
|
if (!serverConfig_.has_value()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no admin groups configured, deny everyone
|
||||||
|
if (serverConfig_->teamspeak.adminGroups.empty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check permission via callback if set
|
||||||
|
if (permissionCheck_ &&
|
||||||
|
(cmd->requiresAdmin() ||
|
||||||
|
cmd->getCategory() == CommandCategory::Admin)) {
|
||||||
|
return permissionCheck_(clientId, cmd->getCategory());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default: deny admin commands if no checker configured
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommandManager::setPrefix(std::string_view prefix)
|
||||||
|
{
|
||||||
|
prefix_ = prefix;
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommandManager::setPermissionCheckFunc(PermissionCheckFunc func)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
permissionCheck_ = std::move(func);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommandManager::setServerConfig(const Api::AppConfig& config)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
serverConfig_ = config;
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommandManager::registerBuiltinCommands()
|
||||||
|
{
|
||||||
|
registerCommand<PlayCommand>("play");
|
||||||
|
registerCommand<SelectCommand>("select");
|
||||||
|
registerCommand<PauseCommand>("pause");
|
||||||
|
registerCommand<ResumeCommand>("resume");
|
||||||
|
registerCommand<StopCommand>("stop");
|
||||||
|
registerCommand<SkipCommand>("skip");
|
||||||
|
// registerCommand<SeekCommand>("seek");
|
||||||
|
registerCommand<VolumeCommand>("volume");
|
||||||
|
registerCommand<QueueCommand>("queue");
|
||||||
|
registerCommand<RemoveCommand>("remove");
|
||||||
|
registerCommand<ClearCommand>("clear");
|
||||||
|
registerCommand<MoveCommand>("move");
|
||||||
|
registerCommand<ShuffleCommand>("shuffle");
|
||||||
|
registerCommand<RepeatCommand>("repeat");
|
||||||
|
registerCommand<PlaylistCommand>("playlist");
|
||||||
|
registerCommand<NowPlayingCommand>("np");
|
||||||
|
registerCommand<SearchCommand>("search");
|
||||||
|
registerCommand<ReloadCommand>("reload");
|
||||||
|
registerCommand<ReloadConfigCommand>("reloadconfig");
|
||||||
|
registerCommand<SubscribeCommand>("subscribe");
|
||||||
|
registerCommand<UnsubscribeCommand>("unsubscribe");
|
||||||
|
registerCommand<SubscribersCommand>("subscribers");
|
||||||
|
registerCommand<UnsubscribeIdCommand>("unsubscribeid");
|
||||||
|
registerCommand<UnsubscribeAllCommand>("unsubscribeall");
|
||||||
|
registerCommand<RpcInfoCommand>("rpc");
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommandManager::registerHelpCommand()
|
||||||
|
{
|
||||||
|
auto helpCmd = std::make_shared<HelpCommand>(*this);
|
||||||
|
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
|
||||||
|
commands_["help"] = helpCmd;
|
||||||
|
uniqueCommands_.push_back({"help", helpCmd});
|
||||||
|
|
||||||
|
for (auto alias : helpCmd->getAliases()) {
|
||||||
|
commands_[std::string(alias)] = helpCmd;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
+424
-369
@@ -1,378 +1,433 @@
|
|||||||
|
#include "LoggerInterface.hpp"
|
||||||
|
#include "Types.hpp"
|
||||||
#include "echoion/core/ConfigLoader.hpp"
|
#include "echoion/core/ConfigLoader.hpp"
|
||||||
#include "echoion/api/AudioTypes.hpp"
|
#include <AudioTypes.hpp>
|
||||||
#include <glaze/glaze.hpp>
|
#include <Void/Data/Json.hpp>
|
||||||
#include <fstream>
|
#include <Void/Data/Reflect.hpp>
|
||||||
#include <format>
|
#include <format>
|
||||||
|
#include <fstream>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
// NOTE: The Echoion::Core::*Json mirror structs are plain reflectable
|
||||||
|
// aggregates whose member names are exactly the desired JSON keys, so
|
||||||
|
// Void::Json reflection (Json::to_json / Json::from_json) produces the same
|
||||||
|
// document the former glz::meta specializations did — no annotations needed.
|
||||||
|
|
||||||
// JSON structures for configuration
|
namespace Echoion::Core
|
||||||
struct BotConfigJson {
|
{
|
||||||
std::string botName = "Echoion";
|
|
||||||
std::string commandPrefix = "!";
|
|
||||||
float defaultVolume = 0.5f;
|
|
||||||
bool autoReconnect = true;
|
|
||||||
uint32_t reconnectDelay = 5000;
|
|
||||||
uint32_t maxReconnectAttempts = 5;
|
|
||||||
std::optional<std::string> proxyHost;
|
|
||||||
std::optional<uint16_t> proxyPort;
|
|
||||||
std::optional<std::string> proxyUsername;
|
|
||||||
std::optional<std::string> proxyPassword;
|
|
||||||
std::optional<std::string> proxyType;
|
|
||||||
std::optional<std::string> youtubeApiKey;
|
|
||||||
std::string preferredQuality = "High";
|
|
||||||
bool allowPlaylistImports = true;
|
|
||||||
uint32_t maxQueueSize = 100;
|
|
||||||
uint32_t trackTimeout = 30000;
|
|
||||||
std::optional<std::string> youtubeCookiesPath;
|
|
||||||
std::optional<std::string> cookiesFromBrowser;
|
|
||||||
uint32_t ytDlpMaxConcurrent = 4;
|
|
||||||
bool ytDlpAsyncEnabled = true;
|
|
||||||
bool enableUrlShortening = true;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct ServerConfigJson {
|
Api::Result<Api::AppConfig>
|
||||||
std::string address;
|
ConfigLoader::loadFromFile(const std::filesystem::path& path)
|
||||||
uint16_t port = 9987;
|
{
|
||||||
std::string serverPassword = "";
|
if (!std::filesystem::exists(path)) {
|
||||||
std::string nickname = "EchoionBot";
|
return std::unexpected(
|
||||||
std::optional<std::string> defaultChannelId;
|
Api::Error(Api::ErrorCode::NotFound,
|
||||||
std::optional<std::string> channelPassword;
|
std::format("Configuration file not found: {}",
|
||||||
std::vector<uint64_t> adminGroups;
|
path.string())));
|
||||||
std::vector<uint64_t> djGroups;
|
}
|
||||||
std::vector<uint64_t> bannedGroups;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct SecurityConfigJson {
|
std::ifstream file(path);
|
||||||
bool requireAuthForAdmin = true;
|
if (!file.is_open()) {
|
||||||
uint32_t maxLoginAttempts = 5;
|
return std::unexpected(
|
||||||
uint32_t lockoutDuration = 300000;
|
Api::Error(Api::ErrorCode::PermissionDenied,
|
||||||
uint32_t sessionTimeout = 3600000;
|
std::format("Failed to open configuration file: {}",
|
||||||
bool enableAuditLog = true;
|
path.string())));
|
||||||
};
|
}
|
||||||
|
|
||||||
struct AppConfigJson {
|
std::string content((std::istreambuf_iterator<char>(file)),
|
||||||
BotConfigJson bot;
|
std::istreambuf_iterator<char>());
|
||||||
ServerConfigJson server;
|
file.close();
|
||||||
SecurityConfigJson security;
|
|
||||||
};
|
auto parsed = Void::Json::parse(content);
|
||||||
|
if (!parsed) {
|
||||||
} // namespace Echoion::Core
|
return std::unexpected(Api::Error(
|
||||||
|
Api::ErrorCode::ParseError,
|
||||||
// Glaze metadata for JSON serialization
|
std::format("Failed to parse configuration ({}:{}): {}",
|
||||||
template<> struct glz::meta<Echoion::Core::BotConfigJson> {
|
parsed.error().line, parsed.error().col,
|
||||||
using T = Echoion::Core::BotConfigJson;
|
parsed.error().message)));
|
||||||
static constexpr auto value = object(
|
}
|
||||||
"botName", &T::botName,
|
|
||||||
"commandPrefix", &T::commandPrefix,
|
// Tolerant deserialization: unknown JSON fields are ignored and missing
|
||||||
"defaultVolume", &T::defaultVolume,
|
// fields keep their default-initialized values (matches the former
|
||||||
"autoReconnect", &T::autoReconnect,
|
// glz::opts{error_on_unknown_keys=false, error_on_missing_keys=false}).
|
||||||
"reconnectDelay", &T::reconnectDelay,
|
auto jsonResult = Void::Json::from_json<AppConfigJson>(*parsed);
|
||||||
"maxReconnectAttempts", &T::maxReconnectAttempts,
|
if (!jsonResult) {
|
||||||
"proxyHost", &T::proxyHost,
|
return std::unexpected(Api::Error(
|
||||||
"proxyPort", &T::proxyPort,
|
Api::ErrorCode::ParseError,
|
||||||
"proxyUsername", &T::proxyUsername,
|
std::format("Failed to parse configuration: field '{}': {}",
|
||||||
"proxyPassword", &T::proxyPassword,
|
jsonResult.error().field,
|
||||||
"proxyType", &T::proxyType,
|
jsonResult.error().message)));
|
||||||
"youtubeApiKey", &T::youtubeApiKey,
|
}
|
||||||
"preferredQuality", &T::preferredQuality,
|
AppConfigJson jsonConfig = std::move(*jsonResult);
|
||||||
"allowPlaylistImports", &T::allowPlaylistImports,
|
|
||||||
"maxQueueSize", &T::maxQueueSize,
|
// Convert to API config
|
||||||
"trackTimeout", &T::trackTimeout,
|
Api::AppConfig config;
|
||||||
"youtubeCookiesPath", &T::youtubeCookiesPath,
|
|
||||||
"cookiesFromBrowser", &T::cookiesFromBrowser,
|
// Bot config
|
||||||
"ytDlpMaxConcurrent", &T::ytDlpMaxConcurrent,
|
config.bot.botName = jsonConfig.bot.botName;
|
||||||
"ytDlpAsyncEnabled", &T::ytDlpAsyncEnabled,
|
config.bot.commandPrefix = jsonConfig.bot.commandPrefix;
|
||||||
"enableUrlShortening", &T::enableUrlShortening
|
config.bot.defaultVolume = jsonConfig.bot.defaultVolume;
|
||||||
);
|
config.bot.maxQueueSize = jsonConfig.bot.maxQueueSize;
|
||||||
};
|
config.bot.trackTimeout =
|
||||||
|
std::chrono::milliseconds(jsonConfig.bot.trackTimeout);
|
||||||
template<> struct glz::meta<Echoion::Core::ServerConfigJson> {
|
config.bot.autoReconnect = jsonConfig.bot.autoReconnect;
|
||||||
using T = Echoion::Core::ServerConfigJson;
|
config.bot.reconnectDelay =
|
||||||
static constexpr auto value = object(
|
std::chrono::milliseconds(jsonConfig.bot.reconnectDelay);
|
||||||
"address", &T::address,
|
config.bot.maxReconnectAttempts = jsonConfig.bot.maxReconnectAttempts;
|
||||||
"port", &T::port,
|
config.bot.preferredQuality =
|
||||||
"serverPassword", &T::serverPassword,
|
parseQuality(jsonConfig.bot.preferredQuality);
|
||||||
"nickname", &T::nickname,
|
config.bot.allowPlaylistImports = jsonConfig.bot.allowPlaylistImports;
|
||||||
"defaultChannelId", &T::defaultChannelId,
|
|
||||||
"channelPassword", &T::channelPassword,
|
// YouTube config
|
||||||
"adminGroups", &T::adminGroups,
|
if (jsonConfig.youtube.youtubeApiKey.has_value()) {
|
||||||
"djGroups", &T::djGroups,
|
config.youtube.youtubeApiKey = jsonConfig.youtube.youtubeApiKey;
|
||||||
"bannedGroups", &T::bannedGroups
|
}
|
||||||
);
|
if (jsonConfig.youtube.youtubeCookiesPath.has_value()) {
|
||||||
};
|
config.youtube.youtubeCookiesPath =
|
||||||
|
jsonConfig.youtube.youtubeCookiesPath;
|
||||||
template<> struct glz::meta<Echoion::Core::SecurityConfigJson> {
|
}
|
||||||
using T = Echoion::Core::SecurityConfigJson;
|
if (jsonConfig.youtube.cookiesFromBrowser.has_value()) {
|
||||||
static constexpr auto value = object(
|
config.youtube.cookiesFromBrowser =
|
||||||
"requireAuthForAdmin", &T::requireAuthForAdmin,
|
jsonConfig.youtube.cookiesFromBrowser;
|
||||||
"maxLoginAttempts", &T::maxLoginAttempts,
|
}
|
||||||
"lockoutDuration", &T::lockoutDuration,
|
config.youtube.ytDlpMaxConcurrent =
|
||||||
"sessionTimeout", &T::sessionTimeout,
|
std::min(static_cast<size_t>(jsonConfig.youtube.ytDlpMaxConcurrent),
|
||||||
"enableAuditLog", &T::enableAuditLog
|
size_t(8));
|
||||||
);
|
config.youtube.ytDlpAsyncEnabled = jsonConfig.youtube.ytDlpAsyncEnabled;
|
||||||
};
|
config.youtube.enableUrlShortening =
|
||||||
|
jsonConfig.youtube.enableUrlShortening;
|
||||||
template<> struct glz::meta<Echoion::Core::AppConfigJson> {
|
|
||||||
using T = Echoion::Core::AppConfigJson;
|
// Network config
|
||||||
static constexpr auto value = object(
|
if (jsonConfig.network.proxyHost.has_value() &&
|
||||||
"bot", &T::bot,
|
jsonConfig.network.proxyPort.has_value()) {
|
||||||
"server", &T::server,
|
Api::ProxyConfig proxy;
|
||||||
"security", &T::security
|
proxy.host = *jsonConfig.network.proxyHost;
|
||||||
);
|
proxy.port = *jsonConfig.network.proxyPort;
|
||||||
};
|
proxy.username = jsonConfig.network.proxyUsername;
|
||||||
|
proxy.password = jsonConfig.network.proxyPassword;
|
||||||
namespace Echoion::Core {
|
const auto& typeStr = jsonConfig.network.proxyType;
|
||||||
|
if (typeStr == "SOCKS5" || typeStr == "socks5") {
|
||||||
Api::Result<Api::AppConfig> ConfigLoader::loadFromFile(const std::filesystem::path& path) {
|
proxy.type = Api::ProxyType::SOCKS5;
|
||||||
if (!std::filesystem::exists(path)) {
|
} else {
|
||||||
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
|
proxy.type = Api::ProxyType::HTTP;
|
||||||
std::format("Configuration file not found: {}", path.string())));
|
}
|
||||||
}
|
config.network.proxy = proxy;
|
||||||
|
}
|
||||||
std::ifstream file(path);
|
config.network.rpcEnabled = jsonConfig.network.rpcEnabled;
|
||||||
if (!file.is_open()) {
|
config.network.rpcPort = jsonConfig.network.rpcPort;
|
||||||
return std::unexpected(Api::Error(Api::ErrorCode::PermissionDenied,
|
config.network.rpcBindAddress = jsonConfig.network.rpcBindAddress;
|
||||||
std::format("Failed to open configuration file: {}", path.string())));
|
|
||||||
}
|
// TeamSpeak config
|
||||||
|
config.teamspeak.address = jsonConfig.teamspeak.address;
|
||||||
std::string content((std::istreambuf_iterator<char>(file)),
|
config.teamspeak.port = jsonConfig.teamspeak.port;
|
||||||
std::istreambuf_iterator<char>());
|
config.teamspeak.serverPassword = jsonConfig.teamspeak.serverPassword;
|
||||||
file.close();
|
config.teamspeak.nickname = jsonConfig.teamspeak.nickname;
|
||||||
|
config.teamspeak.defaultChannelId =
|
||||||
AppConfigJson jsonConfig;
|
jsonConfig.teamspeak.defaultChannelId;
|
||||||
auto ec = glz::read_json(jsonConfig, content);
|
config.teamspeak.channelPassword = jsonConfig.teamspeak.channelPassword;
|
||||||
if (ec) {
|
config.teamspeak.adminGroups = jsonConfig.teamspeak.adminGroups;
|
||||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
config.teamspeak.djGroups = jsonConfig.teamspeak.djGroups;
|
||||||
std::format("Failed to parse configuration: {}", glz::format_error(ec, content))));
|
config.teamspeak.bannedGroups = jsonConfig.teamspeak.bannedGroups;
|
||||||
}
|
|
||||||
|
// Security config
|
||||||
// Convert to API config
|
config.security.requireAuthForAdmin =
|
||||||
Api::AppConfig config;
|
jsonConfig.security.requireAuthForAdmin;
|
||||||
|
config.security.maxLoginAttempts = jsonConfig.security.maxLoginAttempts;
|
||||||
// Bot config
|
config.security.lockoutDuration =
|
||||||
config.bot.botName = jsonConfig.bot.botName;
|
std::chrono::milliseconds(jsonConfig.security.lockoutDuration);
|
||||||
config.bot.commandPrefix = jsonConfig.bot.commandPrefix;
|
config.security.sessionTimeout =
|
||||||
config.bot.defaultVolume = jsonConfig.bot.defaultVolume;
|
std::chrono::milliseconds(jsonConfig.security.sessionTimeout);
|
||||||
config.bot.autoReconnect = jsonConfig.bot.autoReconnect;
|
config.security.enableAuditLog = jsonConfig.security.enableAuditLog;
|
||||||
config.bot.reconnectDelay = std::chrono::milliseconds(jsonConfig.bot.reconnectDelay);
|
if (jsonConfig.security.apiKey.has_value()) {
|
||||||
config.bot.maxReconnectAttempts = jsonConfig.bot.maxReconnectAttempts;
|
config.security.apiKey = jsonConfig.security.apiKey;
|
||||||
config.bot.preferredQuality = parseQuality(jsonConfig.bot.preferredQuality);
|
}
|
||||||
config.bot.allowPlaylistImports = jsonConfig.bot.allowPlaylistImports;
|
config.security.allowCors = jsonConfig.security.allowCors;
|
||||||
config.bot.maxQueueSize = jsonConfig.bot.maxQueueSize;
|
config.security.corsOrigins = jsonConfig.security.corsOrigins;
|
||||||
config.bot.trackTimeout = std::chrono::milliseconds(jsonConfig.bot.trackTimeout);
|
|
||||||
|
// Features config
|
||||||
// Proxy config
|
config.features.enableHotReload = jsonConfig.features.enableHotReload;
|
||||||
if (jsonConfig.bot.proxyHost.has_value() && jsonConfig.bot.proxyPort.has_value()) {
|
config.features.enableAutoReload = jsonConfig.features.enableAutoReload;
|
||||||
Api::ProxyConfig proxy;
|
config.features.enableAutoUpdateCheck =
|
||||||
proxy.host = *jsonConfig.bot.proxyHost;
|
jsonConfig.features.enableAutoUpdateCheck;
|
||||||
proxy.port = *jsonConfig.bot.proxyPort;
|
config.features.autoStartOnSubscribe =
|
||||||
proxy.username = jsonConfig.bot.proxyUsername;
|
jsonConfig.features.autoStartOnSubscribe;
|
||||||
proxy.password = jsonConfig.bot.proxyPassword;
|
config.features.pauseOnEmptySubscribers =
|
||||||
// Parse proxy type (default to HTTP)
|
jsonConfig.features.pauseOnEmptySubscribers;
|
||||||
if (jsonConfig.bot.proxyType.has_value()) {
|
config.features.resumeOnSubscriberReturn =
|
||||||
const auto& typeStr = *jsonConfig.bot.proxyType;
|
jsonConfig.features.resumeOnSubscriberReturn;
|
||||||
if (typeStr == "SOCKS5" || typeStr == "socks5") {
|
config.features.shuffleMode = jsonConfig.features.shuffleMode;
|
||||||
proxy.type = Api::ProxyType::SOCKS5;
|
config.features.repeatMode = jsonConfig.features.repeatMode;
|
||||||
} else {
|
config.features.maxHistorySize = jsonConfig.features.maxHistorySize;
|
||||||
proxy.type = Api::ProxyType::HTTP;
|
|
||||||
}
|
// Advanced config
|
||||||
} else {
|
config.advanced.sampleRate = jsonConfig.advanced.sampleRate;
|
||||||
proxy.type = Api::ProxyType::HTTP;
|
config.advanced.channels = jsonConfig.advanced.channels;
|
||||||
}
|
config.advanced.bufferSize = jsonConfig.advanced.bufferSize;
|
||||||
config.bot.proxy = proxy;
|
config.advanced.commandThreadPoolSize =
|
||||||
}
|
jsonConfig.advanced.commandThreadPoolSize;
|
||||||
|
config.advanced.networkThreadPoolSize =
|
||||||
// YouTube API key
|
jsonConfig.advanced.networkThreadPoolSize;
|
||||||
if (jsonConfig.bot.youtubeApiKey.has_value()) {
|
config.advanced.decoderThreads = jsonConfig.advanced.decoderThreads;
|
||||||
config.bot.youtubeApiKey = jsonConfig.bot.youtubeApiKey;
|
config.advanced.cacheEnabled = jsonConfig.advanced.cacheEnabled;
|
||||||
}
|
config.advanced.cacheMaxSize = jsonConfig.advanced.cacheMaxSize;
|
||||||
|
config.advanced.cacheTTL = jsonConfig.advanced.cacheTTL;
|
||||||
// YouTube cookies
|
config.advanced.tempCleanupInterval =
|
||||||
if (jsonConfig.bot.youtubeCookiesPath.has_value()) {
|
jsonConfig.advanced.tempCleanupInterval;
|
||||||
config.bot.youtubeCookiesPath = jsonConfig.bot.youtubeCookiesPath;
|
|
||||||
}
|
std::cout << std::format("[INFO] Configuration loaded from {}",
|
||||||
if (jsonConfig.bot.cookiesFromBrowser.has_value()) {
|
path.string())
|
||||||
config.bot.cookiesFromBrowser = jsonConfig.bot.cookiesFromBrowser;
|
<< std::endl;
|
||||||
}
|
return config;
|
||||||
|
}
|
||||||
// yt-dlp settings
|
|
||||||
config.bot.ytDlpMaxConcurrent = std::min(static_cast<size_t>(jsonConfig.bot.ytDlpMaxConcurrent), size_t(8));
|
Api::Result<void>
|
||||||
config.bot.ytDlpAsyncEnabled = jsonConfig.bot.ytDlpAsyncEnabled;
|
ConfigLoader::saveToFile(const std::filesystem::path& path,
|
||||||
|
const Api::AppConfig& config)
|
||||||
// URL shortening settings
|
{
|
||||||
config.bot.enableUrlShortening = jsonConfig.bot.enableUrlShortening;
|
AppConfigJson jsonConfig;
|
||||||
|
|
||||||
// Server config
|
// Bot config
|
||||||
config.server.address = jsonConfig.server.address;
|
jsonConfig.bot.botName = config.bot.botName;
|
||||||
config.server.port = jsonConfig.server.port;
|
jsonConfig.bot.commandPrefix = config.bot.commandPrefix;
|
||||||
config.server.serverPassword = jsonConfig.server.serverPassword;
|
jsonConfig.bot.defaultVolume = config.bot.defaultVolume;
|
||||||
config.server.nickname = jsonConfig.server.nickname;
|
jsonConfig.bot.maxQueueSize = config.bot.maxQueueSize;
|
||||||
config.server.defaultChannelId = jsonConfig.server.defaultChannelId;
|
jsonConfig.bot.trackTimeout =
|
||||||
config.server.channelPassword = jsonConfig.server.channelPassword;
|
static_cast<uint32_t>(config.bot.trackTimeout.count());
|
||||||
config.server.adminGroups = jsonConfig.server.adminGroups;
|
jsonConfig.bot.autoReconnect = config.bot.autoReconnect;
|
||||||
config.server.djGroups = jsonConfig.server.djGroups;
|
jsonConfig.bot.reconnectDelay =
|
||||||
config.server.bannedGroups = jsonConfig.server.bannedGroups;
|
static_cast<uint32_t>(config.bot.reconnectDelay.count());
|
||||||
|
jsonConfig.bot.maxReconnectAttempts = config.bot.maxReconnectAttempts;
|
||||||
// Security config
|
jsonConfig.bot.preferredQuality =
|
||||||
config.security.requireAuthForAdmin = jsonConfig.security.requireAuthForAdmin;
|
qualityToString(config.bot.preferredQuality);
|
||||||
config.security.maxLoginAttempts = jsonConfig.security.maxLoginAttempts;
|
jsonConfig.bot.allowPlaylistImports = config.bot.allowPlaylistImports;
|
||||||
config.security.lockoutDuration = std::chrono::milliseconds(jsonConfig.security.lockoutDuration);
|
|
||||||
config.security.sessionTimeout = std::chrono::milliseconds(jsonConfig.security.sessionTimeout);
|
// YouTube config
|
||||||
config.security.enableAuditLog = jsonConfig.security.enableAuditLog;
|
if (config.youtube.youtubeApiKey.has_value()) {
|
||||||
|
jsonConfig.youtube.youtubeApiKey = *config.youtube.youtubeApiKey;
|
||||||
ECHOION_LOG_INFO(std::format("Configuration loaded from {}", path.string()));
|
}
|
||||||
return config;
|
if (config.youtube.youtubeCookiesPath.has_value()) {
|
||||||
}
|
jsonConfig.youtube.youtubeCookiesPath =
|
||||||
|
*config.youtube.youtubeCookiesPath;
|
||||||
Api::Result<void> ConfigLoader::saveToFile(const std::filesystem::path& path, const Api::AppConfig& config) {
|
}
|
||||||
AppConfigJson jsonConfig;
|
if (config.youtube.cookiesFromBrowser.has_value()) {
|
||||||
|
jsonConfig.youtube.cookiesFromBrowser =
|
||||||
// Bot config
|
*config.youtube.cookiesFromBrowser;
|
||||||
jsonConfig.bot.botName = config.bot.botName;
|
}
|
||||||
jsonConfig.bot.commandPrefix = config.bot.commandPrefix;
|
jsonConfig.youtube.ytDlpMaxConcurrent =
|
||||||
jsonConfig.bot.defaultVolume = config.bot.defaultVolume;
|
static_cast<uint32_t>(config.youtube.ytDlpMaxConcurrent);
|
||||||
jsonConfig.bot.autoReconnect = config.bot.autoReconnect;
|
jsonConfig.youtube.ytDlpAsyncEnabled = config.youtube.ytDlpAsyncEnabled;
|
||||||
jsonConfig.bot.reconnectDelay = static_cast<uint32_t>(config.bot.reconnectDelay.count());
|
jsonConfig.youtube.enableUrlShortening =
|
||||||
jsonConfig.bot.maxReconnectAttempts = config.bot.maxReconnectAttempts;
|
config.youtube.enableUrlShortening;
|
||||||
jsonConfig.bot.preferredQuality = qualityToString(config.bot.preferredQuality);
|
|
||||||
jsonConfig.bot.allowPlaylistImports = config.bot.allowPlaylistImports;
|
// Network config
|
||||||
jsonConfig.bot.maxQueueSize = config.bot.maxQueueSize;
|
if (config.network.proxy.has_value()) {
|
||||||
jsonConfig.bot.trackTimeout = static_cast<uint32_t>(config.bot.trackTimeout.count());
|
jsonConfig.network.proxyHost = config.network.proxy->host;
|
||||||
|
jsonConfig.network.proxyPort = config.network.proxy->port;
|
||||||
// Proxy config
|
jsonConfig.network.proxyUsername = config.network.proxy->username;
|
||||||
if (config.bot.proxy.has_value()) {
|
jsonConfig.network.proxyPassword = config.network.proxy->password;
|
||||||
jsonConfig.bot.proxyHost = config.bot.proxy->host;
|
jsonConfig.network.proxyType =
|
||||||
jsonConfig.bot.proxyPort = config.bot.proxy->port;
|
config.network.proxy->type == Api::ProxyType::SOCKS5 ? "SOCKS5"
|
||||||
jsonConfig.bot.proxyUsername = config.bot.proxy->username;
|
: "HTTP";
|
||||||
jsonConfig.bot.proxyPassword = config.bot.proxy->password;
|
}
|
||||||
jsonConfig.bot.proxyType = config.bot.proxy->type == Api::ProxyType::SOCKS5 ? "SOCKS5" : "HTTP";
|
jsonConfig.network.rpcEnabled = config.network.rpcEnabled;
|
||||||
}
|
jsonConfig.network.rpcPort = config.network.rpcPort;
|
||||||
|
jsonConfig.network.rpcBindAddress = config.network.rpcBindAddress;
|
||||||
// YouTube API key
|
|
||||||
if (config.bot.youtubeApiKey.has_value()) {
|
// TeamSpeak config
|
||||||
jsonConfig.bot.youtubeApiKey = *config.bot.youtubeApiKey;
|
jsonConfig.teamspeak.address = config.teamspeak.address;
|
||||||
}
|
jsonConfig.teamspeak.port = config.teamspeak.port;
|
||||||
|
jsonConfig.teamspeak.serverPassword = config.teamspeak.serverPassword;
|
||||||
// YouTube cookies
|
jsonConfig.teamspeak.nickname = config.teamspeak.nickname;
|
||||||
if (config.bot.youtubeCookiesPath.has_value()) {
|
jsonConfig.teamspeak.defaultChannelId =
|
||||||
jsonConfig.bot.youtubeCookiesPath = *config.bot.youtubeCookiesPath;
|
config.teamspeak.defaultChannelId;
|
||||||
}
|
jsonConfig.teamspeak.channelPassword = config.teamspeak.channelPassword;
|
||||||
if (config.bot.cookiesFromBrowser.has_value()) {
|
jsonConfig.teamspeak.adminGroups = config.teamspeak.adminGroups;
|
||||||
jsonConfig.bot.cookiesFromBrowser = *config.bot.cookiesFromBrowser;
|
jsonConfig.teamspeak.djGroups = config.teamspeak.djGroups;
|
||||||
}
|
jsonConfig.teamspeak.bannedGroups = config.teamspeak.bannedGroups;
|
||||||
|
|
||||||
// yt-dlp settings
|
// Security config
|
||||||
jsonConfig.bot.ytDlpMaxConcurrent = static_cast<uint32_t>(config.bot.ytDlpMaxConcurrent);
|
jsonConfig.security.requireAuthForAdmin =
|
||||||
jsonConfig.bot.ytDlpAsyncEnabled = config.bot.ytDlpAsyncEnabled;
|
config.security.requireAuthForAdmin;
|
||||||
|
jsonConfig.security.maxLoginAttempts = config.security.maxLoginAttempts;
|
||||||
// URL shortening settings
|
jsonConfig.security.lockoutDuration =
|
||||||
jsonConfig.bot.enableUrlShortening = config.bot.enableUrlShortening;
|
static_cast<uint32_t>(config.security.lockoutDuration.count());
|
||||||
|
jsonConfig.security.sessionTimeout =
|
||||||
// Server config
|
static_cast<uint32_t>(config.security.sessionTimeout.count());
|
||||||
jsonConfig.server.address = config.server.address;
|
jsonConfig.security.enableAuditLog = config.security.enableAuditLog;
|
||||||
jsonConfig.server.port = config.server.port;
|
if (config.security.apiKey.has_value()) {
|
||||||
jsonConfig.server.serverPassword = config.server.serverPassword;
|
jsonConfig.security.apiKey = *config.security.apiKey;
|
||||||
jsonConfig.server.nickname = config.server.nickname;
|
}
|
||||||
jsonConfig.server.defaultChannelId = config.server.defaultChannelId;
|
jsonConfig.security.allowCors = config.security.allowCors;
|
||||||
jsonConfig.server.channelPassword = config.server.channelPassword;
|
jsonConfig.security.corsOrigins = config.security.corsOrigins;
|
||||||
jsonConfig.server.adminGroups = config.server.adminGroups;
|
|
||||||
jsonConfig.server.djGroups = config.server.djGroups;
|
// Features config
|
||||||
jsonConfig.server.bannedGroups = config.server.bannedGroups;
|
jsonConfig.features.enableHotReload = config.features.enableHotReload;
|
||||||
|
jsonConfig.features.enableAutoReload = config.features.enableAutoReload;
|
||||||
// Security config
|
jsonConfig.features.enableAutoUpdateCheck =
|
||||||
jsonConfig.security.requireAuthForAdmin = config.security.requireAuthForAdmin;
|
config.features.enableAutoUpdateCheck;
|
||||||
jsonConfig.security.maxLoginAttempts = config.security.maxLoginAttempts;
|
jsonConfig.features.autoStartOnSubscribe =
|
||||||
jsonConfig.security.lockoutDuration = static_cast<uint32_t>(config.security.lockoutDuration.count());
|
config.features.autoStartOnSubscribe;
|
||||||
jsonConfig.security.sessionTimeout = static_cast<uint32_t>(config.security.sessionTimeout.count());
|
jsonConfig.features.pauseOnEmptySubscribers =
|
||||||
jsonConfig.security.enableAuditLog = config.security.enableAuditLog;
|
config.features.pauseOnEmptySubscribers;
|
||||||
|
jsonConfig.features.resumeOnSubscriberReturn =
|
||||||
auto json = glz::write_json(jsonConfig);
|
config.features.resumeOnSubscriberReturn;
|
||||||
if (!json.has_value())
|
jsonConfig.features.shuffleMode = config.features.shuffleMode;
|
||||||
{
|
jsonConfig.features.repeatMode = config.features.repeatMode;
|
||||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
jsonConfig.features.maxHistorySize = config.features.maxHistorySize;
|
||||||
std::format("Failed to serialize: {}", json.error().custom_error_message)));
|
|
||||||
}
|
// Advanced config
|
||||||
std::ofstream file(path);
|
jsonConfig.advanced.sampleRate = config.advanced.sampleRate;
|
||||||
if (!file.is_open()) {
|
jsonConfig.advanced.channels = config.advanced.channels;
|
||||||
return std::unexpected(Api::Error(Api::ErrorCode::PermissionDenied,
|
jsonConfig.advanced.bufferSize = config.advanced.bufferSize;
|
||||||
std::format("Failed to write configuration file: {}", path.string())));
|
jsonConfig.advanced.commandThreadPoolSize =
|
||||||
}
|
config.advanced.commandThreadPoolSize;
|
||||||
|
jsonConfig.advanced.networkThreadPoolSize =
|
||||||
file << json.value();
|
config.advanced.networkThreadPoolSize;
|
||||||
file.close();
|
jsonConfig.advanced.decoderThreads = config.advanced.decoderThreads;
|
||||||
|
jsonConfig.advanced.cacheEnabled = config.advanced.cacheEnabled;
|
||||||
ECHOION_LOG_INFO(std::format("Configuration saved to {}", path.string()));
|
jsonConfig.advanced.cacheMaxSize = config.advanced.cacheMaxSize;
|
||||||
return {};
|
jsonConfig.advanced.cacheTTL = config.advanced.cacheTTL;
|
||||||
}
|
jsonConfig.advanced.tempCleanupInterval =
|
||||||
|
config.advanced.tempCleanupInterval;
|
||||||
std::filesystem::path ConfigLoader::getDefaultConfigPath() {
|
|
||||||
// Try to get config path from environment or use default
|
const std::string json = Void::Json::serialize(
|
||||||
const char* configHome = std::getenv("XDG_CONFIG_HOME");
|
Void::Json::to_json(jsonConfig), {.pretty = true});
|
||||||
if (configHome) {
|
std::ofstream file(path);
|
||||||
return std::filesystem::path(configHome) / "echoion" / "config.json";
|
if (!file.is_open()) {
|
||||||
}
|
return std::unexpected(
|
||||||
|
Api::Error(Api::ErrorCode::PermissionDenied,
|
||||||
const char* home = std::getenv("HOME");
|
std::format("Failed to write configuration file: {}",
|
||||||
if (home) {
|
path.string())));
|
||||||
return std::filesystem::path(home) / ".config" / "echoion" / "config.json";
|
}
|
||||||
}
|
|
||||||
|
file << json;
|
||||||
// Fallback to current directory
|
file.close();
|
||||||
return "echoion_config.json";
|
|
||||||
}
|
ECHOION_LOG_INFO(
|
||||||
|
std::format("Configuration saved to {}", path.string()));
|
||||||
Api::AppConfig ConfigLoader::createDefaultConfig() {
|
return {};
|
||||||
Api::AppConfig config;
|
}
|
||||||
|
|
||||||
// Default bot config
|
std::filesystem::path ConfigLoader::getDefaultConfigPath()
|
||||||
config.bot.botName = "Echoion";
|
{
|
||||||
config.bot.commandPrefix = "!";
|
// Try to get config path from environment or use default
|
||||||
config.bot.defaultVolume = 0.5f;
|
const char* configHome = std::getenv("XDG_CONFIG_HOME");
|
||||||
config.bot.autoReconnect = true;
|
if (configHome) {
|
||||||
config.bot.reconnectDelay = std::chrono::milliseconds(5000);
|
return std::filesystem::path(configHome) / "echoion" /
|
||||||
config.bot.maxReconnectAttempts = 5;
|
"config.json";
|
||||||
config.bot.preferredQuality = Api::AudioQuality::High;
|
}
|
||||||
config.bot.allowPlaylistImports = true;
|
|
||||||
config.bot.maxQueueSize = 100;
|
const char* home = std::getenv("HOME");
|
||||||
config.bot.trackTimeout = std::chrono::milliseconds(30000);
|
if (home) {
|
||||||
config.bot.ytDlpMaxConcurrent = 4;
|
return std::filesystem::path(home) / ".config" / "echoion" /
|
||||||
config.bot.ytDlpAsyncEnabled = true;
|
"config.json";
|
||||||
config.bot.enableUrlShortening = true;
|
}
|
||||||
|
|
||||||
// Default server config
|
// Fallback to current directory
|
||||||
config.server.address = "localhost";
|
return "echoion_config.json";
|
||||||
config.server.port = 9987;
|
}
|
||||||
config.server.nickname = "EchoionBot";
|
|
||||||
|
Api::AppConfig ConfigLoader::createDefaultConfig()
|
||||||
// Default security config
|
{
|
||||||
config.security.requireAuthForAdmin = true;
|
Api::AppConfig config;
|
||||||
config.security.maxLoginAttempts = 5;
|
|
||||||
config.security.lockoutDuration = std::chrono::milliseconds(300000);
|
// Default bot config
|
||||||
config.security.sessionTimeout = std::chrono::milliseconds(3600000);
|
config.bot.botName = "Echoion";
|
||||||
config.security.enableAuditLog = true;
|
config.bot.commandPrefix = "!";
|
||||||
|
config.bot.defaultVolume = 0.5f;
|
||||||
return config;
|
config.bot.maxQueueSize = 100;
|
||||||
}
|
config.bot.trackTimeout = std::chrono::milliseconds(30000);
|
||||||
|
config.bot.autoReconnect = true;
|
||||||
Api::AudioQuality ConfigLoader::parseQuality(const std::string& str) {
|
config.bot.reconnectDelay = std::chrono::milliseconds(5000);
|
||||||
if (str == "Low") return Api::AudioQuality::Low;
|
config.bot.maxReconnectAttempts = 5;
|
||||||
if (str == "Medium") return Api::AudioQuality::Medium;
|
config.bot.preferredQuality = Api::AudioQuality::High;
|
||||||
if (str == "High") return Api::AudioQuality::High;
|
config.bot.allowPlaylistImports = true;
|
||||||
if (str == "VeryHigh") return Api::AudioQuality::VeryHigh;
|
|
||||||
if (str == "Lossless") return Api::AudioQuality::Lossless;
|
// Default YouTube config
|
||||||
return Api::AudioQuality::High; // Default
|
config.youtube.ytDlpMaxConcurrent = 4;
|
||||||
}
|
config.youtube.ytDlpAsyncEnabled = true;
|
||||||
|
config.youtube.enableUrlShortening = true;
|
||||||
std::string ConfigLoader::qualityToString(Api::AudioQuality quality) {
|
|
||||||
switch (quality) {
|
// Default network config
|
||||||
case Api::AudioQuality::Low: return "Low";
|
config.network.rpcEnabled = true;
|
||||||
case Api::AudioQuality::Medium: return "Medium";
|
config.network.rpcPort = 8765;
|
||||||
case Api::AudioQuality::High: return "High";
|
config.network.rpcBindAddress = "127.0.0.1";
|
||||||
case Api::AudioQuality::VeryHigh: return "VeryHigh";
|
|
||||||
case Api::AudioQuality::Lossless: return "Lossless";
|
// Default TeamSpeak config
|
||||||
default: return "High";
|
config.teamspeak.address = "localhost";
|
||||||
}
|
config.teamspeak.port = 9987;
|
||||||
}
|
config.teamspeak.nickname = "EchoionBot";
|
||||||
|
|
||||||
|
// Default security config
|
||||||
|
config.security.requireAuthForAdmin = true;
|
||||||
|
config.security.maxLoginAttempts = 5;
|
||||||
|
config.security.lockoutDuration = std::chrono::milliseconds(300000);
|
||||||
|
config.security.sessionTimeout = std::chrono::milliseconds(3600000);
|
||||||
|
config.security.enableAuditLog = true;
|
||||||
|
config.security.allowCors = false;
|
||||||
|
|
||||||
|
// Default features config
|
||||||
|
config.features.enableHotReload = true;
|
||||||
|
config.features.enableAutoReload = false;
|
||||||
|
config.features.enableAutoUpdateCheck = true;
|
||||||
|
config.features.autoStartOnSubscribe = true;
|
||||||
|
config.features.pauseOnEmptySubscribers = true;
|
||||||
|
config.features.resumeOnSubscriberReturn = true;
|
||||||
|
config.features.shuffleMode = "random";
|
||||||
|
config.features.repeatMode = "off";
|
||||||
|
config.features.maxHistorySize = 50;
|
||||||
|
|
||||||
|
// Default advanced config
|
||||||
|
config.advanced.sampleRate = 192000;
|
||||||
|
config.advanced.channels = 2;
|
||||||
|
config.advanced.bufferSize = 7680;
|
||||||
|
config.advanced.commandThreadPoolSize = 4;
|
||||||
|
config.advanced.networkThreadPoolSize = 4;
|
||||||
|
config.advanced.decoderThreads = 2;
|
||||||
|
config.advanced.cacheEnabled = true;
|
||||||
|
config.advanced.cacheMaxSize = "1GB";
|
||||||
|
config.advanced.cacheTTL = 86400;
|
||||||
|
config.advanced.tempCleanupInterval = 3600;
|
||||||
|
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
Api::AudioQuality ConfigLoader::parseQuality(const std::string& str)
|
||||||
|
{
|
||||||
|
if (str == "Low") {
|
||||||
|
return Api::AudioQuality::Low;
|
||||||
|
}
|
||||||
|
if (str == "Medium") {
|
||||||
|
return Api::AudioQuality::Medium;
|
||||||
|
}
|
||||||
|
if (str == "High") {
|
||||||
|
return Api::AudioQuality::High;
|
||||||
|
}
|
||||||
|
if (str == "VeryHigh") {
|
||||||
|
return Api::AudioQuality::VeryHigh;
|
||||||
|
}
|
||||||
|
if (str == "Lossless") {
|
||||||
|
return Api::AudioQuality::Lossless;
|
||||||
|
}
|
||||||
|
return Api::AudioQuality::High; // Default
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string ConfigLoader::qualityToString(Api::AudioQuality quality)
|
||||||
|
{
|
||||||
|
switch (quality) {
|
||||||
|
case Api::AudioQuality::Low:
|
||||||
|
return "Low";
|
||||||
|
case Api::AudioQuality::Medium:
|
||||||
|
return "Medium";
|
||||||
|
case Api::AudioQuality::High:
|
||||||
|
return "High";
|
||||||
|
case Api::AudioQuality::VeryHigh:
|
||||||
|
return "VeryHigh";
|
||||||
|
case Api::AudioQuality::Lossless:
|
||||||
|
return "Lossless";
|
||||||
|
default:
|
||||||
|
return "High";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
#include "ConfigManager.hpp"
|
||||||
|
#include "echoion/core/ConfigLoader.hpp"
|
||||||
|
#include <format>
|
||||||
|
#include <iostream>
|
||||||
|
|
||||||
|
namespace Echoion::Api
|
||||||
|
{
|
||||||
|
|
||||||
|
ConfigManager& ConfigManager::instance()
|
||||||
|
{
|
||||||
|
static ConfigManager instance;
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ConfigManager::initialize(const std::filesystem::path& configPath)
|
||||||
|
{
|
||||||
|
std::unique_lock lock(mutex_);
|
||||||
|
configPath_ = configPath;
|
||||||
|
bool success = loadFromFileInternal();
|
||||||
|
initialized_.store(success);
|
||||||
|
return success;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ConfigManager::initialize()
|
||||||
|
{
|
||||||
|
return initialize(getDefaultConfigPath());
|
||||||
|
}
|
||||||
|
|
||||||
|
AppConfig ConfigManager::getConfig() const
|
||||||
|
{
|
||||||
|
std::shared_lock lock(mutex_);
|
||||||
|
return config_;
|
||||||
|
}
|
||||||
|
|
||||||
|
const BotConfig& ConfigManager::getBot() const
|
||||||
|
{
|
||||||
|
std::shared_lock lock(mutex_);
|
||||||
|
return config_.bot;
|
||||||
|
}
|
||||||
|
|
||||||
|
const YouTubeConfig& ConfigManager::getYouTube() const
|
||||||
|
{
|
||||||
|
std::shared_lock lock(mutex_);
|
||||||
|
return config_.youtube;
|
||||||
|
}
|
||||||
|
|
||||||
|
const NetworkConfig& ConfigManager::getNetwork() const
|
||||||
|
{
|
||||||
|
std::shared_lock lock(mutex_);
|
||||||
|
return config_.network;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TeamSpeakConfig& ConfigManager::getTeamSpeak() const
|
||||||
|
{
|
||||||
|
std::shared_lock lock(mutex_);
|
||||||
|
return config_.teamspeak;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SecurityConfig& ConfigManager::getSecurity() const
|
||||||
|
{
|
||||||
|
std::shared_lock lock(mutex_);
|
||||||
|
return config_.security;
|
||||||
|
}
|
||||||
|
|
||||||
|
const FeaturesConfig& ConfigManager::getFeatures() const
|
||||||
|
{
|
||||||
|
std::shared_lock lock(mutex_);
|
||||||
|
return config_.features;
|
||||||
|
}
|
||||||
|
|
||||||
|
const AdvancedConfig& ConfigManager::getAdvanced() const
|
||||||
|
{
|
||||||
|
std::shared_lock lock(mutex_);
|
||||||
|
return config_.advanced;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ConfigManager::reload()
|
||||||
|
{
|
||||||
|
std::unique_lock lock(mutex_);
|
||||||
|
return loadFromFileInternal();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ConfigManager::save()
|
||||||
|
{
|
||||||
|
std::shared_lock lock(mutex_);
|
||||||
|
return saveToFileInternal();
|
||||||
|
}
|
||||||
|
|
||||||
|
void ConfigManager::updateConfig(const AppConfig& config, bool saveToFile)
|
||||||
|
{
|
||||||
|
{
|
||||||
|
std::unique_lock lock(mutex_);
|
||||||
|
config_ = config;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (saveToFile) {
|
||||||
|
save();
|
||||||
|
}
|
||||||
|
|
||||||
|
notifyCallbacks();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ConfigManager::isInitialized() const { return initialized_.load(); }
|
||||||
|
|
||||||
|
std::filesystem::path ConfigManager::getConfigPath() const
|
||||||
|
{
|
||||||
|
std::shared_lock lock(mutex_);
|
||||||
|
return configPath_;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::filesystem::path ConfigManager::getDefaultConfigPath()
|
||||||
|
{
|
||||||
|
const char* configHome = std::getenv("XDG_CONFIG_HOME");
|
||||||
|
if (configHome) {
|
||||||
|
return std::filesystem::path(configHome) / "echoion" /
|
||||||
|
"config.json";
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* home = std::getenv("HOME");
|
||||||
|
if (home) {
|
||||||
|
return std::filesystem::path(home) / ".config" / "echoion" /
|
||||||
|
"config.json";
|
||||||
|
}
|
||||||
|
|
||||||
|
return "echoion_config.json";
|
||||||
|
}
|
||||||
|
|
||||||
|
void ConfigManager::onConfigChanged(ConfigChangedCallback callback)
|
||||||
|
{
|
||||||
|
std::unique_lock lock(callbackMutex_);
|
||||||
|
callbacks_.push_back(std::move(callback));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ConfigManager::createDefaultConfigIfNeeded()
|
||||||
|
{
|
||||||
|
if (!std::filesystem::exists(configPath_)) {
|
||||||
|
std::filesystem::create_directories(configPath_.parent_path());
|
||||||
|
return save();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ConfigManager::notifyCallbacks()
|
||||||
|
{
|
||||||
|
std::shared_lock lock(mutex_);
|
||||||
|
std::shared_lock cbLock(callbackMutex_);
|
||||||
|
|
||||||
|
for (const auto& callback : callbacks_) {
|
||||||
|
callback(config_);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ConfigManager::loadFromFileInternal()
|
||||||
|
{
|
||||||
|
// Delegate to Core::ConfigLoader, which performs the JSON <-> AppConfig
|
||||||
|
// mapping (via the *Json mirror structs and Void::Json reflection).
|
||||||
|
auto result = Core::ConfigLoader::loadFromFile(configPath_);
|
||||||
|
if (!result) {
|
||||||
|
std::cerr << std::format("Failed to load config: {}\n",
|
||||||
|
result.error().toString());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
config_ = std::move(*result);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ConfigManager::saveToFileInternal()
|
||||||
|
{
|
||||||
|
auto result = Core::ConfigLoader::saveToFile(configPath_, config_);
|
||||||
|
if (!result) {
|
||||||
|
std::cerr << std::format("Failed to save config: {}\n",
|
||||||
|
result.error().toString());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Echoion::Api
|
||||||
+2080
-958
File diff suppressed because it is too large.
Load diff
+1091
-639
File diff suppressed because it is too large.
Load diff
+10
-181
@@ -1,185 +1,14 @@
|
|||||||
#include "echoion/api/EventBus.hpp"
|
#include <EventBus.hpp>
|
||||||
#include "echoion/core/Logger.hpp"
|
|
||||||
#include <format>
|
|
||||||
|
|
||||||
namespace Echoion::Api {
|
namespace Echoion::Api
|
||||||
|
{
|
||||||
|
|
||||||
// Global event bus instance
|
// Global event bus instance. The EventBus type is otherwise header-only
|
||||||
EventBus& GlobalEventBus::instance() {
|
// (it delegates to Void::EventBus); only the singleton lives here.
|
||||||
static EventBus instance;
|
EventBus& GlobalEventBus::instance()
|
||||||
return instance;
|
{
|
||||||
}
|
static EventBus instance;
|
||||||
|
return instance;
|
||||||
EventBus::EventBus() = default;
|
}
|
||||||
|
|
||||||
EventBus::~EventBus() {
|
|
||||||
stop();
|
|
||||||
}
|
|
||||||
|
|
||||||
void EventBus::start() {
|
|
||||||
if (running_.exchange(true)) {
|
|
||||||
return; // Already running
|
|
||||||
}
|
|
||||||
|
|
||||||
stopRequested_ = false;
|
|
||||||
eventThread_ = std::jthread([this] { processEvents(); });
|
|
||||||
ECHOION_LOG_INFO("EventBus started");
|
|
||||||
}
|
|
||||||
|
|
||||||
void EventBus::stop() {
|
|
||||||
if (!running_.exchange(false)) {
|
|
||||||
return; // Not running
|
|
||||||
}
|
|
||||||
|
|
||||||
stopRequested_ = true;
|
|
||||||
queueCv_.notify_all();
|
|
||||||
|
|
||||||
if (eventThread_.joinable()) {
|
|
||||||
eventThread_.join();
|
|
||||||
}
|
|
||||||
|
|
||||||
ECHOION_LOG_INFO("EventBus stopped");
|
|
||||||
}
|
|
||||||
|
|
||||||
void EventBus::unsubscribe(const SubscriptionToken& token) {
|
|
||||||
if (!token.isValid()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::unique_lock<std::shared_mutex> lock(handlersMutex_);
|
|
||||||
auto it = handlers_.find(token.getType());
|
|
||||||
if (it != handlers_.end()) {
|
|
||||||
it->second.erase(token.getId());
|
|
||||||
if (it->second.empty()) {
|
|
||||||
handlers_.erase(it);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void EventBus::processOne() {
|
|
||||||
std::shared_ptr<IEvent> evt;
|
|
||||||
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(queueMutex_);
|
|
||||||
if (eventQueue_.empty()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
evt = std::move(eventQueue_.front());
|
|
||||||
eventQueue_.pop();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get handlers for this event type
|
|
||||||
std::shared_lock<std::shared_mutex> lock(handlersMutex_);
|
|
||||||
auto it = handlers_.find(evt->getType());
|
|
||||||
if (it != handlers_.end()) {
|
|
||||||
// Copy handlers to avoid holding lock during callback
|
|
||||||
auto handlers = it->second;
|
|
||||||
lock.unlock();
|
|
||||||
|
|
||||||
for (const auto& [id, handler] : handlers) {
|
|
||||||
try {
|
|
||||||
if (handler) {
|
|
||||||
(*handler)(evt);
|
|
||||||
}
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("Event handler exception: {}", e.what()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool EventBus::waitAndProcessOne(std::chrono::milliseconds timeout) {
|
|
||||||
std::shared_ptr<IEvent> evt;
|
|
||||||
|
|
||||||
{
|
|
||||||
std::unique_lock<std::mutex> lock(queueMutex_);
|
|
||||||
if (!queueCv_.wait_for(lock, timeout, [this] {
|
|
||||||
return !eventQueue_.empty() || stopRequested_.load();
|
|
||||||
})) {
|
|
||||||
return false; // Timeout
|
|
||||||
}
|
|
||||||
|
|
||||||
if (stopRequested_ || eventQueue_.empty()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
evt = std::move(eventQueue_.front());
|
|
||||||
eventQueue_.pop();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get handlers for this event type
|
|
||||||
std::shared_lock<std::shared_mutex> lock(handlersMutex_);
|
|
||||||
auto it = handlers_.find(evt->getType());
|
|
||||||
if (it != handlers_.end()) {
|
|
||||||
auto handlers = it->second;
|
|
||||||
lock.unlock();
|
|
||||||
|
|
||||||
for (const auto& [id, handler] : handlers) {
|
|
||||||
try {
|
|
||||||
if (handler) {
|
|
||||||
(*handler)(evt);
|
|
||||||
}
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("Event handler exception: {}", e.what()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
void EventBus::clearQueue() {
|
|
||||||
std::lock_guard<std::mutex> lock(queueMutex_);
|
|
||||||
std::queue<std::shared_ptr<IEvent>> empty;
|
|
||||||
std::swap(eventQueue_, empty);
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t EventBus::getPendingEventCount() const {
|
|
||||||
std::lock_guard<std::mutex> lock(queueMutex_);
|
|
||||||
return eventQueue_.size();
|
|
||||||
}
|
|
||||||
|
|
||||||
void EventBus::processEvents() {
|
|
||||||
while (!stopRequested_) {
|
|
||||||
std::shared_ptr<IEvent> evt;
|
|
||||||
|
|
||||||
{
|
|
||||||
std::unique_lock<std::mutex> lock(queueMutex_);
|
|
||||||
queueCv_.wait(lock, [this] {
|
|
||||||
return !eventQueue_.empty() || stopRequested_.load();
|
|
||||||
});
|
|
||||||
|
|
||||||
if (stopRequested_) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (eventQueue_.empty()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
evt = std::move(eventQueue_.front());
|
|
||||||
eventQueue_.pop();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get handlers for this event type
|
|
||||||
std::shared_lock<std::shared_mutex> lock(handlersMutex_);
|
|
||||||
auto it = handlers_.find(evt->getType());
|
|
||||||
if (it != handlers_.end()) {
|
|
||||||
// Copy handlers to avoid holding lock during callback
|
|
||||||
auto handlers = it->second;
|
|
||||||
lock.unlock();
|
|
||||||
|
|
||||||
for (const auto& [id, handler] : handlers) {
|
|
||||||
try {
|
|
||||||
if (handler) {
|
|
||||||
(*handler)(evt);
|
|
||||||
}
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("Event handler exception: {}", e.what()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Echoion::Api
|
} // namespace Echoion::Api
|
||||||
+10
-14
@@ -1,23 +1,19 @@
|
|||||||
#include "echoion/api/Export.hpp"
|
#include <Export.hpp>
|
||||||
#include "echoion/core/Core.hpp"
|
#include "echoion/core/Core.hpp"
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
|
||||||
namespace Echoion::Api {
|
namespace Echoion::Api
|
||||||
|
{
|
||||||
|
|
||||||
CoreInterfacePtr CreateCore() {
|
CoreInterfacePtr CreateCore() { return std::make_shared<Core::Core>(); }
|
||||||
return std::make_shared<Core::Core>();
|
|
||||||
}
|
|
||||||
|
|
||||||
void DestroyCore(ICoreInterface* core) {
|
void DestroyCore(ICoreInterface* core) { delete core; }
|
||||||
delete core;
|
|
||||||
}
|
|
||||||
|
|
||||||
const char* GetApiVersion() {
|
const char* GetApiVersion() { return VERSION_STRING; }
|
||||||
return VERSION_STRING;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool IsApiCompatible(uint32_t major, uint32_t minor) {
|
bool IsApiCompatible(uint32_t major, uint32_t minor)
|
||||||
return major == VERSION_MAJOR && minor <= VERSION_MINOR;
|
{
|
||||||
}
|
return major == VERSION_MAJOR && minor <= VERSION_MINOR;
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace Echoion::Api
|
} // namespace Echoion::Api
|
||||||
+185
-353
@@ -1,381 +1,213 @@
|
|||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <iostream>
|
|
||||||
#include <format>
|
#include <Void/Log/ConsoleLogger.hpp>
|
||||||
|
#include <Void/Log/Entry.hpp>
|
||||||
|
#include <Void/Log/Formatter.hpp>
|
||||||
|
#include <Void/Log/Level.hpp>
|
||||||
|
#include <Void/Log/Sinks.hpp>
|
||||||
|
#include <Void/Log/SplitFileLogger.hpp>
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
#include <iostream>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace
|
||||||
|
{
|
||||||
|
[[nodiscard]] Void::Logging::Level toVoidLevel(Echoion::Api::LogLevel level)
|
||||||
|
{
|
||||||
|
using A = Echoion::Api::LogLevel;
|
||||||
|
using V = Void::Logging::Level;
|
||||||
|
switch (level) {
|
||||||
|
case A::Debug:
|
||||||
|
return V::Debug;
|
||||||
|
case A::Info:
|
||||||
|
return V::Info;
|
||||||
|
case A::Warning:
|
||||||
|
return V::Warning;
|
||||||
|
case A::Error:
|
||||||
|
return V::Error;
|
||||||
|
case A::Critical:
|
||||||
|
return V::Fatal;
|
||||||
|
}
|
||||||
|
return V::Info;
|
||||||
|
}
|
||||||
|
|
||||||
Logger::Logger(std::string_view logDir, std::string_view baseName)
|
[[nodiscard]] Echoion::Api::LogLevel fromVoidLevel(Void::Logging::Level level)
|
||||||
: logDir_(logDir)
|
{
|
||||||
, baseName_(baseName) {
|
using A = Echoion::Api::LogLevel;
|
||||||
|
using V = Void::Logging::Level;
|
||||||
// Ensure log directory exists
|
switch (level) {
|
||||||
std::error_code ec;
|
case V::Trace:
|
||||||
std::filesystem::create_directories(logDir_, ec);
|
case V::Debug:
|
||||||
|
return A::Debug;
|
||||||
// Ensure history directory exists
|
case V::Info:
|
||||||
ensureHistoryDirExists();
|
return A::Info;
|
||||||
|
case V::Warning:
|
||||||
// Open log files for each level
|
return A::Warning;
|
||||||
openLogFiles();
|
case V::Error:
|
||||||
|
return A::Error;
|
||||||
// Start worker thread
|
case V::Fatal:
|
||||||
workerThread_ = std::thread(&Logger::logWorker, this);
|
return A::Critical;
|
||||||
}
|
case V::Disabled:
|
||||||
|
return A::Debug;
|
||||||
|
}
|
||||||
|
return A::Info;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
Logger::~Logger() {
|
namespace Echoion::Core
|
||||||
running_ = false;
|
{
|
||||||
cv_.notify_all();
|
|
||||||
if (workerThread_.joinable()) {
|
|
||||||
workerThread_.join();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close all file streams
|
|
||||||
std::lock_guard<std::mutex> lock(fileMutex_);
|
|
||||||
for (auto& [level, info] : levelFiles_) {
|
|
||||||
if (info.stream.is_open()) {
|
|
||||||
info.stream.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (combinedFile_.stream.is_open()) {
|
|
||||||
combinedFile_.stream.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void Logger::ensureHistoryDirExists() {
|
Logger::Logger(std::string_view logDir, std::string_view baseName)
|
||||||
std::error_code ec;
|
: logDir_(logDir), baseName_(baseName)
|
||||||
auto historyDir = logDir_ / "history";
|
{
|
||||||
std::filesystem::create_directories(historyDir, ec);
|
std::error_code ec;
|
||||||
}
|
std::filesystem::create_directories(logDir_, ec);
|
||||||
|
rebuildSinks();
|
||||||
|
}
|
||||||
|
|
||||||
void Logger::openLogFiles() {
|
Logger::~Logger()
|
||||||
std::lock_guard<std::mutex> lock(fileMutex_);
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(sinkMutex_);
|
||||||
// Open file for each log level
|
if (sink_) {
|
||||||
for (auto level : {Api::LogLevel::Debug, Api::LogLevel::Info,
|
sink_->flush();
|
||||||
Api::LogLevel::Warning, Api::LogLevel::Error, Api::LogLevel::Critical}) {
|
sink_.reset();
|
||||||
auto path = generateLogFilePath(level);
|
}
|
||||||
LogFileInfo info;
|
}
|
||||||
info.path = path;
|
|
||||||
info.stream.open(path, std::ios::app);
|
|
||||||
info.createdAt = std::chrono::system_clock::now();
|
|
||||||
|
|
||||||
// Get current file size
|
|
||||||
if (std::filesystem::exists(path)) {
|
|
||||||
info.size = std::filesystem::file_size(path);
|
|
||||||
}
|
|
||||||
|
|
||||||
levelFiles_[level] = std::move(info);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Open combined log file
|
|
||||||
auto combinedPath = logDir_ / std::format("{}_all.log", baseName_);
|
|
||||||
combinedFile_.path = combinedPath;
|
|
||||||
combinedFile_.stream.open(combinedPath, std::ios::app);
|
|
||||||
combinedFile_.createdAt = std::chrono::system_clock::now();
|
|
||||||
if (std::filesystem::exists(combinedPath)) {
|
|
||||||
combinedFile_.size = std::filesystem::file_size(combinedPath);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::filesystem::path Logger::generateLogFilePath(Api::LogLevel level) {
|
void Logger::rebuildSinks()
|
||||||
std::string levelStr;
|
{
|
||||||
switch (level) {
|
namespace VL = Void::Logging;
|
||||||
case Api::LogLevel::Debug: levelStr = "debug"; break;
|
|
||||||
case Api::LogLevel::Info: levelStr = "info"; break;
|
|
||||||
case Api::LogLevel::Warning: levelStr = "warning"; break;
|
|
||||||
case Api::LogLevel::Error: levelStr = "error"; break;
|
|
||||||
case Api::LogLevel::Critical: levelStr = "critical"; break;
|
|
||||||
default: levelStr = "unknown"; break;
|
|
||||||
}
|
|
||||||
return logDir_ / std::format("{}_{}.log", baseName_, levelStr);
|
|
||||||
}
|
|
||||||
|
|
||||||
void Logger::log(Api::LogLevel level, std::string_view message, std::source_location location) {
|
auto multi = std::make_shared<VL::MultiLogger>();
|
||||||
if (level < minLevel_.load()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Api::LogEntry entry;
|
|
||||||
entry.timestamp = std::chrono::system_clock::now();
|
|
||||||
entry.level = level;
|
|
||||||
entry.message = std::string(message);
|
|
||||||
entry.sourceFile = location.file_name();
|
|
||||||
entry.sourceLine = location.line();
|
|
||||||
entry.function = location.function_name();
|
|
||||||
entry.threadId = std::this_thread::get_id();
|
|
||||||
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(queueMutex_);
|
|
||||||
logQueue_.push(std::move(entry));
|
|
||||||
}
|
|
||||||
cv_.notify_one();
|
|
||||||
}
|
|
||||||
|
|
||||||
void Logger::logWorker() {
|
// Shared layout approximating the previous Logger output:
|
||||||
while (running_.load()) {
|
// [2024-01-01 12:00:00.123] [INFO] [thread] file.cpp - message
|
||||||
std::unique_lock<std::mutex> lock(queueMutex_);
|
auto formatter = std::make_shared<const VL::PatternFormatter>(
|
||||||
cv_.wait(lock, [this] { return !logQueue_.empty() || !running_.load(); });
|
"[{time}] [{level}] [{thread}] {file} - {message}");
|
||||||
|
|
||||||
while (!logQueue_.empty()) {
|
|
||||||
auto entry = std::move(logQueue_.front());
|
|
||||||
logQueue_.pop();
|
|
||||||
lock.unlock();
|
|
||||||
|
|
||||||
// Format the log entry
|
|
||||||
std::string formatted = formatLogEntry(entry);
|
|
||||||
|
|
||||||
// Console output
|
|
||||||
if (consoleOutput_.load()) {
|
|
||||||
if (entry.level >= Api::LogLevel::Error) {
|
|
||||||
std::cerr << formatted << std::endl;
|
|
||||||
} else {
|
|
||||||
std::cout << formatted << std::endl;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// File output
|
|
||||||
if (fileOutput_.load()) {
|
|
||||||
rotateIfNeeded(entry.level);
|
|
||||||
writeToFile(entry.level, formatted);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Callbacks
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> cbLock(callbackMutex_);
|
|
||||||
for (const auto& callback : callbacks_) {
|
|
||||||
callback(entry);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
lock.lock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void Logger::writeToFile(Api::LogLevel level, const std::string& formattedEntry) {
|
if (consoleOutput_.load()) {
|
||||||
std::lock_guard<std::mutex> lock(fileMutex_);
|
auto console = std::make_shared<VL::ConsoleLogger>(std::cout);
|
||||||
|
console->set_formatter(formatter);
|
||||||
// Write to level-specific file
|
multi->add(std::move(console));
|
||||||
auto it = levelFiles_.find(level);
|
}
|
||||||
if (it != levelFiles_.end() && it->second.stream.is_open()) {
|
|
||||||
it->second.stream << formattedEntry << std::endl;
|
|
||||||
it->second.size += formattedEntry.size() + 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write to combined file
|
|
||||||
if (combinedFile_.stream.is_open()) {
|
|
||||||
combinedFile_.stream << formattedEntry << std::endl;
|
|
||||||
combinedFile_.size += formattedEntry.size() + 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void Logger::moveToHistory(const std::filesystem::path& filePath) {
|
if (fileOutput_.load()) {
|
||||||
ensureHistoryDirExists();
|
VL::SplitFileOptions opts;
|
||||||
|
opts.combined = true; // also write <dir>/all.log
|
||||||
auto historyDir = logDir_ / "history";
|
opts.max_bytes = static_cast<std::size_t>(maxFileSize_.load());
|
||||||
auto fileName = filePath.filename().string();
|
opts.max_files = static_cast<std::size_t>(maxFiles_.load());
|
||||||
|
if (auto fileSink = VL::SplitFileLogger::open(logDir_, opts)) {
|
||||||
// Generate timestamp for unique filename
|
(*fileSink)->set_formatter(formatter);
|
||||||
auto now = std::chrono::system_clock::now();
|
multi->add(std::shared_ptr<VL::Logger>(std::move(*fileSink)));
|
||||||
auto time_t = std::chrono::system_clock::to_time_t(now);
|
}
|
||||||
std::tm tm;
|
}
|
||||||
localtime_r(&time_t, &tm);
|
|
||||||
|
|
||||||
std::string timestamp = std::format("{:04d}{:02d}{:02d}_{:02d}{:02d}{:02d}",
|
|
||||||
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
|
|
||||||
tm.tm_hour, tm.tm_min, tm.tm_sec);
|
|
||||||
|
|
||||||
auto historyPath = historyDir / std::format("{}.{}", fileName, timestamp);
|
|
||||||
|
|
||||||
std::error_code ec;
|
|
||||||
std::filesystem::rename(filePath, historyPath, ec);
|
|
||||||
if (!ec) {
|
|
||||||
// Clean up old history files (keep last 30)
|
|
||||||
cleanupOldLogs();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void Logger::cleanupOldLogs() {
|
// Bridge Void entries back to the registered ILogger callbacks so
|
||||||
ensureHistoryDirExists();
|
// existing log subscribers (e.g. RPC log streaming) keep receiving
|
||||||
|
// Api::LogEntry records, asynchronously as before.
|
||||||
auto historyDir = logDir_ / "history";
|
multi->add(std::make_shared<VL::CallbackLogger>(
|
||||||
if (!std::filesystem::exists(historyDir)) {
|
[this](const VL::Entry& entry) {
|
||||||
return;
|
dispatchToCallbacks(fromVoidLevel(entry.level), entry.message,
|
||||||
}
|
entry.location.file_name(),
|
||||||
|
entry.location.line(),
|
||||||
// Get all files in history directory
|
entry.location.function_name());
|
||||||
std::vector<std::pair<std::filesystem::path, std::filesystem::file_time_type>> files;
|
}));
|
||||||
|
|
||||||
for (const auto& entry : std::filesystem::directory_iterator(historyDir)) {
|
|
||||||
if (entry.is_regular_file()) {
|
|
||||||
files.emplace_back(entry.path(), entry.last_write_time());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sort by modification time (oldest first)
|
|
||||||
std::sort(files.begin(), files.end(),
|
|
||||||
[](const auto& a, const auto& b) { return a.second < b.second; });
|
|
||||||
|
|
||||||
// Keep only the most recent 30 files
|
|
||||||
const size_t maxHistoryFiles = 30;
|
|
||||||
if (files.size() > maxHistoryFiles) {
|
|
||||||
std::error_code ec;
|
|
||||||
for (size_t i = 0; i < files.size() - maxHistoryFiles; ++i) {
|
|
||||||
std::filesystem::remove(files[i].first, ec);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void Logger::rotateIfNeeded(Api::LogLevel level) {
|
std::lock_guard<std::mutex> lock(sinkMutex_);
|
||||||
std::lock_guard<std::mutex> lock(fileMutex_);
|
sink_ = std::move(multi);
|
||||||
|
}
|
||||||
auto maxSize = maxFileSize_.load();
|
|
||||||
auto maxFiles = maxFiles_.load();
|
|
||||||
|
|
||||||
// Check level-specific file
|
|
||||||
auto it = levelFiles_.find(level);
|
|
||||||
if (it != levelFiles_.end() && it->second.size >= maxSize) {
|
|
||||||
it->second.stream.close();
|
|
||||||
|
|
||||||
auto basePath = it->second.path;
|
|
||||||
|
|
||||||
// Move oldest to history if at max files
|
|
||||||
auto oldestPath = std::format("{}.{}", basePath.string(), maxFiles);
|
|
||||||
if (std::filesystem::exists(oldestPath)) {
|
|
||||||
moveToHistory(oldestPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Rotate: move .4 to .5, .3 to .4, etc.
|
|
||||||
for (int i = maxFiles - 1; i > 0; --i) {
|
|
||||||
auto oldPath = std::format("{}.{}", basePath.string(), i);
|
|
||||||
auto newPath = std::format("{}.{}", basePath.string(), i + 1);
|
|
||||||
if (std::filesystem::exists(oldPath)) {
|
|
||||||
std::filesystem::rename(oldPath, newPath);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Move current to .1
|
|
||||||
if (std::filesystem::exists(basePath)) {
|
|
||||||
std::filesystem::rename(basePath, std::format("{}.1", basePath.string()));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reopen
|
|
||||||
it->second.stream.open(basePath, std::ios::app);
|
|
||||||
it->second.size = 0;
|
|
||||||
it->second.createdAt = std::chrono::system_clock::now();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check combined file
|
|
||||||
if (combinedFile_.size >= maxSize) {
|
|
||||||
combinedFile_.stream.close();
|
|
||||||
|
|
||||||
auto basePath = combinedFile_.path;
|
|
||||||
|
|
||||||
// Move oldest to history if at max files
|
|
||||||
auto oldestPath = std::format("{}.{}", basePath.string(), maxFiles);
|
|
||||||
if (std::filesystem::exists(oldestPath)) {
|
|
||||||
moveToHistory(oldestPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Rotate: move .4 to .5, .3 to .4, etc.
|
|
||||||
for (int i = maxFiles - 1; i > 0; --i) {
|
|
||||||
auto oldPath = std::format("{}.{}", basePath.string(), i);
|
|
||||||
auto newPath = std::format("{}.{}", basePath.string(), i + 1);
|
|
||||||
if (std::filesystem::exists(oldPath)) {
|
|
||||||
std::filesystem::rename(oldPath, newPath);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Move current to .1
|
|
||||||
if (std::filesystem::exists(basePath)) {
|
|
||||||
std::filesystem::rename(basePath, std::format("{}.1", basePath.string()));
|
|
||||||
}
|
|
||||||
|
|
||||||
combinedFile_.stream.open(basePath, std::ios::app);
|
|
||||||
combinedFile_.size = 0;
|
|
||||||
combinedFile_.createdAt = std::chrono::system_clock::now();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string Logger::formatLogEntry(const Api::LogEntry& entry) {
|
void Logger::dispatchToCallbacks(Api::LogLevel level,
|
||||||
return std::format("[{}] [{}] [{}] {} - {}",
|
const std::string& message,
|
||||||
formatTimestamp(entry.timestamp),
|
const std::string& file, uint32_t line,
|
||||||
levelToString(entry.level),
|
const std::string& function)
|
||||||
entry.threadId,
|
{
|
||||||
entry.sourceFile.substr(entry.sourceFile.find_last_of("/\\") + 1),
|
std::lock_guard<std::mutex> lock(callbackMutex_);
|
||||||
entry.message);
|
if (callbacks_.empty()) {
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
std::string Logger::levelToString(Api::LogLevel level) {
|
Api::LogEntry entry;
|
||||||
switch (level) {
|
entry.level = level;
|
||||||
case Api::LogLevel::Debug: return "DEBUG";
|
entry.message = message;
|
||||||
case Api::LogLevel::Info: return "INFO";
|
entry.sourceFile = file;
|
||||||
case Api::LogLevel::Warning: return "WARN";
|
entry.sourceLine = line;
|
||||||
case Api::LogLevel::Error: return "ERROR";
|
entry.function = function;
|
||||||
case Api::LogLevel::Critical: return "CRITICAL";
|
entry.threadId = std::this_thread::get_id();
|
||||||
default: return "UNKNOWN";
|
entry.timestamp = std::chrono::system_clock::now();
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string Logger::formatTimestamp(const std::chrono::system_clock::time_point& tp) {
|
for (const auto& callback : callbacks_) {
|
||||||
auto time_t = std::chrono::system_clock::to_time_t(tp);
|
callback(entry);
|
||||||
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
}
|
||||||
tp.time_since_epoch()) % 1000;
|
}
|
||||||
|
|
||||||
std::tm tm;
|
|
||||||
localtime_r(&time_t, &tm);
|
|
||||||
|
|
||||||
return std::format("{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}.{:03d}",
|
|
||||||
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
|
|
||||||
tm.tm_hour, tm.tm_min, tm.tm_sec, ms.count());
|
|
||||||
}
|
|
||||||
|
|
||||||
void Logger::setMinLevel(Api::LogLevel level) {
|
void Logger::log(Api::LogLevel level, std::string_view message,
|
||||||
minLevel_.store(level);
|
std::source_location location)
|
||||||
}
|
{
|
||||||
|
if (level < minLevel_.load()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
Api::LogLevel Logger::getMinLevel() const {
|
std::shared_ptr<Void::Logging::MultiLogger> sink;
|
||||||
return minLevel_.load();
|
{
|
||||||
}
|
std::lock_guard<std::mutex> lock(sinkMutex_);
|
||||||
|
sink = sink_;
|
||||||
|
}
|
||||||
|
if (sink) {
|
||||||
|
sink->log(toVoidLevel(level), message, location);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void Logger::registerCallback(const LogCallback& callback) {
|
void Logger::setMinLevel(Api::LogLevel level) { minLevel_.store(level); }
|
||||||
std::lock_guard<std::mutex> lock(callbackMutex_);
|
|
||||||
callbacks_.push_back(callback);
|
|
||||||
}
|
|
||||||
|
|
||||||
void Logger::unregisterCallback(const LogCallback& callback) {
|
Api::LogLevel Logger::getMinLevel() const { return minLevel_.load(); }
|
||||||
std::lock_guard<std::mutex> lock(callbackMutex_);
|
|
||||||
callbacks_.erase(std::remove_if(callbacks_.begin(), callbacks_.end(),
|
|
||||||
[&callback](const auto& cb) { return &cb == &callback; }), callbacks_.end());
|
|
||||||
}
|
|
||||||
|
|
||||||
void Logger::flush() {
|
void Logger::registerCallback(const LogCallback& callback)
|
||||||
std::lock_guard<std::mutex> lock(fileMutex_);
|
{
|
||||||
for (auto& [level, info] : levelFiles_) {
|
std::lock_guard<std::mutex> lock(callbackMutex_);
|
||||||
if (info.stream.is_open()) {
|
callbacks_.push_back(callback);
|
||||||
info.stream.flush();
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
if (combinedFile_.stream.is_open()) {
|
|
||||||
combinedFile_.stream.flush();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void Logger::setConsoleOutput(bool enabled) {
|
void Logger::unregisterCallback(const LogCallback& callback)
|
||||||
consoleOutput_.store(enabled);
|
{
|
||||||
}
|
std::lock_guard<std::mutex> lock(callbackMutex_);
|
||||||
|
callbacks_.erase(std::remove_if(callbacks_.begin(), callbacks_.end(),
|
||||||
|
[&callback](const auto& cb) {
|
||||||
|
return &cb == &callback;
|
||||||
|
}),
|
||||||
|
callbacks_.end());
|
||||||
|
}
|
||||||
|
|
||||||
void Logger::setFileOutput(bool enabled) {
|
void Logger::flush()
|
||||||
fileOutput_.store(enabled);
|
{
|
||||||
}
|
std::lock_guard<std::mutex> lock(sinkMutex_);
|
||||||
|
if (sink_) {
|
||||||
|
sink_->flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void Logger::setMaxFileSize(uint64_t bytes) {
|
void Logger::setConsoleOutput(bool enabled)
|
||||||
maxFileSize_.store(bytes);
|
{
|
||||||
}
|
consoleOutput_.store(enabled);
|
||||||
|
rebuildSinks();
|
||||||
|
}
|
||||||
|
|
||||||
void Logger::setMaxFiles(uint32_t count) {
|
void Logger::setFileOutput(bool enabled)
|
||||||
maxFiles_.store(count);
|
{
|
||||||
}
|
fileOutput_.store(enabled);
|
||||||
|
rebuildSinks();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Logger::setMaxFileSize(uint64_t bytes)
|
||||||
|
{
|
||||||
|
maxFileSize_.store(bytes);
|
||||||
|
rebuildSinks();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Logger::setMaxFiles(uint32_t count)
|
||||||
|
{
|
||||||
|
maxFiles_.store(count);
|
||||||
|
rebuildSinks();
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
+50
-37
@@ -1,47 +1,60 @@
|
|||||||
#include "echoion/api/MemoryPool.hpp"
|
|
||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
|
#include <MemoryPool.hpp>
|
||||||
|
#include <format>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
namespace Echoion::Api {
|
namespace Echoion::Api
|
||||||
|
{
|
||||||
|
|
||||||
AudioBufferPool& AudioBufferPool::instance() {
|
AudioBufferPool& AudioBufferPool::instance()
|
||||||
static AudioBufferPool instance;
|
{
|
||||||
return instance;
|
static AudioBufferPool instance;
|
||||||
}
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
void AudioBufferPool::initialize(size_t bufferSize, size_t poolSize) {
|
void AudioBufferPool::initialize(size_t bufferSize, size_t poolSize)
|
||||||
bufferSize_ = bufferSize;
|
{
|
||||||
pool_ = std::make_unique<MemoryPool<int16_t>>(bufferSize, poolSize);
|
bufferSize_ = bufferSize;
|
||||||
ECHOION_LOG_INFO(std::format("AudioBufferPool initialized: {} buffers of {} samples (~{} KB)",
|
pool_ = std::make_unique<Void::BufferPool::BufferPool<int16_t>>();
|
||||||
poolSize, bufferSize, (bufferSize * poolSize * sizeof(int16_t)) / 1024));
|
|
||||||
}
|
|
||||||
|
|
||||||
void AudioBufferPool::shutdown() {
|
// Pre-warm the size-class bucket: acquire then immediately drop
|
||||||
pool_.reset();
|
// `poolSize` buffers so subsequent acquireBuffer() calls reuse storage.
|
||||||
ECHOION_LOG_INFO("AudioBufferPool shutdown");
|
{
|
||||||
}
|
std::vector<AudioSampleBuffer> warm;
|
||||||
|
warm.reserve(poolSize);
|
||||||
|
for (size_t i = 0; i < poolSize; ++i) {
|
||||||
|
warm.push_back(pool_->acquire(bufferSize));
|
||||||
|
}
|
||||||
|
} // buffers returned to the pool here
|
||||||
|
|
||||||
PooledPtr<int16_t> AudioBufferPool::acquireBuffer() {
|
ECHOION_LOG_INFO(std::format(
|
||||||
if (!pool_) {
|
"AudioBufferPool initialized: {} buffers of {} samples (~{} KB)",
|
||||||
return PooledPtr<int16_t>();
|
poolSize, bufferSize,
|
||||||
}
|
(bufferSize * poolSize * sizeof(int16_t)) / 1024));
|
||||||
|
}
|
||||||
int16_t* ptr = pool_->acquire();
|
|
||||||
if (!ptr) {
|
|
||||||
ECHOION_LOG_WARNING("AudioBufferPool exhausted - consider increasing pool size");
|
|
||||||
return PooledPtr<int16_t>();
|
|
||||||
}
|
|
||||||
|
|
||||||
return PooledPtr<int16_t>(ptr, pool_.get());
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t AudioBufferPool::getAvailableBuffers() const {
|
void AudioBufferPool::shutdown()
|
||||||
if (!pool_) return 0;
|
{
|
||||||
return pool_->available();
|
pool_.reset();
|
||||||
}
|
ECHOION_LOG_INFO("AudioBufferPool shutdown");
|
||||||
|
}
|
||||||
|
|
||||||
size_t AudioBufferPool::getTotalBuffers() const {
|
AudioSampleBuffer AudioBufferPool::acquireBuffer()
|
||||||
if (!pool_) return 0;
|
{
|
||||||
return pool_->capacity();
|
if (!pool_) {
|
||||||
}
|
return AudioSampleBuffer{};
|
||||||
|
}
|
||||||
|
return pool_->acquire(bufferSize_);
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t AudioBufferPool::getAvailableBuffers() const
|
||||||
|
{
|
||||||
|
return pool_ ? pool_->stats().pooled : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t AudioBufferPool::getTotalBuffers() const
|
||||||
|
{
|
||||||
|
return pool_ ? static_cast<size_t>(pool_->stats().allocations) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace Echoion::Api
|
} // namespace Echoion::Api
|
||||||
+2295
-1718
File diff suppressed because it is too large.
Load diff
+871
-755
File diff suppressed because it is too large.
Load diff
+410
-347
@@ -1,400 +1,463 @@
|
|||||||
#include "echoion/core/RpcServer.hpp"
|
|
||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
#include <glaze/glaze.hpp>
|
#include "echoion/core/RpcServer.hpp"
|
||||||
#include <format>
|
#include <Void/Data/Json.hpp>
|
||||||
|
#include <Void/Data/Reflect.hpp>
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
#include <format>
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
RpcServer::RpcServer() = default;
|
RpcServer::RpcServer() = default;
|
||||||
|
|
||||||
RpcServer::~RpcServer() {
|
RpcServer::~RpcServer() { stop(); }
|
||||||
stop();
|
|
||||||
}
|
|
||||||
|
|
||||||
Api::Result<void> RpcServer::start(uint16_t port) {
|
Api::Result<void> RpcServer::start(uint16_t port)
|
||||||
if (running_.exchange(true)) {
|
{
|
||||||
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, "RPC server already running"));
|
if (running_.exchange(true)) {
|
||||||
}
|
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists,
|
||||||
|
"RPC server already running"));
|
||||||
|
}
|
||||||
|
|
||||||
port_ = port;
|
port_ = port;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port);
|
asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port);
|
||||||
acceptor_.emplace(ioContext_);
|
acceptor_.emplace(ioContext_);
|
||||||
acceptor_->open(endpoint.protocol());
|
acceptor_->open(endpoint.protocol());
|
||||||
acceptor_->set_option(asio::ip::tcp::acceptor::reuse_address(true));
|
acceptor_->set_option(asio::ip::tcp::acceptor::reuse_address(true));
|
||||||
acceptor_->bind(endpoint);
|
acceptor_->bind(endpoint);
|
||||||
acceptor_->listen();
|
acceptor_->listen();
|
||||||
|
|
||||||
serverThread_ = std::thread(&RpcServer::acceptLoop, this);
|
serverThread_ = std::thread(&RpcServer::acceptLoop, this);
|
||||||
|
|
||||||
ECHOION_LOG_INFO(std::format("RPC server started on port {}", port));
|
ECHOION_LOG_INFO(
|
||||||
return {};
|
std::format("RPC server started on port {}", port));
|
||||||
} catch (const std::exception& e) {
|
return {};
|
||||||
running_ = false;
|
} catch (const std::exception& e) {
|
||||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
running_ = false;
|
||||||
std::format("Failed to start RPC server: {}", e.what())));
|
return std::unexpected(Api::Error(
|
||||||
}
|
Api::ErrorCode::ServiceUnavailable,
|
||||||
}
|
std::format("Failed to start RPC server: {}", e.what())));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void RpcServer::stop() {
|
void RpcServer::stop()
|
||||||
if (!running_.exchange(false)) {
|
{
|
||||||
return;
|
if (!running_.exchange(false)) {
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Cancel any pending async operations
|
// Cancel any pending async operations
|
||||||
if (acceptor_.has_value()) {
|
if (acceptor_.has_value()) {
|
||||||
boost::system::error_code ec;
|
boost::system::error_code ec;
|
||||||
acceptor_->cancel(ec);
|
acceptor_->cancel(ec);
|
||||||
}
|
}
|
||||||
|
|
||||||
ioContext_.stop();
|
|
||||||
|
|
||||||
// Close all client connections
|
ioContext_.stop();
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
|
||||||
for (auto& [id, ws] : clients_) {
|
|
||||||
if (ws->is_open()) {
|
|
||||||
beast::error_code ec;
|
|
||||||
ws->close(websocket::close_code::normal, ec);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
clients_.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wait for all client threads to finish (with timeout)
|
// Close all client connections
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
|
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||||
for (auto& thread : clientThreads_) {
|
for (auto& [id, ws] : clients_) {
|
||||||
if (thread.joinable()) {
|
if (ws->is_open()) {
|
||||||
thread.detach(); // Don't wait, just detach
|
beast::error_code ec;
|
||||||
}
|
ws->close(websocket::close_code::normal, ec);
|
||||||
}
|
}
|
||||||
clientThreads_.clear();
|
}
|
||||||
}
|
clients_.clear();
|
||||||
|
}
|
||||||
|
|
||||||
// Wait for server thread with timeout
|
// Wait for all client threads to finish (with timeout)
|
||||||
if (serverThread_.joinable()) {
|
{
|
||||||
// Give it a moment to clean up
|
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
|
||||||
auto start = std::chrono::steady_clock::now();
|
for (auto& thread : clientThreads_) {
|
||||||
while (serverThread_.joinable() &&
|
if (thread.joinable()) {
|
||||||
std::chrono::steady_clock::now() - start < std::chrono::seconds(2)) {
|
// Give each thread a short time to finish
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
auto start = std::chrono::steady_clock::now();
|
||||||
}
|
while (thread.joinable() &&
|
||||||
if (serverThread_.joinable()) {
|
std::chrono::steady_clock::now() - start <
|
||||||
serverThread_.detach(); // Force detach if still running
|
std::chrono::milliseconds(100)) {
|
||||||
}
|
std::this_thread::sleep_for(
|
||||||
}
|
std::chrono::milliseconds(10));
|
||||||
|
}
|
||||||
if (acceptor_.has_value()) {
|
if (thread.joinable()) {
|
||||||
boost::system::error_code ec;
|
thread.detach(); // Only detach if still running
|
||||||
acceptor_->close(ec);
|
// after timeout
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
clientThreads_.clear();
|
||||||
|
}
|
||||||
|
|
||||||
ECHOION_LOG_INFO("RPC server stopped");
|
// Wait for server thread with timeout
|
||||||
} catch (const std::exception& e) {
|
if (serverThread_.joinable()) {
|
||||||
ECHOION_LOG_ERROR(std::format("Error stopping RPC server: {}", e.what()));
|
// Give it a moment to clean up
|
||||||
}
|
auto start = std::chrono::steady_clock::now();
|
||||||
}
|
while (serverThread_.joinable() &&
|
||||||
|
std::chrono::steady_clock::now() - start <
|
||||||
|
std::chrono::seconds(2)) {
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||||
|
}
|
||||||
|
if (serverThread_.joinable()) {
|
||||||
|
serverThread_.detach(); // Force detach if still running
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void RpcServer::acceptLoop() {
|
if (acceptor_.has_value()) {
|
||||||
ECHOION_LOG_INFO("RPC server accept loop started");
|
boost::system::error_code ec;
|
||||||
while (running_.load()) {
|
acceptor_->close(ec);
|
||||||
try {
|
}
|
||||||
asio::ip::tcp::socket socket(ioContext_);
|
|
||||||
ECHOION_LOG_DEBUG("RPC server waiting for connection...");
|
|
||||||
|
|
||||||
// Use async accept with cancellation support
|
|
||||||
std::atomic<bool> acceptComplete{false};
|
|
||||||
boost::system::error_code acceptEc;
|
|
||||||
|
|
||||||
acceptor_->async_accept(socket, [&](const boost::system::error_code& ec) {
|
|
||||||
acceptEc = ec;
|
|
||||||
acceptComplete = true;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Poll until accept completes or we're stopped
|
|
||||||
while (!acceptComplete.load() && running_.load()) {
|
|
||||||
ioContext_.poll_one();
|
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cancel pending operation if we're stopping
|
|
||||||
if (!running_.load()) {
|
|
||||||
acceptor_->cancel();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (acceptEc) {
|
|
||||||
throw std::runtime_error(acceptEc.message());
|
|
||||||
}
|
|
||||||
|
|
||||||
ECHOION_LOG_DEBUG(std::format("RPC server accepted TCP connection from {}:{}",
|
|
||||||
socket.remote_endpoint().address().to_string(),
|
|
||||||
socket.remote_endpoint().port()));
|
|
||||||
|
|
||||||
if (!running_.load()) break;
|
ECHOION_LOG_INFO("RPC server stopped");
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Error stopping RPC server: {}", e.what()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
auto ws = std::make_shared<websocket::stream<asio::ip::tcp::socket>>(std::move(socket));
|
void RpcServer::acceptLoop()
|
||||||
ws->accept();
|
{
|
||||||
ECHOION_LOG_DEBUG("RPC server WebSocket handshake completed");
|
ECHOION_LOG_INFO("RPC server accept loop started");
|
||||||
|
while (running_.load()) {
|
||||||
|
try {
|
||||||
|
asio::ip::tcp::socket socket(ioContext_);
|
||||||
|
ECHOION_LOG_DEBUG("RPC server waiting for connection...");
|
||||||
|
|
||||||
uint64_t clientId = nextClientId_++;
|
// Use async accept with cancellation support
|
||||||
{
|
std::atomic<bool> acceptComplete{false};
|
||||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
boost::system::error_code acceptEc;
|
||||||
clients_[clientId] = ws;
|
|
||||||
}
|
|
||||||
|
|
||||||
ECHOION_LOG_DEBUG(std::format("RPC client {} connected", clientId));
|
acceptor_->async_accept(
|
||||||
|
socket, [&](const boost::system::error_code& ec) {
|
||||||
|
acceptEc = ec;
|
||||||
|
acceptComplete = true;
|
||||||
|
});
|
||||||
|
|
||||||
// Handle client in separate thread
|
// Poll until accept completes or we're stopped
|
||||||
std::thread clientThread([this, clientId, ws]() {
|
while (!acceptComplete.load() && running_.load()) {
|
||||||
handleClient(ws);
|
ioContext_.poll_one();
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||||
// Cleanup
|
}
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
|
||||||
clients_.erase(clientId);
|
|
||||||
}
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(authMutex_);
|
|
||||||
authenticatedClients_.erase(clientId);
|
|
||||||
}
|
|
||||||
ECHOION_LOG_DEBUG(std::format("RPC client {} disconnected", clientId));
|
|
||||||
});
|
|
||||||
|
|
||||||
// Track the thread for proper cleanup
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
|
|
||||||
// Clean up any finished threads first
|
|
||||||
clientThreads_.erase(
|
|
||||||
std::remove_if(clientThreads_.begin(), clientThreads_.end(),
|
|
||||||
[](std::thread& t) {
|
|
||||||
if (!t.joinable()) return true;
|
|
||||||
return false;
|
|
||||||
}),
|
|
||||||
clientThreads_.end()
|
|
||||||
);
|
|
||||||
clientThreads_.push_back(std::move(clientThread));
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (const std::exception& e) {
|
// Cancel pending operation if we're stopping
|
||||||
// If we're shutting down, exit gracefully
|
if (!running_.load()) {
|
||||||
if (!running_.load()) {
|
acceptor_->cancel();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
ECHOION_LOG_ERROR(std::format("RPC accept error: {}", e.what()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ECHOION_LOG_INFO("RPC server accept loop stopped");
|
|
||||||
}
|
|
||||||
|
|
||||||
void RpcServer::handleClient(std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws) {
|
if (acceptEc) {
|
||||||
beast::flat_buffer buffer;
|
throw std::runtime_error(acceptEc.message());
|
||||||
|
}
|
||||||
|
|
||||||
while (running_.load() && ws->is_open()) {
|
ECHOION_LOG_DEBUG(
|
||||||
try {
|
std::format("RPC server accepted TCP connection from {}:{}",
|
||||||
beast::error_code ec;
|
socket.remote_endpoint().address().to_string(),
|
||||||
ws->read(buffer, ec);
|
socket.remote_endpoint().port()));
|
||||||
|
|
||||||
if (ec == websocket::error::closed) {
|
if (!running_.load()) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (ec) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("WebSocket read error: {}", ec.message()));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string message = beast::buffers_to_string(buffer.data());
|
auto ws =
|
||||||
buffer.consume(buffer.size());
|
std::make_shared<websocket::stream<asio::ip::tcp::socket>>(
|
||||||
|
std::move(socket));
|
||||||
|
ws->accept();
|
||||||
|
ECHOION_LOG_DEBUG("RPC server WebSocket handshake completed");
|
||||||
|
|
||||||
// Find client ID
|
uint64_t clientId = nextClientId_++;
|
||||||
uint64_t clientId = 0;
|
{
|
||||||
{
|
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
clients_[clientId] = ws;
|
||||||
for (const auto& [id, clientWs] : clients_) {
|
}
|
||||||
if (clientWs.get() == ws.get()) {
|
|
||||||
clientId = id;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (clientId != 0) {
|
ECHOION_LOG_DEBUG(
|
||||||
processMessage(clientId, message);
|
std::format("RPC client {} connected", clientId));
|
||||||
}
|
|
||||||
|
|
||||||
} catch (const std::exception& e) {
|
// Handle client in separate thread
|
||||||
ECHOION_LOG_ERROR(std::format("Client handling error: {}", e.what()));
|
std::thread clientThread([this, clientId, ws]() {
|
||||||
break;
|
handleClient(ws);
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void RpcServer::processMessage(uint64_t clientId, const std::string& message) {
|
// Cleanup
|
||||||
try {
|
{
|
||||||
Api::RpcRequest request;
|
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||||
auto ec = glz::read_json(request, message);
|
clients_.erase(clientId);
|
||||||
if (ec) {
|
}
|
||||||
Api::RpcResponse response;
|
{
|
||||||
response.requestId = 0;
|
std::lock_guard<std::mutex> lock(authMutex_);
|
||||||
response.success = false;
|
authenticatedClients_.erase(clientId);
|
||||||
response.error = "{\"code\":5,\"message\":\"Invalid JSON\",\"source\":\"RpcServer\"}";
|
}
|
||||||
response.success = false;
|
ECHOION_LOG_DEBUG(
|
||||||
sendResponse(clientId, response);
|
std::format("RPC client {} disconnected", clientId));
|
||||||
return;
|
});
|
||||||
}
|
|
||||||
|
|
||||||
// Check authentication (except for Authenticate method)
|
// Track the thread for proper cleanup
|
||||||
if (request.method != Api::RpcMethod::Authenticate) {
|
{
|
||||||
if (!isClientAuthenticated(clientId)) {
|
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
|
||||||
Api::RpcResponse response;
|
// Clean up any finished threads first
|
||||||
response.requestId = request.id;
|
clientThreads_.erase(std::remove_if(clientThreads_.begin(),
|
||||||
response.success = false;
|
clientThreads_.end(),
|
||||||
response.error = "{\"code\":10,\"message\":\"Not authenticated\",\"source\":\"RpcServer\"}";
|
[](std::thread& t) {
|
||||||
response.success = false;
|
if (!t.joinable()) {
|
||||||
sendResponse(clientId, response);
|
return true;
|
||||||
return;
|
}
|
||||||
}
|
return false;
|
||||||
}
|
}),
|
||||||
|
clientThreads_.end());
|
||||||
|
clientThreads_.push_back(std::move(clientThread));
|
||||||
|
}
|
||||||
|
|
||||||
// Find handler
|
} catch (const std::exception& e) {
|
||||||
std::string methodName = std::to_string(static_cast<int>(request.method));
|
// If we're shutting down, exit gracefully
|
||||||
CommandHandler handler;
|
if (!running_.load()) {
|
||||||
{
|
break;
|
||||||
std::lock_guard<std::mutex> lock(handlersMutex_);
|
}
|
||||||
auto it = handlers_.find(methodName);
|
ECHOION_LOG_ERROR(
|
||||||
if (it != handlers_.end()) {
|
std::format("RPC accept error: {}", e.what()));
|
||||||
handler = it->second;
|
}
|
||||||
}
|
}
|
||||||
}
|
ECHOION_LOG_INFO("RPC server accept loop stopped");
|
||||||
|
}
|
||||||
|
|
||||||
Api::RpcResponse response;
|
void RpcServer::handleClient(
|
||||||
response.requestId = request.id;
|
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws)
|
||||||
response.timestamp = std::chrono::system_clock::now();
|
{
|
||||||
|
beast::flat_buffer buffer;
|
||||||
|
|
||||||
if (handler) {
|
while (running_.load() && ws->is_open()) {
|
||||||
auto result = handler(request.params.value_or(""), clientId);
|
try {
|
||||||
if (result) {
|
beast::error_code ec;
|
||||||
response.success = true;
|
ws->read(buffer, ec);
|
||||||
response.result = *result;
|
|
||||||
} else {
|
|
||||||
response.success = false;
|
|
||||||
response.error = std::format("{{\"code\":{},\"message\":\"{}\",\"source\":\"{}\"}}",
|
|
||||||
static_cast<uint32_t>(result.error().code),
|
|
||||||
result.error().message,
|
|
||||||
result.error().source);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
response.success = false;
|
|
||||||
response.error = "{\"code\":2,\"message\":\"Unknown method\",\"source\":\"RpcServer\"}";
|
|
||||||
}
|
|
||||||
|
|
||||||
sendResponse(clientId, response);
|
if (ec == websocket::error::closed) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (ec) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("WebSocket read error: {}", ec.message()));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
} catch (const std::exception& e) {
|
std::string message = beast::buffers_to_string(buffer.data());
|
||||||
ECHOION_LOG_ERROR(std::format("Message processing error: {}", e.what()));
|
buffer.consume(buffer.size());
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void RpcServer::sendResponse(uint64_t clientId, const Api::RpcResponse& response) {
|
// Find client ID
|
||||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
uint64_t clientId = 0;
|
||||||
auto it = clients_.find(clientId);
|
{
|
||||||
if (it == clients_.end() || !it->second->is_open()) {
|
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||||
return;
|
for (const auto& [id, clientWs] : clients_) {
|
||||||
}
|
if (clientWs.get() == ws.get()) {
|
||||||
|
clientId = id;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
if (clientId != 0) {
|
||||||
auto json = glz::write_json(response);
|
processMessage(clientId, message);
|
||||||
if (json) {
|
}
|
||||||
it->second->write(asio::buffer(*json));
|
|
||||||
}
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("Send response error: {}", e.what()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void RpcServer::sendNotification(uint64_t clientId, const Api::RpcNotification& notification) {
|
} catch (const std::exception& e) {
|
||||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
ECHOION_LOG_ERROR(
|
||||||
auto it = clients_.find(clientId);
|
std::format("Client handling error: {}", e.what()));
|
||||||
if (it == clients_.end() || !it->second->is_open()) {
|
break;
|
||||||
return;
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
void RpcServer::processMessage(uint64_t clientId,
|
||||||
auto json = glz::write_json(notification);
|
const std::string& message)
|
||||||
if (json) {
|
{
|
||||||
it->second->write(asio::buffer(*json));
|
try {
|
||||||
}
|
Api::RpcRequest request;
|
||||||
} catch (const std::exception& e) {
|
bool decoded = false;
|
||||||
ECHOION_LOG_ERROR(std::format("Send notification error: {}", e.what()));
|
if (auto parsed = Void::Json::parse(message)) {
|
||||||
}
|
if (auto req = Void::Json::from_json<Api::RpcRequest>(*parsed)) {
|
||||||
}
|
request = std::move(*req);
|
||||||
|
decoded = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!decoded) {
|
||||||
|
Api::RpcResponse response;
|
||||||
|
response.requestId = 0;
|
||||||
|
response.success = false;
|
||||||
|
response.error = "{\"code\":5,\"message\":\"Invalid "
|
||||||
|
"JSON\",\"source\":\"RpcServer\"}";
|
||||||
|
response.success = false;
|
||||||
|
sendResponse(clientId, response);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
void RpcServer::broadcastEvent(const std::string& event, const std::string& data) {
|
// Check authentication (except for Authenticate method)
|
||||||
Api::RpcNotification notification;
|
if (request.method != Api::RpcMethod::Authenticate) {
|
||||||
notification.event = event;
|
if (!isClientAuthenticated(clientId)) {
|
||||||
notification.data = data;
|
Api::RpcResponse response;
|
||||||
notification.timestamp = std::chrono::system_clock::now();
|
response.requestId = request.id;
|
||||||
|
response.success = false;
|
||||||
|
response.error =
|
||||||
|
"{\"code\":10,\"message\":\"Not "
|
||||||
|
"authenticated\",\"source\":\"RpcServer\"}";
|
||||||
|
response.success = false;
|
||||||
|
sendResponse(clientId, response);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
// Find handler
|
||||||
for (const auto& [clientId, ws] : clients_) {
|
std::string methodName =
|
||||||
if (ws->is_open() && isClientAuthenticated(clientId)) {
|
std::to_string(static_cast<int>(request.method));
|
||||||
try {
|
CommandHandler handler;
|
||||||
auto json = glz::write_json(notification);
|
{
|
||||||
if (json) {
|
std::lock_guard<std::mutex> lock(handlersMutex_);
|
||||||
ws->write(asio::buffer(*json));
|
auto it = handlers_.find(methodName);
|
||||||
}
|
if (it != handlers_.end()) {
|
||||||
} catch (const std::exception& e) {
|
handler = it->second;
|
||||||
ECHOION_LOG_ERROR(std::format("Broadcast error: {}", e.what()));
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void RpcServer::sendEvent(uint64_t clientId, const std::string& event, const std::string& data) {
|
Api::RpcResponse response;
|
||||||
Api::RpcNotification notification;
|
response.requestId = request.id;
|
||||||
notification.event = event;
|
response.timestamp = std::chrono::system_clock::now();
|
||||||
notification.data = data;
|
|
||||||
notification.timestamp = std::chrono::system_clock::now();
|
|
||||||
sendNotification(clientId, notification);
|
|
||||||
}
|
|
||||||
|
|
||||||
void RpcServer::registerHandler(const std::string& method, CommandHandler handler) {
|
if (handler) {
|
||||||
std::lock_guard<std::mutex> lock(handlersMutex_);
|
auto result = handler(request.params.value_or(""), clientId);
|
||||||
handlers_[method] = std::move(handler);
|
if (result) {
|
||||||
}
|
response.success = true;
|
||||||
|
response.result = *result;
|
||||||
|
} else {
|
||||||
|
response.success = false;
|
||||||
|
response.error = std::format(
|
||||||
|
"{{\"code\":{},\"message\":\"{}\",\"source\":\"{}\"}}",
|
||||||
|
static_cast<uint32_t>(result.error().code),
|
||||||
|
result.error().message,
|
||||||
|
result.error().source);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
response.success = false;
|
||||||
|
response.error = "{\"code\":2,\"message\":\"Unknown "
|
||||||
|
"method\",\"source\":\"RpcServer\"}";
|
||||||
|
}
|
||||||
|
|
||||||
void RpcServer::unregisterHandler(const std::string& method) {
|
sendResponse(clientId, response);
|
||||||
std::lock_guard<std::mutex> lock(handlersMutex_);
|
|
||||||
handlers_.erase(method);
|
|
||||||
}
|
|
||||||
|
|
||||||
void RpcServer::setAuthToken(const std::string& token) {
|
} catch (const std::exception& e) {
|
||||||
std::lock_guard<std::mutex> lock(authMutex_);
|
ECHOION_LOG_ERROR(
|
||||||
authToken_ = token;
|
std::format("Message processing error: {}", e.what()));
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
bool RpcServer::authenticate(const std::string& token) {
|
void RpcServer::sendResponse(uint64_t clientId,
|
||||||
std::lock_guard<std::mutex> lock(authMutex_);
|
const Api::RpcResponse& response)
|
||||||
return authToken_.empty() || token == authToken_;
|
{
|
||||||
}
|
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||||
|
auto it = clients_.find(clientId);
|
||||||
|
if (it == clients_.end() || !it->second->is_open()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
void RpcServer::addAuthenticatedClient(uint64_t clientId) {
|
try {
|
||||||
std::lock_guard<std::mutex> lock(authMutex_);
|
const std::string json =
|
||||||
authenticatedClients_.insert(clientId);
|
Void::Json::serialize(Void::Json::to_json(response));
|
||||||
}
|
it->second->write(asio::buffer(json));
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(std::format("Send response error: {}", e.what()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void RpcServer::removeAuthenticatedClient(uint64_t clientId) {
|
void RpcServer::sendNotification(uint64_t clientId,
|
||||||
std::lock_guard<std::mutex> lock(authMutex_);
|
const Api::RpcNotification& notification)
|
||||||
authenticatedClients_.erase(clientId);
|
{
|
||||||
}
|
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||||
|
auto it = clients_.find(clientId);
|
||||||
|
if (it == clients_.end() || !it->second->is_open()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
bool RpcServer::isClientAuthenticated(uint64_t clientId) {
|
try {
|
||||||
std::lock_guard<std::mutex> lock(authMutex_);
|
const std::string json =
|
||||||
return authenticatedClients_.contains(clientId);
|
Void::Json::serialize(Void::Json::to_json(notification));
|
||||||
}
|
it->second->write(asio::buffer(json));
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Send notification error: {}", e.what()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void RpcServer::broadcastEvent(const std::string& event,
|
||||||
|
const std::string& data)
|
||||||
|
{
|
||||||
|
Api::RpcNotification notification;
|
||||||
|
notification.event = event;
|
||||||
|
notification.data = data;
|
||||||
|
notification.timestamp = std::chrono::system_clock::now();
|
||||||
|
|
||||||
|
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||||
|
for (const auto& [clientId, ws] : clients_) {
|
||||||
|
if (ws->is_open() && isClientAuthenticated(clientId)) {
|
||||||
|
try {
|
||||||
|
const std::string json = Void::Json::serialize(
|
||||||
|
Void::Json::to_json(notification));
|
||||||
|
ws->write(asio::buffer(json));
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Broadcast error: {}", e.what()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void RpcServer::sendEvent(uint64_t clientId, const std::string& event,
|
||||||
|
const std::string& data)
|
||||||
|
{
|
||||||
|
Api::RpcNotification notification;
|
||||||
|
notification.event = event;
|
||||||
|
notification.data = data;
|
||||||
|
notification.timestamp = std::chrono::system_clock::now();
|
||||||
|
sendNotification(clientId, notification);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RpcServer::registerHandler(const std::string& method,
|
||||||
|
CommandHandler handler)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(handlersMutex_);
|
||||||
|
handlers_[method] = std::move(handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RpcServer::unregisterHandler(const std::string& method)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(handlersMutex_);
|
||||||
|
handlers_.erase(method);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RpcServer::setAuthToken(const std::string& token)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(authMutex_);
|
||||||
|
authToken_ = token;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RpcServer::authenticate(const std::string& token)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(authMutex_);
|
||||||
|
return authToken_.empty() || token == authToken_;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RpcServer::addAuthenticatedClient(uint64_t clientId)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(authMutex_);
|
||||||
|
authenticatedClients_.insert(clientId);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RpcServer::removeAuthenticatedClient(uint64_t clientId)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(authMutex_);
|
||||||
|
authenticatedClients_.erase(clientId);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RpcServer::isClientAuthenticated(uint64_t clientId)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(authMutex_);
|
||||||
|
return authenticatedClients_.contains(clientId);
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
#include "echoion/core/Logger.hpp"
|
||||||
|
#include "echoion/core/SessionManager.hpp"
|
||||||
|
#include <format>
|
||||||
|
#include <iomanip>
|
||||||
|
#include <random>
|
||||||
|
#include <sstream>
|
||||||
|
|
||||||
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
|
SessionManager::SessionManager() = default;
|
||||||
|
|
||||||
|
SessionManager::SessionManager(const Config& config) : config_(config) {}
|
||||||
|
|
||||||
|
bool SessionManager::initialize()
|
||||||
|
{
|
||||||
|
running_ = true;
|
||||||
|
ECHOION_LOG_INFO(std::format(
|
||||||
|
"SessionManager initialized: max {} sessions, timeout {}s",
|
||||||
|
config_.maxSessions, config_.sessionTimeout.count()));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SessionManager::shutdown()
|
||||||
|
{
|
||||||
|
running_ = false;
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
sessions_.clear();
|
||||||
|
ECHOION_LOG_INFO("SessionManager shut down");
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string SessionManager::createSession(uint64_t clientId)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
|
||||||
|
// Check capacity
|
||||||
|
if (sessions_.size() >= config_.maxSessions) {
|
||||||
|
ECHOION_LOG_WARNING(
|
||||||
|
"Session capacity reached, rejecting new session");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate unique token
|
||||||
|
std::string token = generateToken();
|
||||||
|
|
||||||
|
Session session;
|
||||||
|
session.clientId = clientId;
|
||||||
|
session.authToken = token;
|
||||||
|
session.lastActivity = std::chrono::steady_clock::now();
|
||||||
|
session.createdAt = session.lastActivity;
|
||||||
|
session.isAuthenticated = false;
|
||||||
|
|
||||||
|
sessions_[token] = std::move(session);
|
||||||
|
|
||||||
|
ECHOION_LOG_INFO(
|
||||||
|
std::format("Created session for client {}", clientId));
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SessionManager::authenticateSession(const std::string& token)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
|
||||||
|
auto it = sessions_.find(token);
|
||||||
|
if (it == sessions_.end()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
it->second.isAuthenticated = true;
|
||||||
|
it->second.lastActivity = std::chrono::steady_clock::now();
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SessionManager::validateSession(const std::string& token)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
|
||||||
|
auto it = sessions_.find(token);
|
||||||
|
if (it == sessions_.end()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check timeout
|
||||||
|
auto elapsed =
|
||||||
|
std::chrono::steady_clock::now() - it->second.lastActivity;
|
||||||
|
if (elapsed > config_.sessionTimeout) {
|
||||||
|
sessions_.erase(it);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return it->second.isAuthenticated;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SessionManager::updateActivity(const std::string& token)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
|
||||||
|
auto it = sessions_.find(token);
|
||||||
|
if (it != sessions_.end()) {
|
||||||
|
it->second.lastActivity = std::chrono::steady_clock::now();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<SessionManager::Session>
|
||||||
|
SessionManager::getSession(const std::string& token) const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
|
||||||
|
auto it = sessions_.find(token);
|
||||||
|
if (it != sessions_.end()) {
|
||||||
|
return it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SessionManager::endSession(const std::string& token)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
sessions_.erase(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
void SessionManager::endSessionByClientId(uint64_t clientId)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
|
||||||
|
for (auto it = sessions_.begin(); it != sessions_.end();) {
|
||||||
|
if (it->second.clientId == clientId) {
|
||||||
|
it = sessions_.erase(it);
|
||||||
|
} else {
|
||||||
|
++it;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<SessionManager::Session> SessionManager::getAllSessions() const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
|
||||||
|
std::vector<Session> result;
|
||||||
|
result.reserve(sessions_.size());
|
||||||
|
|
||||||
|
for (const auto& [token, session] : sessions_) {
|
||||||
|
result.push_back(session);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t SessionManager::getSessionCount() const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
return sessions_.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t SessionManager::cleanupExpiredSessions()
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
|
||||||
|
size_t cleaned = 0;
|
||||||
|
auto now = std::chrono::steady_clock::now();
|
||||||
|
|
||||||
|
for (auto it = sessions_.begin(); it != sessions_.end();) {
|
||||||
|
auto elapsed = now - it->second.lastActivity;
|
||||||
|
if (elapsed > config_.sessionTimeout) {
|
||||||
|
it = sessions_.erase(it);
|
||||||
|
cleaned++;
|
||||||
|
} else {
|
||||||
|
++it;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cleaned > 0) {
|
||||||
|
ECHOION_LOG_INFO(
|
||||||
|
std::format("Cleaned up {} expired sessions", cleaned));
|
||||||
|
}
|
||||||
|
|
||||||
|
return cleaned;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SessionManager::isAtCapacity() const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
return sessions_.size() >= config_.maxSessions;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string SessionManager::generateToken()
|
||||||
|
{
|
||||||
|
// Generate random 32-byte token
|
||||||
|
static std::random_device rd;
|
||||||
|
static std::mt19937 gen(rd());
|
||||||
|
static std::uniform_int_distribution<> dis(0, 255);
|
||||||
|
|
||||||
|
std::stringstream ss;
|
||||||
|
for (int i = 0; i < 32; ++i) {
|
||||||
|
ss << std::hex << std::setw(2) << std::setfill('0') << dis(gen);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ss.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Echoion::Core
|
||||||
+754
-671
File diff suppressed because it is too large.
Load diff
+198
-174
@@ -1,192 +1,216 @@
|
|||||||
|
#include "LoggerInterface.hpp"
|
||||||
#include "echoion/core/SubscriptionManager.hpp"
|
#include "echoion/core/SubscriptionManager.hpp"
|
||||||
#include "echoion/core/Logger.hpp"
|
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
SubscriptionManager::SubscriptionManager() = default;
|
SubscriptionManager::SubscriptionManager() = default;
|
||||||
|
|
||||||
SubscriptionManager::~SubscriptionManager() {
|
SubscriptionManager::~SubscriptionManager() { shutdown(); }
|
||||||
shutdown();
|
|
||||||
}
|
|
||||||
|
|
||||||
Api::Result<void> SubscriptionManager::initialize(std::shared_ptr<Api::Database> database) {
|
Api::Result<void>
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
SubscriptionManager::initialize(std::shared_ptr<Api::Database> database)
|
||||||
|
{
|
||||||
if (initialized_) {
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
database_ = std::move(database);
|
|
||||||
if (!database_) {
|
|
||||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
|
||||||
"Database not available"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Load existing subscriptions from database
|
|
||||||
auto result = database_->getAllSubscribers();
|
|
||||||
if (!result) {
|
|
||||||
ECHOION_LOG_WARNING(std::format("Failed to load subscriptions: {}", result.error().message));
|
|
||||||
// Not fatal - start with empty subscriptions
|
|
||||||
} else {
|
|
||||||
for (const auto& subscriber : *result) {
|
|
||||||
subscribedUids_.insert(subscriber.uid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
initialized_ = true;
|
|
||||||
ECHOION_LOG_INFO(std::format("SubscriptionManager initialized ({} subscribers)",
|
|
||||||
subscribedUids_.size()));
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
void SubscriptionManager::shutdown() {
|
if (initialized_) {
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
return {};
|
||||||
|
}
|
||||||
if (!initialized_) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
initialized_ = false;
|
|
||||||
database_.reset();
|
|
||||||
subscribedUids_.clear();
|
|
||||||
ECHOION_LOG_INFO("SubscriptionManager shutdown");
|
|
||||||
}
|
|
||||||
|
|
||||||
bool SubscriptionManager::subscribe(const std::string& uid, const std::string& nickname) {
|
database_ = std::move(database);
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
if (!database_) {
|
||||||
|
return std::unexpected(Api::Error(
|
||||||
// Check if already subscribed (ensures uniqueness)
|
Api::ErrorCode::ServiceUnavailable, "Database not available"));
|
||||||
if (subscribedUids_.contains(uid)) {
|
}
|
||||||
// Update nickname even if already subscribed
|
|
||||||
if (database_) {
|
|
||||||
database_->addSubscriber(uid, nickname);
|
|
||||||
}
|
|
||||||
return false; // Already subscribed
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add to database first
|
|
||||||
if (database_) {
|
|
||||||
auto result = database_->addSubscriber(uid, nickname);
|
|
||||||
if (!result) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("Failed to add subscriber {} to database: {}",
|
|
||||||
uid, result.error().message));
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
subscribedUids_.insert(uid);
|
|
||||||
ECHOION_LOG_INFO(std::format("Client {} ({}) subscribed", nickname, uid));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool SubscriptionManager::unsubscribe(const std::string& uid) {
|
// Load existing subscriptions from database
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
auto result = database_->getAllSubscribers();
|
||||||
|
if (!result) {
|
||||||
bool removed = subscribedUids_.erase(uid) > 0;
|
ECHOION_LOG_WARNING(std::format("Failed to load subscriptions: {}",
|
||||||
if (removed) {
|
result.error().message));
|
||||||
// Remove from database
|
// Not fatal - start with empty subscriptions
|
||||||
if (database_) {
|
} else {
|
||||||
auto result = database_->removeSubscriber(uid);
|
for (const auto& subscriber : *result) {
|
||||||
if (!result) {
|
subscribedUids_.insert(subscriber.uid);
|
||||||
ECHOION_LOG_ERROR(std::format("Failed to remove subscriber {} from database: {}",
|
}
|
||||||
uid, result.error().message));
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
ECHOION_LOG_INFO(std::format("Client {} unsubscribed", uid));
|
|
||||||
}
|
|
||||||
return removed;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool SubscriptionManager::isSubscribed(const std::string& uid) const {
|
initialized_ = true;
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
ECHOION_LOG_INFO(
|
||||||
return subscribedUids_.contains(uid);
|
std::format("SubscriptionManager initialized ({} subscribers)",
|
||||||
}
|
subscribedUids_.size()));
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<std::string> SubscriptionManager::getSubscribedUids() const {
|
void SubscriptionManager::shutdown()
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
{
|
||||||
return std::vector<std::string>(subscribedUids_.begin(), subscribedUids_.end());
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<SubscriptionManager::Subscriber> SubscriptionManager::getSubscribers() const {
|
if (!initialized_) {
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
return;
|
||||||
std::vector<Subscriber> result;
|
}
|
||||||
|
|
||||||
if (!database_) {
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto dbSubscribers = database_->getAllSubscribers();
|
|
||||||
if (dbSubscribers) {
|
|
||||||
for (const auto& info : *dbSubscribers) {
|
|
||||||
if (subscribedUids_.contains(info.uid)) {
|
|
||||||
result.push_back({info.uid, info.nickname});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::optional<std::string> SubscriptionManager::getSubscriberNickname(const std::string& uid) const {
|
initialized_ = false;
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
database_.reset();
|
||||||
|
subscribedUids_.clear();
|
||||||
if (!subscribedUids_.contains(uid) || !database_) {
|
ECHOION_LOG_INFO("SubscriptionManager shutdown");
|
||||||
return std::nullopt;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
auto subscribers = database_->getAllSubscribers();
|
|
||||||
if (subscribers) {
|
|
||||||
for (const auto& info : *subscribers) {
|
|
||||||
if (info.uid == uid) {
|
|
||||||
return info.nickname;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool SubscriptionManager::updateNickname(const std::string& uid, const std::string& nickname) {
|
bool SubscriptionManager::subscribe(const std::string& uid,
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
const std::string& nickname)
|
||||||
|
{
|
||||||
if (!subscribedUids_.contains(uid)) {
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (database_) {
|
|
||||||
auto result = database_->addSubscriber(uid, nickname);
|
|
||||||
if (!result) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("Failed to update nickname for {}: {}",
|
|
||||||
uid, result.error().message));
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool SubscriptionManager::hasSubscribers() const {
|
// Check if already subscribed (ensures uniqueness)
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
if (subscribedUids_.contains(uid)) {
|
||||||
return !subscribedUids_.empty();
|
// Update nickname even if already subscribed
|
||||||
}
|
if (database_) {
|
||||||
|
database_->addSubscriber(uid, nickname);
|
||||||
|
}
|
||||||
|
return false; // Already subscribed
|
||||||
|
}
|
||||||
|
|
||||||
size_t SubscriptionManager::getSubscriberCount() const {
|
// Add to database first
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
if (database_) {
|
||||||
return subscribedUids_.size();
|
auto result = database_->addSubscriber(uid, nickname);
|
||||||
}
|
if (!result) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Failed to add subscriber {} to database: {}",
|
||||||
|
uid, result.error().message));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
bool SubscriptionManager::clearAll() {
|
subscribedUids_.insert(uid);
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
ECHOION_LOG_INFO(
|
||||||
|
std::format("Client {} ({}) subscribed", nickname, uid));
|
||||||
if (database_) {
|
return true;
|
||||||
auto result = database_->clearAllSubscribers();
|
}
|
||||||
if (!result) {
|
|
||||||
ECHOION_LOG_ERROR(std::format("Failed to clear all subscribers: {}",
|
bool SubscriptionManager::unsubscribe(const std::string& uid)
|
||||||
result.error().message));
|
{
|
||||||
return false;
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
}
|
|
||||||
}
|
bool removed = subscribedUids_.erase(uid) > 0;
|
||||||
|
if (removed) {
|
||||||
subscribedUids_.clear();
|
// Remove from database
|
||||||
ECHOION_LOG_INFO("All subscriptions cleared");
|
if (database_) {
|
||||||
return true;
|
auto result = database_->removeSubscriber(uid);
|
||||||
}
|
if (!result) {
|
||||||
|
ECHOION_LOG_ERROR(std::format(
|
||||||
|
"Failed to remove subscriber {} from database: {}", uid,
|
||||||
|
result.error().message));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ECHOION_LOG_INFO(std::format("Client {} unsubscribed", uid));
|
||||||
|
}
|
||||||
|
return removed;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SubscriptionManager::isSubscribed(const std::string& uid) const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
return subscribedUids_.contains(uid);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> SubscriptionManager::getSubscribedUids() const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
return std::vector<std::string>(subscribedUids_.begin(),
|
||||||
|
subscribedUids_.end());
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<SubscriptionManager::Subscriber>
|
||||||
|
SubscriptionManager::getSubscribers() const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
std::vector<Subscriber> result;
|
||||||
|
|
||||||
|
if (!database_) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto dbSubscribers = database_->getAllSubscribers();
|
||||||
|
if (dbSubscribers) {
|
||||||
|
for (const auto& info : *dbSubscribers) {
|
||||||
|
if (subscribedUids_.contains(info.uid)) {
|
||||||
|
result.push_back({info.uid, info.nickname});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<std::string>
|
||||||
|
SubscriptionManager::getSubscriberNickname(const std::string& uid) const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
|
||||||
|
if (!subscribedUids_.contains(uid) || !database_) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto subscribers = database_->getAllSubscribers();
|
||||||
|
if (subscribers) {
|
||||||
|
for (const auto& info : *subscribers) {
|
||||||
|
if (info.uid == uid) {
|
||||||
|
return info.nickname;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SubscriptionManager::updateNickname(const std::string& uid,
|
||||||
|
const std::string& nickname)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
|
||||||
|
if (!subscribedUids_.contains(uid)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (database_) {
|
||||||
|
auto result = database_->addSubscriber(uid, nickname);
|
||||||
|
if (!result) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Failed to update nickname for {}: {}", uid,
|
||||||
|
result.error().message));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SubscriptionManager::hasSubscribers() const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
return !subscribedUids_.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t SubscriptionManager::getSubscriberCount() const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
return subscribedUids_.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SubscriptionManager::clearAll()
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
|
||||||
|
if (database_) {
|
||||||
|
auto result = database_->clearAllSubscribers();
|
||||||
|
if (!result) {
|
||||||
|
ECHOION_LOG_ERROR(
|
||||||
|
std::format("Failed to clear all subscribers: {}",
|
||||||
|
result.error().message));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
subscribedUids_.clear();
|
||||||
|
ECHOION_LOG_INFO("All subscriptions cleared");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
+148
-131
@@ -1,144 +1,161 @@
|
|||||||
#include "echoion/core/UrlShortener.hpp"
|
|
||||||
#include "echoion/core/Logger.hpp"
|
#include "echoion/core/Logger.hpp"
|
||||||
|
#include "echoion/core/UrlShortener.hpp"
|
||||||
|
#include <Void/Data/Json.hpp>
|
||||||
#include <format>
|
#include <format>
|
||||||
#include <glaze/glaze.hpp>
|
|
||||||
|
|
||||||
namespace Echoion::Core {
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
UrlShortener::UrlShortener(std::shared_ptr<NetworkClient> networkClient)
|
UrlShortener::UrlShortener(std::shared_ptr<NetworkClient> networkClient)
|
||||||
: networkClient_(std::move(networkClient)) {
|
: networkClient_(std::move(networkClient))
|
||||||
}
|
{
|
||||||
|
}
|
||||||
|
|
||||||
UrlShortener::~UrlShortener() = default;
|
UrlShortener::~UrlShortener() = default;
|
||||||
|
|
||||||
Api::Result<std::string> UrlShortener::shortenYouTubeUrl(std::string_view videoId) {
|
Api::Result<std::string>
|
||||||
std::string originalUrl = std::format("https://www.youtube.com/watch?v={}", videoId);
|
UrlShortener::shortenYouTubeUrl(std::string_view videoId)
|
||||||
return shortenUrl(originalUrl);
|
{
|
||||||
}
|
std::string originalUrl =
|
||||||
|
std::format("https://www.youtube.com/watch?v={}", videoId);
|
||||||
|
return shortenUrl(originalUrl);
|
||||||
|
}
|
||||||
|
|
||||||
Api::Result<std::string> UrlShortener::shortenUrl(std::string_view originalUrl) {
|
Api::Result<std::string>
|
||||||
// Check cache first
|
UrlShortener::shortenUrl(std::string_view originalUrl)
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lock(cacheMutex_);
|
// Check cache first
|
||||||
auto it = cache_.find(std::string(originalUrl));
|
{
|
||||||
if (it != cache_.end()) {
|
std::lock_guard<std::mutex> lock(cacheMutex_);
|
||||||
auto now = std::chrono::system_clock::now();
|
auto it = cache_.find(std::string(originalUrl));
|
||||||
if (now - it->second.timestamp < cacheTtl_) {
|
if (it != cache_.end()) {
|
||||||
ECHOION_LOG_DEBUG(std::format("URL cache hit: {} -> {}",
|
auto now = std::chrono::system_clock::now();
|
||||||
originalUrl, it->second.shortenedUrl));
|
if (now - it->second.timestamp < cacheTtl_) {
|
||||||
return it->second.shortenedUrl;
|
ECHOION_LOG_DEBUG(std::format("URL cache hit: {} -> {}",
|
||||||
}
|
originalUrl,
|
||||||
// Expired, remove from cache
|
it->second.shortenedUrl));
|
||||||
cache_.erase(it);
|
return it->second.shortenedUrl;
|
||||||
}
|
}
|
||||||
}
|
// Expired, remove from cache
|
||||||
|
cache_.erase(it);
|
||||||
if (!networkClient_) {
|
}
|
||||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
}
|
||||||
"Network client not available"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// faumaray.ru API endpoint for URL shortening
|
|
||||||
// POST /shorten with JSON body {"longUrl": "https://..."}
|
|
||||||
// Response: {"shortUrl": "https://faumaray.ru/xxxxx"}
|
|
||||||
std::string apiUrl = "https://faumaray.ru/shorten";
|
|
||||||
|
|
||||||
// Build JSON request body - API expects "longUrl" field
|
|
||||||
std::string jsonBody = std::format(R"({{"longUrl":"{}"}})", originalUrl);
|
|
||||||
|
|
||||||
std::vector<Api::HttpHeader> headers = {
|
|
||||||
{"Content-Type", "application/json"},
|
|
||||||
{"User-Agent", "EchoionBot/1.0"}
|
|
||||||
};
|
|
||||||
|
|
||||||
ECHOION_LOG_DEBUG(std::format("Shortening URL via faumaray.ru: {}", originalUrl));
|
|
||||||
|
|
||||||
auto response = networkClient_->post(apiUrl, jsonBody, headers);
|
|
||||||
|
|
||||||
if (!response) {
|
|
||||||
ECHOION_LOG_WARNING(std::format("URL shortening failed: {}",
|
|
||||||
response.error().message));
|
|
||||||
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
|
|
||||||
"Failed to shorten URL"));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!response->isSuccess()) {
|
|
||||||
ECHOION_LOG_WARNING(std::format("URL shortening returned HTTP {}",
|
|
||||||
response->statusCode));
|
|
||||||
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
|
|
||||||
std::format("Shortening service returned HTTP {}", response->statusCode)));
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Parse response - expecting {"shortUrl": "https://faumaray.ru/xxxxx"}
|
|
||||||
glz::generic json;
|
|
||||||
if (glz::read_json(json, response->body)) {
|
|
||||||
ECHOION_LOG_WARNING("Failed to parse URL shortening response");
|
|
||||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
|
||||||
"Failed to parse shortening response"));
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string shortenedUrl;
|
|
||||||
if (json.contains("shortUrl")) {
|
|
||||||
shortenedUrl = json["shortUrl"].get<std::string>();
|
|
||||||
} else {
|
|
||||||
ECHOION_LOG_WARNING("No shortUrl field in response");
|
|
||||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
|
||||||
"No shortUrl in response"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cache the result
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(cacheMutex_);
|
|
||||||
cache_[std::string(originalUrl)] = {
|
|
||||||
.shortenedUrl = shortenedUrl,
|
|
||||||
.timestamp = std::chrono::system_clock::now()
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
ECHOION_LOG_DEBUG(std::format("URL shortened: {} -> {}", originalUrl, shortenedUrl));
|
|
||||||
return shortenedUrl;
|
|
||||||
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
ECHOION_LOG_WARNING(std::format("Exception parsing shortening response: {}",
|
|
||||||
e.what()));
|
|
||||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
|
||||||
"Exception during URL shortening"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::optional<std::string> UrlShortener::getCachedUrl(std::string_view originalUrl) const {
|
if (!networkClient_) {
|
||||||
std::lock_guard<std::mutex> lock(cacheMutex_);
|
return std::unexpected(
|
||||||
auto it = cache_.find(std::string(originalUrl));
|
Api::Error(Api::ErrorCode::ServiceUnavailable,
|
||||||
if (it != cache_.end()) {
|
"Network client not available"));
|
||||||
auto now = std::chrono::system_clock::now();
|
}
|
||||||
if (now - it->second.timestamp < cacheTtl_) {
|
|
||||||
return it->second.shortenedUrl;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
|
|
||||||
void UrlShortener::clearCache() {
|
// faumaray.ru API endpoint for URL shortening
|
||||||
std::lock_guard<std::mutex> lock(cacheMutex_);
|
// POST /shorten with JSON body {"longUrl": "https://..."}
|
||||||
cache_.clear();
|
// Response: {"shortUrl": "https://faumaray.ru/xxxxx"}
|
||||||
}
|
std::string apiUrl = "https://faumaray.ru/shorten";
|
||||||
|
|
||||||
void UrlShortener::setCacheTtl(std::chrono::hours ttl) {
|
// Build JSON request body - API expects "longUrl" field
|
||||||
cacheTtl_ = ttl;
|
std::string jsonBody =
|
||||||
}
|
std::format(R"({{"longUrl":"{}"}})", originalUrl);
|
||||||
|
|
||||||
void UrlShortener::cleanExpiredCache() {
|
std::vector<Api::HttpHeader> headers = {
|
||||||
std::lock_guard<std::mutex> lock(cacheMutex_);
|
{"Content-Type", "application/json"},
|
||||||
auto now = std::chrono::system_clock::now();
|
{"User-Agent", "EchoionBot/1.0"}};
|
||||||
|
|
||||||
for (auto it = cache_.begin(); it != cache_.end();) {
|
ECHOION_LOG_DEBUG(
|
||||||
if (now - it->second.timestamp >= cacheTtl_) {
|
std::format("Shortening URL via faumaray.ru: {}", originalUrl));
|
||||||
it = cache_.erase(it);
|
|
||||||
} else {
|
auto response = networkClient_->post(apiUrl, jsonBody, headers);
|
||||||
++it;
|
|
||||||
}
|
if (!response) {
|
||||||
}
|
ECHOION_LOG_WARNING(std::format("URL shortening failed: {}",
|
||||||
}
|
response.error().message));
|
||||||
|
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
|
||||||
|
"Failed to shorten URL"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response->isSuccess()) {
|
||||||
|
ECHOION_LOG_WARNING(std::format("URL shortening returned HTTP {}",
|
||||||
|
response->statusCode));
|
||||||
|
return std::unexpected(
|
||||||
|
Api::Error(Api::ErrorCode::NetworkError,
|
||||||
|
std::format("Shortening service returned HTTP {}",
|
||||||
|
response->statusCode)));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Parse response - expecting {"shortUrl":
|
||||||
|
// "https://faumaray.ru/xxxxx"}
|
||||||
|
auto parsed = Void::Json::parse(response->body);
|
||||||
|
if (!parsed) {
|
||||||
|
ECHOION_LOG_WARNING("Failed to parse URL shortening response");
|
||||||
|
return std::unexpected(
|
||||||
|
Api::Error(Api::ErrorCode::ParseError,
|
||||||
|
"Failed to parse shortening response"));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string shortenedUrl;
|
||||||
|
const Void::Json::Value* shortUrl = parsed->find("shortUrl");
|
||||||
|
if (shortUrl && shortUrl->is_string()) {
|
||||||
|
shortenedUrl = shortUrl->as_string();
|
||||||
|
} else {
|
||||||
|
ECHOION_LOG_WARNING("No shortUrl field in response");
|
||||||
|
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
||||||
|
"No shortUrl in response"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cache the result
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(cacheMutex_);
|
||||||
|
cache_[std::string(originalUrl)] = {
|
||||||
|
.shortenedUrl = shortenedUrl,
|
||||||
|
.timestamp = std::chrono::system_clock::now()};
|
||||||
|
}
|
||||||
|
|
||||||
|
ECHOION_LOG_DEBUG(std::format("URL shortened: {} -> {}",
|
||||||
|
originalUrl, shortenedUrl));
|
||||||
|
return shortenedUrl;
|
||||||
|
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ECHOION_LOG_WARNING(std::format(
|
||||||
|
"Exception parsing shortening response: {}", e.what()));
|
||||||
|
return std::unexpected(Api::Error(
|
||||||
|
Api::ErrorCode::ParseError, "Exception during URL shortening"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<std::string>
|
||||||
|
UrlShortener::getCachedUrl(std::string_view originalUrl) const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(cacheMutex_);
|
||||||
|
auto it = cache_.find(std::string(originalUrl));
|
||||||
|
if (it != cache_.end()) {
|
||||||
|
auto now = std::chrono::system_clock::now();
|
||||||
|
if (now - it->second.timestamp < cacheTtl_) {
|
||||||
|
return it->second.shortenedUrl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
void UrlShortener::clearCache()
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(cacheMutex_);
|
||||||
|
cache_.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
void UrlShortener::setCacheTtl(std::chrono::hours ttl) { cacheTtl_ = ttl; }
|
||||||
|
|
||||||
|
void UrlShortener::cleanExpiredCache()
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(cacheMutex_);
|
||||||
|
auto now = std::chrono::system_clock::now();
|
||||||
|
|
||||||
|
for (auto it = cache_.begin(); it != cache_.end();) {
|
||||||
|
if (now - it->second.timestamp >= cacheTtl_) {
|
||||||
|
it = cache_.erase(it);
|
||||||
|
} else {
|
||||||
|
++it;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace Echoion::Core
|
} // namespace Echoion::Core
|
||||||
+1449
-1346
File diff suppressed because it is too large.
Load diff
+620
-627
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,109 @@
|
|||||||
|
#include "echoion/core/NetworkClient.hpp"
|
||||||
|
#include "echoion/core/commands/RpcInfoCommand.hpp"
|
||||||
|
#include <ConfigManager.hpp>
|
||||||
|
#include <format>
|
||||||
|
#include <future>
|
||||||
|
#include <regex>
|
||||||
|
|
||||||
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
|
std::string getPublicIpAddress()
|
||||||
|
{
|
||||||
|
// Try to get public IP from external services
|
||||||
|
static std::string cachedIp;
|
||||||
|
static std::chrono::steady_clock::time_point lastFetch;
|
||||||
|
|
||||||
|
// Cache IP for 5 minutes to avoid excessive API calls
|
||||||
|
auto now = std::chrono::steady_clock::now();
|
||||||
|
if (!cachedIp.empty() &&
|
||||||
|
std::chrono::duration_cast<std::chrono::minutes>(now - lastFetch)
|
||||||
|
.count() < 5) {
|
||||||
|
return cachedIp;
|
||||||
|
}
|
||||||
|
|
||||||
|
// List of services to try
|
||||||
|
const std::vector<std::string> ipServices = {
|
||||||
|
"https://api.ipify.org", "https://checkip.amazonaws.com",
|
||||||
|
"https://icanhazip.com", "https://ifconfig.me/ip"};
|
||||||
|
|
||||||
|
// Create a temporary network client for IP lookup
|
||||||
|
auto networkClient = std::make_shared<NetworkClient>();
|
||||||
|
auto initResult = networkClient->initialize();
|
||||||
|
if (!initResult) {
|
||||||
|
return cachedIp.empty() ? "127.0.0.1" : cachedIp;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const auto& service : ipServices) {
|
||||||
|
try {
|
||||||
|
auto result = networkClient->get(service);
|
||||||
|
if (result && result->isSuccess()) {
|
||||||
|
// Extract IP from response body (trim whitespace)
|
||||||
|
std::string ip = result->body;
|
||||||
|
// Remove whitespace and newlines
|
||||||
|
ip.erase(std::remove_if(ip.begin(), ip.end(),
|
||||||
|
[](unsigned char c) {
|
||||||
|
return std::isspace(c);
|
||||||
|
}),
|
||||||
|
ip.end());
|
||||||
|
|
||||||
|
// Validate IP format (basic check)
|
||||||
|
std::regex ipRegex(
|
||||||
|
R"(^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$)");
|
||||||
|
if (std::regex_match(ip, ipRegex)) {
|
||||||
|
cachedIp = ip;
|
||||||
|
lastFetch = now;
|
||||||
|
return cachedIp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (...) {
|
||||||
|
// Try next service
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return cached IP or localhost if all services failed
|
||||||
|
return cachedIp.empty() ? "127.0.0.1" : cachedIp;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RpcInfoCommand::execute(const CommandContext& ctx)
|
||||||
|
{
|
||||||
|
// Get RPC configuration from global ConfigManager
|
||||||
|
const auto& networkConfig = ECHOION_NETWORK;
|
||||||
|
uint16_t rpcPort = networkConfig.rpcPort;
|
||||||
|
std::string rpcBindAddress = networkConfig.rpcBindAddress;
|
||||||
|
|
||||||
|
// Determine the public IP to show
|
||||||
|
std::string publicIp = getPublicIpAddress();
|
||||||
|
|
||||||
|
// If bind address is not localhost, use it
|
||||||
|
if (rpcBindAddress != "127.0.0.1" && rpcBindAddress != "localhost") {
|
||||||
|
publicIp = rpcBindAddress;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Format message using plain text (compatible with TS3 BBCode and TS6
|
||||||
|
// Markdown)
|
||||||
|
std::string message = std::format(
|
||||||
|
"**RPC Server Information**\n\n"
|
||||||
|
"The RPC server allows remote control via WebSocket API.\n\n"
|
||||||
|
"**Connection Details:**\n"
|
||||||
|
"Address: {}:{}\n"
|
||||||
|
"Protocol: WebSocket (ws://)\n\n"
|
||||||
|
"**To connect:**\n"
|
||||||
|
"1. Subscribe to the bot with !subscribe\n"
|
||||||
|
"2. Connect to ws://{}:{}\n"
|
||||||
|
"3. Send auth request with your nickname: "
|
||||||
|
"{{\"nickname\":\"YourName\"}}\n"
|
||||||
|
"4. Check your TeamSpeak PM for the token\n"
|
||||||
|
"5. Authenticate with: {{\"token\":\"YOUR_TOKEN\"}}\n\n"
|
||||||
|
"**Available endpoints:**\n"
|
||||||
|
"- Playback control (play, pause, skip, volume)\n"
|
||||||
|
"- Queue management\n"
|
||||||
|
"- Track information\n"
|
||||||
|
"- Real-time event updates",
|
||||||
|
publicIp, rpcPort, publicIp, rpcPort);
|
||||||
|
|
||||||
|
ctx.reply(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Echoion::Core
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
#include "echoion/core/state/StateMigration.hpp"
|
||||||
|
#include "echoion/core/state/StateSerializer.hpp"
|
||||||
|
#include <Void/Data/Json.hpp>
|
||||||
|
#include <Void/Data/Reflect.hpp>
|
||||||
|
#include <format>
|
||||||
|
|
||||||
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
|
Api::Result<StateV1> StateMigration::migrate(uint32_t fromVersion,
|
||||||
|
const std::string& jsonData)
|
||||||
|
{
|
||||||
|
// Migration chain: fromVersion -> ... -> CURRENT_VERSION
|
||||||
|
// For now, only V0 -> V1 is implemented
|
||||||
|
// Future: V1 -> V2, V2 -> V3, etc.
|
||||||
|
|
||||||
|
if (fromVersion == 0) {
|
||||||
|
auto parsed = Void::Json::parse(jsonData);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::unexpected(Api::Error{Api::ErrorCode::ParseError,
|
||||||
|
"Failed to parse V0 state"});
|
||||||
|
}
|
||||||
|
auto v0 = Void::Json::from_json<StateV0>(*parsed);
|
||||||
|
if (!v0) {
|
||||||
|
return std::unexpected(Api::Error{Api::ErrorCode::ParseError,
|
||||||
|
"Failed to parse V0 state"});
|
||||||
|
}
|
||||||
|
return fromV0(*v0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add more migrations here as versions evolve
|
||||||
|
// if (fromVersion == 1) { return fromV1(...); }
|
||||||
|
|
||||||
|
return std::unexpected(Api::Error{
|
||||||
|
Api::ErrorCode::IncompatibleVersion,
|
||||||
|
std::format("No migration path from version {}", fromVersion)});
|
||||||
|
}
|
||||||
|
|
||||||
|
StateV1 StateMigration::fromV0(const StateV0& v0)
|
||||||
|
{
|
||||||
|
StateV1 v1;
|
||||||
|
|
||||||
|
// Migrate queue
|
||||||
|
for (const auto& trackId : v0.trackIds) {
|
||||||
|
StateV1::QueueEntryState entry;
|
||||||
|
entry.track.id = trackId;
|
||||||
|
entry.track.title = "Unknown";
|
||||||
|
entry.track.artist = "Unknown";
|
||||||
|
v1.queue.push_back(std::move(entry));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Migrate playback state
|
||||||
|
if (!v1.queue.empty()) {
|
||||||
|
StateV1::PlaybackState playback;
|
||||||
|
playback.currentTrack = v1.queue[0].track;
|
||||||
|
playback.volume = v0.volume;
|
||||||
|
v1.playback = std::move(playback);
|
||||||
|
v1.hasPlayback = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
v1.version = 1;
|
||||||
|
v1.savedAt = StateSerializer::getCurrentTimestampISO8601();
|
||||||
|
|
||||||
|
return v1;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool StateMigration::canMigrate(uint32_t fromVersion)
|
||||||
|
{
|
||||||
|
return fromVersion >= StateSerializer::getMinimumSupportedVersion() &&
|
||||||
|
fromVersion < StateSerializer::getCurrentVersion();
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Echoion::Core
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
// #include "echoion/api/base/StateBlob.hpp"
|
||||||
|
#include "echoion/core/state/StateMigration.hpp"
|
||||||
|
#include "echoion/core/state/StateSerializer.hpp"
|
||||||
|
#include <Void/Data/Json.hpp>
|
||||||
|
#include <Void/Data/Reflect.hpp>
|
||||||
|
#include <format>
|
||||||
|
#include <iomanip>
|
||||||
|
#include <sstream>
|
||||||
|
|
||||||
|
namespace Echoion::Core
|
||||||
|
{
|
||||||
|
|
||||||
|
Api::StateBlob StateSerializer::serialize(const StateV1& state)
|
||||||
|
{
|
||||||
|
// Serialize to JSON using Void::Json reflection
|
||||||
|
std::string jsonStr =
|
||||||
|
Void::Json::serialize(Void::Json::to_json(state));
|
||||||
|
|
||||||
|
// Convert to binary blob
|
||||||
|
std::vector<uint8_t> data(jsonStr.begin(), jsonStr.end());
|
||||||
|
|
||||||
|
return Api::StateBlob{.data = std::move(data),
|
||||||
|
.version = CURRENT_VERSION,
|
||||||
|
.timestamp = getCurrentTimestampISO8601()};
|
||||||
|
}
|
||||||
|
|
||||||
|
Api::Result<StateV1>
|
||||||
|
StateSerializer::deserialize(const Api::StateBlob& blob)
|
||||||
|
{
|
||||||
|
if (blob.data.empty()) {
|
||||||
|
return std::unexpected(Api::Error{Api::ErrorCode::InvalidArgument,
|
||||||
|
"Empty state blob"});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert blob to string
|
||||||
|
std::string jsonStr(blob.data.begin(), blob.data.end());
|
||||||
|
|
||||||
|
// Extract version
|
||||||
|
uint32_t dataVersion = extractVersion(jsonStr);
|
||||||
|
|
||||||
|
// Check if version is supported
|
||||||
|
if (!isVersionSupported(dataVersion)) {
|
||||||
|
if (dataVersion > CURRENT_VERSION) {
|
||||||
|
return std::unexpected(Api::Error{
|
||||||
|
Api::ErrorCode::IncompatibleVersion,
|
||||||
|
std::format("State version {} is from a newer Core. "
|
||||||
|
"Please update/restart to load this state.",
|
||||||
|
dataVersion)});
|
||||||
|
} else {
|
||||||
|
return std::unexpected(Api::Error{
|
||||||
|
Api::ErrorCode::IncompatibleVersion,
|
||||||
|
std::format("State version {} is too old. "
|
||||||
|
"Maximum supported age is {} versions.",
|
||||||
|
dataVersion,
|
||||||
|
Api::MAX_SUPPORTED_STATE_VERSION_AGE)});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If current version, parse directly
|
||||||
|
if (dataVersion == CURRENT_VERSION) {
|
||||||
|
auto parsed = Void::Json::parse(jsonStr);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::unexpected(Api::Error{
|
||||||
|
Api::ErrorCode::ParseError,
|
||||||
|
std::format("Failed to parse state ({}:{}): {}",
|
||||||
|
parsed.error().line, parsed.error().col,
|
||||||
|
parsed.error().message)});
|
||||||
|
}
|
||||||
|
auto state = Void::Json::from_json<StateV1>(*parsed);
|
||||||
|
if (!state) {
|
||||||
|
return std::unexpected(Api::Error{
|
||||||
|
Api::ErrorCode::ParseError,
|
||||||
|
std::format("Failed to decode state: field '{}': {}",
|
||||||
|
state.error().field, state.error().message)});
|
||||||
|
}
|
||||||
|
return *state;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise, migrate
|
||||||
|
return StateMigration::migrate(dataVersion, jsonStr);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool StateSerializer::isVersionSupported(uint32_t version)
|
||||||
|
{
|
||||||
|
if (version > CURRENT_VERSION) {
|
||||||
|
return false; // Future version
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t minVersion = getMinimumSupportedVersion();
|
||||||
|
return version >= minVersion && version <= CURRENT_VERSION;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t StateSerializer::getMinimumSupportedVersion()
|
||||||
|
{
|
||||||
|
// Support 10 versions back, but not below 1
|
||||||
|
return (CURRENT_VERSION > Api::MAX_SUPPORTED_STATE_VERSION_AGE)
|
||||||
|
? CURRENT_VERSION - Api::MAX_SUPPORTED_STATE_VERSION_AGE
|
||||||
|
: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t StateSerializer::getCurrentVersion() { return CURRENT_VERSION; }
|
||||||
|
|
||||||
|
uint32_t StateSerializer::extractVersion(const std::string& jsonStr)
|
||||||
|
{
|
||||||
|
// Quick extraction without full parse
|
||||||
|
// Look for "version": N pattern
|
||||||
|
size_t pos = jsonStr.find("\"version\"");
|
||||||
|
if (pos != std::string::npos) {
|
||||||
|
pos = jsonStr.find(':', pos);
|
||||||
|
if (pos != std::string::npos) {
|
||||||
|
// Skip whitespace
|
||||||
|
pos++;
|
||||||
|
while (pos < jsonStr.size() &&
|
||||||
|
std::isspace(static_cast<unsigned char>(jsonStr[pos]))) {
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
// Parse number
|
||||||
|
if (pos < jsonStr.size() &&
|
||||||
|
std::isdigit(static_cast<unsigned char>(jsonStr[pos]))) {
|
||||||
|
try {
|
||||||
|
return static_cast<uint32_t>(
|
||||||
|
std::stoul(jsonStr.substr(pos)));
|
||||||
|
} catch (...) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default to 0 (unknown/legacy)
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string StateSerializer::getCurrentTimestampISO8601()
|
||||||
|
{
|
||||||
|
auto now = std::chrono::system_clock::now();
|
||||||
|
auto time_t_now = std::chrono::system_clock::to_time_t(now);
|
||||||
|
|
||||||
|
std::stringstream ss;
|
||||||
|
ss << std::put_time(std::gmtime(&time_t_now), "%Y-%m-%dT%H:%M:%SZ");
|
||||||
|
return ss.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Echoion::Core
|
||||||
Reference in new issue
Block a user