Compare commits
54
Commits
a583c17916
...
v2.0.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6555d4c69 | ||
|
|
c2ec314eb9 | ||
|
|
16d9a667eb | ||
|
|
d456257d0c | ||
|
|
cbb178d83d | ||
|
|
29c7e60733 | ||
|
|
4b6f3165b2 | ||
|
|
b08f8ad29b | ||
|
|
915e2ab981 | ||
|
|
9637f1eef7 | ||
|
|
a277f2102b | ||
|
|
dfbbdaaf01 | ||
|
|
7975f2b38e | ||
|
|
9f06af6c80 | ||
|
|
39aff68d8d | ||
|
|
01362d2e51 | ||
|
|
5c036d91fb | ||
|
|
d146f11f02 | ||
|
|
df99b6ea7f | ||
|
|
b9c6c5dbc9 | ||
|
|
352101e657 | ||
|
|
5796ccbc74 | ||
|
|
7e3081ecd1 | ||
|
|
1f26927ad6 | ||
|
|
583e4e752d | ||
|
|
499143050b | ||
|
|
1efdbe0771 | ||
|
|
622335260f | ||
|
|
0e090168e8 | ||
|
|
30884ad0b5 | ||
|
|
0779fdcf20 | ||
|
|
75ee32a24b | ||
|
|
2d7651c308 | ||
|
|
0e08ccaefa | ||
|
|
f7553d10d3 | ||
|
|
9d56a6ff01 | ||
|
|
3af9aecbec | ||
|
|
ef094c0d78 | ||
|
|
da708fa9bb | ||
|
|
5775c522eb | ||
|
|
51f1651c18 | ||
|
|
a9ab0d6b75 | ||
|
|
6c7e6a170f | ||
|
|
23759899bb | ||
|
|
f8757d6040 | ||
|
|
17f31ea3e0 | ||
|
|
aedd3e1692 | ||
|
|
32fbffa171 | ||
|
|
9ff27483ab | ||
|
|
914eb0a232 | ||
|
|
00759450ff | ||
|
|
d74a69aa34 | ||
|
|
2bdb63766d | ||
|
|
53801f2b53 |
No files matched your search
@@ -0,0 +1,55 @@
|
||||
name: Independent component release
|
||||
on:
|
||||
push:
|
||||
tags: [v*]
|
||||
schedule:
|
||||
- cron: '17 2 * * *'
|
||||
workflow_dispatch:
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: echoion-release-serial
|
||||
steps:
|
||||
- name: Check out component
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: Check out pinned public release tools
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
repository: Void/Echoion
|
||||
ref: ${{ vars.ECHOION_RELEASE_TOOLS_REF }}
|
||||
path: .echoion-release-tools
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: Build, publish, and merge feed transaction
|
||||
shell: bash
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.COMPONENT_OBJECT_STORAGE_ACCESS_KEY }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.COMPONENT_OBJECT_STORAGE_SECRET_KEY }}
|
||||
AWS_DEFAULT_REGION: ${{ vars.COMPONENT_OBJECT_STORAGE_REGION }}
|
||||
ECHOION_COMPONENT_SSH_KEY: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
|
||||
ECHOION_DISTRIBUTION_BACKEND: ${{ vars.ECHOION_DISTRIBUTION_BACKEND }}
|
||||
ECHOION_DISTRIBUTION_BASE_URL: ${{ vars.ECHOION_DISTRIBUTION_BASE_URL }}
|
||||
ECHOION_FEED_BASE_URL: ${{ vars.ECHOION_FEED_BASE_URL }}
|
||||
ECHOION_FEED_COMMIT_SIGNING_KEY: ${{ secrets.RELEASE_FEED_GIT_SIGNING_KEY }}
|
||||
ECHOION_FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_KEY }}
|
||||
ECHOION_FEED_REPOSITORY: ssh://gitea@git.faumaray.ru/Void/Echoion.git
|
||||
ECHOION_FEED_SIGNING_KEY_ID: ${{ vars.ECHOION_FEED_SIGNING_KEY_ID }}
|
||||
ECHOION_OBJECT_STORAGE_BUCKET: ${{ vars.COMPONENT_OBJECT_STORAGE_BUCKET }}
|
||||
ECHOION_OBJECT_STORAGE_ENDPOINT: ${{ vars.COMPONENT_OBJECT_STORAGE_ENDPOINT }}
|
||||
ECHOION_OBJECT_STORAGE_PREFIX: ${{ vars.COMPONENT_OBJECT_STORAGE_PREFIX }}
|
||||
ECHOION_RELEASE_TAG_ALLOWED_SIGNERS: ${{ secrets.RELEASE_TAG_ALLOWED_SIGNERS }}
|
||||
GITEA_API_URL: ${{ gitea.api_url }}
|
||||
GITEA_EVENT_NAME: ${{ gitea.event_name }}
|
||||
GITEA_REF_NAME: ${{ gitea.ref_name }}
|
||||
GITEA_RUN_NUMBER: ${{ gitea.run_number }}
|
||||
GITEA_SHA: ${{ gitea.sha }}
|
||||
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
|
||||
RELEASE_TOOLS_REF: ${{ vars.ECHOION_RELEASE_TOOLS_REF }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
[[ "$RELEASE_TOOLS_REF" =~ ^[0-9a-f]{40}$ ]]
|
||||
test "$(git -C .echoion-release-tools rev-parse HEAD)" = "$RELEASE_TOOLS_REF"
|
||||
.echoion-release-tools/scripts/release-component.sh component.release.json
|
||||
+299
-52
@@ -1,48 +1,107 @@
|
||||
cmake_minimum_required(VERSION 3.28)
|
||||
project(EchoionCore VERSION 1.0.0 LANGUAGES CXX)
|
||||
cmake_minimum_required(VERSION 4.0.0)
|
||||
if(NOT DEFINED ECHOION_PRODUCT_VERSION)
|
||||
set(ECHOION_PRODUCT_VERSION 0.0.0)
|
||||
endif()
|
||||
if(NOT DEFINED ECHOION_COMPONENT_VERSION)
|
||||
set(ECHOION_COMPONENT_VERSION "${ECHOION_PRODUCT_VERSION}")
|
||||
endif()
|
||||
project(EchoionCore VERSION "${ECHOION_COMPONENT_VERSION}" LANGUAGES CXX)
|
||||
|
||||
set(ECHOION_LICENSE_ROOT_KEY_ID "" CACHE STRING
|
||||
"Pinned EchoionLicensing root key id")
|
||||
set(ECHOION_LICENSE_ROOT_PUBLIC_KEY "" CACHE STRING
|
||||
"Pinned base64url Ed25519 EchoionLicensing root public key")
|
||||
set(ECHOION_PRODUCT_VERSION "${ECHOION_COMPONENT_VERSION}" CACHE STRING
|
||||
"Echoion product version bound into licensing decisions")
|
||||
set(ECHOION_BUILD_SIGNATURE "development:${ECHOION_COMPONENT_VERSION}" CACHE STRING
|
||||
"Immutable signed-build identifier used by licensing revocation")
|
||||
option(ECHOION_ALLOW_DEVELOPMENT_LICENSE_KEYS
|
||||
"Allow opt-in trust keys from config (never enable for releases)" OFF)
|
||||
|
||||
if(PROJECT_IS_TOP_LEVEL)
|
||||
set(BUILD_SHARED_LIBS ON CACHE BOOL
|
||||
"Build shared component dependencies" FORCE)
|
||||
file(DOWNLOAD
|
||||
https://github.com/cpm-cmake/CPM.cmake/releases/download/v0.40.8/CPM.cmake
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake"
|
||||
EXPECTED_HASH
|
||||
SHA256=78ba32abdf798bc616bab7c73aac32a17bbd7b06ad9e26a6add69de8f3ae4791)
|
||||
include("${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake")
|
||||
CPMAddPackage(
|
||||
NAME Void
|
||||
GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/voidlibrary.git
|
||||
GIT_TAG main
|
||||
OPTIONS "VOID_ENABLE_TESTING OFF")
|
||||
CPMAddPackage(
|
||||
NAME EchoionApi
|
||||
GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/echoionapi.git
|
||||
GIT_TAG main)
|
||||
option(BUILD_TESTS "Build component tests" ON)
|
||||
if(BUILD_TESTS)
|
||||
enable_testing()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
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
|
||||
file(GLOB_RECURSE CORE_SOURCES
|
||||
CONFIGURE_DEPENDS
|
||||
"src/**.cpp"
|
||||
)
|
||||
add_library(EchoionCore SHARED ${CORE_SOURCES})
|
||||
target_compile_definitions(EchoionCore PRIVATE
|
||||
ECHOION_CORE_VERSION="${ECHOION_COMPONENT_VERSION}"
|
||||
ECHOION_MODULE_BUILD
|
||||
ECHOION_COMPONENT_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
|
||||
ECHOION_COMPONENT_VERSION_MINOR=${PROJECT_VERSION_MINOR}
|
||||
ECHOION_COMPONENT_VERSION_PATCH=${PROJECT_VERSION_PATCH}
|
||||
ECHOION_LICENSE_ROOT_KEY_ID="${ECHOION_LICENSE_ROOT_KEY_ID}"
|
||||
ECHOION_LICENSE_ROOT_PUBLIC_KEY="${ECHOION_LICENSE_ROOT_PUBLIC_KEY}"
|
||||
ECHOION_PRODUCT_VERSION="${ECHOION_PRODUCT_VERSION}"
|
||||
ECHOION_BUILD_SIGNATURE="${ECHOION_BUILD_SIGNATURE}")
|
||||
if(ECHOION_ALLOW_DEVELOPMENT_LICENSE_KEYS)
|
||||
target_compile_definitions(EchoionCore PRIVATE
|
||||
ECHOION_ALLOW_DEVELOPMENT_LICENSE_KEYS)
|
||||
endif()
|
||||
|
||||
add_library(Echoion::Core ALIAS EchoionCore)
|
||||
|
||||
target_include_directories(EchoionCore PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/../EchoionApi/include/echoion/api/config>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_link_libraries(EchoionCore PUBLIC Echoion::Api)
|
||||
# Core uses all API modules
|
||||
target_link_libraries(EchoionCore PUBLIC
|
||||
Echoion::ApiBase
|
||||
Echoion::ApiAudio
|
||||
Echoion::ApiTrack
|
||||
Echoion::ApiNetwork
|
||||
Echoion::ApiPlugin
|
||||
Echoion::ApiConfig
|
||||
Echoion::ApiRpc
|
||||
Echoion::ApiYouTube
|
||||
Echoion::ApiLogger
|
||||
Echoion::ApiEventBus
|
||||
Echoion::ApiDatabase
|
||||
Echoion::ApiOpaque
|
||||
Echoion::ApiPluginInterface
|
||||
Echoion::ApiCoreInterface
|
||||
Echoion::ApiUtils
|
||||
Echoion::ApiModuleAbi
|
||||
)
|
||||
|
||||
find_package(glaze CONFIG REQUIRED)
|
||||
find_package(PkgConfig REQUIRED)
|
||||
pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET
|
||||
libavformat
|
||||
libavcodec
|
||||
libswresample
|
||||
libavutil
|
||||
libavformat>=59
|
||||
libavcodec>=59
|
||||
libswresample>=4
|
||||
libavutil>=57
|
||||
)
|
||||
|
||||
CPMAddPackage(
|
||||
@@ -51,35 +110,96 @@ CPMAddPackage(
|
||||
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")
|
||||
# quickjs-ng v0.11.0 compiles its C sources with -Werror, which trips newer GCC
|
||||
# diagnostics (e.g. -Wmaybe-uninitialized / -Wdiscarded-qualifiers under GCC 16+).
|
||||
# It is a vendored third-party dependency, so relax -Werror on every target it
|
||||
# defines (qjs, qjsc, qjs-libc, ...) rather than guessing target names.
|
||||
if(quickjs_SOURCE_DIR)
|
||||
get_property(_qjs_targets DIRECTORY "${quickjs_SOURCE_DIR}"
|
||||
PROPERTY BUILDSYSTEM_TARGETS)
|
||||
foreach(_qjs_target ${_qjs_targets})
|
||||
get_target_property(_qjs_type ${_qjs_target} TYPE)
|
||||
if(NOT _qjs_type STREQUAL "INTERFACE_LIBRARY")
|
||||
target_compile_options(${_qjs_target} PRIVATE -Wno-error)
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
|
||||
add_boost(
|
||||
TRY_BOOST_VERSION BOOST_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED
|
||||
BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED EchoionCore
|
||||
)
|
||||
# Boost: the process must contain exactly ONE copy of the compiled Boost
|
||||
# libraries. VoidLibrary links the SYSTEM Boost, so EchoionCore must use the
|
||||
# same one — vendoring a second copy (the old AddBoost path fetched 1.90
|
||||
# alongside the system 1.91) put two libboost_url.so versions into the
|
||||
# process and the cross-bound symbols corrupted every parsed URL
|
||||
# (SIGSEGV in boost::urls::url_view). Fall back to fetching only when no
|
||||
# usable system Boost exists (in which case Void fetched the same one).
|
||||
find_package(Boost 1.87 CONFIG QUIET COMPONENTS url thread container)
|
||||
if(Boost_FOUND)
|
||||
message(STATUS "EchoionCore using system Boost ${Boost_VERSION}")
|
||||
# Distros ship CMake configs only for the compiled Boost libraries;
|
||||
# header-only components (asio, beast, uuid) have none. Map the targets
|
||||
# EchoionCore links onto the installed headers.
|
||||
foreach(_hdr asio beast uuid system)
|
||||
if(NOT TARGET Boost::${_hdr})
|
||||
add_library(_boost_${_hdr}_hdr INTERFACE)
|
||||
add_library(Boost::${_hdr} ALIAS _boost_${_hdr}_hdr)
|
||||
target_include_directories(_boost_${_hdr}_hdr INTERFACE
|
||||
"${Boost_INCLUDE_DIRS}")
|
||||
endif()
|
||||
endforeach()
|
||||
else()
|
||||
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
|
||||
)
|
||||
endif()
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
find_package(OpenSSL REQUIRED)
|
||||
find_package(SQLite3 REQUIRED)
|
||||
# FindSQLite3 exposed only SQLite::SQLite3 before CMake 4.3. Keep the
|
||||
# component's preferred target name available across the supported CMake 4.x
|
||||
# range; an alias created inside sibling VoidLibrary is not visible here.
|
||||
if(NOT TARGET SQLite3::SQLite3 AND TARGET SQLite::SQLite3)
|
||||
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
|
||||
endif()
|
||||
find_package(TBB REQUIRED)
|
||||
|
||||
target_link_libraries(EchoionCore
|
||||
target_link_libraries(EchoionCore
|
||||
PUBLIC
|
||||
PkgConfig::LIBAV
|
||||
TBB::tbb
|
||||
SQLite::SQLite3
|
||||
SQLite3::SQLite3
|
||||
# VoidLibrary modules (migration target — replacing in-house infra)
|
||||
Void::Data
|
||||
Void::Functional
|
||||
Void::System
|
||||
Void::Log
|
||||
Void::Async
|
||||
Void::Containers
|
||||
Void::Resilience
|
||||
Void::Text
|
||||
Void::Time
|
||||
Void::Math
|
||||
Void::Net
|
||||
Void::Sqlite
|
||||
Void::Service
|
||||
Void::ShortUrl
|
||||
Void::Plugin
|
||||
Void::Crypto
|
||||
Void::Update
|
||||
Void::Security
|
||||
PRIVATE
|
||||
glaze::glaze
|
||||
Threads::Threads
|
||||
qjs
|
||||
Boost::beast
|
||||
@@ -87,7 +207,6 @@ target_link_libraries(EchoionCore
|
||||
Boost::asio
|
||||
OpenSSL::SSL
|
||||
OpenSSL::Crypto
|
||||
|
||||
)
|
||||
|
||||
if(MSVC)
|
||||
@@ -97,6 +216,42 @@ else()
|
||||
target_compile_options(EchoionCore PRIVATE -Wall -Wextra -Wpedantic)
|
||||
endif()
|
||||
|
||||
if(BUILD_TESTS)
|
||||
include("${Void_SOURCE_DIR}/cmake/VoidTesting.cmake")
|
||||
|
||||
add_executable(echoion_log_rotation_tests
|
||||
tests/test_log_rotation.cpp
|
||||
src/LogRotation.cpp
|
||||
)
|
||||
target_include_directories(echoion_log_rotation_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
)
|
||||
target_compile_features(echoion_log_rotation_tests PRIVATE cxx_std_26)
|
||||
add_test(NAME echoion_log_rotation_tests
|
||||
COMMAND echoion_log_rotation_tests)
|
||||
endif()
|
||||
|
||||
# Precompiled headers for the heavy translation units (MusicManager.cpp ~2.4k
|
||||
# lines, Core.cpp, YouTubeClient.cpp). These pull in the same expensive standard
|
||||
# and Void headers, so compiling them once cuts a large slice off build time.
|
||||
# Disabled automatically under unity builds (CMake forbids combining the two).
|
||||
option(ECHOION_ENABLE_PCH "Use precompiled headers for EchoionCore" ON)
|
||||
if(ECHOION_ENABLE_PCH AND NOT CMAKE_UNITY_BUILD)
|
||||
target_precompile_headers(EchoionCore PRIVATE
|
||||
<string>
|
||||
<string_view>
|
||||
<vector>
|
||||
<memory>
|
||||
<optional>
|
||||
<chrono>
|
||||
<format>
|
||||
<mutex>
|
||||
<thread>
|
||||
<atomic>
|
||||
<functional>
|
||||
)
|
||||
endif()
|
||||
|
||||
set_target_properties(EchoionCore PROPERTIES
|
||||
OUTPUT_NAME "Echoion"
|
||||
PREFIX ""
|
||||
@@ -106,20 +261,112 @@ set_target_properties(EchoionCore PROPERTIES
|
||||
ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib
|
||||
)
|
||||
|
||||
include(GNUInstallDirs)
|
||||
# Export EchoionCore
|
||||
target_include_directories(EchoionCore PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
install(TARGETS EchoionCore
|
||||
EXPORT EchoionCoreTargets
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
RUNTIME DESTINATION bin
|
||||
LIBRARY DESTINATION lib
|
||||
ARCHIVE DESTINATION lib
|
||||
INCLUDES DESTINATION include
|
||||
)
|
||||
|
||||
install(EXPORT EchoionCoreTargets
|
||||
FILE EchoionCoreTargets.cmake
|
||||
NAMESPACE Echoion::
|
||||
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/EchoionCore
|
||||
DESTINATION lib/cmake/EchoionCore
|
||||
)
|
||||
|
||||
install(DIRECTORY include/
|
||||
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
|
||||
install(FILES abi/module.json
|
||||
DESTINATION share/echoion/components/EchoionCore/${PROJECT_VERSION}/abi)
|
||||
|
||||
# Package config files
|
||||
include(CMakePackageConfigHelpers)
|
||||
write_basic_package_version_file(
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfigVersion.cmake"
|
||||
VERSION ${PROJECT_VERSION}
|
||||
COMPATIBILITY SameMajorVersion
|
||||
)
|
||||
|
||||
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfig.cmake"
|
||||
"include(\"\${CMAKE_CURRENT_LIST_DIR}/EchoionCoreTargets.cmake\")
|
||||
include(CMakeFindDependencyMacro)
|
||||
find_dependency(EchoionApi)
|
||||
")
|
||||
|
||||
install(FILES
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfig.cmake"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfigVersion.cmake"
|
||||
DESTINATION lib/cmake/EchoionCore
|
||||
)
|
||||
|
||||
if(BUILD_TESTS)
|
||||
add_executable(echoion_core_config_loader_tests
|
||||
tests/test_config_loader.cpp)
|
||||
target_include_directories(echoion_core_config_loader_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_link_libraries(echoion_core_config_loader_tests PRIVATE EchoionCore)
|
||||
add_test(NAME echoion_core_config_loader_tests
|
||||
COMMAND echoion_core_config_loader_tests)
|
||||
|
||||
add_executable(echoion_core_gapless_handoff_tests
|
||||
tests/test_gapless_handoff.cpp)
|
||||
target_include_directories(echoion_core_gapless_handoff_tests PRIVATE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/include)
|
||||
target_compile_features(echoion_core_gapless_handoff_tests PRIVATE cxx_std_23)
|
||||
add_test(NAME echoion_core_gapless_handoff_tests
|
||||
COMMAND echoion_core_gapless_handoff_tests)
|
||||
|
||||
add_executable(echoion_core_license_verifier_tests
|
||||
tests/test_license_verifier.cpp)
|
||||
target_include_directories(echoion_core_license_verifier_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_link_libraries(echoion_core_license_verifier_tests PRIVATE
|
||||
EchoionCore OpenSSL::Crypto)
|
||||
add_test(NAME echoion_core_license_verifier_tests
|
||||
COMMAND echoion_core_license_verifier_tests)
|
||||
|
||||
add_executable(echoion_core_extension_state_tests
|
||||
tests/test_extension_state.cpp)
|
||||
target_include_directories(echoion_core_extension_state_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_link_libraries(echoion_core_extension_state_tests PRIVATE EchoionCore)
|
||||
add_test(NAME echoion_core_extension_state_tests
|
||||
COMMAND echoion_core_extension_state_tests)
|
||||
|
||||
add_executable(echoion_core_teamspeak_directory_tests
|
||||
tests/test_teamspeak_directory.cpp
|
||||
src/TeamSpeakDirectoryService.cpp)
|
||||
target_include_directories(echoion_core_teamspeak_directory_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_link_libraries(echoion_core_teamspeak_directory_tests PRIVATE EchoionCore)
|
||||
add_test(NAME echoion_core_teamspeak_directory_tests
|
||||
COMMAND echoion_core_teamspeak_directory_tests)
|
||||
|
||||
add_executable(echoion_core_url_shortener_tests
|
||||
tests/test_url_shortener.cpp)
|
||||
target_include_directories(echoion_core_url_shortener_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_link_libraries(echoion_core_url_shortener_tests PRIVATE EchoionCore)
|
||||
add_test(NAME echoion_core_url_shortener_tests
|
||||
COMMAND echoion_core_url_shortener_tests)
|
||||
|
||||
add_executable(echoion_core_plugin_compatibility_tests
|
||||
tests/test_plugin_compatibility.cpp)
|
||||
target_include_directories(echoion_core_plugin_compatibility_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src")
|
||||
target_link_libraries(echoion_core_plugin_compatibility_tests PRIVATE
|
||||
EchoionCore)
|
||||
void_add_tests(echoion_core_plugin_compatibility_tests)
|
||||
endif()
|
||||
|
||||
option(BUNDLE_FFMPEG "Bundle FFmpeg libraries with installation" OFF)
|
||||
if(BUNDLE_FFMPEG)
|
||||
include(cmake/BundleFFmpeg.cmake)
|
||||
bundle_ffmpeg_libraries(EchoionCore)
|
||||
endif()
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"contractId": "echoion.module.core",
|
||||
"descriptor": "echoion_module_descriptor_v1",
|
||||
"querySymbol": "echoion_module_abi_query",
|
||||
"moduleId": "EchoionCore",
|
||||
"activation": "reloadable",
|
||||
"dependencies": [
|
||||
{
|
||||
"moduleId": "EchoionApi",
|
||||
"versionRange": "^2.0.0",
|
||||
"abiHash": "sha256:d50293d345a97e52f9844088bdd42277f566bc815a21b7636d3e053f06c6c113"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
# BundleFFmpeg.cmake - Helper to bundle FFmpeg libraries on install
|
||||
|
||||
function(bundle_ffmpeg_libraries target)
|
||||
if(NOT TARGET ${target})
|
||||
return()
|
||||
endif()
|
||||
|
||||
if(UNIX AND NOT APPLE)
|
||||
# Create post-install script to copy FFmpeg libs
|
||||
file(GENERATE OUTPUT ${CMAKE_BINARY_DIR}/bundle_ffmpeg_$<CONFIG>.sh
|
||||
CONTENT "#!/bin/bash
|
||||
# Bundle FFmpeg libraries
|
||||
set -e
|
||||
|
||||
dest_dir=\"$1\"
|
||||
mkdir -p \"\$dest_dir\"
|
||||
|
||||
# Find FFmpeg libraries
|
||||
ffmpeg_libs=($(pkg-config --libs-only-L libavformat libavcodec libswresample libavutil 2>/dev/null | sed 's/-L//g'))
|
||||
|
||||
for libdir in \"\${ffmpeg_libs[@]}\" /usr/lib /usr/local/lib; do
|
||||
if [ -d \"\$libdir\" ]; then
|
||||
for lib in avformat avcodec swresample avutil; do
|
||||
# Try different naming conventions
|
||||
for pattern in \"lib\${lib}.so*\" \"lib\${lib}-*.so*\"; do
|
||||
for file in \$libdir/\$pattern; do
|
||||
if [ -f \"\$file\" ] && [ ! -L \"\$file\" ]; then
|
||||
cp -v \"\$file\" \"\$dest_dir/\" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
done
|
||||
done
|
||||
fi
|
||||
done
|
||||
|
||||
echo \"FFmpeg libraries bundled to \$dest_dir\"
|
||||
"
|
||||
FILE_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE
|
||||
)
|
||||
|
||||
install(CODE "
|
||||
execute_process(
|
||||
COMMAND ${CMAKE_BINARY_DIR}/bundle_ffmpeg_$<CONFIG>.sh \"${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}\"
|
||||
ERROR_QUIET
|
||||
)
|
||||
")
|
||||
endif()
|
||||
endfunction()
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"componentId": "EchoionCore",
|
||||
"productCompatibility": ">=2.0.0 <3.0.0",
|
||||
"publishNightly": true,
|
||||
"cmakeOptions": {}
|
||||
}
|
||||
@@ -1,145 +1,148 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include <condition_variable>
|
||||
#include <queue>
|
||||
#include "NetworkTypes.hpp"
|
||||
#include <AudioTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <atomic>
|
||||
#include <span>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
// Forward declarations for FFmpeg
|
||||
extern "C" {
|
||||
struct AVFormatContext;
|
||||
struct AVCodecContext;
|
||||
struct AVFrame;
|
||||
struct AVPacket;
|
||||
struct SwrContext;
|
||||
struct AVBufferRef;
|
||||
struct AVFormatContext;
|
||||
struct AVCodecContext;
|
||||
struct AVFrame;
|
||||
struct AVPacket;
|
||||
struct SwrContext;
|
||||
}
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class AudioDecoder {
|
||||
public:
|
||||
AudioDecoder();
|
||||
~AudioDecoder();
|
||||
// FFmpeg-backed streaming decoder. openSource() spawns a decode jthread
|
||||
// that resamples to interleaved S16 at the configured output format and
|
||||
// fills int16Queue_ (bounded, backpressured); the playback side drains it
|
||||
// chunk-by-chunk via getNextChunk().
|
||||
class AudioDecoder
|
||||
{
|
||||
public:
|
||||
|
||||
// Initialize decoder with optional hardware acceleration
|
||||
Api::Result<void> initialize(const Api::HwAccelConfig& hwConfig = {});
|
||||
void shutdown();
|
||||
AudioDecoder();
|
||||
~AudioDecoder();
|
||||
|
||||
// Open audio source (URL or file path)
|
||||
Api::Result<void> openSource(const std::string& url);
|
||||
void closeSource();
|
||||
Api::Result<void> initialize();
|
||||
void shutdown();
|
||||
|
||||
// Decode audio - returns zero-copy pooled buffer
|
||||
[[nodiscard]] Api::Result<Api::DecodedAudio> decodeFrame();
|
||||
|
||||
// Seek to position
|
||||
Api::Result<void> seek(std::chrono::milliseconds position);
|
||||
// Open audio source (URL or file path)
|
||||
Api::Result<void> openSource(const std::string& url);
|
||||
void closeSource();
|
||||
|
||||
// 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;
|
||||
// Seek to position
|
||||
Api::Result<void> seek(std::chrono::milliseconds position);
|
||||
|
||||
// Set output format
|
||||
void setOutputFormat(uint32_t sampleRate, uint32_t channels);
|
||||
// Get audio info
|
||||
[[nodiscard]] Api::Result<Api::AudioStreamInfo>
|
||||
getStreamInfo() const;
|
||||
|
||||
// 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(); }
|
||||
// Get current decode position (runs ahead of playback by up to
|
||||
// the queued chunk depth; use MusicManager for playback position)
|
||||
[[nodiscard]] std::chrono::milliseconds getPosition() const;
|
||||
|
||||
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();
|
||||
// Set output format
|
||||
void setOutputFormat(uint32_t sampleRate, uint32_t channels);
|
||||
|
||||
// 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;
|
||||
// Set proxy configuration for network requests
|
||||
void setProxyConfig(const std::optional<Void::Net::ProxyConfig>& proxy);
|
||||
|
||||
// Stream info
|
||||
int audioStreamIndex_ = -1;
|
||||
Api::AudioStreamInfo streamInfo_;
|
||||
|
||||
// Output format
|
||||
uint32_t outputSampleRate_ = 48000;
|
||||
uint32_t outputChannels_ = 2;
|
||||
// Get next S16 chunk. Swaps the caller's buffer for the queued
|
||||
// one, so the caller's previous storage is recycled into the
|
||||
// decode free-list — no per-chunk copy or allocation.
|
||||
bool getNextChunk(std::vector<int16_t>& outChunk,
|
||||
bool blocking = false);
|
||||
|
||||
// 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;
|
||||
// Check if decode is finished
|
||||
[[nodiscard]] bool isFinished() const { return eof_.load(); }
|
||||
|
||||
// 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_;
|
||||
};
|
||||
// Decoded audio waiting in the queue, in interleaved S16 samples.
|
||||
// The crossfade readiness gate uses this: a fade only starts once
|
||||
// the incoming decoder has buffered enough audio to survive it.
|
||||
[[nodiscard]] std::size_t queuedSamples() const;
|
||||
|
||||
// True when the decode queue is at capacity (the decode thread is
|
||||
// backpressured) — waiting longer cannot buffer any more.
|
||||
[[nodiscard]] bool queueSaturated() const;
|
||||
|
||||
private:
|
||||
|
||||
void decodeThread();
|
||||
// One read→decode→flush pass over the source; returns on EOF or
|
||||
// shutdown. decodeThread() parks between sessions awaiting a
|
||||
// seek request, so a post-EOF seek resumes decoding.
|
||||
void decodeSession();
|
||||
// Perform a pending seek request on the decode thread (the only
|
||||
// thread allowed to touch the FFmpeg contexts while decoding).
|
||||
// Returns true if a request was consumed.
|
||||
bool consumePendingSeek();
|
||||
// Borrow a chunk buffer of `samples` length from the recycle
|
||||
// free-list (reusing pooled storage), or allocate one if the
|
||||
// free-list is empty.
|
||||
std::vector<int16_t> acquireChunkBuffer(size_t samples);
|
||||
void cleanupFfmpeg();
|
||||
|
||||
// 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
|
||||
|
||||
// Stream info
|
||||
int audioStreamIndex_ = -1;
|
||||
Api::AudioStreamInfo streamInfo_;
|
||||
|
||||
// Output format
|
||||
uint32_t outputSampleRate_ = 192000;
|
||||
uint32_t outputChannels_ = 2;
|
||||
|
||||
// Threading
|
||||
std::jthread decodeThread_;
|
||||
mutable std::mutex mutex_;
|
||||
std::condition_variable cv_;
|
||||
|
||||
// S16 audio queue (like reference) - avoids float conversion
|
||||
std::deque<std::vector<int16_t>> int16Queue_;
|
||||
static constexpr size_t MAX_INT16_QUEUE_SIZE = 100;
|
||||
// Max samples per swr_convert() output call; outputBuffer_ is
|
||||
// sized for this.
|
||||
static constexpr int MAX_OUT_SAMPLES = 4096;
|
||||
|
||||
// Free-list of recycled chunk buffers. getNextChunk() swaps the
|
||||
// caller's previous buffer in here and decodeThread() reuses that
|
||||
// storage instead of allocating a fresh vector per frame.
|
||||
// Guarded by mutex_ (same as int16Queue_).
|
||||
std::vector<std::vector<int16_t>> recycledChunks_;
|
||||
|
||||
// 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
|
||||
// Decode position in ms; written by the decode thread per frame,
|
||||
// read cross-thread by getPosition() (prefetch decisions).
|
||||
std::atomic<int64_t> currentPositionMs_{0};
|
||||
// Pending seek target in ms, -1 = none. Written by seek() under
|
||||
// mutex_ (coordinated with eof_), consumed by the decode thread.
|
||||
std::atomic<int64_t> seekRequestMs_{-1};
|
||||
std::string currentUrl_;
|
||||
|
||||
std::atomic<uint32_t> streamSampleRate_{48000};
|
||||
std::optional<Void::Net::ProxyConfig> proxyConfig_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,124 +1,237 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "commands/Command.hpp"
|
||||
#include "echoion/api/ConfigTypes.hpp"
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <PluginTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/ThreadPool.hpp>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
#include <string>
|
||||
#include <functional>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class MusicManager;
|
||||
class MusicManager;
|
||||
|
||||
// Function to check if client has permission (set by Core)
|
||||
using PermissionCheckFunc = std::function<bool(uint64_t clientId, CommandCategory category)>;
|
||||
// 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;
|
||||
/**
|
||||
* @brief Manages command registration and dispatch.
|
||||
*
|
||||
* Usage:
|
||||
* CommandManager mgr;
|
||||
* mgr.registerCommand<PlayCommand>("play");
|
||||
* mgr.dispatch(clientId, "play song name", musicManager, replyFunc);
|
||||
*/
|
||||
class CommandManager
|
||||
{
|
||||
public:
|
||||
|
||||
// Disable copy
|
||||
CommandManager(const CommandManager&) = delete;
|
||||
CommandManager& operator=(const CommandManager&) = delete;
|
||||
|
||||
// Enable move
|
||||
CommandManager(CommandManager&&) = default;
|
||||
CommandManager& operator=(CommandManager&&) = default;
|
||||
CommandManager();
|
||||
~CommandManager();
|
||||
|
||||
/**
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
// Shutdown the command manager (stops thread pool)
|
||||
void shutdown();
|
||||
|
||||
/**
|
||||
* @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 = ""
|
||||
);
|
||||
// Provide the service registry that command contexts resolve
|
||||
// shared services from (non-owning; must outlive this manager).
|
||||
void setServices(const Void::Service::ServiceRegistry* services)
|
||||
{
|
||||
services_ = services;
|
||||
}
|
||||
|
||||
[[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;
|
||||
// Disable copy
|
||||
CommandManager(const CommandManager&) = delete;
|
||||
CommandManager& operator=(const CommandManager&) = delete;
|
||||
|
||||
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);
|
||||
// Enable move
|
||||
CommandManager(CommandManager&&) = default;
|
||||
CommandManager& operator=(CommandManager&&) = default;
|
||||
|
||||
private:
|
||||
struct CommandEntry {
|
||||
std::string primaryName;
|
||||
CommandPtr instance;
|
||||
};
|
||||
/**
|
||||
* @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>();
|
||||
|
||||
void registerBuiltinCommands();
|
||||
|
||||
// Internal Help Command (defined in .cpp to access registry)
|
||||
class HelpCommand;
|
||||
void registerHelpCommand();
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
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_;
|
||||
};
|
||||
// Register primary name
|
||||
commands_[primaryName] = cmd;
|
||||
uniqueCommands_.push_back({primaryName, cmd});
|
||||
|
||||
// Register aliases automatically from the class itself
|
||||
for (auto alias : cmd->getAliases()) {
|
||||
commands_[std::string(alias)] = cmd;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Dispatches a command message to the appropriate handler
|
||||
* (ASYNC). Commands are executed in a thread pool, allowing
|
||||
* multiple users to use the bot simultaneously without blocking.
|
||||
* @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 queued for execution,
|
||||
* false otherwise.
|
||||
*/
|
||||
[[nodiscard]] bool
|
||||
dispatch(uint64_t clientId,
|
||||
std::string_view message,
|
||||
std::weak_ptr<MusicManager> musicManager,
|
||||
std::function<void(std::string_view)> replyFunc,
|
||||
std::string_view invokerName = "");
|
||||
|
||||
/**
|
||||
* @brief Executes a command synchronously (for internal use).
|
||||
* Prefer using dispatch() for normal command handling.
|
||||
*/
|
||||
[[nodiscard]] bool
|
||||
dispatchSync(uint64_t clientId,
|
||||
std::string_view message,
|
||||
std::weak_ptr<MusicManager> musicManager,
|
||||
std::function<void(std::string_view)> replyFunc,
|
||||
std::string_view invokerName = "");
|
||||
|
||||
[[nodiscard]] bool hasCommand(std::string_view name) const;
|
||||
[[nodiscard]] std::optional<CommandPtr>
|
||||
getCommand(std::string_view name) const;
|
||||
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>>
|
||||
getAllCommands() const;
|
||||
[[nodiscard]] bool registerExternalCommand(
|
||||
std::string owner, std::string primaryName, CommandPtr command);
|
||||
void unregisterExternalCommands(std::string_view owner);
|
||||
|
||||
// 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();
|
||||
|
||||
// Internal page-navigator command (!page/!next/!prev), defined in
|
||||
// the .cpp so it can reach the paged-reply cache below.
|
||||
class PageNavCommand;
|
||||
void registerPageCommands();
|
||||
|
||||
// Resolve the language a client should be answered in: their stored
|
||||
// per-user preference (kv_store "lang:<uid>") if any, else the
|
||||
// configured bot default, else English.
|
||||
[[nodiscard]] I18n::Language resolveLanguage(
|
||||
uint64_t clientId,
|
||||
const std::weak_ptr<MusicManager>& musicManager) const;
|
||||
|
||||
// --- Oversized-reply pagination -------------------------------
|
||||
// Long replies (from any command except help / the navigator) are
|
||||
// kept to a single message: page 1 is sent with a footer and the
|
||||
// remaining pages are cached here for !page/!next/!prev.
|
||||
struct PagedReply {
|
||||
std::vector<std::string> pages;
|
||||
std::size_t current = 0;
|
||||
std::chrono::steady_clock::time_point ts{};
|
||||
};
|
||||
mutable std::mutex pagedMutex_;
|
||||
std::unordered_map<uint64_t, PagedReply> pagedReplies_;
|
||||
static constexpr std::size_t kPageLimitBytes = 700;
|
||||
static constexpr std::chrono::minutes kPageTtl{10};
|
||||
|
||||
// Split `text` into pages, cache pages 2..N for `clientId`, and
|
||||
// return page 1 (with a footer when there is more than one page).
|
||||
// Replies that already fit one message pass through unchanged.
|
||||
std::string paginateReply(uint64_t clientId, std::string text,
|
||||
I18n::Language lang);
|
||||
|
||||
// Re-render a cached page for `clientId`. When `absolute` is set
|
||||
// the current page jumps to it (1-based, clamped); otherwise it
|
||||
// moves by `delta`. Returns std::nullopt when nothing is cached /
|
||||
// expired.
|
||||
std::optional<std::string>
|
||||
renderCachedPage(uint64_t clientId,
|
||||
std::optional<long> absolute, int delta,
|
||||
I18n::Language lang);
|
||||
|
||||
std::string prefix_ = "!";
|
||||
|
||||
// Non-owning service registry threaded into each CommandContext
|
||||
// so commands can resolve shared services by interface.
|
||||
const Void::Service::ServiceRegistry* services_ = nullptr;
|
||||
|
||||
// Map for fast lookup: "play" -> PlayCommand
|
||||
std::map<std::string, CommandPtr, std::less<>> commands_;
|
||||
|
||||
// List for generating help: {"play", PlayCommand}
|
||||
std::vector<CommandEntry> uniqueCommands_;
|
||||
std::map<std::string, std::vector<CommandPtr>, std::less<>>
|
||||
externalCommands_;
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
// Permission checking
|
||||
PermissionCheckFunc permissionCheck_;
|
||||
std::optional<Api::AppConfig> serverConfig_;
|
||||
|
||||
// Async command execution
|
||||
struct CommandTask {
|
||||
uint64_t clientId;
|
||||
std::string message;
|
||||
std::weak_ptr<MusicManager> musicManager;
|
||||
std::function<void(std::string_view)> replyFunc;
|
||||
std::string invokerName;
|
||||
};
|
||||
|
||||
void startThreadPool();
|
||||
void executeCommandAsync(CommandTask task);
|
||||
|
||||
// Void worker pool backing async command execution (drains
|
||||
// in-flight commands on shutdown via ~ThreadPool).
|
||||
std::unique_ptr<Void::Concurrency::ThreadPool> pool_;
|
||||
std::atomic<bool> shutdown_{false};
|
||||
static constexpr size_t THREAD_POOL_SIZE =
|
||||
4; // Handle up to 4 concurrent commands
|
||||
|
||||
}; // namespace Echoion::Core
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,30 +1,49 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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();
|
||||
// Configuration loader for JSON config files (internal to Core).
|
||||
//
|
||||
// Api::AppConfig is serialized directly through Void::Json reflection —
|
||||
// no mirror DTOs. The on-disk shape follows the domain types: durations
|
||||
// are strings ("30000ms"), enums are names ("High"), the proxy is a
|
||||
// nested object (or null), and time_points are duration strings.
|
||||
class ConfigLoader
|
||||
{
|
||||
public:
|
||||
|
||||
private:
|
||||
// Parse quality string to enum
|
||||
[[nodiscard]] static Api::AudioQuality parseQuality(const std::string& str);
|
||||
[[nodiscard]] static std::string qualityToString(Api::AudioQuality quality);
|
||||
};
|
||||
// Load configuration from JSON file
|
||||
[[nodiscard]] static Api::Result<Api::AppConfig>
|
||||
loadFromFile(const std::filesystem::path& path);
|
||||
|
||||
// Parse, migrate, and normalize a complete JSON configuration. This
|
||||
// is shared by file loading and live configuration updates so
|
||||
// legacy fields have identical behavior through both entry points.
|
||||
[[nodiscard]] static Api::Result<Api::AppConfig>
|
||||
loadFromJson(std::string_view json);
|
||||
|
||||
// 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();
|
||||
|
||||
// Clamp/normalize values that carry hard limits after loading
|
||||
// (e.g. the yt-dlp concurrency cap). Applied by all load/update
|
||||
// paths.
|
||||
static void normalize(Api::AppConfig& config);
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
+277
-85
@@ -1,111 +1,303 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include <echoion/api/Database.hpp>
|
||||
#include "MusicManager.hpp"
|
||||
#include "CommandManager.hpp"
|
||||
#include "ConfigLoader.hpp"
|
||||
#include "LyricsService.hpp"
|
||||
#include "MusicManager.hpp"
|
||||
#include "NetworkClient.hpp"
|
||||
#include "RpcServer.hpp"
|
||||
#include "ConfigLoader.hpp"
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include "licensing/LicenseManager.hpp"
|
||||
#ifdef ECHOION_WITH_WEB
|
||||
#include "echoion/web/HttpServer.hpp"
|
||||
#endif
|
||||
#include <ConfigManager.hpp>
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <CoreInterface.hpp>
|
||||
#include <Database.hpp>
|
||||
#include <RpcTypes.hpp>
|
||||
#include <StateBlob.hpp>
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/EventBus.hpp>
|
||||
#include <Void/Service/Registry.hpp>
|
||||
#include <atomic>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Void::Logging
|
||||
{
|
||||
class MultiLogger;
|
||||
}
|
||||
|
||||
// Main Core implementation of ICoreInterface
|
||||
class Core : public Api::ICoreInterface {
|
||||
public:
|
||||
Core();
|
||||
~Core() override;
|
||||
namespace Echoion::Core
|
||||
{
|
||||
class PluginHost;
|
||||
class TeamSpeakDirectoryService;
|
||||
|
||||
// ICoreInterface implementation
|
||||
Api::Result<void> initialize(const std::filesystem::path& configPath) override;
|
||||
Api::Result<void> shutdown() override;
|
||||
[[nodiscard]] bool isInitialized() const noexcept override;
|
||||
// Main Core implementation of ICoreInterface
|
||||
class Core : public Api::ICoreInterface
|
||||
{
|
||||
public:
|
||||
|
||||
// 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;
|
||||
Core();
|
||||
~Core() 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;
|
||||
// ICoreInterface - Lifecycle
|
||||
Api::Result<void>
|
||||
initialize(const std::filesystem::path& configPath) override;
|
||||
Api::Result<void> shutdown() override;
|
||||
[[nodiscard]] bool isInitialized() const noexcept override;
|
||||
|
||||
// Track info
|
||||
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>> getCurrentTrack() const override;
|
||||
[[nodiscard]] Api::Result<Api::PlaybackState> getPlaybackState() const override;
|
||||
// ICoreInterface - Playback control (decoupled)
|
||||
Api::Result<void> play(const std::string& trackId) 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;
|
||||
|
||||
// Playlist
|
||||
Api::Result<void> loadPlaylist(const std::string& playlistId, uint64_t clientId) override;
|
||||
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>> getPlaylists() const override;
|
||||
// ICoreInterface - Queue management (decoupled)
|
||||
Api::Result<uint64_t> queueTrack(const std::string& trackId,
|
||||
uint64_t clientId) override;
|
||||
Api::Result<void> removeFromQueue(uint64_t queueId) override;
|
||||
Api::Result<void> clearQueue() override;
|
||||
Api::Result<void> moveInQueue(uint64_t queueId,
|
||||
uint32_t newPosition) 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();
|
||||
// ICoreInterface - Track info (decoupled)
|
||||
[[nodiscard]] Api::Result<std::optional<Api::TrackSummary>>
|
||||
getCurrentTrackSummary() const override;
|
||||
[[nodiscard]] Api::Result<Api::PlaybackSummary>
|
||||
getPlaybackSummary() const override;
|
||||
|
||||
// Hot reload
|
||||
Api::Result<Api::HotReloadState> prepareForHotReload() override;
|
||||
Api::Result<void> restoreAfterHotReload(const Api::HotReloadState& state) override;
|
||||
// ICoreInterface - Playlist (decoupled)
|
||||
Api::Result<void> loadPlaylist(const std::string& playlistId,
|
||||
uint64_t clientId) override;
|
||||
[[nodiscard]] Api::Result<std::vector<std::string>>
|
||||
getPlaylistIds() const override;
|
||||
|
||||
// Event handling
|
||||
void registerEventCallback(const Api::EventCallback& callback) override;
|
||||
void unregisterEventCallback(const Api::EventCallback& callback) override;
|
||||
// ICoreInterface - Configuration (decoupled)
|
||||
Api::Result<void>
|
||||
updateConfigJson(const std::string& configJson) override;
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
getConfigJson() const override;
|
||||
|
||||
// Plugin event processing
|
||||
Api::Result<void> onPluginEvent(const Api::PluginEvent& event) override;
|
||||
// ICoreInterface - Hot reload (decoupled)
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
prepareForHotReload() override;
|
||||
Api::Result<void>
|
||||
restoreAfterHotReload(const std::string& state) override;
|
||||
|
||||
// Status
|
||||
[[nodiscard]] std::string getVersion() const override;
|
||||
[[nodiscard]] std::chrono::system_clock::time_point getUptime() const override;
|
||||
// ICoreInterface - Decoupled state management
|
||||
[[nodiscard]] Api::StateBlob saveState() override;
|
||||
Api::Result<void>
|
||||
restoreState(const Api::StateBlob& state) override;
|
||||
[[nodiscard]] uint32_t getStateFormatVersion() const override;
|
||||
[[nodiscard]] bool
|
||||
canRestoreStateVersion(uint32_t version) const override;
|
||||
|
||||
// Additional methods for plugin integration
|
||||
void setPluginInterface(Api::PluginInterfacePtr pluginInterface) override;
|
||||
void setAudioDataCallback(const MusicManager::AudioDataCallback& callback);
|
||||
void triggerAutoConnect() override;
|
||||
// ICoreInterface - Event handling
|
||||
void registerEventCallback(
|
||||
const Api::EventCallback& callback) override;
|
||||
void unregisterEventCallback(
|
||||
const Api::EventCallback& callback) 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();
|
||||
// ICoreInterface - Plugin event processing
|
||||
Api::Result<void>
|
||||
onPluginEvent(const Api::PluginEvent& event) override;
|
||||
|
||||
// Components
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::shared_ptr<MusicManager> musicManager_;
|
||||
std::unique_ptr<CommandManager> commandManager_;
|
||||
Api::PluginInterfacePtr pluginInterface_;
|
||||
// ICoreInterface - Status
|
||||
[[nodiscard]] std::string getVersion() const override;
|
||||
[[nodiscard]] std::chrono::system_clock::time_point
|
||||
getUptime() const override;
|
||||
|
||||
// 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};
|
||||
// ICoreInterface - Plugin interface
|
||||
void setPluginInterface(
|
||||
Api::PluginInterfacePtr pluginInterface) override;
|
||||
void triggerAutoConnect() override;
|
||||
|
||||
// Event callbacks
|
||||
std::vector<Api::EventCallback> eventCallbacks_;
|
||||
mutable std::mutex eventMutex_;
|
||||
// ICoreInterface - Advanced (for internal Core-to-Core use)
|
||||
[[nodiscard]] Api::Result<Api::OpaqueHandle<Api::TrackInfo>>
|
||||
getCurrentTrackHandle() const override;
|
||||
[[nodiscard]] Api::Result<
|
||||
std::vector<Api::OpaqueHandle<Api::QueueEntry>>>
|
||||
getQueueHandles() const override;
|
||||
[[nodiscard]] Api::Result<Api::AppConfigHandle>
|
||||
getConfigHandle() const override;
|
||||
Api::Result<void>
|
||||
updateConfigFromHandle(Api::AppConfigHandle config) override;
|
||||
|
||||
// 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_;
|
||||
};
|
||||
// Additional methods for internal use (not in interface)
|
||||
void setAudioDataCallback(
|
||||
const MusicManager::AudioDataCallback& callback);
|
||||
Api::Result<void> reloadConfig() override;
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
managePluginsJson(const std::string& requestJson) override;
|
||||
|
||||
// Internal implementations using full types
|
||||
Api::Result<void> playTrack(const Api::TrackInfo& track);
|
||||
Api::Result<uint64_t> queueTrackFull(const Api::TrackInfo& track,
|
||||
uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::vector<Api::QueueEntry>>
|
||||
getQueue() const;
|
||||
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>>
|
||||
getCurrentTrack() const;
|
||||
[[nodiscard]] Api::Result<Api::PlaybackState>
|
||||
getPlaybackState() const;
|
||||
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>>
|
||||
getPlaylists() const;
|
||||
Api::Result<void> updateConfig(const Api::AppConfig& config);
|
||||
[[nodiscard]] Api::Result<Api::AppConfig> getConfig() const;
|
||||
[[nodiscard]] Api::Result<Api::HotReloadState>
|
||||
prepareForHotReloadFull();
|
||||
Api::Result<void>
|
||||
restoreAfterHotReloadFull(const Api::HotReloadState& state);
|
||||
|
||||
// Generate RPC tokens for existing subscribers
|
||||
void generateRpcTokensForSubscribers();
|
||||
|
||||
private:
|
||||
|
||||
void onMusicEvent(const Api::PluginEvent& event);
|
||||
void broadcastEvent(const Api::PluginEvent& event);
|
||||
[[nodiscard]] bool isAdmin(uint64_t clientId) const;
|
||||
[[nodiscard]] bool isDj(uint64_t clientId) const;
|
||||
void updateWhisperList();
|
||||
void setupRpcHandlers();
|
||||
void setupEventBusSubscriptions() noexcept;
|
||||
void applyUrlShorteningConfig();
|
||||
|
||||
// Fetch an online client's avatar bytes (TS local cache, then the
|
||||
// myTeamSpeak URL, then a legacy file-transfer download) and
|
||||
// persist them — and the myTS URL — to the database keyed by uid.
|
||||
// Returns {contentType, bytes} on success. Web-agnostic; used by
|
||||
// both the avatar HTTP provider and the background warmer.
|
||||
[[nodiscard]] std::optional<std::pair<std::string, std::string>>
|
||||
fetchClientAvatarBytes(const std::string& uid,
|
||||
uint64_t clientId);
|
||||
// Periodically cache avatars for every online client so they remain
|
||||
// available (from the DB) once the user goes offline. Runs on
|
||||
// avatarWarmer_.
|
||||
void warmAvatarCache();
|
||||
|
||||
// Build the console + split-file logging stack and install it as
|
||||
// the global Void::Log sink (logSink_ must outlive logging).
|
||||
void installLogging(const std::filesystem::path& logDirectory,
|
||||
const Api::LoggingConfig& config);
|
||||
|
||||
// Guard helper: ok if initialized, else a ServiceUnavailable error.
|
||||
[[nodiscard]] Api::Result<void> requireInitialized() const noexcept;
|
||||
// Normal bot operations are denied while licensing is update-only.
|
||||
[[nodiscard]] Api::Result<void> requireOperational() const noexcept;
|
||||
|
||||
// Components
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::unique_ptr<Licensing::LicenseManager> licenseManager_;
|
||||
std::shared_ptr<LyricsService> lyricsService_;
|
||||
std::shared_ptr<MusicManager> musicManager_;
|
||||
std::unique_ptr<CommandManager> commandManager_;
|
||||
std::shared_ptr<PluginHost> extensionPlugins_;
|
||||
std::shared_ptr<TeamSpeakDirectoryService> directoryService_;
|
||||
Api::PluginInterfacePtr pluginInterface_;
|
||||
|
||||
// State
|
||||
Api::AppConfig config_;
|
||||
std::filesystem::path configPath_;
|
||||
std::chrono::system_clock::time_point startTime_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
// Guards triggerAutoConnect() against duplicate connection
|
||||
// attempts (reset on a failed initiation so a retry can run).
|
||||
std::atomic<bool> autoConnectInitiated_{false};
|
||||
|
||||
// Event callbacks
|
||||
std::vector<Api::EventCallback> eventCallbacks_;
|
||||
mutable std::mutex eventMutex_;
|
||||
|
||||
// Authenticated RPC client -> stable TS uid + nickname, resolved
|
||||
// at token auth. Keys per-user features (favorites, vote-skip).
|
||||
struct RpcIdentity {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
};
|
||||
std::map<uint64_t, RpcIdentity> rpcIdentities_;
|
||||
mutable std::mutex rpcIdentityMutex_;
|
||||
[[nodiscard]] std::optional<RpcIdentity>
|
||||
rpcIdentity(uint64_t clientId) const;
|
||||
[[nodiscard]] bool hasLiveTeamSpeakRole(
|
||||
uint64_t clientId,
|
||||
const std::vector<uint64_t>& configuredGroups) const;
|
||||
|
||||
// Full identity behind an RPC token: uid, display nickname and
|
||||
// admin standing. Shared by token auth and IP autologin.
|
||||
struct TokenIdentity {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
bool isAdmin = false;
|
||||
bool isDj = false;
|
||||
};
|
||||
[[nodiscard]] std::optional<TokenIdentity>
|
||||
identityForToken(const std::string& token);
|
||||
// Mark an RPC connection authenticated as `identity` and retain its
|
||||
// stable TeamSpeak identity. Roles are checked live for each
|
||||
// request.
|
||||
void registerRpcAuth(uint64_t clientId,
|
||||
const TokenIdentity& identity);
|
||||
// Guards RestartWebInterface against overlapping restarts.
|
||||
std::atomic<bool> webRestartPending_{false};
|
||||
|
||||
// Database for persistence
|
||||
std::shared_ptr<Api::Database> database_;
|
||||
|
||||
// Background avatar cache warmer + the uids already cached this
|
||||
// session (so we don't re-download an unchanged avatar every
|
||||
// cycle).
|
||||
std::jthread avatarWarmer_;
|
||||
std::unordered_set<std::string> warmedUids_;
|
||||
|
||||
// RPC server for Desktop/API clients
|
||||
std::shared_ptr<RpcServer> rpcServer_;
|
||||
|
||||
#ifdef ECHOION_WITH_WEB
|
||||
// Browser web interface: serves the static dashboard and
|
||||
// same-origin RPC bridge. Bot control still terminates at the RPC
|
||||
// server.
|
||||
std::shared_ptr<Web::HttpServer> webServer_;
|
||||
#endif
|
||||
|
||||
// Composition root: a type-keyed registry of all Core services
|
||||
// (logger, config, event bus, network, database, music, rpc).
|
||||
// initialize() provides each instance; resolveServices() and other
|
||||
// code can require<I>() them by interface instead of reaching for
|
||||
// global singletons. The former singletons stay as thin macro
|
||||
// shims over the same instances.
|
||||
Void::Service::ServiceRegistry registry_;
|
||||
|
||||
// Application event bus (async): playback/queue/subscription events
|
||||
// published by MusicManager and consumed here for RPC broadcast +
|
||||
// DB persistence. Owned by Core, provided as a service.
|
||||
Void::EventBus::EventBus eventBus_{Void::EventBus::Mode::Async};
|
||||
|
||||
// Config holder kept in sync with config_ and provided as a service
|
||||
// (replaces the former ConfigManager singleton).
|
||||
Api::ConfigManager configManager_;
|
||||
|
||||
// Owns the logging stack installed as the global Void::Log sink;
|
||||
// must outlive any logging (i.e. the whole process).
|
||||
std::shared_ptr<Void::Logging::MultiLogger> logSink_;
|
||||
|
||||
public:
|
||||
|
||||
// Access the service registry (composition root).
|
||||
[[nodiscard]] Void::Service::ServiceRegistry& services() noexcept
|
||||
{
|
||||
return registry_;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <filesystem>
|
||||
#include <system_error>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
// Archive a non-empty active log into <directory>/history and prune the
|
||||
// oldest archives. This is intentionally performed before opening the
|
||||
// logger so every process start gets a fresh active file.
|
||||
[[nodiscard]] std::error_code
|
||||
rotateLogOnStartup(const std::filesystem::path& activeLog,
|
||||
std::size_t maxFiles) noexcept;
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,77 +0,0 @@
|
||||
#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
|
||||
@@ -0,0 +1,76 @@
|
||||
#pragma once
|
||||
|
||||
#include "echoion/core/NetworkClient.hpp"
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Fetches song lyrics from lrclib.net (free, no auth) for the currently
|
||||
// playing track. Returns both plain lyrics and, when available, LRC
|
||||
// time-synced lines so the web UI can highlight the active line against the
|
||||
// playback clock. Results are cached in-process for a while since lyrics
|
||||
// never change and the same track is asked about repeatedly (chat command,
|
||||
// web panel, reconnects).
|
||||
//
|
||||
// Reachable by chat commands via the service registry and directly by the
|
||||
// RPC handlers. All network calls are synchronous; callers already run off
|
||||
// the audio thread (command thread pool / RPC worker).
|
||||
class LyricsService
|
||||
{
|
||||
public:
|
||||
|
||||
struct Line {
|
||||
std::int64_t ms = 0; // offset from track start
|
||||
std::string text;
|
||||
};
|
||||
|
||||
struct Lyrics {
|
||||
bool found = false;
|
||||
std::string plain; // full plain-text lyrics
|
||||
std::vector<Line> synced; // empty when only plain exists
|
||||
std::string source; // "lrclib" when resolved
|
||||
std::string title; // as reported by the provider
|
||||
std::string artist;
|
||||
};
|
||||
|
||||
explicit LyricsService(std::shared_ptr<NetworkClient> net);
|
||||
|
||||
// Resolve lyrics for a track. `durationSec` == 0 means unknown and
|
||||
// skips the exact-duration lookup (search fallback still runs).
|
||||
[[nodiscard]] Lyrics fetch(const std::string& title,
|
||||
const std::string& artist,
|
||||
const std::string& album,
|
||||
long long durationSec);
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] Lyrics
|
||||
fetchUncached(const std::string& title,
|
||||
const std::string& artist,
|
||||
const std::string& album,
|
||||
long long durationSec) const;
|
||||
|
||||
// Parse an LRC-format string ("[mm:ss.xx] text") into sorted,
|
||||
// timestamped lines, ignoring metadata tags ([ar:], [ti:], …).
|
||||
[[nodiscard]] static std::vector<Line>
|
||||
parseLrc(const std::string& lrc);
|
||||
|
||||
std::shared_ptr<NetworkClient> net_;
|
||||
|
||||
struct Entry {
|
||||
Lyrics value;
|
||||
std::chrono::steady_clock::time_point at;
|
||||
};
|
||||
mutable std::mutex mutex_;
|
||||
std::unordered_map<std::string, Entry> cache_;
|
||||
static constexpr std::chrono::hours kCacheTtl{6};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,133 +1,454 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "Database.hpp"
|
||||
#include "NetworkClient.hpp"
|
||||
#include "YouTubeClient.hpp"
|
||||
#include "AudioDecoder.hpp"
|
||||
#include "PlaylistLoader.hpp"
|
||||
#include "RpcTypes.hpp"
|
||||
#include "Socks5HttpBridge.hpp"
|
||||
#include "SubscriptionManager.hpp"
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include <condition_variable>
|
||||
#include <queue>
|
||||
#include <random>
|
||||
#include "SubscriptionService.hpp"
|
||||
#include "TrackCache.hpp"
|
||||
#include "YouTubeClient.hpp"
|
||||
#include "playback/PlaybackEngine.hpp"
|
||||
#include "playback/QueueService.hpp"
|
||||
#include "sources/InnertubeSource.hpp"
|
||||
#include "sources/YandexMusicSource.hpp"
|
||||
#include "sources/SourceRouter.hpp"
|
||||
#include "sources/YtDlpSource.hpp"
|
||||
#include <ConfigManager.hpp>
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/EventBus.hpp>
|
||||
#include <atomic>
|
||||
#include <future>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <shared_mutex>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <filesystem>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class MusicManager {
|
||||
public:
|
||||
MusicManager();
|
||||
~MusicManager();
|
||||
// Facade over the playback services. Public surface is unchanged (Core,
|
||||
// the RPC handlers and ~27 commands call it); internally it wires:
|
||||
// - PlaybackEngine: real-time loop, both decoders, gapless handoff
|
||||
// - QueueService: queue + shuffle/repeat (self-locking)
|
||||
// - SubscriptionService: audience bookkeeping + pause-on-empty policy
|
||||
// and implements IPlaybackHost for the engine (stream resolution, queue
|
||||
// access, event publication).
|
||||
class MusicManager : private IPlaybackHost
|
||||
{
|
||||
public:
|
||||
|
||||
Api::Result<void> initialize(const Api::BotConfig& config,
|
||||
std::shared_ptr<NetworkClient> networkClient,
|
||||
std::shared_ptr<Api::Database> database = nullptr);
|
||||
void shutdown();
|
||||
MusicManager();
|
||||
~MusicManager() override;
|
||||
|
||||
[[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);
|
||||
Api::Result<void>
|
||||
initialize(std::shared_ptr<NetworkClient> networkClient,
|
||||
std::shared_ptr<Api::Database> database = nullptr);
|
||||
void shutdown();
|
||||
|
||||
[[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();
|
||||
// Inject the application event bus (owned by Core). Must be set
|
||||
// before playback so emitted events reach subscribers.
|
||||
void setEventBus(Void::EventBus::EventBus* bus) { eventBus_ = bus; }
|
||||
|
||||
[[nodiscard]] Api::Result<uint32_t> loadPlaylist(const std::string& playlistId, uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>> getPlaylists() const;
|
||||
// Inject the config holder (owned by Core). Must be set before
|
||||
// initialize() so config sections resolve.
|
||||
void setConfigManager(Api::ConfigManager* cfg)
|
||||
{
|
||||
configManager_ = cfg;
|
||||
}
|
||||
|
||||
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>> getCurrentTrack() const;
|
||||
[[nodiscard]] Api::Result<Api::PlaybackState> getPlaybackState() const;
|
||||
// Re-apply network settings (proxy) to every outbound client:
|
||||
// the HTTP NetworkClient (YouTube Data API, URL shortener), the
|
||||
// yt-dlp subprocess, and the ffmpeg decoders. Call after a
|
||||
// config reload so proxy changes actually take effect everywhere
|
||||
// instead of only living in the config copy.
|
||||
void applyNetworkConfig(const Api::NetworkConfig& network);
|
||||
|
||||
[[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);
|
||||
// Re-apply YouTube settings (API key, cookies, concurrency, URL
|
||||
// shortening) to the YouTube client after a config reload. Passing
|
||||
// an empty/absent API key clears it, restoring the yt-dlp fallback.
|
||||
void applyYouTubeConfig(const Api::YouTubeConfig& youtube);
|
||||
|
||||
// Help command
|
||||
[[nodiscard]] std::string getHelpText() const;
|
||||
// Re-apply the source-chain settings (order, cooldown, instance
|
||||
// lists) after a config reload.
|
||||
void applySourcesConfig(const Api::SourcesConfig& sources);
|
||||
void addTrackSource(std::shared_ptr<ITrackSource> source);
|
||||
void setSharedYouTubeClient(std::shared_ptr<YouTubeClient> client)
|
||||
{
|
||||
youTubeClient_ = std::move(client);
|
||||
}
|
||||
[[nodiscard]] std::shared_ptr<YouTubeClient> sharedYouTubeClient() const
|
||||
{
|
||||
return youTubeClient_;
|
||||
}
|
||||
// Re-apply bot settings (queue size, track timeout, playlist
|
||||
// import gate) after a config reload. Does not touch the live
|
||||
// volume.
|
||||
void applyBotConfig(const Api::BotConfig& bot);
|
||||
|
||||
// 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;
|
||||
// Re-apply feature toggles (subscriber pause/resume policy,
|
||||
// auto-start, history size, autoplay) after a config reload.
|
||||
// shuffleMode/repeatMode are applied at cold start only.
|
||||
void applyFeaturesConfig(const Api::FeaturesConfig& features);
|
||||
|
||||
[[nodiscard]] Api::HotReloadState getStateForHotReload() const;
|
||||
[[nodiscard]] Api::Result<void> restoreFromHotReload(const Api::HotReloadState& state);
|
||||
[[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);
|
||||
|
||||
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);
|
||||
// Vote-to-skip the current track. Votes are keyed by the voter's
|
||||
// stable uid and reset whenever the current track changes. The
|
||||
// threshold is features.voteSkipThreshold, or a majority of
|
||||
// online subscribers when 0. Reaching it skips the track.
|
||||
struct VoteSkipStatus {
|
||||
uint32_t votes = 0;
|
||||
uint32_t needed = 0;
|
||||
bool voted = false; // caller has an active vote
|
||||
bool skipped = false;
|
||||
};
|
||||
[[nodiscard]] Api::Result<VoteSkipStatus>
|
||||
voteSkip(const std::string& uid);
|
||||
[[nodiscard]] VoteSkipStatus
|
||||
voteSkipStatus(const std::string& uid) const;
|
||||
|
||||
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_;
|
||||
[[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<void> shuffleQueue();
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::unique_ptr<YouTubeClient> youTubeClient_;
|
||||
std::unique_ptr<AudioDecoder> audioDecoder_;
|
||||
std::unique_ptr<SubscriptionManager> subscriptionManager_;
|
||||
// Load playlist asynchronously - returns immediately, processes in
|
||||
// background
|
||||
Api::Result<void> loadPlaylist(const std::string& playlistIdOrUrl,
|
||||
uint64_t clientId);
|
||||
[[nodiscard]] bool isPlaylistLoading() const
|
||||
{
|
||||
return playlistLoader_ && playlistLoader_->isLoading();
|
||||
}
|
||||
[[nodiscard]] size_t getPlaylistLoadProgress() const
|
||||
{
|
||||
return playlistLoader_ ? playlistLoader_->loadedCount() : 0;
|
||||
}
|
||||
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>>
|
||||
getPlaylists() const;
|
||||
|
||||
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;
|
||||
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>>
|
||||
getCurrentTrack() const;
|
||||
[[nodiscard]] Api::Result<Api::PlaybackState>
|
||||
getPlaybackState() const;
|
||||
[[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const;
|
||||
|
||||
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_;
|
||||
// Which catalog(s) a text search targets.
|
||||
enum class SearchScope { All, YouTube, Yandex, SoundCloud };
|
||||
|
||||
AudioDataCallback audioCallback_;
|
||||
SubscriptionChangeCallback subscriptionChangeCallback_;
|
||||
std::mt19937 rng_{std::random_device{}()};
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
search(const std::string& query,
|
||||
SearchScope scope = SearchScope::All);
|
||||
|
||||
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;
|
||||
};
|
||||
// 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);
|
||||
|
||||
// Radio/autoplay toggle. Persisted in kv so it survives restart;
|
||||
// enabling while idle kicks an immediate related-track refill.
|
||||
void setAutoplay(bool enabled);
|
||||
[[nodiscard]] bool autoplayEnabled() const
|
||||
{
|
||||
return autoplay_.load();
|
||||
}
|
||||
|
||||
// Start playback (or seed radio) if nothing is playing and an
|
||||
// online subscriber is listening. Idempotent — safe to call after a
|
||||
// restore/hot-reload or when a subscriber connects, so radio resumes
|
||||
// without a manual !play / !radio toggle.
|
||||
void maybeAutoStart();
|
||||
|
||||
// Set shuffle/repeat mode directly (used when restoring persisted
|
||||
// state); persists the session snapshot.
|
||||
void setShuffle(bool enabled);
|
||||
void setRepeat(bool enabled);
|
||||
|
||||
// Help command
|
||||
[[nodiscard]] std::string getHelpText() const;
|
||||
|
||||
// Subscription management (by client ID - internally uses UID for
|
||||
// persistence)
|
||||
[[nodiscard]] Api::Result<std::string> subscribe(uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
unsubscribe(uint64_t clientId);
|
||||
[[nodiscard]] bool isSubscribed(uint64_t clientId) const;
|
||||
[[nodiscard]] std::set<uint64_t> getSubscribedClients()
|
||||
const; // Returns only ONLINE subscribers' client IDs
|
||||
[[nodiscard]] bool
|
||||
hasSubscribers() const; // Returns true if any subscribers exist
|
||||
// (online or offline)
|
||||
[[nodiscard]] bool hasOnlineSubscribers()
|
||||
const; // Returns true only if there are online subscribers
|
||||
[[nodiscard]] std::vector<SubscriptionManager::Subscriber>
|
||||
getSubscribers() const;
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
unsubscribeByUid(const std::string& uid);
|
||||
[[nodiscard]] Api::Result<std::string> clearAllSubscriptions();
|
||||
|
||||
// Get UIDs of subscribers who are currently online
|
||||
[[nodiscard]] std::set<std::string> getOnlineSubscriberUids() const;
|
||||
|
||||
// Called when a client connects to the server
|
||||
void onClientConnected(uint64_t clientId);
|
||||
|
||||
[[nodiscard]] Api::HotReloadState getStateForHotReload() const;
|
||||
[[nodiscard]] Api::Result<void>
|
||||
restoreFromHotReload(const Api::HotReloadState& state);
|
||||
|
||||
using AudioDataCallback =
|
||||
std::function<void(const std::span<const short>)>;
|
||||
void setAudioDataCallback(const AudioDataCallback& callback);
|
||||
|
||||
using SubscriptionChangeCallback = std::function<void()>;
|
||||
void setSubscriptionChangeCallback(
|
||||
const SubscriptionChangeCallback& callback);
|
||||
|
||||
using PlaybackStartCallback = std::function<void()>;
|
||||
void
|
||||
setPlaybackStartCallback(const PlaybackStartCallback& callback);
|
||||
|
||||
// Callback to resolve client info (UID and nickname) from client ID
|
||||
using ClientInfoCallback = std::function<std::optional<
|
||||
std::pair<std::string, std::string>>(uint64_t clientId)>;
|
||||
void setClientInfoCallback(const ClientInfoCallback& callback);
|
||||
|
||||
// Callback to resolve client ID from UID
|
||||
using UidToClientIdCallback =
|
||||
std::function<std::optional<uint64_t>(const std::string& uid)>;
|
||||
void
|
||||
setUidToClientIdCallback(const UidToClientIdCallback& callback);
|
||||
|
||||
// Callback to resolve nickname from client ID
|
||||
using NicknameCallback =
|
||||
std::function<std::optional<std::string>(uint64_t clientId)>;
|
||||
void setNicknameCallback(const NicknameCallback& callback);
|
||||
|
||||
// Callback to send a private text message to a client (wired by
|
||||
// Core to the plugin). Used for proactive announcements.
|
||||
using MessageCallback =
|
||||
std::function<void(uint64_t clientId, const std::string&)>;
|
||||
void setMessageCallback(const MessageCallback& callback)
|
||||
{
|
||||
messageCallback_ = callback;
|
||||
}
|
||||
|
||||
// Set the current announcement (admin !announce) and deliver it
|
||||
// to online subscribers now. Bumps the stored announcement id so
|
||||
// a fresh post reaches everyone once. Returns how many online
|
||||
// subscribers were reached immediately.
|
||||
[[nodiscard]] size_t setAnnouncement(const std::string& text);
|
||||
|
||||
// Called when a client leaves the server
|
||||
void onClientDisconnected(uint64_t clientId);
|
||||
|
||||
// Resolve the stable TS3 unique identifier for a session client
|
||||
// id (used to key per-user persistent data such as favorites).
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
clientUid(uint64_t clientId) const
|
||||
{
|
||||
if (clientInfoCallback_) {
|
||||
if (auto info = clientInfoCallback_(clientId)) {
|
||||
return info->first;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Persistent storage shared with commands (may be null when the
|
||||
// database failed to open).
|
||||
[[nodiscard]] std::shared_ptr<Api::Database> database() const
|
||||
{
|
||||
return database_;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
// ---- IPlaybackHost (called from the engine) --------------------
|
||||
|
||||
void emitAudio(std::span<const short> samples) override;
|
||||
Api::Result<std::string>
|
||||
resolveStream(const Api::QueueEntry& entry,
|
||||
bool preferDownload) override;
|
||||
std::optional<Api::QueueEntry> peekNextTrack() override;
|
||||
std::optional<Api::QueueEntry>
|
||||
takeNextTrack(uint64_t expectedQueueId) override;
|
||||
std::optional<Api::QueueEntry> takeAnyNextTrack() override;
|
||||
bool repeatEnabled() const override;
|
||||
void onTrackStarted(const Api::QueueEntry& entry) override;
|
||||
void onTrackFinished(const Api::QueueEntry& entry,
|
||||
std::chrono::milliseconds finalPosition)
|
||||
override;
|
||||
void onPositionTick(const Api::QueueEntry& entry,
|
||||
std::chrono::milliseconds position,
|
||||
std::chrono::milliseconds duration) override;
|
||||
void onEngineIdle() override;
|
||||
void onLocalFileDone(const std::string& path) override;
|
||||
|
||||
// Persist the live queue + shuffle/repeat/autoplay to the database
|
||||
// (kv "session.state") so a full restart can restore them; restore
|
||||
// them at startup. persistSession() is a no-op while a restore is in
|
||||
// progress to avoid recursive writes. includeCurrent=false drops
|
||||
// the currently-playing track from the snapshot — used by stop(),
|
||||
// where the engine clears its entry asynchronously and would
|
||||
// otherwise be persisted as still queued.
|
||||
void persistSession(bool includeCurrent = true);
|
||||
void restoreSession();
|
||||
std::atomic<bool> restoringSession_{false};
|
||||
void onPlaybackError(const Api::Error& error,
|
||||
const std::optional<Api::QueueEntry>& entry)
|
||||
override;
|
||||
|
||||
// ---- helpers ---------------------------------------------------
|
||||
|
||||
// Publish a domain event on the injected bus (no-op until set).
|
||||
template <typename T> void emit(T event)
|
||||
{
|
||||
if (eventBus_) {
|
||||
eventBus_->publish<T>(std::move(event));
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-start the playback loop when a playlist's first track lands.
|
||||
void requestPlaybackStart();
|
||||
// Publish PlaybackPaused/PlaybackResumed with the current track
|
||||
// and position (called from pause/resume and the subscriber
|
||||
// policy hooks so the Desktop sees every pause-state change).
|
||||
void emitPauseState(bool paused);
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||
resolveQuery(const std::string& query);
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
getStreamUrl(const Api::TrackInfo& track);
|
||||
[[nodiscard]] std::string nicknameFor(uint64_t clientId) const;
|
||||
|
||||
// Download audio through proxy for playback
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
downloadAudioForPlayback(const Api::TrackInfo& track);
|
||||
void cleanupTempFile(const std::string& filepath);
|
||||
|
||||
// The proxy the playback engine (ffmpeg) should use. ffmpeg only
|
||||
// speaks HTTP CONNECT, so a SOCKS5 config starts the local
|
||||
// Socks5HttpBridge and is rewritten to an Http proxy pointing at
|
||||
// it; Http/none pass through unchanged (and stop the bridge).
|
||||
[[nodiscard]] std::optional<Void::Net::ProxyConfig>
|
||||
effectiveEngineProxy(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy);
|
||||
|
||||
// ---- state -----------------------------------------------------
|
||||
|
||||
// Temporary file tracking
|
||||
std::set<std::string> tempFiles_;
|
||||
mutable std::shared_mutex tempFilesMutex_;
|
||||
|
||||
// Async playlist loading (background thread owned by the loader).
|
||||
std::unique_ptr<PlaylistLoader> playlistLoader_;
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::shared_ptr<Api::Database> database_;
|
||||
// Non-owning application event bus (provided by Core).
|
||||
Void::EventBus::EventBus* eventBus_ = nullptr;
|
||||
// Non-owning config holder (provided by Core).
|
||||
Api::ConfigManager* configManager_ = nullptr;
|
||||
std::shared_ptr<YouTubeClient> youTubeClient_;
|
||||
|
||||
// Source-resolution chain (proxy-free first, proxied last).
|
||||
std::unique_ptr<SourceRouter> router_;
|
||||
std::shared_ptr<InnertubeSource> innertubeSource_;
|
||||
std::shared_ptr<YandexMusicSource> yandexSource_;
|
||||
std::shared_ptr<YtDlpSource> ytdlpProxied_;
|
||||
|
||||
Api::BotConfig config_;
|
||||
std::atomic<bool> autoStartOnSubscribe_{true};
|
||||
std::atomic<bool> autoplay_{false};
|
||||
QueueService queue_;
|
||||
std::unique_ptr<TrackCache> trackCache_;
|
||||
|
||||
// Vote-to-skip state: voter uids for the queue entry identified
|
||||
// by voteSkipQueueId_ (cleared lazily when the track changes).
|
||||
mutable std::mutex voteSkipMutex_;
|
||||
std::set<std::string> voteSkipUids_;
|
||||
uint64_t voteSkipQueueId_ = 0;
|
||||
std::atomic<uint32_t> voteSkipThreshold_{0}; // 0 = auto majority
|
||||
[[nodiscard]] uint32_t voteSkipNeeded() const;
|
||||
|
||||
// Autoplay state: seed track for recommendations + re-entrancy
|
||||
// guard for the async fetch. The seed's catalog decides where
|
||||
// related tracks are pulled from (YouTube radio mix vs. Yandex
|
||||
// similar tracks).
|
||||
enum class AutoplaySeedSource { None, YouTube, Yandex };
|
||||
mutable std::mutex autoplaySeedMutex_;
|
||||
std::string autoplaySeedId_;
|
||||
AutoplaySeedSource autoplaySeedSource_ = AutoplaySeedSource::None;
|
||||
std::atomic<bool> autoplayFetching_{false};
|
||||
std::jthread autoplayThread_;
|
||||
|
||||
// Fallback seed for radio when nothing has been played this
|
||||
// session: derive one from the most recent history entry.
|
||||
[[nodiscard]] std::optional<
|
||||
std::pair<std::string, AutoplaySeedSource>>
|
||||
autoplaySeedFromHistory() const;
|
||||
|
||||
// Spotify/Yandex collection imports (background metadata fetch;
|
||||
// enqueue itself is instant).
|
||||
std::atomic<bool> importRunning_{false};
|
||||
std::jthread importThread_;
|
||||
std::unique_ptr<PlaybackEngine> engine_;
|
||||
// HTTP CONNECT -> SOCKS5 tunnel for ffmpeg (see
|
||||
// effectiveEngineProxy); only running while the configured proxy
|
||||
// is SOCKS5.
|
||||
std::unique_ptr<Socks5HttpBridge> ffmpegProxyBridge_;
|
||||
std::unique_ptr<SubscriptionService> subscriptions_;
|
||||
|
||||
// Pending search results per client (for select command)
|
||||
std::unordered_map<uint64_t, std::vector<Api::TrackInfo>>
|
||||
pendingSearches_;
|
||||
mutable std::mutex pendingSearchMutex_;
|
||||
|
||||
// Callbacks are stored here as well as forwarded to the
|
||||
// subscription service: Core may register them before
|
||||
// initialize() has created the service.
|
||||
AudioDataCallback audioCallback_;
|
||||
PlaybackStartCallback playbackStartCallback_;
|
||||
NicknameCallback nicknameCallback_;
|
||||
MessageCallback messageCallback_;
|
||||
|
||||
// Deliver the current announcement to (clientId, uid) if that
|
||||
// subscriber hasn't seen it yet (per-uid seen-id in kv_store).
|
||||
// Returns true when a message was actually sent.
|
||||
bool deliverAnnouncementTo(uint64_t clientId,
|
||||
const std::string& uid);
|
||||
SubscriptionChangeCallback subscriptionChangeCallback_;
|
||||
ClientInfoCallback clientInfoCallback_;
|
||||
UidToClientIdCallback uidToClientIdCallback_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,202 +1,91 @@
|
||||
#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 <NetworkInterface.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Functional/Retry.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
// Boost.Beast includes needed for template function
|
||||
#include <boost/beast.hpp>
|
||||
#include <boost/beast/http.hpp>
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// HTTP client implementing Api::INetworkClient. A thin adapter over
|
||||
// Void::Net::HttpClient (HTTP/HTTPS, TLS, SOCKS5 + HTTP-CONNECT proxies);
|
||||
// retry/backoff is layered here via Void::Retry. Speaks Void::Net types
|
||||
// directly — no echoion-side HTTP mirror.
|
||||
class NetworkClient : public Api::INetworkClient
|
||||
{
|
||||
public:
|
||||
|
||||
NetworkClient();
|
||||
~NetworkClient() override;
|
||||
|
||||
Api::Result<void>
|
||||
initialize(const std::optional<Void::Net::ProxyConfig>& proxy =
|
||||
std::nullopt) override;
|
||||
void shutdown() override;
|
||||
|
||||
// Synchronous requests
|
||||
[[nodiscard]] Api::Result<Void::Net::Response> get(
|
||||
std::string_view url,
|
||||
const std::vector<Void::Net::Header>& headers = {}) override;
|
||||
[[nodiscard]] Api::Result<Void::Net::Response> post(
|
||||
std::string_view url, std::string_view body,
|
||||
const std::vector<Void::Net::Header>& headers = {}) override;
|
||||
// Security-sensitive HTTPS request. Unlike legacy media scraping
|
||||
// requests, this always verifies the peer certificate and follows
|
||||
// no redirects so credentials cannot be forwarded to another
|
||||
// origin.
|
||||
[[nodiscard]] Api::Result<Void::Net::Response> postVerifiedTls(
|
||||
std::string_view url, std::string_view body,
|
||||
const std::vector<Void::Net::Header>& headers = {});
|
||||
[[nodiscard]] Api::Result<Void::Net::Response>
|
||||
request(const Void::Net::Request& req) override;
|
||||
|
||||
namespace Echoion::Core {
|
||||
// GET that never uses the configured proxy and does not retry —
|
||||
// for endpoints that must be reached directly and cheaply
|
||||
// (Invidious/Piped instance probes and API calls, public-IP
|
||||
// detection). Callers implement their own fallback across
|
||||
// instances, so retrying a dead one is counterproductive.
|
||||
[[nodiscard]] Api::Result<Void::Net::Response>
|
||||
getDirect(std::string_view url,
|
||||
const std::vector<Void::Net::Header>& headers = {});
|
||||
|
||||
// Forward declaration for URL parsing
|
||||
struct UrlComponents;
|
||||
// Proxy configuration
|
||||
void setProxy(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy) override;
|
||||
[[nodiscard]] std::optional<Void::Net::ProxyConfig>
|
||||
getProxy() const override;
|
||||
void clearProxy() override;
|
||||
|
||||
class NetworkClient : public Api::INetworkClient {
|
||||
public:
|
||||
NetworkClient();
|
||||
~NetworkClient() override;
|
||||
private:
|
||||
|
||||
// Initialize with optional proxy
|
||||
Api::Result<void> initialize(const std::optional<Api::ProxyConfig>& proxy = std::nullopt);
|
||||
void shutdown();
|
||||
// Execute with retry/backoff (Void::Retry); single attempt via
|
||||
// Void::Net::HttpClient.
|
||||
[[nodiscard]] Api::Result<Void::Net::Response>
|
||||
executeWithRetry(const Void::Net::Request& req);
|
||||
[[nodiscard]] Api::Result<Void::Net::Response>
|
||||
executeRequest(const Void::Net::Request& req);
|
||||
|
||||
// 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);
|
||||
std::optional<Void::Net::ProxyConfig> proxy_;
|
||||
mutable std::mutex mutex_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
|
||||
// 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);
|
||||
}
|
||||
// Retry policy + the HTTP statuses worth retrying. Internal
|
||||
// defaults — retry tuning is not part of the public client API.
|
||||
Void::Retry::Policy<Void::Retry::ExponentialBackoff> retryPolicy_{
|
||||
.max_attempts = 4,
|
||||
.backoff = Void::Retry::ExponentialBackoff{
|
||||
.base = std::chrono::milliseconds(1000),
|
||||
.max = std::chrono::milliseconds(30000),
|
||||
.multiplier = 2.0}};
|
||||
std::vector<std::uint16_t> retryableStatusCodes_{408, 429, 500,
|
||||
502, 503, 504};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,75 @@
|
||||
#pragma once
|
||||
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/EventBus.hpp>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
class YouTubeClient;
|
||||
|
||||
// Drives async, streaming playlist loading off the audio path. Owns the
|
||||
// background load thread; resolved tracks are handed to the owner's queue
|
||||
// via the enqueue callback, and the owner is asked to start playback on the
|
||||
// first track via requestStart. Event publishing goes through the bus.
|
||||
class PlaylistLoader
|
||||
{
|
||||
public:
|
||||
|
||||
// Returns true if the track was accepted into the queue.
|
||||
using EnqueueFn =
|
||||
std::function<bool(const Api::TrackInfo&, uint64_t)>;
|
||||
using PlaybackStartFn = std::function<void()>;
|
||||
|
||||
PlaylistLoader(YouTubeClient* yt, Void::EventBus::EventBus* bus,
|
||||
EnqueueFn enqueue, PlaybackStartFn requestStart)
|
||||
: yt_(yt), bus_(bus), enqueue_(std::move(enqueue)),
|
||||
requestStart_(std::move(requestStart))
|
||||
{
|
||||
}
|
||||
|
||||
~PlaylistLoader()
|
||||
{
|
||||
if (loadThread_.joinable()) {
|
||||
loadThread_.join();
|
||||
}
|
||||
}
|
||||
|
||||
PlaylistLoader(const PlaylistLoader&) = delete;
|
||||
PlaylistLoader& operator=(const PlaylistLoader&) = delete;
|
||||
|
||||
[[nodiscard]] Api::Result<void>
|
||||
load(const std::string& playlistIdOrUrl, uint64_t clientId);
|
||||
|
||||
[[nodiscard]] bool isLoading() const { return loading_.load(); }
|
||||
[[nodiscard]] std::size_t loadedCount() const
|
||||
{
|
||||
return loadedCount_.load();
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
template <typename T> void emit(T event)
|
||||
{
|
||||
if (bus_) {
|
||||
bus_->publish<T>(std::move(event));
|
||||
}
|
||||
}
|
||||
|
||||
YouTubeClient* yt_;
|
||||
Void::EventBus::EventBus* bus_;
|
||||
EnqueueFn enqueue_;
|
||||
PlaybackStartFn requestStart_;
|
||||
|
||||
std::thread loadThread_;
|
||||
std::atomic<bool> loading_{false};
|
||||
std::atomic<std::size_t> loadedCount_{0};
|
||||
std::atomic<std::size_t> totalCount_{0};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,111 @@
|
||||
#pragma once
|
||||
|
||||
#include <ExtensionPlugin.hpp>
|
||||
#include <NetworkTypes.hpp>
|
||||
#include <Void/Plugin/Manager.hpp>
|
||||
#include <Void/Service/PluginService.hpp>
|
||||
#include <Void/Service/Registry.hpp>
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
class CommandManager;
|
||||
class MusicManager;
|
||||
class ITrackSource;
|
||||
|
||||
class PluginHost final : public std::enable_shared_from_this<PluginHost>
|
||||
{
|
||||
public:
|
||||
|
||||
struct Configuration {
|
||||
std::filesystem::path configDirectory;
|
||||
std::filesystem::path stateDirectory;
|
||||
std::string publicUrl;
|
||||
std::optional<Void::Net::ProxyConfig> proxy;
|
||||
std::string shortenerProvider = "url-shortener-internal";
|
||||
};
|
||||
|
||||
PluginHost(CommandManager& commands,
|
||||
std::shared_ptr<MusicManager>
|
||||
music,
|
||||
std::function<bool(uint64_t)>
|
||||
isAdmin,
|
||||
std::function<void(std::shared_ptr<ITrackSource>)>
|
||||
mediaSink,
|
||||
Configuration configuration);
|
||||
~PluginHost();
|
||||
|
||||
void loadDirectory(const std::filesystem::path& directory);
|
||||
void loadManagedDirectory(const std::filesystem::path& directory);
|
||||
// Bind and validate cross-plugin services after every startup
|
||||
// directory has been loaded.
|
||||
[[nodiscard]] bool finalizeLoading();
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
manage(const std::string& requestJson);
|
||||
void setChangeCallback(std::function<void()> callback);
|
||||
void dispatch(const Api::PluginEvent& event) const;
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
call(std::string_view plugin, std::string_view method,
|
||||
std::string params, uint64_t clientId) const;
|
||||
[[nodiscard]] std::vector<Api::ExtensionWebAsset> webAssets() const;
|
||||
[[nodiscard]] std::vector<std::string> names() const;
|
||||
[[nodiscard]] bool reconfigure(Configuration configuration);
|
||||
[[nodiscard]] std::shared_ptr<Void::ShortUrl::IShortener>
|
||||
shortener() const;
|
||||
[[nodiscard]] Void::ShortUrl::ResolveResult
|
||||
resolveShortLink(std::string_view key) const;
|
||||
struct State {
|
||||
std::string name;
|
||||
std::string json;
|
||||
std::uint32_t version{};
|
||||
};
|
||||
[[nodiscard]] std::vector<State> snapshotStates() const;
|
||||
void restoreStates(const std::vector<State>& states);
|
||||
|
||||
private:
|
||||
|
||||
void publish(std::string name);
|
||||
void unpublish(std::string name);
|
||||
void notifyChanged() const;
|
||||
[[nodiscard]] std::string
|
||||
pluginConfiguration(std::string_view name) const;
|
||||
[[nodiscard]] bool bindShortenerServices();
|
||||
|
||||
CommandManager& commands_;
|
||||
std::shared_ptr<MusicManager> music_;
|
||||
std::function<bool(uint64_t)> isAdmin_;
|
||||
std::function<void(std::shared_ptr<ITrackSource>)> mediaSink_;
|
||||
Void::Plugin::PluginManager plugins_;
|
||||
Void::Service::ServiceRegistry shortenerRegistry_;
|
||||
Void::Service::ServiceRegistry internalShortenerRegistry_;
|
||||
std::unique_ptr<
|
||||
Void::Service::PluginServiceBinding<Void::ShortUrl::IShortener>>
|
||||
shortenerBinding_;
|
||||
std::unique_ptr<
|
||||
Void::Service::PluginServiceBinding<Void::ShortUrl::IShortener>>
|
||||
internalShortenerBinding_;
|
||||
Void::Plugin::ReloadCallbackId reloadCallback_{};
|
||||
mutable std::mutex reconfigureMutex_;
|
||||
mutable std::mutex mutex_;
|
||||
Configuration configuration_;
|
||||
std::vector<std::shared_ptr<class PluginTrackSource>> sources_;
|
||||
std::function<void()> changeCallback_;
|
||||
struct ManagedPlugin {
|
||||
std::string version;
|
||||
std::filesystem::path path;
|
||||
};
|
||||
std::filesystem::path managedDirectory_;
|
||||
std::unordered_map<std::string, ManagedPlugin> managed_;
|
||||
std::unordered_map<std::string, std::filesystem::path> loadedPaths_;
|
||||
};
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,441 @@
|
||||
#pragma once
|
||||
|
||||
#include <TrackTypes.hpp>
|
||||
#include <ExtensionPlugin.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
// Serialize any reflectable DTO to a JSON string (correct escaping).
|
||||
template <typename T> [[nodiscard]] std::string toJson(const T& dto)
|
||||
{
|
||||
return Void::Json::serialize(Void::Json::to_json(dto));
|
||||
}
|
||||
} // namespace Echoion::Core
|
||||
|
||||
// Reflectable DTOs for the RPC responses and event-broadcast payloads. These
|
||||
// are serialized with Void::Json (reflection) instead of hand-built strings,
|
||||
// so member names are the JSON keys and values are always correctly escaped.
|
||||
namespace Echoion::Core::Dto
|
||||
{
|
||||
|
||||
// ── RPC request payloads (parsed) ───────────────────────────────────────
|
||||
|
||||
struct AuthRequest {
|
||||
std::optional<std::string> nickname;
|
||||
std::optional<std::string> token;
|
||||
};
|
||||
|
||||
struct SeekRequest {
|
||||
std::int64_t position = 0; // milliseconds
|
||||
};
|
||||
|
||||
struct VolumeRequest {
|
||||
float volume = 0.5f; // normalised 0.0 - 1.0
|
||||
};
|
||||
|
||||
struct SkipRequest {
|
||||
std::uint32_t count = 1;
|
||||
};
|
||||
|
||||
struct QueueTrackRequest {
|
||||
std::string query;
|
||||
};
|
||||
|
||||
struct QueueIdRequest {
|
||||
std::uint64_t queueId = 0;
|
||||
};
|
||||
|
||||
struct MoveRequest {
|
||||
std::uint64_t queueId = 0;
|
||||
std::uint32_t newPosition = 0;
|
||||
};
|
||||
|
||||
struct SearchRequest {
|
||||
std::string query;
|
||||
};
|
||||
|
||||
struct TrackIdRequest {
|
||||
std::string id;
|
||||
};
|
||||
|
||||
struct PlaylistIdRequest {
|
||||
std::string playlistId;
|
||||
};
|
||||
|
||||
struct SavePlaylistRequest {
|
||||
std::string name;
|
||||
std::string description;
|
||||
};
|
||||
|
||||
struct ManageUsersRequest {
|
||||
std::string action; // "list" | "remove" | "clearAll"
|
||||
std::optional<std::string> uid;
|
||||
};
|
||||
|
||||
struct UrlRequest {
|
||||
std::string url;
|
||||
};
|
||||
|
||||
struct AnnounceRequest {
|
||||
std::string text;
|
||||
};
|
||||
|
||||
// ── RPC handler responses ───────────────────────────────────────────────
|
||||
|
||||
struct Track {
|
||||
std::string id;
|
||||
std::string title;
|
||||
std::string artist;
|
||||
std::string album;
|
||||
std::optional<std::int64_t> duration; // milliseconds
|
||||
int source = 0;
|
||||
std::optional<std::string> thumbnailUrl;
|
||||
std::optional<std::string> url; // originalUrl (play-by-url)
|
||||
// Provider-generated shortened link when available; the web UI prefers
|
||||
// it for "open original link" (falls back to url).
|
||||
std::optional<std::string> shortenedUrl;
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Track toTrack(const Api::TrackInfo& t)
|
||||
{
|
||||
return Track{.id = t.id,
|
||||
.title = t.title,
|
||||
.artist = t.artist,
|
||||
.album = t.album,
|
||||
.duration = t.duration
|
||||
? std::optional<std::int64_t>(
|
||||
t.duration->count())
|
||||
: std::nullopt,
|
||||
.source = static_cast<int>(t.source),
|
||||
.thumbnailUrl = t.thumbnailUrl,
|
||||
.url = t.originalUrl.empty()
|
||||
? std::nullopt
|
||||
: std::optional(t.originalUrl),
|
||||
.shortenedUrl =
|
||||
t.shortenedUrl && !t.shortenedUrl->empty()
|
||||
? t.shortenedUrl
|
||||
: std::nullopt};
|
||||
}
|
||||
|
||||
// Inverse of toTrack (client-supplied tracks, e.g. AddFavorite).
|
||||
[[nodiscard]] inline Api::TrackInfo fromTrack(const Track& t)
|
||||
{
|
||||
Api::TrackInfo info;
|
||||
info.id = t.id;
|
||||
info.title = t.title;
|
||||
info.artist = t.artist;
|
||||
info.album = t.album;
|
||||
if (t.duration) {
|
||||
info.duration = std::chrono::milliseconds(*t.duration);
|
||||
}
|
||||
info.source = static_cast<Api::TrackSource>(t.source);
|
||||
info.thumbnailUrl = t.thumbnailUrl;
|
||||
info.originalUrl = t.url.value_or("");
|
||||
return info;
|
||||
}
|
||||
|
||||
struct QueueItem {
|
||||
std::uint64_t queueId = 0;
|
||||
Track track;
|
||||
bool isPlaying = false;
|
||||
};
|
||||
|
||||
struct QueueResponse {
|
||||
std::vector<QueueItem> queue;
|
||||
};
|
||||
|
||||
struct CurrentTrackResponse {
|
||||
std::optional<Track> track;
|
||||
};
|
||||
|
||||
struct Status {
|
||||
bool isPlaying = false;
|
||||
bool isPaused = false;
|
||||
float volume = 0.0f;
|
||||
bool repeat = false;
|
||||
bool shuffle = false;
|
||||
// Radio mode: auto-enqueue related tracks when the queue runs dry.
|
||||
bool autoplay = false;
|
||||
// Vote-skip state for the current track (additive fields).
|
||||
std::uint32_t skipVotes = 0;
|
||||
std::uint32_t skipVotesNeeded = 0;
|
||||
bool skipVoted = false;
|
||||
};
|
||||
|
||||
struct Success {
|
||||
bool success = true;
|
||||
};
|
||||
|
||||
struct SuccessMessage {
|
||||
bool success = true;
|
||||
std::string message;
|
||||
};
|
||||
|
||||
struct SuccessVolume {
|
||||
bool success = true;
|
||||
float volume = 0.0f;
|
||||
};
|
||||
|
||||
struct Capabilities {
|
||||
bool plugins = false;
|
||||
bool webExtensions = false;
|
||||
};
|
||||
|
||||
struct PluginCallRequest {
|
||||
std::string plugin;
|
||||
std::string method;
|
||||
std::string params;
|
||||
};
|
||||
|
||||
struct PluginExtensions {
|
||||
std::vector<Api::ExtensionWebAsset> assets;
|
||||
};
|
||||
|
||||
struct Autoplay {
|
||||
bool autoplay = false;
|
||||
};
|
||||
|
||||
// Per-user preferences stored in the kv store; `language` shares the
|
||||
// "lang:<uid>" key with the !lang chat command so the web switcher and
|
||||
// the bot stay in sync.
|
||||
struct UserPrefs {
|
||||
std::string language;
|
||||
};
|
||||
|
||||
struct QueuedResponse {
|
||||
bool success = true;
|
||||
std::uint64_t queueId = 0;
|
||||
};
|
||||
|
||||
struct SearchResults {
|
||||
std::vector<Track> tracks;
|
||||
};
|
||||
|
||||
struct PlaylistBrief {
|
||||
std::string id;
|
||||
std::string name;
|
||||
std::string description;
|
||||
std::uint32_t trackCount = 0;
|
||||
};
|
||||
|
||||
struct PlaylistList {
|
||||
std::vector<PlaylistBrief> playlists;
|
||||
};
|
||||
|
||||
struct PlaylistContents {
|
||||
std::string id;
|
||||
std::string name;
|
||||
std::string description;
|
||||
std::vector<Track> tracks;
|
||||
};
|
||||
|
||||
struct HistoryRequest {
|
||||
std::uint32_t limit = 20;
|
||||
};
|
||||
|
||||
struct HistoryResponse {
|
||||
std::vector<Track> tracks;
|
||||
};
|
||||
|
||||
struct StatsResponse {
|
||||
std::uint64_t totalPlays = 0;
|
||||
std::uint64_t totalTracks = 0;
|
||||
std::uint64_t totalPlaytimeMs = 0;
|
||||
std::optional<std::string> mostPlayedTitle;
|
||||
std::uint64_t mostPlayedCount = 0;
|
||||
};
|
||||
|
||||
struct ServerInfo {
|
||||
std::string version;
|
||||
std::int64_t uptimeSeconds = 0;
|
||||
std::uint32_t connectedClients = 0;
|
||||
std::uint32_t subscribers = 0;
|
||||
std::uint32_t queueLength = 0;
|
||||
std::uint32_t onlineSubscribers = 0;
|
||||
// Nicknames behind onlineSubscribers, so non-admin clients can
|
||||
// render a "listening now" list without the admin user API.
|
||||
std::vector<std::string> onlineSubscriberNames;
|
||||
// TeamSpeak uids parallel to onlineSubscriberNames (same order), so
|
||||
// the web UI can fetch each listener's avatar at /avatar/<uid>.
|
||||
std::vector<std::string> onlineSubscriberUids;
|
||||
};
|
||||
|
||||
struct AuditEntryDto {
|
||||
std::uint64_t clientId = 0;
|
||||
int method = 0;
|
||||
std::int64_t timestamp = 0; // unix seconds
|
||||
};
|
||||
|
||||
struct AuditLogResponse {
|
||||
std::vector<AuditEntryDto> entries;
|
||||
};
|
||||
|
||||
struct SubscriberDto {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
bool online = false;
|
||||
};
|
||||
|
||||
struct UsersResponse {
|
||||
std::vector<SubscriberDto> users;
|
||||
};
|
||||
|
||||
// Authenticate success. isAdmin/isDj/uid/nickname are additive — older
|
||||
// clients that only read `message` keep working.
|
||||
struct AuthSuccess {
|
||||
bool success = true;
|
||||
std::string message;
|
||||
bool isAdmin = false;
|
||||
bool isDj = false;
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
// Set by address-based autologin so the client can persist the
|
||||
// session token it never typed; empty for normal token auth.
|
||||
std::string token;
|
||||
};
|
||||
|
||||
struct AddFavoriteRequest {
|
||||
Track track;
|
||||
};
|
||||
|
||||
struct FavoritesResponse {
|
||||
std::vector<Track> tracks;
|
||||
};
|
||||
|
||||
// GetLyrics response: plain text plus, when available, time-synced lines
|
||||
// (ms offset from track start) so the web UI can highlight the active line.
|
||||
struct LyricsLineDto {
|
||||
std::int64_t ms = 0;
|
||||
std::string text;
|
||||
};
|
||||
|
||||
struct LyricsResponse {
|
||||
bool found = false;
|
||||
std::string plain;
|
||||
std::vector<LyricsLineDto> synced;
|
||||
std::string source; // "lrclib" when resolved
|
||||
std::string title;
|
||||
std::string artist;
|
||||
};
|
||||
|
||||
struct VoteSkipResponse {
|
||||
std::uint32_t votes = 0;
|
||||
std::uint32_t needed = 0;
|
||||
bool voted = false;
|
||||
bool skipped = false;
|
||||
};
|
||||
|
||||
struct RequesterDto {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
std::uint64_t count = 0;
|
||||
};
|
||||
|
||||
struct AggregateStatsResponse {
|
||||
std::uint64_t tracksToday = 0;
|
||||
std::uint64_t listeningMsToday = 0;
|
||||
std::uint64_t queueAdditionsToday = 0;
|
||||
std::uint64_t skipsToday = 0;
|
||||
std::uint64_t playsTotal = 0;
|
||||
std::uint64_t skipsTotal = 0;
|
||||
std::vector<RequesterDto> topRequesters;
|
||||
std::uint64_t youtubeCount = 0;
|
||||
std::uint64_t yandexCount = 0;
|
||||
std::uint64_t otherCount = 0;
|
||||
};
|
||||
|
||||
// ── Event-broadcast payloads ────────────────────────────────────────────
|
||||
|
||||
struct TrackBrief {
|
||||
std::string id;
|
||||
std::string title;
|
||||
std::string artist;
|
||||
};
|
||||
|
||||
struct PlaybackStarted {
|
||||
TrackBrief track;
|
||||
std::int64_t position = 0;
|
||||
};
|
||||
|
||||
struct Position {
|
||||
std::int64_t position = 0;
|
||||
};
|
||||
|
||||
struct PositionProgress {
|
||||
std::int64_t position = 0;
|
||||
std::int64_t duration = 0;
|
||||
float progress = 0.0f;
|
||||
};
|
||||
|
||||
struct Volume {
|
||||
float volume = 0.0f;
|
||||
};
|
||||
|
||||
struct Shuffle {
|
||||
bool shuffle = false;
|
||||
};
|
||||
|
||||
struct Repeat {
|
||||
bool repeat = false;
|
||||
};
|
||||
|
||||
struct TrackQueued {
|
||||
std::uint64_t queueId = 0;
|
||||
std::string title;
|
||||
std::string artist;
|
||||
std::uint32_t position = 0;
|
||||
std::uint32_t queueLength = 0;
|
||||
};
|
||||
|
||||
struct TrackRemoved {
|
||||
std::uint64_t queueId = 0;
|
||||
std::uint32_t queueLength = 0;
|
||||
};
|
||||
|
||||
struct QueueReordered {
|
||||
std::uint64_t queueId = 0;
|
||||
std::uint32_t oldPosition = 0;
|
||||
std::uint32_t newPosition = 0;
|
||||
};
|
||||
|
||||
struct PlaylistId {
|
||||
std::string playlistId;
|
||||
};
|
||||
|
||||
struct PlaylistTrackLoaded {
|
||||
std::string playlistId;
|
||||
std::uint32_t loaded = 0;
|
||||
std::uint32_t total = 0;
|
||||
};
|
||||
|
||||
struct PlaylistLoadCompleted {
|
||||
std::string playlistId;
|
||||
std::uint32_t totalTracks = 0;
|
||||
bool success = false;
|
||||
};
|
||||
|
||||
struct User {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
};
|
||||
|
||||
struct ClientId {
|
||||
std::uint64_t clientId = 0;
|
||||
};
|
||||
|
||||
// Plugin-event track payload (duration in seconds, matching the legacy
|
||||
// broadcastEvent shape).
|
||||
struct EventTrack {
|
||||
std::string id;
|
||||
std::string title;
|
||||
std::string artist;
|
||||
std::int64_t duration = 0;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core::Dto
|
||||
@@ -1,81 +1,136 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include <PluginTypes.hpp>
|
||||
#include <RpcTypes.hpp>
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/ThreadPool.hpp>
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/beast.hpp>
|
||||
#include <boost/beast/websocket.hpp>
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <chrono>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
namespace asio = boost::asio;
|
||||
namespace beast = boost::beast;
|
||||
namespace websocket = beast::websocket;
|
||||
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)>;
|
||||
class RpcServer : public std::enable_shared_from_this<RpcServer>
|
||||
{
|
||||
public:
|
||||
|
||||
RpcServer();
|
||||
~RpcServer();
|
||||
using CommandHandler = std::function<Api::Result<std::string>(
|
||||
const std::string& params, uint64_t clientId)>;
|
||||
|
||||
// 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_; }
|
||||
RpcServer();
|
||||
~RpcServer();
|
||||
|
||||
// Register command handlers
|
||||
void registerHandler(const std::string& method, CommandHandler handler);
|
||||
void unregisterHandler(const std::string& method);
|
||||
// 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_; }
|
||||
|
||||
// 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);
|
||||
// Register command handlers
|
||||
void registerHandler(const std::string& method,
|
||||
CommandHandler handler);
|
||||
void unregisterHandler(const std::string& method);
|
||||
|
||||
// Broadcast events to all connected clients
|
||||
void broadcastEvent(const std::string& event, const std::string& data);
|
||||
// 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);
|
||||
|
||||
// Send event to specific client
|
||||
void sendEvent(uint64_t clientId, const std::string& event, const std::string& data);
|
||||
// The client's effective network address: the X-Echoion-Client-Ip
|
||||
// header set by the web server's /rpc bridge (trusted only from
|
||||
// loopback peers), else the socket's remote address. Used for
|
||||
// address-based autologin.
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
getClientAddress(uint64_t clientId) const;
|
||||
|
||||
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);
|
||||
// Server introspection (for GetServerInfo / GetAuditLog).
|
||||
struct AuditEntry {
|
||||
uint64_t clientId = 0;
|
||||
int method = 0;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
[[nodiscard]] std::vector<AuditEntry> getAuditLog() const;
|
||||
[[nodiscard]] size_t getClientCount() const;
|
||||
[[nodiscard]] std::chrono::seconds getUptime() const;
|
||||
|
||||
asio::io_context ioContext_;
|
||||
std::optional<asio::ip::tcp::acceptor> acceptor_;
|
||||
std::thread serverThread_;
|
||||
std::atomic<bool> running_{false};
|
||||
uint16_t port_ = 8765;
|
||||
// Broadcast events to all connected clients
|
||||
void broadcastEvent(const std::string& event,
|
||||
const std::string& data);
|
||||
|
||||
// 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_;
|
||||
// Send event to specific client
|
||||
void sendEvent(uint64_t clientId, const std::string& event,
|
||||
const std::string& data);
|
||||
|
||||
// Authenticated clients
|
||||
std::set<uint64_t> authenticatedClients_;
|
||||
std::mutex authMutex_;
|
||||
std::string authToken_;
|
||||
private:
|
||||
|
||||
// Command handlers
|
||||
std::unordered_map<std::string, CommandHandler> handlers_;
|
||||
std::mutex handlersMutex_;
|
||||
};
|
||||
void acceptLoop();
|
||||
void doAccept();
|
||||
void onAccept(asio::ip::tcp::socket socket);
|
||||
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_;
|
||||
// clientId -> effective network address (see getClientAddress).
|
||||
std::unordered_map<uint64_t, std::string> clientAddresses_;
|
||||
mutable std::mutex clientsMutex_;
|
||||
std::atomic<uint64_t> nextClientId_{1};
|
||||
|
||||
// Per-client handlers run on a Void worker pool instead of one
|
||||
// detached std::thread each; ~ThreadPool drains and joins them on
|
||||
// stop. Sized well above any realistic concurrent-client count
|
||||
// (each long-lived handler holds a worker for the connection's
|
||||
// lifetime).
|
||||
static constexpr std::size_t CLIENT_POOL_SIZE = 64;
|
||||
std::unique_ptr<Void::Concurrency::ThreadPool> clientPool_;
|
||||
|
||||
// Authenticated clients
|
||||
std::set<uint64_t> authenticatedClients_;
|
||||
std::mutex authMutex_;
|
||||
std::string authToken_;
|
||||
|
||||
// Audit ring + uptime tracking
|
||||
mutable std::mutex auditMutex_;
|
||||
std::deque<AuditEntry> auditLog_;
|
||||
static constexpr size_t MAX_AUDIT_ENTRIES = 500;
|
||||
std::chrono::steady_clock::time_point startTime_{
|
||||
std::chrono::steady_clock::now()};
|
||||
|
||||
// Command handlers
|
||||
std::unordered_map<std::string, CommandHandler> handlers_;
|
||||
std::mutex handlersMutex_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,87 @@
|
||||
#pragma once
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Session management for RPC clients
|
||||
// Supports 100+ concurrent authenticated sessions
|
||||
class SessionManager
|
||||
{
|
||||
public:
|
||||
|
||||
struct Session {
|
||||
uint64_t clientId;
|
||||
std::string authToken;
|
||||
std::chrono::steady_clock::time_point lastActivity;
|
||||
std::chrono::steady_clock::time_point createdAt;
|
||||
bool isAuthenticated;
|
||||
|
||||
// Optional: store client-specific state
|
||||
struct ClientState {
|
||||
std::optional<std::string> currentPlaylist;
|
||||
float preferredVolume = -1.0f; // -1 = use default
|
||||
// Add more client preferences here
|
||||
};
|
||||
std::optional<ClientState> clientState;
|
||||
};
|
||||
|
||||
struct Config {
|
||||
size_t maxSessions = 150; // 100 users + buffer
|
||||
std::chrono::seconds sessionTimeout{3600}; // 1 hour timeout
|
||||
std::chrono::seconds cleanupInterval{
|
||||
300}; // Cleanup every 5 min
|
||||
};
|
||||
|
||||
SessionManager();
|
||||
explicit SessionManager(const Config& config);
|
||||
|
||||
// Initialize session manager
|
||||
bool initialize();
|
||||
void shutdown();
|
||||
|
||||
// Create new session
|
||||
std::string createSession(uint64_t clientId);
|
||||
|
||||
// Authenticate session
|
||||
bool authenticateSession(const std::string& token);
|
||||
|
||||
// Validate and update session
|
||||
bool validateSession(const std::string& token);
|
||||
void updateActivity(const std::string& token);
|
||||
|
||||
// Get session info
|
||||
std::optional<Session> getSession(const std::string& token) const;
|
||||
|
||||
// End session
|
||||
void endSession(const std::string& token);
|
||||
void endSessionByClientId(uint64_t clientId);
|
||||
|
||||
// Get all active sessions
|
||||
std::vector<Session> getAllSessions() const;
|
||||
|
||||
// Get session count
|
||||
size_t getSessionCount() const;
|
||||
|
||||
// Cleanup expired sessions (call periodically)
|
||||
size_t cleanupExpiredSessions();
|
||||
|
||||
// Check if at capacity
|
||||
bool isAtCapacity() const;
|
||||
|
||||
private:
|
||||
|
||||
std::string generateToken();
|
||||
|
||||
Config config_;
|
||||
std::unordered_map<std::string, Session> sessions_;
|
||||
mutable std::mutex mutex_;
|
||||
std::atomic<bool> running_{false};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,129 +1,141 @@
|
||||
#pragma once
|
||||
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
#include <optional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <filesystem>
|
||||
|
||||
#include <quickjs.h>
|
||||
// Opaque quickjs handles — only the .cpp needs <quickjs.h>, and keeping it
|
||||
// out of this header keeps the quickjs include dir private to EchoionCore.
|
||||
struct JSRuntime;
|
||||
struct JSContext;
|
||||
|
||||
namespace Echoion::Core {
|
||||
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();
|
||||
/**
|
||||
* 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:
|
||||
|
||||
// Disable copy, enable move
|
||||
SignatureCipher(const SignatureCipher&) = delete;
|
||||
SignatureCipher& operator=(const SignatureCipher&) = delete;
|
||||
SignatureCipher(SignatureCipher&&) noexcept;
|
||||
SignatureCipher& operator=(SignatureCipher&&) noexcept;
|
||||
SignatureCipher();
|
||||
~SignatureCipher();
|
||||
|
||||
/**
|
||||
* Initialize the QuickJS solver with core libraries
|
||||
* Must be called before using the cipher
|
||||
*/
|
||||
void initialize();
|
||||
// Disable copy, enable move
|
||||
SignatureCipher(const SignatureCipher&) = delete;
|
||||
SignatureCipher& operator=(const SignatureCipher&) = delete;
|
||||
SignatureCipher(SignatureCipher&&) noexcept;
|
||||
SignatureCipher& operator=(SignatureCipher&&) noexcept;
|
||||
|
||||
/**
|
||||
* 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);
|
||||
/**
|
||||
* Initialize the QuickJS solver with core libraries
|
||||
* Must be called before using the cipher
|
||||
*/
|
||||
void initialize();
|
||||
|
||||
/**
|
||||
* Check if the cipher is ready (has valid decipher function)
|
||||
*/
|
||||
[[nodiscard]] bool isReady() const;
|
||||
/**
|
||||
* 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);
|
||||
|
||||
/**
|
||||
* 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);
|
||||
/**
|
||||
* Check if the cipher is ready (has valid decipher function)
|
||||
*/
|
||||
[[nodiscard]] bool isReady() const;
|
||||
|
||||
/**
|
||||
* 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 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);
|
||||
|
||||
/**
|
||||
* 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);
|
||||
/**
|
||||
* 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);
|
||||
|
||||
/**
|
||||
* Clear the cipher state
|
||||
*/
|
||||
void clear();
|
||||
/**
|
||||
* 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);
|
||||
|
||||
/**
|
||||
* Check if cipher has been initialized
|
||||
*/
|
||||
[[nodiscard]] bool isInitialized() const;
|
||||
/**
|
||||
* Clear the cipher state
|
||||
*/
|
||||
void clear();
|
||||
|
||||
private:
|
||||
/**
|
||||
* Initialize QuickJS runtime and context with solver libraries
|
||||
*/
|
||||
void initSolver();
|
||||
/**
|
||||
* Check if cipher has been initialized
|
||||
*/
|
||||
[[nodiscard]] bool isInitialized() const;
|
||||
|
||||
/**
|
||||
* 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);
|
||||
private:
|
||||
|
||||
/**
|
||||
* Get cache directory for storing solver libraries
|
||||
*/
|
||||
[[nodiscard]] std::filesystem::path getCacheDir();
|
||||
/**
|
||||
* Initialize QuickJS runtime and context with solver libraries
|
||||
*/
|
||||
void initSolver();
|
||||
|
||||
/**
|
||||
* Execute JavaScript code in QuickJS and return result
|
||||
*/
|
||||
[[nodiscard]] std::optional<std::string> executeJS(
|
||||
std::string_view code,
|
||||
std::string_view filename = "<script>");
|
||||
/**
|
||||
* 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);
|
||||
|
||||
/**
|
||||
* Cleanup QuickJS resources
|
||||
*/
|
||||
void cleanupQuickJS();
|
||||
/**
|
||||
* Get cache directory for storing solver libraries
|
||||
*/
|
||||
[[nodiscard]] std::filesystem::path getCacheDir();
|
||||
|
||||
JSRuntime* runtime_ = nullptr;
|
||||
JSContext* context_ = nullptr;
|
||||
/**
|
||||
* Execute JavaScript code in QuickJS and return result
|
||||
*/
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
executeJS(std::string_view code,
|
||||
std::string_view filename = "<script>");
|
||||
|
||||
// Player JS code and extracted functions
|
||||
std::string playerJsCode_;
|
||||
std::string preprocessedPlayer_;
|
||||
/**
|
||||
* Cleanup QuickJS resources
|
||||
*/
|
||||
void cleanupQuickJS();
|
||||
|
||||
// State
|
||||
bool initialized_ = false;
|
||||
bool solverInitialized_ = false;
|
||||
bool hasPlayerJs_ = false;
|
||||
JSRuntime* runtime_ = nullptr;
|
||||
JSContext* context_ = nullptr;
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
};
|
||||
// Player JS code and extracted functions
|
||||
std::string playerJsCode_;
|
||||
std::string preprocessedPlayer_;
|
||||
|
||||
// State
|
||||
bool initialized_ = false;
|
||||
bool solverInitialized_ = false;
|
||||
bool hasPlayerJs_ = false;
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,90 @@
|
||||
#pragma once
|
||||
|
||||
#include <Types.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <boost/asio.hpp>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Local HTTP CONNECT proxy that tunnels through a SOCKS5 upstream.
|
||||
//
|
||||
// FFmpeg has no SOCKS5 support at all — its http protocol only knows the
|
||||
// `http_proxy` option, which speaks HTTP CONNECT. To stream IP-locked
|
||||
// googlevideo URLs directly through a SOCKS5 proxy, the decoder is pointed
|
||||
// at 127.0.0.1:<port()> and every CONNECT is forwarded through the
|
||||
// configured SOCKS5 proxy (greeting/auth/CONNECT handshake, then a raw
|
||||
// byte pump in both directions).
|
||||
//
|
||||
// Only the two decoder slots stream concurrently, so a blocking
|
||||
// thread-per-connection design is deliberate: no io_context pump, no
|
||||
// async state machines.
|
||||
class Socks5HttpBridge
|
||||
{
|
||||
public:
|
||||
|
||||
Socks5HttpBridge() = default;
|
||||
~Socks5HttpBridge();
|
||||
|
||||
Socks5HttpBridge(const Socks5HttpBridge&) = delete;
|
||||
Socks5HttpBridge& operator=(const Socks5HttpBridge&) = delete;
|
||||
|
||||
// Bind 127.0.0.1:<ephemeral>, start the accept thread and return
|
||||
// the bound port. Restarts (against the new upstream) when already
|
||||
// running.
|
||||
Api::Result<uint16_t> start(const Void::Net::ProxyConfig& socks5);
|
||||
|
||||
// Close the acceptor and every live tunnel; joins all threads.
|
||||
void stop();
|
||||
|
||||
[[nodiscard]] bool running() const { return running_.load(); }
|
||||
[[nodiscard]] uint16_t port() const { return port_; }
|
||||
|
||||
// The SOCKS5 endpoint the bridge currently forwards to (empty when
|
||||
// stopped). Lets callers skip a restart when the config is
|
||||
// unchanged.
|
||||
[[nodiscard]] std::optional<Void::Net::ProxyConfig> upstream() const;
|
||||
|
||||
private:
|
||||
|
||||
struct Connection {
|
||||
boost::asio::ip::tcp::socket client;
|
||||
boost::asio::ip::tcp::socket upstream;
|
||||
std::atomic<bool> done{false};
|
||||
std::thread worker;
|
||||
|
||||
explicit Connection(boost::asio::io_context& io)
|
||||
: client(io), upstream(io)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
void acceptLoop();
|
||||
void serve(Connection& conn);
|
||||
// SOCKS5 greeting/auth/CONNECT for host:port on conn.upstream.
|
||||
// Throws std::runtime_error on any protocol failure.
|
||||
void socks5Connect(boost::asio::ip::tcp::socket& upstream,
|
||||
const std::string& host, uint16_t targetPort,
|
||||
const Void::Net::ProxyConfig& proxy);
|
||||
// Drop connections whose worker already finished (joins them).
|
||||
void pruneFinished();
|
||||
|
||||
boost::asio::io_context io_;
|
||||
std::optional<boost::asio::ip::tcp::acceptor> acceptor_;
|
||||
std::thread acceptThread_;
|
||||
uint16_t port_ = 0;
|
||||
std::atomic<bool> running_{false};
|
||||
|
||||
mutable std::mutex mutex_; // guards upstream_ and connections_
|
||||
std::optional<Void::Net::ProxyConfig> upstream_;
|
||||
std::vector<std::unique_ptr<Connection>> connections_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,45 +1,73 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "Database.hpp"
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <mutex>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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();
|
||||
/**
|
||||
* Manages user subscriptions to the bot's audio output
|
||||
* Subscriptions are persisted to database and survive client reloads
|
||||
* Uses unique client UID instead of session-specific client ID
|
||||
*/
|
||||
class SubscriptionManager
|
||||
{
|
||||
public:
|
||||
|
||||
// Initialize and load subscriptions from database
|
||||
Api::Result<void> initialize(std::shared_ptr<Api::Database> database);
|
||||
void shutdown();
|
||||
struct Subscriber {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
};
|
||||
|
||||
// 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;
|
||||
SubscriptionManager();
|
||||
~SubscriptionManager();
|
||||
|
||||
private:
|
||||
std::set<uint64_t> subscribedClients_;
|
||||
mutable std::mutex mutex_;
|
||||
std::shared_ptr<Api::Database> database_;
|
||||
bool initialized_ = false;
|
||||
};
|
||||
// Initialize and load subscriptions from database
|
||||
Api::Result<void>
|
||||
initialize(std::shared_ptr<Api::Database> database);
|
||||
void shutdown();
|
||||
|
||||
// Subscription management (by UID)
|
||||
bool subscribe(const std::string& uid, const std::string& nickname);
|
||||
bool unsubscribe(const std::string& uid);
|
||||
bool isSubscribed(const std::string& uid) const;
|
||||
|
||||
// Get all subscribed UIDs
|
||||
std::vector<std::string> getSubscribedUids() const;
|
||||
|
||||
// Get all subscribers with info
|
||||
std::vector<Subscriber> getSubscribers() const;
|
||||
|
||||
// Get subscriber nickname
|
||||
std::optional<std::string>
|
||||
getSubscriberNickname(const std::string& uid) const;
|
||||
|
||||
// Update nickname for subscriber
|
||||
bool updateNickname(const std::string& uid,
|
||||
const std::string& nickname);
|
||||
|
||||
// Check if anyone is subscribed
|
||||
bool hasSubscribers() const;
|
||||
|
||||
// Get subscriber count
|
||||
size_t getSubscriberCount() const;
|
||||
|
||||
// Clear all subscriptions
|
||||
bool clearAll();
|
||||
|
||||
private:
|
||||
|
||||
std::set<std::string> subscribedUids_;
|
||||
mutable std::mutex mutex_;
|
||||
std::shared_ptr<Api::Database> database_;
|
||||
bool initialized_ = false;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,121 @@
|
||||
#pragma once
|
||||
|
||||
#include "SubscriptionManager.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/EventBus.hpp>
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Subscription bookkeeping + audience policy, extracted from
|
||||
// MusicManager. Owns the persistent SubscriptionManager and the
|
||||
// client-resolution callbacks; drives the pause-on-empty /
|
||||
// resume-on-return policy through two injected hooks so it never touches
|
||||
// playback internals directly.
|
||||
class SubscriptionService
|
||||
{
|
||||
public:
|
||||
|
||||
using ClientInfoCallback = std::function<std::optional<
|
||||
std::pair<std::string, std::string>>(uint64_t clientId)>;
|
||||
using UidToClientIdCallback =
|
||||
std::function<std::optional<uint64_t>(const std::string& uid)>;
|
||||
using ChangeCallback = std::function<void()>;
|
||||
// requestPause returns true when playback was actually paused by
|
||||
// this policy (so a returning subscriber should resume it).
|
||||
using RequestPause = std::function<bool()>;
|
||||
using RequestResume = std::function<bool()>;
|
||||
|
||||
Api::Result<void>
|
||||
initialize(std::shared_ptr<Api::Database> database);
|
||||
|
||||
void setEventBus(Void::EventBus::EventBus* bus) { eventBus_ = bus; }
|
||||
void setClientInfoCallback(ClientInfoCallback cb)
|
||||
{
|
||||
clientInfo_ = std::move(cb);
|
||||
}
|
||||
void setUidToClientIdCallback(UidToClientIdCallback cb)
|
||||
{
|
||||
uidToClientId_ = std::move(cb);
|
||||
}
|
||||
void setChangeCallback(ChangeCallback cb)
|
||||
{
|
||||
onChange_ = std::move(cb);
|
||||
}
|
||||
void setPauseResumeHooks(RequestPause pause, RequestResume resume)
|
||||
{
|
||||
requestPause_ = std::move(pause);
|
||||
requestResume_ = std::move(resume);
|
||||
}
|
||||
|
||||
// Audience policy toggles (features.pauseOnEmptySubscribers /
|
||||
// features.resumeOnSubscriberReturn); re-applied on config
|
||||
// reload.
|
||||
void setPolicy(bool pauseOnEmpty, bool resumeOnReturn)
|
||||
{
|
||||
pauseOnEmpty_ = pauseOnEmpty;
|
||||
resumeOnReturn_ = resumeOnReturn;
|
||||
}
|
||||
|
||||
// Command surface (message strings go back to the chat user).
|
||||
[[nodiscard]] Api::Result<std::string> subscribe(uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
unsubscribe(uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
unsubscribeByUid(const std::string& uid);
|
||||
[[nodiscard]] Api::Result<std::string> clearAllSubscriptions();
|
||||
|
||||
[[nodiscard]] bool isSubscribed(uint64_t clientId) const;
|
||||
[[nodiscard]] bool hasSubscribers() const;
|
||||
[[nodiscard]] bool hasOnlineSubscribers() const;
|
||||
[[nodiscard]] std::set<uint64_t> getSubscribedClients() const;
|
||||
[[nodiscard]] std::set<std::string> getOnlineSubscriberUids() const;
|
||||
[[nodiscard]] std::vector<SubscriptionManager::Subscriber>
|
||||
getSubscribers() const;
|
||||
|
||||
// Presence events from the plugin. onClientConnected resolves the
|
||||
// client once and hands the uid back so callers don't repeat the
|
||||
// (plugin round-trip) lookup: subscribedUid is set when the
|
||||
// client is a subscriber; mayAutoStart when playback should
|
||||
// auto-start if tracks are queued.
|
||||
struct ClientConnectResult {
|
||||
std::optional<std::string> subscribedUid;
|
||||
bool mayAutoStart = false;
|
||||
};
|
||||
ClientConnectResult onClientConnected(uint64_t clientId);
|
||||
void onClientDisconnected(uint64_t clientId);
|
||||
|
||||
private:
|
||||
|
||||
template <typename T> void emit(T event)
|
||||
{
|
||||
if (eventBus_) {
|
||||
eventBus_->publish<T>(std::move(event));
|
||||
}
|
||||
}
|
||||
|
||||
// Pause playback if the audience vanished; remember that WE
|
||||
// paused so the next returning subscriber resumes.
|
||||
void pauseIfAudienceGone();
|
||||
|
||||
std::unique_ptr<SubscriptionManager> manager_;
|
||||
Void::EventBus::EventBus* eventBus_ = nullptr;
|
||||
ClientInfoCallback clientInfo_;
|
||||
UidToClientIdCallback uidToClientId_;
|
||||
ChangeCallback onChange_;
|
||||
RequestPause requestPause_;
|
||||
RequestResume requestResume_;
|
||||
std::atomic<bool> pausedForNoSubscribers_{false};
|
||||
std::atomic<bool> pauseOnEmpty_{true};
|
||||
std::atomic<bool> resumeOnReturn_{true};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,54 @@
|
||||
#pragma once
|
||||
|
||||
#include <PluginInterface.hpp>
|
||||
#include <PluginTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
// One authoritative, event-refreshed TeamSpeak topology cache. The public
|
||||
// serializer is deliberately structural: it has no fields for UIDs, groups,
|
||||
// database IDs, addresses, or query clients, so private data cannot leak by
|
||||
// accidentally toggling a flag at the HTTP boundary.
|
||||
class TeamSpeakDirectoryService
|
||||
{
|
||||
public:
|
||||
|
||||
struct Snapshot {
|
||||
Api::ServerInfo server;
|
||||
std::vector<Api::ChannelInfo> channels;
|
||||
std::vector<Api::ClientInfo> clients;
|
||||
bool connected = false;
|
||||
std::uint64_t revision = 0;
|
||||
};
|
||||
|
||||
void setPluginInterface(Api::PluginInterfacePtr plugin);
|
||||
[[nodiscard]] Api::Result<void> refresh();
|
||||
void handleEvent(Api::PluginEventType type);
|
||||
|
||||
[[nodiscard]] Snapshot snapshot() const;
|
||||
[[nodiscard]] Void::Json::Value publicJson() const;
|
||||
[[nodiscard]] Void::Json::Value adminJson() const;
|
||||
|
||||
// TeamSpeak stores a sibling's predecessor id in channel_order.
|
||||
// This helper turns that linked-list representation into display
|
||||
// order and deterministically appends malformed/orphaned entries.
|
||||
[[nodiscard]] static std::vector<Api::ChannelInfo>
|
||||
orderChannels(std::vector<Api::ChannelInfo> channels);
|
||||
|
||||
private:
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
Api::PluginInterfacePtr plugin_;
|
||||
Snapshot snapshot_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,74 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Persistent on-disk cache of downloaded audio files, keyed by track id.
|
||||
// Survives restarts (lives under XDG_CACHE_HOME/echoion/tracks); evicts
|
||||
// least-recently-used files past maxBytes and entries older than the
|
||||
// TTL. Honors advanced.cacheEnabled / cacheMaxSize / cacheTTL.
|
||||
class TrackCache
|
||||
{
|
||||
public:
|
||||
|
||||
struct Config {
|
||||
bool enabled = true;
|
||||
uint64_t maxBytes = 1ull << 30; // 1 GiB
|
||||
std::chrono::seconds ttl{86400};
|
||||
};
|
||||
|
||||
// dirOverride points tests at a temp dir.
|
||||
explicit TrackCache(Config config,
|
||||
std::filesystem::path dirOverride = {});
|
||||
|
||||
// Parse "1GB"/"500MB"/"1024" (bytes) size strings; 0 on garbage.
|
||||
[[nodiscard]] static uint64_t
|
||||
parseSize(const std::string& text);
|
||||
|
||||
[[nodiscard]] bool enabled() const { return config_.enabled; }
|
||||
|
||||
// Cached file path for the track id, when present and fresh.
|
||||
// Bumps the file's LRU timestamp.
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
lookup(const std::string& trackId);
|
||||
|
||||
// Move a downloaded file into the cache; returns the new path
|
||||
// (or the original on failure/disabled). Triggers eviction.
|
||||
[[nodiscard]] std::string store(const std::string& trackId,
|
||||
const std::string& filePath);
|
||||
|
||||
// True when the path lives inside the cache directory — such
|
||||
// files must NOT be deleted after playback.
|
||||
[[nodiscard]] bool owns(const std::string& filePath) const;
|
||||
|
||||
// Drop expired entries and evict LRU past the size budget.
|
||||
void sweep();
|
||||
|
||||
[[nodiscard]] const std::filesystem::path& directory() const
|
||||
{
|
||||
return dir_;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] std::filesystem::path
|
||||
pathFor(const std::string& trackId,
|
||||
const std::string& extension) const;
|
||||
[[nodiscard]] static std::string
|
||||
sanitize(const std::string& trackId);
|
||||
// Eviction pass; caller holds mutex_.
|
||||
void sweepLocked();
|
||||
|
||||
Config config_;
|
||||
std::filesystem::path dir_;
|
||||
mutable std::mutex mutex_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
// Thin Core adapter around the universal Void ShortUrl service. It owns no
|
||||
// provider and performs no HTTP itself: the getter returns a pinned service
|
||||
// instance for each operation, making calls safe across plugin hot reloads.
|
||||
class UrlShortener
|
||||
{
|
||||
public:
|
||||
|
||||
using ProviderGetter = std::function<
|
||||
std::shared_ptr<Void::ShortUrl::IShortener>()>;
|
||||
|
||||
void setProvider(ProviderGetter provider);
|
||||
void setSources(const std::vector<std::string>& sources);
|
||||
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
shortenUrl(std::string_view originalUrl,
|
||||
Api::TrackSource source) const;
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] bool sourceAllowed(Api::TrackSource source) const;
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
ProviderGetter provider_;
|
||||
std::unordered_set<Api::TrackSource> sources_ = {
|
||||
Api::TrackSource::YouTube};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,67 +1,221 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "NetworkClient.hpp"
|
||||
#include "UrlShortener.hpp"
|
||||
#include "YtDlpManager.hpp"
|
||||
#include <regex>
|
||||
#include <NetworkTypes.hpp>
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/ThreadPool.hpp>
|
||||
#include <YouTubeTypes.hpp>
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <regex>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class YouTubeClient {
|
||||
public:
|
||||
explicit YouTubeClient(std::shared_ptr<NetworkClient> networkClient);
|
||||
~YouTubeClient();
|
||||
class YouTubeClient
|
||||
{
|
||||
public:
|
||||
|
||||
// Initialize the client - downloads yt-dlp if needed
|
||||
Api::Result<void> initialize();
|
||||
void shutdown();
|
||||
explicit YouTubeClient(
|
||||
std::shared_ptr<NetworkClient> networkClient);
|
||||
~YouTubeClient();
|
||||
|
||||
// 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();
|
||||
// Initialize the client - downloads yt-dlp if needed
|
||||
Api::Result<void> initialize();
|
||||
void shutdown();
|
||||
|
||||
// Search for videos using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::SearchResult> search(std::string_view query,
|
||||
std::optional<std::string> pageToken = std::nullopt);
|
||||
// Check if yt-dlp is available
|
||||
[[nodiscard]] bool isAvailable() const;
|
||||
|
||||
// Get video details including stream URLs using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo> getVideoInfo(std::string_view videoId);
|
||||
// Get yt-dlp version
|
||||
[[nodiscard]] std::string getYtDlpVersion() const;
|
||||
|
||||
// Get playlist videos using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::PlaylistInfo> getPlaylist(std::string_view playlistId);
|
||||
// Force update yt-dlp
|
||||
Api::Result<void> updateYtDlp();
|
||||
|
||||
// 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);
|
||||
// Search for videos using YouTube Data API v3 (or yt-dlp as
|
||||
// fallback)
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
search(std::string_view query,
|
||||
std::optional<std::string> pageToken = std::nullopt);
|
||||
|
||||
// Check if URL is a YouTube URL
|
||||
[[nodiscard]] static bool isYouTubeUrl(std::string_view url);
|
||||
// Search SoundCloud via yt-dlp (scsearch). Returns SoundCloud
|
||||
// tracks whose originalUrl is the permalink, streamable through the
|
||||
// ytdlp-direct source.
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
searchSoundCloud(std::string_view query);
|
||||
|
||||
// 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);
|
||||
// Related tracks for radio autoplay: lists the YouTube "mix"
|
||||
// playlist (RD<videoId>) via yt-dlp --flat-playlist. Runs through
|
||||
// the proxy like every yt-dlp call, so it works under SOCKS5.
|
||||
[[nodiscard]] Api::Result<std::vector<Api::TrackInfo>>
|
||||
radioMix(const std::string& videoId, size_t limit = 10);
|
||||
|
||||
private:
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::unique_ptr<YtDlpManager> ytDlpManager_;
|
||||
|
||||
std::atomic<bool> initialized_{false};
|
||||
mutable std::mutex mutex_;
|
||||
};
|
||||
// Fetch music-video candidates for a random search query. Used as a
|
||||
// radio fallback when no unplayed related track can be found (or
|
||||
// there is no seed). Goes through yt-dlp/proxy like radioMix; the
|
||||
// returned list is shuffled so the caller can pick/filter freely.
|
||||
[[nodiscard]] Api::Result<std::vector<Api::TrackInfo>>
|
||||
randomMusicVideo(size_t limit = 10);
|
||||
|
||||
// Get video details including stream URLs using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||
getVideoInfo(std::string_view videoId);
|
||||
|
||||
// Get video details asynchronously
|
||||
[[nodiscard]] std::future<Api::Result<Api::TrackInfo>>
|
||||
getVideoInfoAsync(std::string_view videoId);
|
||||
|
||||
// Get multiple video details concurrently
|
||||
[[nodiscard]] std::vector<Api::Result<Api::TrackInfo>>
|
||||
getVideoInfoBatch(const std::vector<std::string>& videoIds);
|
||||
|
||||
// Get playlist videos - uses YouTube API v2 if key available,
|
||||
// otherwise yt-dlp Then resolves each track individually via yt-dlp
|
||||
// for full metadata
|
||||
[[nodiscard]] Api::Result<Api::PlaylistInfo>
|
||||
getPlaylist(std::string_view playlistId);
|
||||
|
||||
// Get playlist videos asynchronously with concurrent track
|
||||
// resolution
|
||||
[[nodiscard]] std::future<Api::Result<Api::PlaylistInfo>>
|
||||
getPlaylistAsync(std::string_view playlistId);
|
||||
|
||||
// Stream playlist tracks with callback - calls trackCallback for
|
||||
// each track as it is resolved, enabling immediate playback of
|
||||
// first track
|
||||
void getPlaylistStreaming(
|
||||
std::string_view playlistId,
|
||||
std::function<void(Api::TrackInfo&&)>
|
||||
trackCallback,
|
||||
std::function<void(size_t totalTracks)> onPlaylistInfo =
|
||||
nullptr,
|
||||
std::function<void()> onComplete = nullptr);
|
||||
|
||||
// Extract a video ID from known YouTube URL formats or a bare ID.
|
||||
[[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);
|
||||
// Resolve a stream URL for any yt-dlp-supported page URL
|
||||
// (SoundCloud, Bandcamp, VK, radio pages, ...). When useProxy is
|
||||
// false the configured proxy is explicitly bypassed with a
|
||||
// trailing --proxy "" (yt-dlp honours the last occurrence).
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
getStreamUrlForPage(std::string_view pageUrl, bool useProxy);
|
||||
|
||||
// Download the best audio to a file via yt-dlp (used when the
|
||||
// stream URL can't be opened directly — e.g. behind a SOCKS5 proxy
|
||||
// that ffmpeg can't use). yt-dlp applies the proxy + cookies and
|
||||
// writes to disk; returns the resulting file path.
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
downloadAudioToFile(std::string_view videoIdOrUrl,
|
||||
const std::string& outDir);
|
||||
|
||||
// Configure cookie options for yt-dlp
|
||||
void setCookiesPath(const std::string& path);
|
||||
void setCookiesFromBrowser(const std::string& browser);
|
||||
|
||||
// Configure proxy for yt-dlp
|
||||
void setProxyConfig(const std::optional<Void::Net::ProxyConfig>& proxy);
|
||||
[[nodiscard]] std::optional<Void::Net::ProxyConfig>
|
||||
getProxyConfig() const;
|
||||
|
||||
// Set YouTube API key for enhanced playlist resolution (optional)
|
||||
void setApiKey(const std::string& apiKey);
|
||||
[[nodiscard]] bool hasApiKey() const;
|
||||
|
||||
// Configure concurrent resolution settings
|
||||
void setMaxConcurrentResolutions(size_t max);
|
||||
[[nodiscard]] size_t getMaxConcurrentResolutions() const;
|
||||
|
||||
// Enable/disable URL shortening for track links
|
||||
void setUrlShorteningEnabled(bool enabled);
|
||||
void setUrlShortenerProvider(UrlShortener::ProviderGetter provider);
|
||||
void setUrlShorteningSources(
|
||||
const std::vector<std::string>& sources);
|
||||
void setUrlShorteningTimeout(std::chrono::milliseconds timeout);
|
||||
// Apply the provider-neutral policy to resolved tracks from any
|
||||
// source. Operations are best-effort and timeout-bounded.
|
||||
void populateShortenedUrls(std::vector<Api::TrackInfo>& tracks);
|
||||
void populateShortenedUrl(Api::TrackInfo& track);
|
||||
|
||||
// Gate yt-dlp's periodic background self-update
|
||||
// (features.enableAutoUpdateCheck). Set before initialize().
|
||||
void setAutoUpdateEnabled(bool enabled);
|
||||
[[nodiscard]] bool isUrlShorteningEnabled() const;
|
||||
|
||||
private:
|
||||
|
||||
// Internal search implementations
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
searchWithApi(std::string_view query,
|
||||
const std::optional<std::string>& pageToken);
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
searchWithYtDlp(std::string_view query,
|
||||
const std::optional<std::string>& pageToken);
|
||||
// Shared yt-dlp search backend. `searchPrefix` is the yt-dlp search
|
||||
// selector (e.g. "ytsearch5", "scsearch5"); `source` tags the
|
||||
// resulting tracks and decides how originalUrl is built.
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
searchWithYtDlpProvider(std::string_view query,
|
||||
std::string_view searchPrefix,
|
||||
Api::TrackSource source);
|
||||
|
||||
// Fetch video durations for search results (batch API call)
|
||||
void fetchVideoDurations(std::vector<Api::TrackInfo>& tracks,
|
||||
const std::vector<std::string>& videoIds);
|
||||
|
||||
// Internal methods for playlist resolution
|
||||
[[nodiscard]] Api::Result<std::vector<Api::YouTubePlaylistItem>>
|
||||
fetchPlaylistItems(std::string_view playlistId);
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||
resolveTrackWithYtDlp(const Api::YouTubePlaylistItem& item);
|
||||
|
||||
// Build YouTube API v3 URL for playlist items
|
||||
[[nodiscard]] std::string buildPlaylistApiUrl(
|
||||
std::string_view playlistId,
|
||||
const std::optional<std::string>& pageToken =
|
||||
std::nullopt) const;
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::unique_ptr<YtDlpManager> ytDlpManager_;
|
||||
std::unique_ptr<UrlShortener> urlShortener_;
|
||||
|
||||
// Worker pool backing the parallel API/resolution fan-outs. Bounds
|
||||
// thread reuse instead of spawning an OS thread per std::async call.
|
||||
Void::Concurrency::ThreadPool pool_;
|
||||
|
||||
std::atomic<bool> initialized_{false};
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
// Configuration
|
||||
std::optional<std::string> apiKey_;
|
||||
mutable std::mutex configMutex_;
|
||||
size_t maxConcurrentResolutions_ = 4;
|
||||
bool urlShorteningEnabled_ = true;
|
||||
std::chrono::milliseconds urlShorteningTimeout_{3000};
|
||||
|
||||
};
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,81 +1,149 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "NetworkClient.hpp"
|
||||
#include <string>
|
||||
#include <filesystem>
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/ThreadPool.hpp>
|
||||
#include <YouTubeTypes.hpp>
|
||||
#include <atomic>
|
||||
#include <filesystem>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class YtDlpManager {
|
||||
public:
|
||||
explicit YtDlpManager(std::shared_ptr<NetworkClient> networkClient);
|
||||
~YtDlpManager();
|
||||
struct YtDlpResult {
|
||||
std::string output;
|
||||
int exitCode;
|
||||
bool success;
|
||||
std::chrono::milliseconds executionTime;
|
||||
};
|
||||
|
||||
// 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;
|
||||
class YtDlpManager
|
||||
{
|
||||
public:
|
||||
|
||||
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;
|
||||
explicit YtDlpManager(std::shared_ptr<NetworkClient> networkClient);
|
||||
~YtDlpManager();
|
||||
|
||||
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";
|
||||
};
|
||||
// Initialize - checks for yt-dlp and downloads if needed
|
||||
Api::Result<void> initialize();
|
||||
|
||||
// Gate the periodic (7-day) background self-update. Configured
|
||||
// via features.enableAutoUpdateCheck; set BEFORE initialize().
|
||||
void setAutoUpdateEnabled(bool enabled)
|
||||
{
|
||||
autoUpdateEnabled_ = enabled;
|
||||
}
|
||||
|
||||
// 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; returns the verified
|
||||
// version string of the freshly installed binary.
|
||||
Api::Result<std::string> update();
|
||||
|
||||
// Execute yt-dlp with given arguments and return output
|
||||
// (synchronous)
|
||||
[[nodiscard]] std::string
|
||||
execute(const std::vector<std::string>& args) const;
|
||||
|
||||
// Execute yt-dlp asynchronously and return a future
|
||||
[[nodiscard]] std::future<YtDlpResult>
|
||||
executeAsync(const std::vector<std::string>& args);
|
||||
|
||||
// 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;
|
||||
|
||||
// Set proxy configuration for yt-dlp
|
||||
void setProxyConfig(const std::optional<Void::Net::ProxyConfig>& proxy);
|
||||
[[nodiscard]] std::optional<Void::Net::ProxyConfig>
|
||||
getProxyConfig() const;
|
||||
|
||||
// Configure thread pool size for async operations (default: 4)
|
||||
void setThreadPoolSize(size_t size);
|
||||
[[nodiscard]] size_t getThreadPoolSize() 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 the given file executable (Unix only)
|
||||
Api::Result<void> makeExecutable(const std::filesystem::path& path);
|
||||
|
||||
// Check if update is needed (older than 7 days)
|
||||
[[nodiscard]] bool shouldUpdate() const;
|
||||
|
||||
// Get download URL based on platform
|
||||
[[nodiscard]] std::string getDownloadUrl() const;
|
||||
|
||||
// Internal execute implementation
|
||||
[[nodiscard]] YtDlpResult
|
||||
executeInternal(const std::vector<std::string>& args) const;
|
||||
|
||||
// Get proxy arguments for yt-dlp command
|
||||
[[nodiscard]] std::vector<std::string> getProxyArgs() const;
|
||||
|
||||
// Thread pool for async operations
|
||||
void startThreadPool();
|
||||
void stopThreadPool();
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::filesystem::path executablePath_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
std::atomic<bool> autoUpdateEnabled_{true};
|
||||
// Background download/verify (joined in the destructor).
|
||||
std::jthread initThread_;
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
// Cookie configuration for YouTube authentication
|
||||
std::optional<std::string> cookiesPath_;
|
||||
std::optional<std::string> cookiesFromBrowser_;
|
||||
|
||||
// Proxy configuration
|
||||
std::optional<Void::Net::ProxyConfig> proxyConfig_;
|
||||
mutable std::mutex proxyMutex_;
|
||||
|
||||
// Thread pool for async operations (Void worker pool; recreated
|
||||
// on resize). Guarded by mutex_ for start/stop/submit.
|
||||
size_t threadPoolSize_ = 4;
|
||||
std::unique_ptr<Void::Concurrency::ThreadPool> pool_;
|
||||
|
||||
// yt-dlp download URLs
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_LINUX_X86_64 =
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/"
|
||||
"yt-dlp_linux";
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_LINUX_AARCH64 =
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/"
|
||||
"yt-dlp_linux_aarch64";
|
||||
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,56 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !announce <text> — admin-only. Stores the announcement and delivers it
|
||||
// as a private message to each subscriber exactly once: to those online
|
||||
// now, and to others the next time they connect. Persisted per-uid, so a
|
||||
// bot restart never re-sends, and re-running !announce with new text
|
||||
// reaches everyone once more.
|
||||
class AnnounceCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
ctx.tr("The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply(
|
||||
ctx.trf("Usage: {}announce <message>", ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
const size_t reached = manager->setAnnouncement(ctx.args);
|
||||
ctx.reply(ctx.trf(
|
||||
"Announcement saved and delivered to {} online "
|
||||
"subscriber(s). Offline subscribers get it on their "
|
||||
"next connect.",
|
||||
reached));
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Send an announcement to all subscribers (admin).";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "<message>"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
|
||||
bool requiresAdmin() const override { return true; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !autoplay [on|off] / !radio — toggle endless related-track playback.
|
||||
// With no argument it flips the current state. The choice is persisted so
|
||||
// it survives restarts. Related tracks come from the same catalog as the
|
||||
// last played track (YouTube radio mix or Yandex similar tracks).
|
||||
class AutoplayCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
bool enable = !manager->autoplayEnabled();
|
||||
std::string arg(ctx.args);
|
||||
std::transform(arg.begin(), arg.end(), arg.begin(),
|
||||
[](unsigned char c) {
|
||||
return static_cast<char>(
|
||||
std::tolower(c));
|
||||
});
|
||||
if (arg == "on" || arg == "true" || arg == "1" ||
|
||||
arg == "enable") {
|
||||
enable = true;
|
||||
} else if (arg == "off" || arg == "false" || arg == "0" ||
|
||||
arg == "disable") {
|
||||
enable = false;
|
||||
}
|
||||
|
||||
manager->setAutoplay(enable);
|
||||
|
||||
if (enable) {
|
||||
ctx.reply(ctx.tr(
|
||||
"\xf0\x9f\x93\xbb Autoplay is ON \xe2\x80\x94 I'll "
|
||||
"keep the music going with related tracks."));
|
||||
} else {
|
||||
ctx.reply(ctx.tr("\xf0\x9f\x93\xbb Autoplay is OFF."));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"AutoplayCommand", "{}",
|
||||
std::format("Autoplay command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Toggles radio mode: auto-queues related tracks when "
|
||||
"the queue runs out.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "[on|off]"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"radio"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,46 +1,60 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class ClearCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
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;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
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.");
|
||||
}
|
||||
}
|
||||
auto result = manager->clearQueue();
|
||||
if (!result) {
|
||||
Void::Log::error("ClearCommand", "{}",
|
||||
std::format("Clear command failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't clear the queue. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Clears all tracks from the queue.";
|
||||
}
|
||||
ctx.reply(ctx.tr("Queue cleared!"));
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"ClearCommand", "{}",
|
||||
std::format("Clear command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Clears all tracks from the queue.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"clr", "empty"};
|
||||
}
|
||||
};
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"clr", "empty"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,105 +1,283 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include "echoion/core/i18n/Localization.hpp"
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Service/Registry.hpp>
|
||||
#include <cstdint>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <functional>
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class MusicManager;
|
||||
class MusicManager;
|
||||
|
||||
enum class CommandCategory {
|
||||
Music,
|
||||
Queue,
|
||||
Playback,
|
||||
Utility,
|
||||
Admin
|
||||
};
|
||||
// Declaration order also decides the order of the collapsible sections
|
||||
// in !help (the help map is keyed by this enum). Play and Search lead so
|
||||
// their related commands are grouped together up top.
|
||||
enum class CommandCategory {
|
||||
Play,
|
||||
Search,
|
||||
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";
|
||||
}
|
||||
inline std::string toString(CommandCategory category)
|
||||
{
|
||||
switch (category) {
|
||||
case CommandCategory::Play:
|
||||
return "Play";
|
||||
case CommandCategory::Search:
|
||||
return "Search";
|
||||
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);
|
||||
}
|
||||
}
|
||||
};
|
||||
// Middot separator (U+00B7) used between a track link and its duration.
|
||||
inline constexpr std::string_view kDot = "\xc2\xb7";
|
||||
|
||||
/**
|
||||
* @brief Interface that all commands must implement.
|
||||
*/
|
||||
class Command {
|
||||
public:
|
||||
virtual ~Command() = default;
|
||||
// Escape Markdown punctuation in dynamic text (track titles, etc.) so it
|
||||
// cannot break an enclosing [text](url) link or apply stray formatting.
|
||||
inline std::string escapeMarkdown(std::string_view text)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(text.size() + 8);
|
||||
for (char c : text) {
|
||||
switch (c) {
|
||||
case '\\':
|
||||
case '`':
|
||||
case '*':
|
||||
case '_':
|
||||
case '[':
|
||||
case ']':
|
||||
case '(':
|
||||
case ')':
|
||||
case '~':
|
||||
case '|':
|
||||
out += '\\';
|
||||
[[fallthrough]];
|
||||
default:
|
||||
out += c;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The logic of the command.
|
||||
*/
|
||||
virtual void execute(const CommandContext& ctx) = 0;
|
||||
// Render `text` as a Markdown link to `url` (escaping the text). When `url`
|
||||
// is empty/absent the escaped text is returned without a link.
|
||||
inline std::string markdownLink(std::string_view text,
|
||||
const std::optional<std::string>& url)
|
||||
{
|
||||
if (url.has_value() && !url->empty()) {
|
||||
return std::format("[{}]({})", escapeMarkdown(text), *url);
|
||||
}
|
||||
return escapeMarkdown(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the description used for help generation.
|
||||
*/
|
||||
virtual std::string_view getDescription() const = 0;
|
||||
// The best public link for a track: the provider-generated short link when
|
||||
// available, otherwise the original source URL (e.g. the YouTube or
|
||||
// Yandex Music page). Used so every list — search, queue, history,
|
||||
// favorites, stats — links to the real track, never the CDN/stream URL.
|
||||
inline std::optional<std::string> trackLinkUrl(const Api::TrackInfo& track)
|
||||
{
|
||||
if (track.shortenedUrl.has_value() && !track.shortenedUrl->empty()) {
|
||||
return track.shortenedUrl;
|
||||
}
|
||||
if (!track.originalUrl.empty()) {
|
||||
return track.originalUrl;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns usage syntax (e.g., "<url>").
|
||||
*/
|
||||
virtual std::string_view getUsage() const { return ""; }
|
||||
// Render "Title by Artist" (or just Title) as a Markdown link to the
|
||||
// track's best public URL.
|
||||
inline std::string trackLink(const Api::TrackInfo& track)
|
||||
{
|
||||
std::string display = track.title;
|
||||
if (!track.artist.empty()) {
|
||||
display = std::format("{} by {}", track.title, track.artist);
|
||||
}
|
||||
return markdownLink(display, trackLinkUrl(track));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the command category for grouping in help.
|
||||
*/
|
||||
virtual CommandCategory getCategory() const {
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
/**
|
||||
* @brief Context passed to every command execution.
|
||||
* Wraps all dependencies required to perform an action.
|
||||
*/
|
||||
struct CommandContext {
|
||||
uint64_t clientId = 0;
|
||||
std::string prefix;
|
||||
std::string args; // Arguments excluding the command name
|
||||
std::string_view invokerName;
|
||||
|
||||
/**
|
||||
* @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; }
|
||||
};
|
||||
// Dependencies
|
||||
std::weak_ptr<MusicManager> musicManager;
|
||||
|
||||
using CommandPtr = std::shared_ptr<Command>;
|
||||
// Service registry for resolving shared services by interface
|
||||
// (non-owning; outlives the command). Populated by CommandManager.
|
||||
const Void::Service::ServiceRegistry* services = nullptr;
|
||||
|
||||
// Language the invoking user should be answered in. Resolved by
|
||||
// CommandManager (per-user kv override, else the config default).
|
||||
I18n::Language language = I18n::Language::English;
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
// Translate an English source string into the invoker's language.
|
||||
// Missing translations fall back to the English original.
|
||||
[[nodiscard]] std::string_view tr(std::string_view english) const
|
||||
{
|
||||
return I18n::translate(english, language);
|
||||
}
|
||||
|
||||
// Translate a std::format-style English template, then substitute
|
||||
// the arguments. The template is translated at runtime, so callers
|
||||
// use this instead of std::format for user-facing text.
|
||||
template <typename... Args>
|
||||
[[nodiscard]] std::string trf(std::string_view englishFmt,
|
||||
Args&&... args) const
|
||||
{
|
||||
return std::vformat(I18n::translate(englishFmt, language),
|
||||
std::make_format_args(args...));
|
||||
}
|
||||
|
||||
// Resolve a shared service by interface, or nullptr if the
|
||||
// registry is absent / the service was not provided.
|
||||
template <typename I>
|
||||
[[nodiscard]] std::shared_ptr<I> service() const
|
||||
{
|
||||
return services ? services->get<I>() : nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
// Format a duration as m:ss (or h:mm:ss past an hour). Shared by the
|
||||
// track-listing commands (!np, !queue) so their timestamps line up.
|
||||
inline std::string formatDuration(std::chrono::milliseconds duration)
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
|
||||
// A compact one-line playback status readout (volume / shuffle / repeat /
|
||||
// radio) shared by !help, !np and !list so all three show the same
|
||||
// at-a-glance state. Rendered as a Markdown blockquote line. Returns an
|
||||
// empty string when playback state is unavailable. Radio comes from
|
||||
// autoplayEnabled() since PlaybackState carries no autoplay field.
|
||||
inline std::string playbackStatusLine(const CommandContext& ctx)
|
||||
{
|
||||
auto mm = ctx.musicManager.lock();
|
||||
if (!mm) {
|
||||
return {};
|
||||
}
|
||||
auto st = mm->getPlaybackState();
|
||||
if (!st) {
|
||||
return {};
|
||||
}
|
||||
auto onOff = [&](bool b) -> std::string_view {
|
||||
return b ? ctx.tr("On") : ctx.tr("Off");
|
||||
};
|
||||
return ctx.trf(
|
||||
"> \xf0\x9f\x8e\x9a {} {}% \xc2\xb7 "
|
||||
"\xf0\x9f\x94\x80 {} {} \xc2\xb7 "
|
||||
"\xf0\x9f\x94\x81 {} {} \xc2\xb7 "
|
||||
"\xf0\x9f\x93\xbb {} {}",
|
||||
ctx.tr("Volume"), static_cast<int>(st->volume * 100),
|
||||
ctx.tr("Shuffle"), onOff(st->shuffle),
|
||||
ctx.tr("Repeat"), onOff(st->repeat),
|
||||
ctx.tr("Radio"), onOff(mm->autoplayEnabled()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @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; }
|
||||
|
||||
/**
|
||||
* @brief Whether an over-long reply from this command should be
|
||||
* auto-paginated into a single message with a "!page" footer.
|
||||
*
|
||||
* Defaults to true. Commands that manage their own output shape
|
||||
* (help's collapsible sections, the page navigator itself) return
|
||||
* false so their replies are sent verbatim.
|
||||
*/
|
||||
virtual bool autoPaginate() const { return true; }
|
||||
};
|
||||
|
||||
using CommandPtr = std::shared_ptr<Command>;
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,25 +1,42 @@
|
||||
#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 "AnnounceCommand.hpp"
|
||||
#include "AutoplayCommand.hpp"
|
||||
#include "ClearCommand.hpp"
|
||||
#include "Command.hpp"
|
||||
#include "FavoriteCommand.hpp"
|
||||
#include "HistoryCommand.hpp"
|
||||
#include "LanguageCommand.hpp"
|
||||
#include "LyricsCommand.hpp"
|
||||
#include "MoveCommand.hpp"
|
||||
#include "ShuffleCommand.hpp"
|
||||
#include "RepeatCommand.hpp"
|
||||
#include "PlaylistCommand.hpp"
|
||||
#include "NowPlayingCommand.hpp"
|
||||
#include "SearchCommand.hpp"
|
||||
#include "PauseCommand.hpp"
|
||||
#include "PlayCommand.hpp"
|
||||
#include "PlaylistCommand.hpp"
|
||||
#include "QueueCommand.hpp"
|
||||
#include "ReloadCommand.hpp"
|
||||
#include "ReloadConfigCommand.hpp"
|
||||
#include "RemoveCommand.hpp"
|
||||
#include "RepeatCommand.hpp"
|
||||
#include "ResumeCommand.hpp"
|
||||
#include "RpcInfoCommand.hpp"
|
||||
#include "SearchCommand.hpp"
|
||||
#include "SeekCommand.hpp"
|
||||
#include "SelectCommand.hpp"
|
||||
#include "ShuffleCommand.hpp"
|
||||
#include "SkipCommand.hpp"
|
||||
#include "SoundCloudPlayCommand.hpp"
|
||||
#include "SoundCloudSearchCommand.hpp"
|
||||
#include "StatsCommand.hpp"
|
||||
#include "StopCommand.hpp"
|
||||
#include "SubscribeCommand.hpp"
|
||||
#include "SubscribersCommand.hpp"
|
||||
#include "UnsubscribeAllCommand.hpp"
|
||||
#include "UnsubscribeCommand.hpp"
|
||||
#include "UnsubscribeIdCommand.hpp"
|
||||
#include "VolumeCommand.hpp"
|
||||
#include "YandexPlayCommand.hpp"
|
||||
#include "YandexSearchCommand.hpp"
|
||||
#include "YoutubePlayCommand.hpp"
|
||||
#include "YoutubeSearchCommand.hpp"
|
||||
@@ -0,0 +1,206 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !fav add | list | play <n> | remove <n> — per-user favorites keyed by
|
||||
// the stable TS3 unique identifier (hashed to the database's uint64
|
||||
// user key with FNV-1a; session client ids are NOT stable).
|
||||
class FavoriteCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
auto manager = ctx.musicManager.lock();
|
||||
auto db = ctx.service<Api::Database>();
|
||||
if (!manager || !db) {
|
||||
ctx.reply(ctx.tr("Favorites are unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto uid = manager->clientUid(ctx.clientId);
|
||||
if (!uid) {
|
||||
ctx.reply(ctx.tr("Couldn't identify you on the server."));
|
||||
return;
|
||||
}
|
||||
const uint64_t userKey = fnv1a(*uid);
|
||||
|
||||
const auto [sub, rest] = splitFirstWord(ctx.args);
|
||||
|
||||
if (sub.empty() || sub == "list") {
|
||||
listFavorites(ctx, *db, userKey);
|
||||
} else if (sub == "add") {
|
||||
addCurrent(ctx, *manager, *db, userKey);
|
||||
} else if (sub == "play") {
|
||||
playFavorite(ctx, *manager, *db, userKey, rest);
|
||||
} else if (sub == "remove" || sub == "rm") {
|
||||
removeFavorite(ctx, *db, userKey, rest);
|
||||
} else {
|
||||
ctx.reply(ctx.trf(
|
||||
"Usage: {}fav add | list | play <n> | remove <n>",
|
||||
ctx.prefix));
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Manage your favorite tracks";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "add | list | play <n> | remove <n>";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"favorite", "favorites"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] static uint64_t fnv1a(std::string_view text)
|
||||
{
|
||||
uint64_t hash = 14695981039346656037ull;
|
||||
for (unsigned char c : text) {
|
||||
hash ^= c;
|
||||
hash *= 1099511628211ull;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
[[nodiscard]] static std::pair<std::string, std::string>
|
||||
splitFirstWord(const std::string& text)
|
||||
{
|
||||
const auto start = text.find_first_not_of(' ');
|
||||
if (start == std::string::npos) {
|
||||
return {};
|
||||
}
|
||||
const auto end = text.find(' ', start);
|
||||
if (end == std::string::npos) {
|
||||
return {text.substr(start), {}};
|
||||
}
|
||||
const auto restStart = text.find_first_not_of(' ', end);
|
||||
return {text.substr(start, end - start),
|
||||
restStart == std::string::npos
|
||||
? std::string{}
|
||||
: text.substr(restStart)};
|
||||
}
|
||||
|
||||
[[nodiscard]] static std::optional<size_t>
|
||||
parseIndex(const std::string& text)
|
||||
{
|
||||
unsigned parsed = 0;
|
||||
auto [_, ec] = std::from_chars(
|
||||
text.data(), text.data() + text.size(), parsed);
|
||||
if (ec != std::errc{} || parsed == 0) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
static void listFavorites(const CommandContext& ctx,
|
||||
Api::Database& db, uint64_t userKey)
|
||||
{
|
||||
auto favorites = db.getFavorites(userKey);
|
||||
if (!favorites) {
|
||||
ctx.reply(ctx.tr("Couldn't read your favorites."));
|
||||
return;
|
||||
}
|
||||
if (favorites->empty()) {
|
||||
ctx.reply(ctx.trf(
|
||||
"You have no favorites yet. Save the current track "
|
||||
"with {}fav add",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
std::string msg = "Your favorites:";
|
||||
size_t index = 1;
|
||||
for (const auto& fav : *favorites) {
|
||||
msg +=
|
||||
std::format("\n{}. {}", index++, trackLink(fav.track));
|
||||
}
|
||||
ctx.reply(msg);
|
||||
}
|
||||
|
||||
static void addCurrent(const CommandContext& ctx,
|
||||
MusicManager& manager, Api::Database& db,
|
||||
uint64_t userKey)
|
||||
{
|
||||
auto current = manager.getCurrentTrack();
|
||||
if (!current || !current->has_value()) {
|
||||
ctx.reply(ctx.tr("Nothing is playing right now."));
|
||||
return;
|
||||
}
|
||||
const auto& track = (*current)->track;
|
||||
if (db.addFavorite(userKey, track)) {
|
||||
ctx.reply(ctx.trf("Added to favorites: {}", track.title));
|
||||
} else {
|
||||
ctx.reply(ctx.tr("Couldn't save the favorite."));
|
||||
}
|
||||
}
|
||||
|
||||
static void playFavorite(const CommandContext& ctx,
|
||||
MusicManager& manager, Api::Database& db,
|
||||
uint64_t userKey, const std::string& arg)
|
||||
{
|
||||
auto index = parseIndex(arg);
|
||||
if (!index) {
|
||||
ctx.reply(
|
||||
ctx.tr("Usage: fav play <number> (see fav list)"));
|
||||
return;
|
||||
}
|
||||
auto favorites = db.getFavorites(userKey);
|
||||
if (!favorites || *index > favorites->size()) {
|
||||
ctx.reply(ctx.tr("No favorite with that number."));
|
||||
return;
|
||||
}
|
||||
const auto& track = (*favorites)[*index - 1].track;
|
||||
auto result = manager.play(track.originalUrl, ctx.clientId);
|
||||
if (result) {
|
||||
ctx.reply(*result);
|
||||
} else {
|
||||
ctx.reply(ctx.trf("Couldn't play it: {}",
|
||||
result.error().message));
|
||||
}
|
||||
}
|
||||
|
||||
static void removeFavorite(const CommandContext& ctx,
|
||||
Api::Database& db, uint64_t userKey,
|
||||
const std::string& arg)
|
||||
{
|
||||
auto index = parseIndex(arg);
|
||||
if (!index) {
|
||||
ctx.reply(
|
||||
ctx.tr("Usage: fav remove <number> (see fav list)"));
|
||||
return;
|
||||
}
|
||||
auto favorites = db.getFavorites(userKey);
|
||||
if (!favorites || *index > favorites->size()) {
|
||||
ctx.reply(ctx.tr("No favorite with that number."));
|
||||
return;
|
||||
}
|
||||
const auto& fav = (*favorites)[*index - 1];
|
||||
if (db.removeFavorite(userKey, fav.track.originalUrl)) {
|
||||
ctx.reply(
|
||||
ctx.trf("Removed from favorites: {}", fav.track.title));
|
||||
} else {
|
||||
ctx.reply(ctx.tr("Couldn't remove the favorite."));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,72 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !history [n] — recently played tracks (global, deduplicated).
|
||||
class HistoryCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
auto db = ctx.service<Api::Database>();
|
||||
if (!db) {
|
||||
ctx.reply(ctx.tr("History is unavailable (no database)."));
|
||||
return;
|
||||
}
|
||||
|
||||
size_t limit = 10;
|
||||
if (!ctx.args.empty()) {
|
||||
unsigned parsed = 0;
|
||||
auto [_, ec] = std::from_chars(
|
||||
ctx.args.data(), ctx.args.data() + ctx.args.size(),
|
||||
parsed);
|
||||
if (ec == std::errc{} && parsed > 0) {
|
||||
limit = std::min<size_t>(parsed, 25);
|
||||
}
|
||||
}
|
||||
|
||||
auto recent = db->getRecentlyPlayed(0, limit);
|
||||
if (!recent) {
|
||||
ctx.reply(ctx.tr("Couldn't read the playback history."));
|
||||
return;
|
||||
}
|
||||
if (recent->empty()) {
|
||||
ctx.reply(ctx.tr("Nothing has been played yet."));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string msg = "Recently played:";
|
||||
size_t index = 1;
|
||||
for (const auto& track : *recent) {
|
||||
msg += std::format("\n{}. {}", index++, trackLink(track));
|
||||
}
|
||||
ctx.reply(msg);
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Show recently played tracks";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "[count]"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"recent"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,111 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "../i18n/Localization.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <format>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !language [en|ru] — show or set the caller's reply language. The choice
|
||||
// is stored per user (keyed by the stable TS3 unique identifier) in
|
||||
// kv_store so it survives reconnects and restarts. With no argument it
|
||||
// reports the current language and the available options.
|
||||
class LanguageCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
std::string arg = trimmedLower(ctx.args);
|
||||
|
||||
if (arg.empty()) {
|
||||
ctx.reply(
|
||||
ctx.trf("Current language: {}. Available: en, ru. Use "
|
||||
"{}language <en|ru>.",
|
||||
I18n::languageName(ctx.language), ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
const bool isEn =
|
||||
arg == "en" || arg == "eng" || arg == "english";
|
||||
const bool isRu = arg == "ru" || arg == "rus" ||
|
||||
arg == "russian" ||
|
||||
arg == "\xd1\x80\xd1\x83\xd1\x81\xd1\x81"
|
||||
"\xd0\xba\xd0\xb8\xd0\xb9";
|
||||
if (!isEn && !isRu) {
|
||||
ctx.reply(ctx.tr("Unknown language. Choose 'en' or 'ru'."));
|
||||
return;
|
||||
}
|
||||
const I18n::Language newLang =
|
||||
isRu ? I18n::Language::Russian : I18n::Language::English;
|
||||
|
||||
auto manager = ctx.musicManager.lock();
|
||||
auto db = ctx.service<Api::Database>();
|
||||
if (!manager || !db) {
|
||||
ctx.reply(
|
||||
ctx.tr("Language settings are unavailable right now."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto uid = manager->clientUid(ctx.clientId);
|
||||
if (!uid || uid->empty()) {
|
||||
ctx.reply(ctx.tr("Couldn't identify you on the server."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto saved = db->setKv(
|
||||
"lang:" + *uid, std::string(I18n::languageCode(newLang)));
|
||||
if (!saved) {
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't save your language. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
// Confirm in the newly selected language.
|
||||
std::string name(I18n::languageName(newLang));
|
||||
ctx.reply(std::vformat(
|
||||
I18n::translate("\xe2\x9c\x85 Language set to {}.",
|
||||
newLang),
|
||||
std::make_format_args(name)));
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Sets your reply language (English or Russian).";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "[en|ru]"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"lang"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static std::string trimmedLower(std::string_view in)
|
||||
{
|
||||
size_t b = in.find_first_not_of(" \t");
|
||||
if (b == std::string_view::npos) {
|
||||
return {};
|
||||
}
|
||||
size_t e = in.find_last_not_of(" \t");
|
||||
std::string out(in.substr(b, e - b + 1));
|
||||
std::transform(out.begin(), out.end(), out.begin(),
|
||||
[](unsigned char c) { return std::tolower(c); });
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/LyricsService.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !lyrics — show the lyrics of the currently playing track (via lrclib).
|
||||
class LyricsCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto current = manager->getCurrentTrack();
|
||||
if (!current || !current->has_value()) {
|
||||
ctx.reply(ctx.trf("Nothing is currently playing. "
|
||||
"Add something with {}play !",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& track = current->value().track;
|
||||
|
||||
auto lyrics = ctx.service<LyricsService>();
|
||||
if (!lyrics) {
|
||||
ctx.reply(ctx.tr("Lyrics are unavailable right now."));
|
||||
return;
|
||||
}
|
||||
|
||||
long long durationSec =
|
||||
track.duration.has_value()
|
||||
? track.duration->count() / 1000
|
||||
: 0;
|
||||
auto result = lyrics->fetch(track.title, track.artist,
|
||||
track.album, durationSec);
|
||||
|
||||
if (!result.found || result.plain.empty()) {
|
||||
ctx.reply(ctx.trf("No lyrics found for {}.",
|
||||
trackLink(track)));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string msg = std::format(
|
||||
"\xf0\x9f\x8e\xa4 {}\n\n{}", trackLink(track),
|
||||
result.plain);
|
||||
ctx.reply(msg);
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"LyricsCommand", "{}",
|
||||
std::format("Lyrics command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Shows the lyrics of the current track.";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"ly"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,82 +1,106 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class MoveCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: move <from> <to>\nExample: move 5 1 (moves track 5 to position 1)");
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
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;
|
||||
}
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply(
|
||||
ctx.tr("Usage: move <from> <to>\nExample: move 5 1 "
|
||||
"(moves track 5 to position 1)"));
|
||||
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);
|
||||
// Parse arguments: from and to positions
|
||||
uint32_t from = 0, to = 0;
|
||||
|
||||
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 spacePos = ctx.args.find(' ');
|
||||
if (spacePos == std::string::npos) {
|
||||
ctx.reply(ctx.tr(
|
||||
"Please provide both from and to positions."));
|
||||
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;
|
||||
}
|
||||
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);
|
||||
|
||||
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.");
|
||||
}
|
||||
}
|
||||
if (result1.ec != std::errc() ||
|
||||
result2.ec != std::errc() || from == 0 || to == 0) {
|
||||
ctx.reply(
|
||||
ctx.tr("Please provide valid position numbers "
|
||||
"(starting from 1)."));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Moves a track to a different position in the queue.";
|
||||
}
|
||||
auto moveResult = manager->moveInQueue(
|
||||
from - 1, to - 1); // Convert to 0-based
|
||||
if (!moveResult) {
|
||||
Void::Log::error(
|
||||
"MoveCommand", "{}",
|
||||
std::format("Move command failed: {}",
|
||||
moveResult.error().message));
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "<from> <to>";
|
||||
}
|
||||
if (moveResult.error().code ==
|
||||
Api::ErrorCode::NotFound) {
|
||||
ctx.reply(ctx.tr(
|
||||
"One of those positions doesn't exist in "
|
||||
"the queue."));
|
||||
} else {
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't move that track. Please try again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
ctx.reply(ctx.trf("Moved track from position {} to {}.",
|
||||
from, to));
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"MoveCommand", "{}",
|
||||
std::format("Move command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"mv"};
|
||||
}
|
||||
};
|
||||
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
|
||||
@@ -1,66 +1,109 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class NowPlayingCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
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;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!current->has_value()) {
|
||||
ctx.reply("Nothing is currently playing. Add something with [prefix]play!");
|
||||
return;
|
||||
}
|
||||
auto current = manager->getCurrentTrack();
|
||||
if (!current) {
|
||||
Void::Log::error(
|
||||
"NowPlayingCommand", "{}",
|
||||
std::format("NowPlaying command failed: {}",
|
||||
current.error().message));
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't get current track information."));
|
||||
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);
|
||||
}
|
||||
if (!current->has_value()) {
|
||||
ctx.reply(ctx.trf("Nothing is currently playing. "
|
||||
"Add something with {}play !",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
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.");
|
||||
}
|
||||
}
|
||||
const auto& track = current->value();
|
||||
const auto& trackInfo = track.track;
|
||||
std::string displayText = trackInfo.title;
|
||||
if (!trackInfo.artist.empty()) {
|
||||
displayText = std::format("{} by {}", trackInfo.title,
|
||||
trackInfo.artist);
|
||||
}
|
||||
std::string msg = std::format(
|
||||
"\xf0\x9f\x8e\xb5 {}",
|
||||
markdownLink(displayText, trackLinkUrl(trackInfo)));
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Shows the currently playing track.";
|
||||
}
|
||||
// Show current position / total duration after a middot
|
||||
// (no [] — TeamSpeak parses it as a link reference).
|
||||
auto playbackState = manager->getPlaybackState();
|
||||
if (playbackState &&
|
||||
playbackState->currentTrack.has_value() &&
|
||||
trackInfo.duration.has_value() &&
|
||||
trackInfo.duration->count() > 0) {
|
||||
auto position = playbackState->position;
|
||||
msg += std::format(" {} {}/{}", kDot,
|
||||
formatDuration(position),
|
||||
formatDuration(*trackInfo.duration));
|
||||
} else if (trackInfo.duration.has_value() &&
|
||||
trackInfo.duration->count() > 0) {
|
||||
msg += std::format(" {} {}", kDot,
|
||||
formatDuration(*trackInfo.duration));
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
if (!track.addedBy.empty()) {
|
||||
msg += std::format(" (requested by {})",
|
||||
escapeMarkdown(track.addedBy));
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"np", "current", "playing"};
|
||||
}
|
||||
};
|
||||
// Same at-a-glance status footer as !help and !list.
|
||||
if (std::string status = playbackStatusLine(ctx);
|
||||
!status.empty()) {
|
||||
msg += "\n\n";
|
||||
msg += status;
|
||||
}
|
||||
|
||||
ctx.reply(msg);
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"NowPlayingCommand", "{}",
|
||||
std::format("NowPlaying command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("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
|
||||
@@ -1,51 +1,66 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class PauseCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
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;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
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.");
|
||||
}
|
||||
}
|
||||
auto result = manager->pause();
|
||||
if (!result) {
|
||||
Void::Log::error("PauseCommand", "{}",
|
||||
std::format("Pause command failed: {}",
|
||||
result.error().message));
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Pauses the current playback.";
|
||||
}
|
||||
if (result.error().code ==
|
||||
Api::ErrorCode::InvalidArgument) {
|
||||
ctx.reply(ctx.tr("Nothing is playing right now."));
|
||||
} else {
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't pause playback. Please try again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
ctx.reply(ctx.tr("Playback paused."));
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"PauseCommand", "{}",
|
||||
std::format("Pause command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
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
|
||||
@@ -1,125 +1,218 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
// Shared play rendering. Concrete commands pick the catalog scope:
|
||||
// !play (both), !pyt (YouTube), !pya (Yandex). A bare URL always plays
|
||||
// directly regardless of scope; free text searches the chosen catalog(s)
|
||||
// and, when there is more than one hit, shows a !select list — the same
|
||||
// flow as the search commands.
|
||||
class PlayCommandBase : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: play <url or search query>\nExample: play never gonna give you up");
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable. "
|
||||
"Please try again later."));
|
||||
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;
|
||||
}
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply(ctx.trf("Usage: {} <url or search "
|
||||
"query>\nExample: {} never "
|
||||
"gonna give you up",
|
||||
label(), label()));
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(std::format("Added to queue: {}", *result));
|
||||
return;
|
||||
}
|
||||
// Direct URL: hand straight to the player.
|
||||
if (ctx.args.find("http") == 0) {
|
||||
auto result = manager->play(ctx.args, ctx.clientId);
|
||||
if (!result) {
|
||||
Void::Log::error(
|
||||
"PlayCommand", "{}",
|
||||
std::format("Play URL failed '{}': {}",
|
||||
ctx.args, result.error().message));
|
||||
|
||||
// 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;
|
||||
}
|
||||
switch (result.error().code) {
|
||||
case Api::ErrorCode::NetworkError:
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't connect to that URL. "
|
||||
"Please check and try again."));
|
||||
break;
|
||||
case Api::ErrorCode::InvalidUrl:
|
||||
ctx.reply(ctx.tr(
|
||||
"That doesn't look like a valid URL."));
|
||||
break;
|
||||
default:
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't play that URL. Please "
|
||||
"try again."));
|
||||
break;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (searchResult->tracks.empty()) {
|
||||
ctx.reply("No results found. Try different keywords.");
|
||||
return;
|
||||
}
|
||||
ctx.reply(ctx.trf("Added to queue: {}", *result));
|
||||
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;
|
||||
}
|
||||
// Otherwise, search the chosen catalog(s).
|
||||
auto searchResult = manager->search(ctx.args, scope());
|
||||
if (!searchResult) {
|
||||
Void::Log::error(
|
||||
"PlayCommand", "{}",
|
||||
std::format("Search failed for '{}': {}", ctx.args,
|
||||
searchResult.error().message));
|
||||
|
||||
ctx.reply(std::format("Added to queue: {}", track.title));
|
||||
return;
|
||||
}
|
||||
if (searchResult.error().code ==
|
||||
Api::ErrorCode::NetworkError) {
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't connect to search service. "
|
||||
"Please check your connection."));
|
||||
} else {
|
||||
ctx.reply(
|
||||
ctx.tr("Search failed. Please try again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Multiple results - store and show list
|
||||
manager->storePendingSearch(ctx.clientId, searchResult->tracks);
|
||||
if (searchResult->tracks.empty()) {
|
||||
ctx.reply(ctx.tr(
|
||||
"No results found. Try different keywords."));
|
||||
return;
|
||||
}
|
||||
|
||||
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";
|
||||
}
|
||||
// Single result - queue immediately.
|
||||
if (searchResult->tracks.size() == 1) {
|
||||
const auto& track = searchResult->tracks[0];
|
||||
auto playResult =
|
||||
manager->queueTrack(track, ctx.clientId);
|
||||
if (!playResult) {
|
||||
Void::Log::error(
|
||||
"PlayCommand", "{}",
|
||||
std::format("Queue failed: {}",
|
||||
playResult.error().message));
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't add that track. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(msg);
|
||||
std::string displayText = track.title;
|
||||
if (!track.artist.empty()) {
|
||||
displayText = std::format("{} by {}", track.title,
|
||||
track.artist);
|
||||
}
|
||||
ctx.reply(ctx.trf(
|
||||
"Added to queue: {}",
|
||||
markdownLink(displayText, trackLinkUrl(track))));
|
||||
return;
|
||||
}
|
||||
|
||||
} 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.");
|
||||
}
|
||||
}
|
||||
// Multiple results - store and show list.
|
||||
manager->storePendingSearch(ctx.clientId,
|
||||
searchResult->tracks);
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Plays a track from URL or searches and lets you select.";
|
||||
}
|
||||
std::string msg =
|
||||
std::format("Multiple results \xe2\x80\x94 use "
|
||||
"{}select <number>:\n\n",
|
||||
ctx.prefix);
|
||||
for (size_t i = 0; i < searchResult->tracks.size() && i < 5;
|
||||
++i) {
|
||||
const auto& track = searchResult->tracks[i];
|
||||
std::string displayText = track.title;
|
||||
if (!track.artist.empty()) {
|
||||
displayText = std::format("{} by {}", track.title,
|
||||
track.artist);
|
||||
}
|
||||
msg += std::format(
|
||||
"{}. {}", i + 1,
|
||||
markdownLink(displayText, trackLinkUrl(track)));
|
||||
if (track.duration.has_value()) {
|
||||
msg += std::format(" {} {}", kDot,
|
||||
formatDuration(*track.duration));
|
||||
}
|
||||
msg += "\n";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "<url or search query>";
|
||||
}
|
||||
ctx.reply(msg);
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"PlayCommand", "{}",
|
||||
std::format("Play command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong while trying to play. "
|
||||
"Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"p", "add"};
|
||||
}
|
||||
};
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Play;
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
// The catalog(s) this command searches, and the command name used
|
||||
// in usage text.
|
||||
[[nodiscard]] virtual MusicManager::SearchScope scope() const = 0;
|
||||
[[nodiscard]] virtual std::string_view label() const = 0;
|
||||
|
||||
private:
|
||||
|
||||
static std::string
|
||||
formatDuration(std::chrono::milliseconds duration)
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
|
||||
// !play — both YouTube and Yandex Music.
|
||||
class PlayCommand : public PlayCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Plays a track from URL, or searches YouTube and Yandex "
|
||||
"Music and lets you select.";
|
||||
}
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<url or search query>";
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"p", "add"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::All;
|
||||
}
|
||||
std::string_view label() const override { return "play"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,80 +1,109 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class PlaylistCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
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;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (playlists->empty()) {
|
||||
ctx.reply("No playlists available.");
|
||||
return;
|
||||
}
|
||||
if (ctx.args.empty()) {
|
||||
// List playlists
|
||||
auto playlists = manager->getPlaylists();
|
||||
if (!playlists) {
|
||||
Void::Log::error(
|
||||
"PlaylistCommand", "{}",
|
||||
std::format("Playlist list failed: {}",
|
||||
playlists.error().message));
|
||||
ctx.reply(ctx.tr("Couldn't retrieve playlists."));
|
||||
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());
|
||||
}
|
||||
if (playlists->empty()) {
|
||||
ctx.reply(ctx.tr("No playlists available."));
|
||||
return;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
std::stringstream msg;
|
||||
msg << ctx.tr(
|
||||
"\xf0\x9f\x93\x81 Available playlists:\n");
|
||||
for (const auto& pl : *playlists) {
|
||||
msg << ctx.trf("- {} ({} tracks)\n", pl.name,
|
||||
pl.tracks.size());
|
||||
}
|
||||
|
||||
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.");
|
||||
}
|
||||
}
|
||||
ctx.reply(msg.str());
|
||||
} else {
|
||||
// Load playlist
|
||||
auto result = manager->loadPlaylist(
|
||||
std::string(ctx.args), ctx.clientId);
|
||||
if (!result) {
|
||||
Void::Log::error(
|
||||
"PlaylistCommand", "{}",
|
||||
std::format("Playlist load failed: {}",
|
||||
result.error().message));
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Lists or loads a playlist.";
|
||||
}
|
||||
if (result.error().code ==
|
||||
Api::ErrorCode::NotFound) {
|
||||
ctx.reply(
|
||||
ctx.tr("That playlist doesn't exist."));
|
||||
} else {
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't load the playlist. Please "
|
||||
"try again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "[playlist name]";
|
||||
}
|
||||
ctx.reply(ctx.trf(
|
||||
"Loading playlist '{}'... Tracks will be added to "
|
||||
"the queue as they are resolved.",
|
||||
ctx.args));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"PlaylistCommand", "{}",
|
||||
std::format("Playlist command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Lists or loads a playlist.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"pl"};
|
||||
}
|
||||
};
|
||||
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
|
||||
@@ -1,95 +1,181 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class QueueCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
auto current = manager->getCurrentTrack();
|
||||
auto queue = manager->getQueue();
|
||||
auto state = manager->getPlaybackState();
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!queue) {
|
||||
ECHOION_LOG_ERROR(std::format("Queue command failed: {}", queue.error().message));
|
||||
ctx.reply("Couldn't get queue information.");
|
||||
return;
|
||||
}
|
||||
auto current = manager->getCurrentTrack();
|
||||
auto queue = manager->getQueue();
|
||||
auto state = manager->getPlaybackState();
|
||||
|
||||
std::stringstream msg;
|
||||
msg << "\xf0\x9f\x93\x9c **Queue**\n";
|
||||
if (!queue) {
|
||||
Void::Log::error("QueueCommand", "{}",
|
||||
std::format("Queue command failed: {}",
|
||||
queue.error().message));
|
||||
ctx.reply(ctx.tr("Couldn't get queue information."));
|
||||
return;
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
// Parse page number from args (default to 1)
|
||||
int page = 1;
|
||||
if (!ctx.args.empty()) {
|
||||
try {
|
||||
page = std::stoi(std::string(ctx.args));
|
||||
if (page < 1) {
|
||||
page = 1;
|
||||
}
|
||||
} catch (const std::exception&) {
|
||||
page = 1;
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
constexpr int ITEMS_PER_PAGE = 10;
|
||||
int totalPages =
|
||||
(static_cast<int>(queue->size()) + ITEMS_PER_PAGE - 1) /
|
||||
ITEMS_PER_PAGE;
|
||||
if (totalPages == 0) {
|
||||
totalPages = 1;
|
||||
}
|
||||
|
||||
// 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));
|
||||
}
|
||||
// Clamp page to valid range
|
||||
if (page > totalPages) {
|
||||
page = totalPages;
|
||||
}
|
||||
|
||||
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.");
|
||||
}
|
||||
}
|
||||
int startIdx = (page - 1) * ITEMS_PER_PAGE;
|
||||
int endIdx = std::min(startIdx + ITEMS_PER_PAGE,
|
||||
static_cast<int>(queue->size()));
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Shows the current queue and playback status.";
|
||||
}
|
||||
std::stringstream msg;
|
||||
// Same at-a-glance status footer as !help and !np. A
|
||||
// "Paused" marker is prepended since the queue view is
|
||||
// where a stopped playhead is most relevant.
|
||||
if (std::string status = playbackStatusLine(ctx);
|
||||
!status.empty()) {
|
||||
if (state && state->isPaused) {
|
||||
msg << ctx.tr("\xe2\x8f\xb8 Paused\n");
|
||||
}
|
||||
msg << status;
|
||||
}
|
||||
// Current track
|
||||
if (current && current->has_value()) {
|
||||
const auto& track = current->value();
|
||||
const auto& trackInfo = track.track;
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
// Build time display: · current/total or · total
|
||||
// (no [] — TeamSpeak parses it as a link reference).
|
||||
std::string timeStr;
|
||||
if (trackInfo.duration.has_value() &&
|
||||
trackInfo.duration->count() > 0) {
|
||||
if (state) {
|
||||
timeStr = std::format(
|
||||
" {} {}/{}", kDot,
|
||||
formatDuration(state->position),
|
||||
formatDuration(*trackInfo.duration));
|
||||
} else {
|
||||
timeStr = std::format(
|
||||
" {} {}", kDot,
|
||||
formatDuration(*trackInfo.duration));
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"q", "list"};
|
||||
}
|
||||
};
|
||||
std::string displayText = trackInfo.title;
|
||||
if (!trackInfo.artist.empty()) {
|
||||
displayText = std::format(
|
||||
"{} by {}", trackInfo.title, trackInfo.artist);
|
||||
}
|
||||
msg << ctx.trf(
|
||||
"\n**Now Playing:** {}{}\n",
|
||||
markdownLink(displayText, trackLinkUrl(trackInfo)),
|
||||
timeStr);
|
||||
}
|
||||
|
||||
// Queue
|
||||
if (queue->empty()) {
|
||||
msg << ctx.trf(
|
||||
"\nThe queue is empty. Add songs with {}play !",
|
||||
ctx.prefix);
|
||||
} else {
|
||||
msg << ctx.trf("\n**Up Next ({} tracks):**\n",
|
||||
queue->size());
|
||||
for (int i = startIdx; i < endIdx; ++i) {
|
||||
const auto& entry = (*queue)[i];
|
||||
const auto& trackInfo = entry.track;
|
||||
std::string displayText = trackInfo.title;
|
||||
if (!trackInfo.artist.empty()) {
|
||||
displayText =
|
||||
std::format("{} by {}", trackInfo.title,
|
||||
trackInfo.artist);
|
||||
}
|
||||
msg << ctx.trf(
|
||||
"{}. {}", i + 1,
|
||||
markdownLink(displayText,
|
||||
trackLinkUrl(trackInfo)));
|
||||
if (trackInfo.duration.has_value()) {
|
||||
msg << ctx.trf(
|
||||
" {} {}", kDot,
|
||||
formatDuration(*trackInfo.duration));
|
||||
}
|
||||
if (!entry.addedBy.empty()) {
|
||||
msg << ctx.trf(" (by {})",
|
||||
escapeMarkdown(entry.addedBy));
|
||||
}
|
||||
msg << ctx.tr("\n");
|
||||
}
|
||||
|
||||
if (totalPages > 1) {
|
||||
msg << ctx.trf("\nUse {}queue <page> to see more "
|
||||
"(page {} of {})",
|
||||
ctx.prefix, page, totalPages);
|
||||
}
|
||||
}
|
||||
|
||||
msg << ctx.tr("\xf0\x9f\x93\x9c **Queue** (Page ") << page
|
||||
<< "/" << totalPages << ctx.tr(")\n");
|
||||
ctx.reply(msg.str());
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"QueueCommand", "{}",
|
||||
std::format("Queue command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Shows the current queue and playback status.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "[page]"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"q", "list"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,34 +1,57 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <CoreInterface.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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.");
|
||||
}
|
||||
class ReloadCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Shows information about reloading the bot.";
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
Void::Log::info("ReloadCommand", "{}",
|
||||
"Reload requested by user");
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
// Reload configuration from disk. A full core/plugin reload is
|
||||
// driven from the TS plugin menu (that lives in the plugin).
|
||||
if (auto core = ctx.service<Api::ICoreInterface>()) {
|
||||
auto result = core->reloadConfig();
|
||||
if (result) {
|
||||
ctx.reply(
|
||||
ctx.tr("✅ Configuration reloaded. For a full core "
|
||||
"reload, use the TS plugin menu."));
|
||||
} else {
|
||||
ctx.reply(std::string("❌ Config reload failed: ") +
|
||||
result.error().message);
|
||||
}
|
||||
} else {
|
||||
ctx.reply(
|
||||
ctx.tr("Reload is handled by the plugin. Use the TS "
|
||||
"plugin menu to reload the core."));
|
||||
}
|
||||
}
|
||||
|
||||
bool requiresAdmin() const override {
|
||||
return true;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Shows information about reloading the bot.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"restart", "r"};
|
||||
}
|
||||
};
|
||||
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
|
||||
@@ -1,42 +1,62 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include "echoion/core/Core.hpp" // For Core::reloadConfig
|
||||
#include <CoreInterface.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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.");
|
||||
}
|
||||
}
|
||||
class ReloadConfigCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Reloads the bot configuration from file.";
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto core = ctx.service<Api::ICoreInterface>();
|
||||
if (!core) {
|
||||
ctx.reply(
|
||||
ctx.tr("Config reload is unavailable right now."));
|
||||
return;
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
auto result = core->reloadConfig();
|
||||
if (result) {
|
||||
ctx.reply(
|
||||
ctx.tr("✅ Configuration reloaded from disk."));
|
||||
} else {
|
||||
ctx.reply(std::string("❌ Failed to reload config: ") +
|
||||
result.error().message);
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"ReloadConfigCommand",
|
||||
"{}",
|
||||
std::format("ReloadConfig command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
bool requiresAdmin() const override {
|
||||
return true;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Reloads the bot configuration from file.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"reloadcfg", "rlcfg"};
|
||||
}
|
||||
};
|
||||
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
|
||||
@@ -1,70 +1,94 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class RemoveCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: remove <position>\nUse [prefix]queue to see track positions.");
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
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;
|
||||
}
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply(
|
||||
ctx.trf("Usage: remove <position>\nUse {}queue "
|
||||
"to see track positions.",
|
||||
ctx.prefix));
|
||||
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;
|
||||
}
|
||||
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(
|
||||
ctx.tr("Please provide a valid position number "
|
||||
"(starting from 1)."));
|
||||
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.");
|
||||
}
|
||||
}
|
||||
auto remResult = manager->removeFromQueue(
|
||||
position - 1); // Convert to 0-based
|
||||
if (!remResult) {
|
||||
Void::Log::error(
|
||||
"RemoveCommand", "{}",
|
||||
std::format("Remove command failed: {}",
|
||||
remResult.error().message));
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Removes a track from the queue by position.";
|
||||
}
|
||||
if (remResult.error().code ==
|
||||
Api::ErrorCode::NotFound) {
|
||||
ctx.reply(ctx.tr(
|
||||
"That position doesn't exist in the queue."));
|
||||
} else {
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't remove that track. Please try "
|
||||
"again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "<position>";
|
||||
}
|
||||
ctx.reply(
|
||||
ctx.trf("Removed track at position {}.", position));
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"RemoveCommand", "{}",
|
||||
std::format("Remove command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Removes a track from the queue by position.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"rm", "delete", "del"};
|
||||
}
|
||||
};
|
||||
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
|
||||
@@ -1,46 +1,63 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class RepeatCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
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;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
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.");
|
||||
}
|
||||
}
|
||||
auto result = manager->toggleRepeat();
|
||||
if (!result) {
|
||||
Void::Log::error(
|
||||
"RepeatCommand", "{}",
|
||||
std::format("Repeat command failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't toggle repeat. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Toggles repeat mode for the current track.";
|
||||
}
|
||||
ctx.reply(*result
|
||||
? ctx.tr("\xf0\x9f\x94\x81 Repeat is now ON.")
|
||||
: ctx.tr("Repeat is now OFF."));
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"RepeatCommand", "{}",
|
||||
std::format("Repeat command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Toggles repeat mode for the current track.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"loop"};
|
||||
}
|
||||
};
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"loop"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,51 +1,68 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class ResumeCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
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;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
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.");
|
||||
}
|
||||
}
|
||||
auto result = manager->resume();
|
||||
if (!result) {
|
||||
Void::Log::error(
|
||||
"ResumeCommand", "{}",
|
||||
std::format("Resume command failed: {}",
|
||||
result.error().message));
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Resumes the paused playback.";
|
||||
}
|
||||
if (result.error().code ==
|
||||
Api::ErrorCode::InvalidArgument) {
|
||||
ctx.reply(
|
||||
ctx.tr("Playback isn't paused right now."));
|
||||
} else {
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't resume playback. Please try again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
ctx.reply(ctx.tr("Playback resumed."));
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"ResumeCommand", "{}",
|
||||
std::format("Resume command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"unpause", "continue"};
|
||||
}
|
||||
};
|
||||
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,28 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class RpcInfoCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override;
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Get RPC server connection information";
|
||||
}
|
||||
std::string_view getUsage() const override { return ""; }
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"rpc", "api", "remote"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,90 +1,152 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
// Shared search rendering. Concrete commands pick the catalog scope:
|
||||
// !search (both), !youtube/!yb (YouTube), !ya/!yandex (Yandex).
|
||||
class SearchCommandBase : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: search <query>\nExample: search never gonna give you up");
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
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 (ctx.args.empty()) {
|
||||
ctx.reply(ctx.trf("Usage: {} <query>", label()));
|
||||
return;
|
||||
}
|
||||
|
||||
if (result->tracks.empty()) {
|
||||
ctx.reply("No results found. Try different keywords.");
|
||||
return;
|
||||
}
|
||||
auto result = manager->search(ctx.args, scope());
|
||||
if (!result) {
|
||||
Void::Log::error(
|
||||
"SearchCommand", "{}",
|
||||
std::format("Search failed for '{}': {}", ctx.args,
|
||||
result.error().message));
|
||||
|
||||
// Store results for this client so they can use select
|
||||
manager->storePendingSearch(ctx.clientId, result->tracks);
|
||||
if (result.error().code ==
|
||||
Api::ErrorCode::NetworkError) {
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't connect to search service. "
|
||||
"Please check your connection."));
|
||||
} else {
|
||||
ctx.reply(ctx.tr(
|
||||
"Search failed. Please try again later."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
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";
|
||||
}
|
||||
if (result->tracks.empty()) {
|
||||
ctx.reply(ctx.tr(
|
||||
"No results found. Try different keywords."));
|
||||
return;
|
||||
}
|
||||
|
||||
msg << "\nUse [prefix]select <number> to play a result.";
|
||||
// Store results for this client so they can use select
|
||||
manager->storePendingSearch(ctx.clientId, result->tracks);
|
||||
|
||||
ctx.reply(msg.str());
|
||||
std::stringstream msg;
|
||||
msg << ctx.tr("Search results for \"") << ctx.args
|
||||
<< ctx.tr("\":\n\n");
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Search command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
for (size_t i = 0; i < result->tracks.size() && i < 5;
|
||||
++i) {
|
||||
const auto& track = result->tracks[i];
|
||||
std::string displayText = track.title;
|
||||
if (!track.artist.empty()) {
|
||||
displayText = std::format("{} by {}", track.title,
|
||||
track.artist);
|
||||
}
|
||||
// [escaped title](url) · duration (no [] around the
|
||||
// duration: TeamSpeak parses [..] as a link reference).
|
||||
msg << ctx.trf(
|
||||
"{}. {}", i + 1,
|
||||
markdownLink(displayText, trackLinkUrl(track)));
|
||||
if (track.duration.has_value()) {
|
||||
msg << " " << kDot << " "
|
||||
<< formatDuration(*track.duration);
|
||||
}
|
||||
msg << ctx.tr("\n");
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Searches for tracks and shows results.";
|
||||
}
|
||||
msg << ctx.trf("\nUse {}select <number> to play a result.",
|
||||
ctx.prefix);
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "<query>";
|
||||
}
|
||||
ctx.reply(msg.str());
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"SearchCommand", "{}",
|
||||
std::format("Search command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"find", "s"};
|
||||
}
|
||||
};
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Search;
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
// The catalog(s) this command searches, and the command name
|
||||
// used in usage text.
|
||||
[[nodiscard]] virtual MusicManager::SearchScope scope() const = 0;
|
||||
[[nodiscard]] virtual std::string_view label() const = 0;
|
||||
|
||||
private:
|
||||
|
||||
static std::string
|
||||
formatDuration(std::chrono::milliseconds duration)
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
|
||||
// !search — both YouTube and Yandex Music.
|
||||
class SearchCommand : public SearchCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Search YouTube and Yandex Music for tracks.";
|
||||
}
|
||||
std::string_view getUsage() const override { return "<query>"; }
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"find", "s"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::All;
|
||||
}
|
||||
std::string_view label() const override { return "search"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,84 +1,153 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
#include <chrono>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class SeekCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: seek <seconds>\nExample: seek 60 (jumps to 1 minute)");
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
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 (ctx.args.empty()) {
|
||||
ctx.reply(ctx.tr(
|
||||
"Usage: seek <+/-seconds>\nExamples:\n seek +30 "
|
||||
"(skip forward 30s)\n seek -10 (skip back 10s)\n "
|
||||
"seek 60 (jump to 1 minute mark)"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (seconds < 0) {
|
||||
ctx.reply("Time must be a positive number.");
|
||||
return;
|
||||
}
|
||||
// Parse the seek argument (supports +30, -10, or absolute
|
||||
// 60)
|
||||
std::string_view arg = ctx.args;
|
||||
bool relative = false;
|
||||
bool forward = true;
|
||||
|
||||
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;
|
||||
}
|
||||
if (arg.starts_with('+')) {
|
||||
relative = true;
|
||||
forward = true;
|
||||
arg = arg.substr(1);
|
||||
} else if (arg.starts_with('-')) {
|
||||
relative = true;
|
||||
forward = false;
|
||||
arg = arg.substr(1);
|
||||
}
|
||||
|
||||
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.");
|
||||
}
|
||||
}
|
||||
int seconds = 0;
|
||||
auto parseResult = std::from_chars(
|
||||
arg.data(), arg.data() + arg.size(), seconds);
|
||||
if (parseResult.ec != std::errc() || seconds < 0) {
|
||||
ctx.reply(ctx.tr(
|
||||
"Please provide a valid number of "
|
||||
"seconds.\nExamples: seek +30, seek -10, seek 60"));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Seeks to a position in the current track.";
|
||||
}
|
||||
std::chrono::milliseconds targetPosition;
|
||||
std::string positionStr;
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "<seconds>";
|
||||
}
|
||||
if (relative) {
|
||||
// Get current position from playback state
|
||||
auto state = manager->getPlaybackState();
|
||||
if (!state) {
|
||||
ctx.reply(ctx.tr(
|
||||
"Unable to get current playback position."));
|
||||
return;
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
auto currentPos = state->position;
|
||||
if (forward) {
|
||||
targetPosition =
|
||||
currentPos + std::chrono::seconds(seconds);
|
||||
positionStr = std::format("+{}s", seconds);
|
||||
} else {
|
||||
// Seek backward
|
||||
if (currentPos.count() < seconds * 1000) {
|
||||
targetPosition = std::chrono::milliseconds(0);
|
||||
} else {
|
||||
targetPosition =
|
||||
currentPos - std::chrono::seconds(seconds);
|
||||
}
|
||||
positionStr = std::format("-{}s", seconds);
|
||||
}
|
||||
} else {
|
||||
// Absolute seek (legacy behavior)
|
||||
targetPosition = std::chrono::seconds(seconds);
|
||||
auto mins = seconds / 60;
|
||||
auto secs = seconds % 60;
|
||||
positionStr = std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"jump"};
|
||||
}
|
||||
};
|
||||
auto result = manager->seek(targetPosition);
|
||||
if (!result) {
|
||||
Void::Log::error("SeekCommand", "{}",
|
||||
std::format("Seek command failed: {}",
|
||||
result.error().message));
|
||||
|
||||
if (result.error().code ==
|
||||
Api::ErrorCode::InvalidArgument) {
|
||||
ctx.reply(ctx.tr("Nothing is playing right now."));
|
||||
} else if (result.error().code ==
|
||||
Api::ErrorCode::NotSupported) {
|
||||
ctx.reply(
|
||||
ctx.tr("This track doesn't support seeking."));
|
||||
} else {
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't seek. Please try again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (relative) {
|
||||
ctx.reply(ctx.trf("Seeked {} from current position.",
|
||||
positionStr));
|
||||
} else {
|
||||
ctx.reply(
|
||||
ctx.trf("Seeked to position {}.", positionStr));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"SeekCommand", "{}",
|
||||
std::format("Seek command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Seeks to a position in the current track. Use +seconds "
|
||||
"to skip forward, -seconds to skip backward.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<+/-seconds>";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"jump"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,75 +1,99 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class SelectCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: select <number>\nSelect a track from your last search results.");
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
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;
|
||||
}
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply(ctx.tr(
|
||||
"Usage: select <number>\nSelect a track from "
|
||||
"your last search results."));
|
||||
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;
|
||||
}
|
||||
// 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(ctx.tr(
|
||||
"Please provide a valid number (1, 2, 3, etc.)."));
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*selectResult);
|
||||
std::string invokerName(ctx.invokerName);
|
||||
auto selectResult = manager->selectSearchResult(
|
||||
ctx.clientId, index, invokerName);
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Select command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
if (!selectResult) {
|
||||
Void::Log::error(
|
||||
"SelectCommand", "{}",
|
||||
std::format(
|
||||
"Select failed for client {} index {}: {}",
|
||||
ctx.clientId, index,
|
||||
selectResult.error().message));
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Selects a track from your search results.";
|
||||
}
|
||||
if (selectResult.error().code ==
|
||||
Api::ErrorCode::NotFound) {
|
||||
ctx.reply(
|
||||
ctx.trf("No search results found. Use {}play "
|
||||
"<query> to search first.",
|
||||
ctx.prefix));
|
||||
} else {
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't select that track. Please try "
|
||||
"again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "<number>";
|
||||
}
|
||||
ctx.reply(*selectResult);
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"SelectCommand", "{}",
|
||||
std::format("Select command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"sel", "pick", "choose"};
|
||||
}
|
||||
};
|
||||
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
|
||||
@@ -1,46 +1,61 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class ShuffleCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
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;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
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.");
|
||||
}
|
||||
}
|
||||
// Actually shuffle the queue (not just toggle mode)
|
||||
if (auto result = manager->shuffleQueue(); !result) {
|
||||
Void::Log::warn(
|
||||
"ShuffleCommand", "{}",
|
||||
std::format("Shuffle failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(ctx.tr(
|
||||
"Something went wrong. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Toggles shuffle mode for the queue.";
|
||||
}
|
||||
ctx.reply(ctx.tr("\xf0\x9f\x94\x80 Queue shuffled!"));
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"ShuffleCommand", "{}",
|
||||
std::format("Shuffle command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Toggles shuffle mode for the queue.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"random"};
|
||||
}
|
||||
};
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"random"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,71 +1,86 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class SkipCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
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;
|
||||
}
|
||||
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(ctx.tr(
|
||||
"Please provide a valid number (1 or more)."));
|
||||
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.");
|
||||
}
|
||||
}
|
||||
auto result = manager->skip(count);
|
||||
if (!result) {
|
||||
Void::Log::error("SkipCommand", "{}",
|
||||
std::format("Skip command failed: {}",
|
||||
result.error().message));
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Skips to the next track(s).";
|
||||
}
|
||||
if (result.error().code == Api::ErrorCode::NotFound) {
|
||||
ctx.reply(ctx.tr(
|
||||
"No more tracks in the queue to skip to."));
|
||||
} else {
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't skip. Please try again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "[count]";
|
||||
}
|
||||
if (count == 1) {
|
||||
ctx.reply(ctx.tr("Skipped to next track."));
|
||||
} else {
|
||||
ctx.reply(ctx.trf("Skipped {} tracks.", count));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"SkipCommand", "{}",
|
||||
std::format("Skip command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Skips to the next track(s).";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"next", "n"};
|
||||
}
|
||||
};
|
||||
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,35 @@
|
||||
#pragma once
|
||||
|
||||
#include "PlayCommand.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !psc / !playsc — play from SoundCloud only (URL or search).
|
||||
class SoundCloudPlayCommand : public PlayCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Plays from SoundCloud only (URL or search).";
|
||||
}
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<url or search query>";
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"playsc"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::SoundCloud;
|
||||
}
|
||||
std::string_view label() const override { return "psc"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include "SearchCommand.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !soundcloud / !sc — search SoundCloud only.
|
||||
class SoundCloudSearchCommand : public SearchCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Search SoundCloud only for tracks.";
|
||||
}
|
||||
std::string_view getUsage() const override { return "<query>"; }
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"sc", "scloud"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::SoundCloud;
|
||||
}
|
||||
std::string_view label() const override { return "soundcloud"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !stats — global playback statistics.
|
||||
class StatsCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
auto db = ctx.service<Api::Database>();
|
||||
if (!db) {
|
||||
ctx.reply(
|
||||
ctx.tr("Statistics are unavailable (no database)."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto stats = db->getStatistics(0);
|
||||
if (!stats) {
|
||||
ctx.reply(ctx.tr("Couldn't read playback statistics."));
|
||||
return;
|
||||
}
|
||||
|
||||
const auto totalMinutes = stats->totalPlaytimeMs / 1000 / 60;
|
||||
std::string msg = std::format(
|
||||
"\xf0\x9f\x93\x8a Plays: {} {} Unique tracks: {} {} "
|
||||
"Playtime: {}h {}m",
|
||||
stats->totalPlays, kDot, stats->totalTracks, kDot,
|
||||
totalMinutes / 60, totalMinutes % 60);
|
||||
if (stats->mostPlayedTrack) {
|
||||
msg += std::format("\nMost played: {} ({}x)",
|
||||
trackLink(*stats->mostPlayedTrack),
|
||||
stats->mostPlayedCount);
|
||||
}
|
||||
ctx.reply(msg);
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Show playback statistics";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,46 +1,60 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class StopCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
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;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
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.");
|
||||
}
|
||||
}
|
||||
auto result = manager->stop();
|
||||
if (!result) {
|
||||
Void::Log::error("StopCommand", "{}",
|
||||
std::format("Stop command failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't stop playback. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Stops playback and clears the queue.";
|
||||
}
|
||||
ctx.reply(ctx.tr("Playback stopped and queue cleared."));
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"StopCommand", "{}",
|
||||
std::format("Stop command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Stops playback and clears the queue.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"s"};
|
||||
}
|
||||
};
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"s"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,46 +1,63 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class SubscribeCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
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;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
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.");
|
||||
}
|
||||
}
|
||||
auto result = manager->subscribe(ctx.clientId);
|
||||
if (!result) {
|
||||
Void::Log::error("SubscribeCommand",
|
||||
"{}",
|
||||
std::format("Subscribe failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't subscribe you. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Subscribes to the music bot to receive audio.";
|
||||
}
|
||||
ctx.reply(*result);
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"SubscribeCommand",
|
||||
"{}",
|
||||
std::format("Subscribe command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Subscribes to the music bot to receive audio.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"sub", "join"};
|
||||
}
|
||||
};
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"sub", "join"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,112 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class SubscribersCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto subscribers = manager->getSubscribers();
|
||||
auto onlineUids = manager->getOnlineSubscriberUids();
|
||||
|
||||
if (subscribers.empty()) {
|
||||
ctx.reply(ctx.tr("No subscribers. Use !subscribe to "
|
||||
"receive audio."));
|
||||
return;
|
||||
}
|
||||
|
||||
// Separate online and offline
|
||||
std::vector<SubscriptionManager::Subscriber> online;
|
||||
std::vector<SubscriptionManager::Subscriber> offline;
|
||||
|
||||
for (const auto& sub : subscribers) {
|
||||
if (onlineUids.contains(sub.uid)) {
|
||||
online.push_back(sub);
|
||||
} else {
|
||||
offline.push_back(sub);
|
||||
}
|
||||
}
|
||||
|
||||
std::stringstream msg;
|
||||
msg << ctx.tr("\xf0\x9f\x93\x8b **Subscribed Users** (")
|
||||
<< subscribers.size() << ctx.tr(" total)\n");
|
||||
msg << ctx.tr("\xf0\x9f\x9f\xa2 Online: ") << online.size()
|
||||
<< ctx.tr(" | \xe2\x9a\xaa Offline: ") << offline.size()
|
||||
<< ctx.tr("\n\n");
|
||||
|
||||
// Online subscribers
|
||||
if (!online.empty()) {
|
||||
msg << ctx.tr("**\xf0\x9f\x9f\xa2 Online:**\n");
|
||||
for (size_t i = 0; i < online.size(); ++i) {
|
||||
const auto& sub = online[i];
|
||||
msg << ctx.trf("{}. **{}**\n", i + 1, sub.nickname);
|
||||
msg << ctx.trf(" UID: `{}`\n", sub.uid);
|
||||
}
|
||||
msg << ctx.tr("\n");
|
||||
}
|
||||
|
||||
// Offline subscribers
|
||||
if (!offline.empty()) {
|
||||
msg << ctx.tr("**\xe2\x9a\xaa Offline:**\n");
|
||||
for (size_t i = 0; i < offline.size(); ++i) {
|
||||
const auto& sub = offline[i];
|
||||
msg << ctx.trf("{}. **{}**\n", i + 1, sub.nickname);
|
||||
msg << ctx.trf(" UID: `{}`\n", sub.uid);
|
||||
}
|
||||
msg << ctx.tr("\n");
|
||||
}
|
||||
|
||||
msg << ctx.tr(
|
||||
"Use `!unsubscribeid <uid>` to remove a specific "
|
||||
"subscriber.\n");
|
||||
msg << ctx.tr(
|
||||
"Use `!unsubscribeall` to remove all subscribers.");
|
||||
|
||||
ctx.reply(msg.str());
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"SubscribersCommand", "{}",
|
||||
std::format("Subscribers command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Lists all subscribed users (online/offline).";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return ""; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"subs", "listsubs"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,68 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class UnsubscribeAllCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->clearAllSubscriptions();
|
||||
|
||||
if (!result) {
|
||||
Void::Log::error(
|
||||
"UnsubscribeAllCommand", "{}",
|
||||
std::format("Unsubscribe all failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't clear subscriptions. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*result);
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"UnsubscribeAllCommand", "{}",
|
||||
std::format("Unsubscribeall command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Removes all subscriptions (admin only).";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return ""; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"unsuball", "clearsubs"};
|
||||
}
|
||||
|
||||
bool requiresAdmin() const override { return true; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,46 +1,63 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class UnsubscribeCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
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;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
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.");
|
||||
}
|
||||
}
|
||||
auto result = manager->unsubscribe(ctx.clientId);
|
||||
if (!result) {
|
||||
Void::Log::error("UnsubscribeCommand",
|
||||
"{}",
|
||||
std::format("Unsubscribe failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't unsubscribe you. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Unsubscribes from the music bot.";
|
||||
}
|
||||
ctx.reply(*result);
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"UnsubscribeCommand",
|
||||
"{}",
|
||||
std::format("Unsubscribe command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Unsubscribes from the music bot.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"unsub", "leave"};
|
||||
}
|
||||
};
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"unsub", "leave"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,76 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class UnsubscribeIdCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply(ctx.tr(
|
||||
"Please provide a user UID. Use !subscribers "
|
||||
"to see UIDs."));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string uid(ctx.args);
|
||||
auto result = manager->unsubscribeByUid(uid);
|
||||
|
||||
if (!result) {
|
||||
Void::Log::error(
|
||||
"UnsubscribeIdCommand", "{}",
|
||||
std::format("Unsubscribe by ID failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't unsubscribe user. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*result);
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"UnsubscribeIdCommand", "{}",
|
||||
std::format("Unsubscribeid command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Unsubscribes a user by their UID (admin only).";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "<uid>"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"unsubid", "removeuser"};
|
||||
}
|
||||
|
||||
bool requiresAdmin() const override { return true; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,85 +1,106 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
}
|
||||
class VolumeCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
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;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
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 (ctx.args.empty()) {
|
||||
// Show current volume
|
||||
auto state = manager->getPlaybackState();
|
||||
if (state) {
|
||||
ctx.reply(
|
||||
ctx.trf("Current volume: {}%",
|
||||
static_cast<int>(state->volume * 100)));
|
||||
} else {
|
||||
ctx.reply(ctx.tr("Unable to get current volume."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (volumePercent < 0 || volumePercent > 100) {
|
||||
ctx.reply("Volume must be between 0 and 100.");
|
||||
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(
|
||||
ctx.tr("Please provide a valid number (0-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;
|
||||
}
|
||||
if (volumePercent < 0 || volumePercent > 100) {
|
||||
ctx.reply(ctx.tr("Volume must be between 0 and 100."));
|
||||
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.");
|
||||
}
|
||||
}
|
||||
float volume = volumePercent / 100.0f;
|
||||
auto volResult = manager->setVolume(volume);
|
||||
if (!volResult) {
|
||||
Void::Log::error(
|
||||
"VolumeCommand", "{}",
|
||||
std::format("Volume command failed: {}",
|
||||
volResult.error().message));
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't change volume. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Sets or shows the playback volume.";
|
||||
}
|
||||
// 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
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "[0-100]";
|
||||
}
|
||||
ctx.reply(
|
||||
ctx.trf("Volume: {}% {}", volumePercent, indicator));
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"VolumeCommand", "{}",
|
||||
std::format("Volume command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Sets or shows the playback volume.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"vol", "v"};
|
||||
}
|
||||
};
|
||||
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
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include "PlayCommand.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !pya / !playya — play from Yandex Music only.
|
||||
class YandexPlayCommand : public PlayCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Plays from Yandex Music only (URL or search).";
|
||||
}
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<url or search query>";
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"playya"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::Yandex;
|
||||
}
|
||||
std::string_view label() const override { return "pya"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include "SearchCommand.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !yandex / !ya — search Yandex Music only.
|
||||
class YandexSearchCommand : public SearchCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Search Yandex Music only for tracks.";
|
||||
}
|
||||
std::string_view getUsage() const override { return "<query>"; }
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"ya"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::Yandex;
|
||||
}
|
||||
std::string_view label() const override { return "yandex"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include "PlayCommand.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !pyt / !playyt — play from YouTube only.
|
||||
class YoutubePlayCommand : public PlayCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Plays from YouTube only (URL or search).";
|
||||
}
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<url or search query>";
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"playyt"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::YouTube;
|
||||
}
|
||||
std::string_view label() const override { return "pyt"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include "SearchCommand.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !youtube / !yb — search YouTube only.
|
||||
class YoutubeSearchCommand : public SearchCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Search YouTube only for tracks.";
|
||||
}
|
||||
std::string_view getUsage() const override { return "<query>"; }
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"yb", "yt"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::YouTube;
|
||||
}
|
||||
std::string_view label() const override { return "youtube"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Core::Detail
|
||||
{
|
||||
[[nodiscard]] inline std::optional<std::uint64_t>
|
||||
uintField(const Void::Json::Value& object, std::string_view key)
|
||||
{
|
||||
const auto* value = object.find(key);
|
||||
if (!value || !value->is_number()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const auto number = value->as_number();
|
||||
// A double equal to 2^64 is what uint64_t::max() rounds to, so use
|
||||
// an exclusive 2^64 bound before converting. Floating-to-integer
|
||||
// conversion outside the destination range is undefined behavior.
|
||||
constexpr double kUint64Limit = 18446744073709551616.0;
|
||||
if (!std::isfinite(number) || number < 0.0 ||
|
||||
std::trunc(number) != number || number >= kUint64Limit) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return static_cast<std::uint64_t>(number);
|
||||
}
|
||||
} // namespace Echoion::Core::Detail
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
|
||||
#include <format>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Core::I18n
|
||||
{
|
||||
|
||||
// Languages the bot can reply in. English is the source language: every
|
||||
// English string in the code is a valid translation key, so English never
|
||||
// needs a table entry.
|
||||
enum class Language { English, Russian };
|
||||
|
||||
// Parse a language code ("en"/"ru", case-insensitive). Unknown codes fall
|
||||
// back to English so a bad config/kv value never breaks replies.
|
||||
Language parseLanguage(std::string_view code);
|
||||
|
||||
// The canonical code ("en"/"ru") — used as the kv_store / config value.
|
||||
std::string_view languageCode(Language lang);
|
||||
|
||||
// Human-readable, self-referential name ("English" / "Русский").
|
||||
std::string_view languageName(Language lang);
|
||||
|
||||
// Translate an English source string to `lang`. Returns the original string
|
||||
// unchanged when `lang` is English or no translation is registered, so a
|
||||
// missing entry degrades gracefully to English rather than to an empty
|
||||
// message.
|
||||
std::string_view translate(std::string_view english, Language lang);
|
||||
|
||||
} // namespace Echoion::Core::I18n
|
||||
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
|
||||
#include "echoion/core/NetworkClient.hpp"
|
||||
#include "echoion/core/licensing/LicenseVerifier.hpp"
|
||||
|
||||
#include <ConfigTypes.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
namespace Echoion::Core::Licensing
|
||||
{
|
||||
class LicenseManager
|
||||
{
|
||||
public:
|
||||
|
||||
LicenseManager(Api::LicensingConfig config,
|
||||
std::shared_ptr<NetworkClient>
|
||||
network,
|
||||
std::filesystem::path stateDirectory);
|
||||
~LicenseManager();
|
||||
|
||||
LicenseManager(const LicenseManager&) = delete;
|
||||
LicenseManager& operator=(const LicenseManager&) = delete;
|
||||
|
||||
/// Load a still-valid cached lease and then attempt an online
|
||||
/// refresh. A failed refresh retains a valid cache; otherwise
|
||||
/// operation remains update-only.
|
||||
void initialize();
|
||||
void shutdown();
|
||||
void refreshNow();
|
||||
|
||||
[[nodiscard]] bool canOperate() const noexcept;
|
||||
[[nodiscard]] LeaseStatus status() const;
|
||||
[[nodiscard]] std::string deviceId() const;
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] Void::Result::Result<LeaseStatus>
|
||||
verifyBundle(std::string_view bundle,
|
||||
std::string_view expectedChallenge);
|
||||
[[nodiscard]] std::string loadOrCreateDeviceId();
|
||||
void installStatus(LeaseStatus status);
|
||||
void installFailure(std::string reason,
|
||||
bool retainValidLease = true);
|
||||
void run(std::stop_token stopToken);
|
||||
|
||||
Api::LicensingConfig config_;
|
||||
std::shared_ptr<NetworkClient> network_;
|
||||
std::filesystem::path stateDirectory_;
|
||||
Void::Update::Keyring rootKeys_;
|
||||
std::string deviceId_;
|
||||
std::atomic<bool> operational_{false};
|
||||
std::atomic<std::int64_t> operationalUntilUnix_{0};
|
||||
mutable std::mutex mutex_;
|
||||
LeaseStatus status_;
|
||||
std::jthread refreshThread_;
|
||||
std::uint64_t minimumSequence_{0};
|
||||
};
|
||||
} // namespace Echoion::Core::Licensing
|
||||
@@ -0,0 +1,60 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Update/Feed.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core::Licensing
|
||||
{
|
||||
enum class Mode { Active, UpdateOnly };
|
||||
|
||||
struct LeaseContext {
|
||||
std::string productId;
|
||||
std::string productVersion;
|
||||
std::string deviceId;
|
||||
std::string buildSignature;
|
||||
std::string challenge;
|
||||
std::chrono::system_clock::time_point now;
|
||||
std::chrono::milliseconds maximumLeaseLifetime{
|
||||
std::chrono::hours(24)};
|
||||
std::uint64_t minimumSequence{0};
|
||||
};
|
||||
|
||||
struct LeaseStatus {
|
||||
Mode mode{Mode::UpdateOnly};
|
||||
std::string reason;
|
||||
std::string licenseId;
|
||||
std::uint64_t sequence{0};
|
||||
std::chrono::system_clock::time_point refreshAfter;
|
||||
std::chrono::system_clock::time_point expiresAt;
|
||||
std::vector<std::string> entitlements;
|
||||
};
|
||||
|
||||
/// Decode a base64/base64url Ed25519 public key and add it to a keyring.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
addPublicKey(Void::Update::Keyring& keyring, std::string_view keyId,
|
||||
std::string_view encodedKey);
|
||||
|
||||
/// Verify a root-signed keyset and append currently valid, non-revoked
|
||||
/// lease signing keys. The pinned root itself remains in the returned
|
||||
/// keyring so a direct emergency root-signed lease can still be accepted.
|
||||
[[nodiscard]] Void::Result::Result<Void::Update::Keyring>
|
||||
verifyKeyset(std::string_view envelopeJson,
|
||||
const Void::Update::Keyring& rootKeys,
|
||||
std::chrono::system_clock::time_point now);
|
||||
|
||||
/// Verify the signed lease and signed revocation snapshot as one decision.
|
||||
/// Any malformed, expired, replayed, mismatched, or revoked input fails
|
||||
/// closed into UpdateOnly through the returned error.
|
||||
[[nodiscard]] Void::Result::Result<LeaseStatus>
|
||||
verifyLease(std::string_view leaseEnvelopeJson,
|
||||
std::string_view revocationEnvelopeJson,
|
||||
const Void::Update::Keyring& leaseKeys,
|
||||
const LeaseContext& context);
|
||||
} // namespace Echoion::Core::Licensing
|
||||
@@ -0,0 +1,93 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Fixed-capacity ring buffer of audio samples for the playback thread.
|
||||
//
|
||||
// A std::vector<short> drained with erase(begin(), begin()+n) every 20ms
|
||||
// is an O(n) shift of the whole remaining buffer on the real-time audio
|
||||
// path. This ring buffer drains by advancing a head index (O(1)) and
|
||||
// reuses one contiguous allocation, so steady-state playback performs
|
||||
// zero per-frame allocations and no element shuffling. Capacity grows
|
||||
// only if a decoder hands back an unusually large chunk (rare); steady
|
||||
// state never reallocates.
|
||||
//
|
||||
// Single-threaded by design: owned and touched only by the playback
|
||||
// engine thread.
|
||||
class AudioRingBuffer
|
||||
{
|
||||
public:
|
||||
|
||||
void reserve(std::size_t capacity)
|
||||
{
|
||||
if (capacity > storage_.size()) {
|
||||
grow(capacity);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t size() const { return count_; }
|
||||
[[nodiscard]] bool empty() const { return count_ == 0; }
|
||||
|
||||
// Read the i-th sample counting from the current head.
|
||||
short operator[](std::size_t i) const
|
||||
{
|
||||
return storage_[(head_ + i) % storage_.size()];
|
||||
}
|
||||
|
||||
void append(std::span<const short> data)
|
||||
{
|
||||
if (count_ + data.size() > storage_.size()) {
|
||||
grow(count_ + data.size());
|
||||
}
|
||||
const std::size_t cap = storage_.size();
|
||||
std::size_t tail = (head_ + count_) % cap;
|
||||
for (short sample : data) {
|
||||
storage_[tail] = sample;
|
||||
tail = (tail + 1) % cap;
|
||||
}
|
||||
count_ += data.size();
|
||||
}
|
||||
|
||||
// Drop the first n samples (advance head). O(1).
|
||||
void popFront(std::size_t n)
|
||||
{
|
||||
n = std::min(n, count_);
|
||||
head_ = (head_ + n) % storage_.size();
|
||||
count_ -= n;
|
||||
}
|
||||
|
||||
void clear()
|
||||
{
|
||||
head_ = 0;
|
||||
count_ = 0;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
void grow(std::size_t needed)
|
||||
{
|
||||
// Linearise existing samples into a fresh, larger buffer.
|
||||
std::size_t newCap = storage_.empty() ? 1 : storage_.size();
|
||||
while (newCap < needed) {
|
||||
newCap *= 2;
|
||||
}
|
||||
std::vector<short> next(newCap);
|
||||
for (std::size_t i = 0; i < count_; ++i) {
|
||||
next[i] = storage_[(head_ + i) % storage_.size()];
|
||||
}
|
||||
storage_ = std::move(next);
|
||||
head_ = 0;
|
||||
}
|
||||
|
||||
std::vector<short> storage_;
|
||||
std::size_t head_ = 0;
|
||||
std::size_t count_ = 0;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
namespace Echoion::Core::PlaybackDetail
|
||||
{
|
||||
/// A boundary can be emitted without padding when the outgoing tail and
|
||||
/// already-decoded incoming PCM together fill one device frame.
|
||||
[[nodiscard]] constexpr bool
|
||||
canFillDeviceFrame(std::size_t outgoingSamples,
|
||||
std::size_t incomingSamples,
|
||||
std::size_t frameSamples) noexcept
|
||||
{
|
||||
return frameSamples > 0 && outgoingSamples > 0 &&
|
||||
outgoingSamples < frameSamples &&
|
||||
incomingSamples >= frameSamples - outgoingSamples;
|
||||
}
|
||||
} // namespace Echoion::Core::PlaybackDetail
|
||||
@@ -0,0 +1,348 @@
|
||||
#pragma once
|
||||
|
||||
#include "../AudioDecoder.hpp"
|
||||
#include "AudioRingBuffer.hpp"
|
||||
#include "PositionClock.hpp"
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <thread>
|
||||
#include <variant>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Everything the engine needs from the outside world. Implemented by
|
||||
// MusicManager; keeps queue policy, source resolution and event
|
||||
// publication out of the real-time loop.
|
||||
class IPlaybackHost
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~IPlaybackHost() = default;
|
||||
|
||||
// Emit one 20ms PCM chunk to the audio sink (TeamSpeak).
|
||||
virtual void emitAudio(std::span<const short> samples) = 0;
|
||||
|
||||
// Resolve a playable URL / local file path for the entry.
|
||||
// Blocking; the engine calls it on a detached async, never on the
|
||||
// audio thread. preferDownload retries via the proxy-download
|
||||
// path after a direct open failed.
|
||||
virtual Api::Result<std::string>
|
||||
resolveStream(const Api::QueueEntry& entry,
|
||||
bool preferDownload) = 0;
|
||||
|
||||
// Queue access: peek what would play next / pop it if unchanged.
|
||||
virtual std::optional<Api::QueueEntry> peekNextTrack() = 0;
|
||||
virtual std::optional<Api::QueueEntry>
|
||||
takeNextTrack(uint64_t expectedQueueId) = 0;
|
||||
// Unconditional pop (fallback when the peeked entry vanished).
|
||||
virtual std::optional<Api::QueueEntry> takeAnyNextTrack() = 0;
|
||||
|
||||
virtual bool repeatEnabled() const = 0;
|
||||
|
||||
// Lifecycle notifications (called on the engine thread).
|
||||
virtual void onTrackStarted(const Api::QueueEntry& entry) = 0;
|
||||
virtual void
|
||||
onTrackFinished(const Api::QueueEntry& entry,
|
||||
std::chrono::milliseconds finalPosition) = 0;
|
||||
virtual void onPositionTick(const Api::QueueEntry& entry,
|
||||
std::chrono::milliseconds position,
|
||||
std::chrono::milliseconds duration) = 0;
|
||||
// Queue ran dry; engine went idle.
|
||||
virtual void onEngineIdle() = 0;
|
||||
// A resolved local temp file finished playing and can be deleted.
|
||||
virtual void onLocalFileDone(const std::string& path) = 0;
|
||||
// A track failed to resolve or open (before the engine advanced
|
||||
// past it). Called on the engine thread.
|
||||
virtual void onPlaybackError(
|
||||
const Api::Error& error,
|
||||
const std::optional<Api::QueueEntry>& entry) = 0;
|
||||
};
|
||||
|
||||
// Real-time playback engine with gapless track transitions.
|
||||
//
|
||||
// One fixed-cadence (20ms) loop owns BOTH AudioDecoder instances, the
|
||||
// ring buffer and the position clock; no other thread ever touches them.
|
||||
// Control arrives through a small command mailbox; state is published
|
||||
// through atomics. While the current track plays, the next one is
|
||||
// resolved asynchronously and its decoder pre-opened ("warm"), so at EOF
|
||||
// the engine swaps slots and PCM flows without interruption.
|
||||
class PlaybackEngine
|
||||
{
|
||||
public:
|
||||
|
||||
// Sample layout must match the TS3 custom device registration.
|
||||
static constexpr uint32_t SAMPLE_RATE = 192000;
|
||||
static constexpr uint32_t CHANNELS = 2;
|
||||
static constexpr int CHUNK_MS = 20;
|
||||
static constexpr size_t SHORTS_PER_CHUNK =
|
||||
(SAMPLE_RATE * CHANNELS * CHUNK_MS) / 1000;
|
||||
static constexpr auto PREFETCH_THRESHOLD = std::chrono::seconds(15);
|
||||
static constexpr int MAX_CONSECUTIVE_FAILURES = 5;
|
||||
// Grace while a download-to-file retry is in flight. Must cover
|
||||
// YouTubeClient::downloadAudioToFile's 180s wait — the normal
|
||||
// resolve grace (bot.trackTimeout, ~10s) would skip the track
|
||||
// long before the download lands.
|
||||
static constexpr int64_t DOWNLOAD_GRACE_MS = 200'000;
|
||||
|
||||
// How long the engine emits silence waiting for a late resolve
|
||||
// before it gives up on the track and advances. Configurable via
|
||||
// bot.trackTimeout.
|
||||
void setResolveGrace(std::chrono::milliseconds grace)
|
||||
{
|
||||
if (grace.count() > 0) {
|
||||
resolveGraceMs_.store(grace.count());
|
||||
}
|
||||
}
|
||||
|
||||
// Crossfade duration between tracks (bot.crossfadeMs);
|
||||
// 0 = plain gapless handoff.
|
||||
void setCrossfade(std::chrono::milliseconds duration)
|
||||
{
|
||||
crossfadeMs_.store(std::max<int64_t>(duration.count(), 0));
|
||||
}
|
||||
|
||||
// Loudness normalization (features.normalizeLoudness /
|
||||
// targetLoudnessDb): slow AGC toward the target RMS level,
|
||||
// applied before the user volume.
|
||||
void setNormalization(bool enabled, float targetDb)
|
||||
{
|
||||
normalizeTargetDb_.store(targetDb);
|
||||
normalizeEnabled_.store(enabled);
|
||||
}
|
||||
|
||||
explicit PlaybackEngine(IPlaybackHost& host);
|
||||
~PlaybackEngine();
|
||||
|
||||
Api::Result<void>
|
||||
initialize(const std::optional<Void::Net::ProxyConfig>& proxy);
|
||||
void shutdown();
|
||||
|
||||
void setProxyConfig(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy);
|
||||
|
||||
// ---- control (thread-safe, non-blocking) ---------------------
|
||||
|
||||
// Play this entry now, replacing whatever is playing. The URL was
|
||||
// already resolved by the caller (so resolution errors could be
|
||||
// reported to the user synchronously).
|
||||
void playNow(Api::QueueEntry entry, std::string streamUrl,
|
||||
bool isLocalFile);
|
||||
|
||||
// Wake the engine so it pulls from the queue if it is idle.
|
||||
void start();
|
||||
|
||||
void pause();
|
||||
void resume();
|
||||
void stopPlayback(); // stop + drop current track (engine idles)
|
||||
void skip(uint32_t count);
|
||||
void seekTo(std::chrono::milliseconds position);
|
||||
|
||||
// Restore after hot reload: open url, seek, optionally stay
|
||||
// paused.
|
||||
void restore(Api::QueueEntry entry, std::string streamUrl,
|
||||
std::chrono::milliseconds position, bool paused);
|
||||
|
||||
void setVolume(float volume) { volume_.store(volume); }
|
||||
[[nodiscard]] float volume() const { return volume_.load(); }
|
||||
|
||||
// ---- state (thread-safe reads) --------------------------------
|
||||
|
||||
[[nodiscard]] bool isPlaying() const { return playing_.load(); }
|
||||
[[nodiscard]] bool isPaused() const { return paused_.load(); }
|
||||
[[nodiscard]] std::chrono::milliseconds position() const
|
||||
{
|
||||
return clock_.position();
|
||||
}
|
||||
[[nodiscard]] std::optional<Api::QueueEntry> currentEntry() const;
|
||||
[[nodiscard]] std::chrono::milliseconds currentDuration() const;
|
||||
|
||||
private:
|
||||
|
||||
// ---- mailbox ---------------------------------------------------
|
||||
|
||||
struct CmdPlayNow {
|
||||
Api::QueueEntry entry;
|
||||
std::string url;
|
||||
bool isLocalFile = false;
|
||||
};
|
||||
struct CmdStart {
|
||||
};
|
||||
struct CmdPause {
|
||||
};
|
||||
struct CmdResume {
|
||||
};
|
||||
struct CmdStop {
|
||||
};
|
||||
struct CmdSkip {
|
||||
uint32_t count = 1;
|
||||
};
|
||||
struct CmdSeek {
|
||||
std::chrono::milliseconds position;
|
||||
};
|
||||
struct CmdRestore {
|
||||
Api::QueueEntry entry;
|
||||
std::string url;
|
||||
std::chrono::milliseconds position;
|
||||
bool paused = false;
|
||||
};
|
||||
using Command =
|
||||
std::variant<CmdPlayNow, CmdStart, CmdPause, CmdResume, CmdStop,
|
||||
CmdSkip, CmdSeek, CmdRestore>;
|
||||
|
||||
void post(Command cmd);
|
||||
|
||||
// ---- decoder slots --------------------------------------------
|
||||
|
||||
struct ResolvedStream {
|
||||
std::string url;
|
||||
bool isLocalFile = false;
|
||||
};
|
||||
|
||||
struct DecoderSlot {
|
||||
enum class State {
|
||||
Idle, // nothing assigned
|
||||
Resolving, // resolveFuture in flight
|
||||
Warming, // decoder open, pre-filling its queue
|
||||
Active, // currently feeding the ring buffer
|
||||
};
|
||||
|
||||
State state = State::Idle;
|
||||
std::unique_ptr<AudioDecoder> decoder;
|
||||
std::optional<Api::QueueEntry> entry;
|
||||
std::future<Api::Result<std::string>> resolveFuture;
|
||||
std::chrono::steady_clock::time_point resolveStartedAt{};
|
||||
std::string openUrl;
|
||||
bool isLocalFile = false;
|
||||
// Whether the download-to-file fallback was already tried
|
||||
// for this entry (bounds the retry to one attempt).
|
||||
bool triedDownload = false;
|
||||
|
||||
void closeAndReset()
|
||||
{
|
||||
if (decoder) {
|
||||
decoder->closeSource();
|
||||
}
|
||||
state = State::Idle;
|
||||
entry.reset();
|
||||
resolveFuture = {};
|
||||
openUrl.clear();
|
||||
isLocalFile = false;
|
||||
triedDownload = false;
|
||||
}
|
||||
};
|
||||
|
||||
// Kick off an async download-to-file retry for the slot's entry
|
||||
// (preferDownload=true). Returns false when no retry is possible
|
||||
// (already tried, or no entry).
|
||||
bool retryViaDownload(DecoderSlot& slot);
|
||||
|
||||
// ---- engine thread --------------------------------------------
|
||||
|
||||
void run(std::stop_token st);
|
||||
void drainMailbox();
|
||||
void handle(CmdPlayNow&& cmd);
|
||||
void handle(CmdStart&&);
|
||||
void handle(CmdPause&&);
|
||||
void handle(CmdResume&&);
|
||||
void handle(CmdStop&&);
|
||||
void handle(CmdSkip&& cmd);
|
||||
void handle(CmdSeek&& cmd);
|
||||
void handle(CmdRestore&& cmd);
|
||||
|
||||
// Try to begin playing the next queued track in the current slot
|
||||
// (used when idle). Returns true when a track started resolving
|
||||
// or playing.
|
||||
bool beginNextFromQueue();
|
||||
|
||||
// Kick off async resolution of the upcoming track into next_.
|
||||
void maybeStartPrefetch();
|
||||
// Move a finished resolve into an open, warming decoder.
|
||||
void pollNextResolve();
|
||||
// Current track hit EOF and drained: hand off or advance.
|
||||
void handleTrackEnd();
|
||||
// Crossfade: drain the current track's tail and swap to the warm
|
||||
// slot early so emitChunk can mix the two.
|
||||
void beginCrossfade();
|
||||
void clearFade()
|
||||
{
|
||||
fadeTail_.clear();
|
||||
fadeTailPos_ = 0;
|
||||
fadeEnvPos_ = 0;
|
||||
fadeIncomingStarved_ = false;
|
||||
}
|
||||
// AGC gain for one chunk (updates the internal RMS/gain state).
|
||||
[[nodiscard]] float agcGainFor(std::size_t samples);
|
||||
// Open `slot`'s decoder for `url`; false on failure.
|
||||
bool openSlot(DecoderSlot& slot, const std::string& url,
|
||||
bool isLocalFile);
|
||||
void activateSlot(DecoderSlot& slot,
|
||||
std::chrono::milliseconds startAt =
|
||||
std::chrono::milliseconds(0));
|
||||
void publishCurrent(const std::optional<Api::QueueEntry>& entry);
|
||||
void emitChunk(bool fromRing);
|
||||
void positionTick();
|
||||
|
||||
IPlaybackHost& host_;
|
||||
|
||||
// Mailbox
|
||||
std::mutex mailboxMutex_;
|
||||
std::deque<Command> mailbox_;
|
||||
std::condition_variable mailboxCv_;
|
||||
|
||||
// Engine-thread-only state
|
||||
DecoderSlot current_;
|
||||
DecoderSlot next_;
|
||||
AudioRingBuffer ring_;
|
||||
std::vector<short> outChunk_;
|
||||
std::vector<int16_t> incomingChunk_;
|
||||
std::chrono::steady_clock::time_point nextTick_{};
|
||||
std::chrono::steady_clock::time_point lastPositionTick_{};
|
||||
std::chrono::steady_clock::time_point silenceSince_{};
|
||||
int consecutiveFailures_ = 0;
|
||||
|
||||
// Crossfade state (engine thread only): the outgoing track's
|
||||
// remaining PCM, mixed into the incoming track equal-power.
|
||||
// The tail cursor and the envelope advance independently: the
|
||||
// tail plays continuously, while the envelope only progresses as
|
||||
// incoming audio is actually delivered — so a network-starved
|
||||
// incoming stream stretches the fade instead of being chopped
|
||||
// against a racing envelope.
|
||||
std::vector<short> fadeTail_;
|
||||
std::size_t fadeTailPos_ = 0;
|
||||
std::size_t fadeEnvPos_ = 0;
|
||||
bool fadeIncomingStarved_ = false;
|
||||
|
||||
// AGC state (engine thread only): EMA of mean-square level and
|
||||
// the current smoothed gain in dB.
|
||||
double agcMeanSquare_ = 0.0;
|
||||
float agcGainDb_ = 0.0f;
|
||||
|
||||
// Published state
|
||||
std::atomic<bool> playing_{false};
|
||||
std::atomic<bool> paused_{false};
|
||||
std::atomic<float> volume_{0.5f};
|
||||
std::atomic<int64_t> resolveGraceMs_{10000};
|
||||
std::atomic<int64_t> crossfadeMs_{0};
|
||||
std::atomic<bool> normalizeEnabled_{false};
|
||||
std::atomic<float> normalizeTargetDb_{-14.0f};
|
||||
PositionClock clock_;
|
||||
mutable std::mutex currentEntryMutex_;
|
||||
std::optional<Api::QueueEntry> publishedEntry_;
|
||||
std::atomic<int64_t> currentDurationMs_{0};
|
||||
|
||||
std::optional<Void::Net::ProxyConfig> proxy_;
|
||||
std::jthread thread_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,89 @@
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Wall-clock based playback position. Replaces the playbackPosition_ /
|
||||
// playbackBasePosition_ / playbackStartTime_ triple whose reset logic was
|
||||
// duplicated across play/resume/skip/seek/track-finished/restore.
|
||||
//
|
||||
// Lock-free: the engine thread writes, any thread reads a consistent
|
||||
// position (worst case one field is a few ns stale, irrelevant at ms
|
||||
// granularity for UI display).
|
||||
class PositionClock
|
||||
{
|
||||
public:
|
||||
|
||||
using ms = std::chrono::milliseconds;
|
||||
|
||||
// Track started from zero (or restarted); clock runs.
|
||||
void restart()
|
||||
{
|
||||
seekTo(ms{0});
|
||||
running_.store(true);
|
||||
}
|
||||
|
||||
// Jump to a position and keep running/paused state.
|
||||
void seekTo(ms position)
|
||||
{
|
||||
baseMs_.store(position.count());
|
||||
startedAtNs_.store(nowNs());
|
||||
}
|
||||
|
||||
void pause()
|
||||
{
|
||||
if (!running_.exchange(false)) {
|
||||
return;
|
||||
}
|
||||
baseMs_.store(currentMs());
|
||||
}
|
||||
|
||||
void resume()
|
||||
{
|
||||
if (running_.load()) {
|
||||
return; // already running; resetting startedAt would
|
||||
// rewind the position
|
||||
}
|
||||
startedAtNs_.store(nowNs());
|
||||
running_.store(true);
|
||||
}
|
||||
|
||||
void stop()
|
||||
{
|
||||
running_.store(false);
|
||||
baseMs_.store(0);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool running() const { return running_.load(); }
|
||||
|
||||
[[nodiscard]] ms position() const { return ms{currentMs()}; }
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] static int64_t nowNs()
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
[[nodiscard]] int64_t currentMs() const
|
||||
{
|
||||
const int64_t base = baseMs_.load();
|
||||
if (!running_.load()) {
|
||||
return base;
|
||||
}
|
||||
const int64_t elapsedNs = nowNs() - startedAtNs_.load();
|
||||
return base + elapsedNs / 1'000'000;
|
||||
}
|
||||
|
||||
std::atomic<int64_t> baseMs_{0};
|
||||
std::atomic<int64_t> startedAtNs_{0};
|
||||
std::atomic<bool> running_{false};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,97 @@
|
||||
#pragma once
|
||||
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Owns the playback queue, shuffle order and repeat flag. Self-locking:
|
||||
// every public method takes the internal mutex, so callers never manage
|
||||
// queue locks (the old QueueManager exposed raw references and relied on
|
||||
// MusicManager's shared_mutex, which several writers acquired shared).
|
||||
//
|
||||
// Shuffle model: shuffledIndices_ is a permutation of positions into
|
||||
// entries_; shuffleIndex_ is the cursor of the next shuffled pick.
|
||||
// Removing/moving/adding entries fixes the permutation up in place, so
|
||||
// already-played order is preserved.
|
||||
class QueueService
|
||||
{
|
||||
public:
|
||||
|
||||
using Entry = Api::QueueEntry;
|
||||
|
||||
// ---- mutation -------------------------------------------------
|
||||
|
||||
// Appends a track. Fails when the queue is at maxSize.
|
||||
Api::Result<uint64_t> enqueue(const Api::TrackInfo& track,
|
||||
std::string addedBy,
|
||||
std::size_t maxSize);
|
||||
|
||||
// Removes the entry at `position`; returns it for event payloads.
|
||||
Api::Result<Entry> removeAt(uint32_t position);
|
||||
|
||||
// Returns the number of entries removed.
|
||||
uint32_t clear();
|
||||
|
||||
// Moves an entry; returns its queueId for event payloads.
|
||||
Api::Result<uint64_t> move(uint32_t from, uint32_t to);
|
||||
|
||||
// Pops the next entry honouring shuffle order.
|
||||
std::optional<Entry> popNext();
|
||||
|
||||
// Pops the next entry only if it is still the given one — the
|
||||
// gapless engine peeks, warms a decoder, and commits at the swap;
|
||||
// queue edits in between invalidate the warm slot.
|
||||
std::optional<Entry> popIfNext(uint64_t queueId);
|
||||
|
||||
// Replace the whole queue (hot-reload restore).
|
||||
void replaceAll(std::vector<Entry> entries);
|
||||
|
||||
// In-place random shuffle of the raw order (legacy !shufflequeue).
|
||||
void shuffleInPlace();
|
||||
|
||||
// ---- shuffle / repeat -----------------------------------------
|
||||
|
||||
bool toggleShuffle();
|
||||
void setShuffle(bool enabled);
|
||||
[[nodiscard]] bool shuffleEnabled() const;
|
||||
|
||||
bool toggleRepeat();
|
||||
void setRepeat(bool enabled);
|
||||
[[nodiscard]] bool repeatEnabled() const;
|
||||
|
||||
// ---- inspection -----------------------------------------------
|
||||
|
||||
[[nodiscard]] std::optional<Entry> peekNext() const;
|
||||
[[nodiscard]] std::vector<Entry> snapshot() const;
|
||||
[[nodiscard]] std::size_t size() const;
|
||||
[[nodiscard]] bool empty() const;
|
||||
|
||||
// Allocate a queue id for entries created outside the queue (the
|
||||
// immediately-played track in play()).
|
||||
[[nodiscard]] uint64_t allocateQueueId();
|
||||
|
||||
private:
|
||||
|
||||
// All *Locked helpers assume mutex_ is held.
|
||||
void rebuildShuffledIndicesLocked();
|
||||
[[nodiscard]] std::optional<std::size_t> nextPositionLocked() const;
|
||||
std::optional<Entry> popNextLocked();
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::vector<Entry> entries_;
|
||||
std::vector<std::size_t> shuffledIndices_;
|
||||
std::size_t shuffleIndex_ = 0;
|
||||
uint64_t nextQueueId_ = 1;
|
||||
bool shuffle_ = false;
|
||||
bool repeat_ = false;
|
||||
std::mt19937 rng_{std::random_device{}()};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include "TrackSource.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Pass-through for URLs that already point at an audio stream (radio
|
||||
// streams, .mp3/.ogg/.opus/.m3u8 files, icecast mounts). No network work
|
||||
// at resolve time — ffmpeg opens the URL directly.
|
||||
class DirectUrlSource : public ITrackSource
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] std::string_view name() const override
|
||||
{
|
||||
return "direct-url";
|
||||
}
|
||||
[[nodiscard]] bool canHandle(const std::string& query) const override;
|
||||
[[nodiscard]] bool isAvailable() const override { return true; }
|
||||
[[nodiscard]] bool supportsSearch() const override
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult>
|
||||
search(std::string_view query) override;
|
||||
Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& urlOrId) override;
|
||||
Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track) override;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,86 @@
|
||||
#pragma once
|
||||
|
||||
#include "../NetworkClient.hpp"
|
||||
#include "../SignatureCipher.hpp"
|
||||
#include "TrackSource.hpp"
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Native YouTube resolution through the innertube player API — one HTTP
|
||||
// POST instead of a yt-dlp subprocess, so it is by far the fastest
|
||||
// YouTube path. Requests go through the configured proxy (NetworkClient
|
||||
// applies it); youtubei is ISP-blocked here, so with requireProxy=true
|
||||
// (default) the source reports unavailable when no proxy is set and the
|
||||
// router skips it.
|
||||
//
|
||||
// Client strategy: the IOS client historically returns direct
|
||||
// adaptiveFormats[].url with no signature deciphering. When it yields
|
||||
// nothing playable, the WEB client + SignatureCipher (quickjs solver)
|
||||
// deciphers signatureCipher/n-param challenges.
|
||||
class InnertubeSource : public ITrackSource
|
||||
{
|
||||
public:
|
||||
|
||||
// endpointOverride points tests at a StubHttpServer; production
|
||||
// passes nothing and talks to https://www.youtube.com.
|
||||
explicit InnertubeSource(std::shared_ptr<NetworkClient> network,
|
||||
std::string endpointOverride = "");
|
||||
|
||||
void configure(bool enabled, bool requireProxy);
|
||||
|
||||
[[nodiscard]] std::string_view name() const override
|
||||
{
|
||||
return "innertube";
|
||||
}
|
||||
[[nodiscard]] bool canHandle(const std::string& query) const override;
|
||||
[[nodiscard]] bool isAvailable() const override;
|
||||
[[nodiscard]] bool supportsSearch() const override
|
||||
{
|
||||
return false; // text search runs through the yt-dlp sources
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult>
|
||||
search(std::string_view query) override;
|
||||
Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& urlOrId) override;
|
||||
Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track) override;
|
||||
|
||||
private:
|
||||
|
||||
struct PlayerResponse {
|
||||
std::string title;
|
||||
std::string author;
|
||||
int64_t lengthSeconds = 0;
|
||||
std::string thumbnailUrl;
|
||||
std::string streamUrl; // direct url when present
|
||||
std::string signatureCipher; // needs deciphering
|
||||
};
|
||||
|
||||
// POST youtubei/v1/player with the given client context; parses
|
||||
// the best audio format out of the response.
|
||||
Api::Result<PlayerResponse> callPlayer(const std::string& videoId,
|
||||
bool webClient);
|
||||
|
||||
// WEB fallback: fetch the watch page + player JS, feed the
|
||||
// cipher, decipher the signatureCipher/n-param challenge.
|
||||
Api::Result<std::string>
|
||||
decipherWithWebPlayer(const std::string& videoId,
|
||||
const std::string& signatureCipher);
|
||||
|
||||
std::shared_ptr<NetworkClient> network_;
|
||||
std::string endpoint_;
|
||||
std::atomic<bool> enabled_{true};
|
||||
std::atomic<bool> requireProxy_{true};
|
||||
|
||||
// Lazy cipher state (only the WEB fallback needs it).
|
||||
std::mutex cipherMutex_;
|
||||
std::unique_ptr<SignatureCipher> cipher_;
|
||||
std::string loadedPlayerJsUrl_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,75 @@
|
||||
#pragma once
|
||||
|
||||
#include "TrackSource.hpp"
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Ordered chain of track sources with per-source failure cooldown and a
|
||||
// stream-URL cache. Resolution walks the configured order and takes the
|
||||
// first source that canHandle() the query, is available, and succeeds;
|
||||
// failures put a source on cooldown (skipped unless it is the last
|
||||
// candidate) and fall through to the next.
|
||||
class SourceRouter
|
||||
{
|
||||
public:
|
||||
|
||||
void setSources(std::vector<std::shared_ptr<ITrackSource>> sources);
|
||||
void addSource(std::shared_ptr<ITrackSource> source);
|
||||
|
||||
// Reorder/enable per config; names not found are ignored, sources
|
||||
// not named are dropped from the chain.
|
||||
void setOrder(const std::vector<std::string>& order);
|
||||
void setFailureCooldown(std::chrono::milliseconds cooldown);
|
||||
// Hedged getStream: when the first candidate hasn't answered
|
||||
// within this delay, race the second one (first success wins).
|
||||
// 0 disables hedging.
|
||||
void setHedgeDelay(std::chrono::milliseconds delay);
|
||||
|
||||
// Text search across the first searching source that succeeds.
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
search(std::string_view query);
|
||||
|
||||
// URL/id/text -> track metadata.
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& query);
|
||||
|
||||
// Track -> playable stream handle (cached).
|
||||
[[nodiscard]] Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track);
|
||||
|
||||
// A cached/served handle failed to open: evict it and demote the
|
||||
// producing source so the next resolve tries elsewhere.
|
||||
void invalidate(const std::string& trackId);
|
||||
|
||||
private:
|
||||
|
||||
struct CachedStream {
|
||||
StreamHandle handle;
|
||||
std::chrono::steady_clock::time_point expiry;
|
||||
};
|
||||
|
||||
struct SourceState {
|
||||
std::shared_ptr<ITrackSource> source;
|
||||
std::chrono::steady_clock::time_point cooldownUntil{};
|
||||
};
|
||||
|
||||
[[nodiscard]] std::vector<std::shared_ptr<ITrackSource>>
|
||||
candidatesFor(const std::string& query, bool needSearch);
|
||||
void reportFailure(const std::shared_ptr<ITrackSource>& source);
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::vector<std::shared_ptr<ITrackSource>> allSources_;
|
||||
std::vector<SourceState> chain_;
|
||||
std::chrono::milliseconds cooldown_{std::chrono::minutes(5)};
|
||||
std::chrono::milliseconds hedgeDelay_{std::chrono::milliseconds(300)};
|
||||
std::unordered_map<std::string, CachedStream> streamCache_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// A playable handle produced by a source: either an http(s) URL the
|
||||
// decoder can stream, or a local file path (downloaded audio) the caller
|
||||
// must delete after playback.
|
||||
struct StreamHandle {
|
||||
std::string url;
|
||||
bool isLocalFile = false;
|
||||
std::string sourceName; // for logging / failure attribution
|
||||
};
|
||||
|
||||
// One catalog/stream backend in the resolution chain. Implementations:
|
||||
// InnertubeSource (native YouTube player API), YandexMusicSource (native
|
||||
// Yandex Music), DirectUrlSource (raw audio URLs), YtDlpSource (direct
|
||||
// and proxied yt-dlp).
|
||||
class ITrackSource
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~ITrackSource() = default;
|
||||
|
||||
[[nodiscard]] virtual std::string_view name() const = 0;
|
||||
|
||||
// Can this source resolve the query at all? URLs are matched by
|
||||
// host/scheme; bare text search is handled only by
|
||||
// YouTube-catalog sources.
|
||||
[[nodiscard]] virtual bool
|
||||
canHandle(const std::string& query) const = 0;
|
||||
|
||||
// Health gate — sources with no healthy instances report false
|
||||
// and are skipped by the router.
|
||||
[[nodiscard]] virtual bool isAvailable() const = 0;
|
||||
|
||||
// Does this source implement text search?
|
||||
[[nodiscard]] virtual bool supportsSearch() const = 0;
|
||||
|
||||
virtual Api::Result<Api::SearchResult>
|
||||
search(std::string_view query) = 0;
|
||||
|
||||
// Resolve metadata for a URL or id this source canHandle().
|
||||
virtual Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& urlOrId) = 0;
|
||||
|
||||
// Produce a playable handle for a resolved track.
|
||||
virtual Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track) = 0;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,79 @@
|
||||
#pragma once
|
||||
|
||||
#include "../NetworkClient.hpp"
|
||||
#include "TrackSource.hpp"
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Native Yandex Music source (unofficial api.music.yandex.net). Full
|
||||
// tracks require a Yandex OAuth token (sources.yandexToken) from an
|
||||
// account with Plus; without one this source reports unavailable and
|
||||
// yandex URLs keep routing to ytdlp-direct.
|
||||
//
|
||||
// Yandex is reachable directly in this deployment's region and may
|
||||
// geo-block foreign proxy exits, so every request deliberately bypasses
|
||||
// the configured proxy (NetworkClient::getDirect).
|
||||
class YandexMusicSource : public ITrackSource
|
||||
{
|
||||
public:
|
||||
|
||||
// endpointOverride points tests at a StubHttpServer (it replaces
|
||||
// both the API base and the download-info hosts).
|
||||
explicit YandexMusicSource(std::shared_ptr<NetworkClient> network,
|
||||
std::string endpointOverride = "");
|
||||
|
||||
void configure(bool enabled, std::string token);
|
||||
|
||||
[[nodiscard]] std::string_view name() const override
|
||||
{
|
||||
return "yandex";
|
||||
}
|
||||
[[nodiscard]] bool canHandle(const std::string& query) const override;
|
||||
[[nodiscard]] bool isAvailable() const override;
|
||||
[[nodiscard]] bool supportsSearch() const override
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult>
|
||||
search(std::string_view query) override;
|
||||
Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& urlOrId) override;
|
||||
Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track) override;
|
||||
|
||||
// Album/playlist track listing for queue imports.
|
||||
[[nodiscard]] bool isCollectionUrl(const std::string& url) const;
|
||||
Api::Result<std::vector<Api::TrackInfo>>
|
||||
playlistTracks(const std::string& url);
|
||||
|
||||
// Related/similar tracks for radio autoplay. trackId is the bare
|
||||
// Yandex numeric id (no "yandex:" prefix).
|
||||
Api::Result<std::vector<Api::TrackInfo>>
|
||||
related(const std::string& trackId, size_t limit = 10);
|
||||
|
||||
// Extract the bare Yandex track id from a music.yandex.* URL, if it
|
||||
// is a single-track URL. Used to seed radio from history.
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
trackIdFromUrl(const std::string& url) const;
|
||||
|
||||
private:
|
||||
|
||||
Api::Result<std::string> apiGet(const std::string& path);
|
||||
[[nodiscard]] std::string tokenSnapshot() const;
|
||||
|
||||
std::shared_ptr<NetworkClient> network_;
|
||||
std::string endpoint_;
|
||||
std::atomic<bool> enabled_{true};
|
||||
mutable std::mutex tokenMutex_;
|
||||
std::string token_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
|
||||
#include "../YouTubeClient.hpp"
|
||||
#include "TrackSource.hpp"
|
||||
#include <memory>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// yt-dlp-backed source, in two router entries over the same
|
||||
// YouTubeClient:
|
||||
// - Direct ("ytdlp-direct", useProxy=false): non-YouTube extractor URLs
|
||||
// (SoundCloud, Bandcamp, VK, Yandex, radio pages) reachable without a
|
||||
// proxy. Never handles bare text search.
|
||||
// - Proxied ("ytdlp-proxied", useProxy=true): last-resort YouTube
|
||||
// resolution + text search through the configured proxy; also owns
|
||||
// the SOCKS5 download-to-file path.
|
||||
class YtDlpSource : public ITrackSource
|
||||
{
|
||||
public:
|
||||
|
||||
enum class Mode { Direct, Proxied };
|
||||
|
||||
YtDlpSource(std::shared_ptr<YouTubeClient> client, Mode mode,
|
||||
std::string tempDir);
|
||||
|
||||
[[nodiscard]] std::string_view name() const override
|
||||
{
|
||||
return mode_ == Mode::Direct ? "ytdlp-direct"
|
||||
: "ytdlp-proxied";
|
||||
}
|
||||
[[nodiscard]] bool canHandle(const std::string& query) const override;
|
||||
[[nodiscard]] bool isAvailable() const override;
|
||||
[[nodiscard]] bool supportsSearch() const override
|
||||
{
|
||||
return mode_ == Mode::Proxied;
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult>
|
||||
search(std::string_view query) override;
|
||||
Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& urlOrId) override;
|
||||
Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track) override;
|
||||
|
||||
// Force the download-to-file path on the next getStream (set by
|
||||
// the router's preferDownload retry).
|
||||
Api::Result<StreamHandle>
|
||||
getStreamViaDownload(const Api::TrackInfo& track);
|
||||
|
||||
private:
|
||||
|
||||
std::shared_ptr<YouTubeClient> client_;
|
||||
Mode mode_;
|
||||
std::string tempDir_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
#include "Types.hpp"
|
||||
#include "echoion/core/state/StateVersions.hpp"
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Handles migration between state versions
|
||||
class StateMigration
|
||||
{
|
||||
public:
|
||||
|
||||
// Migrate from any old version to current
|
||||
static Api::Result<StateV1> migrate(uint32_t fromVersion,
|
||||
const std::string& jsonData);
|
||||
|
||||
// Specific migrations
|
||||
static StateV1 fromV0(const StateV0& v0);
|
||||
|
||||
// Check if migration path exists
|
||||
static bool canMigrate(uint32_t fromVersion);
|
||||
|
||||
private:
|
||||
|
||||
// Migration chain: V0 -> V1 -> V2 -> ...
|
||||
// Each version only knows how to migrate from previous
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
#include "StateBlob.hpp"
|
||||
#include "echoion/core/state/StateVersions.hpp"
|
||||
#include <Types.hpp>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class StateSerializer
|
||||
{
|
||||
public:
|
||||
|
||||
// Current version being used
|
||||
static constexpr uint32_t CURRENT_VERSION = 1;
|
||||
|
||||
// Serialize current state to opaque blob
|
||||
static Api::StateBlob serialize(const StateV1& state);
|
||||
|
||||
// Deserialize blob to current version (handles migration)
|
||||
static Api::Result<StateV1> deserialize(const Api::StateBlob& blob);
|
||||
|
||||
// Check if version is supported
|
||||
static bool isVersionSupported(uint32_t version);
|
||||
|
||||
// Get supported version range
|
||||
static uint32_t getMinimumSupportedVersion();
|
||||
static uint32_t getCurrentVersion();
|
||||
|
||||
private:
|
||||
|
||||
// Extract version from JSON blob
|
||||
static uint32_t extractVersion(const std::string& jsonStr);
|
||||
|
||||
// Make it accessible to StateMigration
|
||||
friend class StateMigration;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,75 @@
|
||||
#pragma once
|
||||
#include "TrackTypes.hpp"
|
||||
#include "RpcTypes.hpp"
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
using namespace Echoion::Api;
|
||||
|
||||
// State V0 - Initial version (placeholder for testing migration)
|
||||
struct StateV0 {
|
||||
std::vector<std::string> trackIds;
|
||||
float volume = 0.5f;
|
||||
};
|
||||
|
||||
// State V1 - Current version with full playback state
|
||||
struct StateV1 {
|
||||
// Playback state
|
||||
struct PlaybackState {
|
||||
TrackInfo currentTrack;
|
||||
int64_t positionMs = 0; // Use int64 for JSON compatibility
|
||||
bool isPlaying = false;
|
||||
bool isPaused = false;
|
||||
float volume = 0.5f;
|
||||
bool shuffle = false;
|
||||
bool repeat = false;
|
||||
};
|
||||
|
||||
// Queue entry with metadata
|
||||
struct QueueEntryState {
|
||||
TrackInfo track;
|
||||
uint64_t queueId = 0;
|
||||
std::string addedBy;
|
||||
std::string addedAt; // ISO 8601
|
||||
};
|
||||
|
||||
// Session state for RPC clients
|
||||
struct SessionState {
|
||||
uint64_t clientId = 0;
|
||||
std::string authToken;
|
||||
std::string lastActivity; // ISO 8601
|
||||
};
|
||||
|
||||
struct ExtensionPluginState {
|
||||
std::string name;
|
||||
std::string json;
|
||||
std::uint32_t version = 0;
|
||||
};
|
||||
|
||||
// Main state
|
||||
PlaybackState playback;
|
||||
bool hasPlayback =
|
||||
false; // Flag to indicate if playback state is valid
|
||||
bool autoplay = false; // Radio mode on/off (persisted for restart)
|
||||
std::vector<QueueEntryState> queue;
|
||||
std::vector<SessionState> sessions;
|
||||
std::vector<ExtensionPluginState> extensionPlugins;
|
||||
|
||||
// Version info
|
||||
uint32_t version = 1;
|
||||
std::string savedAt; // ISO 8601
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
|
||||
// StateV0/StateV1 (and the nested PlaybackState/QueueEntryState/SessionState)
|
||||
// are plain reflectable aggregates whose member names are the desired JSON
|
||||
// keys, so Void::Json reflection serializes them with no annotations. The only
|
||||
// non-reflectable member is TrackInfo, which supplies its own
|
||||
// to_json()/from_json() in TrackTypes.hpp.
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core::Util
|
||||
{
|
||||
|
||||
// Split `text` into pages no larger than `limit` bytes each, breaking on
|
||||
// line boundaries where possible and hard-splitting over-long lines on a
|
||||
// UTF-8 code-point boundary. Every returned page is <= `limit` bytes, so a
|
||||
// caller can append a short footer and still stay under the transport's
|
||||
// single-message cap. Returns a single element when `text` already fits.
|
||||
std::vector<std::string> paginate(std::string_view text, std::size_t limit);
|
||||
|
||||
} // namespace Echoion::Core::Util
|
||||
+697
-618
File diff suppressed because it is too large.
Load diff
@@ -1,46 +0,0 @@
|
||||
#include "echoion/api/Cache.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
CacheManager& CacheManager::instance() {
|
||||
static CacheManager instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
void CacheManager::initialize() {
|
||||
ECHOION_LOG_INFO("CacheManager initialized");
|
||||
}
|
||||
|
||||
void CacheManager::shutdown() {
|
||||
clearAll();
|
||||
ECHOION_LOG_INFO("CacheManager shutdown");
|
||||
}
|
||||
|
||||
void CacheManager::purgeAllExpired() {
|
||||
size_t totalPurged = 0;
|
||||
totalPurged += httpCache_.purgeExpired();
|
||||
totalPurged += trackCache_.purgeExpired();
|
||||
totalPurged += metadataCache_.purgeExpired();
|
||||
|
||||
if (totalPurged > 0) {
|
||||
ECHOION_LOG_INFO(std::format("Purged {} expired cache entries", totalPurged));
|
||||
}
|
||||
}
|
||||
|
||||
void CacheManager::clearAll() {
|
||||
httpCache_.clear();
|
||||
trackCache_.clear();
|
||||
metadataCache_.clear();
|
||||
ECHOION_LOG_INFO("All caches cleared");
|
||||
}
|
||||
|
||||
std::unordered_map<std::string, CacheStats> CacheManager::getAllStats() const {
|
||||
return {
|
||||
{"http", httpCache_.getStats()},
|
||||
{"track", trackCache_.getStats()},
|
||||
{"metadata", metadataCache_.getStats()}
|
||||
};
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api
|
||||
+787
-237
File diff suppressed because it is too large.
Load diff
+320
-346
@@ -1,355 +1,329 @@
|
||||
#include "Types.hpp"
|
||||
#include "echoion/core/ConfigLoader.hpp"
|
||||
#include "echoion/api/AudioTypes.hpp"
|
||||
#include <glaze/glaze.hpp>
|
||||
#include <fstream>
|
||||
#include <AudioTypes.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <ranges>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Core {
|
||||
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;
|
||||
};
|
||||
void ConfigLoader::normalize(Api::AppConfig& config)
|
||||
{
|
||||
// yt-dlp concurrency is hard-capped regardless of what the file says.
|
||||
config.youtube.ytDlpMaxConcurrent =
|
||||
std::min(config.youtube.ytDlpMaxConcurrent, size_t(8));
|
||||
|
||||
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;
|
||||
};
|
||||
// Bot language: only "en"/"ru" are understood; anything else (including
|
||||
// an empty field) falls back to English so replies never break.
|
||||
if (config.bot.language != "en" && config.bot.language != "ru") {
|
||||
config.bot.language = "en";
|
||||
}
|
||||
|
||||
struct SecurityConfigJson {
|
||||
bool requireAuthForAdmin = true;
|
||||
uint32_t maxLoginAttempts = 5;
|
||||
uint32_t lockoutDuration = 300000;
|
||||
uint32_t sessionTimeout = 3600000;
|
||||
bool enableAuditLog = true;
|
||||
};
|
||||
const std::filesystem::path logFile{config.logging.fileName};
|
||||
if (config.logging.fileName.empty() || logFile.is_absolute() ||
|
||||
logFile.has_parent_path() || logFile.filename() != logFile ||
|
||||
logFile == "." || logFile == "..") {
|
||||
config.logging.fileName = "echoion.log";
|
||||
}
|
||||
config.logging.maxFileSizeBytes = std::clamp<uint64_t>(
|
||||
config.logging.maxFileSizeBytes, 64 * 1024, 1024ULL * 1024 * 1024);
|
||||
config.logging.maxFiles =
|
||||
std::clamp<uint32_t>(config.logging.maxFiles, 1, 1000);
|
||||
config.logging.queueCapacity =
|
||||
std::clamp<uint32_t>(config.logging.queueCapacity, 16, 1'000'000);
|
||||
static constexpr std::array<std::string_view, 8> kLogLevels = {
|
||||
"trace", "debug", "info", "warning",
|
||||
"warn", "error", "critical", "fatal"};
|
||||
if (std::ranges::find(kLogLevels, config.logging.level) ==
|
||||
kLogLevels.end()) {
|
||||
config.logging.level = "debug";
|
||||
}
|
||||
static constexpr std::array<std::string_view, 3> kLogFormats = {
|
||||
"pattern", "json", "logfmt"};
|
||||
if (std::ranges::find(kLogFormats, config.logging.format) ==
|
||||
kLogFormats.end()) {
|
||||
config.logging.format = "pattern";
|
||||
}
|
||||
if (config.logging.pattern.empty() ||
|
||||
config.logging.pattern.size() > 4096) {
|
||||
config.logging.pattern =
|
||||
"[{time}] [{level}] [{thread}] {file} - {message}";
|
||||
}
|
||||
static constexpr std::array<std::string_view, 3> kLogModes = {
|
||||
"async", "immediate", "buffered"};
|
||||
if (std::ranges::find(kLogModes, config.logging.mode) ==
|
||||
kLogModes.end()) {
|
||||
config.logging.mode = "async";
|
||||
}
|
||||
static constexpr std::array<std::string_view, 3> kOverflowPolicies = {
|
||||
"block", "drop-newest", "drop-oldest"};
|
||||
if (std::ranges::find(kOverflowPolicies,
|
||||
config.logging.overflowPolicy) ==
|
||||
kOverflowPolicies.end()) {
|
||||
config.logging.overflowPolicy = "block";
|
||||
}
|
||||
|
||||
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";
|
||||
}
|
||||
}
|
||||
config.licensing.refreshInterval =
|
||||
std::clamp(config.licensing.refreshInterval,
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::minutes(15)),
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::hours(12)));
|
||||
config.licensing.retryInterval =
|
||||
std::clamp(config.licensing.retryInterval,
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::seconds(30)),
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::hours(1)));
|
||||
config.licensing.maximumLeaseLifetime =
|
||||
std::clamp(config.licensing.maximumLeaseLifetime,
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::hours(1)),
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::hours(24)));
|
||||
if (config.licensing.productId.empty() ||
|
||||
config.licensing.productId.size() > 128) {
|
||||
config.licensing.productId = "echoion";
|
||||
}
|
||||
if (config.licensing.activationTokenEnv.empty() ||
|
||||
config.licensing.activationTokenEnv.size() > 128) {
|
||||
config.licensing.activationTokenEnv = "ECHOION_LICENSE_TOKEN";
|
||||
}
|
||||
if (!config.licensing.serviceUrl.empty() &&
|
||||
!config.licensing.serviceUrl.starts_with("https://")) {
|
||||
config.licensing.serviceUrl.clear();
|
||||
}
|
||||
|
||||
// Keep partially specified updater sections usable. Security-sensitive
|
||||
// URL/key validation happens in the host updater before the policy is
|
||||
// persisted or used; normalization here only supplies structural
|
||||
// defaults for older configuration files.
|
||||
if (!config.updates.sources.contains("official")) {
|
||||
config.updates.sources.emplace("official",
|
||||
Api::UpdateSourceConfig{});
|
||||
}
|
||||
auto normalizeComponent = [](Api::UpdateComponentConfig& component) {
|
||||
if (component.source.empty()) {
|
||||
component.source = "official";
|
||||
}
|
||||
if (component.channel.empty()) {
|
||||
component.channel = "stable";
|
||||
}
|
||||
};
|
||||
normalizeComponent(config.updates.runtime);
|
||||
normalizeComponent(config.updates.core);
|
||||
if (config.updates.plugins.source.empty()) {
|
||||
config.updates.plugins.source = "official";
|
||||
}
|
||||
if (config.updates.plugins.channel.empty()) {
|
||||
config.updates.plugins.channel = "stable";
|
||||
}
|
||||
|
||||
if (config.urlShortening.provider.empty()) {
|
||||
config.urlShortening.provider = "url-shortener-internal";
|
||||
}
|
||||
if (config.urlShortening.enabled &&
|
||||
config.urlShortening.provider == "url-shortener-internal" &&
|
||||
config.web.publicUrl.empty()) {
|
||||
config.urlShortening.enabled = false;
|
||||
Void::Log::warn(
|
||||
"ConfigLoader", "{}",
|
||||
"Internal URL shortening was disabled because web.publicUrl is "
|
||||
"empty; configure the bot's public URL before enabling "
|
||||
"url-shortener-internal");
|
||||
}
|
||||
config.urlShortening.timeout = std::clamp(
|
||||
config.urlShortening.timeout, std::chrono::milliseconds(100),
|
||||
std::chrono::milliseconds(30000));
|
||||
const auto validSource = [](std::string_view source) {
|
||||
static constexpr std::array<std::string_view, 6> kSources = {
|
||||
"youtube", "yandex", "url", "soundcloud", "spotify", "plugin"};
|
||||
return std::ranges::find(kSources, source) != kSources.end();
|
||||
};
|
||||
std::erase_if(
|
||||
config.urlShortening.sources,
|
||||
[&](const std::string& source) { return !validSource(source); });
|
||||
std::ranges::sort(config.urlShortening.sources);
|
||||
auto unique = std::ranges::unique(config.urlShortening.sources);
|
||||
config.urlShortening.sources.erase(unique.begin(), unique.end());
|
||||
}
|
||||
|
||||
Api::Result<Api::AppConfig>
|
||||
ConfigLoader::loadFromFile(const std::filesystem::path& path)
|
||||
{
|
||||
if (!std::filesystem::exists(path)) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::NotFound,
|
||||
std::format("Configuration file not found: {}", path.string()));
|
||||
}
|
||||
|
||||
std::ifstream file(path);
|
||||
if (!file.is_open()) {
|
||||
return Api::fail(
|
||||
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();
|
||||
|
||||
auto config = loadFromJson(content);
|
||||
if (!config) {
|
||||
return std::unexpected(config.error());
|
||||
}
|
||||
|
||||
std::cout << std::format("[INFO] Configuration loaded from {}",
|
||||
path.string())
|
||||
<< '\n';
|
||||
return config;
|
||||
}
|
||||
|
||||
Api::Result<Api::AppConfig>
|
||||
ConfigLoader::loadFromJson(std::string_view json)
|
||||
{
|
||||
auto parsed = Void::Json::parse(json);
|
||||
if (!parsed) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::ParseError,
|
||||
std::format("Failed to parse configuration ({}:{}): {}",
|
||||
parsed.error().line, parsed.error().col,
|
||||
parsed.error().message));
|
||||
}
|
||||
|
||||
// Deserialize Api::AppConfig directly via reflection: unknown keys are
|
||||
// ignored and absent fields keep their defaults. Durations are duration
|
||||
// strings ("30000ms"), enums are names, the proxy is a nested object.
|
||||
auto result = Void::Json::from_json<Api::AppConfig>(*parsed);
|
||||
if (!result) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::ParseError,
|
||||
std::format("Failed to parse configuration: field '{}': {}",
|
||||
result.error().field, result.error().message));
|
||||
}
|
||||
|
||||
Api::AppConfig config = std::move(*result);
|
||||
// Legacy files only had youtube.enableUrlShortening. An explicitly
|
||||
// present new section always wins, including enabled=false.
|
||||
if (parsed->find("urlShortening") == nullptr) {
|
||||
config.urlShortening.enabled = config.youtube.enableUrlShortening;
|
||||
config.urlShortening.provider = "url-shortener-internal";
|
||||
config.urlShortening.sources = {"youtube"};
|
||||
}
|
||||
normalize(config);
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
Api::Result<void>
|
||||
ConfigLoader::saveToFile(const std::filesystem::path& path,
|
||||
const Api::AppConfig& config)
|
||||
{
|
||||
const std::string json = Void::Json::serialize(
|
||||
Void::Json::to_json(config), {.pretty = true});
|
||||
std::ofstream file(path);
|
||||
if (!file.is_open()) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied,
|
||||
std::format("Failed to write configuration file: {}",
|
||||
path.string()));
|
||||
}
|
||||
|
||||
file << json;
|
||||
file.close();
|
||||
|
||||
Void::Log::info(
|
||||
"ConfigLoader", "{}",
|
||||
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.maxQueueSize = 100;
|
||||
config.bot.trackTimeout = std::chrono::milliseconds(10000);
|
||||
config.bot.allowPlaylistImports = true;
|
||||
|
||||
// Default YouTube config
|
||||
config.youtube.ytDlpMaxConcurrent = 4;
|
||||
config.youtube.ytDlpAsyncEnabled = true;
|
||||
config.youtube.enableUrlShortening = true;
|
||||
config.urlShortening.enabled = false;
|
||||
config.urlShortening.provider = "url-shortener-internal";
|
||||
config.urlShortening.sources = {"youtube"};
|
||||
config.urlShortening.timeout = std::chrono::milliseconds(3000);
|
||||
|
||||
// Default network config
|
||||
config.network.rpcEnabled = true;
|
||||
config.network.rpcPort = 8765;
|
||||
config.network.rpcBindAddress = "127.0.0.1";
|
||||
|
||||
// Default TeamSpeak config
|
||||
config.teamspeak.address = "localhost";
|
||||
config.teamspeak.port = 9987;
|
||||
config.teamspeak.nickname = "EchoionBot";
|
||||
|
||||
// Default security config
|
||||
config.security.requireAuthForAdmin = true;
|
||||
config.security.maxLoginAttempts = 5;
|
||||
config.security.lockoutDuration = std::chrono::milliseconds(300000);
|
||||
config.security.sessionTimeout = std::chrono::milliseconds(3600000);
|
||||
config.security.enableAuditLog = true;
|
||||
config.security.allowCors = false;
|
||||
|
||||
// Default features config
|
||||
config.features.enableHotReload = true;
|
||||
config.features.enableAutoReload = false;
|
||||
config.features.enableAutoUpdateCheck = true;
|
||||
config.features.autoStartOnSubscribe = true;
|
||||
config.features.pauseOnEmptySubscribers = true;
|
||||
config.features.resumeOnSubscriberReturn = true;
|
||||
config.features.shuffleMode = "off";
|
||||
config.features.repeatMode = "off";
|
||||
config.features.maxHistorySize = 50;
|
||||
|
||||
// Default advanced config
|
||||
config.advanced.cacheEnabled = true;
|
||||
config.advanced.cacheMaxSize = "1GB";
|
||||
config.advanced.cacheTTL = 86400;
|
||||
config.advanced.tempCleanupInterval = 3600;
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,181 @@
|
||||
#include "ConfigManager.hpp"
|
||||
#include "echoion/core/ConfigLoader.hpp"
|
||||
#include <format>
|
||||
#include <iostream>
|
||||
#include <tuple>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
bool ConfigManager::initialize(const std::filesystem::path& configPath)
|
||||
{
|
||||
std::unique_lock lock(mutex_);
|
||||
configPath_ = configPath;
|
||||
bool success = loadFromFileInternal();
|
||||
initialized_.store(success);
|
||||
return success;
|
||||
}
|
||||
|
||||
bool ConfigManager::initialize()
|
||||
{
|
||||
return initialize(getDefaultConfigPath());
|
||||
}
|
||||
|
||||
AppConfig ConfigManager::getConfig() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_;
|
||||
}
|
||||
|
||||
const BotConfig& ConfigManager::getBot() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.bot;
|
||||
}
|
||||
|
||||
const YouTubeConfig& ConfigManager::getYouTube() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.youtube;
|
||||
}
|
||||
|
||||
const NetworkConfig& ConfigManager::getNetwork() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.network;
|
||||
}
|
||||
|
||||
const SourcesConfig& ConfigManager::getSources() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.sources;
|
||||
}
|
||||
|
||||
const TeamSpeakConfig& ConfigManager::getTeamSpeak() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.teamspeak;
|
||||
}
|
||||
|
||||
const SecurityConfig& ConfigManager::getSecurity() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.security;
|
||||
}
|
||||
|
||||
const FeaturesConfig& ConfigManager::getFeatures() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.features;
|
||||
}
|
||||
|
||||
const AdvancedConfig& ConfigManager::getAdvanced() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.advanced;
|
||||
}
|
||||
|
||||
bool ConfigManager::reload()
|
||||
{
|
||||
std::unique_lock lock(mutex_);
|
||||
return loadFromFileInternal();
|
||||
}
|
||||
|
||||
bool ConfigManager::save()
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return saveToFileInternal();
|
||||
}
|
||||
|
||||
void ConfigManager::updateConfig(const AppConfig& config, bool saveToFile)
|
||||
{
|
||||
{
|
||||
std::unique_lock lock(mutex_);
|
||||
config_ = config;
|
||||
}
|
||||
|
||||
if (saveToFile) {
|
||||
// save() already reports failures (saveToFileInternal); the
|
||||
// in-memory update stands either way.
|
||||
std::ignore = save();
|
||||
}
|
||||
|
||||
notifyCallbacks();
|
||||
}
|
||||
|
||||
bool ConfigManager::isInitialized() const { return initialized_.load(); }
|
||||
|
||||
std::filesystem::path ConfigManager::getConfigPath() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return configPath_;
|
||||
}
|
||||
|
||||
std::filesystem::path ConfigManager::getDefaultConfigPath()
|
||||
{
|
||||
const char* configHome = std::getenv("XDG_CONFIG_HOME");
|
||||
if (configHome) {
|
||||
return std::filesystem::path(configHome) / "echoion" /
|
||||
"config.json";
|
||||
}
|
||||
|
||||
const char* home = std::getenv("HOME");
|
||||
if (home) {
|
||||
return std::filesystem::path(home) / ".config" / "echoion" /
|
||||
"config.json";
|
||||
}
|
||||
|
||||
return "echoion_config.json";
|
||||
}
|
||||
|
||||
void ConfigManager::onConfigChanged(ConfigChangedCallback callback)
|
||||
{
|
||||
std::unique_lock lock(callbackMutex_);
|
||||
callbacks_.push_back(std::move(callback));
|
||||
}
|
||||
|
||||
bool ConfigManager::createDefaultConfigIfNeeded()
|
||||
{
|
||||
if (!std::filesystem::exists(configPath_)) {
|
||||
std::filesystem::create_directories(configPath_.parent_path());
|
||||
return save();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void ConfigManager::notifyCallbacks()
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
std::shared_lock cbLock(callbackMutex_);
|
||||
|
||||
for (const auto& callback : callbacks_) {
|
||||
callback(config_);
|
||||
}
|
||||
}
|
||||
|
||||
bool ConfigManager::loadFromFileInternal()
|
||||
{
|
||||
// Delegate to Core::ConfigLoader, which performs the JSON <-> AppConfig
|
||||
// mapping (via the *Json mirror structs and Void::Json reflection).
|
||||
auto result = Core::ConfigLoader::loadFromFile(configPath_);
|
||||
if (!result) {
|
||||
std::cerr << std::format("Failed to load config: {}\n",
|
||||
result.error().toString());
|
||||
return false;
|
||||
}
|
||||
config_ = std::move(*result);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ConfigManager::saveToFileInternal()
|
||||
{
|
||||
auto result = Core::ConfigLoader::saveToFile(configPath_, config_);
|
||||
if (!result) {
|
||||
std::cerr << std::format("Failed to save config: {}\n",
|
||||
result.error().toString());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api
|
||||
+2507
-898
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,301 @@
|
||||
#include "echoion/core/Core.hpp"
|
||||
#include "echoion/core/RpcDtos.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <Events.hpp>
|
||||
#include <RpcTypes.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
void Core::setupEventBusSubscriptions() noexcept
|
||||
{
|
||||
using namespace Api::Events;
|
||||
|
||||
// Subscribe to playback events for RPC broadcasting and database
|
||||
// persistence
|
||||
eventBus_.subscribe<PlaybackStarted>(
|
||||
[this](const PlaybackStarted& evt) mutable {
|
||||
// Broadcast to RPC/WebSocket clients
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.started",
|
||||
toJson(Dto::PlaybackStarted{
|
||||
.track = {.id = evt.track.id,
|
||||
.title = evt.track.title,
|
||||
.artist = evt.track.artist},
|
||||
.position = evt.position.count()}));
|
||||
}
|
||||
|
||||
// Record playback start in database
|
||||
if (database_) {
|
||||
if (auto result = database_->recordPlayback(
|
||||
evt.track, evt.clientId,
|
||||
std::chrono::milliseconds(0), false);
|
||||
!result) {
|
||||
Void::Log::warn(
|
||||
"Core", "{}",
|
||||
std::format("Failed to record playback start: {}",
|
||||
result.error().message));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<PlaybackPaused>(
|
||||
[this](const PlaybackPaused& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.paused",
|
||||
toJson(Dto::Position{.position = evt.position.count()}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<PlaybackResumed>(
|
||||
[this](const PlaybackResumed& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.resumed",
|
||||
toJson(Dto::Position{.position = evt.position.count()}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<PlaybackStopped>(
|
||||
[this](const PlaybackStopped&) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent("playback.stopped", "{}");
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<PlaybackPositionChanged>(
|
||||
[this](const PlaybackPositionChanged& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.position",
|
||||
toJson(Dto::PositionProgress{
|
||||
.position = evt.position.count(),
|
||||
.duration = evt.duration.count(),
|
||||
.progress = evt.progressPercent}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<TrackFinished>(
|
||||
[this](const TrackFinished& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent("playback.finished", "{}");
|
||||
}
|
||||
|
||||
// Update playback record as completed, keeping the history
|
||||
// bounded per features.maxHistorySize.
|
||||
if (database_) {
|
||||
if (auto result = database_->recordPlayback(
|
||||
evt.track, 0, evt.finalPosition, true);
|
||||
!result) {
|
||||
Void::Log::warn(
|
||||
"Core", "{}",
|
||||
std::format("Failed to record playback: {}",
|
||||
result.error().message));
|
||||
}
|
||||
if (auto result = database_->trimHistory(
|
||||
config_.features.maxHistorySize);
|
||||
!result) {
|
||||
Void::Log::warn(
|
||||
"Core", "{}",
|
||||
std::format("Failed to trim history: {}",
|
||||
result.error().message));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Volume and playback mode changes
|
||||
eventBus_.subscribe<VolumeChanged>(
|
||||
[this](const VolumeChanged& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.volumeChanged",
|
||||
toJson(Dto::Volume{.volume = evt.newVolume}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<ShuffleChanged>(
|
||||
[this](const ShuffleChanged& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.shuffleChanged",
|
||||
toJson(Dto::Shuffle{.shuffle = evt.enabled}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<RepeatChanged>(
|
||||
[this](const RepeatChanged& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.repeatChanged",
|
||||
toJson(Dto::Repeat{.repeat = evt.enabled}));
|
||||
}
|
||||
});
|
||||
|
||||
// Queue events
|
||||
eventBus_.subscribe<TrackQueued>(
|
||||
[this](const TrackQueued& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"queue.trackAdded",
|
||||
toJson(Dto::TrackQueued{
|
||||
.queueId = evt.queueId,
|
||||
.title = evt.track.title,
|
||||
.artist = evt.track.artist,
|
||||
.position = evt.position,
|
||||
.queueLength = evt.queueLength}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<TrackRemoved>(
|
||||
[this](const TrackRemoved& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"queue.trackRemoved",
|
||||
toJson(Dto::TrackRemoved{
|
||||
.queueId = evt.queueId,
|
||||
.queueLength = evt.queueLength}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<QueueCleared>(
|
||||
[this](const QueueCleared&) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent("queue.cleared", "{}");
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<QueueReordered>(
|
||||
[this](const QueueReordered& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"queue.reordered",
|
||||
toJson(Dto::QueueReordered{
|
||||
.queueId = evt.queueId,
|
||||
.oldPosition = evt.oldPosition,
|
||||
.newPosition = evt.newPosition}));
|
||||
}
|
||||
});
|
||||
|
||||
// Playlist events - save to database via event bus using external ID
|
||||
eventBus_.subscribe<PlaylistLoadStarted>(
|
||||
[this](const PlaylistLoadStarted& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playlist.loadStarted",
|
||||
toJson(Dto::PlaylistId{.playlistId = evt.playlistId}));
|
||||
}
|
||||
|
||||
if (database_) {
|
||||
auto result = database_->getOrCreatePlaylistByExternalId(
|
||||
evt.playlistId, evt.playlistId, "Loaded from YouTube",
|
||||
evt.requestedByClientId, true);
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<PlaylistTrackLoaded>(
|
||||
[this](const PlaylistTrackLoaded& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playlist.trackLoaded",
|
||||
toJson(Dto::PlaylistTrackLoaded{
|
||||
.playlistId = evt.playlistId,
|
||||
.loaded = evt.loadedCount,
|
||||
.total = evt.totalCount}));
|
||||
}
|
||||
|
||||
// Add track to playlist in database - lookup by external ID
|
||||
if (database_) {
|
||||
auto result = database_->getOrCreatePlaylistByExternalId(
|
||||
evt.playlistId, evt.playlistId, "Loaded from YouTube",
|
||||
0, true);
|
||||
if (result) {
|
||||
if (auto added = database_->addTrackToPlaylist(
|
||||
result.value(), evt.track,
|
||||
evt.loadedCount - 1);
|
||||
!added) {
|
||||
Void::Log::warn(
|
||||
"Core", "{}",
|
||||
std::format(
|
||||
"Failed to add track to playlist: {}",
|
||||
added.error().message));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<PlaylistLoadCompleted>(
|
||||
[this](const PlaylistLoadCompleted& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playlist.loadCompleted",
|
||||
toJson(Dto::PlaylistLoadCompleted{
|
||||
.playlistId = evt.playlistId,
|
||||
.totalTracks = evt.totalTracksLoaded,
|
||||
.success = evt.success}));
|
||||
}
|
||||
});
|
||||
|
||||
// Subscription events
|
||||
eventBus_.subscribe<UserSubscribed>(
|
||||
[this](const UserSubscribed& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"subscription.subscribed",
|
||||
toJson(Dto::User{.uid = evt.uid,
|
||||
.nickname = evt.nickname}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<UserUnsubscribed>(
|
||||
[this](const UserUnsubscribed& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"subscription.unsubscribed",
|
||||
toJson(Dto::User{.uid = evt.uid,
|
||||
.nickname = evt.nickname}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<QueueShuffled>(
|
||||
[this](const QueueShuffled&) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent("queue.shuffled", "{}");
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<PlaybackError>(
|
||||
[this](const PlaybackError& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
// Build via the JSON model: the error message may
|
||||
// contain quotes/newlines that must be escaped.
|
||||
Void::Json::Value payload = Void::Json::object();
|
||||
auto& obj = payload.as_object();
|
||||
obj.emplace_back("message",
|
||||
Void::Json::Value{evt.message});
|
||||
obj.emplace_back(
|
||||
"track", evt.track
|
||||
? Void::Json::Value{evt.track->title}
|
||||
: Void::Json::Value{nullptr});
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.error", Void::Json::serialize(payload, {}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<ConfigReloaded>(
|
||||
[this](const ConfigReloaded&) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent("config.reloaded", "{}");
|
||||
}
|
||||
});
|
||||
|
||||
Void::Log::info("Core", "{}", "EventBus subscriptions set up");
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
File diff suppressed because it is too large.
Load diff
+1603
-578
File diff suppressed because it is too large.
Load diff
@@ -1,185 +0,0 @@
|
||||
#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
|
||||
+167
-14
@@ -1,23 +1,176 @@
|
||||
#include "echoion/api/Export.hpp"
|
||||
#include <Export.hpp>
|
||||
#include "echoion/core/Core.hpp"
|
||||
#include <Void/Plugin/Plugin.hpp>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace Echoion::Api {
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
CoreInterfacePtr CreateCore() {
|
||||
return std::make_shared<Core::Core>();
|
||||
}
|
||||
CoreInterfacePtr CreateCore() { return std::make_shared<Core::Core>(); }
|
||||
|
||||
void DestroyCore(ICoreInterface* core) {
|
||||
delete core;
|
||||
}
|
||||
void DestroyCore(ICoreInterface* core) { delete core; }
|
||||
|
||||
const char* GetApiVersion() {
|
||||
return VERSION_STRING;
|
||||
}
|
||||
const char* GetApiVersion() { return VERSION_STRING; }
|
||||
|
||||
bool IsApiCompatible(uint32_t major, uint32_t minor) {
|
||||
return major == VERSION_MAJOR && minor <= VERSION_MINOR;
|
||||
}
|
||||
bool IsApiCompatible(uint32_t major, uint32_t minor)
|
||||
{
|
||||
return major == VERSION_MAJOR && minor <= VERSION_MINOR;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
// Adapter that makes Core loadable through Void::Plugin. It IS-A
|
||||
// Void::Plugin::IPlugin (the type the loader manages) and IS-A Core (hence
|
||||
// Api::ICoreInterface), so the host recovers the bot interface by
|
||||
// dynamic_cast-ing the IPlugin* back to Api::ICoreInterface*.
|
||||
class CorePlugin final : public Void::Plugin::IPlugin, public Core
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] std::string_view name() const noexcept override
|
||||
{
|
||||
return "Echoion";
|
||||
}
|
||||
|
||||
void configure(std::filesystem::path path)
|
||||
{
|
||||
configPath_ = std::move(path);
|
||||
}
|
||||
|
||||
void stageState(std::string state)
|
||||
{
|
||||
pendingState_ = std::move(state);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool ready() const noexcept { return ready_; }
|
||||
|
||||
// Configuration and state are supplied before on_load(). Keep all
|
||||
// fallible activation work here so void_plugin_ready can make the
|
||||
// manager's eventual swap transactional.
|
||||
void on_load() override
|
||||
{
|
||||
ready_ = false;
|
||||
const auto path = configPath_.empty()
|
||||
? ConfigLoader::getDefaultConfigPath()
|
||||
: configPath_;
|
||||
if (auto result = initialize(path); !result) {
|
||||
return;
|
||||
}
|
||||
if (pendingState_.has_value()) {
|
||||
if (auto result = restoreAfterHotReload(*pendingState_); !result) {
|
||||
(void)shutdown();
|
||||
return;
|
||||
}
|
||||
pendingState_.reset();
|
||||
}
|
||||
ready_ = true;
|
||||
}
|
||||
|
||||
void on_unload() override
|
||||
{
|
||||
ready_ = false;
|
||||
if (isInitialized()) {
|
||||
(void)shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::filesystem::path configPath_;
|
||||
std::optional<std::string> pendingState_;
|
||||
bool ready_{false};
|
||||
};
|
||||
} // namespace Echoion::Core
|
||||
|
||||
// ── Void::Plugin C ABI ──────────────────────────────────────────────────────
|
||||
// Exposes Core as a Void plugin with the v2 state protocol (serialize/
|
||||
// deserialize via the already-Void::Json hot-reload path). The legacy
|
||||
// CreateCore/DestroyCore exports above remain for the current dylib CoreLoader;
|
||||
// these are additive and let the host migrate to Void::Plugin::PluginManager.
|
||||
//
|
||||
// NOTE: the live hot-reload + state-survival behaviour is only exercised
|
||||
// against a running TeamSpeak host — compile-verified here, runtime-gated there.
|
||||
extern "C"
|
||||
{
|
||||
void* void_plugin_create()
|
||||
{
|
||||
return static_cast<Void::Plugin::IPlugin*>(
|
||||
new Echoion::Core::CorePlugin());
|
||||
}
|
||||
|
||||
void void_plugin_destroy(void* instance)
|
||||
{
|
||||
delete static_cast<Void::Plugin::IPlugin*>(instance);
|
||||
}
|
||||
|
||||
Void::Plugin::PluginInfo void_plugin_info()
|
||||
{
|
||||
return Void::Plugin::PluginInfo{
|
||||
.abi_version = Void::Plugin::ABI_VERSION,
|
||||
.name = "Echoion",
|
||||
.plugin_version = ECHOION_CORE_VERSION,
|
||||
.description = "Echoion TeamSpeak music bot core"};
|
||||
}
|
||||
|
||||
void void_plugin_configure(void* instance, const char* config)
|
||||
{
|
||||
auto* plugin = dynamic_cast<Echoion::Core::CorePlugin*>(
|
||||
static_cast<Void::Plugin::IPlugin*>(instance));
|
||||
if (plugin != nullptr) {
|
||||
plugin->configure(config != nullptr ? std::filesystem::path{config}
|
||||
: std::filesystem::path{});
|
||||
}
|
||||
}
|
||||
|
||||
int void_plugin_ready(void* instance)
|
||||
{
|
||||
auto* plugin = dynamic_cast<Echoion::Core::CorePlugin*>(
|
||||
static_cast<Void::Plugin::IPlugin*>(instance));
|
||||
return plugin != nullptr && plugin->ready() ? 0 : -1;
|
||||
}
|
||||
|
||||
// v2 state protocol — survives layout changes across plugin versions.
|
||||
std::uint32_t void_plugin_state_version()
|
||||
{
|
||||
return 1; // matches StateSerializer::CURRENT_VERSION
|
||||
}
|
||||
|
||||
const char* void_plugin_serialize_state(void* instance)
|
||||
{
|
||||
auto* core = dynamic_cast<Echoion::Api::ICoreInterface*>(
|
||||
static_cast<Void::Plugin::IPlugin*>(instance));
|
||||
if (!core) {
|
||||
return nullptr;
|
||||
}
|
||||
auto state = core->prepareForHotReload();
|
||||
if (!state) {
|
||||
return nullptr;
|
||||
}
|
||||
// Heap copy owned by this .so; released via void_plugin_free_string.
|
||||
return strdup(state->c_str());
|
||||
}
|
||||
|
||||
void void_plugin_free_string(const char* s)
|
||||
{
|
||||
std::free(const_cast<char*>(s));
|
||||
}
|
||||
|
||||
int void_plugin_deserialize_state(void* instance, const char* json,
|
||||
std::uint32_t /*from_version*/)
|
||||
{
|
||||
auto* plugin = dynamic_cast<Echoion::Core::CorePlugin*>(
|
||||
static_cast<Void::Plugin::IPlugin*>(instance));
|
||||
if (!plugin || !json) {
|
||||
return -1;
|
||||
}
|
||||
plugin->stageState(json);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
#include "echoion/core/LogRotation.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
#include <format>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] std::string archiveTimestamp()
|
||||
{
|
||||
using namespace std::chrono;
|
||||
const auto now = system_clock::now();
|
||||
const auto secondsPart = floor<seconds>(now);
|
||||
const auto micros = duration_cast<microseconds>(now - secondsPart);
|
||||
const std::time_t raw = system_clock::to_time_t(now);
|
||||
std::tm utc{};
|
||||
#ifdef _WIN32
|
||||
gmtime_s(&utc, &raw);
|
||||
#else
|
||||
gmtime_r(&raw, &utc);
|
||||
#endif
|
||||
return std::format("{:04}{:02}{:02}-{:02}{:02}{:02}-{:06}",
|
||||
utc.tm_year + 1900, utc.tm_mon + 1, utc.tm_mday,
|
||||
utc.tm_hour, utc.tm_min, utc.tm_sec,
|
||||
micros.count());
|
||||
}
|
||||
|
||||
[[nodiscard]] bool isArchiveFor(const std::filesystem::path& path,
|
||||
const std::filesystem::path& active)
|
||||
{
|
||||
const auto name = path.filename().string();
|
||||
const auto prefix = active.stem().string() + "-";
|
||||
return name.starts_with(prefix) &&
|
||||
path.extension() == active.extension();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::error_code rotateLogOnStartup(const std::filesystem::path& activeLog,
|
||||
std::size_t maxFiles) noexcept
|
||||
{
|
||||
std::error_code error;
|
||||
const auto status = std::filesystem::symlink_status(activeLog, error);
|
||||
if (error && error != std::errc::no_such_file_or_directory) {
|
||||
return error;
|
||||
}
|
||||
error.clear();
|
||||
|
||||
const bool exists = std::filesystem::exists(status);
|
||||
if (exists && std::filesystem::is_symlink(status)) {
|
||||
return std::make_error_code(
|
||||
std::errc::too_many_symbolic_link_levels);
|
||||
}
|
||||
|
||||
const auto history = activeLog.parent_path() / "history";
|
||||
std::filesystem::create_directories(activeLog.parent_path(), error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
if (exists) {
|
||||
if (!std::filesystem::is_regular_file(status)) {
|
||||
return std::make_error_code(std::errc::invalid_argument);
|
||||
}
|
||||
const auto size = std::filesystem::file_size(activeLog, error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
if (size == 0 || maxFiles == 0) {
|
||||
std::filesystem::remove(activeLog, error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
} else {
|
||||
std::filesystem::create_directories(history, error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
const auto timestamp = archiveTimestamp();
|
||||
auto archived = history / (activeLog.stem().string() + "-" +
|
||||
timestamp +
|
||||
activeLog.extension().string());
|
||||
for (std::size_t suffix = 1;
|
||||
std::filesystem::exists(archived, error) && !error;
|
||||
++suffix) {
|
||||
archived = history / (activeLog.stem().string() + "-" +
|
||||
timestamp + "-" +
|
||||
std::to_string(suffix) +
|
||||
activeLog.extension().string());
|
||||
}
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
std::filesystem::rename(activeLog, archived, error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const auto historyStatus =
|
||||
std::filesystem::symlink_status(history, error);
|
||||
if (error == std::errc::no_such_file_or_directory ||
|
||||
historyStatus.type() == std::filesystem::file_type::not_found) {
|
||||
return {};
|
||||
}
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
if (!std::filesystem::is_directory(historyStatus) ||
|
||||
std::filesystem::is_symlink(historyStatus)) {
|
||||
return std::make_error_code(std::errc::invalid_argument);
|
||||
}
|
||||
std::vector<std::filesystem::path> archives;
|
||||
for (std::filesystem::directory_iterator iterator(history, error), end;
|
||||
!error && iterator != end; iterator.increment(error)) {
|
||||
const auto entryStatus = iterator->symlink_status(error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
if (std::filesystem::is_regular_file(entryStatus) &&
|
||||
isArchiveFor(iterator->path(), activeLog)) {
|
||||
archives.push_back(iterator->path());
|
||||
}
|
||||
}
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
std::ranges::sort(archives);
|
||||
while (archives.size() > maxFiles) {
|
||||
std::filesystem::remove(archives.front(), error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
archives.erase(archives.begin());
|
||||
}
|
||||
return {};
|
||||
}
|
||||
} // namespace Echoion::Core
|
||||
-295
@@ -1,295 +0,0 @@
|
||||
#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
|
||||
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user