Initial commit

This commit is contained in:
faumaray committed 2026-02-01 23:04:49 +03:00
commit a583c17916
56 files changed
+11025

No files matched your search

+272
View File
@@ -0,0 +1,272 @@
---
BasedOnStyle: LLVM
AccessModifierOffset: 0
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveAssignments:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: true
AlignConsecutiveBitFields:
Enabled: true
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveDeclarations:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveMacros:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveShortCaseStatements:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCaseArrows: false
AlignCaseColons: false
AlignConsecutiveTableGenBreakingDAGArgColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveTableGenCondOperatorColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveTableGenDefinitionColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignEscapedNewlines: Right
AlignOperands: Align
AlignTrailingComments:
Kind: Always
OverEmptyLines: 0
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowBreakBeforeNoexceptSpecifier: Never
AllowShortBlocksOnASingleLine: Never
AllowShortCaseExpressionOnASingleLine: true
AllowShortCaseLabelsOnASingleLine: false
AllowShortCompoundRequirementOnASingleLine: true
AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AttributeMacros:
- __capability
BinPackArguments: true
BinPackParameters: true
BitFieldColonSpacing: Both
BraceWrapping:
AfterCaseLabel: true
AfterClass: true
AfterControlStatement: Never
AfterEnum: false
AfterFunction: true
AfterNamespace: true
AfterObjCDeclaration: false
AfterStruct: true
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: true
BeforeLambdaBody: true
BeforeWhile: true
IndentBraces: true
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakAdjacentStringLiterals: true
BreakAfterAttributes: Leave
BreakAfterJavaFieldAnnotations: false
BreakAfterReturnType: None
BreakArrays: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Linux
BreakBeforeConceptDeclarations: Always
BreakBeforeInlineASMColon: OnlyMultiline
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
BreakFunctionDefinitionParameters: false
BreakInheritanceList: BeforeColon
BreakStringLiterals: true
BreakTemplateDeclarations: MultiLine
ColumnLimit: 80
CommentPragmas: ""
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: true
DisableFormat: false
EmptyLineAfterAccessModifier: Always
EmptyLineBeforeAccessModifier: LogicalBlock
ExperimentalAutoDetectBinPacking: true
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Preserve
IncludeCategories:
- Regex: ^"(llvm|llvm-c|clang|clang-c)/
Priority: 2
SortPriority: 0
CaseSensitive: true
- Regex: ^(<|"(gtest|gmock|isl|json)/)
Priority: 3
SortPriority: 0
CaseSensitive: true
- Regex: .*
Priority: 1
SortPriority: 0
CaseSensitive: true
IncludeIsMainRegex: (Test)?$
IncludeIsMainSourceRegex: ""
IndentAccessModifiers: true
IndentCaseBlocks: true
IndentCaseLabels: true
IndentExternBlock: AfterExternBlock
IndentGotoLabels: true
IndentPPDirectives: None
IndentRequiresClause: true
IndentWidth: 4
IndentWrappedFunctionNames: true
InsertBraces: true
InsertNewlineAtEOF: true
InsertTrailingCommas: None
IntegerLiteralSeparator:
Binary: 0
BinaryMinDigits: 0
Decimal: 0
DecimalMinDigits: 0
Hex: 0
HexMinDigits: 0
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLines:
AtEndOfFile: false
AtStartOfBlock: true
AtStartOfFile: true
LambdaBodyIndentation: Signature
LineEnding: DeriveLF
MacroBlockBegin: ""
MacroBlockEnd: ""
MainIncludeChar: AngleBracket
MaxEmptyLinesToKeep: 1
NamespaceIndentation: All
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 2
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PPIndentWidth: -1
PackConstructorInitializers: BinPack
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
PenaltyBreakScopeResolution: 500
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyIndentedWhitespace: 0
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
QualifierAlignment: Leave
ReferenceAlignment: Pointer
ReflowComments: true
RemoveBracesLLVM: false
RemoveParentheses: Leave
RemoveSemicolon: false
RequiresClausePosition: OwnLine
RequiresExpressionIndentation: OuterScope
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SkipMacroDefinitionBody: false
SortIncludes: CaseSensitive
SortJavaStaticImport: Before
SortUsingDeclarations: LexicographicNumeric
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceAroundPointerQualifiers: Default
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeJsonColon: false
SpaceBeforeParens: ControlStatements
SpaceBeforeParensOptions:
AfterControlStatements: true
AfterForeachMacros: true
AfterFunctionDeclarationName: false
AfterFunctionDefinitionName: false
AfterIfMacros: true
AfterOverloadedOperator: false
AfterPlacementOperator: true
AfterRequiresInClause: false
AfterRequiresInExpression: false
BeforeNonEmptyParentheses: false
SpaceBeforeRangeBasedForLoopColon: true
SpaceBeforeSquareBrackets: false
SpaceInEmptyBlock: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: Never
SpacesInContainerLiterals: true
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: -1
SpacesInParens: Never
SpacesInParensOptions:
ExceptDoubleParentheses: false
InConditionalStatements: false
InCStyleCasts: false
InEmptyParentheses: false
Other: false
SpacesInSquareBrackets: false
Standard: Latest
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 4
TableGenBreakInsideDAGArg: DontBreak
UseTab: Always
VerilogBreakBetweenInstancePorts: true
WhitespaceSensitiveMacros:
- BOOST_PP_STRINGIZE
- CF_SWIFT_NAME
- NS_SWIFT_NAME
- PP_STRINGIZE
- STRINGIZE
+4
View File
@@ -0,0 +1,4 @@
*build*
.cache
.idea
AGENTS.md
+125
View File
@@ -0,0 +1,125 @@
cmake_minimum_required(VERSION 3.28)
project(EchoionCore VERSION 1.0.0 LANGUAGES CXX)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
add_definitions(-DECHOION_API_EXPORT)
add_library(EchoionCore SHARED
src/Logger.cpp
src/NetworkClient.cpp
src/SignatureCipher.cpp
src/YouTubeClient.cpp
src/YtDlpManager.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(Echoion::Core ALIAS EchoionCore)
target_include_directories(EchoionCore PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
target_link_libraries(EchoionCore PUBLIC Echoion::Api)
find_package(glaze CONFIG REQUIRED)
find_package(PkgConfig REQUIRED)
pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET
libavformat
libavcodec
libswresample
libavutil
)
CPMAddPackage(
NAME quickjs
GITHUB_REPOSITORY quickjs-ng/quickjs
GIT_TAG v0.11.0
)
set(AddBoost.cmake_VERSION 3.7.3)
CPMAddPackage(
NAME AddBoost.cmake
VERSION "${AddBoost.cmake_VERSION}"
URL "https://github.com/Arniiiii/AddBoost.cmake/archive/refs/tags/${AddBoost.cmake_VERSION}.tar.gz"
)
set(TRY_BOOST_VERSION "1.90.0")
set(BOOST_MY_OPTIONS "BOOST_ENABLE_PYTHON ON;")
set(BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED "thread;system")
set(BOOST_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED "asio;beast;uuid;container;cobalt;url")
add_boost(
TRY_BOOST_VERSION BOOST_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED
BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED EchoionCore
)
find_package(Threads REQUIRED)
find_package(OpenSSL REQUIRED)
find_package(SQLite3 REQUIRED)
find_package(TBB REQUIRED)
target_link_libraries(EchoionCore
PUBLIC
PkgConfig::LIBAV
TBB::tbb
SQLite::SQLite3
PRIVATE
glaze::glaze
Threads::Threads
qjs
Boost::beast
Boost::url
Boost::asio
OpenSSL::SSL
OpenSSL::Crypto
)
if(MSVC)
target_compile_options(EchoionCore PRIVATE /W4 /WX-)
target_compile_definitions(EchoionCore PRIVATE _CRT_SECURE_NO_WARNINGS)
else()
target_compile_options(EchoionCore PRIVATE -Wall -Wextra -Wpedantic)
endif()
set_target_properties(EchoionCore PROPERTIES
OUTPUT_NAME "Echoion"
PREFIX ""
SUFFIX ".ts"
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib
ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib
)
include(GNUInstallDirs)
install(TARGETS EchoionCore
EXPORT EchoionCoreTargets
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
)
install(EXPORT EchoionCoreTargets
FILE EchoionCoreTargets.cmake
NAMESPACE Echoion::
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/EchoionCore
)
install(DIRECTORY include/
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
+458
View File
@@ -0,0 +1,458 @@
# SPDX-FileCopyrightText: 2024 L. E. Segovia <amy@centricular.com>
# SPDX-License-Ref: LGPL-2.1-or-later
#[=======================================================================[.rst:
FindGStreamer
-------
Finds the GStreamer library. Requires ``pkg-config`` to be installed.
Configuration
^^^^^^^^^^^^^
This module can be configured with the following variables:
``GStreamer_STATIC``
Link against GStreamer statically (see below).
Imported Targets
^^^^^^^^^^^^^^^^
This module defines the following :prop_tgt:`IMPORTED` targets:
``GStreamer::GStreamer``
The GStreamer library.
Result Variables
^^^^^^^^^^^^^^^^
This will define the following variables:
``GStreamer_FOUND``
True if the system has the GStreamer library.
``GStreamer_VERSION``
The version of the GStreamer library which was found.
``GStreamer_INCLUDE_DIRS``
Include directories needed to use GStreamer.
``GStreamer_LIBRARIES``
Libraries needed to link to GStreamer.
Cache Variables
^^^^^^^^^^^^^^^
The following cache variables may also be set:
``GStreamer_INCLUDE_DIR``
The directory containing ``gst/gstversion.h``.
``GStreamer_LIBRARY``
The path to the GStreamer library.
Configuration Variables
^^^^^^^^^^^^^^^
Setting the following variables is required, depending on the operating system:
``GStreamer_ROOT_DIR``
Installation prefix of the GStreamer SDK.
``GStreamer_USE_STATIC_LIBS`
Set to ON to force the use of the static libraries. Default is OFF.
``GStreamer_EXTRA_DEPS``
pkg-config names of the extra dependencies that will be included whenever linking against GStreamer.
#]=======================================================================]
if(GStreamer_FOUND)
return()
endif()
#####################
# Setup variables #
#####################
if(NOT DEFINED GStreamer_ROOT_DIR AND DEFINED GSTREAMER_ROOT)
set(GStreamer_ROOT_DIR ${GSTREAMER_ROOT})
endif()
if(NOT GStreamer_ROOT_DIR)
set(GStreamer_ROOT_DIR "${CMAKE_CURRENT_LIST_DIR}/../../")
endif()
if(NOT EXISTS "${GStreamer_ROOT_DIR}")
message(FATAL_ERROR "The directory GStreamer_ROOT_DIR=${GStreamer_ROOT_DIR} does not exist")
endif()
if(NOT DEFINED GStreamer_USE_STATIC_LIBS)
set(GStreamer_USE_STATIC_LIBS OFF)
endif()
# Set the environment for pkg-config
if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows")
set(ENV{PKG_CONFIG_PATH} "${GStreamer_ROOT_DIR}/lib/pkgconfig;${GStreamer_ROOT_DIR}/lib/gstreamer-1.0/pkgconfig;${GStreamer_ROOT_DIR}/lib/gio/modules/pkgconfig")
# Block pkgconf's forced relocation for non-lib/pkgconfig modules on Windows -- https://github.com/pkgconf/pkgconf/commit/dcf529b83d621ed09e99e41fc35fdffd068bd87a
set(ENV{PKG_CONFIG_DONT_DEFINE_PREFIX} 1)
else()
set(ENV{PKG_CONFIG_PATH} "${GStreamer_ROOT_DIR}/lib/pkgconfig:${GStreamer_ROOT_DIR}/lib/gstreamer-1.0/pkgconfig:${GStreamer_ROOT_DIR}/lib/gio/modules/pkgconfig")
endif()
# Set the list of extra dependencies
if(NOT DEFINED GStreamer_EXTRA_DEPS)
set(GStreamer_EXTRA_DEPS)
if(DEFINED GSTREAMER_EXTRA_DEPS)
set(GStreamer_EXTRA_DEPS ${GSTREAMER_EXTRA_DEPS})
endif()
endif()
# Find libraries. This is meant to be used with static libraries
# (hence the reprioritization) but I've added a fallback to shared libraries
# and stub modules in case any are non-existent.
function(_gst_find_library LOCAL_LIB GST_LOCAL_LIB)
if(DEFINED ${GST_LOCAL_LIB})
return()
endif()
set(_gst_suffixes ${CMAKE_FIND_LIBRARY_SUFFIXES})
set(_gst_prefixes ${CMAKE_FIND_LIBRARY_PREFIXES})
if(APPLE)
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a" ".dylib" ".so" ".tbd")
set(CMAKE_FIND_LIBRARY_PREFIXES "" "lib")
elseif(UNIX)
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a" ".so")
set(CMAKE_FIND_LIBRARY_PREFIXES "" "lib")
else()
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a" ".lib")
set(CMAKE_FIND_LIBRARY_PREFIXES "" "lib")
endif()
if("${LOCAL_LIB}" IN_LIST _gst_IGNORED_SYSTEM_LIBRARIES)
set(${GST_LOCAL_LIB} ${LOCAL_LIB} PARENT_SCOPE)
else()
find_library(${GST_LOCAL_LIB}
${LOCAL_LIB}
HINTS ${ARGN}
NO_DEFAULT_PATH
NO_CMAKE_FIND_ROOT_PATH
REQUIRED
)
set(${GST_LOCAL_LIB} "${${GST_LOCAL_LIB}}" PARENT_SCOPE)
if(NOT ${GST_LOCAL_LIB})
message(FATAL_ERROR "${LOCAL_LIB} was unexpectedly not found.")
endif()
endif()
set(CMAKE_FIND_LIBRARY_SUFFIXES ${_gst_suffixes})
set(CMAKE_FIND_LIBRARY_PREFIXES ${_gst_prefixes})
endfunction()
macro(_gst_apply_link_libraries HIDE PC_LIBRARIES PC_HINTS GST_TARGET)
if(APPLE AND ${HIDE})
target_link_directories(${GST_TARGET} INTERFACE
${${PC_HINTS}}
)
endif()
foreach(LOCAL_LIB IN LISTS ${PC_LIBRARIES})
if(LOCAL_LIB MATCHES "${_gst_SRT_REGEX_PATCH}")
string(REGEX REPLACE "${_gst_SRT_REGEX_PATCH}" "\\1" LOCAL_LIB "${LOCAL_LIB}")
endif()
string(MAKE_C_IDENTIFIER "_gst_${LOCAL_LIB}" GST_LOCAL_LIB)
if(NOT ${GST_LOCAL_LIB})
_gst_find_library(${LOCAL_LIB} ${GST_LOCAL_LIB} ${${PC_HINTS}})
endif()
if("${${GST_LOCAL_LIB}}" IN_LIST _gst_IGNORED_SYSTEM_LIBRARIES)
target_link_libraries(${GST_TARGET} INTERFACE
${${GST_LOCAL_LIB}})
elseif(APPLE AND ${HIDE})
set(LOCAL_FILE)
get_filename_component(LOCAL_FILE ${${GST_LOCAL_LIB}} NAME)
target_link_libraries(${GST_TARGET} INTERFACE
"-hidden-l${LOCAL_FILE}")
elseif((UNIX OR ANDROID) AND ${HIDE})
target_link_libraries(${GST_TARGET} INTERFACE
-Wl,--exclude-libs,${${GST_LOCAL_LIB}})
else()
target_link_libraries(${GST_TARGET} INTERFACE
${${GST_LOCAL_LIB}})
endif()
endforeach()
endmacro()
macro(_gst_filter_missing_directories GST_INCLUDE_DIRS)
set(_gst_include_dirs)
foreach(DIR IN LISTS ${GST_INCLUDE_DIRS})
string(MAKE_C_IDENTIFIER "${DIR}" _gst_dir_id)
if(DEFINED _gst_exists_${_gst_dir_id})
if(_gst_exists_${_gst_dir_id})
list(APPEND _gst_include_dirs "${DIR}")
endif()
elseif(EXISTS "${DIR}")
list(APPEND _gst_include_dirs "${DIR}")
set(_gst_exists_${_gst_dir_id} TRUE)
else()
message(WARNING "Skipping missing include folder ${DIR}.")
set(_gst_exists_${_gst_dir_id} FALSE)
endif()
endforeach()
set(${GST_INCLUDE_DIRS} "${_gst_include_dirs}")
endmacro()
macro(_gst_apply_frameworks PC_STATIC_LDFLAGS_OTHER GST_TARGET)
if(APPLE)
# LDFLAGS_OTHER may include framework linkage. Because CMake
# iterates over arguments separated by spaces, it doesn't realise
# that those arguments must not be split.
set(new_ldflags)
set(assemble_framework FALSE)
foreach(_arg IN LISTS ${PC_STATIC_LDFLAGS_OTHER})
if(assemble_framework)
set(assemble_framework FALSE)
find_library(GST_${_arg}_LIB ${_arg} REQUIRED)
target_link_libraries(${GST_TARGET}
INTERFACE
"${GST_${_arg}_LIB}"
)
elseif(_arg STREQUAL "-framework")
set(assemble_framework TRUE)
else()
set(assemble_framework FALSE)
list(APPEND new_ldflags "${_arg}")
endif()
endforeach()
set_target_properties(${GST_TARGET} PROPERTIES
INTERFACE_LINK_OPTIONS "${new_ldflags}"
)
else()
set_target_properties(${TARGET} PROPERTIES
INTERFACE_LINK_OPTIONS "${${PC_STATIC_LDFLAGS_OTHER}}"
)
endif()
endmacro()
################################
# Set up the targets #
################################
find_package(PkgConfig REQUIRED)
# GStreamer's pkg-config modules are a MUST -- but we'll test them below
pkg_check_modules(PC_GStreamer gstreamer-1.0 ${GStreamer_EXTRA_DEPS})
# Simulate the list that'll be wholearchive'd.
# Unfortunately, this uses an option only available with pkgconf.
# set(_old_pkg_config_executable "${PKG_CONFIG_EXECUTABLE}")
# set(PKG_CONFIG_EXECUTABLE ${PKG_CONFIG_EXECUTABLE} --maximum-traverse-depth=1)
# pkg_check_modules(PC_GStreamer_NoDeps QUIET REQUIRED gstreamer-1.0 ${GStreamer_EXTRA_DEPS})
# set(PKG_CONFIG_EXECUTABLE "${_old_pkg_config_executable}")
set(GStreamer_VERSION "${PC_GStreamer_VERSION}")
# Test validity of the paths
# NOTE: only paths that must be considered are those provided by pkg-config
# NOTE 2: also exclude sysroots
find_path(GStreamer_INCLUDE_DIR
NAMES gst/gstversion.h
PATHS ${PC_GStreamer_INCLUDE_DIRS}
PATH_SUFFIXES gstreamer-1.0
NO_DEFAULT_PATH
NO_CMAKE_FIND_ROOT_PATH
REQUIRED
)
find_library(GStreamer_LIBRARY
NAMES gstreamer-1.0
PATHS ${PC_GStreamer_LIBRARY_DIRS}
NO_DEFAULT_PATH
NO_CMAKE_FIND_ROOT_PATH
REQUIRED
)
# Android: Ignore these libraries when constructing the IMPORTED_LOCATION
set(_gst_IGNORED_SYSTEM_LIBRARIES c c++ unwind m dl atomic)
if(ANDROID)
list(APPEND _gst_IGNORED_SYSTEM_LIBRARIES log GLESv2 EGL OpenSLES android vulkan)
elseif(APPLE)
list(APPEND _gst_IGNORED_SYSTEM_LIBRARIES iconv resolv System)
endif()
# Normalize library flags coming from srt/haisrt
# https://github.com/Haivision/srt/commit/b90b64d26f850fb0efcc4cdd8b31cbf74bd4db0c
set(_gst_SRT_REGEX_PATCH "^:lib(.+)\\.(a|so|lib|dylib)$")
if(PC_GStreamer_FOUND AND (NOT TARGET GStreamer::GStreamer))
# This is not UNKNOWN but INTERFACE, as we only intend to
# make a target suitable for downstream consumption.
# FindPkgConfig already takes care of things, however it is totally unable
# to discern between shared and static libraries when populating
# xxx_STATIC_LINK_LIBRARIES, so we need to populate them manually.
add_library(GStreamer::GStreamer INTERFACE IMPORTED)
if(GStreamer_USE_STATIC_LIBS)
_gst_filter_missing_directories(PC_GStreamer_STATIC_INCLUDE_DIRS)
set_target_properties(GStreamer::GStreamer PROPERTIES
INTERFACE_COMPILE_OPTIONS "${PC_GStreamer_STATIC_CFLAGS_OTHER}"
)
if(PC_GStreamer_STATIC_INCLUDE_DIRS)
set_target_properties(GStreamer::GStreamer PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${PC_GStreamer_STATIC_INCLUDE_DIRS}"
)
endif()
_gst_apply_frameworks(PC_GStreamer_STATIC_LDFLAGS_OTHER GStreamer::GStreamer)
else()
set_target_properties(GStreamer::GStreamer PROPERTIES
INTERFACE_COMPILE_OPTIONS "${PC_GStreamer_CFLAGS_OTHER}"
INTERFACE_INCLUDE_DIRECTORIES "${PC_GStreamer_INCLUDE_DIRS}"
INTERFACE_LINK_OPTIONS "${PC_GStreamer_LDFLAGS_OTHER}"
)
endif()
add_library(GStreamer::deps INTERFACE IMPORTED)
if(NOT GStreamer_USE_STATIC_LIBS)
set_target_properties(GStreamer::deps PROPERTIES
INTERFACE_LINK_LIBRARIES "${PC_GStreamer_LINK_LIBRARIES}"
)
# We're done
else()
# Handle all libraries, even those specified with -l:libfoo.a (srt)
# Due to the unavailability of pkgconf's `--maximum-traverse-depth`
# on stock pkg-config, I attempt to simulate it through the shared
# libraries listing.
# If pkgconf is available, replace all PC_GStreamer_ entries with
# PC_GStreamer_NoDeps and uncomment the code block above.
foreach(LOCAL_LIB IN LISTS PC_GStreamer_LIBRARIES)
# list(TRANSFORM REPLACE) is of no use here
# https://gitlab.kitware.com/cmake/cmake/-/issues/16899
if(LOCAL_LIB MATCHES "${_gst_SRT_REGEX_PATCH}")
string(REGEX REPLACE "${_gst_SRT_REGEX_PATCH}" "\\1" LOCAL_LIB "${LOCAL_LIB}")
endif()
string(MAKE_C_IDENTIFIER "_gst_${LOCAL_LIB}" GST_LOCAL_LIB)
if(NOT ${GST_LOCAL_LIB})
_gst_find_library(${LOCAL_LIB} ${GST_LOCAL_LIB} ${PC_GStreamer_STATIC_LIBRARY_DIRS})
endif()
target_link_libraries(GStreamer::GStreamer INTERFACE
"${${GST_LOCAL_LIB}}"
)
endforeach()
_gst_apply_link_libraries(ON PC_GStreamer_STATIC_LIBRARIES PC_GStreamer_STATIC_LIBRARY_DIRS GStreamer::deps)
endif()
target_link_libraries(GStreamer::GStreamer
INTERFACE
GStreamer::deps
)
endif()
foreach(_gst_PLUGIN IN LISTS GSTREAMER_PLUGINS)
# Safety valve for the custom targets above
if("${_gst_plugin}" IN_LIST _gst_CUSTOM_TARGETS)
continue()
endif()
if(TARGET GStreamer::${_gst_PLUGIN})
continue()
endif()
if(GStreamer_FIND_REQUIRED_${_gst_PLUGIN})
set(_gst_PLUGIN_REQUIRED REQUIRED)
else()
set(_gst_PLUGIN_REQUIRED)
endif()
pkg_check_modules(PC_GStreamer_${_gst_PLUGIN} "gst${_gst_PLUGIN}")
set(GStreamer_${_gst_PLUGIN}_FOUND "${PC_GStreamer_${_gst_PLUGIN}_FOUND}")
if(NOT GStreamer_${_gst_PLUGIN}_FOUND)
continue()
endif()
add_library(GStreamer::${_gst_PLUGIN} INTERFACE IMPORTED)
_gst_filter_missing_directories(PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS)
set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES
INTERFACE_COMPILE_OPTIONS "${PC_GStreamer_${_gst_PLUGIN}_CFLAGS_OTHER}"
)
if(PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS)
set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS}"
)
endif()
if(GStreamer_USE_STATIC_LIBS)
_gst_apply_frameworks(PC_GStreamer_${_gst_PLUGIN}_STATIC_LDFLAGS_OTHER GStreamer::${_gst_PLUGIN})
else()
set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES
INTERFACE_LINK_OPTIONS "${PC_GStreamer_${_gst_PLUGIN}_LDFLAGS_OTHER}"
INTERFACE_LINK_LIBRARIES "${PC_GStreamer_${_gst_PLUGIN}_LINK_LIBRARIES}"
)
# We're done
continue()
endif()
# Handle all libraries, even those specified with -l:libfoo.a (srt)
_gst_apply_link_libraries(OFF PC_GStreamer_${_gst_PLUGIN}_STATIC_LIBRARIES PC_GStreamer_${_gst_PLUGIN}_STATIC_LIBRARY_DIRS GStreamer::${_gst_PLUGIN})
endforeach()
foreach(_gst_PLUGIN IN LISTS GSTREAMER_APIS)
# Safety valve for the custom targets above
if("${_gst_plugin}" IN_LIST _gst_CUSTOM_TARGETS)
continue()
endif()
if(TARGET GStreamer::${_gst_PLUGIN})
continue()
endif()
if(GStreamer_FIND_REQUIRED_${_gst_PLUGIN})
set(_gst_PLUGIN_REQUIRED REQUIRED)
else()
set(_gst_PLUGIN_REQUIRED)
endif()
string(REGEX REPLACE "^api_(.+)" "\\1" _gst_PLUGIN_PC "${_gst_PLUGIN}")
string(REPLACE "_" "-" _gst_PLUGIN_PC "${_gst_PLUGIN_PC}")
pkg_check_modules(PC_GStreamer_${_gst_PLUGIN} "gstreamer-${_gst_PLUGIN_PC}-1.0")
set(GStreamer_${_gst_PLUGIN}_FOUND "${PC_GStreamer_${_gst_PLUGIN}_FOUND}")
if(NOT GStreamer_${_gst_PLUGIN}_FOUND)
continue()
endif()
add_library(GStreamer::${_gst_PLUGIN} INTERFACE IMPORTED)
_gst_filter_missing_directories(PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS)
set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES
INTERFACE_COMPILE_OPTIONS "${PC_GStreamer_${_gst_PLUGIN}_CFLAGS_OTHER}"
INTERFACE_LINK_OPTIONS "${PC_GStreamer_${_gst_PLUGIN}_LDFLAGS_OTHER}"
)
if(PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS)
set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS}"
)
endif()
if(GStreamer_USE_STATIC_LIBS)
_gst_apply_frameworks(PC_GStreamer_${_gst_PLUGIN}_STATIC_LDFLAGS_OTHER GStreamer::${_gst_PLUGIN})
else()
set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES
INTERFACE_LINK_OPTIONS "${PC_GStreamer_${_gst_PLUGIN}_LDFLAGS_OTHER}"
INTERFACE_LINK_LIBRARIES "${PC_GStreamer_${_gst_PLUGIN}_LINK_LIBRARIES}"
)
# We're done
continue()
endif()
# Handle all libraries, even those specified with -l:libfoo.a (srt)
_gst_apply_link_libraries(OFF PC_GStreamer_${_gst_PLUGIN}_STATIC_LIBRARIES PC_GStreamer_${_gst_PLUGIN}_STATIC_LIBRARY_DIRS GStreamer::${_gst_PLUGIN})
endforeach()
# Perform final validation
include(FindPackageHandleStandardArgs)
set(_gst_handle_version_range)
if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.19.0")
set(_gst_handle_version_range "HANDLE_VERSION_RANGE")
endif()
find_package_handle_standard_args(GStreamer
REQUIRED_VARS
GStreamer_LIBRARY
GStreamer_INCLUDE_DIR
VERSION_VAR GStreamer_VERSION
${_gst_handle_version_range}
HANDLE_COMPONENTS
)
+145
View File
@@ -0,0 +1,145 @@
#pragma once
#include <echoion/api.hpp>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <atomic>
#include <span>
#include <optional>
// Forward declarations for FFmpeg
extern "C" {
struct AVFormatContext;
struct AVCodecContext;
struct AVFrame;
struct AVPacket;
struct SwrContext;
struct AVBufferRef;
}
namespace Echoion::Core {
class AudioDecoder {
public:
AudioDecoder();
~AudioDecoder();
// Initialize decoder with optional hardware acceleration
Api::Result<void> initialize(const Api::HwAccelConfig& hwConfig = {});
void shutdown();
// Open audio source (URL or file path)
Api::Result<void> openSource(const std::string& url);
void closeSource();
// Decode audio - returns zero-copy pooled buffer
[[nodiscard]] Api::Result<Api::DecodedAudio> decodeFrame();
// Seek to position
Api::Result<void> seek(std::chrono::milliseconds position);
// Get audio info
[[nodiscard]] Api::Result<Api::AudioStreamInfo> getStreamInfo() const;
// Get current position
[[nodiscard]] std::chrono::milliseconds getPosition() const;
// Check if decoder has more data
[[nodiscard]] bool hasMoreData() const;
// Set output format
void setOutputFormat(uint32_t sampleRate, uint32_t channels);
// Set proxy configuration for network requests
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
// 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:
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();
// Zero-copy frame conversion
Api::Result<Api::DecodedAudio> convertFrameZeroCopy();
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_ = 48000;
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::optional<Api::ProxyConfig> proxyConfig_;
// Statistics
mutable std::mutex statsMutex_;
Stats stats_;
};
} // namespace Echoion::Core
+124
View File
@@ -0,0 +1,124 @@
#pragma once
#include <echoion/api.hpp>
#include "commands/Command.hpp"
#include "echoion/api/ConfigTypes.hpp"
#include <map>
#include <vector>
#include <memory>
#include <mutex>
#include <string>
#include <functional>
namespace Echoion::Core {
class MusicManager;
// Function to check if client has permission (set by Core)
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() = default;
// 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.
* @param clientId The client ID who invoked the command.
* @param message The full message (including prefix, e.g., "!play 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 executed, 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 = ""
);
[[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_;
};
} // namespace Echoion::Core
+30
View File
@@ -0,0 +1,30 @@
#pragma once
#include <echoion/api.hpp>
#include <filesystem>
#include <string>
namespace Echoion::Core {
// 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();
private:
// 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
+111
View File
@@ -0,0 +1,111 @@
#pragma once
#include <echoion/api.hpp>
#include <echoion/api/Database.hpp>
#include "MusicManager.hpp"
#include "CommandManager.hpp"
#include "NetworkClient.hpp"
#include "RpcServer.hpp"
#include "ConfigLoader.hpp"
#include <thread>
#include <mutex>
#include <atomic>
namespace Echoion::Core {
// Main Core implementation of ICoreInterface
class Core : public Api::ICoreInterface {
public:
Core();
~Core() override;
// ICoreInterface implementation
Api::Result<void> initialize(const std::filesystem::path& configPath) override;
Api::Result<void> shutdown() override;
[[nodiscard]] bool isInitialized() const noexcept override;
// Playback control
Api::Result<void> play(const Api::TrackInfo& track) override;
Api::Result<void> pause() override;
Api::Result<void> resume() override;
Api::Result<void> stop() 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
Api::Result<uint64_t> queueTrack(const Api::TrackInfo& track, uint64_t clientId) override;
Api::Result<void> removeFromQueue(uint64_t queueId) override;
Api::Result<void> clearQueue() override;
[[nodiscard]] Api::Result<std::vector<Api::QueueEntry>> getQueue() const override;
Api::Result<void> moveInQueue(uint64_t queueId, uint32_t newPosition) override;
// Track info
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>> getCurrentTrack() const override;
[[nodiscard]] Api::Result<Api::PlaybackState> getPlaybackState() const override;
// Playlist
Api::Result<void> loadPlaylist(const std::string& playlistId, uint64_t clientId) override;
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>> getPlaylists() const override;
// Configuration
Api::Result<void> updateConfig(const Api::AppConfig& config) override;
[[nodiscard]] Api::Result<Api::AppConfig> getConfig() const override;
// Reload config from disk (stored path from initialize)
Api::Result<void> reloadConfig();
// Hot reload
Api::Result<Api::HotReloadState> prepareForHotReload() override;
Api::Result<void> restoreAfterHotReload(const Api::HotReloadState& state) override;
// Event handling
void registerEventCallback(const Api::EventCallback& callback) override;
void unregisterEventCallback(const Api::EventCallback& callback) override;
// Plugin event processing
Api::Result<void> onPluginEvent(const Api::PluginEvent& event) override;
// Status
[[nodiscard]] std::string getVersion() const override;
[[nodiscard]] std::chrono::system_clock::time_point getUptime() const override;
// Additional methods for plugin integration
void setPluginInterface(Api::PluginInterfacePtr pluginInterface) override;
void setAudioDataCallback(const MusicManager::AudioDataCallback& callback);
void triggerAutoConnect() override;
private:
void onMusicEvent(const Api::PluginEvent& event);
void broadcastEvent(const Api::PluginEvent& event);
[[nodiscard]] bool isAdmin(uint64_t clientId) const;
void updateWhisperList();
void setupRpcHandlers();
// Components
std::shared_ptr<NetworkClient> networkClient_;
std::shared_ptr<MusicManager> musicManager_;
std::unique_ptr<CommandManager> commandManager_;
Api::PluginInterfacePtr pluginInterface_;
// State
Api::AppConfig config_; // Config loaded internally
std::filesystem::path configPath_; // Path to config file for reload
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
+77
View File
@@ -0,0 +1,77 @@
#pragma once
#include <echoion/api.hpp>
#include <fstream>
#include <mutex>
#include <queue>
#include <thread>
#include <condition_variable>
#include <atomic>
#include <filesystem>
#include <vector>
#include <chrono>
#include <array>
#include <map>
namespace Echoion::Core {
// Log file info for rotation
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 {
public:
explicit Logger(std::string_view logDir = "logs", std::string_view baseName = "echoion");
~Logger() override;
void log(Api::LogLevel level, std::string_view message,
std::source_location location) override;
void setMinLevel(Api::LogLevel level) override;
[[nodiscard]] Api::LogLevel getMinLevel() const override;
void registerCallback(const LogCallback& callback) override;
void unregisterCallback(const LogCallback& callback) override;
void flush();
void setConsoleOutput(bool enabled);
void setFileOutput(bool enabled);
void setMaxFileSize(uint64_t bytes);
void setMaxFiles(uint32_t count);
private:
void logWorker();
void rotateIfNeeded(Api::LogLevel level);
void openLogFiles();
void cleanupOldLogs();
[[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_;
std::string baseName_;
// Separate files for each level + combined file
std::map<Api::LogLevel, LogFileInfo> levelFiles_;
LogFileInfo combinedFile_;
std::mutex fileMutex_;
std::mutex queueMutex_;
std::queue<Api::LogEntry> logQueue_;
std::thread workerThread_;
std::condition_variable cv_;
std::atomic<bool> running_{true};
std::atomic<Api::LogLevel> minLevel_{Api::LogLevel::Info};
std::atomic<bool> consoleOutput_{true};
std::atomic<bool> fileOutput_{true};
std::atomic<uint64_t> maxFileSize_{10 * 1024 * 1024}; // 10 MB per file
std::atomic<uint32_t> maxFiles_{5};
std::vector<LogCallback> callbacks_;
std::mutex callbackMutex_;
};
} // namespace Echoion::Core
+133
View File
@@ -0,0 +1,133 @@
#pragma once
#include <echoion/api.hpp>
#include "NetworkClient.hpp"
#include "YouTubeClient.hpp"
#include "AudioDecoder.hpp"
#include "SubscriptionManager.hpp"
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <random>
#include <atomic>
#include <future>
#include <set>
#include <unordered_map>
#include <filesystem>
namespace Echoion::Core {
class MusicManager {
public:
MusicManager();
~MusicManager();
Api::Result<void> initialize(const Api::BotConfig& config,
std::shared_ptr<NetworkClient> networkClient,
std::shared_ptr<Api::Database> database = nullptr);
void shutdown();
[[nodiscard]] Api::Result<std::string> play(const std::string& query, uint64_t clientId);
[[nodiscard]] Api::Result<void> pause();
[[nodiscard]] Api::Result<void> resume();
[[nodiscard]] Api::Result<void> stop();
[[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<void> removeFromQueue(uint32_t position);
[[nodiscard]] Api::Result<void> clearQueue();
[[nodiscard]] Api::Result<std::vector<Api::QueueEntry>> 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<uint32_t> loadPlaylist(const std::string& playlistId, uint64_t clientId);
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>> getPlaylists() const;
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>> getCurrentTrack() const;
[[nodiscard]] Api::Result<Api::PlaybackState> getPlaybackState() const;
[[nodiscard]] Api::Result<Api::SearchResult> search(const std::string& query);
// Search result selection (client-specific)
void storePendingSearch(uint64_t clientId, const std::vector<Api::TrackInfo>& results);
[[nodiscard]] std::optional<std::vector<Api::TrackInfo>> getPendingSearch(uint64_t clientId);
[[nodiscard]] Api::Result<std::string> selectSearchResult(
uint64_t clientId, uint32_t index, const std::string& invokerName);
// Help command
[[nodiscard]] std::string getHelpText() const;
// Subscription management
[[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;
[[nodiscard]] bool hasSubscribers() const;
[[nodiscard]] Api::HotReloadState getStateForHotReload() const;
[[nodiscard]] Api::Result<void> restoreFromHotReload(const Api::HotReloadState& state);
using AudioDataCallback = std::function<void(const std::span<const float>)>;
void setAudioDataCallback(const AudioDataCallback& callback);
using SubscriptionChangeCallback = std::function<void()>;
void setSubscriptionChangeCallback(const SubscriptionChangeCallback& callback);
// Called when a client leaves the server
void onClientDisconnected(uint64_t clientId);
private:
void playbackThread();
[[nodiscard]] Api::Result<Api::TrackInfo> resolveQuery(const std::string& query);
[[nodiscard]] Api::Result<std::string> getStreamUrl(const Api::TrackInfo& track);
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);
// Temporary file tracking
std::set<std::string> tempFiles_;
mutable std::mutex tempFilesMutex_;
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_;
bool isPlaying_ = false;
bool isPaused_ = false;
bool wasPausedForNoSubscribers_ = false; // Track if we auto-paused
float volume_ = 0.5f;
bool shuffle_ = false;
bool repeat_ = false;
uint64_t nextQueueId_ = 1;
std::jthread playbackThread_;
mutable std::mutex mutex_;
std::condition_variable cv_;
// 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_;
std::mt19937 rng_{std::random_device{}()};
static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE = 192000; // Match reference
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
+202
View File
@@ -0,0 +1,202 @@
#pragma once
#include "boost/asio/ssl/context.hpp"
#include <echoion/api.hpp>
#include <glaze/glaze.hpp>
#include <thread>
#include <mutex>
#include <future>
#include <queue>
#include <atomic>
#include <chrono>
// Boost.Beast includes needed for template function
#include <boost/beast.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;
// Initialize with optional proxy
Api::Result<void> initialize(const std::optional<Api::ProxyConfig>& proxy = std::nullopt);
void shutdown();
// Synchronous requests
[[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);
// Asynchronous requests
[[nodiscard]] std::future<Api::Result<Api::HttpResponse>> getAsync(std::string_view url,
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);
// Concurrent batch requests
[[nodiscard]] std::vector<Api::Result<Api::HttpResponse>> requestBatch(
const std::vector<Api::HttpRequest>& requests);
// JSON helpers using glaze
template<typename T>
[[nodiscard]] Api::Result<T> getJson(std::string_view url,
const std::vector<Api::HttpHeader>& headers = {}) {
auto response = get(url, 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;
}
template<typename T, typename Body>
[[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
void setProxy(const std::optional<Api::ProxyConfig>& proxy);
[[nodiscard]] std::optional<Api::ProxyConfig> getProxy() const;
void clearProxy();
// Retry configuration
void setRetryConfig(const Api::RetryConfig& config);
[[nodiscard]] Api::RetryConfig getRetryConfig() const;
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_;
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
+81
View File
@@ -0,0 +1,81 @@
#pragma once
#include <echoion/api.hpp>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <boost/beast/websocket.hpp>
#include <thread>
#include <mutex>
#include <set>
#include <functional>
#include <unordered_map>
namespace Echoion::Core {
namespace asio = boost::asio;
namespace beast = boost::beast;
namespace websocket = beast::websocket;
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)>;
RpcServer();
~RpcServer();
// Initialize and start the server
Api::Result<void> start(uint16_t port = 8765);
void stop();
[[nodiscard]] bool isRunning() const { return running_; }
[[nodiscard]] uint16_t getPort() const { return port_; }
// Register command handlers
void registerHandler(const std::string& method, CommandHandler handler);
void unregisterHandler(const std::string& method);
// Authentication
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);
// Broadcast events to all connected clients
void broadcastEvent(const std::string& event, const std::string& data);
// Send event to specific client
void sendEvent(uint64_t clientId, const std::string& event, const std::string& data);
private:
void acceptLoop();
void handleClient(std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws);
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_;
std::optional<asio::ip::tcp::acceptor> acceptor_;
std::thread serverThread_;
std::atomic<bool> running_{false};
uint16_t port_ = 8765;
// Connected clients
std::unordered_map<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
+129
View File
@@ -0,0 +1,129 @@
#pragma once
#include <string>
#include <string_view>
#include <vector>
#include <optional>
#include <memory>
#include <mutex>
#include <filesystem>
#include <quickjs.h>
namespace Echoion::Core {
/**
* Signature cipher for YouTube stream URLs
* Uses QuickJS (when available) to execute the JavaScript decipher functions from player JS
*
* Based on yt-dlp's signature extraction logic
*/
class SignatureCipher {
public:
SignatureCipher();
~SignatureCipher();
// Disable copy, enable move
SignatureCipher(const SignatureCipher&) = delete;
SignatureCipher& operator=(const SignatureCipher&) = delete;
SignatureCipher(SignatureCipher&&) noexcept;
SignatureCipher& operator=(SignatureCipher&&) noexcept;
/**
* Initialize the QuickJS solver with core libraries
* Must be called before using the cipher
*/
void initialize();
/**
* Set the player JS code and extract decipher functions
* @param playerJsCode The raw player JavaScript code from YouTube
* @return true if extraction succeeded
*/
bool setPlayerJs(std::string_view playerJsCode);
/**
* Check if the cipher is ready (has valid decipher function)
*/
[[nodiscard]] bool isReady() const;
/**
* Decipher a signature cipher string
* Format: s=ENCODED_SIG&sp=SIG_PARAM&url=ENCODED_URL
* @param signatureCipher The signature cipher string
* @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
* @param challenge The challenge string to solve
* @param type "sig" for signature, "n" for n-parameter
* @return The solved challenge or empty string on failure
*/
[[nodiscard]] std::string solveChallenge(const std::string& challenge, const std::string& type);
/**
* Decipher the n-parameter for throttling
* @param nParam The encoded n parameter
* @return The deciphered n parameter
*/
[[nodiscard]] std::string decipherNParam(std::string_view nParam);
/**
* Clear the cipher state
*/
void clear();
/**
* Check if cipher has been initialized
*/
[[nodiscard]] bool isInitialized() const;
private:
/**
* Initialize QuickJS runtime and context with solver libraries
*/
void initSolver();
/**
* 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
*/
[[nodiscard]] std::filesystem::path getCacheDir();
/**
* Execute JavaScript code in QuickJS and return result
*/
[[nodiscard]] std::optional<std::string> executeJS(
std::string_view code,
std::string_view filename = "<script>");
/**
* Cleanup QuickJS resources
*/
void cleanupQuickJS();
JSRuntime* runtime_ = nullptr;
JSContext* context_ = nullptr;
// 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
@@ -0,0 +1,45 @@
#pragma once
#include <echoion/api.hpp>
#include <set>
#include <string>
#include <mutex>
#include <memory>
namespace Echoion::Core {
/**
* Manages user subscriptions to the bot's audio output
* Subscriptions are persisted to database and survive client reloads
*/
class SubscriptionManager {
public:
SubscriptionManager();
~SubscriptionManager();
// Initialize and load subscriptions from database
Api::Result<void> initialize(std::shared_ptr<Api::Database> database);
void shutdown();
// Subscription management
bool subscribe(uint64_t clientId);
bool unsubscribe(uint64_t clientId);
bool isSubscribed(uint64_t clientId) const;
// Get all subscribed clients
std::set<uint64_t> getSubscribedClients() const;
// Check if anyone is subscribed
bool hasSubscribers() const;
// Get subscriber count
size_t getSubscriberCount() const;
private:
std::set<uint64_t> subscribedClients_;
mutable std::mutex mutex_;
std::shared_ptr<Api::Database> database_;
bool initialized_ = false;
};
} // namespace Echoion::Core
+67
View File
@@ -0,0 +1,67 @@
#pragma once
#include <echoion/api.hpp>
#include "NetworkClient.hpp"
#include "YtDlpManager.hpp"
#include <regex>
#include <mutex>
#include <optional>
#include <string>
#include <memory>
namespace Echoion::Core {
class YouTubeClient {
public:
explicit YouTubeClient(std::shared_ptr<NetworkClient> networkClient);
~YouTubeClient();
// Initialize the client - downloads yt-dlp if needed
Api::Result<void> initialize();
void shutdown();
// Check if yt-dlp is available
[[nodiscard]] bool isAvailable() const;
// Get yt-dlp version
[[nodiscard]] std::string getYtDlpVersion() const;
// Force update yt-dlp
Api::Result<void> updateYtDlp();
// Search for videos using yt-dlp
[[nodiscard]] Api::Result<Api::SearchResult> search(std::string_view query,
std::optional<std::string> pageToken = std::nullopt);
// Get video details including stream URLs using yt-dlp
[[nodiscard]] Api::Result<Api::TrackInfo> getVideoInfo(std::string_view videoId);
// Get playlist videos using yt-dlp
[[nodiscard]] Api::Result<Api::PlaylistInfo> getPlaylist(std::string_view playlistId);
// Extract video ID from various YouTube URL formats (handles redirects for short URLs)
[[nodiscard]] std::optional<std::string> extractVideoId(std::string_view url);
[[nodiscard]] static std::optional<std::string> extractPlaylistId(std::string_view url);
// Check if URL is a YouTube URL
[[nodiscard]] static bool isYouTubeUrl(std::string_view url);
// Get stream URL for a video (used by MusicManager)
[[nodiscard]] Api::Result<std::string> getStreamUrl(std::string_view videoId);
// Get best audio stream URL using yt-dlp
[[nodiscard]] Api::Result<std::string> getAudioStreamUrl(std::string_view videoId);
// Configure cookie options for yt-dlp
void setCookiesPath(const std::string& path);
void setCookiesFromBrowser(const std::string& browser);
private:
std::shared_ptr<NetworkClient> networkClient_;
std::unique_ptr<YtDlpManager> ytDlpManager_;
std::atomic<bool> initialized_{false};
mutable std::mutex mutex_;
};
} // namespace Echoion::Core
+81
View File
@@ -0,0 +1,81 @@
#pragma once
#include <echoion/api.hpp>
#include "NetworkClient.hpp"
#include <string>
#include <filesystem>
#include <atomic>
#include <mutex>
namespace Echoion::Core {
class YtDlpManager {
public:
explicit YtDlpManager(std::shared_ptr<NetworkClient> networkClient);
~YtDlpManager();
// Initialize - checks for yt-dlp and downloads if needed
Api::Result<void> initialize();
// 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
[[nodiscard]] std::string execute(const std::vector<std::string>& args) const;
// Set cookie options for YouTube authentication
void setCookiesPath(const std::string& path);
void setCookiesFromBrowser(const std::string& browser);
// Get cookie arguments for yt-dlp command
[[nodiscard]] std::vector<std::string> getCookieArgs() const;
private:
// Get the storage directory for yt-dlp
[[nodiscard]] std::filesystem::path getStorageDir() const;
// 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;
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_;
// 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
@@ -0,0 +1,46 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class ClearCommand : 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 result = manager->clearQueue();
if (!result) {
ECHOION_LOG_ERROR(std::format("Clear command failed: {}", result.error().message));
ctx.reply("Couldn't clear the queue. Please try again.");
return;
}
ctx.reply("Queue cleared!");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Clear command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Clears all tracks from the queue.";
}
CommandCategory getCategory() const override {
return CommandCategory::Queue;
}
std::vector<std::string_view> getAliases() const override {
return {"clr", "empty"};
}
};
} // namespace Echoion::Core
+105
View File
@@ -0,0 +1,105 @@
#pragma once
#include <echoion/api.hpp>
#include <cstdint>
#include <string>
#include <string_view>
#include <vector>
#include <memory>
#include <functional>
#include "echoion/core/MusicManager.hpp"
namespace Echoion::Core {
class MusicManager;
enum class CommandCategory {
Music,
Queue,
Playback,
Utility,
Admin
};
inline std::string toString(CommandCategory category) {
switch (category) {
case CommandCategory::Music:
return "Music";
case CommandCategory::Queue:
return "Queue";
case CommandCategory::Playback:
return "Playback";
case CommandCategory::Utility:
return "Utility";
case CommandCategory::Admin:
return "Admin";
}
return "Utility";
}
/**
* @brief Context passed to every command execution.
* Wraps all dependencies required to perform an action.
*/
struct CommandContext {
uint64_t clientId = 0;
std::string args; // Arguments excluding the command name
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);
}
}
};
/**
* @brief Interface that all commands must implement.
*/
class Command {
public:
virtual ~Command() = default;
/**
* @brief The logic of the command.
*/
virtual void execute(const CommandContext& ctx) = 0;
/**
* @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
@@ -0,0 +1,25 @@
#pragma once
// 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 "MoveCommand.hpp"
#include "ShuffleCommand.hpp"
#include "RepeatCommand.hpp"
#include "PlaylistCommand.hpp"
#include "NowPlayingCommand.hpp"
#include "SearchCommand.hpp"
#include "ReloadCommand.hpp"
#include "ReloadConfigCommand.hpp"
#include "SubscribeCommand.hpp"
#include "UnsubscribeCommand.hpp"
@@ -0,0 +1,82 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <charconv>
namespace Echoion::Core {
class MoveCommand : 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: move <from> <to>\nExample: move 5 1 (moves track 5 to position 1)");
return;
}
// Parse arguments: from and to positions
uint32_t from = 0, to = 0;
auto spacePos = ctx.args.find(' ');
if (spacePos == std::string::npos) {
ctx.reply("Please provide both from and to positions.");
return;
}
auto result1 = std::from_chars(ctx.args.data(),
ctx.args.data() + spacePos,
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) {
ctx.reply("Please provide valid position numbers (starting from 1).");
return;
}
auto moveResult = manager->moveInQueue(from - 1, to - 1); // Convert to 0-based
if (!moveResult) {
ECHOION_LOG_ERROR(std::format("Move command failed: {}", moveResult.error().message));
if (moveResult.error().code == 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;
}
ctx.reply(std::format("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::string_view getDescription() const override {
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
@@ -0,0 +1,66 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
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("Nothing is currently playing. Add something with [prefix]play!");
return;
}
const auto& track = current->value();
std::string msg = std::format("\xf0\x9f\x8e\xb5 **{}** by **{}**",
track.track.title,
track.track.artist);
if (track.track.duration > std::chrono::seconds(0)) {
auto mins = std::chrono::minutes(track.track.duration->count()).count();
auto secs = std::chrono::seconds(track.track.duration->count()).count() % 60;
msg += std::format(" [{}:{:02}]", mins, secs);
}
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"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,51 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class PauseCommand : 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 result = manager->pause();
if (!result) {
ECHOION_LOG_ERROR(std::format("Pause command failed: {}", result.error().message));
if (result.error().code == Api::ErrorCode::InvalidArgument) {
ctx.reply("Nothing is playing right now.");
} else {
ctx.reply("Couldn't pause playback. Please try again.");
}
return;
}
ctx.reply("Playback paused.");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Pause command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Pauses the current playback.";
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::vector<std::string_view> getAliases() const override {
return {};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,125 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
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;
}
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;
}
ctx.reply(std::format("Added to queue: {}", track.title));
return;
}
// Multiple results - store and show list
manager->storePendingSearch(ctx.clientId, searchResult->tracks);
std::string msg = "\xf0\x9f\x94\x8d Multiple results found. Use [prefix]select <number>:\n";
for (size_t i = 0; i < searchResult->tracks.size() && i < 5; ++i) {
const auto& track = searchResult->tracks[i];
msg += std::format("{}. {}", i + 1, track.title);
if (!track.artist.empty()) {
msg += std::format(" by {}", track.artist);
}
if (track.duration.has_value()) {
auto mins = std::chrono::duration_cast<std::chrono::minutes>(*track.duration).count();
auto secs = std::chrono::duration_cast<std::chrono::seconds>(*track.duration).count() % 60;
msg += std::format(" [{}:{:02}]", mins, secs);
}
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"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,80 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <sstream>
namespace Echoion::Core {
class PlaylistCommand : 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()) {
// List playlists
auto playlists = manager->getPlaylists();
if (!playlists) {
ECHOION_LOG_ERROR(std::format("Playlist list failed: {}", playlists.error().message));
ctx.reply("Couldn't retrieve playlists.");
return;
}
if (playlists->empty()) {
ctx.reply("No playlists available.");
return;
}
std::stringstream msg;
msg << "\xf0\x9f\x93\x81 Available playlists:\n";
for (const auto& pl : *playlists) {
msg << std::format("- {} ({} tracks)\n", pl.name, pl.tracks.size());
}
ctx.reply(msg.str());
} else {
// Load playlist
auto result = manager->loadPlaylist(std::string(ctx.args), ctx.clientId);
if (!result) {
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("Loaded {} tracks from playlist '{}'!", *result, 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.");
}
}
std::string_view getDescription() const override {
return "Lists or loads a playlist.";
}
std::string_view getUsage() const override {
return "[playlist name]";
}
CommandCategory getCategory() const override {
return CommandCategory::Music;
}
std::vector<std::string_view> getAliases() const override {
return {"pl"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,95 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <sstream>
namespace Echoion::Core {
class QueueCommand : 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();
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;
}
std::stringstream msg;
msg << "\xf0\x9f\x93\x9c **Queue**\n";
// Current track
if (current && current->has_value()) {
const auto& track = current->value();
msg << std::format("\n**Now Playing:** {} by {}\n",
track.track.title,
track.track.artist);
}
// Queue
if (queue->empty()) {
msg << "\nThe queue is empty. Add songs with [prefix]play!";
} else {
msg << std::format("\n**Up Next ({} tracks):**\n", queue->size());
for (size_t i = 0; i < queue->size() && i < 10; ++i) {
const auto& entry = (*queue)[i];
msg << std::format("{}. {}", i + 1, entry.track.title);
if (!entry.addedBy.empty()) {
msg << std::format(" (by {})", entry.addedBy);
}
msg << "\n";
}
if (queue->size() > 10) {
msg << std::format("\n... and {} more", queue->size() - 10);
}
}
// State indicators
if (state) {
msg << "\n\n";
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.");
}
}
std::string_view getDescription() const override {
return "Shows the current queue and playback status.";
}
CommandCategory getCategory() const override {
return CommandCategory::Queue;
}
std::vector<std::string_view> getAliases() const override {
return {"q", "list"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,34 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class ReloadCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
// 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 {
return "Shows information about reloading the bot.";
}
CommandCategory getCategory() const override {
return CommandCategory::Admin;
}
bool requiresAdmin() const override {
return true;
}
std::vector<std::string_view> getAliases() const override {
return {"restart", "r"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,42 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include "echoion/core/Core.hpp" // For Core::reloadConfig
#include <format>
namespace Echoion::Core {
class ReloadConfigCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
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 {
return "Reloads the bot configuration from file.";
}
CommandCategory getCategory() const override {
return CommandCategory::Admin;
}
bool requiresAdmin() const override {
return true;
}
std::vector<std::string_view> getAliases() const override {
return {"reloadcfg", "rlcfg"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,70 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <charconv>
namespace Echoion::Core {
class RemoveCommand : 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: remove <position>\nUse [prefix]queue to see track positions.");
return;
}
uint32_t position = 0;
auto result = std::from_chars(ctx.args.data(),
ctx.args.data() + ctx.args.size(),
position);
if (result.ec != std::errc() || position == 0) {
ctx.reply("Please provide a valid position number (starting from 1).");
return;
}
auto remResult = manager->removeFromQueue(position - 1); // Convert to 0-based
if (!remResult) {
ECHOION_LOG_ERROR(std::format("Remove command failed: {}", remResult.error().message));
if (remResult.error().code == 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;
}
ctx.reply(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.");
}
}
std::string_view getDescription() const override {
return "Removes a track from the queue by position.";
}
std::string_view getUsage() const override {
return "<position>";
}
CommandCategory getCategory() const override {
return CommandCategory::Queue;
}
std::vector<std::string_view> getAliases() const override {
return {"rm", "delete", "del"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,46 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class RepeatCommand : 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 result = manager->toggleRepeat();
if (!result) {
ECHOION_LOG_ERROR(std::format("Repeat command failed: {}", result.error().message));
ctx.reply("Couldn't toggle repeat. Please try again.");
return;
}
ctx.reply(*result ? "\xf0\x9f\x94\x81 Repeat is now ON." : "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.");
}
}
std::string_view getDescription() const override {
return "Toggles repeat mode for the current track.";
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::vector<std::string_view> getAliases() const override {
return {"loop"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,51 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class ResumeCommand : 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 result = manager->resume();
if (!result) {
ECHOION_LOG_ERROR(std::format("Resume command failed: {}", result.error().message));
if (result.error().code == Api::ErrorCode::InvalidArgument) {
ctx.reply("Playback isn't paused right now.");
} else {
ctx.reply("Couldn't resume playback. Please try again.");
}
return;
}
ctx.reply("Playback resumed.");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Resume command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
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
@@ -0,0 +1,90 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <sstream>
namespace Echoion::Core {
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];
msg << std::format("{}. {}", i + 1, track.title);
if (!track.artist.empty()) {
msg << std::format(" by {}", track.artist);
}
if (track.duration.has_value()) {
auto mins = std::chrono::duration_cast<std::chrono::minutes>(*track.duration).count();
auto secs = std::chrono::duration_cast<std::chrono::seconds>(*track.duration).count() % 60;
msg << std::format(" [{}:{:02}]", mins, secs);
}
msg << "\n";
}
msg << "\nUse [prefix]select <number> to play a result.";
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"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,84 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <chrono>
#include <charconv>
namespace Echoion::Core {
class SeekCommand : 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: seek <seconds>\nExample: seek 60 (jumps to 1 minute)");
return;
}
int seconds = 0;
auto parseResult = std::from_chars(ctx.args.data(),
ctx.args.data() + ctx.args.size(),
seconds);
if (parseResult.ec != std::errc()) {
ctx.reply("Please provide a valid number of seconds.");
return;
}
if (seconds < 0) {
ctx.reply("Time must be a positive number.");
return;
}
auto result = manager->seek(std::chrono::seconds(seconds));
if (!result) {
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;
}
auto mins = seconds / 60;
auto secs = seconds % 60;
if (mins > 0) {
ctx.reply(std::format("Seeked to {}:{:02}.", mins, secs));
} else {
ctx.reply(std::format("Seeked to {} seconds.", seconds));
}
} 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.";
}
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
@@ -0,0 +1,75 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <charconv>
namespace Echoion::Core {
class SelectCommand : 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: select <number>\nSelect a track from your last search results.");
return;
}
// Parse index
uint32_t index = 0;
auto result = std::from_chars(ctx.args.data(),
ctx.args.data() + ctx.args.size(),
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);
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("No search results found. Use [prefix]play <query> to search first.");
} 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.");
}
}
std::string_view getDescription() const override {
return "Selects a track from your search results.";
}
std::string_view getUsage() const override {
return "<number>";
}
CommandCategory getCategory() const override {
return CommandCategory::Music;
}
std::vector<std::string_view> getAliases() const override {
return {"sel", "pick", "choose"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,46 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class ShuffleCommand : 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 result = manager->toggleShuffle();
if (!result) {
ECHOION_LOG_ERROR(std::format("Shuffle command failed: {}", result.error().message));
ctx.reply("Couldn't toggle shuffle. Please try again.");
return;
}
ctx.reply(*result ? "\xf0\x9f\x94\x80 Shuffle is now ON." : "Shuffle is now OFF.");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Shuffle command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Toggles shuffle mode for the queue.";
}
CommandCategory getCategory() const override {
return CommandCategory::Queue;
}
std::vector<std::string_view> getAliases() const override {
return {"random"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,71 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <charconv>
namespace Echoion::Core {
class SkipCommand : 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;
}
uint32_t count = 1;
if (!ctx.args.empty()) {
auto result = std::from_chars(ctx.args.data(),
ctx.args.data() + ctx.args.size(),
count);
if (result.ec != std::errc() || count == 0) {
ctx.reply("Please provide a valid number (1 or more).");
return;
}
}
auto result = manager->skip(count);
if (!result) {
ECHOION_LOG_ERROR(std::format("Skip command failed: {}", result.error().message));
if (result.error().code == Api::ErrorCode::NotFound) {
ctx.reply("No more tracks in the queue to skip to.");
} else {
ctx.reply("Couldn't skip. Please try again.");
}
return;
}
if (count == 1) {
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.");
}
}
std::string_view getDescription() const override {
return "Skips to the next track(s).";
}
std::string_view getUsage() const override {
return "[count]";
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::vector<std::string_view> getAliases() const override {
return {"next", "n"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,46 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class StopCommand : 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 result = manager->stop();
if (!result) {
ECHOION_LOG_ERROR(std::format("Stop command failed: {}", result.error().message));
ctx.reply("Couldn't stop playback. Please try again.");
return;
}
ctx.reply("Playback stopped and queue cleared.");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Stop command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Stops playback and clears the queue.";
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::vector<std::string_view> getAliases() const override {
return {"s"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,46 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class SubscribeCommand : 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 result = manager->subscribe(ctx.clientId);
if (!result) {
ECHOION_LOG_ERROR(std::format("Subscribe failed: {}", result.error().message));
ctx.reply("Couldn't subscribe you. Please try again.");
return;
}
ctx.reply(*result);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Subscribe command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Subscribes to the music bot to receive audio.";
}
CommandCategory getCategory() const override {
return CommandCategory::Utility;
}
std::vector<std::string_view> getAliases() const override {
return {"sub", "join"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,46 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class UnsubscribeCommand : 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 result = manager->unsubscribe(ctx.clientId);
if (!result) {
ECHOION_LOG_ERROR(std::format("Unsubscribe failed: {}", result.error().message));
ctx.reply("Couldn't unsubscribe you. Please try again.");
return;
}
ctx.reply(*result);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Unsubscribe command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Unsubscribes from the music bot.";
}
CommandCategory getCategory() const override {
return CommandCategory::Utility;
}
std::vector<std::string_view> getAliases() const override {
return {"unsub", "leave"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,85 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <charconv>
namespace Echoion::Core {
class VolumeCommand : 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()) {
// Show current volume
auto state = manager->getPlaybackState();
if (state) {
ctx.reply(std::format("Current volume: {}%", static_cast<int>(state->volume * 100)));
} else {
ctx.reply("Unable to get current volume.");
}
return;
}
// Parse volume (0-100)
int volumePercent = 0;
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;
}
if (volumePercent < 0 || volumePercent > 100) {
ctx.reply("Volume must be between 0 and 100.");
return;
}
float volume = volumePercent / 100.0f;
auto volResult = manager->setVolume(volume);
if (!volResult) {
ECHOION_LOG_ERROR(std::format("Volume command failed: {}", volResult.error().message));
ctx.reply("Couldn't change volume. Please try again.");
return;
}
// Visual volume indicator
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
}
ctx.reply(std::format("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.");
}
}
std::string_view getDescription() const override {
return "Sets or shows the playback volume.";
}
std::string_view getUsage() const override {
return "[0-100]";
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::vector<std::string_view> getAliases() const override {
return {"vol", "v"};
}
};
} // namespace Echoion::Core
+630
View File
@@ -0,0 +1,630 @@
#include "echoion/core/AudioDecoder.hpp"
#include "echoion/core/NetworkClient.hpp"
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/opt.h>
#include <libavutil/dict.h>
#include <libavutil/hwcontext.h>
#include <libavutil/samplefmt.h>
#include <libswresample/swresample.h>
}
#include <format>
#include <cstring>
#include <fstream>
#include <filesystem>
#include <thread>
namespace Echoion::Core {
AudioDecoder::AudioDecoder() = default;
AudioDecoder::~AudioDecoder() {
shutdown();
cleanupFfmpeg();
cleanupHardwareAccel();
}
Api::Result<void> AudioDecoder::initialize(const Api::HwAccelConfig& hwConfig) {
if (initialized_) {
return {};
}
if (zeroCopyEnabled_) {
Api::AudioBufferPool::instance().initialize(
outputSampleRate_ / 50 * outputChannels_,
256
);
}
if (hwConfig.isEnabled()) {
auto result = initializeHardwareAccel(hwConfig);
if (!result) {
ECHOION_LOG_WARNING(std::format("Hardware acceleration init failed: {}, falling back to software",
result.error().message));
}
}
av_log_set_level(AV_LOG_DEBUG);
initialized_ = true;
ECHOION_LOG_INFO("AudioDecoder initialized");
return {};
}
Api::Result<void> AudioDecoder::initializeHardwareAccel(const Api::HwAccelConfig& config) {
enum AVHWDeviceType hwType = AV_HWDEVICE_TYPE_NONE;
switch (config.type) {
case Api::HwAccelType::CUDA: hwType = AV_HWDEVICE_TYPE_CUDA; break;
case Api::HwAccelType::VAAPI: hwType = AV_HWDEVICE_TYPE_VAAPI; break;
case Api::HwAccelType::DXVA2: hwType = AV_HWDEVICE_TYPE_DXVA2; break;
case Api::HwAccelType::D3D11VA: hwType = AV_HWDEVICE_TYPE_D3D11VA; break;
case Api::HwAccelType::VideoToolbox: hwType = AV_HWDEVICE_TYPE_VIDEOTOOLBOX; break;
default: return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, "Unsupported hardware acceleration type"));
}
if (av_hwdevice_find_type_by_name(av_hwdevice_get_type_name(hwType)) == AV_HWDEVICE_TYPE_NONE) {
return std::unexpected(Api::Error(Api::ErrorCode::NotSupported, "Hardware acceleration not available on this system"));
}
hwAccelType_ = config.type;
ECHOION_LOG_INFO(std::format("Hardware acceleration configured: {}", av_hwdevice_get_type_name(hwType)));
return {};
}
void AudioDecoder::shutdown() {
decoding_ = false;
shouldExit_ = true; // Signal FFmpeg to abort blocking I/O
cv_.notify_all();
if (decodeThread_.joinable()) {
decodeThread_.join();
}
closeSource();
initialized_ = false;
}
void AudioDecoder::cleanupHardwareAccel() {
if (hwFramesContext_) av_buffer_unref(&hwFramesContext_);
if (hwDeviceContext_) av_buffer_unref(&hwDeviceContext_);
hwAccelEnabled_ = false;
}
Api::Result<void> AudioDecoder::openSource(const std::string& url) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Decoder not initialized"));
}
std::lock_guard<std::mutex> lock(mutex_);
closeSource();
currentUrl_ = url;
AVDictionary* options = nullptr;
av_dict_set(&options, "protocol_whitelist", "file,http,https,tls,tcp,udp,crypto,httpproxy,socks,socks5,socks5h", 0);
// CRITICAL: Use iOS User Agent to match the client that generated the URL.
// Mismatch between URL client (c=IOS) and User-Agent (Chrome) causes 403 Forbidden.
av_dict_set(&options, "user_agent",
"Mozilla/5.0 (Linux; Android 12; Quest 2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Mobile VR Safari/537.36", 0);
av_dict_set(&options, "timeout", "15000000", 0);
av_dict_set(&options, "reconnect", "1", 0);
av_dict_set(&options, "reconnect_streamed", "1", 0);
av_dict_set(&options, "reconnect_delay_max", "5", 0);
av_dict_set(&options, "analyzeduration", "20000000", 0);
av_dict_set(&options, "probesize", "10240000", 0);
if (proxyConfig_.has_value() && proxyConfig_->isValid()) {
std::string proxyUrl;
if (proxyConfig_->isSocks5()) {
// Use standard socks5:// scheme. FFmpeg http protocol handles this correctly.
// socks5h:// is often rejected by the http protocol handler, causing proxy bypass.
if (proxyConfig_->requiresAuth()) {
proxyUrl = std::format("socks5://{}:{}@{}:{}",
*proxyConfig_->username, *proxyConfig_->password,
proxyConfig_->host, proxyConfig_->port);
} else {
proxyUrl = std::format("socks5://{}:{}",
proxyConfig_->host, proxyConfig_->port);
}
} else {
if (proxyConfig_->requiresAuth()) {
proxyUrl = std::format("http://{}:{}@{}:{}",
*proxyConfig_->username, *proxyConfig_->password,
proxyConfig_->host, proxyConfig_->port);
} else {
proxyUrl = std::format("http://{}:{}",
proxyConfig_->host, proxyConfig_->port);
}
}
av_dict_set(&options, "proxy", proxyUrl.c_str(), 0);
ECHOION_LOG_INFO(std::format("Using proxy for ffmpeg: {}:{}", proxyConfig_->host, proxyConfig_->port));
}
ECHOION_LOG_DEBUG(std::format("Opening audio source: {}", url.substr(0, 80)));
// Allocate format context first (needed for interrupt callback)
formatContext_ = avformat_alloc_context();
if (!formatContext_) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError,
"Failed to allocate format context"));
}
// Set up interrupt callback to allow graceful shutdown during blocking I/O
shouldExit_ = false;
formatContext_->interrupt_callback.callback = [](void* ctx) -> int {
auto* decoder = static_cast<AudioDecoder*>(ctx);
return decoder->shouldExit_.load() ? 1 : 0;
};
formatContext_->interrupt_callback.opaque = this;
int ret = avformat_open_input(&formatContext_, url.c_str(), nullptr, &options);
if (options) {
av_dict_free(&options);
}
if (ret < 0) {
char errbuf[256];
av_strerror(ret, errbuf, sizeof(errbuf));
ECHOION_LOG_ERROR(std::format("FFmpeg failed to open input (error {}): {}", ret, errbuf));
return std::unexpected(Api::Error(Api::ErrorCode::AudioError,
std::format("Failed to open audio source: {} (FFmpeg error {}: {})",
url.substr(0, 80), ret, errbuf)));
}
ECHOION_LOG_DEBUG("avformat_open_input succeeded");
ret = avformat_find_stream_info(formatContext_, nullptr);
if (ret < 0) {
char errbuf[256];
av_strerror(ret, errbuf, sizeof(errbuf));
ECHOION_LOG_ERROR(std::format("FFmpeg failed to find stream info (error {}): {}", ret, errbuf));
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError,
std::format("Failed to find stream info: {}", errbuf)));
}
const AVCodec *decoder = nullptr;
audioStreamIndex_ = -1;
audioStreamIndex_ = av_find_best_stream(formatContext_, AVMEDIA_TYPE_AUDIO, -1,
-1, &decoder, 0);
if (audioStreamIndex_ == -1) {
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "No audio stream found"));
}
codecContext_ = avcodec_alloc_context3(decoder);
if (!codecContext_) {
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Failed to allocate codec context"));
}
codecContext_->thread_count = 0; // Auto-detect CPU cores
codecContext_->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE;
ret = avcodec_parameters_to_context(codecContext_,
formatContext_->streams[audioStreamIndex_]->codecpar);
if (ret < 0) {
avcodec_free_context(&codecContext_);
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Failed to copy codec parameters"));
}
ret = avcodec_open2(codecContext_, decoder, nullptr);
if (ret < 0) {
avcodec_free_context(&codecContext_);
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Failed to open codec"));
}
frame_ = av_frame_alloc();
packet_ = av_packet_alloc();
if (!frame_ || !packet_) {
cleanupFfmpeg();
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Failed to allocate frame/packet"));
}
streamInfo_.sampleRate = codecContext_->sample_rate;
streamInfo_.channels = codecContext_->ch_layout.nb_channels;
streamInfo_.bitrate = static_cast<uint32_t>(codecContext_->bit_rate);
streamInfo_.hwAccelerated = hwAccelEnabled_;
streamInfo_.hwAccelType = hwAccelType_;
if (formatContext_->duration != AV_NOPTS_VALUE) {
streamInfo_.duration = std::chrono::milliseconds(
formatContext_->duration * 1000 / AV_TIME_BASE);
}
switch (codecContext_->codec_id) {
case AV_CODEC_ID_MP3: streamInfo_.format = Api::AudioFormat::MP3; break;
case AV_CODEC_ID_AAC: streamInfo_.format = Api::AudioFormat::AAC; break;
case AV_CODEC_ID_OPUS: streamInfo_.format = Api::AudioFormat::Opus; break;
case AV_CODEC_ID_VORBIS: streamInfo_.format = Api::AudioFormat::Vorbis; break;
case AV_CODEC_ID_FLAC: streamInfo_.format = Api::AudioFormat::FLAC; break;
default: streamInfo_.format = Api::AudioFormat::Unknown; break;
}
// Setup resampler to output S16 (int16) like reference - avoids float->int conversion
AVChannelLayout outLayout;
av_channel_layout_default(&outLayout, static_cast<int>(outputChannels_));
ret = swr_alloc_set_opts2(&swrContext_,
&outLayout, AV_SAMPLE_FMT_S16, static_cast<int>(outputSampleRate_),
&codecContext_->ch_layout, codecContext_->sample_fmt, codecContext_->sample_rate,
0, nullptr);
if (codecContext_->sample_rate != outputSampleRate_) {
av_opt_set_int(swrContext_, "linear_interp", 1, 0);
av_opt_set_int(swrContext_, "filter_size", 256, 0);
}
if (ret < 0 || swr_init(swrContext_) < 0) {
cleanupFfmpeg();
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Failed to initialize resampler"));
}
// Allocate output buffer for S16 samples (like reference)
constexpr int maxSamples = 4096;
av_samples_alloc(&outputBuffer_, nullptr, static_cast<int>(outputChannels_), maxSamples,
AV_SAMPLE_FMT_S16, 0);
decoding_ = true;
shouldExit_ = false;
decodeThread_ = std::jthread(&AudioDecoder::decodeThread, this);
ECHOION_LOG_INFO(std::format("Audio source opened: {} -> {} Hz, {} ch, in={} out=S16",
url, outputSampleRate_, outputChannels_,
av_get_sample_fmt_name(codecContext_->sample_fmt)));
return {};
}
void AudioDecoder::closeSource() {
decoding_ = false;
shouldExit_ = true; // Signal FFmpeg to abort blocking I/O
cv_.notify_all();
if (decodeThread_.joinable()) {
decodeThread_.join();
}
cleanupFfmpeg();
currentUrl_.clear();
currentPosition_ = std::chrono::milliseconds(0);
eof_ = false;
shouldExit_ = false; // Reset for next use
}
Api::Result<Api::DecodedAudio> AudioDecoder::decodeFrame() {
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this] {
return !decodedQueue_.empty() || eof_ || !decoding_;
});
if (!decodedQueue_.empty()) {
auto audio = std::move(decodedQueue_.front());
decodedQueue_.pop();
cv_.notify_one();
std::lock_guard<std::mutex> statsLock(statsMutex_);
stats_.framesDecoded++;
ECHOION_LOG_DEBUG(std::format("Frame consumed: {} samples, {} ms",
audio.view.samplesPerChannel() * 2, audio.timestamp.count()));
return audio;
}
if (eof_) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "End of stream"));
}
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Decoder stopped"));
}
static int callCount = 0;
bool AudioDecoder::getNextChunk(std::vector<int16_t>& outChunk, bool blocking) {
callCount++;
std::unique_lock<std::mutex> lock(mutex_);
if (blocking) {
cv_.wait(lock, [this] { return !int16Queue_.empty() || eof_.load(); });
}
if (int16Queue_.empty()) {
return false;
}
outChunk = std::move(int16Queue_.front());
int16Queue_.pop_front();
cv_.notify_one();
if (callCount <= 10 || callCount % 1000 == 0) {
ECHOION_LOG_DEBUG(std::format("getNextChunk {}: returned {} samples, queue left: {}",
callCount, outChunk.size(), int16Queue_.size()));
}
std::lock_guard<std::mutex> statsLock(statsMutex_);
stats_.framesDecoded++;
return true;
}
Api::Result<void> AudioDecoder::seek(std::chrono::milliseconds position) {
if (!formatContext_ || audioStreamIndex_ < 0) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "No source open"));
}
std::lock_guard<std::mutex> lock(mutex_);
int64_t targetPts = position.count() * AV_TIME_BASE / 1000;
int ret = av_seek_frame(formatContext_, -1, targetPts, AVSEEK_FLAG_BACKWARD);
if (ret < 0) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Seek failed"));
}
avcodec_flush_buffers(codecContext_);
currentPosition_ = position;
std::queue<Api::DecodedAudio> empty;
std::swap(decodedQueue_, empty);
return {};
}
Api::Result<Api::AudioStreamInfo> AudioDecoder::getStreamInfo() const {
if (!initialized_ || !formatContext_) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "No source open"));
}
return streamInfo_;
}
std::chrono::milliseconds AudioDecoder::getPosition() const {
return currentPosition_;
}
bool AudioDecoder::hasMoreData() const {
std::lock_guard<std::mutex> lock(mutex_);
return !decodedQueue_.empty() || (!eof_ && decoding_);
}
void AudioDecoder::setOutputFormat(uint32_t sampleRate, uint32_t channels) {
outputSampleRate_ = sampleRate;
outputChannels_ = channels;
}
void AudioDecoder::setProxyConfig(const std::optional<Api::ProxyConfig>& proxy) {
proxyConfig_ = proxy;
}
AudioDecoder::Stats AudioDecoder::getStats() const {
std::lock_guard<std::mutex> lock(statsMutex_);
return stats_;
}
void AudioDecoder::decodeThread() {
ECHOION_LOG_DEBUG("Decode thread started");
constexpr int maxSamples = 4096;
int packetsRead = 0;
int framesProduced = 0;
while (decoding_.load()) {
// Check queue size limit
{
std::unique_lock<std::mutex> lock(mutex_);
if (int16Queue_.size() >= MAX_INT16_QUEUE_SIZE) {
cv_.wait(lock, [this] { return int16Queue_.size() < MAX_INT16_QUEUE_SIZE || !decoding_; });
if (!decoding_) break;
}
}
int ret = av_read_frame(formatContext_, packet_);
if (ret == AVERROR_EOF) {
break; // End of file - go to flush
}
if (ret < 0) {
continue; // Read error - try next packet
}
packetsRead++;
if (packet_->stream_index != audioStreamIndex_) {
av_packet_unref(packet_);
continue;
}
// Send packet to decoder - ignore errors like reference
avcodec_send_packet(codecContext_, packet_);
av_packet_unref(packet_);
// Receive all available frames
while (decoding_.load()) {
ret = avcodec_receive_frame(codecContext_, frame_);
if (ret == AVERROR(EAGAIN)) {
break; // Need more packets
}
if (ret < 0) {
break; // Error - continue to next packet
}
// Convert to S16 and queue (like reference)
int outSamples = swr_convert(swrContext_, &outputBuffer_, maxSamples,
const_cast<const uint8_t**>(frame_->data), frame_->nb_samples);
if (outSamples > 0) {
std::vector<int16_t> chunk(outSamples * outputChannels_);
std::memcpy(chunk.data(), outputBuffer_,
outSamples * outputChannels_ * sizeof(int16_t));
{
std::lock_guard<std::mutex> lock(mutex_);
int16Queue_.push_back(std::move(chunk));
}
cv_.notify_one();
framesProduced++;
if (framesProduced <= 5) {
ECHOION_LOG_DEBUG(std::format("Decode produced frame {}: {} samples",
framesProduced, chunk.size()));
}
}
}
}
// Final flush (CRITICAL - like reference)
avcodec_send_packet(codecContext_, nullptr);
while (decoding_.load()) {
int ret = avcodec_receive_frame(codecContext_, frame_);
if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN)) {
break;
}
if (ret < 0) break;
int outSamples = swr_convert(swrContext_, &outputBuffer_, 4096,
const_cast<const uint8_t**>(frame_->data), frame_->nb_samples);
if (outSamples > 0) {
std::vector<int16_t> chunk(outSamples * outputChannels_);
std::memcpy(chunk.data(), outputBuffer_,
outSamples * outputChannels_ * sizeof(int16_t));
{
std::lock_guard<std::mutex> lock(mutex_);
int16Queue_.push_back(std::move(chunk));
}
cv_.notify_one();
framesProduced++;
}
}
eof_ = true;
cv_.notify_all();
ECHOION_LOG_INFO(std::format("Decode finished. Packets: {}, Frames: {}",
packetsRead, framesProduced));
}
Api::Result<void> AudioDecoder::readPacket() {
int ret = av_read_frame(formatContext_, packet_);
if (ret < 0) {
if (ret == AVERROR_EOF) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "End of file"));
}
if (ret == AVERROR_EXIT) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Interrupted"));
}
char errbuf[256];
av_strerror(ret, errbuf, sizeof(errbuf));
return std::unexpected(Api::Error(Api::ErrorCode::AudioError,
std::format("Error reading frame: {}", errbuf)));
}
if (packet_->stream_index != audioStreamIndex_) {
av_packet_unref(packet_);
return {};
}
// Send packet to decoder - don't check error, just like reference code
// Some packets may be corrupt but we continue to next
avcodec_send_packet(codecContext_, packet_);
av_packet_unref(packet_);
// Receive all available frames from the decoder
while (true) {
ret = avcodec_receive_frame(codecContext_, frame_);
if (ret == AVERROR(EAGAIN)) {
// Need more packets to produce a frame
break;
}
if (ret < 0) {
// Error receiving frame - log but continue to next packet
// Don't treat as fatal - Opus may have bad packets that are safe to skip
break;
}
Api::Result<Api::DecodedAudio> audio;
if (zeroCopyEnabled_) {
audio = convertFramePooled();
} else {
audio = convertFrame();
}
if (audio) {
std::lock_guard<std::mutex> lock(mutex_);
decodedQueue_.push(std::move(*audio));
cv_.notify_one();
}
}
return {};
}
Api::Result<Api::DecodedAudio> AudioDecoder::convertFrame() {
int outSamples = swr_get_out_samples(swrContext_, frame_->nb_samples);
std::vector<float> outputBuffer(outSamples * outputChannels_);
uint8_t* outData = reinterpret_cast<uint8_t*>(outputBuffer.data());
const uint8_t** inData = const_cast<const uint8_t**>(frame_->extended_data);
int converted = swr_convert(swrContext_, &outData, outSamples, inData, frame_->nb_samples);
if (converted < 0) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Resampling failed"));
}
outputBuffer.resize(converted * outputChannels_);
if (frame_->pts != AV_NOPTS_VALUE) {
AVRational timeBase = formatContext_->streams[audioStreamIndex_]->time_base;
currentPosition_ = std::chrono::milliseconds(
frame_->pts * 1000 * timeBase.num / timeBase.den);
}
Api::DecodedAudio audio;
audio.view = Api::FloatAudioView(outputBuffer.data(), outputBuffer.size(), outputChannels_);
audio.sampleRate = outputSampleRate_;
audio.channels = outputChannels_;
audio.timestamp = currentPosition_;
return audio;
}
Api::Result<Api::DecodedAudio> AudioDecoder::convertFramePooled() {
int outSamples = swr_get_out_samples(swrContext_, frame_->nb_samples);
auto pooledBuffer = Api::AudioBufferPool::instance().acquireBuffer();
if (!pooledBuffer) return convertFrame();
uint8_t* outData = reinterpret_cast<uint8_t*>(pooledBuffer.get());
const uint8_t** inData = const_cast<const uint8_t**>(frame_->extended_data);
int converted = swr_convert(swrContext_, &outData, outSamples, inData, frame_->nb_samples);
if (converted < 0) return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Resampling failed"));
if (frame_->pts != AV_NOPTS_VALUE) {
AVRational timeBase = formatContext_->streams[audioStreamIndex_]->time_base;
currentPosition_ = std::chrono::milliseconds(
frame_->pts * 1000 * timeBase.num / timeBase.den);
}
Api::DecodedAudio audio;
audio.pooledSamples = std::move(pooledBuffer);
audio.view = Api::FloatAudioView(audio.pooledSamples.get(), converted * outputChannels_, outputChannels_);
audio.sampleRate = outputSampleRate_;
audio.channels = outputChannels_;
audio.timestamp = currentPosition_;
return audio;
}
void AudioDecoder::cleanupFfmpeg() {
if (swrContext_) swr_free(&swrContext_);
if (frame_) av_frame_free(&frame_);
if (packet_) av_packet_free(&packet_);
if (codecContext_) avcodec_free_context(&codecContext_);
if (formatContext_) avformat_close_input(&formatContext_);
if (outputBuffer_) av_freep(&outputBuffer_);
audioStreamIndex_ = -1;
}
} // namespace Echoion::Core
+46
View File
@@ -0,0 +1,46 @@
#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
+278
View File
@@ -0,0 +1,278 @@
#include "echoion/core/CommandManager.hpp"
#include "echoion/api/ConfigTypes.hpp"
#include "echoion/core/MusicManager.hpp"
#include "echoion/core/Logger.hpp"
#include <echoion/core/commands/Commands.hpp>
#include <algorithm>
#include <sstream>
#include <format>
namespace Echoion::Core {
// --- Internal Help Command ---
class CommandManager::HelpCommand : public Command {
CommandManager& manager_;
public:
explicit HelpCommand(CommandManager& mgr) : manager_(mgr) {}
void execute(const CommandContext& ctx) override {
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
auto visibleCommands = manager_.getVisibleCommands(ctx.clientId);
// Group commands by category
std::map<CommandCategory, std::vector<std::pair<std::string, CommandPtr>>> grouped;
for (const auto& [name, cmd] : visibleCommands) {
grouped[cmd->getCategory()].push_back({name, cmd});
}
for (const auto& [cat, cmds] : grouped) {
helpMsg += std::format("**{} Commands**\n", toString(cat));
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);
}
// Description
helpMsg += std::format("> {}\n", cmd->getDescription());
// Aliases
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";
}
helpMsg += "\n";
}
}
ctx.reply(helpMsg);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Help command exception: {}", e.what()));
ctx.reply("Couldn't generate help. Please try again.");
}
}
std::string_view getDescription() const override {
return "Shows this help message with all available commands.";
}
std::string_view getUsage() const override { return "[command]"; }
CommandCategory getCategory() const override { return CommandCategory::Utility; }
std::vector<std::string_view> getAliases() const override {
return {"h", "?", "commands"};
}
};
// --- Manager Implementation ---
CommandManager::CommandManager() {
registerBuiltinCommands();
registerHelpCommand();
}
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);
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; // Command was found but not allowed
}
CommandContext ctx{
.clientId = clientId,
.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_) {
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");
}
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
+355
View File
@@ -0,0 +1,355 @@
#include "echoion/core/ConfigLoader.hpp"
#include "echoion/api/AudioTypes.hpp"
#include <glaze/glaze.hpp>
#include <fstream>
#include <format>
namespace Echoion::Core {
// JSON structures for configuration
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;
};
struct ServerConfigJson {
std::string address;
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;
};
struct AppConfigJson {
BotConfigJson bot;
ServerConfigJson server;
SecurityConfigJson security;
};
} // namespace Echoion::Core
// Glaze metadata for JSON serialization
template<> struct glz::meta<Echoion::Core::BotConfigJson> {
using T = Echoion::Core::BotConfigJson;
static constexpr auto value = object(
"botName", &T::botName,
"commandPrefix", &T::commandPrefix,
"defaultVolume", &T::defaultVolume,
"autoReconnect", &T::autoReconnect,
"reconnectDelay", &T::reconnectDelay,
"maxReconnectAttempts", &T::maxReconnectAttempts,
"proxyHost", &T::proxyHost,
"proxyPort", &T::proxyPort,
"proxyUsername", &T::proxyUsername,
"proxyPassword", &T::proxyPassword,
"proxyType", &T::proxyType,
"youtubeApiKey", &T::youtubeApiKey,
"preferredQuality", &T::preferredQuality,
"allowPlaylistImports", &T::allowPlaylistImports,
"maxQueueSize", &T::maxQueueSize,
"trackTimeout", &T::trackTimeout,
"youtubeCookiesPath", &T::youtubeCookiesPath,
"cookiesFromBrowser", &T::cookiesFromBrowser
);
};
template<> struct glz::meta<Echoion::Core::ServerConfigJson> {
using T = Echoion::Core::ServerConfigJson;
static constexpr auto value = object(
"address", &T::address,
"port", &T::port,
"serverPassword", &T::serverPassword,
"nickname", &T::nickname,
"defaultChannelId", &T::defaultChannelId,
"channelPassword", &T::channelPassword,
"adminGroups", &T::adminGroups,
"djGroups", &T::djGroups,
"bannedGroups", &T::bannedGroups
);
};
template<> struct glz::meta<Echoion::Core::SecurityConfigJson> {
using T = Echoion::Core::SecurityConfigJson;
static constexpr auto value = object(
"requireAuthForAdmin", &T::requireAuthForAdmin,
"maxLoginAttempts", &T::maxLoginAttempts,
"lockoutDuration", &T::lockoutDuration,
"sessionTimeout", &T::sessionTimeout,
"enableAuditLog", &T::enableAuditLog
);
};
template<> struct glz::meta<Echoion::Core::AppConfigJson> {
using T = Echoion::Core::AppConfigJson;
static constexpr auto value = object(
"bot", &T::bot,
"server", &T::server,
"security", &T::security
);
};
namespace Echoion::Core {
Api::Result<Api::AppConfig> ConfigLoader::loadFromFile(const std::filesystem::path& path) {
if (!std::filesystem::exists(path)) {
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
std::format("Configuration file not found: {}", path.string())));
}
std::ifstream file(path);
if (!file.is_open()) {
return std::unexpected(Api::Error(Api::ErrorCode::PermissionDenied,
std::format("Failed to open configuration file: {}", path.string())));
}
std::string content((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
file.close();
AppConfigJson jsonConfig;
auto ec = glz::read_json(jsonConfig, content);
if (ec) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
std::format("Failed to parse configuration: {}", glz::format_error(ec, content))));
}
// Convert to API config
Api::AppConfig config;
// Bot config
config.bot.botName = jsonConfig.bot.botName;
config.bot.commandPrefix = jsonConfig.bot.commandPrefix;
config.bot.defaultVolume = jsonConfig.bot.defaultVolume;
config.bot.autoReconnect = jsonConfig.bot.autoReconnect;
config.bot.reconnectDelay = std::chrono::milliseconds(jsonConfig.bot.reconnectDelay);
config.bot.maxReconnectAttempts = jsonConfig.bot.maxReconnectAttempts;
config.bot.preferredQuality = parseQuality(jsonConfig.bot.preferredQuality);
config.bot.allowPlaylistImports = jsonConfig.bot.allowPlaylistImports;
config.bot.maxQueueSize = jsonConfig.bot.maxQueueSize;
config.bot.trackTimeout = std::chrono::milliseconds(jsonConfig.bot.trackTimeout);
// Proxy config
if (jsonConfig.bot.proxyHost.has_value() && jsonConfig.bot.proxyPort.has_value()) {
Api::ProxyConfig proxy;
proxy.host = *jsonConfig.bot.proxyHost;
proxy.port = *jsonConfig.bot.proxyPort;
proxy.username = jsonConfig.bot.proxyUsername;
proxy.password = jsonConfig.bot.proxyPassword;
// Parse proxy type (default to HTTP)
if (jsonConfig.bot.proxyType.has_value()) {
const auto& typeStr = *jsonConfig.bot.proxyType;
if (typeStr == "SOCKS5" || typeStr == "socks5") {
proxy.type = Api::ProxyType::SOCKS5;
} else {
proxy.type = Api::ProxyType::HTTP;
}
} else {
proxy.type = Api::ProxyType::HTTP;
}
config.bot.proxy = proxy;
}
// YouTube API key
if (jsonConfig.bot.youtubeApiKey.has_value()) {
config.bot.youtubeApiKey = jsonConfig.bot.youtubeApiKey;
}
// YouTube cookies
if (jsonConfig.bot.youtubeCookiesPath.has_value()) {
config.bot.youtubeCookiesPath = jsonConfig.bot.youtubeCookiesPath;
}
if (jsonConfig.bot.cookiesFromBrowser.has_value()) {
config.bot.cookiesFromBrowser = jsonConfig.bot.cookiesFromBrowser;
}
// Server config
config.server.address = jsonConfig.server.address;
config.server.port = jsonConfig.server.port;
config.server.serverPassword = jsonConfig.server.serverPassword;
config.server.nickname = jsonConfig.server.nickname;
config.server.defaultChannelId = jsonConfig.server.defaultChannelId;
config.server.channelPassword = jsonConfig.server.channelPassword;
config.server.adminGroups = jsonConfig.server.adminGroups;
config.server.djGroups = jsonConfig.server.djGroups;
config.server.bannedGroups = jsonConfig.server.bannedGroups;
// Security config
config.security.requireAuthForAdmin = jsonConfig.security.requireAuthForAdmin;
config.security.maxLoginAttempts = jsonConfig.security.maxLoginAttempts;
config.security.lockoutDuration = std::chrono::milliseconds(jsonConfig.security.lockoutDuration);
config.security.sessionTimeout = std::chrono::milliseconds(jsonConfig.security.sessionTimeout);
config.security.enableAuditLog = jsonConfig.security.enableAuditLog;
ECHOION_LOG_INFO(std::format("Configuration loaded from {}", path.string()));
return config;
}
Api::Result<void> ConfigLoader::saveToFile(const std::filesystem::path& path, const Api::AppConfig& config) {
AppConfigJson jsonConfig;
// Bot config
jsonConfig.bot.botName = config.bot.botName;
jsonConfig.bot.commandPrefix = config.bot.commandPrefix;
jsonConfig.bot.defaultVolume = config.bot.defaultVolume;
jsonConfig.bot.autoReconnect = config.bot.autoReconnect;
jsonConfig.bot.reconnectDelay = static_cast<uint32_t>(config.bot.reconnectDelay.count());
jsonConfig.bot.maxReconnectAttempts = config.bot.maxReconnectAttempts;
jsonConfig.bot.preferredQuality = qualityToString(config.bot.preferredQuality);
jsonConfig.bot.allowPlaylistImports = config.bot.allowPlaylistImports;
jsonConfig.bot.maxQueueSize = config.bot.maxQueueSize;
jsonConfig.bot.trackTimeout = static_cast<uint32_t>(config.bot.trackTimeout.count());
// Proxy config
if (config.bot.proxy.has_value()) {
jsonConfig.bot.proxyHost = config.bot.proxy->host;
jsonConfig.bot.proxyPort = config.bot.proxy->port;
jsonConfig.bot.proxyUsername = config.bot.proxy->username;
jsonConfig.bot.proxyPassword = config.bot.proxy->password;
jsonConfig.bot.proxyType = config.bot.proxy->type == Api::ProxyType::SOCKS5 ? "SOCKS5" : "HTTP";
}
// YouTube API key
if (config.bot.youtubeApiKey.has_value()) {
jsonConfig.bot.youtubeApiKey = *config.bot.youtubeApiKey;
}
// YouTube cookies
if (config.bot.youtubeCookiesPath.has_value()) {
jsonConfig.bot.youtubeCookiesPath = *config.bot.youtubeCookiesPath;
}
if (config.bot.cookiesFromBrowser.has_value()) {
jsonConfig.bot.cookiesFromBrowser = *config.bot.cookiesFromBrowser;
}
// Server config
jsonConfig.server.address = config.server.address;
jsonConfig.server.port = config.server.port;
jsonConfig.server.serverPassword = config.server.serverPassword;
jsonConfig.server.nickname = config.server.nickname;
jsonConfig.server.defaultChannelId = config.server.defaultChannelId;
jsonConfig.server.channelPassword = config.server.channelPassword;
jsonConfig.server.adminGroups = config.server.adminGroups;
jsonConfig.server.djGroups = config.server.djGroups;
jsonConfig.server.bannedGroups = config.server.bannedGroups;
// Security config
jsonConfig.security.requireAuthForAdmin = config.security.requireAuthForAdmin;
jsonConfig.security.maxLoginAttempts = config.security.maxLoginAttempts;
jsonConfig.security.lockoutDuration = static_cast<uint32_t>(config.security.lockoutDuration.count());
jsonConfig.security.sessionTimeout = static_cast<uint32_t>(config.security.sessionTimeout.count());
jsonConfig.security.enableAuditLog = config.security.enableAuditLog;
auto json = glz::write_json(jsonConfig);
if (!json.has_value())
{
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
std::format("Failed to serialize: {}", json.error().custom_error_message)));
}
std::ofstream file(path);
if (!file.is_open()) {
return std::unexpected(Api::Error(Api::ErrorCode::PermissionDenied,
std::format("Failed to write configuration file: {}", path.string())));
}
file << json.value();
file.close();
ECHOION_LOG_INFO(std::format("Configuration saved to {}", path.string()));
return {};
}
std::filesystem::path ConfigLoader::getDefaultConfigPath() {
// Try to get config path from environment or use default
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";
}
// Fallback to current directory
return "echoion_config.json";
}
Api::AppConfig ConfigLoader::createDefaultConfig() {
Api::AppConfig config;
// Default bot config
config.bot.botName = "Echoion";
config.bot.commandPrefix = "!";
config.bot.defaultVolume = 0.5f;
config.bot.autoReconnect = true;
config.bot.reconnectDelay = std::chrono::milliseconds(5000);
config.bot.maxReconnectAttempts = 5;
config.bot.preferredQuality = Api::AudioQuality::High;
config.bot.allowPlaylistImports = true;
config.bot.maxQueueSize = 100;
config.bot.trackTimeout = std::chrono::milliseconds(30000);
// Default server config
config.server.address = "localhost";
config.server.port = 9987;
config.server.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;
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
+902
View File
@@ -0,0 +1,902 @@
#include "echoion/core/Core.hpp"
#include "echoion/core/Logger.hpp"
#include <echoion/api/Database.hpp>
#include <format>
#include <algorithm>
namespace Echoion::Core {
Core::Core() = default;
Core::~Core() {
if (initialized_) {
shutdown();
}
}
Api::Result<void> Core::initialize(const std::filesystem::path& configPath) {
if (initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, "Core already initialized"));
}
// Store config path for later reload
configPath_ = configPath;
// Load config from file (Core-internal, Plugin doesn't need to know about AppConfig structure)
auto configResult = ConfigLoader::loadFromFile(configPath);
if (!configResult) {
// Try to create default config
ECHOION_LOG_WARNING(std::format("Failed to load config: {}, creating default", configResult.error().message));
config_ = ConfigLoader::createDefaultConfig();
ConfigLoader::saveToFile(configPath, config_);
} else {
config_ = *configResult;
}
ECHOION_LOG_INFO(std::format("Core loaded config - Server: {}:{}, Nickname: {}",
config_.server.address, config_.server.port, config_.server.nickname));
// Initialize logger
auto logger = std::make_shared<Logger>();
logger->setMinLevel(Api::LogLevel::Debug);
Api::LoggerRegistry::instance().setLogger(logger);
ECHOION_LOG_INFO("Initializing Echoion Core...");
// Initialize network client
networkClient_ = std::make_shared<NetworkClient>();
auto netResult = networkClient_->initialize(config_.bot.proxy);
if (!netResult) {
return std::unexpected(netResult.error());
}
// Initialize database
database_ = std::make_shared<Api::Database>();
auto dbResult = database_->initialize();
if (!dbResult) {
ECHOION_LOG_WARNING(std::format("Failed to initialize database: {}",
dbResult.error().message));
// Not fatal - continue without database
database_ = nullptr;
} else {
ECHOION_LOG_INFO("Database initialized successfully");
}
// Initialize music manager
musicManager_ = std::make_shared<MusicManager>();
auto musicResult = musicManager_->initialize(config_.bot, networkClient_, database_);
if (!musicResult) {
return std::unexpected(musicResult.error());
}
// Initialize command manager
commandManager_ = std::make_unique<CommandManager>();
commandManager_->setPrefix(config_.bot.commandPrefix);
commandManager_->setServerConfig(config_);
// Set up permission check function
commandManager_->setPermissionCheckFunc([this](uint64_t clientId, CommandCategory category) -> bool {
// Check if client is in admin groups
if (!pluginInterface_) return false;
// Get client info from plugin
auto clientInfo = pluginInterface_->getClient(clientId);
if (!clientInfo || !clientInfo->has_value()) {
return false;
}
// Admin category requires admin group membership
if (category == CommandCategory::Admin) {
// Check if any admin groups are configured
if (config_.server.adminGroups.empty()) {
return false; // No admin groups configured = no admin access
}
// Check if client is in any admin group
// This would need to be implemented with proper group checking
// For now, we'll rely on the TS3 plugin to provide this info
// through a future interface
return false; // Default deny until proper group check is implemented
}
return true; // Non-admin categories are allowed
});
// Set up audio data callback
// Receives float audio from MusicManager (-1.0 to 1.0), converts to bytes for plugin
musicManager_->setAudioDataCallback([this](const std::span<const float> data) {
static int callCount = 0;
static auto lastLog = std::chrono::steady_clock::now();
if (pluginInterface_ && !data.empty()) {
// Convert float (-1.0 to 1.0) to int16 for TeamSpeak
// Use 32768.0f scaling but ensure we don't overflow
std::vector<int16_t> int16Data(data.size());
for (size_t i = 0; i < data.size(); ++i) {
float sample = data[i];
// Soft clipping to prevent hard distortion
if (sample > 0.95f) sample = 0.95f + (sample - 0.95f) * 0.5f;
if (sample < -0.95f) sample = -0.95f + (sample + 0.95f) * 0.5f;
int16Data[i] = static_cast<int16_t>(sample * 32767.0f);
}
// Send to plugin
auto result = pluginInterface_->sendAudioData(std::span<const uint8_t>(
reinterpret_cast<const uint8_t*>(int16Data.data()),
int16Data.size() * sizeof(int16_t)));
callCount++;
auto now = std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::seconds>(now - lastLog).count() >= 5) {
ECHOION_LOG_DEBUG(std::format("Audio callback: {} calls, {} samples, result: {}",
callCount, data.size(), result.has_value() ? "ok" : "error"));
lastLog = now;
}
}
});
// Set up subscription change callback to update whisper list
musicManager_->setSubscriptionChangeCallback([this]() {
updateWhisperList();
});
// Set initial whisper list from loaded subscriptions
updateWhisperList();
// Start RPC server for Desktop/API clients
rpcServer_ = std::make_shared<RpcServer>();
uint16_t rpcPort = config_.bot.rpcPort > 0 ? config_.bot.rpcPort : 8765;
auto rpcResult = rpcServer_->start(rpcPort);
if (!rpcResult) {
ECHOION_LOG_WARNING(std::format("Failed to start RPC server: {}",
rpcResult.error().message));
// Not fatal - continue without RPC
rpcServer_.reset();
} else {
ECHOION_LOG_INFO(std::format("RPC server started on port {}", rpcPort));
setupRpcHandlers();
}
startTime_ = std::chrono::system_clock::now();
initialized_ = true;
ECHOION_LOG_INFO("Echoion Core initialized successfully");
// Auto-connect to server if configured
if (!config_.server.address.empty() && pluginInterface_) {
ECHOION_LOG_INFO(std::format("Auto-connecting to {}:{}...",
config_.server.address, config_.server.port));
auto connectResult = pluginInterface_->connectToServer(config_.server);
if (!connectResult) {
ECHOION_LOG_ERROR(std::format("Auto-connect failed: {}",
connectResult.error().message));
} else {
ECHOION_LOG_INFO("Auto-connect initiated");
}
}
return {};
}
Api::Result<void> Core::shutdown() {
if (!initialized_) {
return {};
}
ECHOION_LOG_INFO("Shutting down Echoion Core...");
if (musicManager_) {
musicManager_->shutdown();
}
if (networkClient_) {
networkClient_->shutdown();
}
if (rpcServer_) {
rpcServer_->stop();
rpcServer_.reset();
}
if (database_) {
database_->shutdown();
database_.reset();
}
// Clear callbacks
{
std::lock_guard<std::mutex> lock(eventMutex_);
eventCallbacks_.clear();
}
initialized_ = false;
ECHOION_LOG_INFO("Echoion Core shutdown complete");
return {};
}
bool Core::isInitialized() const noexcept {
return initialized_.load();
}
Api::Result<void> Core::play(const Api::TrackInfo& track) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
auto result = musicManager_->queueTrack(track, 0);
if (!result) {
return std::unexpected(result.error());
}
// If not playing, start playback
auto state = musicManager_->getPlaybackState();
if (state && !state->isPlaying) {
auto playResult = musicManager_->skip(0); // Start first track
if (!playResult) {
return std::unexpected(playResult.error());
}
}
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::PlayRequested,
.clientId = 0,
.trackInfo = track,
.timestamp = std::chrono::system_clock::now()
});
return {};
}
Api::Result<void> Core::pause() {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
auto result = musicManager_->pause();
if (result) {
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::PlaybackPaused,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()
});
}
return result;
}
Api::Result<void> Core::resume() {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
auto result = musicManager_->resume();
if (result) {
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::PlaybackStarted,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()
});
}
return result;
}
Api::Result<void> Core::stop() {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
auto result = musicManager_->stop();
if (result) {
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::PlaybackStopped,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()
});
}
return result;
}
Api::Result<void> Core::skip(uint32_t count) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
auto result = musicManager_->skip(count);
if (result) {
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::SkipRequested,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()
});
}
return result;
}
Api::Result<void> Core::seek(std::chrono::milliseconds position) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
return musicManager_->seek(position);
}
Api::Result<void> Core::setVolume(float volume) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
return musicManager_->setVolume(volume);
}
Api::Result<uint64_t> Core::queueTrack(const Api::TrackInfo& track, uint64_t clientId) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
auto result = musicManager_->queueTrack(track, clientId);
if (result) {
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::TrackQueued,
.clientId = clientId,
.trackInfo = track,
.timestamp = std::chrono::system_clock::now()
});
}
return result;
}
Api::Result<void> Core::removeFromQueue(uint64_t queueId) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
// Find position by queueId
auto queue = musicManager_->getQueue();
if (!queue) {
return std::unexpected(queue.error());
}
for (size_t i = 0; i < queue->size(); ++i) {
if ((*queue)[i].queueId == queueId) {
return musicManager_->removeFromQueue(static_cast<uint32_t>(i));
}
}
return std::unexpected(Api::Error(Api::ErrorCode::NotFound, "Track not found in queue"));
}
Api::Result<void> Core::clearQueue() {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
auto result = musicManager_->clearQueue();
if (result) {
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::QueueCleared,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()
});
}
return result;
}
Api::Result<std::vector<Api::QueueEntry>> Core::getQueue() const {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
return musicManager_->getQueue();
}
Api::Result<void> Core::moveInQueue(uint64_t queueId, uint32_t newPosition) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
// Find current position
auto queue = musicManager_->getQueue();
if (!queue) {
return std::unexpected(queue.error());
}
uint32_t fromPosition = 0;
bool found = false;
for (size_t i = 0; i < queue->size(); ++i) {
if ((*queue)[i].queueId == queueId) {
fromPosition = static_cast<uint32_t>(i);
found = true;
break;
}
}
if (!found) {
return std::unexpected(Api::Error(Api::ErrorCode::NotFound, "Track not found in queue"));
}
return musicManager_->moveInQueue(fromPosition, newPosition);
}
Api::Result<std::optional<Api::QueueEntry>> Core::getCurrentTrack() const {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
return musicManager_->getCurrentTrack();
}
Api::Result<Api::PlaybackState> Core::getPlaybackState() const {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
return musicManager_->getPlaybackState();
}
Api::Result<void> Core::loadPlaylist(const std::string& playlistId, uint64_t clientId) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
auto result = musicManager_->loadPlaylist(playlistId, clientId);
if (!result) {
return std::unexpected(result.error());
}
return {};
}
Api::Result<std::vector<Api::PlaylistInfo>> Core::getPlaylists() const {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
return musicManager_->getPlaylists();
}
Api::Result<void> Core::updateConfig(const Api::AppConfig& config) {
// Update local config copy
config_ = config;
if (commandManager_) {
commandManager_->setPrefix(config.bot.commandPrefix);
commandManager_->setServerConfig(config);
}
// Update network proxy if changed
if (networkClient_ && config.bot.proxy != networkClient_->getProxy()) {
networkClient_->setProxy(config.bot.proxy);
}
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::ConfigurationChanged,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()
});
return {};
}
Api::Result<Api::AppConfig> Core::getConfig() const {
return config_;
}
Api::Result<void> Core::reloadConfig() {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
if (configPath_.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, "Config path not set"));
}
// Reload config from disk
auto configResult = ConfigLoader::loadFromFile(configPath_);
if (!configResult) {
return std::unexpected(configResult.error());
}
// Update local config
config_ = *configResult;
// Update components with new config
if (commandManager_) {
commandManager_->setPrefix(config_.bot.commandPrefix);
commandManager_->setServerConfig(config_);
}
ECHOION_LOG_INFO("Configuration reloaded from disk");
return {};
}
Api::Result<Api::HotReloadState> Core::prepareForHotReload() {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
ECHOION_LOG_INFO("Preparing for hot reload...");
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::HotReloadRequested,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()
});
return musicManager_->getStateForHotReload();
}
Api::Result<void> Core::restoreAfterHotReload(const Api::HotReloadState& state) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
ECHOION_LOG_INFO("Restoring after hot reload...");
auto result = musicManager_->restoreFromHotReload(state);
if (!result) {
return result;
}
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::HotReloadCompleted,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()
});
ECHOION_LOG_INFO("Hot reload restore complete");
return {};
}
void Core::registerEventCallback(const Api::EventCallback& callback) {
std::lock_guard<std::mutex> lock(eventMutex_);
eventCallbacks_.push_back(callback);
}
void Core::unregisterEventCallback(const Api::EventCallback& callback) {
std::lock_guard<std::mutex> lock(eventMutex_);
std::erase_if(eventCallbacks_, [&callback](const auto& cb) {
return cb.target_type() == callback.target_type();
});
}
Api::Result<void> Core::onPluginEvent(const Api::PluginEvent& event) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
switch (event.type) {
case Api::PluginEventType::TextMessageReceived:
if (event.message) {
// Check if it's a command
if (event.message->starts_with(config_.bot.commandPrefix)) {
// Create reply callback
auto replyFunc = [this](uint64_t clientId, std::string_view message) {
if (pluginInterface_) {
pluginInterface_->sendTextMessage(clientId, std::string(message));
}
};
bool handled = commandManager_->dispatch(
event.clientId,
*event.message,
musicManager_,
[replyFunc, clientId = event.clientId](std::string_view msg) {
replyFunc(clientId, msg);
},
event.clientName.value_or("")
);
if (!handled) {
if (pluginInterface_) {
pluginInterface_->sendTextMessage(event.clientId,
std::format("Unknown command. Type {}help for available commands.", config_.bot.commandPrefix));
}
}
}
}
break;
case Api::PluginEventType::ClientConnected:
ECHOION_LOG_INFO(std::format("Client {} connected", event.clientId));
break;
case Api::PluginEventType::ClientDisconnected:
ECHOION_LOG_INFO(std::format("Client {} disconnected", event.clientId));
if (musicManager_) {
musicManager_->onClientDisconnected(event.clientId);
}
// Update whisper list after client disconnect
updateWhisperList();
break;
default:
// Forward other events to subscribers
broadcastEvent(event);
break;
}
return {};
}
std::string Core::getVersion() const {
return Api::VERSION_STRING;
}
std::chrono::system_clock::time_point Core::getUptime() const {
return startTime_;
}
void Core::setPluginInterface(Api::PluginInterfacePtr pluginInterface) {
pluginInterface_ = std::move(pluginInterface);
}
void Core::triggerAutoConnect() {
if (!initialized_) {
ECHOION_LOG_WARNING("Cannot auto-connect: Core not initialized");
return;
}
if (!pluginInterface_) {
ECHOION_LOG_WARNING("Cannot auto-connect: Plugin interface not set");
return;
}
if (config_.server.address.empty()) {
ECHOION_LOG_INFO("Auto-connect skipped: No server address configured");
return;
}
ECHOION_LOG_INFO(std::format("Auto-connecting to {}:{}...",
config_.server.address, config_.server.port));
auto connectResult = pluginInterface_->connectToServer(config_.server);
if (!connectResult) {
ECHOION_LOG_ERROR(std::format("Auto-connect failed: {}",
connectResult.error().message));
} else {
ECHOION_LOG_INFO("Auto-connect initiated");
}
}
void Core::setAudioDataCallback(const MusicManager::AudioDataCallback& callback) {
if (musicManager_) {
musicManager_->setAudioDataCallback(callback);
}
}
void Core::broadcastEvent(const Api::PluginEvent& event) {
// Send to plugin event callbacks
{
std::lock_guard<std::mutex> lock(eventMutex_);
for (const auto& callback : eventCallbacks_) {
try {
callback(event);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Event callback error: {}", e.what()));
}
}
}
// Broadcast to WebSocket/RPC clients
if (rpcServer_) {
std::string eventName;
switch (event.type) {
case Api::PluginEventType::PlaybackStarted:
eventName = "playback.started";
break;
case Api::PluginEventType::PlaybackPaused:
eventName = "playback.paused";
break;
case Api::PluginEventType::PlaybackResumed:
eventName = "playback.resumed";
break;
case Api::PluginEventType::PlaybackStopped:
eventName = "playback.stopped";
break;
case Api::PluginEventType::TrackFinished:
eventName = "playback.trackFinished";
break;
case Api::PluginEventType::TrackSkipped:
eventName = "playback.trackSkipped";
break;
case Api::PluginEventType::QueueUpdated:
eventName = "queue.updated";
break;
case Api::PluginEventType::VolumeChanged:
eventName = "playback.volumeChanged";
break;
case Api::PluginEventType::TrackQueued:
eventName = "queue.trackAdded";
break;
case Api::PluginEventType::TrackRemoved:
eventName = "queue.trackRemoved";
break;
case Api::PluginEventType::SeekPosition:
eventName = "playback.seeked";
break;
case Api::PluginEventType::HotReloadRequested:
eventName = "system.hotReloadRequested";
break;
case Api::PluginEventType::HotReloadCompleted:
eventName = "system.hotReloadCompleted";
break;
default:
eventName = "unknown";
break;
}
// Serialize event data to JSON with proper escaping
std::string eventData = "{}";
if (event.trackInfo) {
eventData = std::format("{{\"id\":\"{}\",\"title\":\"{}\",\"artist\":\"{}\",\"album\":\"{}\"}}",
event.trackInfo->id,
event.trackInfo->title,
event.trackInfo->artist,
event.trackInfo->album);
}
if (event.volume.has_value()) {
eventData = std::format("{{\"volume\":{:.2f}}}", *event.volume);
}
if (event.queuePosition.has_value()) {
eventData = std::format("{{\"position\":{}}}", *event.queuePosition);
}
if (event.clientId > 0) {
eventData = std::format("{{\"clientId\":{}}}", event.clientId);
}
rpcServer_->broadcastEvent(eventName, eventData);
}
}
bool Core::isAdmin(uint64_t clientId) const {
std::lock_guard<std::mutex> lock(adminMutex_);
return std::find(adminClients_.begin(), adminClients_.end(), clientId) != adminClients_.end();
}
void Core::updateWhisperList() {
if (!pluginInterface_ || !musicManager_) {
return;
}
auto subscribers = musicManager_->getSubscribedClients();
std::vector<uint64_t> subscriberVec(subscribers.begin(), subscribers.end());
ECHOION_LOG_DEBUG(std::format("Updating whisper list with {} subscribers", subscriberVec.size()));
auto result = pluginInterface_->setWhisperList(subscriberVec);
if (!result) {
ECHOION_LOG_WARNING(std::format("Failed to update whisper list: {}", result.error().message));
}
}
void Core::setupRpcHandlers() {
if (!rpcServer_) return;
// Helper to serialize track info
auto serializeTrack = [](const Api::TrackInfo& track) -> std::string {
std::string json = "{";
json += std::format("\"id\":\"{}\",", track.id);
json += std::format("\"title\":\"{}\",", track.title);
json += std::format("\"artist\":\"{}\",", track.artist);
json += std::format("\"album\":\"{}\",", track.album);
if (track.duration.has_value()) {
json += std::format("\"duration\":{},", track.duration->count());
}
json += std::format("\"source\":{}", static_cast<int>(track.source));
json += "}";
return json;
};
// Authentication
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::Authenticate)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
rpcServer_->addAuthenticatedClient(clientId);
return std::string("{\"success\":true,\"token\":\"authenticated\"}");
});
// Playback control
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::Play)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
// Parse query from params (simple implementation)
std::string query = params;
// Remove quotes if present
if (query.size() >= 2 && query.front() == '"' && query.back() == '"') {
query = query.substr(1, query.size() - 2);
}
auto result = musicManager_->play(query, clientId);
if (!result) return std::unexpected(result.error());
return std::format("{{\"success\":true,\"message\":\"{}\"}}", *result);
});
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::Pause)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
auto result = pause();
if (!result) return std::unexpected(result.error());
return std::string("{\"success\":true}");
});
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::Resume)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
auto result = resume();
if (!result) return std::unexpected(result.error());
return std::string("{\"success\":true}");
});
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::Stop)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
auto result = stop();
if (!result) return std::unexpected(result.error());
return std::string("{\"success\":true}");
});
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::Skip)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
auto result = skip(1);
if (!result) return std::unexpected(result.error());
return std::string("{\"success\":true}");
});
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::SetVolume)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
// Parse volume from params - expect {"volume":0.5}
float volume = 0.5f;
if (params.find("volume") != std::string::npos) {
size_t pos = params.find(':');
if (pos != std::string::npos) {
volume = std::stof(params.substr(pos + 1));
}
}
auto result = setVolume(volume);
if (!result) return std::unexpected(result.error());
return std::format("{{\"success\":true,\"volume\":{}}}", volume);
});
// Queue management
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::GetQueue)),
[this, serializeTrack](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
auto queue = getQueue();
if (!queue) return std::unexpected(queue.error());
std::string json = "{\"queue\":[";
for (size_t i = 0; i < queue->size(); ++i) {
if (i > 0) json += ",";
json += "{";
json += std::format("\"queueId\":{},", (*queue)[i].queueId);
json += std::format("\"track\":{},", serializeTrack((*queue)[i].track));
json += std::format("\"isPlaying\":{}", (*queue)[i].isPlaying ? "true" : "false");
json += "}";
}
json += "]}";
return json;
});
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::GetCurrentTrack)),
[this, serializeTrack](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
auto track = getCurrentTrack();
if (!track) return std::unexpected(track.error());
if (!track->has_value()) {
return std::string("{\"track\":null}");
}
return std::format("{{\"track\":{}}}", serializeTrack(track->value().track));
});
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::GetStatus)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
auto state = getPlaybackState();
if (!state) return std::unexpected(state.error());
std::string json = "{";
json += std::format("\"isPlaying\":{},", state->isPlaying ? "true" : "false");
json += std::format("\"isPaused\":{},", state->isPaused ? "true" : "false");
json += std::format("\"volume\":{},", state->volume);
json += std::format("\"repeat\":{},", state->repeat ? "true" : "false");
json += std::format("\"shuffle\":{}", state->shuffle ? "true" : "false");
json += "}";
return json;
});
ECHOION_LOG_INFO("RPC handlers registered");
}
} // namespace Echoion::Core
+714
View File
@@ -0,0 +1,714 @@
#include "echoion/api/Database.hpp"
#include "echoion/core/Logger.hpp"
#include <sqlite3.h>
#include <format>
#include <cstring>
namespace Echoion::Api {
// Internal implementation
class DatabaseImpl {
public:
sqlite3* db = nullptr;
DatabaseConfig config;
bool initialized = false;
int version = 0;
};
Database::Database() : impl_(std::make_unique<DatabaseImpl>()) {}
Database::~Database() {
shutdown();
}
Result<void> Database::initialize(const DatabaseConfig& config) {
impl_->config = config;
int rc = sqlite3_open(config.path.c_str(), &impl_->db);
if (rc != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
std::format("Failed to open database: {}", sqlite3_errmsg(impl_->db))));
}
// Enable WAL mode
if (config.walMode) {
char* errMsg = nullptr;
sqlite3_exec(impl_->db, "PRAGMA journal_mode=WAL;", nullptr, nullptr, &errMsg);
if (errMsg) sqlite3_free(errMsg);
}
// Set busy timeout
sqlite3_busy_timeout(impl_->db,
static_cast<int>(config.busyTimeout.count()));
// Run migrations
auto result = migrate();
if (!result) {
return result;
}
impl_->initialized = true;
ECHOION_LOG_INFO(std::format("Database initialized: {}", config.path));
return {};
}
void Database::shutdown() {
if (impl_->db) {
sqlite3_close(impl_->db);
impl_->db = nullptr;
}
impl_->initialized = false;
}
bool Database::isInitialized() const {
return impl_->initialized;
}
Result<void> Database::migrate() {
// Create migrations table
const char* createMigrationsTable = R"(
CREATE TABLE IF NOT EXISTS schema_migrations (
version INTEGER PRIMARY KEY,
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
)";
char* errMsg = nullptr;
sqlite3_exec(impl_->db, createMigrationsTable, nullptr, nullptr, &errMsg);
if (errMsg) {
std::string error = errMsg;
sqlite3_free(errMsg);
return std::unexpected(Error(ErrorCode::DatabaseError, error));
}
// Get current version
sqlite3_stmt* stmt;
int currentVersion = 0;
if (sqlite3_prepare_v2(impl_->db,
"SELECT MAX(version) FROM schema_migrations", -1, &stmt, nullptr) == SQLITE_OK) {
if (sqlite3_step(stmt) == SQLITE_ROW) {
currentVersion = sqlite3_column_int(stmt, 0);
}
sqlite3_finalize(stmt);
}
// Migration 1: Initial schema
if (currentVersion < 1) {
const char* migration1 = R"(
CREATE TABLE IF NOT EXISTS playlists (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT,
created_by INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_public INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS playlist_tracks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
playlist_id INTEGER NOT NULL,
track_url TEXT NOT NULL,
track_title TEXT NOT NULL,
track_artist TEXT,
track_thumbnail TEXT,
position INTEGER NOT NULL,
added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS playback_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
track_url TEXT NOT NULL,
track_title TEXT NOT NULL,
track_artist TEXT,
played_by INTEGER NOT NULL,
played_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
duration_ms INTEGER DEFAULT 0,
completed INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS user_favorites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
track_url TEXT NOT NULL,
track_title TEXT NOT NULL,
track_artist TEXT,
added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, track_url)
);
CREATE TABLE IF NOT EXISTS subscriptions (
client_id INTEGER PRIMARY KEY,
subscribed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_history_user ON playback_history(played_by);
CREATE INDEX IF NOT EXISTS idx_history_date ON playback_history(played_at);
CREATE INDEX IF NOT EXISTS idx_favorites_user ON user_favorites(user_id);
CREATE INDEX IF NOT EXISTS idx_playlist_tracks ON playlist_tracks(playlist_id);
CREATE TABLE IF NOT EXISTS subscriptions (
client_id INTEGER PRIMARY KEY,
subscribed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_subscriptions_client ON subscriptions(client_id);
)";
sqlite3_exec(impl_->db, migration1, nullptr, nullptr, &errMsg);
if (errMsg) {
std::string error = errMsg;
sqlite3_free(errMsg);
return std::unexpected(Error(ErrorCode::DatabaseError, error));
}
// Record migration
sqlite3_exec(impl_->db,
"INSERT INTO schema_migrations (version) VALUES (1)",
nullptr, nullptr, nullptr);
ECHOION_LOG_INFO("Database migration 1 applied");
}
impl_->version = 1;
return {};
}
int Database::getCurrentVersion() const {
return impl_->version;
}
// Playlist operations
Result<uint64_t> Database::createPlaylist(const std::string& name,
const std::string& description, uint64_t createdBy, bool isPublic) {
const char* sql = R"(
INSERT INTO playlists (name, description, created_by, is_public)
VALUES (?, ?, ?, ?);
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_text(stmt, 1, name.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, description.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_int64(stmt, 3, static_cast<sqlite3_int64>(createdBy));
sqlite3_bind_int(stmt, 4, isPublic ? 1 : 0);
if (sqlite3_step(stmt) != SQLITE_DONE) {
sqlite3_finalize(stmt);
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
uint64_t id = static_cast<uint64_t>(sqlite3_last_insert_rowid(impl_->db));
sqlite3_finalize(stmt);
return id;
}
Result<std::optional<Playlist>> Database::getPlaylist(uint64_t id) {
const char* sql = R"(
SELECT id, name, description, created_by, created_at, updated_at, is_public
FROM playlists WHERE id = ?;
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(id));
Playlist playlist;
bool found = false;
if (sqlite3_step(stmt) == SQLITE_ROW) {
found = true;
playlist.id = static_cast<uint64_t>(sqlite3_column_int64(stmt, 0));
playlist.name = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
playlist.description = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2));
playlist.createdBy = static_cast<uint64_t>(sqlite3_column_int64(stmt, 3));
playlist.isPublic = sqlite3_column_int(stmt, 6) != 0;
}
sqlite3_finalize(stmt);
if (!found) {
return std::optional<Playlist>{};
}
// Load tracks
const char* tracksSql = R"(
SELECT track_url, track_title, track_artist, track_thumbnail
FROM playlist_tracks
WHERE playlist_id = ?
ORDER BY position;
)";
if (sqlite3_prepare_v2(impl_->db, tracksSql, -1, &stmt, nullptr) == SQLITE_OK) {
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(id));
while (sqlite3_step(stmt) == SQLITE_ROW) {
TrackInfo track;
track.originalUrl = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
track.title = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
track.artist = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2));
if (sqlite3_column_text(stmt, 3)) {
track.thumbnailUrl = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 3));
}
playlist.tracks.push_back(track);
}
sqlite3_finalize(stmt);
}
return playlist;
}
Result<std::vector<Playlist>> Database::getUserPlaylists(uint64_t userId) {
std::vector<Playlist> playlists;
const char* sql = R"(
SELECT id, name, description, created_at, is_public
FROM playlists
WHERE created_by = ? OR is_public = 1
ORDER BY updated_at DESC;
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
while (sqlite3_step(stmt) == SQLITE_ROW) {
Playlist playlist;
playlist.id = static_cast<uint64_t>(sqlite3_column_int64(stmt, 0));
playlist.name = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
playlist.description = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2));
playlist.isPublic = sqlite3_column_int(stmt, 4) != 0;
playlists.push_back(playlist);
}
sqlite3_finalize(stmt);
return playlists;
}
Result<void> Database::deletePlaylist(uint64_t id) {
const char* sql = "DELETE FROM playlists WHERE id = ?;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(id));
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return {};
}
Result<void> Database::addTrackToPlaylist(uint64_t playlistId,
const TrackInfo& track, uint32_t position) {
const char* sql = R"(
INSERT INTO playlist_tracks
(playlist_id, track_url, track_title, track_artist, track_thumbnail, position)
VALUES (?, ?, ?, ?, ?, ?);
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(playlistId));
sqlite3_bind_text(stmt, 2, track.originalUrl.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 3, track.title.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 4, track.artist.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 5,
track.thumbnailUrl ? track.thumbnailUrl->c_str() : "", -1, SQLITE_STATIC);
sqlite3_bind_int(stmt, 6, position);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
// Update playlist timestamp
sqlite3_exec(impl_->db,
std::format("UPDATE playlists SET updated_at = CURRENT_TIMESTAMP WHERE id = {}",
playlistId).c_str(), nullptr, nullptr, nullptr);
return {};
}
// Playback history
Result<void> Database::recordPlayback(const TrackInfo& track,
uint64_t playedBy, std::chrono::milliseconds duration, bool completed) {
const char* sql = R"(
INSERT INTO playback_history
(track_url, track_title, track_artist, played_by, duration_ms, completed)
VALUES (?, ?, ?, ?, ?, ?);
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_text(stmt, 1, track.originalUrl.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, track.title.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 3, track.artist.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_int64(stmt, 4, static_cast<sqlite3_int64>(playedBy));
sqlite3_bind_int64(stmt, 5, duration.count());
sqlite3_bind_int(stmt, 6, completed ? 1 : 0);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return {};
}
Result<std::vector<PlaybackHistoryEntry>> Database::getPlaybackHistory(
uint64_t userId, size_t limit, size_t offset) {
std::vector<PlaybackHistoryEntry> history;
const char* sql = R"(
SELECT id, track_url, track_title, track_artist, played_at, duration_ms, completed
FROM playback_history
WHERE played_by = ?
ORDER BY played_at DESC
LIMIT ? OFFSET ?;
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
sqlite3_bind_int64(stmt, 2, static_cast<sqlite3_int64>(limit));
sqlite3_bind_int64(stmt, 3, static_cast<sqlite3_int64>(offset));
while (sqlite3_step(stmt) == SQLITE_ROW) {
PlaybackHistoryEntry entry;
entry.id = static_cast<uint64_t>(sqlite3_column_int64(stmt, 0));
entry.track.originalUrl = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
entry.track.title = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2));
entry.track.artist = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 3));
entry.playedBy = userId;
entry.duration = std::chrono::milliseconds(sqlite3_column_int64(stmt, 5));
entry.completed = sqlite3_column_int(stmt, 6) != 0;
history.push_back(entry);
}
sqlite3_finalize(stmt);
return history;
}
// Favorites
Result<void> Database::addFavorite(uint64_t userId, const TrackInfo& track) {
const char* sql = R"(
INSERT OR REPLACE INTO user_favorites
(user_id, track_url, track_title, track_artist)
VALUES (?, ?, ?, ?);
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
sqlite3_bind_text(stmt, 2, track.originalUrl.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 3, track.title.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 4, track.artist.c_str(), -1, SQLITE_STATIC);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return {};
}
Result<void> Database::removeFavorite(uint64_t userId, const std::string& trackUrl) {
const char* sql = "DELETE FROM user_favorites WHERE user_id = ? AND track_url = ?;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
sqlite3_bind_text(stmt, 2, trackUrl.c_str(), -1, SQLITE_STATIC);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return {};
}
Result<bool> Database::isFavorite(uint64_t userId, const std::string& trackUrl) {
const char* sql =
"SELECT 1 FROM user_favorites WHERE user_id = ? AND track_url = ? LIMIT 1;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
sqlite3_bind_text(stmt, 2, trackUrl.c_str(), -1, SQLITE_STATIC);
bool found = sqlite3_step(stmt) == SQLITE_ROW;
sqlite3_finalize(stmt);
return found;
}
Result<std::vector<FavoriteTrack>> Database::getFavorites(uint64_t userId) {
std::vector<FavoriteTrack> favorites;
const char* sql = R"(
SELECT track_url, track_title, track_artist, added_at
FROM user_favorites
WHERE user_id = ?
ORDER BY added_at DESC;
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
while (sqlite3_step(stmt) == SQLITE_ROW) {
FavoriteTrack fav;
fav.track.originalUrl = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
fav.track.title = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
fav.track.artist = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2));
fav.userId = userId;
favorites.push_back(fav);
}
sqlite3_finalize(stmt);
return favorites;
}
// Maintenance
Result<void> Database::trimHistory(size_t keepCount) {
const char* sql = R"(
DELETE FROM playback_history
WHERE id NOT IN (
SELECT id FROM playback_history
ORDER BY played_at DESC
LIMIT ?
);
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(keepCount));
sqlite3_step(stmt);
sqlite3_finalize(stmt);
// Vacuum to reclaim space
sqlite3_exec(impl_->db, "VACUUM;", nullptr, nullptr, nullptr);
return {};
}
Result<void> Database::clearUserData(uint64_t userId) {
const char* sql1 = "DELETE FROM user_favorites WHERE user_id = ?;";
const char* sql2 = "DELETE FROM playback_history WHERE played_by = ?;";
const char* sql3 = "DELETE FROM playlists WHERE created_by = ?;";
sqlite3_stmt* stmt;
for (const char* sql : {sql1, sql2, sql3}) {
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) == SQLITE_OK) {
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
sqlite3_step(stmt);
sqlite3_finalize(stmt);
}
}
return {};
}
Result<void> Database::vacuum() {
sqlite3_exec(impl_->db, "VACUUM;", nullptr, nullptr, nullptr);
return {};
}
// Subscriptions
Result<void> Database::addSubscriber(uint64_t clientId) {
const char* sql = R"(
INSERT OR REPLACE INTO subscriptions (client_id)
VALUES (?);
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(clientId));
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return {};
}
Result<void> Database::removeSubscriber(uint64_t clientId) {
const char* sql = "DELETE FROM subscriptions WHERE client_id = ?;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(clientId));
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return {};
}
Result<bool> Database::isSubscriber(uint64_t clientId) {
const char* sql =
"SELECT 1 FROM subscriptions WHERE client_id = ? LIMIT 1;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(clientId));
bool found = sqlite3_step(stmt) == SQLITE_ROW;
sqlite3_finalize(stmt);
return found;
}
Result<std::vector<uint64_t>> Database::getAllSubscribers() {
std::vector<uint64_t> subscribers;
const char* sql = "SELECT client_id FROM subscriptions;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
while (sqlite3_step(stmt) == SQLITE_ROW) {
subscribers.push_back(static_cast<uint64_t>(sqlite3_column_int64(stmt, 0)));
}
sqlite3_finalize(stmt);
return subscribers;
}
Result<size_t> Database::getSubscriberCount() {
const char* sql = "SELECT COUNT(*) FROM subscriptions;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
size_t count = 0;
if (sqlite3_step(stmt) == SQLITE_ROW) {
count = static_cast<size_t>(sqlite3_column_int64(stmt, 0));
}
sqlite3_finalize(stmt);
return count;
}
// Stub implementations for missing methods
Result<void> Database::updatePlaylist(uint64_t id,
const std::optional<std::string>& name,
const std::optional<std::string>& description,
const std::optional<bool>& isPublic) {
(void)id; (void)name; (void)description; (void)isPublic;
return {};
}
Result<void> Database::removeTrackFromPlaylist(uint64_t playlistId, uint64_t trackId) {
(void)playlistId; (void)trackId;
return {};
}
Result<void> Database::reorderPlaylistTrack(uint64_t playlistId,
uint64_t trackId, uint32_t newPosition) {
(void)playlistId; (void)trackId; (void)newPosition;
return {};
}
Result<std::vector<TrackInfo>> Database::getRecentlyPlayed(
uint64_t userId, size_t limit) {
(void)userId; (void)limit;
return std::vector<TrackInfo>{};
}
Result<PlaybackStatistics> Database::getStatistics(
uint64_t userId,
std::optional<std::chrono::system_clock::time_point> since) {
(void)userId; (void)since;
return PlaybackStatistics{};
}
Result<std::vector<std::pair<TrackInfo, uint64_t>>> Database::getMostPlayed(
uint64_t userId, size_t limit) {
(void)userId; (void)limit;
return std::vector<std::pair<TrackInfo, uint64_t>>{};
}
Result<void> Database::executeQuery(const std::string& sql, RowCallback callback) {
(void)sql; (void)callback;
return {};
}
// Database manager
Database& DatabaseManager::instance() {
static Database db;
return db;
}
Result<void> DatabaseManager::initialize(const DatabaseConfig& config) {
return instance().initialize(config);
}
void DatabaseManager::shutdown() {
instance().shutdown();
}
} // namespace Echoion::Api
+185
View File
@@ -0,0 +1,185 @@
#include "echoion/api/EventBus.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Api {
// Global event bus instance
EventBus& GlobalEventBus::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
+23
View File
@@ -0,0 +1,23 @@
#include "echoion/api/Export.hpp"
#include "echoion/core/Core.hpp"
#include <memory>
namespace Echoion::Api {
CoreInterfacePtr CreateCore() {
return std::make_shared<Core::Core>();
}
void DestroyCore(ICoreInterface* core) {
delete core;
}
const char* GetApiVersion() {
return VERSION_STRING;
}
bool IsApiCompatible(uint32_t major, uint32_t minor) {
return major == VERSION_MAJOR && minor <= VERSION_MINOR;
}
} // namespace Echoion::Api
+295
View File
@@ -0,0 +1,295 @@
#include "echoion/core/Logger.hpp"
#include <iostream>
#include <format>
#include <algorithm>
namespace Echoion::Core {
Logger::Logger(std::string_view logDir, std::string_view baseName)
: logDir_(logDir)
, baseName_(baseName) {
// Ensure log directory exists
std::error_code ec;
std::filesystem::create_directories(logDir_, ec);
// Open log files for each level
openLogFiles();
// Start worker thread
workerThread_ = std::thread(&Logger::logWorker, this);
}
Logger::~Logger() {
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::openLogFiles() {
std::lock_guard<std::mutex> lock(fileMutex_);
// Open file for each log level
for (auto level : {Api::LogLevel::Debug, Api::LogLevel::Info,
Api::LogLevel::Warning, Api::LogLevel::Error, Api::LogLevel::Critical}) {
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) {
std::string levelStr;
switch (level) {
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) {
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() {
while (running_.load()) {
std::unique_lock<std::mutex> lock(queueMutex_);
cv_.wait(lock, [this] { return !logQueue_.empty() || !running_.load(); });
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) {
std::lock_guard<std::mutex> lock(fileMutex_);
// Write to level-specific file
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::rotateIfNeeded(Api::LogLevel level) {
std::lock_guard<std::mutex> lock(fileMutex_);
auto maxSize = maxFileSize_.load();
// Check level-specific file
auto it = levelFiles_.find(level);
if (it != levelFiles_.end() && it->second.size >= maxSize) {
it->second.stream.close();
// Rotate: move current to .1, .1 to .2, etc.
auto basePath = it->second.path;
for (int i = maxFiles_.load() - 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);
}
}
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;
for (int i = maxFiles_.load() - 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);
}
}
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) {
return std::format("[{}] [{}] [{}] {} - {}",
formatTimestamp(entry.timestamp),
levelToString(entry.level),
entry.threadId,
entry.sourceFile.substr(entry.sourceFile.find_last_of("/\\") + 1),
entry.message);
}
std::string Logger::levelToString(Api::LogLevel level) {
switch (level) {
case Api::LogLevel::Debug: return "DEBUG";
case Api::LogLevel::Info: return "INFO";
case Api::LogLevel::Warning: return "WARN";
case Api::LogLevel::Error: return "ERROR";
case Api::LogLevel::Critical: return "CRITICAL";
default: return "UNKNOWN";
}
}
std::string Logger::formatTimestamp(const std::chrono::system_clock::time_point& tp) {
auto time_t = std::chrono::system_clock::to_time_t(tp);
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) {
minLevel_.store(level);
}
Api::LogLevel Logger::getMinLevel() const {
return minLevel_.load();
}
void Logger::registerCallback(const LogCallback& callback) {
std::lock_guard<std::mutex> lock(callbackMutex_);
callbacks_.push_back(callback);
}
void Logger::unregisterCallback(const LogCallback& callback) {
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() {
std::lock_guard<std::mutex> lock(fileMutex_);
for (auto& [level, info] : levelFiles_) {
if (info.stream.is_open()) {
info.stream.flush();
}
}
if (combinedFile_.stream.is_open()) {
combinedFile_.stream.flush();
}
}
void Logger::setConsoleOutput(bool enabled) {
consoleOutput_.store(enabled);
}
void Logger::setFileOutput(bool enabled) {
fileOutput_.store(enabled);
}
void Logger::setMaxFileSize(uint64_t bytes) {
maxFileSize_.store(bytes);
}
void Logger::setMaxFiles(uint32_t count) {
maxFiles_.store(count);
}
} // namespace Echoion::Core
+47
View File
@@ -0,0 +1,47 @@
#include "echoion/api/MemoryPool.hpp"
#include "echoion/core/Logger.hpp"
namespace Echoion::Api {
AudioBufferPool& AudioBufferPool::instance() {
static AudioBufferPool instance;
return instance;
}
void AudioBufferPool::initialize(size_t bufferSize, size_t poolSize) {
bufferSize_ = bufferSize;
pool_ = std::make_unique<MemoryPool<float>>(bufferSize, poolSize);
ECHOION_LOG_INFO(std::format("AudioBufferPool initialized: {} buffers of {} samples (~{} MB)",
poolSize, bufferSize, (bufferSize * poolSize * sizeof(float)) / (1024 * 1024)));
}
void AudioBufferPool::shutdown() {
pool_.reset();
ECHOION_LOG_INFO("AudioBufferPool shutdown");
}
PooledPtr<float> AudioBufferPool::acquireBuffer() {
if (!pool_) {
return PooledPtr<float>();
}
float* ptr = pool_->acquire();
if (!ptr) {
ECHOION_LOG_WARNING("AudioBufferPool exhausted - consider increasing pool size");
return PooledPtr<float>();
}
return PooledPtr<float>(ptr, pool_.get());
}
size_t AudioBufferPool::getAvailableBuffers() const {
if (!pool_) return 0;
return pool_->available();
}
size_t AudioBufferPool::getTotalBuffers() const {
if (!pool_) return 0;
return pool_->capacity();
}
} // namespace Echoion::Api
+1081
View File
File diff suppressed because it is too large. Load diff
+813
View File
@@ -0,0 +1,813 @@
#include "echoion/core/NetworkClient.hpp"
#include "boost/beast/core/buffers_to_string.hpp"
#include "echoion/core/Logger.hpp"
#include <boost/beast/http/field.hpp>
#include <format>
#include <algorithm>
#include <glaze/glaze.hpp>
// Boost.Beast for HTTP with proxy support
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/beast.hpp>
#include <boost/beast/ssl.hpp>
#include <boost/url.hpp>
namespace Echoion::Core {
namespace asio = boost::asio;
namespace beast = boost::beast;
namespace http = boost::beast::http;
namespace ssl = boost::asio::ssl;
namespace urls = boost::urls;
// Simple base64 encoding for proxy authentication
namespace base64 {
static const std::string chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string encode(const std::string& input) {
std::string encoded;
encoded.reserve(((input.size() + 2) / 3) * 4);
int val = 0, valb = -6;
for (unsigned char c : input) {
val = (val << 8) + c;
valb += 8;
while (valb >= 0) {
encoded.push_back(chars[(val >> valb) & 0x3F]);
valb -= 6;
}
}
if (valb > -6) {
encoded.push_back(chars[((val << 8) >> (valb + 8)) & 0x3F]);
}
while (encoded.size() % 4) {
encoded.push_back('=');
}
return encoded;
}
}
// Helper to perform URL encoding
std::string urlEncode(std::string_view value) {
std::string encoded;
encoded.reserve(value.size() * 3);
for (unsigned char c : value) {
if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
encoded += c;
} else {
encoded += std::format("%{:02X}", c);
}
}
return encoded;
}
// Helper to parse URL into components
struct UrlComponents {
std::string protocol;
std::string host;
std::string port;
std::string path;
std::string query;
bool isHttps;
};
std::optional<UrlComponents> parseUrl(std::string_view url) {
try {
auto result = urls::parse_uri(url);
if (!result) {
return std::nullopt;
}
const auto& uri = *result;
UrlComponents comp;
comp.protocol = std::string(uri.scheme());
comp.host = std::string(uri.host());
comp.isHttps = (comp.protocol == "https");
// Set default port
if (uri.port().empty()) {
comp.port = comp.isHttps ? "443" : "80";
} else {
comp.port = std::string(uri.port());
}
// Build path (use encoded path to preserve percent-encoding)
comp.path = std::string(uri.encoded_path());
if (comp.path.empty()) {
comp.path = "/";
}
// Add query if present (use encoded query to preserve percent-encoding)
if (!uri.query().empty()) {
comp.query = std::string(uri.encoded_query());
comp.path += "?" + comp.query;
}
return comp;
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("URL parse error: {}", e.what()));
return std::nullopt;
}
}
NetworkClient::NetworkClient() = default;
NetworkClient::~NetworkClient() {
shutdown();
}
Api::Result<void> NetworkClient::initialize(const std::optional<Api::ProxyConfig>& proxy) {
proxy_ = proxy;
initialized_ = true;
// Initialize thread pool
for (size_t i = 0; i < THREAD_POOL_SIZE; ++i) {
threadPool_.emplace_back([this] {
while (!stopThreads_.load()) {
std::packaged_task<Api::Result<Api::HttpResponse>()> task;
{
std::unique_lock<std::mutex> lock(taskMutex_);
taskCv_.wait(lock, [this] { return !taskQueue_.empty() || stopThreads_.load(); });
if (stopThreads_.load() && taskQueue_.empty()) {
return;
}
task = std::move(taskQueue_.front());
taskQueue_.pop();
}
task();
}
});
}
ECHOION_LOG_INFO(std::format("NetworkClient initialized (proxy: {})",
proxy.has_value() ? "enabled" : "disabled"));
return {};
}
void NetworkClient::shutdown() {
stopThreads_ = true;
taskCv_.notify_all();
for (auto& thread : threadPool_) {
if (thread.joinable()) {
thread.join();
}
}
threadPool_.clear();
initialized_ = false;
ECHOION_LOG_INFO("NetworkClient shutdown");
}
Api::Result<Api::HttpResponse> NetworkClient::get(std::string_view url,
const std::vector<Api::HttpHeader>& headers) {
Api::HttpRequest req;
req.url = std::string(url);
req.method = Api::HttpMethod::GET;
req.headers = addDefaultHeaders(headers);
req.proxy = proxy_;
return request(req);
}
Api::Result<Api::HttpResponse> NetworkClient::post(std::string_view url, std::string_view body,
const std::vector<Api::HttpHeader>& headers) {
Api::HttpRequest req;
req.url = std::string(url);
req.method = Api::HttpMethod::POST;
req.headers = addDefaultHeaders(headers);
req.body = std::vector<uint8_t>(body.begin(), body.end());
req.proxy = proxy_;
return request(req);
}
Api::Result<Api::HttpResponse> NetworkClient::request(const Api::HttpRequest& req) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"NetworkClient not initialized"));
}
return executeWithRetry(req);
}
std::future<Api::Result<Api::HttpResponse>> NetworkClient::getAsync(std::string_view url,
const std::vector<Api::HttpHeader>& headers) {
std::packaged_task<Api::Result<Api::HttpResponse>()> task([this, urlStr = std::string(url), headers] {
return get(urlStr, headers);
});
auto future = task.get_future();
{
std::lock_guard<std::mutex> lock(taskMutex_);
taskQueue_.push(std::move(task));
}
taskCv_.notify_one();
return future;
}
std::future<Api::Result<Api::HttpResponse>> NetworkClient::postAsync(std::string_view url,
std::string_view body, const std::vector<Api::HttpHeader>& headers) {
std::packaged_task<Api::Result<Api::HttpResponse>()> task([this, urlStr = std::string(url),
bodyStr = std::string(body), headers] {
return post(urlStr, bodyStr, headers);
});
auto future = task.get_future();
{
std::lock_guard<std::mutex> lock(taskMutex_);
taskQueue_.push(std::move(task));
}
taskCv_.notify_one();
return future;
}
std::future<Api::Result<Api::HttpResponse>> NetworkClient::requestAsync(const Api::HttpRequest& req) {
std::packaged_task<Api::Result<Api::HttpResponse>()> task([this, req] {
return request(req);
});
auto future = task.get_future();
{
std::lock_guard<std::mutex> lock(taskMutex_);
taskQueue_.push(std::move(task));
}
taskCv_.notify_one();
return future;
}
std::vector<Api::Result<Api::HttpResponse>> NetworkClient::requestBatch(
const std::vector<Api::HttpRequest>& requests) {
std::vector<std::future<Api::Result<Api::HttpResponse>>> futures;
futures.reserve(requests.size());
for (const auto& req : requests) {
futures.push_back(requestAsync(req));
}
std::vector<Api::Result<Api::HttpResponse>> results;
results.reserve(requests.size());
for (auto& future : futures) {
results.push_back(future.get());
}
return results;
}
void NetworkClient::setProxy(const std::optional<Api::ProxyConfig>& proxy) {
std::lock_guard<std::mutex> lock(mutex_);
proxy_ = proxy;
ECHOION_LOG_INFO(std::format("Proxy {}", proxy.has_value() ? "configured" : "cleared"));
}
std::optional<Api::ProxyConfig> NetworkClient::getProxy() const {
std::lock_guard<std::mutex> lock(mutex_);
return proxy_;
}
void NetworkClient::clearProxy() {
std::lock_guard<std::mutex> lock(mutex_);
proxy_.reset();
ECHOION_LOG_INFO("Proxy cleared");
}
void NetworkClient::setRetryConfig(const Api::RetryConfig& config) {
std::lock_guard<std::mutex> lock(mutex_);
retryConfig_ = config;
}
Api::RetryConfig NetworkClient::getRetryConfig() const {
std::lock_guard<std::mutex> lock(mutex_);
return retryConfig_;
}
Api::Result<Api::HttpResponse> NetworkClient::executeWithRetry(const Api::HttpRequest& req) {
auto delay = retryConfig_.initialDelay;
for (uint32_t attempt = 0; attempt <= retryConfig_.maxRetries; ++attempt) {
auto result = executeRequest(req);
if (result) {
// Check if we should retry based on status code
if (result->isError() && attempt < retryConfig_.maxRetries) {
auto it = std::find(retryConfig_.retryableStatusCodes.begin(),
retryConfig_.retryableStatusCodes.end(),
result->statusCode);
if (it != retryConfig_.retryableStatusCodes.end()) {
ECHOION_LOG_WARNING(std::format("Request failed with status {}, retrying (attempt {}/{})",
result->statusCode, attempt + 1, retryConfig_.maxRetries));
std::this_thread::sleep_for(delay);
delay = std::min(std::chrono::milliseconds(static_cast<uint32_t>(
delay.count() * retryConfig_.backoffMultiplier)), retryConfig_.maxDelay);
continue;
}
}
return result;
} else if (attempt < retryConfig_.maxRetries) {
ECHOION_LOG_WARNING(std::format("Request error: {}, retrying (attempt {}/{})",
result.error().message, attempt + 1, retryConfig_.maxRetries));
std::this_thread::sleep_for(delay);
delay = std::min(std::chrono::milliseconds(static_cast<uint32_t>(
delay.count() * retryConfig_.backoffMultiplier)), retryConfig_.maxDelay);
} else {
return result;
}
}
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"Max retries exceeded"));
}
// Execute HTTP request using Boost.Beast with proxy support
Api::Result<Api::HttpResponse> NetworkClient::executeRequest(const Api::HttpRequest& req) {
try {
auto start = std::chrono::steady_clock::now();
// Parse target URL
auto urlComp = parseUrl(req.url);
if (!urlComp) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidUrl,
"Failed to parse URL"));
}
// Determine which proxy to use (request-specific or global)
std::optional<Api::ProxyConfig> activeProxy = req.proxy.has_value() ? req.proxy : proxy_;
bool useProxy = activeProxy.has_value() && activeProxy->isValid();
// Setup IO context
asio::io_context ioc;
ssl::context ctx(ssl::context::tlsv12_client);
ctx.set_default_verify_paths();
// Resolve timeout
auto timeout = std::chrono::seconds(req.timeout.count());
Api::HttpResponse response;
if (useProxy) {
// Route to appropriate proxy handler based on proxy type
const auto& proxy = *activeProxy;
if (proxy.isSocks5()) {
response = executeWithSocks5Proxy(ioc, ctx, *urlComp, req, proxy, timeout);
} else {
response = executeWithHttpProxy(ioc, ctx, *urlComp, req, proxy, timeout);
}
} else {
// Direct connection
response = executeDirect(ioc, ctx, *urlComp, req, timeout);
}
auto end = std::chrono::steady_clock::now();
response.responseTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
return response;
} catch (const std::exception& e) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
std::format("HTTP request failed: {}", e.what())));
}
}
// Execute request through HTTP proxy using CONNECT tunneling
Api::HttpResponse NetworkClient::executeWithProxy(
asio::io_context& ioc,
ssl::context& ctx,
const UrlComponents& urlComp,
const Api::HttpRequest& req,
const Api::ProxyConfig& proxy,
std::chrono::seconds timeout) {
// Dispatch to appropriate proxy handler
if (proxy.isSocks5()) {
return executeWithSocks5Proxy(ioc, ctx, urlComp, req, proxy, timeout);
} else {
return executeWithHttpProxy(ioc, ctx, urlComp, req, proxy, timeout);
}
}
// Execute request through HTTP proxy using CONNECT tunneling
Api::HttpResponse NetworkClient::executeWithHttpProxy(
asio::io_context& ioc,
ssl::context& ctx,
const UrlComponents& urlComp,
const Api::HttpRequest& req,
const Api::ProxyConfig& proxy,
std::chrono::seconds timeout) {
// Create TCP socket for proxy connection
asio::ip::tcp::socket socket(ioc);
// Resolve proxy address
asio::ip::tcp::resolver resolver(ioc);
auto proxyResults = resolver.resolve(proxy.host, std::to_string(proxy.port));
// Connect to proxy
asio::connect(socket, proxyResults);
std::string target = urlComp.host + ":" + urlComp.port;
if (urlComp.isHttps) {
// For HTTPS: Send CONNECT request to establish tunnel
http::request<http::string_body> connect_req(http::verb::connect, target, 11);
connect_req.set(http::field::host, target);
// Add proxy authentication if needed
if (proxy.requiresAuth()) {
std::string auth = std::format("{}:{}", *proxy.username, *proxy.password);
std::string encoded = base64::encode(auth);
connect_req.set(http::field::proxy_authorization, "Basic " + encoded);
}
// Send CONNECT request
http::write(socket, connect_req);
// Read CONNECT response
beast::flat_buffer buffer;
http::response<http::empty_body> connect_res;
http::read(socket, buffer, connect_res);
if (connect_res.result() != http::status::ok) {
throw std::runtime_error(std::format("Proxy CONNECT failed: {}",
static_cast<int>(connect_res.result())));
}
// Upgrade socket to SSL
ssl::stream<asio::ip::tcp::socket> stream(std::move(socket), ctx);
stream.set_verify_mode(ssl::verify_peer);
stream.set_verify_callback(ssl::host_name_verification(urlComp.host));
// Perform SSL handshake
stream.handshake(ssl::stream_base::client);
// Send actual HTTPS request through tunnel
return sendHttpsRequest(stream, urlComp, req);
} else {
// For HTTP: Proxy forwards the request
// Some proxies require absolute URL in the request line
return sendHttpRequestThroughProxy(socket, urlComp, req, proxy);
}
}
// Execute request through SOCKS5 proxy
Api::HttpResponse NetworkClient::executeWithSocks5Proxy(
asio::io_context& ioc,
ssl::context& ctx,
const UrlComponents& urlComp,
const Api::HttpRequest& req,
const Api::ProxyConfig& proxy,
std::chrono::seconds timeout) {
// Create TCP socket for proxy connection
asio::ip::tcp::socket socket(ioc);
// Resolve proxy address
asio::ip::tcp::resolver resolver(ioc);
auto proxyResults = resolver.resolve(proxy.host, std::to_string(proxy.port));
// Connect to SOCKS5 proxy
asio::connect(socket, proxyResults);
// SOCKS5 handshake
// Step 1: Send greeting
std::vector<uint8_t> greeting;
greeting.push_back(0x05); // SOCKS version 5
if (proxy.requiresAuth()) {
greeting.push_back(0x02); // 2 auth methods
greeting.push_back(0x00); // No auth
greeting.push_back(0x02); // Username/password auth
} else {
greeting.push_back(0x01); // 1 auth method
greeting.push_back(0x00); // No auth
}
asio::write(socket, asio::buffer(greeting));
// Step 2: Receive server response
std::vector<uint8_t> response(2);
asio::read(socket, asio::buffer(response));
if (response[0] != 0x05) {
throw std::runtime_error("SOCKS5 proxy: Invalid version");
}
// Step 3: Handle authentication if required
if (response[1] == 0x02) {
// Username/password authentication
if (!proxy.requiresAuth()) {
throw std::runtime_error("SOCKS5 proxy: Auth required but no credentials provided");
}
// Build auth request
std::vector<uint8_t> authRequest;
authRequest.push_back(0x01); // Auth version
authRequest.push_back(static_cast<uint8_t>(proxy.username->size()));
authRequest.insert(authRequest.end(), proxy.username->begin(), proxy.username->end());
authRequest.push_back(static_cast<uint8_t>(proxy.password->size()));
authRequest.insert(authRequest.end(), proxy.password->begin(), proxy.password->end());
asio::write(socket, asio::buffer(authRequest));
// Read auth response
std::vector<uint8_t> authResponse(2);
asio::read(socket, asio::buffer(authResponse));
if (authResponse[0] != 0x01 || authResponse[1] != 0x00) {
throw std::runtime_error("SOCKS5 proxy: Authentication failed");
}
} else if (response[1] != 0x00) {
throw std::runtime_error(std::format("SOCKS5 proxy: Auth method {} not accepted",
static_cast<int>(response[1])));
}
// Step 4: Send connection request
std::vector<uint8_t> connectRequest;
connectRequest.push_back(0x05); // SOCKS version 5
connectRequest.push_back(0x01); // CONNECT command
connectRequest.push_back(0x00); // Reserved
// Check if target is IP address or domain name
asio::ip::address ipAddr;
bool isIp = false;
try {
ipAddr = asio::ip::make_address(urlComp.host);
isIp = true;
} catch (...) {
isIp = false;
}
uint16_t targetPort = static_cast<uint16_t>(std::stoi(urlComp.port));
if (isIp) {
if (ipAddr.is_v4()) {
connectRequest.push_back(0x01); // IPv4
auto bytes = ipAddr.to_v4().to_bytes();
connectRequest.insert(connectRequest.end(), bytes.begin(), bytes.end());
} else {
connectRequest.push_back(0x04); // IPv6
auto bytes = ipAddr.to_v6().to_bytes();
connectRequest.insert(connectRequest.end(), bytes.begin(), bytes.end());
}
} else {
connectRequest.push_back(0x03); // Domain name
connectRequest.push_back(static_cast<uint8_t>(urlComp.host.size()));
connectRequest.insert(connectRequest.end(), urlComp.host.begin(), urlComp.host.end());
}
// Port in network byte order
connectRequest.push_back(static_cast<uint8_t>((targetPort >> 8) & 0xFF));
connectRequest.push_back(static_cast<uint8_t>(targetPort & 0xFF));
asio::write(socket, asio::buffer(connectRequest));
// Step 5: Receive connection response
std::vector<uint8_t> connectResponse(4);
asio::read(socket, asio::buffer(connectResponse));
if (connectResponse[0] != 0x05) {
throw std::runtime_error("SOCKS5 proxy: Invalid version in connect response");
}
if (connectResponse[1] != 0x00) {
std::string errorMsg;
switch (connectResponse[1]) {
case 0x01: errorMsg = "General SOCKS server failure"; break;
case 0x02: errorMsg = "Connection not allowed by ruleset"; break;
case 0x03: errorMsg = "Network unreachable"; break;
case 0x04: errorMsg = "Host unreachable"; break;
case 0x05: errorMsg = "Connection refused"; break;
case 0x06: errorMsg = "TTL expired"; break;
case 0x07: errorMsg = "Command not supported"; break;
case 0x08: errorMsg = "Address type not supported"; break;
default: errorMsg = std::format("Unknown error code {}", static_cast<int>(connectResponse[1]));
}
throw std::runtime_error(std::format("SOCKS5 proxy connection failed: {}", errorMsg));
}
// Read the bind address from response (variable length)
uint8_t addrType = connectResponse[3];
std::vector<uint8_t> bindAddr;
if (addrType == 0x01) {
// IPv4: 4 bytes + 2 bytes port
bindAddr.resize(6);
asio::read(socket, asio::buffer(bindAddr));
} else if (addrType == 0x03) {
// Domain name: 1 byte length + domain + 2 bytes port
std::vector<uint8_t> domainLen(1);
asio::read(socket, asio::buffer(domainLen));
bindAddr.resize(domainLen[0] + 2);
asio::read(socket, asio::buffer(bindAddr));
} else if (addrType == 0x04) {
// IPv6: 16 bytes + 2 bytes port
bindAddr.resize(18);
asio::read(socket, asio::buffer(bindAddr));
}
// SOCKS5 tunnel established, now send HTTP request
if (urlComp.isHttps) {
// Upgrade socket to SSL for HTTPS
ssl::stream<asio::ip::tcp::socket> stream(std::move(socket), ctx);
stream.set_verify_mode(ssl::verify_peer);
stream.set_verify_callback(ssl::host_name_verification(urlComp.host));
// Perform SSL handshake
stream.handshake(ssl::stream_base::client);
// Send HTTPS request through tunnel
return sendHttpsRequest(stream, urlComp, req);
} else {
// Send HTTP request through tunnel
return sendHttpRequest(socket, urlComp, req);
}
}
// Execute direct request without proxy
Api::HttpResponse NetworkClient::executeDirect(
asio::io_context& ioc,
ssl::context& ctx,
const UrlComponents& urlComp,
const Api::HttpRequest& req,
std::chrono::seconds timeout) {
if (urlComp.isHttps) {
// HTTPS direct connection
ssl::stream<asio::ip::tcp::socket> stream(ioc, ctx);
// Set SNI hostname
if (!SSL_set_tlsext_host_name(stream.native_handle(), urlComp.host.c_str())) {
throw std::runtime_error("Failed to set SNI hostname");
}
// Resolve and connect
asio::ip::tcp::resolver resolver(ioc);
auto results = resolver.resolve(urlComp.host, urlComp.port);
asio::connect(stream.next_layer(), results);
// SSL handshake
stream.handshake(ssl::stream_base::client);
return sendHttpsRequest(stream, urlComp, req);
} else {
// HTTP direct connection
asio::ip::tcp::socket socket(ioc);
asio::ip::tcp::resolver resolver(ioc);
auto results = resolver.resolve(urlComp.host, urlComp.port);
asio::connect(socket, results);
return sendHttpRequest(socket, urlComp, req);
}
}
// Send HTTP request through socket
Api::HttpResponse NetworkClient::sendHttpRequest(
asio::ip::tcp::socket& socket,
const UrlComponents& urlComp,
const Api::HttpRequest& req) {
http::request<http::string_body> request = buildBeastRequest(urlComp, req);
http::write(socket, request);
beast::flat_buffer buffer;
http::response<http::dynamic_body> response;
http::read(socket, buffer, response);
return convertBeastResponse(response);
}
// Send HTTP request through proxy (for non-HTTPS)
Api::HttpResponse NetworkClient::sendHttpRequestThroughProxy(
asio::ip::tcp::socket& socket,
const UrlComponents& urlComp,
const Api::HttpRequest& req,
const Api::ProxyConfig& proxy) {
// Build request with absolute URL
std::string absoluteUrl = std::format("{}://{}{}",
urlComp.protocol, urlComp.host, urlComp.path);
http::verb method = http::verb::get;
switch (req.method) {
case Api::HttpMethod::GET: method = http::verb::get; break;
case Api::HttpMethod::POST: method = http::verb::post; break;
case Api::HttpMethod::PUT: method = http::verb::put; break;
case Api::HttpMethod::DELETE: method = http::verb::delete_; break;
case Api::HttpMethod::PATCH: method = http::verb::patch; break;
case Api::HttpMethod::HEAD: method = http::verb::head; break;
case Api::HttpMethod::OPTIONS: method = http::verb::options; break;
}
http::request<http::string_body> request(method, absoluteUrl, 11);
request.set(http::field::host, urlComp.host);
request.set(http::field::user_agent, "EchoionBot/1.0");
// Add headers
for (const auto& header : req.headers) {
request.set(header.name, header.value);
}
// Add proxy auth
if (proxy.requiresAuth()) {
std::string auth = std::format("{}:{}", *proxy.username, *proxy.password);
std::string encoded = base64::encode(auth);
request.set(http::field::proxy_authorization, "Basic " + encoded);
}
// Add body
if (req.body.has_value()) {
request.body() = std::string(req.body->begin(), req.body->end());
request.prepare_payload();
}
http::write(socket, request);
beast::flat_buffer buffer;
http::response<http::dynamic_body> response;
http::read(socket, buffer, response);
return convertBeastResponse(response);
}
// Build Beast HTTP request
http::request<http::string_body> NetworkClient::buildBeastRequest(
const UrlComponents& urlComp,
const Api::HttpRequest& req) {
http::verb method = http::verb::get;
switch (req.method) {
case Api::HttpMethod::GET: method = http::verb::get; break;
case Api::HttpMethod::POST: method = http::verb::post; break;
case Api::HttpMethod::PUT: method = http::verb::put; break;
case Api::HttpMethod::DELETE: method = http::verb::delete_; break;
case Api::HttpMethod::PATCH: method = http::verb::patch; break;
case Api::HttpMethod::HEAD: method = http::verb::head; break;
case Api::HttpMethod::OPTIONS: method = http::verb::options; break;
}
http::request<http::string_body> request(method, urlComp.path, 11);
request.set(http::field::host, urlComp.host);
request.set(http::field::user_agent, "EchoionBot/1.0");
// Add custom headers
for (const auto& header : req.headers) {
request.set(header.name, header.value);
}
// Add body if present
if (req.body.has_value()) {
request.body() = std::string(req.body->begin(), req.body->end());
request.prepare_payload();
}
return request;
}
// Convert Beast response to Api::HttpResponse
Api::HttpResponse NetworkClient::convertBeastResponse(
const http::response<http::dynamic_body>& beastResponse) {
Api::HttpResponse response;
response.statusCode = static_cast<uint16_t>(beastResponse.result_int());
// Extract body
response.body = boost::beast::buffers_to_string(beastResponse.body().data());
// Extract headers (use push_back to preserve multiple headers with same name)
for (const auto& field : beastResponse.base()) {
response.headers.push_back({
std::string(field.name_string()),
std::string(field.value())
});
}
return response;
}
std::vector<Api::HttpHeader> NetworkClient::addDefaultHeaders(const std::vector<Api::HttpHeader>& headers) {
std::vector<Api::HttpHeader> result = headers;
// Check if User-Agent is already present
bool hasUserAgent = std::any_of(headers.begin(), headers.end(),
[](const auto& h) { return h.name == "User-Agent"; });
if (!hasUserAgent) {
result.push_back({"User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"});
}
// Check if Accept is already present
bool hasAccept = std::any_of(headers.begin(), headers.end(),
[](const auto& h) { return h.name == "Accept"; });
if (!hasAccept) {
result.push_back({"Accept", "application/json, */*"});
}
return result;
}
} // namespace Echoion::Core
+400
View File
@@ -0,0 +1,400 @@
#include "echoion/core/RpcServer.hpp"
#include "echoion/core/Logger.hpp"
#include <glaze/glaze.hpp>
#include <format>
#include <algorithm>
namespace Echoion::Core {
RpcServer::RpcServer() = default;
RpcServer::~RpcServer() {
stop();
}
Api::Result<void> RpcServer::start(uint16_t port) {
if (running_.exchange(true)) {
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, "RPC server already running"));
}
port_ = port;
try {
asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port);
acceptor_.emplace(ioContext_);
acceptor_->open(endpoint.protocol());
acceptor_->set_option(asio::ip::tcp::acceptor::reuse_address(true));
acceptor_->bind(endpoint);
acceptor_->listen();
serverThread_ = std::thread(&RpcServer::acceptLoop, this);
ECHOION_LOG_INFO(std::format("RPC server started on port {}", port));
return {};
} catch (const std::exception& e) {
running_ = false;
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
std::format("Failed to start RPC server: {}", e.what())));
}
}
void RpcServer::stop() {
if (!running_.exchange(false)) {
return;
}
try {
// Cancel any pending async operations
if (acceptor_.has_value()) {
boost::system::error_code ec;
acceptor_->cancel(ec);
}
ioContext_.stop();
// Close all client connections
{
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)
{
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
for (auto& thread : clientThreads_) {
if (thread.joinable()) {
thread.detach(); // Don't wait, just detach
}
}
clientThreads_.clear();
}
// Wait for server thread with timeout
if (serverThread_.joinable()) {
// 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
}
}
if (acceptor_.has_value()) {
boost::system::error_code ec;
acceptor_->close(ec);
}
ECHOION_LOG_INFO("RPC server stopped");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Error stopping RPC server: {}", e.what()));
}
}
void RpcServer::acceptLoop() {
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...");
// 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;
auto ws = std::make_shared<websocket::stream<asio::ip::tcp::socket>>(std::move(socket));
ws->accept();
ECHOION_LOG_DEBUG("RPC server WebSocket handshake completed");
uint64_t clientId = nextClientId_++;
{
std::lock_guard<std::mutex> lock(clientsMutex_);
clients_[clientId] = ws;
}
ECHOION_LOG_DEBUG(std::format("RPC client {} connected", clientId));
// Handle client in separate thread
std::thread clientThread([this, clientId, ws]() {
handleClient(ws);
// 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) {
// If we're shutting down, exit gracefully
if (!running_.load()) {
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) {
beast::flat_buffer buffer;
while (running_.load() && ws->is_open()) {
try {
beast::error_code ec;
ws->read(buffer, ec);
if (ec == websocket::error::closed) {
break;
}
if (ec) {
ECHOION_LOG_ERROR(std::format("WebSocket read error: {}", ec.message()));
break;
}
std::string message = beast::buffers_to_string(buffer.data());
buffer.consume(buffer.size());
// Find client ID
uint64_t clientId = 0;
{
std::lock_guard<std::mutex> lock(clientsMutex_);
for (const auto& [id, clientWs] : clients_) {
if (clientWs.get() == ws.get()) {
clientId = id;
break;
}
}
}
if (clientId != 0) {
processMessage(clientId, message);
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Client handling error: {}", e.what()));
break;
}
}
}
void RpcServer::processMessage(uint64_t clientId, const std::string& message) {
try {
Api::RpcRequest request;
auto ec = glz::read_json(request, message);
if (ec) {
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;
}
// Check authentication (except for Authenticate method)
if (request.method != Api::RpcMethod::Authenticate) {
if (!isClientAuthenticated(clientId)) {
Api::RpcResponse response;
response.requestId = request.id;
response.success = false;
response.error = "{\"code\":10,\"message\":\"Not authenticated\",\"source\":\"RpcServer\"}";
response.success = false;
sendResponse(clientId, response);
return;
}
}
// Find handler
std::string methodName = std::to_string(static_cast<int>(request.method));
CommandHandler handler;
{
std::lock_guard<std::mutex> lock(handlersMutex_);
auto it = handlers_.find(methodName);
if (it != handlers_.end()) {
handler = it->second;
}
}
Api::RpcResponse response;
response.requestId = request.id;
response.timestamp = std::chrono::system_clock::now();
if (handler) {
auto result = handler(request.params.value_or(""), clientId);
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\"}";
}
sendResponse(clientId, response);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Message processing error: {}", e.what()));
}
}
void RpcServer::sendResponse(uint64_t clientId, const Api::RpcResponse& response) {
std::lock_guard<std::mutex> lock(clientsMutex_);
auto it = clients_.find(clientId);
if (it == clients_.end() || !it->second->is_open()) {
return;
}
try {
auto json = glz::write_json(response);
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) {
std::lock_guard<std::mutex> lock(clientsMutex_);
auto it = clients_.find(clientId);
if (it == clients_.end() || !it->second->is_open()) {
return;
}
try {
auto json = glz::write_json(notification);
if (json) {
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 {
auto json = glz::write_json(notification);
if (json) {
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
+721
View File
@@ -0,0 +1,721 @@
#include "echoion/core/SignatureCipher.hpp"
#include "echoion/core/Logger.hpp"
#include <regex>
#include <format>
#include <algorithm>
#include <cctype>
#include <glaze/glaze.hpp>
#include <fstream>
#include <filesystem>
// Minimal embedded fallback - a stub that logs errors
// The real solver is downloaded from GitHub releases
namespace {
constexpr std::string_view FALLBACK_CORE_JS = R"(
var globalThis = globalThis || this;
var jsc = function(input) {
return JSON.stringify({
error: "Solver libraries not available. Please check internet connection.",
responses: []
});
};
)";
}
namespace Echoion::Core {
SignatureCipher::SignatureCipher() = default;
SignatureCipher::~SignatureCipher() {
clear();
}
SignatureCipher::SignatureCipher(SignatureCipher&& other) noexcept
: runtime_(other.runtime_)
, context_(other.context_)
, playerJsCode_(std::move(other.playerJsCode_))
, preprocessedPlayer_(std::move(other.preprocessedPlayer_))
, initialized_(other.initialized_)
, solverInitialized_(other.solverInitialized_)
, hasPlayerJs_(other.hasPlayerJs_) {
other.runtime_ = nullptr;
other.context_ = nullptr;
other.initialized_ = false;
other.solverInitialized_ = false;
other.hasPlayerJs_ = false;
}
SignatureCipher& SignatureCipher::operator=(SignatureCipher&& other) noexcept {
if (this != &other) {
clear();
runtime_ = other.runtime_;
context_ = other.context_;
playerJsCode_ = std::move(other.playerJsCode_);
preprocessedPlayer_ = std::move(other.preprocessedPlayer_);
initialized_ = other.initialized_;
solverInitialized_ = other.solverInitialized_;
hasPlayerJs_ = other.hasPlayerJs_;
other.runtime_ = nullptr;
other.context_ = nullptr;
other.initialized_ = false;
other.solverInitialized_ = false;
other.hasPlayerJs_ = false;
}
return *this;
}
void SignatureCipher::initialize() {
std::lock_guard<std::mutex> lock(mutex_);
if (initialized_) {
return;
}
initSolver();
initialized_ = true;
}
bool SignatureCipher::setPlayerJs(std::string_view playerJsCode) {
std::lock_guard<std::mutex> lock(mutex_);
if (!initialized_) {
ECHOION_LOG_ERROR("Cipher not initialized. Call initialize() first.");
return false;
}
if (!solverInitialized_) {
ECHOION_LOG_WARNING("Solver not initialized - cannot process player JS");
return false;
}
playerJsCode_ = std::string(playerJsCode);
hasPlayerJs_ = false;
preprocessedPlayer_.clear();
if (playerJsCode_.empty()) {
ECHOION_LOG_WARNING("Empty player JS code provided");
return false;
}
if (!context_) {
ECHOION_LOG_ERROR("QuickJS context not available");
return false;
}
// Create input for the solver
glz::generic input;
input["type"] = "player";
input["player"] = playerJsCode_;
input["output_preprocessed"] = true;
input["requests"] = glz::generic::array_t{};
std::string inputStr = glz::write_json(input).value();
// Log input for debugging (truncate if too large)
std::string_view inputPreview(inputStr);
if (inputPreview.size() > 500) {
inputPreview = inputPreview.substr(0, 500);
ECHOION_LOG_DEBUG(std::format("Solver input (truncated): {}...", inputPreview));
} else {
ECHOION_LOG_DEBUG(std::format("Solver input: {}", inputPreview));
}
// Get global object and jsc function
JSValue global = JS_GetGlobalObject(context_);
JSValue jsc = JS_GetPropertyStr(context_, global, "jsc");
if (JS_IsUndefined(jsc)) {
ECHOION_LOG_ERROR("jsc function not found in QuickJS context");
JS_FreeValue(context_, global);
return false;
}
// Parse input JSON
JSValue inputVal = JS_ParseJSON(context_, inputStr.c_str(), inputStr.size(), "input");
if (JS_IsException(inputVal)) {
ECHOION_LOG_ERROR("Failed to parse input JSON");
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
return false;
}
// Call jsc function with error handling wrapper
// The solver can throw on malformed player JS, so we wrap in try/catch
// Also JSON.stringify the result since jsc returns a JS object, not a string
const char* wrapperJS = R"(
(function(jscFunc, input) {
try {
var result = jscFunc(input);
return JSON.stringify(result);
} catch (e) {
return JSON.stringify({
error: e.message || String(e),
stack: e.stack || '',
responses: []
});
}
})
)";
JSValue wrapper = JS_Eval(context_, wrapperJS, strlen(wrapperJS), "<wrapper>",
JS_EVAL_TYPE_GLOBAL);
if (JS_IsException(wrapper)) {
ECHOION_LOG_ERROR("Failed to compile error handling wrapper");
JS_FreeValue(context_, inputVal);
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
return false;
}
// Call the wrapper with jsc and input as arguments
JSValue args[] = { jsc, inputVal };
JSValue result = JS_Call(context_, wrapper, global, 2, args);
JS_FreeValue(context_, wrapper);
if (!JS_IsException(result)) {
// Check if result is null or undefined
if (JS_IsNull(result) || JS_IsUndefined(result)) {
ECHOION_LOG_ERROR("jsc returned null/undefined - solver may have failed silently");
} else {
const char* resultStr = JS_ToCString(context_, result);
if (resultStr) {
// Log first 500 chars of result for debugging
std::string_view resultView(resultStr);
if (resultView.size() > 500) resultView = resultView.substr(0, 500);
ECHOION_LOG_DEBUG(std::format("jsc result: {}", resultView));
try {
glz::generic output;
auto ec = glz::read_json(output, resultStr);
if (!ec) {
if (output.contains("preprocessed_player")) {
preprocessedPlayer_ = output["preprocessed_player"].get<std::string>();
hasPlayerJs_ = true;
ECHOION_LOG_INFO("Player JS preprocessed successfully");
} else if (output.contains("error")) {
ECHOION_LOG_ERROR(std::format("Solver error: {}",
output["error"].get<std::string>()));
} else {
ECHOION_LOG_ERROR(std::format("Unexpected solver output: {}", resultStr));
}
} else {
ECHOION_LOG_ERROR(std::format("Failed to parse solver JSON output: {}", resultStr));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Failed to parse solver output: {}", e.what()));
}
JS_FreeCString(context_, resultStr);
} else {
ECHOION_LOG_ERROR("jsc returned non-convertible value");
}
}
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
if (errorStr) {
ECHOION_LOG_ERROR(std::format("QuickJS execution error: {}", errorStr));
} else {
// Try to get exception details differently
ECHOION_LOG_ERROR("QuickJS execution failed (exception value not convertible to string)");
}
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
}
return hasPlayerJs_;
}
bool SignatureCipher::isReady() const {
std::lock_guard<std::mutex> lock(mutex_);
return initialized_ && solverInitialized_ && hasPlayerJs_;
}
bool SignatureCipher::isInitialized() const {
std::lock_guard<std::mutex> lock(mutex_);
return initialized_;
}
std::string SignatureCipher::decipher(std::string_view signatureCipher) {
if (!isReady() || signatureCipher.empty()) {
return std::string(signatureCipher);
}
// Parse the signature cipher parameters
// Format: s=ENCODED_SIG&sp=SIG_PARAM&url=ENCODED_URL
std::string url, signature, sigParam = "signature";
// Parse query string
auto parseQuery = [](std::string_view query) {
std::map<std::string, std::string> result;
std::regex re("([^&=]+)=([^&]*)");
std::string queryStr(query);
for (std::sregex_iterator it(queryStr.begin(), queryStr.end(), re), end;
it != end; ++it) {
std::string key = (*it)[1].str();
std::string value = (*it)[2].str();
// URL decode
auto decodeUrl = [](std::string_view input) -> std::string {
std::string out;
for (size_t i = 0; i < input.size(); ++i) {
if (input[i] == '%' && i + 2 < input.size()) {
int hex = std::stoi(std::string(input.substr(i + 1, 2)), nullptr, 16);
out += static_cast<char>(hex);
i += 2;
} else if (input[i] == '+') {
out += ' ';
} else {
out += input[i];
}
}
return out;
};
result[key] = decodeUrl(value);
}
return result;
};
auto params = parseQuery(signatureCipher);
if (params.count("s")) {
signature = params["s"];
}
if (params.count("sp")) {
sigParam = params["sp"];
}
if (params.count("url")) {
url = params["url"];
}
if (signature.empty()) {
return std::string(signatureCipher);
}
// Solve the signature challenge
std::string deciphered = solveChallenge(signature, "sig");
if (deciphered.empty()) {
return std::string(signatureCipher);
}
// Build final URL
if (!url.empty()) {
url += "&" + sigParam + "=" + deciphered;
return url;
}
return deciphered;
}
std::string SignatureCipher::solveChallenge(const std::string& challenge, const std::string& type) {
std::lock_guard<std::mutex> lock(mutex_);
if (!solverInitialized_ || preprocessedPlayer_.empty()) {
return "";
}
if (!context_) {
return "";
}
// Create input for challenge solving
glz::generic input;
input["type"] = "preprocessed";
input["preprocessed_player"] = preprocessedPlayer_;
glz::generic request;
request["type"] = type;
request["challenges"] = glz::array(challenge);
input["requests"] = glz::array(request);
std::string inputStr = glz::write_json(input).value();
// Get global object and jsc function
JSValue global = JS_GetGlobalObject(context_);
JSValue jsc = JS_GetPropertyStr(context_, global, "jsc");
if (JS_IsUndefined(jsc)) {
JS_FreeValue(context_, global);
return "";
}
// Parse input JSON
JSValue inputVal = JS_ParseJSON(context_, inputStr.c_str(), inputStr.size(), "input");
if (JS_IsException(inputVal)) {
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
return "";
}
// Call jsc function
JSValue args[] = { inputVal };
JSValue result = JS_Call(context_, jsc, global, 1, args);
std::string output;
if (!JS_IsException(result)) {
const char* resultStr = JS_ToCString(context_, result);
if (resultStr) {
try {
glz::generic jsonResult;
auto ec = glz::read_json(jsonResult, resultStr);
if (!ec && jsonResult.contains("responses")) {
auto& responses = jsonResult["responses"];
if (responses.is_array() && !responses.empty()) {
auto& firstResponse = responses[0];
if (firstResponse.contains("type") &&
firstResponse["type"].get<std::string>() == "result" &&
firstResponse.contains("data")) {
auto& data = firstResponse["data"];
if (data.contains(challenge)) {
output = data[challenge].get<std::string>();
}
}
}
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Failed to parse challenge response: {}", e.what()));
}
JS_FreeCString(context_, resultStr);
}
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_ERROR(std::format("Challenge solving error: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
}
JS_FreeValue(context_, result);
JS_FreeValue(context_, inputVal);
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
return output;
}
std::string SignatureCipher::decipherNParam(std::string_view nParam) {
if (!isReady() || nParam.empty()) {
return std::string(nParam);
}
return solveChallenge(std::string(nParam), "n");
}
void SignatureCipher::clear() {
std::lock_guard<std::mutex> lock(mutex_);
cleanupQuickJS();
playerJsCode_.clear();
preprocessedPlayer_.clear();
initialized_ = false;
solverInitialized_ = false;
hasPlayerJs_ = false;
}
std::filesystem::path SignatureCipher::getCacheDir() {
std::filesystem::path cacheDir;
// Use XDG_CACHE_HOME or fallback to ~/.cache
const char* xdgCache = std::getenv("XDG_CACHE_HOME");
if (xdgCache && *xdgCache) {
cacheDir = std::filesystem::path(xdgCache) / "echoion";
} else {
const char* home = std::getenv("HOME");
if (home && *home) {
cacheDir = std::filesystem::path(home) / ".cache" / "echoion";
} else {
// Fallback to current directory
cacheDir = std::filesystem::path(".echoion_cache");
}
}
std::error_code ec;
std::filesystem::create_directories(cacheDir, ec);
return cacheDir;
}
std::optional<std::string> SignatureCipher::downloadSolverLibrary(std::string_view url) {
// Simple curl-based download with redirect following
// -s: silent, -L: follow redirects, -f: fail on HTTP error, -m 30: timeout 30s
std::string cmd = std::format("curl -sLf -m 30 '{}' 2>&1", std::string(url));
ECHOION_LOG_DEBUG(std::format("Downloading: {}", url));
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe) {
ECHOION_LOG_WARNING(std::format("Failed to run curl for {}", url));
return std::nullopt;
}
std::string result;
char buffer[4096];
while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
result += buffer;
}
int status = pclose(pipe);
if (status != 0) {
ECHOION_LOG_WARNING(std::format("curl failed with status {} for {}", status, url));
return std::nullopt;
}
if (result.empty()) {
ECHOION_LOG_WARNING(std::format("Downloaded empty file from {}", url));
return std::nullopt;
}
return result;
}
void SignatureCipher::initSolver() {
if (runtime_ && context_) {
return; // Already initialized
}
// Create QuickJS runtime
runtime_ = JS_NewRuntime();
if (!runtime_) {
ECHOION_LOG_ERROR("Failed to create QuickJS runtime");
return;
}
// Set memory limit (256 MB - player JS processing needs more memory)
JS_SetMemoryLimit(runtime_, 256 * 1024 * 1024);
// Set max stack size (8 MB to handle deep AST recursion)
JS_SetMaxStackSize(runtime_, 8 * 1024 * 1024);
// Create context
context_ = JS_NewContext(runtime_);
if (!context_) {
ECHOION_LOG_ERROR("Failed to create QuickJS context");
JS_FreeRuntime(runtime_);
runtime_ = nullptr;
return;
}
// Get cache directory for storing solver libraries
auto cacheDir = getCacheDir();
auto corePath = cacheDir / "yt.solver.core.js";
auto libPath = cacheDir / "yt.solver.lib.js";
std::string coreCode;
std::string libCode;
// Try to load from cache first
std::error_code ec;
if (std::filesystem::exists(corePath, ec) && std::filesystem::exists(libPath, ec)) {
// Load from cache
std::ifstream coreFile(corePath);
std::ifstream libFile(libPath);
if (coreFile && libFile) {
coreCode = std::string((std::istreambuf_iterator<char>(coreFile)),
std::istreambuf_iterator<char>());
libCode = std::string((std::istreambuf_iterator<char>(libFile)),
std::istreambuf_iterator<char>());
ECHOION_LOG_INFO(std::format("Loaded solver libraries from cache (core: {} bytes, lib: {} bytes)",
coreCode.size(), libCode.size()));
// Validate content
if (coreCode.empty() || libCode.empty()) {
ECHOION_LOG_WARNING("Cached solver files are empty");
coreCode.clear();
libCode.clear();
}
}
}
// Download if not in cache or empty
if (coreCode.empty() || libCode.empty()) {
ECHOION_LOG_INFO("Downloading solver libraries from GitHub releases...");
// Download core
auto coreOpt = downloadSolverLibrary(
"https://github.com/yt-dlp/ejs/releases/latest/download/yt.solver.core.js");
// Download lib
auto libOpt = downloadSolverLibrary(
"https://github.com/yt-dlp/ejs/releases/latest/download/yt.solver.lib.js");
if (coreOpt && libOpt && !coreOpt->empty() && !libOpt->empty()) {
coreCode = *coreOpt;
libCode = *libOpt;
ECHOION_LOG_DEBUG(std::format("Downloaded core: {} bytes, lib: {} bytes",
coreCode.size(), libCode.size()));
// Log first 200 chars of core to verify it's valid
if (!coreCode.empty()) {
std::string_view preview(coreCode.c_str(), std::min(size_t(200), coreCode.size()));
ECHOION_LOG_DEBUG(std::format("Core preview: {}", preview));
}
// Validate downloaded content looks like JS
if (coreCode.find("function") == std::string::npos &&
coreCode.find("var") == std::string::npos) {
ECHOION_LOG_WARNING("Downloaded core.js doesn't look like valid JavaScript");
coreCode.clear();
}
if (libCode.find("function") == std::string::npos &&
libCode.find("var") == std::string::npos) {
ECHOION_LOG_WARNING("Downloaded lib.js doesn't look like valid JavaScript");
libCode.clear();
}
// Save to cache
if (!coreCode.empty() && !libCode.empty()) {
std::ofstream coreOut(corePath);
std::ofstream libOut(libPath);
if (coreOut && libOut) {
coreOut << coreCode;
libOut << libCode;
coreOut.close();
libOut.close();
ECHOION_LOG_INFO("Solver libraries cached successfully");
}
}
} else {
ECHOION_LOG_WARNING("Failed to download solver libraries");
}
}
// Load libraries into QuickJS
// Order matters: lib.js creates 'lib' object, then bridge, then core.js uses meriyah/astring
bool coreLoaded = false;
bool libLoaded = false;
bool bridgeLoaded = false;
// Step 1: Load lib.js (contains meriyah and astring)
if (!libCode.empty()) {
JSValue libResult = JS_Eval(context_, libCode.c_str(), libCode.size(),
"lib.js", JS_EVAL_TYPE_GLOBAL);
if (!JS_IsException(libResult)) {
libLoaded = true;
ECHOION_LOG_DEBUG("Solver lib.js loaded successfully");
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_WARNING(std::format("Failed to load lib solver: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
}
JS_FreeValue(context_, libResult);
}
// Step 2: Create bridge to expose meriyah and astring as global variables
if (libLoaded) {
const char* bridge = "var meriyah=lib.meriyah; var astring=lib.astring;";
JSValue bridgeResult = JS_Eval(context_, bridge, strlen(bridge), "bridge",
JS_EVAL_TYPE_GLOBAL);
if (!JS_IsException(bridgeResult)) {
bridgeLoaded = true;
ECHOION_LOG_DEBUG("Solver bridge created successfully");
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_ERROR(std::format("Failed to load bridge: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
}
JS_FreeValue(context_, bridgeResult);
}
// Step 3: Load core.js (uses meriyah and astring, creates jsc global function)
if (!coreCode.empty() && bridgeLoaded && libLoaded) {
JSValue coreResult = JS_Eval(context_, coreCode.c_str(), coreCode.size(),
"core.js", JS_EVAL_TYPE_GLOBAL);
if (!JS_IsException(coreResult)) {
coreLoaded = true;
ECHOION_LOG_DEBUG("Solver core.js loaded successfully");
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_ERROR(std::format("Failed to load core solver: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
}
JS_FreeValue(context_, coreResult);
}
// If core failed to load, we can't solve cipher signatures
if (!coreLoaded) {
ECHOION_LOG_WARNING("Loading fallback solver stub - ciphered videos won't work");
JSValue fallbackResult = JS_Eval(context_, FALLBACK_CORE_JS.data(),
FALLBACK_CORE_JS.size(), "fallback.js",
JS_EVAL_TYPE_GLOBAL);
JS_FreeValue(context_, fallbackResult);
cleanupQuickJS();
return;
}
// Verify jsc function exists in global scope
JSValue global = JS_GetGlobalObject(context_);
JSValue jsc = JS_GetPropertyStr(context_, global, "jsc");
bool hasJsc = !JS_IsUndefined(jsc);
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
if (!hasJsc) {
ECHOION_LOG_ERROR("jsc function not found after loading solver - ciphered videos won't work");
cleanupQuickJS();
return;
}
solverInitialized_ = true;
ECHOION_LOG_INFO("QuickJS solver initialized successfully (jsc function verified)");
}
std::optional<std::string> SignatureCipher::executeJS(std::string_view code, std::string_view filename) {
if (!context_) {
return std::nullopt;
}
JSValue result = JS_Eval(context_, code.data(), code.size(),
filename.data(), JS_EVAL_TYPE_GLOBAL);
if (JS_IsException(result)) {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_ERROR(std::format("JS execution error: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
JS_FreeValue(context_, result);
return std::nullopt;
}
std::string output;
const char* resultStr = JS_ToCString(context_, result);
if (resultStr) {
output = resultStr;
JS_FreeCString(context_, resultStr);
}
JS_FreeValue(context_, result);
return output;
}
void SignatureCipher::cleanupQuickJS() {
if (context_) {
JS_FreeContext(context_);
context_ = nullptr;
}
if (runtime_) {
JS_FreeRuntime(runtime_);
runtime_ = nullptr;
}
solverInitialized_ = false;
}
} // namespace Echoion::Core
+115
View File
@@ -0,0 +1,115 @@
#include "echoion/core/SubscriptionManager.hpp"
#include "echoion/core/Logger.hpp"
namespace Echoion::Core {
SubscriptionManager::SubscriptionManager() = default;
SubscriptionManager::~SubscriptionManager() {
shutdown();
}
Api::Result<void> SubscriptionManager::initialize(std::shared_ptr<Api::Database> database) {
std::lock_guard<std::mutex> lock(mutex_);
if (initialized_) {
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 (auto clientId : *result) {
subscribedClients_.insert(clientId);
}
}
initialized_ = true;
ECHOION_LOG_INFO(std::format("SubscriptionManager initialized ({} subscribers)",
subscribedClients_.size()));
return {};
}
void SubscriptionManager::shutdown() {
std::lock_guard<std::mutex> lock(mutex_);
if (!initialized_) {
return;
}
initialized_ = false;
database_.reset();
ECHOION_LOG_INFO("SubscriptionManager shutdown");
}
bool SubscriptionManager::subscribe(uint64_t clientId) {
std::lock_guard<std::mutex> lock(mutex_);
// Check if already subscribed (ensures uniqueness)
if (subscribedClients_.contains(clientId)) {
return false; // Already subscribed
}
// Add to database first
if (database_) {
auto result = database_->addSubscriber(clientId);
if (!result) {
ECHOION_LOG_ERROR(std::format("Failed to add subscriber {} to database: {}",
clientId, result.error().message));
return false;
}
}
subscribedClients_.insert(clientId);
ECHOION_LOG_INFO(std::format("Client {} subscribed", clientId));
return true;
}
bool SubscriptionManager::unsubscribe(uint64_t clientId) {
std::lock_guard<std::mutex> lock(mutex_);
bool removed = subscribedClients_.erase(clientId) > 0;
if (removed) {
// Remove from database
if (database_) {
auto result = database_->removeSubscriber(clientId);
if (!result) {
ECHOION_LOG_ERROR(std::format("Failed to remove subscriber {} from database: {}",
clientId, result.error().message));
}
}
ECHOION_LOG_INFO(std::format("Client {} unsubscribed", clientId));
}
return removed;
}
bool SubscriptionManager::isSubscribed(uint64_t clientId) const {
std::lock_guard<std::mutex> lock(mutex_);
return subscribedClients_.contains(clientId);
}
std::set<uint64_t> SubscriptionManager::getSubscribedClients() const {
std::lock_guard<std::mutex> lock(mutex_);
return subscribedClients_;
}
bool SubscriptionManager::hasSubscribers() const {
std::lock_guard<std::mutex> lock(mutex_);
return !subscribedClients_.empty();
}
size_t SubscriptionManager::getSubscriberCount() const {
std::lock_guard<std::mutex> lock(mutex_);
return subscribedClients_.size();
}
} // namespace Echoion::Core
+373
View File
@@ -0,0 +1,373 @@
#include "echoion/core/YouTubeClient.hpp"
#include "echoion/core/Logger.hpp"
#include <glaze/glaze.hpp>
#include <format>
#include <algorithm>
#include <regex>
namespace Echoion::Core {
YouTubeClient::YouTubeClient(std::shared_ptr<NetworkClient> networkClient)
: networkClient_(std::move(networkClient))
, ytDlpManager_(std::make_unique<YtDlpManager>(networkClient_)) {
}
YouTubeClient::~YouTubeClient() {
shutdown();
}
Api::Result<void> YouTubeClient::initialize() {
if (initialized_) return {};
ECHOION_LOG_INFO("Initializing YouTube client...");
// Initialize yt-dlp manager (downloads if needed)
auto result = ytDlpManager_->initialize();
if (!result) {
return result;
}
initialized_ = true;
ECHOION_LOG_INFO("YouTube client initialized successfully");
return {};
}
void YouTubeClient::setCookiesPath(const std::string& path) {
if (ytDlpManager_) {
ytDlpManager_->setCookiesPath(path);
}
}
void YouTubeClient::setCookiesFromBrowser(const std::string& browser) {
if (ytDlpManager_) {
ytDlpManager_->setCookiesFromBrowser(browser);
}
}
void YouTubeClient::shutdown() {
initialized_ = false;
}
bool YouTubeClient::isAvailable() const {
return ytDlpManager_ && ytDlpManager_->isAvailable();
}
std::string YouTubeClient::getYtDlpVersion() const {
if (!ytDlpManager_) return "";
return ytDlpManager_->getVersion();
}
Api::Result<void> YouTubeClient::updateYtDlp() {
if (!ytDlpManager_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"yt-dlp manager not initialized"));
}
return ytDlpManager_->update();
}
Api::Result<std::string> YouTubeClient::getAudioStreamUrl(std::string_view videoId) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"YouTubeClient not initialized"));
}
if (!ytDlpManager_->isAvailable()) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"yt-dlp not available"));
}
ECHOION_LOG_INFO(std::format("Getting audio stream URL for video: {}", videoId));
// Use yt-dlp to get best audio URL - prefer AAC (m4a) over Opus (webm)
// 140 = AAC 128kbps (m4a), 251 = Opus 160kbps (webm)
std::string url = std::format("https://www.youtube.com/watch?v={}", videoId);
// Fallback: try any audio format
ECHOION_LOG_INFO("Trying any audio format...");
std::string result = ytDlpManager_->execute({
url,
"-f", "bestaudio/251/140",
"-g",
"--no-warnings"
});
if (!result.empty() && result.back() == '\n') {
result.pop_back();
}
if (!result.empty() && result.find("http") == 0) {
ECHOION_LOG_INFO("Successfully got audio URL from yt-dlp (fallback)");
return result;
}
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
"Failed to get audio URL from yt-dlp"));
}
Api::Result<std::string> YouTubeClient::getStreamUrl(std::string_view videoId) {
return getAudioStreamUrl(videoId);
}
Api::Result<Api::TrackInfo> YouTubeClient::getVideoInfo(std::string_view videoId) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"YouTubeClient not initialized"));
}
if (!ytDlpManager_->isAvailable()) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"yt-dlp not available"));
}
std::string url = std::format("https://www.youtube.com/watch?v={}", videoId);
std::string jsonStr = ytDlpManager_->execute({
url,
"-J",
"--no-warnings"
});
if (jsonStr.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"yt-dlp failed to get video info"));
}
try {
glz::generic json;
if (glz::read_json(json, jsonStr)) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
"Failed to parse yt-dlp output"));
}
Api::TrackInfo info;
if (json.contains("id")) info.id = json["id"].get<std::string>();
if (json.contains("title")) info.title = json["title"].get<std::string>();
if (json.contains("uploader")) info.artist = json["uploader"].get<std::string>();
if (json.contains("duration")) {
info.duration = std::chrono::seconds(static_cast<int64_t>(json["duration"].get<double>()));
}
if (json.contains("thumbnail")) info.thumbnailUrl = json["thumbnail"].get<std::string>();
// Set originalUrl so we can extract video ID later for streaming
info.originalUrl = url;
info.source = Api::TrackSource::YouTube;
return info;
} catch (const std::exception& e) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
std::format("Exception parsing yt-dlp output: {}", e.what())));
}
}
Api::Result<Api::SearchResult> YouTubeClient::search(std::string_view query,
std::optional<std::string> pageToken) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"YouTubeClient not initialized"));
}
if (!ytDlpManager_->isAvailable()) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"yt-dlp not available"));
}
// yt-dlp search format: ytsearch5:query
std::string searchQuery = std::format("ytsearch5:{}", query);
std::string jsonStr = ytDlpManager_->execute({
searchQuery,
"-J",
"--flat-playlist",
"--no-warnings"
});
if (jsonStr.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"yt-dlp search failed"));
}
try {
glz::generic json;
if (glz::read_json(json, jsonStr)) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
"Failed to parse yt-dlp search output"));
}
Api::SearchResult result;
result.query = std::string(query);
if (json.contains("entries") && json["entries"].is_array()) {
for (const auto& entry : json["entries"].get<std::vector<glz::generic>>()) {
if (!entry.contains("id")) continue;
Api::TrackInfo track;
track.id = entry["id"].get<std::string>();
if (entry.contains("title")) track.title = entry["title"].get<std::string>();
if (entry.contains("uploader")) track.artist = entry["uploader"].get<std::string>();
if (entry.contains("duration")) {
track.duration = std::chrono::seconds(static_cast<int64_t>(entry["duration"].get<double>()));
}
if (entry.contains("thumbnail")) track.thumbnailUrl = entry["thumbnail"].get<std::string>();
// Set originalUrl so we can extract video ID later for streaming
track.originalUrl = std::format("https://www.youtube.com/watch?v={}", track.id);
track.source = Api::TrackSource::YouTube;
result.tracks.push_back(track);
}
}
result.totalResults = result.tracks.size();
return result;
} catch (const std::exception& e) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
std::format("Exception parsing yt-dlp search: {}", e.what())));
}
}
Api::Result<Api::PlaylistInfo> YouTubeClient::getPlaylist(std::string_view playlistId) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"YouTubeClient not initialized"));
}
if (!ytDlpManager_->isAvailable()) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"yt-dlp not available"));
}
std::string url = std::format("https://www.youtube.com/playlist?list={}", playlistId);
std::string jsonStr = ytDlpManager_->execute({
url,
"-J",
"--flat-playlist",
"--no-warnings"
});
if (jsonStr.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"yt-dlp playlist fetch failed"));
}
try {
glz::generic json;
if (glz::read_json(json, jsonStr)) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
"Failed to parse yt-dlp playlist output"));
}
Api::PlaylistInfo info;
if (json.contains("title")) info.name = json["title"].get<std::string>();
if (json.contains("id")) info.id = json["id"].get<std::string>();
if (json.contains("entries") && json["entries"].is_array()) {
for (const auto& entry : json["entries"].get<std::vector<glz::generic>>()) {
if (!entry.contains("id")) continue;
Api::TrackInfo track;
track.id = entry["id"].get<std::string>();
if (entry.contains("title")) track.title = entry["title"].get<std::string>();
if (entry.contains("uploader")) track.artist = entry["uploader"].get<std::string>();
if (entry.contains("duration")) {
track.duration = std::chrono::seconds(static_cast<int64_t>(entry["duration"].get<double>()));
}
// Set originalUrl so we can extract video ID later for streaming
track.originalUrl = std::format("https://www.youtube.com/watch?v={}", track.id);
track.source = Api::TrackSource::YouTube;
info.tracks.push_back(track);
}
}
return info;
} catch (const std::exception& e) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
std::format("Exception parsing yt-dlp playlist: {}", e.what())));
}
}
std::optional<std::string> YouTubeClient::extractVideoId(std::string_view url) {
std::string url_str(url);
// Handle faumaray.ru redirects using NetworkClient
if (url_str.find("faumaray.ru") != std::string::npos && networkClient_) {
ECHOION_LOG_DEBUG(std::format("Following redirect for: {}", url_str));
std::vector<Api::HttpHeader> headers = {
{"User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
};
// Make request without following redirects to get the Location header
auto response = networkClient_->get(url_str, headers);
if (response) {
// Check if we got a redirect
if (response->isRedirect()) {
auto location = response->getHeader("location");
if (location.has_value()) {
ECHOION_LOG_DEBUG(std::format("Redirected to: {}", *location));
url_str = *location;
}
} else if (response->isSuccess()) {
// Some shorteners might return the target in the body or we might need
// to look at the URL after any automatic redirect following
// Try to extract from current URL or response
auto finalUrl = response->getHeader("x-final-url"); // Some clients add this
if (finalUrl.has_value()) {
url_str = *finalUrl;
}
}
}
}
// More comprehensive regex patterns for YouTube URLs
static const std::regex watch_pattern(
R"((?:https?://)?(?:www\.)?youtube\.com/watch\?[^\s]*v=([a-zA-Z0-9_-]{11})(?:&[^\s]*)?)",
std::regex::icase);
static const std::regex short_pattern(
R"((?:https?://)?(?:www\.)?youtu\.be/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?)",
std::regex::icase);
static const std::regex embed_pattern(
R"((?:https?://)?(?:www\.)?youtube\.com/embed/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?)",
std::regex::icase);
static const std::regex shorts_pattern(
R"((?:https?://)?(?:www\.)?youtube\.com/shorts/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?)",
std::regex::icase);
// Also match just the video ID (11 characters)
static const std::regex id_only_pattern(
R"(^([a-zA-Z0-9_-]{11})$)",
std::regex::icase);
std::smatch match;
if (std::regex_search(url_str, match, watch_pattern) ||
std::regex_search(url_str, match, short_pattern) ||
std::regex_search(url_str, match, embed_pattern) ||
std::regex_search(url_str, match, shorts_pattern) ||
std::regex_search(url_str, match, id_only_pattern)) {
return match[1].str();
}
return std::nullopt;
}
std::optional<std::string> YouTubeClient::extractPlaylistId(std::string_view url) {
std::string urlStr(url);
std::smatch match;
if (std::regex_search(urlStr, match, std::regex(R"(list=([a-zA-Z0-9_-]+))"))) {
return match[1].str();
}
return std::nullopt;
}
bool YouTubeClient::isYouTubeUrl(std::string_view url) {
return url.find("youtube.com") != std::string::npos || url.find("youtu.be") != std::string::npos;
}
} // namespace Echoion::Core
+456
View File
@@ -0,0 +1,456 @@
#include "echoion/core/YtDlpManager.hpp"
#include "echoion/core/Logger.hpp"
#include <glaze/glaze.hpp>
#include <format>
#include <fstream>
#include <cstdlib>
#include <array>
#include <chrono>
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Echoion::Core {
YtDlpManager::YtDlpManager(std::shared_ptr<NetworkClient> networkClient)
: networkClient_(std::move(networkClient)) {
}
YtDlpManager::~YtDlpManager() = default;
std::filesystem::path YtDlpManager::getStorageDir() const {
// Store in ~/.local/share/echoion/yt-dlp on Linux
// or %APPDATA%/echoion/yt-dlp on Windows
// or ~/Library/Application Support/echoion/yt-dlp on macOS
std::filesystem::path homeDir;
#ifdef _WIN32
const char* appData = std::getenv("APPDATA");
if (appData) {
homeDir = appData;
} else {
homeDir = std::filesystem::temp_directory_path();
}
return homeDir / "echoion" / "yt-dlp";
#else
const char* home = std::getenv("HOME");
if (home) {
homeDir = home;
} else {
homeDir = std::filesystem::temp_directory_path();
}
#ifdef __APPLE__
return homeDir / "Library" / "Application Support" / "echoion" / "yt-dlp";
#else
return homeDir / ".local" / "share" / "echoion" / "yt-dlp";
#endif
#endif
}
std::string YtDlpManager::getExecutableName() const {
#ifdef _WIN32
return "yt-dlp.exe";
#else
return "yt-dlp";
#endif
}
std::string YtDlpManager::getDownloadUrl() const {
#ifdef _WIN32
return std::string(YTDLP_DOWNLOAD_WINDOWS);
#elif defined(__APPLE__)
return std::string(YTDLP_DOWNLOAD_MACOS);
#else
return std::string(YTDLP_DOWNLOAD_LINUX);
#endif
}
std::filesystem::path YtDlpManager::getExecutablePath() const {
if (!executablePath_.empty()) {
return executablePath_;
}
return getStorageDir() / getExecutableName();
}
bool YtDlpManager::isAvailable() const {
return std::filesystem::exists(getExecutablePath());
}
Api::Result<void> YtDlpManager::initialize() {
{
std::lock_guard<std::mutex> lock(mutex_);
if (initialized_) {
return {};
}
ECHOION_LOG_INFO("Initializing yt-dlp manager...");
// Create storage directory if needed
std::filesystem::path storageDir = getStorageDir();
ECHOION_LOG_DEBUG(std::format("yt-dlp storage dir: {}", storageDir.string()));
if (!std::filesystem::exists(storageDir)) {
ECHOION_LOG_INFO("Creating yt-dlp storage directory...");
try {
std::filesystem::create_directories(storageDir);
} catch (const std::exception& e) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
std::format("Failed to create yt-dlp storage directory: {}", e.what())));
}
}
executablePath_ = storageDir / getExecutableName();
ECHOION_LOG_DEBUG(std::format("yt-dlp executable path: {}", executablePath_.string()));
// Check if yt-dlp exists
bool exists = std::filesystem::exists(executablePath_);
ECHOION_LOG_DEBUG(std::format("yt-dlp exists: {}", exists));
if (!exists) {
ECHOION_LOG_INFO("yt-dlp not found, downloading...");
auto result = downloadYtDlp();
if (!result) {
return result;
}
} else if (shouldUpdate()) {
ECHOION_LOG_INFO("yt-dlp may be outdated, checking for updates...");
// Try to update, but don't fail if update fails
auto result = update();
if (!result) {
ECHOION_LOG_WARNING(std::format("yt-dlp update failed: {}", result.error().toString()));
}
}
} // Release lock before calling getVersion() to avoid deadlock with getCookieArgs()
// Verify it works (outside lock to prevent deadlock with execute()->getCookieArgs())
ECHOION_LOG_INFO("Checking yt-dlp version...");
std::string version = getVersion();
if (version.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"yt-dlp executable not working"));
}
ECHOION_LOG_INFO(std::format("yt-dlp ready: {}", version));
std::lock_guard<std::mutex> lock(mutex_);
initialized_ = true;
return {};
}
Api::Result<void> YtDlpManager::downloadYtDlp() {
if (!networkClient_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Network client not available"));
}
std::string downloadUrl = getDownloadUrl();
ECHOION_LOG_INFO(std::format("Downloading yt-dlp from: {}", downloadUrl));
std::vector<Api::HttpHeader> headers = {
{"User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"}
};
// Follow redirects manually (GitHub releases use 302 redirects)
Api::HttpResponse response;
int redirectCount = 0;
constexpr int maxRedirects = 5;
while (redirectCount < maxRedirects) {
auto result = networkClient_->get(downloadUrl, headers);
if (!result) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
std::format("Failed to download yt-dlp: {}", result.error().message)));
}
response = std::move(*result);
// Check for redirect (3xx status codes)
if (response.statusCode >= 300 && response.statusCode < 400) {
auto location = response.getHeader("location");
if (!location.has_value()) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"Redirect response missing Location header"));
}
// Handle relative URLs
std::string newUrl = *location;
if (newUrl.starts_with("/")) {
// Relative to host - extract host from current URL
auto pos = downloadUrl.find("://");
if (pos != std::string::npos) {
auto pathStart = downloadUrl.find("/", pos + 3);
std::string base = (pathStart != std::string::npos)
? downloadUrl.substr(0, pathStart)
: downloadUrl;
newUrl = base + newUrl;
}
}
ECHOION_LOG_INFO(std::format("Following redirect (HTTP {}): {}",
response.statusCode, newUrl));
downloadUrl = newUrl;
redirectCount++;
continue;
}
break;
}
if (!response.isSuccess()) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
std::format("Failed to download yt-dlp: HTTP {}", response.statusCode)));
}
ECHOION_LOG_INFO(std::format("Downloaded {} bytes", response.body.size()));
// Write to file
try {
std::ofstream file(executablePath_, std::ios::binary);
if (!file) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Failed to open yt-dlp file for writing"));
}
file.write(response.body.data(), response.body.size());
file.close();
} catch (const std::exception& e) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
std::format("Failed to write yt-dlp file: {}", e.what())));
}
// Make executable on Unix
#ifndef _WIN32
auto execResult = makeExecutable();
if (!execResult) {
return execResult;
}
#endif
// Write timestamp file for update checking
try {
std::ofstream tsFile(getStorageDir() / ".last_update");
if (tsFile) {
auto now = std::chrono::system_clock::now();
auto timestamp = std::chrono::system_clock::to_time_t(now);
tsFile << timestamp;
}
} catch (...) {}
ECHOION_LOG_INFO("yt-dlp downloaded successfully");
return {};
}
Api::Result<void> YtDlpManager::makeExecutable() {
#ifdef _WIN32
return {}; // Windows doesn't need this
#else
if (chmod(executablePath_.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Failed to make yt-dlp executable"));
}
return {};
#endif
}
bool YtDlpManager::shouldUpdate() const {
try {
std::filesystem::path tsPath = getStorageDir() / ".last_update";
if (!std::filesystem::exists(tsPath)) {
return true;
}
std::ifstream tsFile(tsPath);
if (!tsFile) {
return true;
}
std::time_t lastUpdate;
tsFile >> lastUpdate;
auto now = std::chrono::system_clock::now();
auto last = std::chrono::system_clock::from_time_t(lastUpdate);
auto diff = std::chrono::duration_cast<std::chrono::hours>(now - last).count();
// Update if older than 7 days
return diff > (7 * 24);
} catch (...) {
return true;
}
}
Api::Result<void> YtDlpManager::update() {
std::lock_guard<std::mutex> lock(mutex_);
ECHOION_LOG_INFO("Updating yt-dlp...");
// Backup current version
std::filesystem::path backupPath = executablePath_.string() + ".backup";
try {
if (std::filesystem::exists(executablePath_)) {
std::filesystem::copy_file(executablePath_, backupPath,
std::filesystem::copy_options::overwrite_existing);
}
} catch (...) {}
// Download new version
auto result = downloadYtDlp();
if (!result) {
// Restore backup if available
try {
if (std::filesystem::exists(backupPath)) {
std::filesystem::copy_file(backupPath, executablePath_,
std::filesystem::copy_options::overwrite_existing);
}
} catch (...) {}
return result;
}
// Remove backup
try {
std::filesystem::remove(backupPath);
} catch (...) {}
// Verify new version works
std::string version = getVersion();
if (version.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Updated yt-dlp not working"));
}
ECHOION_LOG_INFO(std::format("yt-dlp updated to: {}", version));
return {};
}
std::string YtDlpManager::getVersion() const {
if (!std::filesystem::exists(executablePath_)) {
ECHOION_LOG_WARNING("yt-dlp executable not found for version check");
return "";
}
ECHOION_LOG_DEBUG("Executing yt-dlp --version...");
std::string result = execute({"--version"});
ECHOION_LOG_DEBUG(std::format("yt-dlp --version output: '{}'", result));
// Remove trailing newline
if (!result.empty() && result.back() == '\n') {
result.pop_back();
}
return result;
}
void YtDlpManager::setCookiesPath(const std::string& path) {
std::lock_guard<std::mutex> lock(mutex_);
cookiesPath_ = path;
ECHOION_LOG_INFO(std::format("yt-dlp cookies path set to: {}", path));
}
void YtDlpManager::setCookiesFromBrowser(const std::string& browser) {
std::lock_guard<std::mutex> lock(mutex_);
cookiesFromBrowser_ = browser;
ECHOION_LOG_INFO(std::format("yt-dlp will use cookies from browser: {}", browser));
}
std::vector<std::string> YtDlpManager::getCookieArgs() const {
std::lock_guard<std::mutex> lock(mutex_);
std::vector<std::string> cookieArgs;
if (cookiesFromBrowser_.has_value()) {
cookieArgs.push_back("--cookies-from-browser");
cookieArgs.push_back(*cookiesFromBrowser_);
} else if (cookiesPath_.has_value()) {
cookieArgs.push_back("--cookies");
cookieArgs.push_back(*cookiesPath_);
}
return cookieArgs;
}
std::string YtDlpManager::execute(const std::vector<std::string>& args) const {
if (!std::filesystem::exists(executablePath_)) {
return "";
}
std::string cmd = executablePath_.string();
// Add cookie arguments first
auto cookieArgs = getCookieArgs();
for (const auto& arg : cookieArgs) {
cmd += " ";
// Simple escaping
if (arg.find(' ') != std::string::npos ||
arg.find('"') != std::string::npos ||
arg.find('\\') != std::string::npos) {
std::string escaped;
for (char c : arg) {
if (c == '"') escaped += "\\";
escaped += c;
}
cmd += "\"" + escaped + "\"";
} else {
cmd += arg;
}
}
for (const auto& arg : args) {
cmd += " ";
// Simple escaping - wrap in quotes if contains spaces or special chars
if (arg.find(' ') != std::string::npos ||
arg.find('"') != std::string::npos ||
arg.find('\\') != std::string::npos) {
// Escape existing quotes and wrap
std::string escaped;
for (char c : arg) {
if (c == '"') escaped += "\\";
escaped += c;
}
cmd += "\"" + escaped + "\"";
} else {
cmd += arg;
}
}
// Suppress stderr
#ifdef _WIN32
cmd += " 2>nul";
#else
cmd += " 2>/dev/null";
#endif
// Add timeout to prevent hanging (10 seconds for version check, 60 for download)
bool isVersionCheck = (args.size() == 1 && args[0] == "--version");
int timeoutSec = isVersionCheck ? 10 : 60;
#ifdef __linux__
cmd = std::format("timeout {} {}", timeoutSec, cmd);
#elif defined(__APPLE__)
cmd = std::format("gtimeout {} {} 2>/dev/null || {}", timeoutSec, cmd, cmd);
#endif
ECHOION_LOG_DEBUG(std::format("Executing yt-dlp: {}", cmd));
std::array<char, 8192> buffer;
std::string result;
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe) {
ECHOION_LOG_WARNING("Failed to open pipe for yt-dlp execution");
return "";
}
while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
result += buffer.data();
}
pclose(pipe);
return result;
}
} // namespace Echoion::Core