Compare commits
27
Commits
b4073ddf1e
..
v2.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
847308c160 | ||
|
|
fccdb2e159 | ||
|
|
21e158fae0 | ||
|
|
e4f5d88d14 | ||
|
|
a1ee8ef10b | ||
|
|
14b6f7a046 | ||
|
|
efabac6564 | ||
|
|
325b1b9ae8 | ||
|
|
257d2a9971 | ||
|
|
06e06b7622 | ||
|
|
3d61e6952f | ||
|
|
caac928923 | ||
|
|
24075fbd52 | ||
|
|
295542ab9e | ||
|
|
e7573fbcd0 | ||
|
|
97dc183bdf | ||
|
|
dede07748a | ||
|
|
222aee8889 | ||
|
|
c2b68dea2f | ||
|
|
e2e4214687 | ||
|
|
95454f9d83 | ||
|
|
317cef3782 | ||
|
|
85c0377e87 | ||
|
|
a2de8c63ce | ||
|
|
0e0f8915e9 | ||
|
|
e17cfed56f | ||
|
|
5e1e3d66c4 |
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
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
*build*
|
||||
.cache
|
||||
.idea
|
||||
AGENTS.md
|
||||
AGENTS.md
|
||||
__pycache__/
|
||||
+352
-20
@@ -1,47 +1,379 @@
|
||||
cmake_minimum_required(VERSION 3.28)
|
||||
project(EchoionApi 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(EchoionApi VERSION "${ECHOION_COMPONENT_VERSION}" LANGUAGES CXX)
|
||||
|
||||
if(PROJECT_IS_TOP_LEVEL)
|
||||
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")
|
||||
option(BUILD_TESTS "Build component tests" ON)
|
||||
if(BUILD_TESTS)
|
||||
enable_testing()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# Create header-only interface library for API
|
||||
add_library(EchoionApi INTERFACE)
|
||||
find_package(Threads REQUIRED)
|
||||
find_package(Boost 1.87 CONFIG REQUIRED)
|
||||
|
||||
add_library(Echoion::Api ALIAS EchoionApi)
|
||||
# ===== Granular API Libraries =====
|
||||
# Directory structure:
|
||||
# include/echoion/api/
|
||||
# base/ - Types.hpp (Error, Result, LogLevel, LogEntry)
|
||||
# audio/ - AudioTypes.hpp (AudioQuality, AudioFormat, AudioBuffer)
|
||||
# track/ - TrackTypes.hpp (TrackInfo, QueueEntry, PlaybackState, etc.)
|
||||
# network/ - NetworkTypes.hpp (HttpRequest, HttpResponse, ProxyConfig)
|
||||
# plugin/ - PluginTypes.hpp (PluginEvent, ClientInfo, ChannelInfo, etc.)
|
||||
# config/ - ConfigTypes.hpp (BotConfig, ServerConfig, AppConfig)
|
||||
# rpc/ - RpcTypes.hpp (RpcMethod, RpcRequest, RpcResponse, HotReloadState)
|
||||
# youtube/ - YouTubeTypes.hpp (YouTube types)
|
||||
# logger/ - LoggerInterface.hpp (ILogger, LoggerRegistry)
|
||||
# eventbus/ - EventBus.hpp (EventBus, all event types)
|
||||
# database/ - Database.hpp (Database interface)
|
||||
# interfaces/- CoreInterface.hpp, PluginInterface
|
||||
# utils/ - Cache.hpp, MemoryPool.hpp
|
||||
|
||||
target_include_directories(EchoionApi INTERFACE
|
||||
# 1. Base Types
|
||||
add_library(EchoionApiBase INTERFACE)
|
||||
add_library(Echoion::ApiBase ALIAS EchoionApiBase)
|
||||
target_include_directories(EchoionApiBase INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/base>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/base>
|
||||
)
|
||||
target_link_libraries(EchoionApiBase INTERFACE Void::Functional)
|
||||
|
||||
# 2. Audio Types
|
||||
add_library(EchoionApiAudio INTERFACE)
|
||||
add_library(Echoion::ApiAudio ALIAS EchoionApiAudio)
|
||||
target_include_directories(EchoionApiAudio INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/audio>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/audio>
|
||||
)
|
||||
target_link_libraries(EchoionApiAudio INTERFACE Echoion::ApiBase Echoion::ApiUtils)
|
||||
|
||||
# 3. Track Types (depends on Audio)
|
||||
add_library(EchoionApiTrack INTERFACE)
|
||||
add_library(Echoion::ApiTrack ALIAS EchoionApiTrack)
|
||||
target_include_directories(EchoionApiTrack INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/track>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/track>
|
||||
)
|
||||
target_link_libraries(EchoionApiTrack INTERFACE
|
||||
Echoion::ApiBase
|
||||
Echoion::ApiAudio
|
||||
Void::Data
|
||||
)
|
||||
|
||||
# 4. Network Types
|
||||
add_library(EchoionApiNetwork INTERFACE)
|
||||
add_library(Echoion::ApiNetwork ALIAS EchoionApiNetwork)
|
||||
target_include_directories(EchoionApiNetwork INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/network>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/network>
|
||||
)
|
||||
target_link_libraries(EchoionApiNetwork INTERFACE Echoion::ApiBase)
|
||||
|
||||
# 5. Plugin Types
|
||||
add_library(EchoionApiPlugin INTERFACE)
|
||||
add_library(Echoion::ApiPlugin ALIAS EchoionApiPlugin)
|
||||
target_include_directories(EchoionApiPlugin INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/plugin>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/plugin>
|
||||
)
|
||||
target_link_libraries(EchoionApiPlugin INTERFACE
|
||||
Echoion::ApiBase
|
||||
Echoion::ApiTrack
|
||||
Void::Plugin
|
||||
)
|
||||
|
||||
# Shared first-party plugin configuration and URL-host safety helpers. Their
|
||||
# implementation remains in the SDK so independently built plugins do not
|
||||
# duplicate or diverge from the same validation rules.
|
||||
add_library(EchoionApiPluginSdk STATIC
|
||||
src/ShortUrlSupport.cpp
|
||||
)
|
||||
add_library(Echoion::ApiPluginSdk ALIAS EchoionApiPluginSdk)
|
||||
set_target_properties(EchoionApiPluginSdk PROPERTIES
|
||||
EXPORT_NAME ApiPluginSdk
|
||||
POSITION_INDEPENDENT_CODE ON
|
||||
)
|
||||
target_compile_features(EchoionApiPluginSdk PUBLIC cxx_std_26)
|
||||
target_include_directories(EchoionApiPluginSdk PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
target_link_libraries(EchoionApiPluginSdk
|
||||
PUBLIC
|
||||
Echoion::ApiPlugin
|
||||
Void::Data
|
||||
Void::Net
|
||||
Void::Text
|
||||
)
|
||||
target_include_directories(EchoionApiPluginSdk PRIVATE ${Boost_INCLUDE_DIRS})
|
||||
|
||||
# Require glaze for JSON serialization (header-only)
|
||||
find_package(glaze CONFIG REQUIRED)
|
||||
target_link_libraries(EchoionApi INTERFACE glaze::glaze)
|
||||
# Echoion's discovery symbol and SDK aliases for VoidLibrary's reusable C++
|
||||
# module descriptor, lifecycle, SemVer, JSON, Result, and service types.
|
||||
add_library(EchoionApiModuleAbi INTERFACE)
|
||||
add_library(Echoion::ApiModuleAbi ALIAS EchoionApiModuleAbi)
|
||||
set_target_properties(EchoionApiModuleAbi PROPERTIES
|
||||
EXPORT_NAME ApiModuleAbi
|
||||
)
|
||||
target_include_directories(EchoionApiModuleAbi INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
target_link_libraries(EchoionApiModuleAbi INTERFACE Void::Plugin)
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
target_link_libraries(EchoionApi INTERFACE Threads::Threads)
|
||||
# 6. Config Types (depends on Network, Audio)
|
||||
add_library(EchoionApiConfig INTERFACE)
|
||||
add_library(Echoion::ApiConfig ALIAS EchoionApiConfig)
|
||||
target_include_directories(EchoionApiConfig INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/config>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/config>
|
||||
)
|
||||
target_link_libraries(EchoionApiConfig INTERFACE
|
||||
Echoion::ApiBase
|
||||
Echoion::ApiNetwork
|
||||
Echoion::ApiAudio
|
||||
)
|
||||
|
||||
# Compiler-specific options (interface library, so use INTERFACE)
|
||||
# 7. RPC Types (depends on Track)
|
||||
add_library(EchoionApiRpc INTERFACE)
|
||||
add_library(Echoion::ApiRpc ALIAS EchoionApiRpc)
|
||||
target_include_directories(EchoionApiRpc INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/rpc>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/rpc>
|
||||
)
|
||||
target_link_libraries(EchoionApiRpc INTERFACE
|
||||
Echoion::ApiBase
|
||||
Echoion::ApiTrack
|
||||
Echoion::ApiConfig
|
||||
)
|
||||
|
||||
# 8. YouTube Types (depends on Track)
|
||||
add_library(EchoionApiYouTube INTERFACE)
|
||||
add_library(Echoion::ApiYouTube ALIAS EchoionApiYouTube)
|
||||
target_include_directories(EchoionApiYouTube INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/youtube>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/youtube>
|
||||
)
|
||||
target_link_libraries(EchoionApiYouTube INTERFACE
|
||||
Echoion::ApiBase
|
||||
Echoion::ApiTrack
|
||||
)
|
||||
|
||||
# 9. Logger (self-contained)
|
||||
add_library(EchoionApiLogger INTERFACE)
|
||||
add_library(Echoion::ApiLogger ALIAS EchoionApiLogger)
|
||||
target_include_directories(EchoionApiLogger INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/logger>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/logger>
|
||||
)
|
||||
target_link_libraries(EchoionApiLogger INTERFACE
|
||||
Echoion::ApiBase
|
||||
Threads::Threads
|
||||
)
|
||||
|
||||
# 10. EventBus (depends on Track, Config, Plugin)
|
||||
add_library(EchoionApiEventBus INTERFACE)
|
||||
add_library(Echoion::ApiEventBus ALIAS EchoionApiEventBus)
|
||||
target_include_directories(EchoionApiEventBus INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/eventbus>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/eventbus>
|
||||
)
|
||||
target_link_libraries(EchoionApiEventBus INTERFACE
|
||||
Echoion::ApiBase
|
||||
Echoion::ApiTrack
|
||||
Echoion::ApiConfig
|
||||
Echoion::ApiPlugin
|
||||
Threads::Threads
|
||||
Void::Async
|
||||
)
|
||||
|
||||
# 11. Database (depends on Track, Config)
|
||||
add_library(EchoionApiDatabase INTERFACE)
|
||||
add_library(Echoion::ApiDatabase ALIAS EchoionApiDatabase)
|
||||
target_include_directories(EchoionApiDatabase INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/database>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/database>
|
||||
)
|
||||
target_link_libraries(EchoionApiDatabase INTERFACE
|
||||
Echoion::ApiBase
|
||||
Echoion::ApiTrack
|
||||
Echoion::ApiConfig
|
||||
Echoion::ApiEventBus
|
||||
)
|
||||
|
||||
# 11b. OpaqueHandle (for breaking dependencies)
|
||||
add_library(EchoionApiOpaque INTERFACE)
|
||||
add_library(Echoion::ApiOpaque ALIAS EchoionApiOpaque)
|
||||
target_include_directories(EchoionApiOpaque INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/interfaces>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/interfaces>
|
||||
)
|
||||
target_link_libraries(EchoionApiOpaque INTERFACE Echoion::ApiBase)
|
||||
|
||||
# 12a. Host interface used by Core and EchoionStandalone
|
||||
add_library(EchoionApiPluginInterface INTERFACE)
|
||||
add_library(Echoion::ApiPluginInterface ALIAS EchoionApiPluginInterface)
|
||||
target_include_directories(EchoionApiPluginInterface INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/interfaces>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/interfaces>
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/plugin>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/plugin>
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/base>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/base>
|
||||
)
|
||||
target_link_libraries(EchoionApiPluginInterface INTERFACE
|
||||
Echoion::ApiBase
|
||||
Echoion::ApiPlugin
|
||||
Echoion::ApiOpaque
|
||||
)
|
||||
|
||||
# 12b. CoreInterface (decoupled host boundary)
|
||||
add_library(EchoionApiCoreInterface INTERFACE)
|
||||
add_library(Echoion::ApiCoreInterface ALIAS EchoionApiCoreInterface)
|
||||
target_include_directories(EchoionApiCoreInterface INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/interfaces>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/interfaces>
|
||||
)
|
||||
target_link_libraries(EchoionApiCoreInterface INTERFACE
|
||||
Echoion::ApiBase
|
||||
Echoion::ApiPlugin
|
||||
Echoion::ApiPluginInterface
|
||||
Echoion::ApiOpaque
|
||||
)
|
||||
|
||||
# 12c. Combined host interfaces
|
||||
add_library(EchoionApiInterfaces INTERFACE)
|
||||
add_library(Echoion::ApiInterfaces ALIAS EchoionApiInterfaces)
|
||||
target_link_libraries(EchoionApiInterfaces INTERFACE
|
||||
Echoion::ApiPluginInterface
|
||||
Echoion::ApiCoreInterface
|
||||
Echoion::ApiConfig
|
||||
)
|
||||
|
||||
# 13. Utilities (Cache, MemoryPool)
|
||||
add_library(EchoionApiUtils INTERFACE)
|
||||
add_library(Echoion::ApiUtils ALIAS EchoionApiUtils)
|
||||
target_include_directories(EchoionApiUtils INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/utils>
|
||||
$<INSTALL_INTERFACE:include/echoion/api/utils>
|
||||
)
|
||||
target_link_libraries(EchoionApiUtils INTERFACE Echoion::ApiBase Void::Containers)
|
||||
|
||||
# 14. Full API (backward compatibility)
|
||||
add_library(EchoionApi INTERFACE)
|
||||
add_library(Echoion::Api ALIAS EchoionApi)
|
||||
target_include_directories(EchoionApi INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api>
|
||||
$<INSTALL_INTERFACE:include/echoion/api>
|
||||
)
|
||||
target_link_libraries(EchoionApi INTERFACE
|
||||
Echoion::ApiModuleAbi
|
||||
Echoion::ApiPluginSdk
|
||||
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
|
||||
)
|
||||
|
||||
# Compiler options
|
||||
if(MSVC)
|
||||
target_compile_options(EchoionApi INTERFACE /W4 /WX-)
|
||||
target_compile_options(EchoionApiBase INTERFACE /W4 /WX-)
|
||||
else()
|
||||
target_compile_options(EchoionApi INTERFACE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(EchoionApiBase INTERFACE -Wall -Wextra -Wpedantic)
|
||||
endif()
|
||||
|
||||
# Installation (header-only library, no archive)
|
||||
include(GNUInstallDirs)
|
||||
install(TARGETS EchoionApi
|
||||
# Install and export all modules
|
||||
install(TARGETS
|
||||
EchoionApiModuleAbi
|
||||
EchoionApiPluginSdk
|
||||
EchoionApiBase
|
||||
EchoionApiAudio
|
||||
EchoionApiTrack
|
||||
EchoionApiNetwork
|
||||
EchoionApiPlugin
|
||||
EchoionApiConfig
|
||||
EchoionApiRpc
|
||||
EchoionApiYouTube
|
||||
EchoionApiLogger
|
||||
EchoionApiEventBus
|
||||
EchoionApiDatabase
|
||||
EchoionApiOpaque
|
||||
EchoionApiPluginInterface
|
||||
EchoionApiCoreInterface
|
||||
EchoionApiInterfaces
|
||||
EchoionApiUtils
|
||||
EchoionApi
|
||||
EXPORT EchoionApiTargets
|
||||
INCLUDES DESTINATION include
|
||||
)
|
||||
|
||||
install(DIRECTORY include/ DESTINATION include)
|
||||
install(FILES abi/echoion-module-v1.json
|
||||
DESTINATION share/echoion/abi)
|
||||
|
||||
install(EXPORT EchoionApiTargets
|
||||
FILE EchoionApiTargets.cmake
|
||||
NAMESPACE Echoion::
|
||||
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/EchoionApi
|
||||
DESTINATION lib/cmake/EchoionApi
|
||||
)
|
||||
|
||||
install(DIRECTORY include/
|
||||
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
|
||||
# Create package config files
|
||||
include(CMakePackageConfigHelpers)
|
||||
write_basic_package_version_file(
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/EchoionApiConfigVersion.cmake"
|
||||
VERSION ${PROJECT_VERSION}
|
||||
COMPATIBILITY SameMajorVersion
|
||||
)
|
||||
|
||||
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/EchoionApiConfig.cmake"
|
||||
"include(\"\${CMAKE_CURRENT_LIST_DIR}/EchoionApiTargets.cmake\")
|
||||
")
|
||||
|
||||
install(FILES
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/EchoionApiConfig.cmake"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/EchoionApiConfigVersion.cmake"
|
||||
DESTINATION lib/cmake/EchoionApi
|
||||
)
|
||||
|
||||
if(BUILD_TESTS)
|
||||
find_package(Python3 QUIET COMPONENTS Interpreter)
|
||||
if(Python3_Interpreter_FOUND)
|
||||
add_test(NAME echoion_module_abi_contract_tests
|
||||
COMMAND "${Python3_EXECUTABLE}"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/tests/test_abi_contract.py")
|
||||
add_test(NAME echoion_module_abi_c_header_tests
|
||||
COMMAND "${Python3_EXECUTABLE}"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/tests/test_module_abi_c.py")
|
||||
endif()
|
||||
endif()
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
# API Reorganization Guide
|
||||
|
||||
## Directory Structure to Create
|
||||
|
||||
```
|
||||
EchoionApi/include/echoion/api/
|
||||
├── base/
|
||||
│ └── Types.hpp # Error, Result, LogLevel, LogEntry, version constants
|
||||
├── audio/
|
||||
│ └── AudioTypes.hpp # AudioQuality, AudioFormat, AudioBuffer
|
||||
├── track/
|
||||
│ └── TrackTypes.hpp # TrackInfo, QueueEntry, PlaybackState, SearchResult
|
||||
├── network/
|
||||
│ └── NetworkTypes.hpp # HttpHeader, HttpRequest, HttpResponse, ProxyConfig
|
||||
├── plugin/
|
||||
│ └── PluginTypes.hpp # PluginEventType, PluginEvent, ClientInfo, ChannelInfo
|
||||
├── config/
|
||||
│ └── ConfigTypes.hpp # BotConfig, ServerConfig, SecurityConfig, AppConfig
|
||||
├── rpc/
|
||||
│ └── RpcTypes.hpp # RpcMethod, RpcRequest, RpcResponse, HotReloadState
|
||||
├── youtube/
|
||||
│ └── YouTubeTypes.hpp # YouTubeVideoInfo, YouTubePlaylistInfo, etc.
|
||||
├── logger/
|
||||
│ └── LoggerInterface.hpp # ILogger, LoggerRegistry, macros
|
||||
├── eventbus/
|
||||
│ └── EventBus.hpp # EventBus, all event types
|
||||
├── database/
|
||||
│ └── Database.hpp # Database interface
|
||||
├── interfaces/
|
||||
│ ├── CoreInterface.hpp # ICoreInterface, INetworkClient
|
||||
│ └── PluginInterface.hpp # IPluginInterface
|
||||
└── utils/
|
||||
├── Cache.hpp # Cache interface
|
||||
└── MemoryPool.hpp # MemoryPool interface
|
||||
```
|
||||
|
||||
## Files to Move
|
||||
|
||||
### From root `include/echoion/api/` to subfolders:
|
||||
|
||||
| Current Location | New Location |
|
||||
|-----------------|--------------|
|
||||
| `Types.hpp` | `base/Types.hpp` |
|
||||
| `AudioTypes.hpp` | `audio/AudioTypes.hpp` |
|
||||
| `TrackTypes.hpp` | `track/TrackTypes.hpp` |
|
||||
| `NetworkTypes.hpp` | `network/NetworkTypes.hpp` |
|
||||
| `PluginTypes.hpp` | `plugin/PluginTypes.hpp` |
|
||||
| `ConfigTypes.hpp` | `config/ConfigTypes.hpp` |
|
||||
| `RpcTypes.hpp` | `rpc/RpcTypes.hpp` |
|
||||
| `YouTubeTypes.hpp` | `youtube/YouTubeTypes.hpp` |
|
||||
| `LoggerInterface.hpp` | `logger/LoggerInterface.hpp` |
|
||||
| `EventBus.hpp` | `eventbus/EventBus.hpp` |
|
||||
| `Database.hpp` | `database/Database.hpp` |
|
||||
| `CoreInterface.hpp` | `interfaces/CoreInterface.hpp` |
|
||||
| `Cache.hpp` | `utils/Cache.hpp` |
|
||||
| `MemoryPool.hpp` | `utils/MemoryPool.hpp` |
|
||||
|
||||
## Files to Delete
|
||||
|
||||
- `AudioTypesOnly.hpp`
|
||||
- `ConfigTypesOnly.hpp`
|
||||
- `LoggerTypesOnly.hpp`
|
||||
- `NetworkTypesOnly.hpp`
|
||||
- `PluginTypesOnly.hpp`
|
||||
- `RpcTypesOnly.hpp`
|
||||
- `TrackTypesOnly.hpp`
|
||||
- `YouTubeTypesOnly.hpp`
|
||||
- `BaseTypes.hpp`
|
||||
|
||||
## Include Path Changes
|
||||
|
||||
### For a host adapter (minimal):
|
||||
|
||||
**Before:**
|
||||
```cpp
|
||||
#include <echoion/api.hpp>
|
||||
```
|
||||
|
||||
**After:**
|
||||
```cpp
|
||||
#include <Types.hpp>
|
||||
#include <PluginTypes.hpp>
|
||||
#include <CoreInterface.hpp>
|
||||
```
|
||||
|
||||
The CMake target `Echoion::ApiPlugin` provides the event and host DTO include
|
||||
paths retained for source compatibility.
|
||||
|
||||
### For Core:
|
||||
|
||||
**Before:**
|
||||
```cpp
|
||||
#include <echoion/api/EventBus.hpp>
|
||||
```
|
||||
|
||||
**After:**
|
||||
```cpp
|
||||
#include <EventBus.hpp>
|
||||
```
|
||||
|
||||
The CMake target `Echoion::ApiEventBus` adds `eventbus/` to the include path.
|
||||
|
||||
## CMake Usage
|
||||
|
||||
### Standalone host needs:
|
||||
```cmake
|
||||
target_link_libraries(EchoionStandalone PRIVATE
|
||||
Echoion::ApiBase
|
||||
Echoion::ApiPlugin
|
||||
Echoion::ApiInterfaces
|
||||
)
|
||||
```
|
||||
|
||||
### Core uses everything:
|
||||
```cmake
|
||||
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::ApiInterfaces
|
||||
Echoion::ApiUtils
|
||||
)
|
||||
```
|
||||
|
||||
## Commands to Execute
|
||||
|
||||
Run these commands in the project root:
|
||||
|
||||
```bash
|
||||
# Create directory structure
|
||||
cd EchoionApi/include/echoion/api
|
||||
mkdir -p base audio track network plugin config rpc youtube logger eventbus database interfaces utils
|
||||
|
||||
# Move files
|
||||
mv Types.hpp base/
|
||||
mv AudioTypes.hpp audio/
|
||||
mv TrackTypes.hpp track/
|
||||
mv NetworkTypes.hpp network/
|
||||
mv PluginTypes.hpp plugin/
|
||||
mv ConfigTypes.hpp config/
|
||||
mv RpcTypes.hpp rpc/
|
||||
mv YouTubeTypes.hpp youtube/
|
||||
mv LoggerInterface.hpp logger/
|
||||
mv EventBus.hpp eventbus/
|
||||
mv Database.hpp database/
|
||||
mv CoreInterface.hpp interfaces/
|
||||
mv Cache.hpp utils/
|
||||
mv MemoryPool.hpp utils/
|
||||
|
||||
# Remove old files
|
||||
rm -f *Only.hpp BaseTypes.hpp
|
||||
|
||||
# Go back to project root
|
||||
cd ../../../../..
|
||||
|
||||
# Create Export.hpp in interfaces (if not exists)
|
||||
touch EchoionApi/include/echoion/api/interfaces/Export.hpp
|
||||
```
|
||||
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"contractId": "echoion.module",
|
||||
"language": "C",
|
||||
"header": "echoion/api/module/ModuleAbi.h",
|
||||
"querySymbol": "echoion_module_abi_query",
|
||||
"entryPoints": [
|
||||
{
|
||||
"name": "echoion_module_abi_query",
|
||||
"returns": "const echoion_module_descriptor_v1*",
|
||||
"ownership": "static-borrowed"
|
||||
}
|
||||
],
|
||||
"types": [
|
||||
{
|
||||
"name": "echoion_module_descriptor_v1",
|
||||
"version": 1,
|
||||
"sizeVersioned": true,
|
||||
"fields": [
|
||||
{"name": "struct_size", "type": "size_t"},
|
||||
{"name": "abi_version", "type": "uint32_t"},
|
||||
{"name": "component_id", "type": "echoion_string_view_v1"},
|
||||
{"name": "version_major", "type": "uint32_t"},
|
||||
{"name": "version_minor", "type": "uint32_t"},
|
||||
{"name": "version_patch", "type": "uint32_t"},
|
||||
{"name": "version_prerelease", "type": "echoion_string_view_v1"},
|
||||
{"name": "abi_hash", "type": "echoion_string_view_v1"},
|
||||
{"name": "dependencies", "type": "const echoion_module_dependency_v1*"},
|
||||
{"name": "dependency_count", "type": "size_t"},
|
||||
{"name": "activation_policy", "type": "echoion_activation_policy_v1"},
|
||||
{"name": "api", "type": "const echoion_module_api_v1*"},
|
||||
{"name": "reserved", "type": "const void*[8]"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "echoion_module_api_v1",
|
||||
"version": 1,
|
||||
"sizeVersioned": true,
|
||||
"fields": [
|
||||
{"name": "struct_size", "type": "size_t"},
|
||||
{"name": "abi_version", "type": "uint32_t"},
|
||||
{"name": "create", "type": "echoion_status_v1 (*)(const echoion_module_host_v1*, echoion_module_instance_v1*)"},
|
||||
{"name": "destroy", "type": "void (*)(echoion_module_instance_v1)"},
|
||||
{"name": "activate", "type": "echoion_status_v1 (*)(echoion_module_instance_v1)"},
|
||||
{"name": "quiesce", "type": "echoion_status_v1 (*)(echoion_module_instance_v1, int64_t)"},
|
||||
{"name": "checkpoint", "type": "echoion_status_v1 (*)(echoion_module_instance_v1, echoion_write_bytes_fn_v1, void*)"},
|
||||
{"name": "restore", "type": "echoion_status_v1 (*)(echoion_module_instance_v1, echoion_bytes_view_v1)"},
|
||||
{"name": "readiness", "type": "echoion_status_v1 (*)(echoion_module_instance_v1, echoion_module_readiness_v1*)"},
|
||||
{"name": "deactivate", "type": "echoion_status_v1 (*)(echoion_module_instance_v1)"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "echoion_module_host_v1",
|
||||
"version": 1,
|
||||
"sizeVersioned": true,
|
||||
"fields": [
|
||||
{"name": "struct_size", "type": "size_t"},
|
||||
{"name": "abi_version", "type": "uint32_t"},
|
||||
{"name": "context", "type": "void*"},
|
||||
{"name": "query_service", "type": "echoion_query_service_fn_v1"},
|
||||
{"name": "log", "type": "echoion_log_fn_v1"}
|
||||
]
|
||||
}
|
||||
],
|
||||
"rules": {
|
||||
"opaqueHandles": true,
|
||||
"explicitOwnership": true,
|
||||
"exceptionsCrossBoundary": false,
|
||||
"cppTypesCrossBoundary": false,
|
||||
"appendOnlyCompatibility": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"componentId": "EchoionApi",
|
||||
"productCompatibility": ">=2.0.0 <3.0.0",
|
||||
"publishNightly": true,
|
||||
"cmakeOptions": {}
|
||||
}
|
||||
+30
-17
@@ -1,20 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
// Main Echoion API header - includes all types
|
||||
// Main Echoion API header - backward compatibility
|
||||
// Includes all submodules
|
||||
|
||||
#include "echoion/api/Types.hpp"
|
||||
#include "echoion/api/AudioTypes.hpp"
|
||||
#include "echoion/api/TrackTypes.hpp"
|
||||
#include "echoion/api/NetworkTypes.hpp"
|
||||
#include "echoion/api/PluginTypes.hpp"
|
||||
#include "echoion/api/ConfigTypes.hpp"
|
||||
// Note: ConfigManager is deprecated - config is now passed from Plugin to Core via initialize()
|
||||
#include "echoion/api/RpcTypes.hpp"
|
||||
#include "echoion/api/YouTubeTypes.hpp"
|
||||
#include "echoion/api/LoggerInterface.hpp"
|
||||
#include "echoion/api/CoreInterface.hpp"
|
||||
#include "echoion/api/MemoryPool.hpp"
|
||||
#include "echoion/api/Cache.hpp"
|
||||
#include "echoion/api/EventBus.hpp"
|
||||
#include "echoion/api/Database.hpp"
|
||||
#include "echoion/api/Export.hpp"
|
||||
// Base types
|
||||
#include "api/base/Types.hpp"
|
||||
|
||||
// Granular type modules
|
||||
#include "api/audio/AudioTypes.hpp"
|
||||
#include "api/config/ConfigTypes.hpp"
|
||||
#include "api/network/NetworkInterface.hpp"
|
||||
#include "api/network/NetworkTypes.hpp"
|
||||
#include "api/plugin/PluginTypes.hpp"
|
||||
#include "api/plugin/ExtensionPlugin.hpp"
|
||||
#include "api/rpc/RpcTypes.hpp"
|
||||
#include "api/track/TrackTypes.hpp"
|
||||
#include "api/youtube/YouTubeTypes.hpp"
|
||||
|
||||
// Interfaces (decoupled)
|
||||
#include "api/interfaces/CoreInterface.hpp"
|
||||
#include "api/interfaces/OpaqueHandle.hpp"
|
||||
#include "api/interfaces/PluginInterface.hpp"
|
||||
|
||||
// Utilities
|
||||
#include "api/utils/MemoryPool.hpp"
|
||||
|
||||
// Core systems (for Core implementation only)
|
||||
#include "api/database/Database.hpp"
|
||||
#include "api/eventbus/Events.hpp"
|
||||
|
||||
// Export macros
|
||||
#include "api/interfaces/Export.hpp"
|
||||
@@ -1,113 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "MemoryPool.hpp"
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
enum class AudioFormat : uint8_t {
|
||||
Unknown = 0,
|
||||
MP3,
|
||||
AAC,
|
||||
Opus,
|
||||
Vorbis,
|
||||
FLAC,
|
||||
WAV
|
||||
};
|
||||
|
||||
enum class AudioQuality : uint8_t {
|
||||
Low = 0, // 64-96 kbps
|
||||
Medium, // 128-160 kbps
|
||||
High, // 192-256 kbps
|
||||
VeryHigh, // 320 kbps
|
||||
Lossless // FLAC or equivalent
|
||||
};
|
||||
|
||||
// Hardware acceleration types
|
||||
enum class HwAccelType : uint8_t {
|
||||
None = 0,
|
||||
CUDA, // NVIDIA CUDA
|
||||
VAAPI, // Video Acceleration API (Linux)
|
||||
DXVA2, // DirectX Video Acceleration 2 (Windows)
|
||||
D3D11VA, // Direct3D 11 Video Acceleration
|
||||
VideoToolbox, // Apple VideoToolbox
|
||||
Vulkan // Vulkan Video
|
||||
};
|
||||
|
||||
struct AudioFrame {
|
||||
std::vector<uint8_t> data;
|
||||
std::chrono::milliseconds pts;
|
||||
std::chrono::milliseconds duration;
|
||||
bool isKeyFrame;
|
||||
};
|
||||
|
||||
struct AudioStreamInfo {
|
||||
AudioFormat format;
|
||||
uint32_t sampleRate;
|
||||
uint32_t channels;
|
||||
uint32_t bitrate;
|
||||
std::chrono::milliseconds duration;
|
||||
std::optional<AudioQuality> quality;
|
||||
bool hwAccelerated = false;
|
||||
HwAccelType hwAccelType = HwAccelType::None;
|
||||
};
|
||||
|
||||
// Zero-copy decoded audio using pooled memory
|
||||
struct DecodedAudio {
|
||||
// Use pooled buffer instead of std::vector for zero-copy
|
||||
PooledPtr<float> pooledSamples;
|
||||
|
||||
// Non-owning view into the data
|
||||
FloatAudioView view;
|
||||
|
||||
uint32_t sampleRate;
|
||||
uint32_t channels;
|
||||
std::chrono::milliseconds timestamp;
|
||||
|
||||
// Backwards compatibility - creates a copy
|
||||
[[nodiscard]] std::vector<float> getSamples() const {
|
||||
if (view.empty()) {
|
||||
return {};
|
||||
}
|
||||
return std::vector<float>(view.data(), view.data() + view.size());
|
||||
}
|
||||
|
||||
// Check if valid
|
||||
[[nodiscard]] bool isValid() const {
|
||||
return !view.empty();
|
||||
}
|
||||
|
||||
// Apply volume in-place
|
||||
void applyVolume(float volume) {
|
||||
view.applyGain(volume);
|
||||
}
|
||||
};
|
||||
|
||||
// Hardware acceleration configuration
|
||||
struct HwAccelConfig {
|
||||
HwAccelType type = HwAccelType::None;
|
||||
int deviceIndex = -1; // -1 for auto-select
|
||||
std::optional<std::string> deviceName;
|
||||
|
||||
[[nodiscard]] bool isEnabled() const {
|
||||
return type != HwAccelType::None;
|
||||
}
|
||||
};
|
||||
|
||||
// Audio processing options
|
||||
struct AudioProcessOptions {
|
||||
float volume = 1.0f;
|
||||
bool normalize = false;
|
||||
bool highPassFilter = false; // Remove DC offset
|
||||
float highPassFreq = 20.0f; // Hz
|
||||
bool limiter = false; // Prevent clipping
|
||||
float limiterThreshold = 0.95f;
|
||||
};
|
||||
|
||||
using AudioBuffer = std::vector<uint8_t>;
|
||||
using AudioFramePtr = std::shared_ptr<AudioFrame>;
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -1,389 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "NetworkTypes.hpp"
|
||||
#include "TrackTypes.hpp"
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <chrono>
|
||||
#include <optional>
|
||||
#include <functional>
|
||||
#include <list>
|
||||
#include <memory>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// Cache entry with metadata
|
||||
template<typename T>
|
||||
struct CacheEntry {
|
||||
T value;
|
||||
std::chrono::system_clock::time_point created;
|
||||
std::chrono::system_clock::time_point lastAccessed;
|
||||
std::chrono::milliseconds ttl;
|
||||
uint64_t accessCount = 0;
|
||||
size_t size = 0; // Approximate memory size
|
||||
|
||||
[[nodiscard]] bool isExpired() const {
|
||||
auto now = std::chrono::system_clock::now();
|
||||
return (now - created) > ttl;
|
||||
}
|
||||
};
|
||||
|
||||
// Cache statistics
|
||||
struct CacheStats {
|
||||
size_t hits = 0;
|
||||
size_t misses = 0;
|
||||
size_t evictions = 0;
|
||||
size_t inserts = 0;
|
||||
size_t currentSize = 0;
|
||||
size_t maxSize = 0;
|
||||
size_t memoryUsage = 0;
|
||||
double hitRate() const {
|
||||
auto total = hits + misses;
|
||||
return total > 0 ? static_cast<double>(hits) / total : 0.0;
|
||||
}
|
||||
};
|
||||
|
||||
// Eviction policy
|
||||
enum class EvictionPolicy {
|
||||
LRU, // Least Recently Used
|
||||
LFU, // Least Frequently Used
|
||||
FIFO, // First In First Out
|
||||
TTL // Time To Live only
|
||||
};
|
||||
|
||||
// LRU Cache implementation
|
||||
template<typename Key, typename Value>
|
||||
class LruCache {
|
||||
public:
|
||||
using Entry = CacheEntry<Value>;
|
||||
using Loader = std::function<std::optional<Value>(const Key&)>;
|
||||
|
||||
explicit LruCache(size_t maxSize = 1000,
|
||||
std::chrono::milliseconds defaultTtl = std::chrono::minutes(5),
|
||||
EvictionPolicy policy = EvictionPolicy::LRU)
|
||||
: maxSize_(maxSize)
|
||||
, defaultTtl_(defaultTtl)
|
||||
, policy_(policy) {}
|
||||
|
||||
// Get value from cache (with optional loader for cache-aside pattern)
|
||||
[[nodiscard]] std::optional<Value> get(const Key& key, Loader loader = nullptr) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
|
||||
auto it = cache_.find(key);
|
||||
if (it != cache_.end()) {
|
||||
// Check if expired
|
||||
if (it->second.entry.isExpired()) {
|
||||
// Remove expired entry
|
||||
memoryUsage_ -= it->second.entry.size;
|
||||
removeFromOrder(it->second.orderIt);
|
||||
cache_.erase(it);
|
||||
stats_.evictions++;
|
||||
lock.unlock();
|
||||
stats_.misses++;
|
||||
|
||||
// Try to load if loader provided
|
||||
if (loader) {
|
||||
auto value = loader(key);
|
||||
if (value) {
|
||||
put(key, *value);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Update access info
|
||||
it->second.entry.lastAccessed = std::chrono::system_clock::now();
|
||||
it->second.entry.accessCount++;
|
||||
|
||||
// Move to front (MRU) for LRU policy
|
||||
if (policy_ == EvictionPolicy::LRU) {
|
||||
order_.splice(order_.begin(), order_, it->second.orderIt);
|
||||
}
|
||||
|
||||
stats_.hits++;
|
||||
return it->second.entry.value;
|
||||
}
|
||||
|
||||
lock.unlock();
|
||||
stats_.misses++;
|
||||
|
||||
// Try to load if loader provided
|
||||
if (loader) {
|
||||
auto value = loader(key);
|
||||
if (value) {
|
||||
put(key, *value);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Put value into cache
|
||||
void put(const Key& key, const Value& value,
|
||||
std::optional<std::chrono::milliseconds> ttl = std::nullopt,
|
||||
size_t estimatedSize = 0) {
|
||||
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
|
||||
// Check if key already exists
|
||||
auto it = cache_.find(key);
|
||||
if (it != cache_.end()) {
|
||||
// Update existing entry
|
||||
memoryUsage_ -= it->second.entry.size;
|
||||
it->second.entry.value = value;
|
||||
it->second.entry.created = std::chrono::system_clock::now();
|
||||
it->second.entry.lastAccessed = it->second.entry.created;
|
||||
it->second.entry.ttl = ttl.value_or(defaultTtl_);
|
||||
it->second.entry.size = estimatedSize;
|
||||
memoryUsage_ += estimatedSize;
|
||||
|
||||
// Move to front for LRU
|
||||
if (policy_ == EvictionPolicy::LRU) {
|
||||
order_.splice(order_.begin(), order_, it->second.orderIt);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Evict entries if necessary
|
||||
while (cache_.size() >= maxSize_ ||
|
||||
(maxMemory_ > 0 && memoryUsage_ + estimatedSize > maxMemory_)) {
|
||||
if (!evictOne()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Insert new entry
|
||||
order_.push_front(key);
|
||||
Entry entry{
|
||||
.value = value,
|
||||
.created = std::chrono::system_clock::now(),
|
||||
.lastAccessed = entry.created,
|
||||
.ttl = ttl.value_or(defaultTtl_),
|
||||
.accessCount = 1,
|
||||
.size = estimatedSize
|
||||
};
|
||||
|
||||
cache_[key] = {
|
||||
.entry = std::move(entry),
|
||||
.orderIt = order_.begin()
|
||||
};
|
||||
|
||||
memoryUsage_ += estimatedSize;
|
||||
stats_.inserts++;
|
||||
stats_.currentSize = cache_.size();
|
||||
}
|
||||
|
||||
// Remove specific key
|
||||
bool remove(const Key& key) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
|
||||
auto it = cache_.find(key);
|
||||
if (it == cache_.end()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
memoryUsage_ -= it->second.entry.size;
|
||||
removeFromOrder(it->second.orderIt);
|
||||
cache_.erase(it);
|
||||
stats_.currentSize = cache_.size();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Clear all entries
|
||||
void clear() {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
cache_.clear();
|
||||
order_.clear();
|
||||
memoryUsage_ = 0;
|
||||
stats_.currentSize = 0;
|
||||
}
|
||||
|
||||
// Check if key exists (without updating access)
|
||||
[[nodiscard]] bool contains(const Key& key) const {
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
return cache_.find(key) != cache_.end();
|
||||
}
|
||||
|
||||
// Get cache statistics
|
||||
[[nodiscard]] CacheStats getStats() const {
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
CacheStats stats = stats_;
|
||||
stats.currentSize = cache_.size();
|
||||
stats.maxSize = maxSize_;
|
||||
stats.memoryUsage = memoryUsage_;
|
||||
return stats;
|
||||
}
|
||||
|
||||
// Reset statistics
|
||||
void resetStats() {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
stats_ = CacheStats{};
|
||||
}
|
||||
|
||||
// Set max size
|
||||
void setMaxSize(size_t maxSize) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
maxSize_ = maxSize;
|
||||
|
||||
// Evict if necessary
|
||||
while (cache_.size() > maxSize_) {
|
||||
if (!evictOne()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Set max memory (0 = unlimited)
|
||||
void setMaxMemory(size_t maxMemory) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
maxMemory_ = maxMemory;
|
||||
|
||||
// Evict if necessary
|
||||
if (maxMemory_ > 0) {
|
||||
while (memoryUsage_ > maxMemory_) {
|
||||
if (!evictOne()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove expired entries
|
||||
size_t purgeExpired() {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
size_t count = 0;
|
||||
|
||||
auto now = std::chrono::system_clock::now();
|
||||
for (auto it = cache_.begin(); it != cache_.end();) {
|
||||
if ((now - it->second.entry.created) > it->second.entry.ttl) {
|
||||
memoryUsage_ -= it->second.entry.size;
|
||||
removeFromOrder(it->second.orderIt);
|
||||
it = cache_.erase(it);
|
||||
count++;
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
stats_.evictions += count;
|
||||
stats_.currentSize = cache_.size();
|
||||
return count;
|
||||
}
|
||||
|
||||
private:
|
||||
struct Node {
|
||||
Entry entry;
|
||||
typename std::list<Key>::iterator orderIt;
|
||||
};
|
||||
|
||||
bool evictOne() {
|
||||
if (order_.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Key keyToEvict;
|
||||
|
||||
switch (policy_) {
|
||||
case EvictionPolicy::LRU:
|
||||
case EvictionPolicy::FIFO:
|
||||
// Evict from back (oldest/least recently used)
|
||||
keyToEvict = order_.back();
|
||||
break;
|
||||
|
||||
case EvictionPolicy::LFU: {
|
||||
// Find least frequently used
|
||||
auto minAccess = std::numeric_limits<uint64_t>::max();
|
||||
for (const auto& [key, node] : cache_) {
|
||||
if (node.entry.accessCount < minAccess) {
|
||||
minAccess = node.entry.accessCount;
|
||||
keyToEvict = key;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case EvictionPolicy::TTL: {
|
||||
// Find soonest to expire
|
||||
auto now = std::chrono::system_clock::now();
|
||||
auto minRemaining = std::chrono::milliseconds::max();
|
||||
for (const auto& [key, node] : cache_) {
|
||||
auto remaining = node.entry.ttl - (now - node.entry.created);
|
||||
if (remaining < minRemaining) {
|
||||
minRemaining = remaining;
|
||||
keyToEvict = key;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
auto it = cache_.find(keyToEvict);
|
||||
if (it != cache_.end()) {
|
||||
memoryUsage_ -= it->second.entry.size;
|
||||
removeFromOrder(it->second.orderIt);
|
||||
cache_.erase(it);
|
||||
stats_.evictions++;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void removeFromOrder(typename std::list<Key>::iterator it) {
|
||||
order_.erase(it);
|
||||
}
|
||||
|
||||
mutable std::shared_mutex mutex_;
|
||||
std::unordered_map<Key, Node> cache_;
|
||||
std::list<Key> order_; // For LRU/FIFO ordering
|
||||
|
||||
size_t maxSize_;
|
||||
size_t maxMemory_ = 0;
|
||||
size_t memoryUsage_ = 0;
|
||||
std::chrono::milliseconds defaultTtl_;
|
||||
EvictionPolicy policy_;
|
||||
|
||||
mutable CacheStats stats_;
|
||||
};
|
||||
|
||||
// Type aliases for common cache types
|
||||
using StringCache = LruCache<std::string, std::string>;
|
||||
using HttpCache = LruCache<std::string, HttpResponse>;
|
||||
using TrackCache = LruCache<std::string, TrackInfo>;
|
||||
|
||||
// Cache manager for multiple cache types
|
||||
class CacheManager {
|
||||
public:
|
||||
static CacheManager& instance();
|
||||
|
||||
void initialize();
|
||||
void shutdown();
|
||||
|
||||
// Get specific caches
|
||||
[[nodiscard]] HttpCache& httpCache() { return httpCache_; }
|
||||
[[nodiscard]] TrackCache& trackCache() { return trackCache_; }
|
||||
[[nodiscard]] StringCache& metadataCache() { return metadataCache_; }
|
||||
|
||||
// Purge all expired entries
|
||||
void purgeAllExpired();
|
||||
|
||||
// Clear all caches
|
||||
void clearAll();
|
||||
|
||||
// Get combined stats
|
||||
[[nodiscard]] std::unordered_map<std::string, CacheStats> getAllStats() const;
|
||||
|
||||
private:
|
||||
CacheManager() = default;
|
||||
|
||||
HttpCache httpCache_{100, std::chrono::minutes(5)};
|
||||
TrackCache trackCache_{500, std::chrono::hours(1)};
|
||||
StringCache metadataCache_{1000, std::chrono::minutes(30)};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -1,96 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "ConfigTypes.hpp"
|
||||
#include <filesystem>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <optional>
|
||||
#include <functional>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
/**
|
||||
* @brief DEPRECATED: Global configuration manager
|
||||
*
|
||||
* This singleton pattern does NOT work across shared library boundaries.
|
||||
* Each shared library (Plugin and Core) gets its own instance.
|
||||
*
|
||||
* NEW ARCHITECTURE:
|
||||
* - Plugin loads config using ConfigLoader
|
||||
- Plugin passes config to Core via CoreLoader::setConfig() -> Core::initialize()
|
||||
* - Core stores config locally, updates via Core::updateConfig()
|
||||
* - Config reload: Core calls plugin->reloadConfig() -> Core::updateConfig()
|
||||
*
|
||||
* This header is kept for backward compatibility but should not be used.
|
||||
*/
|
||||
class ConfigManager {
|
||||
public:
|
||||
using ConfigChangedCallback = std::function<void(const AppConfig&)>;
|
||||
|
||||
// Get singleton instance
|
||||
static ConfigManager& instance();
|
||||
|
||||
// Delete copy/move
|
||||
ConfigManager(const ConfigManager&) = delete;
|
||||
ConfigManager& operator=(const ConfigManager&) = delete;
|
||||
|
||||
// Initialize with config file path (call once at startup)
|
||||
[[nodiscard]] bool initialize(const std::filesystem::path& configPath);
|
||||
|
||||
// Initialize with default path (~/.config/echoion/config.json)
|
||||
[[nodiscard]] bool initialize();
|
||||
|
||||
// Get current config (thread-safe)
|
||||
[[nodiscard]] AppConfig getConfig() const;
|
||||
|
||||
// Get config by reference (faster, but hold lock briefly)
|
||||
template<typename Func>
|
||||
auto withConfig(Func&& func) const -> decltype(func(std::declval<const AppConfig&>())) {
|
||||
std::shared_lock lock(mutex_);
|
||||
return func(config_);
|
||||
}
|
||||
|
||||
// Reload configuration from file
|
||||
[[nodiscard]] bool reload();
|
||||
|
||||
// Save current configuration to file
|
||||
[[nodiscard]] bool save();
|
||||
|
||||
// Update config (and optionally save)
|
||||
void updateConfig(const AppConfig& config, bool saveToFile = true);
|
||||
|
||||
// Check if initialized
|
||||
[[nodiscard]] bool isInitialized() const;
|
||||
|
||||
// Get config file path
|
||||
[[nodiscard]] std::filesystem::path getConfigPath() const;
|
||||
|
||||
// Get default config path (~/.config/echoion/config.json)
|
||||
[[nodiscard]] static std::filesystem::path getDefaultConfigPath();
|
||||
|
||||
// Subscribe to config changes
|
||||
void onConfigChanged(ConfigChangedCallback callback);
|
||||
|
||||
// Create default config file if it doesn't exist
|
||||
[[nodiscard]] bool createDefaultConfigIfNeeded();
|
||||
|
||||
private:
|
||||
ConfigManager() = default;
|
||||
~ConfigManager() = default;
|
||||
|
||||
mutable std::shared_mutex mutex_;
|
||||
AppConfig config_;
|
||||
std::filesystem::path configPath_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
std::vector<ConfigChangedCallback> callbacks_;
|
||||
mutable std::mutex callbackMutex_;
|
||||
|
||||
void notifyCallbacks();
|
||||
[[nodiscard]] bool loadFromFileInternal();
|
||||
[[nodiscard]] bool saveToFileInternal();
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
|
||||
// Convenience macro for accessing config
|
||||
#define ECHOION_CONFIG (::Echoion::Api::ConfigManager::instance().getConfig())
|
||||
@@ -1,93 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "NetworkTypes.hpp"
|
||||
#include "echoion/api/AudioTypes.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <variant>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
using ConfigValue = std::variant<
|
||||
std::monostate,
|
||||
bool,
|
||||
int64_t,
|
||||
double,
|
||||
std::string,
|
||||
std::vector<std::string>
|
||||
>;
|
||||
|
||||
struct ConfigEntry {
|
||||
std::string key;
|
||||
ConfigValue value;
|
||||
std::string description;
|
||||
bool isSecret;
|
||||
std::optional<ConfigValue> defaultValue;
|
||||
std::optional<std::string> category;
|
||||
};
|
||||
|
||||
struct BotConfig {
|
||||
std::string botName = "Echoion";
|
||||
std::string commandPrefix = "!";
|
||||
float defaultVolume = 0.5f;
|
||||
bool autoReconnect = true;
|
||||
std::chrono::milliseconds reconnectDelay = 5000ms;
|
||||
uint32_t maxReconnectAttempts = 5;
|
||||
std::optional<ProxyConfig> proxy;
|
||||
std::optional<std::string> youtubeApiKey;
|
||||
AudioQuality preferredQuality = AudioQuality::High;
|
||||
bool allowPlaylistImports = true;
|
||||
uint32_t maxQueueSize = 100;
|
||||
std::chrono::milliseconds trackTimeout = 30000ms;
|
||||
uint16_t rpcPort = 8765; // WebSocket RPC server port for Desktop/API clients
|
||||
|
||||
// YouTube cookie file path for yt-dlp authentication
|
||||
// See: https://github.com/yt-dlp/yt-dlp/wiki/Extractors#exporting-youtube-cookies
|
||||
std::optional<std::string> youtubeCookiesPath;
|
||||
|
||||
// Alternative: use cookies from browser directly
|
||||
// e.g., "chrome", "firefox", "safari", "edge"
|
||||
std::optional<std::string> cookiesFromBrowser;
|
||||
};
|
||||
|
||||
struct ServerConfig {
|
||||
std::string address;
|
||||
uint16_t port;
|
||||
std::string serverPassword;
|
||||
std::string nickname;
|
||||
std::optional<std::string> defaultChannelId;
|
||||
std::optional<std::string> channelPassword;
|
||||
std::vector<uint64_t> adminGroups;
|
||||
std::vector<uint64_t> djGroups;
|
||||
std::vector<uint64_t> bannedGroups;
|
||||
};
|
||||
|
||||
struct AdminCredentials {
|
||||
std::string username;
|
||||
std::string passwordHash;
|
||||
std::optional<std::string> salt;
|
||||
std::vector<std::string> permissions;
|
||||
std::chrono::system_clock::time_point createdAt;
|
||||
std::optional<std::chrono::system_clock::time_point> lastLogin;
|
||||
bool isActive;
|
||||
};
|
||||
|
||||
struct SecurityConfig {
|
||||
bool requireAuthForAdmin = true;
|
||||
uint32_t maxLoginAttempts = 5;
|
||||
std::chrono::milliseconds lockoutDuration = 300000ms;
|
||||
std::chrono::milliseconds sessionTimeout = 3600000ms;
|
||||
bool enableAuditLog = true;
|
||||
};
|
||||
|
||||
struct AppConfig {
|
||||
BotConfig bot;
|
||||
ServerConfig server;
|
||||
SecurityConfig security;
|
||||
std::map<std::string, ConfigEntry> custom;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -1,163 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "TrackTypes.hpp"
|
||||
#include "PluginTypes.hpp"
|
||||
#include "ConfigTypes.hpp"
|
||||
#include "RpcTypes.hpp"
|
||||
#include "NetworkTypes.hpp"
|
||||
#include <filesystem>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <functional>
|
||||
#include <expected>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// Forward declarations
|
||||
class IAudioDecoder;
|
||||
class IMusicManager;
|
||||
class ICommandManager;
|
||||
class IPluginInterface;
|
||||
class ICoreInterface;
|
||||
|
||||
// Network client interface
|
||||
class INetworkClient {
|
||||
public:
|
||||
virtual ~INetworkClient() = default;
|
||||
|
||||
// Initialize with optional proxy
|
||||
virtual Result<void> initialize(const std::optional<ProxyConfig>& proxy = std::nullopt) = 0;
|
||||
virtual void shutdown() = 0;
|
||||
|
||||
// Synchronous requests
|
||||
[[nodiscard]] virtual Result<HttpResponse> get(std::string_view url,
|
||||
const std::vector<HttpHeader>& headers = {}) = 0;
|
||||
[[nodiscard]] virtual Result<HttpResponse> post(std::string_view url,
|
||||
std::string_view body, const std::vector<HttpHeader>& headers = {}) = 0;
|
||||
[[nodiscard]] virtual Result<HttpResponse> request(const HttpRequest& req) = 0;
|
||||
|
||||
// Asynchronous requests
|
||||
[[nodiscard]] virtual std::future<Result<HttpResponse>> getAsync(std::string_view url,
|
||||
const std::vector<HttpHeader>& headers = {}) = 0;
|
||||
[[nodiscard]] virtual std::future<Result<HttpResponse>> postAsync(std::string_view url,
|
||||
std::string_view body, const std::vector<HttpHeader>& headers = {}) = 0;
|
||||
[[nodiscard]] virtual std::future<Result<HttpResponse>> requestAsync(const HttpRequest& req) = 0;
|
||||
|
||||
// Proxy configuration
|
||||
virtual void setProxy(const std::optional<ProxyConfig>& proxy) = 0;
|
||||
[[nodiscard]] virtual std::optional<ProxyConfig> getProxy() const = 0;
|
||||
virtual void clearProxy() = 0;
|
||||
|
||||
// Retry configuration
|
||||
virtual void setRetryConfig(const RetryConfig& config) = 0;
|
||||
[[nodiscard]] virtual RetryConfig getRetryConfig() const = 0;
|
||||
};
|
||||
|
||||
// Plugin interface that the core will use
|
||||
class IPluginInterface {
|
||||
public:
|
||||
virtual ~IPluginInterface() = default;
|
||||
|
||||
// Lifecycle
|
||||
virtual Result<void> initialize() = 0;
|
||||
virtual Result<void> shutdown() = 0;
|
||||
|
||||
// Client operations
|
||||
[[nodiscard]] virtual Result<std::vector<ClientInfo>> getClients() const = 0;
|
||||
[[nodiscard]] virtual Result<std::optional<ClientInfo>> getClient(uint64_t clientId) const = 0;
|
||||
virtual Result<void> moveClient(uint64_t clientId, uint64_t channelId) = 0;
|
||||
virtual Result<void> kickClient(uint64_t clientId, const std::string& reason) = 0;
|
||||
|
||||
// Channel operations
|
||||
[[nodiscard]] virtual Result<std::vector<ChannelInfo>> getChannels() const = 0;
|
||||
[[nodiscard]] virtual Result<std::optional<ChannelInfo>> getChannel(uint64_t channelId) const = 0;
|
||||
|
||||
// Messaging
|
||||
virtual Result<void> sendTextMessage(uint64_t targetId, const std::string& message) = 0;
|
||||
virtual Result<void> sendChannelMessage(uint64_t channelId, const std::string& message) = 0;
|
||||
virtual Result<void> sendServerMessage(const std::string& message) = 0;
|
||||
|
||||
// Audio
|
||||
virtual Result<void> sendAudioData(const std::span<const uint8_t>& data) = 0;
|
||||
virtual Result<void> setWhisperList(const std::vector<uint64_t>& clientIds) = 0;
|
||||
|
||||
// Server connection
|
||||
virtual Result<void> connectToServer(const ServerConfig& config) = 0;
|
||||
virtual Result<void> disconnectFromServer() = 0;
|
||||
[[nodiscard]] virtual bool isConnected() const = 0;
|
||||
virtual Result<void> reconnect() = 0;
|
||||
|
||||
// Event subscription
|
||||
virtual void registerEventCallback(const EventCallback& callback) = 0;
|
||||
virtual void unregisterEventCallback(const EventCallback& callback) = 0;
|
||||
};
|
||||
|
||||
using PluginInterfacePtr = std::shared_ptr<IPluginInterface>;
|
||||
|
||||
// Core interface that the plugin will use to communicate with the core
|
||||
class ICoreInterface {
|
||||
public:
|
||||
virtual ~ICoreInterface() = default;
|
||||
|
||||
// Lifecycle
|
||||
// Plugin passes config file path, Core loads config internally (no AppConfig dependency in Plugin)
|
||||
virtual Result<void> initialize(const std::filesystem::path& configPath) = 0;
|
||||
virtual Result<void> shutdown() = 0;
|
||||
virtual bool isInitialized() const noexcept = 0;
|
||||
|
||||
// Playback control
|
||||
virtual Result<void> play(const TrackInfo& track) = 0;
|
||||
virtual Result<void> pause() = 0;
|
||||
virtual Result<void> resume() = 0;
|
||||
virtual Result<void> stop() = 0;
|
||||
virtual Result<void> skip(uint32_t count = 1) = 0;
|
||||
virtual Result<void> seek(std::chrono::milliseconds position) = 0;
|
||||
virtual Result<void> setVolume(float volume) = 0;
|
||||
|
||||
// Queue management
|
||||
virtual Result<uint64_t> queueTrack(const TrackInfo& track, uint64_t clientId) = 0;
|
||||
virtual Result<void> removeFromQueue(uint64_t queueId) = 0;
|
||||
virtual Result<void> clearQueue() = 0;
|
||||
[[nodiscard]] virtual Result<std::vector<QueueEntry>> getQueue() const = 0;
|
||||
virtual Result<void> moveInQueue(uint64_t queueId, uint32_t newPosition) = 0;
|
||||
|
||||
// Track info
|
||||
[[nodiscard]] virtual Result<std::optional<QueueEntry>> getCurrentTrack() const = 0;
|
||||
[[nodiscard]] virtual Result<PlaybackState> getPlaybackState() const = 0;
|
||||
|
||||
// Playlist
|
||||
virtual Result<void> loadPlaylist(const std::string& playlistId, uint64_t clientId) = 0;
|
||||
virtual Result<std::vector<PlaylistInfo>> getPlaylists() const = 0;
|
||||
|
||||
// Configuration
|
||||
virtual Result<void> updateConfig(const AppConfig& config) = 0;
|
||||
[[nodiscard]] virtual Result<AppConfig> getConfig() const = 0;
|
||||
|
||||
// Hot reload
|
||||
virtual Result<HotReloadState> prepareForHotReload() = 0;
|
||||
virtual Result<void> restoreAfterHotReload(const HotReloadState& state) = 0;
|
||||
|
||||
// Event handling
|
||||
virtual void registerEventCallback(const EventCallback& callback) = 0;
|
||||
virtual void unregisterEventCallback(const EventCallback& callback) = 0;
|
||||
|
||||
// Plugin event processing
|
||||
virtual Result<void> onPluginEvent(const PluginEvent& event) = 0;
|
||||
|
||||
// Status
|
||||
[[nodiscard]] virtual std::string getVersion() const = 0;
|
||||
[[nodiscard]] virtual std::chrono::system_clock::time_point getUptime() const = 0;
|
||||
|
||||
// Plugin interface
|
||||
virtual void setPluginInterface(PluginInterfacePtr pluginInterface) = 0;
|
||||
|
||||
// Trigger auto-connect (call after setPluginInterface)
|
||||
virtual void triggerAutoConnect() = 0;
|
||||
};
|
||||
|
||||
using CoreInterfacePtr = std::shared_ptr<ICoreInterface>;
|
||||
using CoreCreateFunc = std::function<CoreInterfacePtr()>;
|
||||
using CoreDestroyFunc = std::function<void(ICoreInterface*)>;
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -1,210 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "TrackTypes.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <optional>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// Forward declaration
|
||||
class DatabaseImpl;
|
||||
|
||||
// Database configuration
|
||||
struct DatabaseConfig {
|
||||
std::string path = "echoion.db";
|
||||
bool walMode = true; // Write-Ahead Logging for better concurrency
|
||||
int maxConnections = 4;
|
||||
std::chrono::seconds busyTimeout{5000};
|
||||
};
|
||||
|
||||
// Playlist with tracks
|
||||
struct Playlist {
|
||||
uint64_t id;
|
||||
std::string name;
|
||||
std::string description;
|
||||
uint64_t createdBy;
|
||||
std::chrono::system_clock::time_point createdAt;
|
||||
std::chrono::system_clock::time_point updatedAt;
|
||||
std::vector<TrackInfo> tracks;
|
||||
bool isPublic = false;
|
||||
};
|
||||
|
||||
// Playback history entry
|
||||
struct PlaybackHistoryEntry {
|
||||
uint64_t id;
|
||||
TrackInfo track;
|
||||
uint64_t playedBy;
|
||||
std::chrono::system_clock::time_point playedAt;
|
||||
std::chrono::milliseconds duration; // How long it played
|
||||
bool completed = false; // Did it play to the end
|
||||
};
|
||||
|
||||
// User favorites
|
||||
struct FavoriteTrack {
|
||||
TrackInfo track;
|
||||
uint64_t userId;
|
||||
std::chrono::system_clock::time_point addedAt;
|
||||
};
|
||||
|
||||
// Statistics
|
||||
struct PlaybackStatistics {
|
||||
uint64_t totalPlays = 0;
|
||||
uint64_t totalTracks = 0;
|
||||
uint64_t totalPlaytimeMs = 0;
|
||||
std::optional<TrackInfo> mostPlayedTrack;
|
||||
uint64_t mostPlayedCount = 0;
|
||||
};
|
||||
|
||||
// Main database interface
|
||||
class Database {
|
||||
public:
|
||||
Database();
|
||||
~Database();
|
||||
|
||||
// Non-copyable
|
||||
Database(const Database&) = delete;
|
||||
Database& operator=(const Database&) = delete;
|
||||
|
||||
// Initialization
|
||||
Api::Result<void> initialize(const DatabaseConfig& config = {});
|
||||
void shutdown();
|
||||
[[nodiscard]] bool isInitialized() const;
|
||||
|
||||
// Migrations
|
||||
Api::Result<void> migrate(); // Run pending migrations
|
||||
[[nodiscard]] int getCurrentVersion() const;
|
||||
|
||||
// ===== Playlists =====
|
||||
|
||||
// Create a new playlist
|
||||
[[nodiscard]] Api::Result<uint64_t> createPlaylist(
|
||||
const std::string& name,
|
||||
const std::string& description,
|
||||
uint64_t createdBy,
|
||||
bool isPublic = false);
|
||||
|
||||
// Get playlist by ID
|
||||
[[nodiscard]] Api::Result<std::optional<Playlist>> getPlaylist(uint64_t id);
|
||||
|
||||
// Get all playlists for a user
|
||||
[[nodiscard]] Api::Result<std::vector<Playlist>> getUserPlaylists(uint64_t userId);
|
||||
|
||||
// Update playlist
|
||||
Api::Result<void> updatePlaylist(uint64_t id,
|
||||
const std::optional<std::string>& name = std::nullopt,
|
||||
const std::optional<std::string>& description = std::nullopt,
|
||||
const std::optional<bool>& isPublic = std::nullopt);
|
||||
|
||||
// Delete playlist
|
||||
Api::Result<void> deletePlaylist(uint64_t id);
|
||||
|
||||
// Add track to playlist
|
||||
Api::Result<void> addTrackToPlaylist(uint64_t playlistId,
|
||||
const TrackInfo& track, uint32_t position = 0);
|
||||
|
||||
// Remove track from playlist
|
||||
Api::Result<void> removeTrackFromPlaylist(uint64_t playlistId, uint64_t trackId);
|
||||
|
||||
// Reorder playlist tracks
|
||||
Api::Result<void> reorderPlaylistTrack(uint64_t playlistId,
|
||||
uint64_t trackId, uint32_t newPosition);
|
||||
|
||||
// ===== Playback History =====
|
||||
|
||||
// Record a playback
|
||||
Api::Result<void> recordPlayback(const TrackInfo& track,
|
||||
uint64_t playedBy,
|
||||
std::chrono::milliseconds duration,
|
||||
bool completed);
|
||||
|
||||
// Get playback history for a user
|
||||
[[nodiscard]] Api::Result<std::vector<PlaybackHistoryEntry>> getPlaybackHistory(
|
||||
uint64_t userId,
|
||||
size_t limit = 100,
|
||||
size_t offset = 0);
|
||||
|
||||
// Get recently played tracks
|
||||
[[nodiscard]] Api::Result<std::vector<TrackInfo>> getRecentlyPlayed(
|
||||
uint64_t userId,
|
||||
size_t limit = 20);
|
||||
|
||||
// ===== Favorites =====
|
||||
|
||||
// Add track to favorites
|
||||
Api::Result<void> addFavorite(uint64_t userId, const TrackInfo& track);
|
||||
|
||||
// Remove track from favorites
|
||||
Api::Result<void> removeFavorite(uint64_t userId, const std::string& trackUrl);
|
||||
|
||||
// Check if track is favorited
|
||||
[[nodiscard]] Api::Result<bool> isFavorite(uint64_t userId, const std::string& trackUrl);
|
||||
|
||||
// Get all favorites for a user
|
||||
[[nodiscard]] Api::Result<std::vector<FavoriteTrack>> getFavorites(uint64_t userId);
|
||||
|
||||
// ===== Statistics =====
|
||||
|
||||
// Get playback statistics
|
||||
[[nodiscard]] Api::Result<PlaybackStatistics> getStatistics(
|
||||
uint64_t userId,
|
||||
std::optional<std::chrono::system_clock::time_point> since = std::nullopt);
|
||||
|
||||
// Get most played tracks
|
||||
[[nodiscard]] Api::Result<std::vector<std::pair<TrackInfo, uint64_t>>> getMostPlayed(
|
||||
uint64_t userId,
|
||||
size_t limit = 10);
|
||||
|
||||
// ===== Subscriptions =====
|
||||
|
||||
// Add a subscriber
|
||||
Api::Result<void> addSubscriber(uint64_t clientId);
|
||||
|
||||
// Remove a subscriber
|
||||
Api::Result<void> removeSubscriber(uint64_t clientId);
|
||||
|
||||
// Check if client is subscribed
|
||||
[[nodiscard]] Api::Result<bool> isSubscriber(uint64_t clientId);
|
||||
|
||||
// Get all subscribers
|
||||
[[nodiscard]] Api::Result<std::vector<uint64_t>> getAllSubscribers();
|
||||
|
||||
// Get subscriber count
|
||||
[[nodiscard]] Api::Result<size_t> getSubscriberCount();
|
||||
|
||||
// ===== Cache Management =====
|
||||
|
||||
// Clear old history (keep last N entries)
|
||||
Api::Result<void> trimHistory(size_t keepCount = 10000);
|
||||
|
||||
// Clear all data for a user
|
||||
Api::Result<void> clearUserData(uint64_t userId);
|
||||
|
||||
// Vacuum database (reclaim space)
|
||||
Api::Result<void> vacuum();
|
||||
|
||||
// ===== Raw Query (for advanced use) =====
|
||||
|
||||
using RowCallback = std::function<void(const std::vector<std::optional<std::string>>&)>;
|
||||
Api::Result<void> executeQuery(const std::string& sql, RowCallback callback = nullptr);
|
||||
|
||||
private:
|
||||
std::unique_ptr<DatabaseImpl> impl_;
|
||||
};
|
||||
|
||||
// Database manager (singleton)
|
||||
class DatabaseManager {
|
||||
public:
|
||||
static Database& instance();
|
||||
|
||||
static Api::Result<void> initialize(const DatabaseConfig& config = {});
|
||||
static void shutdown();
|
||||
|
||||
private:
|
||||
DatabaseManager() = default;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -1,269 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "echoion/api/ConfigTypes.hpp"
|
||||
#include "echoion/api/PluginTypes.hpp"
|
||||
#include "echoion/api/TrackTypes.hpp"
|
||||
#include <functional>
|
||||
#include <typeindex>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <queue>
|
||||
#include <thread>
|
||||
#include <condition_variable>
|
||||
#include <atomic>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// Base event interface
|
||||
struct IEvent {
|
||||
virtual ~IEvent() = default;
|
||||
virtual std::type_index getType() const = 0;
|
||||
std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now();
|
||||
};
|
||||
|
||||
// Typed event wrapper
|
||||
template<typename T>
|
||||
struct Event : IEvent {
|
||||
T data;
|
||||
|
||||
explicit Event(T d) : data(std::move(d)) {}
|
||||
|
||||
std::type_index getType() const override {
|
||||
return std::type_index(typeid(T));
|
||||
}
|
||||
};
|
||||
|
||||
// Event handler type
|
||||
template<typename T>
|
||||
using EventHandler = std::function<void(const T&)>;
|
||||
|
||||
// Subscription token for unsubscribing
|
||||
class SubscriptionToken {
|
||||
public:
|
||||
using Id = uint64_t;
|
||||
|
||||
SubscriptionToken() = default;
|
||||
explicit SubscriptionToken(Id id, std::type_index type,
|
||||
std::weak_ptr<std::function<void(const std::shared_ptr<IEvent>&)>> handler)
|
||||
: id_(id), type_(type), handler_(std::move(handler)) {}
|
||||
|
||||
[[nodiscard]] bool isValid() const { return id_ != 0; }
|
||||
[[nodiscard]] Id getId() const { return id_; }
|
||||
[[nodiscard]] std::type_index getType() const { return type_; }
|
||||
|
||||
private:
|
||||
Id id_ = 0;
|
||||
std::type_index type_ = std::type_index(typeid(void));
|
||||
std::weak_ptr<std::function<void(const std::shared_ptr<IEvent>&)>> handler_;
|
||||
|
||||
friend class EventBus;
|
||||
};
|
||||
|
||||
// Event bus for decoupled communication
|
||||
class EventBus {
|
||||
public:
|
||||
EventBus();
|
||||
~EventBus();
|
||||
|
||||
// Delete copy/move
|
||||
EventBus(const EventBus&) = delete;
|
||||
EventBus& operator=(const EventBus&) = delete;
|
||||
EventBus(EventBus&&) = delete;
|
||||
EventBus& operator=(EventBus&&) = delete;
|
||||
|
||||
// Start processing events
|
||||
void start();
|
||||
void stop();
|
||||
|
||||
// Publish an event (thread-safe)
|
||||
template<typename T>
|
||||
void publish(T event) {
|
||||
auto evt = std::make_shared<Event<T>>(std::move(event));
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(queueMutex_);
|
||||
eventQueue_.push(evt);
|
||||
}
|
||||
queueCv_.notify_one();
|
||||
}
|
||||
|
||||
// Subscribe to events (thread-safe)
|
||||
template<typename T>
|
||||
[[nodiscard]] SubscriptionToken subscribe(EventHandler<T> handler) {
|
||||
auto wrappedHandler = std::make_shared<std::function<void(const std::shared_ptr<IEvent>&)>>(
|
||||
[h = std::move(handler)](const std::shared_ptr<IEvent>& evt) {
|
||||
if (auto typedEvt = std::dynamic_pointer_cast<Event<T>>(evt)) {
|
||||
h(typedEvt->data);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
std::type_index type(typeid(T));
|
||||
auto id = nextId_++;
|
||||
|
||||
{
|
||||
std::unique_lock<std::shared_mutex> lock(handlersMutex_);
|
||||
handlers_[type][id] = wrappedHandler;
|
||||
}
|
||||
|
||||
return SubscriptionToken(id, type, wrappedHandler);
|
||||
}
|
||||
|
||||
// Unsubscribe from events
|
||||
void unsubscribe(const SubscriptionToken& token);
|
||||
|
||||
// Process a single event immediately (for synchronous processing)
|
||||
void processOne();
|
||||
|
||||
// Wait for and process one event (blocking)
|
||||
bool waitAndProcessOne(std::chrono::milliseconds timeout);
|
||||
|
||||
// Clear all pending events
|
||||
void clearQueue();
|
||||
|
||||
// Get number of pending events
|
||||
[[nodiscard]] size_t getPendingEventCount() const;
|
||||
|
||||
private:
|
||||
void processEvents();
|
||||
|
||||
mutable std::shared_mutex handlersMutex_;
|
||||
std::unordered_map<std::type_index, std::unordered_map<SubscriptionToken::Id,
|
||||
std::shared_ptr<std::function<void(const std::shared_ptr<IEvent>&)>>>> handlers_;
|
||||
|
||||
mutable std::mutex queueMutex_;
|
||||
std::queue<std::shared_ptr<IEvent>> eventQueue_;
|
||||
std::condition_variable queueCv_;
|
||||
|
||||
std::atomic<bool> running_{false};
|
||||
std::atomic<bool> stopRequested_{false};
|
||||
std::jthread eventThread_;
|
||||
|
||||
std::atomic<SubscriptionToken::Id> nextId_{1};
|
||||
};
|
||||
|
||||
// Global event bus singleton
|
||||
class GlobalEventBus {
|
||||
public:
|
||||
[[nodiscard]] static EventBus& instance();
|
||||
|
||||
private:
|
||||
GlobalEventBus() = default;
|
||||
};
|
||||
|
||||
// Common event types for Echoion
|
||||
namespace Events {
|
||||
|
||||
// Playback events
|
||||
struct PlaybackStarted {
|
||||
TrackInfo track;
|
||||
uint64_t clientId;
|
||||
};
|
||||
|
||||
struct PlaybackPaused {
|
||||
std::chrono::milliseconds position;
|
||||
};
|
||||
|
||||
struct PlaybackResumed {
|
||||
std::chrono::milliseconds position;
|
||||
};
|
||||
|
||||
struct PlaybackStopped {};
|
||||
|
||||
struct TrackFinished {
|
||||
TrackInfo track;
|
||||
bool autoSkipped;
|
||||
};
|
||||
|
||||
struct VolumeChanged {
|
||||
float oldVolume;
|
||||
float newVolume;
|
||||
uint64_t changedByClientId;
|
||||
};
|
||||
|
||||
// Queue events
|
||||
struct TrackQueued {
|
||||
TrackInfo track;
|
||||
uint64_t queueId;
|
||||
uint64_t addedByClientId;
|
||||
uint32_t position;
|
||||
};
|
||||
|
||||
struct TrackRemoved {
|
||||
uint64_t queueId;
|
||||
uint64_t removedByClientId;
|
||||
};
|
||||
|
||||
struct QueueCleared {
|
||||
uint64_t clearedByClientId;
|
||||
};
|
||||
|
||||
struct QueueShuffled {
|
||||
uint64_t triggeredByClientId;
|
||||
};
|
||||
|
||||
// Connection events
|
||||
struct ClientConnected {
|
||||
ClientInfo client;
|
||||
};
|
||||
|
||||
struct ClientDisconnected {
|
||||
uint64_t clientId;
|
||||
std::string reason;
|
||||
};
|
||||
|
||||
struct ChannelChanged {
|
||||
uint64_t clientId;
|
||||
uint64_t oldChannelId;
|
||||
uint64_t newChannelId;
|
||||
};
|
||||
|
||||
// Error events
|
||||
struct PlaybackError {
|
||||
ErrorCode code;
|
||||
std::string message;
|
||||
std::optional<TrackInfo> track;
|
||||
};
|
||||
|
||||
struct NetworkError {
|
||||
std::string url;
|
||||
ErrorCode code;
|
||||
std::string message;
|
||||
};
|
||||
|
||||
// Configuration events
|
||||
struct ConfigReloaded {
|
||||
BotConfig newConfig;
|
||||
};
|
||||
|
||||
struct ConfigChanged {
|
||||
std::string key;
|
||||
std::string oldValue;
|
||||
std::string newValue;
|
||||
};
|
||||
|
||||
// Cache events
|
||||
struct CacheHit {
|
||||
std::string key;
|
||||
std::string type;
|
||||
};
|
||||
|
||||
struct CacheMiss {
|
||||
std::string key;
|
||||
std::string type;
|
||||
};
|
||||
|
||||
struct CacheEvicted {
|
||||
std::string key;
|
||||
std::string reason;
|
||||
};
|
||||
|
||||
} // namespace Events
|
||||
|
||||
// Helper macros for event publishing/subscribing
|
||||
#define ECHOION_PUBLISH(event) Echoion::Api::GlobalEventBus::instance().publish(event)
|
||||
#define ECHOION_SUBSCRIBE(type, handler) Echoion::Api::GlobalEventBus::instance().subscribe<type>(handler)
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -1,39 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "CoreInterface.hpp"
|
||||
|
||||
// Platform-specific export macros
|
||||
#ifdef _WIN32
|
||||
#ifdef ECHOION_API_EXPORT
|
||||
#define ECHOION_API __declspec(dllexport)
|
||||
#else
|
||||
#define ECHOION_API __declspec(dllimport)
|
||||
#endif
|
||||
#else
|
||||
#define ECHOION_API __attribute__((visibility("default")))
|
||||
#endif
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// Version information
|
||||
constexpr uint32_t VERSION_MAJOR = 1;
|
||||
constexpr uint32_t VERSION_MINOR = 0;
|
||||
constexpr uint32_t VERSION_PATCH = 0;
|
||||
constexpr const char* VERSION_STRING = "1.0.0";
|
||||
|
||||
// API export functions
|
||||
extern "C" {
|
||||
// Create a new core instance
|
||||
ECHOION_API CoreInterfacePtr CreateCore();
|
||||
|
||||
// Destroy a core instance
|
||||
ECHOION_API void DestroyCore(ICoreInterface* core);
|
||||
|
||||
// Get API version
|
||||
ECHOION_API const char* GetApiVersion();
|
||||
|
||||
// Check if API is compatible
|
||||
ECHOION_API bool IsApiCompatible(uint32_t major, uint32_t minor);
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -1,104 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include <string>
|
||||
#include <functional>
|
||||
#include <source_location>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// Logger interface for the user's custom logger implementation
|
||||
class ILogger {
|
||||
public:
|
||||
virtual ~ILogger() = default;
|
||||
|
||||
// Core logging method
|
||||
virtual void log(LogLevel level, std::string_view message,
|
||||
std::source_location location = std::source_location::current()) = 0;
|
||||
|
||||
// Convenience methods
|
||||
virtual void debug(std::string_view message,
|
||||
std::source_location location = std::source_location::current()) {
|
||||
log(LogLevel::Debug, message, location);
|
||||
}
|
||||
|
||||
virtual void info(std::string_view message,
|
||||
std::source_location location = std::source_location::current()) {
|
||||
log(LogLevel::Info, message, location);
|
||||
}
|
||||
|
||||
virtual void warning(std::string_view message,
|
||||
std::source_location location = std::source_location::current()) {
|
||||
log(LogLevel::Warning, message, location);
|
||||
}
|
||||
|
||||
virtual void error(std::string_view message,
|
||||
std::source_location location = std::source_location::current()) {
|
||||
log(LogLevel::Error, message, location);
|
||||
}
|
||||
|
||||
virtual void critical(std::string_view message,
|
||||
std::source_location location = std::source_location::current()) {
|
||||
log(LogLevel::Critical, message, location);
|
||||
}
|
||||
|
||||
// Template method for formatted logging
|
||||
template<typename... Args>
|
||||
void logf(LogLevel level, std::format_string<Args...> fmt, Args&&... args,
|
||||
std::source_location location = std::source_location::current()) {
|
||||
log(level, std::format(fmt, std::forward<Args>(args)...), location);
|
||||
}
|
||||
|
||||
// Set minimum log level
|
||||
virtual void setMinLevel(LogLevel level) = 0;
|
||||
[[nodiscard]] virtual LogLevel getMinLevel() const = 0;
|
||||
|
||||
// Register log callback
|
||||
using LogCallback = std::function<void(const LogEntry&)>;
|
||||
virtual void registerCallback(const LogCallback& callback) = 0;
|
||||
virtual void unregisterCallback(const LogCallback& callback) = 0;
|
||||
};
|
||||
|
||||
using LoggerPtr = std::shared_ptr<ILogger>;
|
||||
|
||||
// Global logger accessor
|
||||
class LoggerRegistry {
|
||||
public:
|
||||
static LoggerRegistry& instance() {
|
||||
static LoggerRegistry instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
void setLogger(LoggerPtr logger) { logger_ = std::move(logger); }
|
||||
[[nodiscard]] LoggerPtr getLogger() const { return logger_; }
|
||||
|
||||
[[nodiscard]] bool hasLogger() const noexcept { return static_cast<bool>(logger_); }
|
||||
|
||||
private:
|
||||
LoggerRegistry() = default;
|
||||
LoggerPtr logger_;
|
||||
};
|
||||
|
||||
// Convenience macros
|
||||
#define ECHOION_LOG_DEBUG(msg) \
|
||||
do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \
|
||||
logger->debug(msg); } while(0)
|
||||
|
||||
#define ECHOION_LOG_INFO(msg) \
|
||||
do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \
|
||||
logger->info(msg); } while(0)
|
||||
|
||||
#define ECHOION_LOG_WARNING(msg) \
|
||||
do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \
|
||||
logger->warning(msg); } while(0)
|
||||
|
||||
#define ECHOION_LOG_ERROR(msg) \
|
||||
do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \
|
||||
logger->error(msg); } while(0)
|
||||
|
||||
#define ECHOION_LOG_CRITICAL(msg) \
|
||||
do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \
|
||||
logger->critical(msg); } while(0)
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -1,287 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <atomic>
|
||||
#include <cstring>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// Custom allocator for audio buffers
|
||||
template<typename T>
|
||||
class MemoryPool {
|
||||
public:
|
||||
explicit MemoryPool(size_t blockSize, size_t initialBlocks = 64)
|
||||
: blockSize_(blockSize)
|
||||
, capacity_(initialBlocks) {
|
||||
|
||||
// Pre-allocate memory
|
||||
storage_.resize(blockSize_ * capacity_);
|
||||
|
||||
// Initialize free list
|
||||
for (size_t i = 0; i < capacity_; ++i) {
|
||||
freeList_.push(&storage_[i * blockSize_]);
|
||||
}
|
||||
|
||||
available_.store(capacity_, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
~MemoryPool() = default;
|
||||
|
||||
// Non-copyable, non-movable
|
||||
MemoryPool(const MemoryPool&) = delete;
|
||||
MemoryPool& operator=(const MemoryPool&) = delete;
|
||||
MemoryPool(MemoryPool&&) = delete;
|
||||
MemoryPool& operator=(MemoryPool&&) = delete;
|
||||
|
||||
// Allocate a block
|
||||
[[nodiscard]] T* acquire() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (freeList_.empty()) {
|
||||
// Grow pool if needed
|
||||
grow();
|
||||
}
|
||||
|
||||
if (freeList_.empty()) {
|
||||
return nullptr; // Out of memory
|
||||
}
|
||||
|
||||
T* block = freeList_.front();
|
||||
freeList_.pop();
|
||||
available_.fetch_sub(1, std::memory_order_relaxed);
|
||||
|
||||
return block;
|
||||
}
|
||||
|
||||
// Release a block back to pool
|
||||
void release(T* block) {
|
||||
if (!block) return;
|
||||
|
||||
// Verify block belongs to this pool
|
||||
if (!contains(block)) {
|
||||
return; // Or assert/panic
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
freeList_.push(block);
|
||||
available_.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
// Get available blocks count
|
||||
[[nodiscard]] size_t available() const {
|
||||
return available_.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
// Get total capacity
|
||||
[[nodiscard]] size_t capacity() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return capacity_;
|
||||
}
|
||||
|
||||
// Get block size
|
||||
[[nodiscard]] size_t blockSize() const {
|
||||
return blockSize_;
|
||||
}
|
||||
|
||||
// Reserve additional blocks
|
||||
void reserve(size_t additionalBlocks) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
size_t oldCapacity = capacity_;
|
||||
size_t newCapacity = capacity_ + additionalBlocks;
|
||||
|
||||
storage_.resize(blockSize_ * newCapacity);
|
||||
|
||||
// Add new blocks to free list
|
||||
for (size_t i = oldCapacity; i < newCapacity; ++i) {
|
||||
freeList_.push(&storage_[i * blockSize_]);
|
||||
}
|
||||
|
||||
capacity_ = newCapacity;
|
||||
available_.fetch_add(additionalBlocks, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
private:
|
||||
[[nodiscard]] bool contains(const T* block) const {
|
||||
return block >= &storage_[0] &&
|
||||
block <= &storage_[(capacity_ - 1) * blockSize_];
|
||||
}
|
||||
|
||||
void grow() {
|
||||
// Double the capacity
|
||||
size_t additionalBlocks = capacity_;
|
||||
reserve(additionalBlocks);
|
||||
}
|
||||
|
||||
size_t blockSize_;
|
||||
size_t capacity_;
|
||||
std::vector<T> storage_;
|
||||
std::queue<T*> freeList_;
|
||||
mutable std::mutex mutex_;
|
||||
std::atomic<size_t> available_;
|
||||
};
|
||||
|
||||
// Smart pointer for pooled memory
|
||||
template<typename T>
|
||||
class PooledPtr {
|
||||
public:
|
||||
PooledPtr() = default;
|
||||
|
||||
PooledPtr(T* ptr, MemoryPool<T>* pool)
|
||||
: ptr_(ptr), pool_(pool) {}
|
||||
|
||||
~PooledPtr() {
|
||||
reset();
|
||||
}
|
||||
|
||||
// Move semantics only
|
||||
PooledPtr(PooledPtr&& other) noexcept
|
||||
: ptr_(other.ptr_), pool_(other.pool_) {
|
||||
other.ptr_ = nullptr;
|
||||
other.pool_ = nullptr;
|
||||
}
|
||||
|
||||
PooledPtr& operator=(PooledPtr&& other) noexcept {
|
||||
if (this != &other) {
|
||||
reset();
|
||||
ptr_ = other.ptr_;
|
||||
pool_ = other.pool_;
|
||||
other.ptr_ = nullptr;
|
||||
other.pool_ = nullptr;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Delete copy
|
||||
PooledPtr(const PooledPtr&) = delete;
|
||||
PooledPtr& operator=(const PooledPtr&) = delete;
|
||||
|
||||
[[nodiscard]] T* get() const { return ptr_; }
|
||||
[[nodiscard]] T& operator*() const { return *ptr_; }
|
||||
[[nodiscard]] T* operator->() const { return ptr_; }
|
||||
[[nodiscard]] explicit operator bool() const { return ptr_ != nullptr; }
|
||||
|
||||
[[nodiscard]] T* release() {
|
||||
T* tmp = ptr_;
|
||||
ptr_ = nullptr;
|
||||
pool_ = nullptr;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
if (ptr_ && pool_) {
|
||||
pool_->release(ptr_);
|
||||
}
|
||||
ptr_ = nullptr;
|
||||
pool_ = nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
T* ptr_ = nullptr;
|
||||
MemoryPool<T>* pool_ = nullptr;
|
||||
};
|
||||
|
||||
// Specialized audio buffer pool
|
||||
class AudioBufferPool {
|
||||
public:
|
||||
static constexpr size_t DEFAULT_BUFFER_SIZE = 1920; // 48000Hz * 2ch * 20ms
|
||||
static constexpr size_t DEFAULT_POOL_SIZE = 256; // ~7.5MB for float buffers
|
||||
|
||||
static AudioBufferPool& instance();
|
||||
|
||||
void initialize(size_t bufferSize = DEFAULT_BUFFER_SIZE,
|
||||
size_t poolSize = DEFAULT_POOL_SIZE);
|
||||
void shutdown();
|
||||
|
||||
// Get a buffer (returns nullptr if pool exhausted)
|
||||
[[nodiscard]] PooledPtr<float> acquireBuffer();
|
||||
|
||||
// Get buffer size
|
||||
[[nodiscard]] size_t getBufferSize() const { return bufferSize_; }
|
||||
|
||||
// Get stats
|
||||
[[nodiscard]] size_t getAvailableBuffers() const;
|
||||
[[nodiscard]] size_t getTotalBuffers() const;
|
||||
|
||||
private:
|
||||
AudioBufferPool() = default;
|
||||
|
||||
std::unique_ptr<MemoryPool<float>> pool_;
|
||||
size_t bufferSize_ = DEFAULT_BUFFER_SIZE;
|
||||
};
|
||||
|
||||
// Zero-copy audio buffer view
|
||||
template<typename T>
|
||||
class AudioBufferView {
|
||||
public:
|
||||
AudioBufferView() = default;
|
||||
|
||||
AudioBufferView(T* data, size_t size, size_t channels = 2)
|
||||
: data_(data), size_(size), channels_(channels) {}
|
||||
|
||||
[[nodiscard]] T* data() { return data_; }
|
||||
[[nodiscard]] const T* data() const { return data_; }
|
||||
[[nodiscard]] size_t size() const { return size_; }
|
||||
[[nodiscard]] size_t channels() const { return channels_; }
|
||||
[[nodiscard]] size_t samplesPerChannel() const { return size_ / channels_; }
|
||||
|
||||
[[nodiscard]] T* channel(size_t ch) {
|
||||
return data_ + ch;
|
||||
}
|
||||
|
||||
[[nodiscard]] T& sample(size_t frame, size_t ch) {
|
||||
return data_[frame * channels_ + ch];
|
||||
}
|
||||
|
||||
[[nodiscard]] const T& sample(size_t frame, size_t ch) const {
|
||||
return data_[frame * channels_ + ch];
|
||||
}
|
||||
|
||||
// Span for single channel
|
||||
[[nodiscard]] std::span<T> getChannelSpan(size_t ch) {
|
||||
return std::span<T>(data_ + ch, size_, channels_);
|
||||
}
|
||||
|
||||
// Span for all data
|
||||
[[nodiscard]] std::span<T> getSpan() {
|
||||
return std::span<T>(data_, size_);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool empty() const { return data_ == nullptr || size_ == 0; }
|
||||
|
||||
void clear() {
|
||||
if (data_) {
|
||||
std::memset(data_, 0, size_ * sizeof(T));
|
||||
}
|
||||
}
|
||||
|
||||
// Apply gain in-place
|
||||
void applyGain(float gain) {
|
||||
if (!data_) return;
|
||||
for (size_t i = 0; i < size_; ++i) {
|
||||
data_[i] *= gain;
|
||||
}
|
||||
}
|
||||
|
||||
// Mix another buffer into this one
|
||||
void mix(const AudioBufferView& other, float gain = 1.0f) {
|
||||
if (!data_ || !other.data_) return;
|
||||
size_t mixSize = std::min(size_, other.size_);
|
||||
for (size_t i = 0; i < mixSize; ++i) {
|
||||
data_[i] += other.data_[i] * gain;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
T* data_ = nullptr;
|
||||
size_t size_ = 0;
|
||||
size_t channels_ = 2;
|
||||
};
|
||||
|
||||
using FloatAudioView = AudioBufferView<float>;
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -1,145 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <chrono>
|
||||
#include <cctype>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
enum class HttpMethod : uint8_t {
|
||||
GET = 0,
|
||||
POST,
|
||||
PUT,
|
||||
DELETE,
|
||||
PATCH,
|
||||
HEAD,
|
||||
OPTIONS
|
||||
};
|
||||
|
||||
enum class ProxyType : uint8_t {
|
||||
HTTP = 0,
|
||||
SOCKS5
|
||||
};
|
||||
|
||||
struct ProxyConfig {
|
||||
ProxyType type = ProxyType::HTTP;
|
||||
std::string host;
|
||||
uint16_t port;
|
||||
std::optional<std::string> username;
|
||||
std::optional<std::string> password;
|
||||
std::optional<std::chrono::milliseconds> timeout;
|
||||
|
||||
[[nodiscard]] bool isValid() const noexcept {
|
||||
return !host.empty() && port > 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool requiresAuth() const noexcept {
|
||||
return username.has_value() && password.has_value();
|
||||
}
|
||||
|
||||
[[nodiscard]] bool isSocks5() const noexcept {
|
||||
return type == ProxyType::SOCKS5;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool operator==(const ProxyConfig& other) const = default;
|
||||
[[nodiscard]] bool operator!=(const ProxyConfig& other) const = default;
|
||||
};
|
||||
|
||||
struct HttpHeader {
|
||||
std::string name;
|
||||
std::string value;
|
||||
};
|
||||
|
||||
struct HttpRequest {
|
||||
std::string url;
|
||||
HttpMethod method = HttpMethod::GET;
|
||||
std::vector<HttpHeader> headers;
|
||||
std::optional<std::vector<uint8_t>> body;
|
||||
std::optional<ProxyConfig> proxy;
|
||||
std::chrono::milliseconds timeout = 30000ms;
|
||||
bool followRedirects = true;
|
||||
uint32_t maxRedirects = 10;
|
||||
};
|
||||
|
||||
struct HttpResponse {
|
||||
int32_t statusCode;
|
||||
// Using vector to support multiple headers with same name (e.g., Set-Cookie)
|
||||
std::vector<std::pair<std::string, std::string>> headers;
|
||||
std::string body;
|
||||
std::chrono::milliseconds responseTime;
|
||||
std::optional<std::string> contentType;
|
||||
bool fromCache = false;
|
||||
|
||||
[[nodiscard]] bool isSuccess() const noexcept {
|
||||
return statusCode >= 200 && statusCode < 300;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool isRedirect() const noexcept {
|
||||
return statusCode >= 300 && statusCode < 400;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool isError() const noexcept {
|
||||
return statusCode >= 400 || statusCode == 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string bodyAsString() const {
|
||||
return std::string(body.begin(), body.end());
|
||||
}
|
||||
|
||||
// Helper to get first header value by name (case-insensitive)
|
||||
[[nodiscard]] std::optional<std::string> getHeader(std::string_view name) const {
|
||||
for (const auto& [key, value] : headers) {
|
||||
if (key.size() == name.size()) {
|
||||
bool match = true;
|
||||
for (size_t i = 0; i < key.size(); ++i) {
|
||||
if (std::tolower(static_cast<unsigned char>(key[i])) !=
|
||||
std::tolower(static_cast<unsigned char>(name[i]))) {
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (match) return value;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Helper to get all header values by name (case-insensitive) - useful for Set-Cookie
|
||||
[[nodiscard]] std::vector<std::string> getHeaders(std::string_view name) const {
|
||||
std::vector<std::string> result;
|
||||
for (const auto& [key, value] : headers) {
|
||||
if (key.size() == name.size()) {
|
||||
bool match = true;
|
||||
for (size_t i = 0; i < key.size(); ++i) {
|
||||
if (std::tolower(static_cast<unsigned char>(key[i])) !=
|
||||
std::tolower(static_cast<unsigned char>(name[i]))) {
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (match) result.push_back(value);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
struct RateLimitInfo {
|
||||
uint32_t limit;
|
||||
uint32_t remaining;
|
||||
std::optional<std::chrono::system_clock::time_point> resetTime;
|
||||
};
|
||||
|
||||
struct RetryConfig {
|
||||
uint32_t maxRetries = 3;
|
||||
std::chrono::milliseconds initialDelay = 1000ms;
|
||||
std::chrono::milliseconds maxDelay = 30000ms;
|
||||
float backoffMultiplier = 2.0f;
|
||||
std::vector<int32_t> retryableStatusCodes = {408, 429, 500, 502, 503, 504};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -1,107 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "TrackTypes.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
enum class PluginEventType : uint8_t {
|
||||
// Connection events
|
||||
ClientConnected = 0,
|
||||
ClientDisconnected,
|
||||
ClientMoved,
|
||||
|
||||
// Chat events
|
||||
TextMessageReceived,
|
||||
|
||||
// Audio events
|
||||
VoiceDataReceived,
|
||||
|
||||
// Bot control events
|
||||
PlayRequested,
|
||||
PauseRequested,
|
||||
SkipRequested,
|
||||
StopRequested,
|
||||
|
||||
// Queue events
|
||||
TrackQueued,
|
||||
TrackRemoved,
|
||||
QueueCleared,
|
||||
QueueUpdated,
|
||||
|
||||
// State events
|
||||
PlaybackStarted,
|
||||
PlaybackPaused,
|
||||
PlaybackResumed,
|
||||
PlaybackStopped,
|
||||
TrackFinished,
|
||||
TrackSkipped,
|
||||
VolumeChanged,
|
||||
SeekPosition,
|
||||
|
||||
// System events
|
||||
HotReloadRequested,
|
||||
HotReloadCompleted,
|
||||
ConfigurationChanged
|
||||
};
|
||||
|
||||
struct PluginEvent {
|
||||
PluginEventType type;
|
||||
std::optional<std::string> clientName;
|
||||
uint64_t clientId;
|
||||
std::optional<uint64_t> targetChannelId;
|
||||
std::optional<std::string> message;
|
||||
std::optional<TrackInfo> trackInfo;
|
||||
std::optional<float> volume;
|
||||
std::optional<int> queuePosition;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
struct ClientInfo {
|
||||
uint64_t id;
|
||||
std::string nickname;
|
||||
std::optional<std::string> uniqueIdentifier;
|
||||
uint64_t channelId;
|
||||
bool isTalking;
|
||||
bool isMuted;
|
||||
bool isDeafened;
|
||||
std::vector<uint64_t> serverGroups;
|
||||
};
|
||||
|
||||
struct ChannelInfo {
|
||||
uint64_t id;
|
||||
std::string name;
|
||||
std::optional<uint64_t> parentId;
|
||||
uint64_t order;
|
||||
bool isDefault;
|
||||
bool hasPassword;
|
||||
uint32_t maxClients;
|
||||
uint32_t currentClients;
|
||||
};
|
||||
|
||||
struct ServerInfo {
|
||||
uint64_t id;
|
||||
std::string name;
|
||||
std::string welcomeMessage;
|
||||
uint32_t maxClients;
|
||||
uint32_t currentClients;
|
||||
uint64_t defaultChannelId;
|
||||
};
|
||||
|
||||
using EventCallback = std::function<void(const PluginEvent&)>;
|
||||
using CommandHandler = std::function<void(uint64_t clientId, const std::vector<std::string>& args)>;
|
||||
|
||||
struct CommandInfo {
|
||||
std::string name;
|
||||
std::string description;
|
||||
std::vector<std::string> aliases;
|
||||
std::optional<std::string> usage;
|
||||
bool requiresAdmin;
|
||||
CommandHandler handler;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -1,105 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "TrackTypes.hpp"
|
||||
#include "PluginTypes.hpp"
|
||||
#include "ConfigTypes.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <optional>
|
||||
#include <functional>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
enum class RpcMethod : uint8_t {
|
||||
// Playback control
|
||||
Play = 0,
|
||||
Pause,
|
||||
Resume,
|
||||
Stop,
|
||||
Skip,
|
||||
Seek,
|
||||
SetVolume,
|
||||
|
||||
// Queue management
|
||||
QueueTrack,
|
||||
RemoveFromQueue,
|
||||
ClearQueue,
|
||||
GetQueue,
|
||||
MoveInQueue,
|
||||
|
||||
// Track info
|
||||
GetCurrentTrack,
|
||||
GetTrackInfo,
|
||||
SearchTracks,
|
||||
|
||||
// Playlist
|
||||
LoadPlaylist,
|
||||
SavePlaylist,
|
||||
GetPlaylists,
|
||||
DeletePlaylist,
|
||||
|
||||
// Configuration
|
||||
GetConfig,
|
||||
SetConfig,
|
||||
ReloadConfig,
|
||||
|
||||
// Plugin/Core management
|
||||
GetStatus,
|
||||
HotReload,
|
||||
Shutdown,
|
||||
|
||||
// Admin
|
||||
Authenticate,
|
||||
Logout,
|
||||
GetAuditLog,
|
||||
ManageUsers
|
||||
};
|
||||
|
||||
struct RpcRequest {
|
||||
uint64_t id;
|
||||
RpcMethod method;
|
||||
std::optional<std::string> params;
|
||||
std::optional<std::string> authToken;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
struct RpcResponse {
|
||||
uint64_t requestId;
|
||||
bool success;
|
||||
std::optional<std::string> result;
|
||||
std::optional<std::string> error; // JSON string: {"code":N,"message":"...","source":"..."}
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
struct RpcNotification {
|
||||
std::string event;
|
||||
std::optional<std::string> data;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
using RpcHandler = std::function<RpcResponse(const RpcRequest&)>;
|
||||
|
||||
struct RpcEndpoint {
|
||||
RpcMethod method;
|
||||
std::string name;
|
||||
std::string description;
|
||||
bool requiresAuth;
|
||||
RpcHandler handler;
|
||||
};
|
||||
|
||||
// Hot reload state preservation
|
||||
struct HotReloadState {
|
||||
PlaybackState playback;
|
||||
std::vector<QueueEntry> queue;
|
||||
std::optional<std::string> currentStreamUrl;
|
||||
std::chrono::milliseconds playbackPosition;
|
||||
BotConfig config;
|
||||
std::map<std::string, std::string> sessionData;
|
||||
|
||||
[[nodiscard]] bool shouldPreservePlayback() const noexcept {
|
||||
return playback.isPlaying && playback.currentTrack.has_value();
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -1,77 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "AudioTypes.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <chrono>
|
||||
#include <optional>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
enum class TrackSource : uint8_t {
|
||||
Unknown = 0,
|
||||
YouTube,
|
||||
SoundCloud,
|
||||
Spotify,
|
||||
LocalFile,
|
||||
URL
|
||||
};
|
||||
|
||||
struct TrackInfo {
|
||||
std::string id;
|
||||
std::string title;
|
||||
std::string artist;
|
||||
std::string album;
|
||||
std::optional<std::string> thumbnailUrl;
|
||||
std::optional<std::chrono::milliseconds> duration;
|
||||
TrackSource source;
|
||||
std::string originalUrl;
|
||||
std::optional<std::string> streamUrl;
|
||||
std::optional<AudioStreamInfo> audioInfo;
|
||||
std::chrono::system_clock::time_point addedAt;
|
||||
std::string requestedBy;
|
||||
};
|
||||
|
||||
struct PlaylistInfo {
|
||||
std::string id;
|
||||
std::string name;
|
||||
std::string description;
|
||||
std::optional<std::string> thumbnailUrl;
|
||||
std::string owner;
|
||||
std::vector<TrackInfo> tracks;
|
||||
std::chrono::system_clock::time_point createdAt;
|
||||
std::chrono::system_clock::time_point updatedAt;
|
||||
};
|
||||
|
||||
struct QueueEntry {
|
||||
uint64_t queueId;
|
||||
TrackInfo track;
|
||||
std::chrono::system_clock::time_point addedAt;
|
||||
std::string addedBy;
|
||||
bool isPlaying;
|
||||
std::optional<std::chrono::milliseconds> position;
|
||||
};
|
||||
|
||||
struct PlaybackState {
|
||||
std::optional<QueueEntry> currentTrack;
|
||||
std::vector<QueueEntry> queue;
|
||||
bool isPlaying;
|
||||
bool isPaused;
|
||||
std::chrono::milliseconds position;
|
||||
std::chrono::milliseconds buffered;
|
||||
float volume;
|
||||
bool repeat;
|
||||
bool shuffle;
|
||||
std::chrono::system_clock::time_point lastUpdate;
|
||||
};
|
||||
|
||||
struct SearchResult {
|
||||
std::vector<TrackInfo> tracks;
|
||||
std::vector<PlaylistInfo> playlists;
|
||||
std::string query;
|
||||
std::optional<std::string> nextPageToken;
|
||||
uint32_t totalResults;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -1,73 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <optional>
|
||||
#include <chrono>
|
||||
#include <expected>
|
||||
#include <format>
|
||||
#include <thread>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
enum class ErrorCode : uint32_t {
|
||||
Success = 0,
|
||||
InvalidArgument,
|
||||
NotFound,
|
||||
AlreadyExists,
|
||||
NetworkError,
|
||||
ParseError,
|
||||
AudioError,
|
||||
PluginError,
|
||||
InvalidUrl,
|
||||
NotAuthenticated,
|
||||
Unauthorized,
|
||||
PermissionDenied,
|
||||
ServiceUnavailable,
|
||||
DatabaseError,
|
||||
NotSupported,
|
||||
UnknownError
|
||||
};
|
||||
|
||||
struct Error {
|
||||
ErrorCode code;
|
||||
std::string message;
|
||||
std::string source;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
|
||||
Error() = default;
|
||||
Error(ErrorCode c, std::string_view msg, std::string_view src = "")
|
||||
: code(c), message(msg), source(src), timestamp(std::chrono::system_clock::now()) {}
|
||||
|
||||
[[nodiscard]] std::string toString() const {
|
||||
return std::format("[{}] {} (from: {})",
|
||||
static_cast<uint32_t>(code), message, source);
|
||||
}
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
using Result = std::expected<T, Error>;
|
||||
|
||||
enum class LogLevel : uint8_t {
|
||||
Debug = 0,
|
||||
Info,
|
||||
Warning,
|
||||
Error,
|
||||
Critical
|
||||
};
|
||||
|
||||
struct LogEntry {
|
||||
LogLevel level;
|
||||
std::string message;
|
||||
std::string source;
|
||||
std::string sourceFile;
|
||||
uint32_t sourceLine = 0;
|
||||
std::string function;
|
||||
std::thread::id threadId;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -1,134 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include "TrackTypes.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <optional>
|
||||
#include <chrono>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
// YouTube-specific types for the extracted client algorithm
|
||||
|
||||
struct YouTubeFormat {
|
||||
std::string itag;
|
||||
std::string mimeType;
|
||||
std::optional<std::string> url;
|
||||
std::optional<std::string> signatureCipher;
|
||||
int32_t bitrate;
|
||||
int32_t width;
|
||||
int32_t height;
|
||||
std::optional<std::string> qualityLabel;
|
||||
std::optional<std::string> audioQuality;
|
||||
int32_t audioSampleRate;
|
||||
int32_t audioChannels;
|
||||
bool hasVideo;
|
||||
bool hasAudio;
|
||||
};
|
||||
|
||||
struct YouTubeVideoDetails {
|
||||
std::string videoId;
|
||||
std::string title;
|
||||
std::string author;
|
||||
std::optional<std::chrono::seconds> lengthSeconds;
|
||||
std::vector<YouTubeFormat> formats;
|
||||
std::vector<YouTubeFormat> adaptiveFormats;
|
||||
std::optional<std::string> playerJsUrl;
|
||||
std::optional<std::string> streamingData;
|
||||
};
|
||||
|
||||
struct YouTubeSearchResult {
|
||||
std::string videoId;
|
||||
std::string title;
|
||||
std::string channelTitle;
|
||||
std::optional<std::chrono::seconds> duration;
|
||||
std::optional<std::string> thumbnailUrl;
|
||||
std::string publishedAt;
|
||||
uint64_t viewCount;
|
||||
};
|
||||
|
||||
struct YouTubePlaylistItem {
|
||||
std::string videoId;
|
||||
std::string title;
|
||||
std::optional<std::chrono::seconds> duration;
|
||||
std::optional<std::string> thumbnailUrl;
|
||||
};
|
||||
|
||||
struct YouTubePlaylist {
|
||||
std::string playlistId;
|
||||
std::string title;
|
||||
std::string author;
|
||||
std::vector<YouTubePlaylistItem> videos;
|
||||
std::optional<std::string> continuationToken;
|
||||
};
|
||||
|
||||
struct YouTubePlayerConfig {
|
||||
std::string innertubeApiKey;
|
||||
std::string innertubeClientName;
|
||||
std::string innertubeClientVersion;
|
||||
std::string contextClientName;
|
||||
std::string contextClientVersion;
|
||||
std::string visitorData;
|
||||
std::optional<std::string> poToken;
|
||||
};
|
||||
|
||||
struct YouTubeClientContext {
|
||||
std::string hl = "en";
|
||||
std::string gl = "US";
|
||||
std::string clientName = "WEB";
|
||||
std::string clientVersion;
|
||||
std::optional<std::string> visitorData;
|
||||
std::optional<std::string> userAgent;
|
||||
};
|
||||
|
||||
// Convert YouTube types to generic TrackInfo
|
||||
[[nodiscard]] inline TrackInfo ConvertToTrackInfo(const YouTubeVideoDetails& details) {
|
||||
TrackInfo info;
|
||||
info.id = details.videoId;
|
||||
info.title = details.title;
|
||||
info.artist = details.author;
|
||||
if (details.lengthSeconds.has_value()) {
|
||||
info.duration = std::chrono::milliseconds(*details.lengthSeconds * 1000);
|
||||
}
|
||||
info.source = TrackSource::YouTube;
|
||||
info.originalUrl = "https://youtube.com/watch?v=" + details.videoId;
|
||||
return info;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline TrackInfo ConvertToTrackInfo(const YouTubeSearchResult& result) {
|
||||
TrackInfo info;
|
||||
info.id = result.videoId;
|
||||
info.title = result.title;
|
||||
info.artist = result.channelTitle;
|
||||
if (result.duration.has_value()) {
|
||||
info.duration = std::chrono::milliseconds(*result.duration * 1000);
|
||||
}
|
||||
info.thumbnailUrl = result.thumbnailUrl;
|
||||
info.source = TrackSource::YouTube;
|
||||
info.originalUrl = "https://youtube.com/watch?v=" + result.videoId;
|
||||
return info;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline PlaylistInfo ConvertToPlaylistInfo(const YouTubePlaylist& playlist) {
|
||||
PlaylistInfo info;
|
||||
info.id = playlist.playlistId;
|
||||
info.name = playlist.title;
|
||||
info.owner = playlist.author;
|
||||
// Convert playlist items to tracks
|
||||
for (const auto& item : playlist.videos) {
|
||||
TrackInfo track;
|
||||
track.id = item.videoId;
|
||||
track.title = item.title;
|
||||
track.source = TrackSource::YouTube;
|
||||
track.originalUrl = "https://youtube.com/watch?v=" + item.videoId;
|
||||
if (item.duration.has_value()) {
|
||||
track.duration = std::chrono::milliseconds(*item.duration * 1000);
|
||||
}
|
||||
track.thumbnailUrl = item.thumbnailUrl;
|
||||
info.tracks.push_back(std::move(track));
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,122 @@
|
||||
#pragma once
|
||||
|
||||
#include <MemoryPool.hpp>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
enum class AudioFormat : uint8_t {
|
||||
Unknown = 0,
|
||||
MP3,
|
||||
AAC,
|
||||
Opus,
|
||||
Vorbis,
|
||||
FLAC,
|
||||
WAV
|
||||
};
|
||||
|
||||
enum class AudioQuality : uint8_t {
|
||||
Low = 0, // 64-96 kbps
|
||||
Medium, // 128-160 kbps
|
||||
High, // 192-256 kbps
|
||||
VeryHigh, // 320 kbps
|
||||
Lossless // FLAC or equivalent
|
||||
};
|
||||
|
||||
// Hardware acceleration types
|
||||
enum class HwAccelType : uint8_t {
|
||||
None = 0,
|
||||
CUDA, // NVIDIA CUDA
|
||||
VAAPI, // Video Acceleration API (Linux)
|
||||
DXVA2, // DirectX Video Acceleration 2 (Windows)
|
||||
D3D11VA, // Direct3D 11 Video Acceleration
|
||||
VideoToolbox, // Apple VideoToolbox
|
||||
Vulkan // Vulkan Video
|
||||
};
|
||||
|
||||
struct AudioFrame {
|
||||
std::vector<uint8_t> data;
|
||||
std::chrono::milliseconds pts;
|
||||
std::chrono::milliseconds duration;
|
||||
bool isKeyFrame;
|
||||
};
|
||||
|
||||
struct AudioStreamInfo {
|
||||
AudioFormat format;
|
||||
uint32_t sampleRate;
|
||||
uint32_t channels;
|
||||
uint32_t bitrate;
|
||||
std::chrono::milliseconds duration;
|
||||
std::optional<AudioQuality> quality;
|
||||
bool hwAccelerated = false;
|
||||
HwAccelType hwAccelType = HwAccelType::None;
|
||||
};
|
||||
|
||||
// Zero-copy decoded audio using pooled memory (int16 for direct playback)
|
||||
struct DecodedAudio {
|
||||
// Use pooled buffer instead of std::vector for zero-copy
|
||||
// Now using int16_t for direct TeamSpeak compatibility (no float
|
||||
// conversion)
|
||||
std::vector<int16_t> samples;
|
||||
|
||||
// Non-owning view into the data
|
||||
Int16AudioView view;
|
||||
|
||||
uint32_t sampleRate;
|
||||
uint32_t channels;
|
||||
std::chrono::milliseconds timestamp;
|
||||
|
||||
// Backwards compatibility - returns the samples
|
||||
[[nodiscard]] std::vector<int16_t> getSamples() const
|
||||
{
|
||||
return samples;
|
||||
}
|
||||
|
||||
// Check if valid
|
||||
[[nodiscard]] bool isValid() const { return !samples.empty(); }
|
||||
|
||||
// Apply volume in-place (int16 version)
|
||||
void applyVolume(float volume)
|
||||
{
|
||||
if (samples.empty()) {
|
||||
return;
|
||||
}
|
||||
int32_t volInt = static_cast<int32_t>(volume * 32768);
|
||||
for (auto& sample : samples) {
|
||||
int32_t scaled =
|
||||
(static_cast<int32_t>(sample) * volInt) / 32768;
|
||||
sample =
|
||||
static_cast<int16_t>(std::clamp(scaled, -32768, 32767));
|
||||
}
|
||||
// Update view to point to new data
|
||||
view = Int16AudioView(samples.data(), samples.size(), channels);
|
||||
}
|
||||
};
|
||||
|
||||
// Hardware acceleration configuration
|
||||
struct HwAccelConfig {
|
||||
HwAccelType type = HwAccelType::None;
|
||||
int deviceIndex = -1; // -1 for auto-select
|
||||
std::optional<std::string> deviceName;
|
||||
|
||||
[[nodiscard]] bool isEnabled() const
|
||||
{
|
||||
return type != HwAccelType::None;
|
||||
}
|
||||
};
|
||||
|
||||
// Audio processing options
|
||||
struct AudioProcessOptions {
|
||||
float volume = 1.0f;
|
||||
bool normalize = false;
|
||||
bool highPassFilter = false; // Remove DC offset
|
||||
float highPassFreq = 20.0f; // Hz
|
||||
bool limiter = false; // Prevent clipping
|
||||
float limiterThreshold = 0.95f;
|
||||
};
|
||||
|
||||
using AudioBuffer = std::vector<uint8_t>;
|
||||
using AudioFramePtr = std::shared_ptr<AudioFrame>;
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
// Opaque state blob - contents are internal to Core
|
||||
// Plugin should NEVER inspect or modify the data field
|
||||
struct StateBlob {
|
||||
std::vector<uint8_t>
|
||||
data; // Serialized state data (JSON using glaze)
|
||||
uint32_t version = 0; // Format version (for logging/debugging only)
|
||||
std::string timestamp; // ISO 8601 timestamp when saved
|
||||
|
||||
bool empty() const { return data.empty(); }
|
||||
size_t size() const { return data.size(); }
|
||||
|
||||
// Clear the state
|
||||
void clear()
|
||||
{
|
||||
data.clear();
|
||||
version = 0;
|
||||
timestamp.clear();
|
||||
}
|
||||
};
|
||||
|
||||
// Constants for state management
|
||||
constexpr uint32_t MAX_SUPPORTED_STATE_VERSION_AGE =
|
||||
10; // Support 10 versions back
|
||||
constexpr uint32_t STATE_VERSION_NONE = 0;
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,151 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <format>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
// Version constants
|
||||
inline constexpr uint32_t VERSION_MAJOR = 1;
|
||||
inline constexpr uint32_t VERSION_MINOR = 1;
|
||||
inline constexpr uint32_t VERSION_PATCH = 1;
|
||||
inline constexpr const char* VERSION_STRING = "1.1.1";
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
enum class ErrorCode : uint32_t {
|
||||
Success = 0,
|
||||
InvalidArgument,
|
||||
NotFound,
|
||||
AlreadyExists,
|
||||
NetworkError,
|
||||
ParseError,
|
||||
AudioError,
|
||||
PluginError,
|
||||
InvalidUrl,
|
||||
NotAuthenticated,
|
||||
Unauthorized,
|
||||
PermissionDenied,
|
||||
ServiceUnavailable,
|
||||
DatabaseError,
|
||||
NotSupported,
|
||||
NotInitialized,
|
||||
IncompatibleVersion, // State version incompatible
|
||||
UnknownError
|
||||
};
|
||||
|
||||
struct Error {
|
||||
ErrorCode code = ErrorCode::UnknownError;
|
||||
std::string message;
|
||||
std::string source;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
// Optional underlying cause (set via with_context), forming a chain.
|
||||
std::shared_ptr<const Error> cause;
|
||||
|
||||
Error() = default;
|
||||
Error(ErrorCode c, std::string_view msg, std::string_view src = "")
|
||||
: code(c), message(msg), source(src),
|
||||
timestamp(std::chrono::system_clock::now())
|
||||
{
|
||||
}
|
||||
|
||||
// Void::Result context API: wrap this error as the cause of a new
|
||||
// contextual layer, preserving the original ErrorCode and source.
|
||||
[[nodiscard]] Error with_context(std::string ctx) const&
|
||||
{
|
||||
Error e(code, ctx, source);
|
||||
e.cause = std::make_shared<const Error>(*this);
|
||||
return e;
|
||||
}
|
||||
[[nodiscard]] Error with_context(std::string ctx) &&
|
||||
{
|
||||
Error e(code, ctx, source);
|
||||
e.cause = std::make_shared<const Error>(std::move(*this));
|
||||
return e;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string toString() const
|
||||
{
|
||||
std::string out =
|
||||
std::format("[{}] {} (from: {})",
|
||||
static_cast<uint32_t>(code), message, source);
|
||||
for (const Error* c = cause.get(); c; c = c->cause.get()) {
|
||||
out += std::format("\n caused by: {}", c->message);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
// Result<T> aliases Void::Result with Echoion's domain Error (which keeps
|
||||
// the ErrorCode used across RPC and error handling). Void::Result::Result
|
||||
// is itself std::expected<T, E>, so existing call sites are unaffected and
|
||||
// Void::Result::ok/fail/with_context all work with Api::Error.
|
||||
template <typename T>
|
||||
using Result = Void::Result::Result<T, Error>;
|
||||
|
||||
// Concise failure factory: `return Api::fail(ErrorCode::X, "msg")` instead
|
||||
// of `return std::unexpected(Api::Error(ErrorCode::X, "msg"))`. Carries the
|
||||
// domain ErrorCode, so it cannot defer to Void::Result::fail (which builds a
|
||||
// code-less Void::Result::Error).
|
||||
[[nodiscard]] inline std::unexpected<Error> fail(ErrorCode code,
|
||||
std::string_view message,
|
||||
std::string_view source = "")
|
||||
{
|
||||
return std::unexpected(Error(code, message, source));
|
||||
}
|
||||
|
||||
enum class LogLevel : uint8_t { Debug = 0, Info, Warning, Error, Critical };
|
||||
|
||||
inline constexpr std::string LogLevelToString(const LogLevel level) noexcept
|
||||
{
|
||||
switch (level) {
|
||||
|
||||
case LogLevel::Debug:
|
||||
return "Debug";
|
||||
case LogLevel::Info:
|
||||
return "Info";
|
||||
case LogLevel::Warning:
|
||||
return "Warning";
|
||||
case LogLevel::Error:
|
||||
return "Error";
|
||||
case LogLevel::Critical:
|
||||
return "Critical";
|
||||
}
|
||||
}
|
||||
inline constexpr LogLevel StringToLogLevel(const std::string level) noexcept
|
||||
{
|
||||
if (level == "Info") {
|
||||
return LogLevel::Info;
|
||||
} else if (level == "Warning") {
|
||||
return LogLevel::Warning;
|
||||
|
||||
} else if (level == "Error") {
|
||||
return LogLevel::Error;
|
||||
|
||||
} else if (level == "Critical") {
|
||||
return LogLevel::Critical;
|
||||
}
|
||||
return LogLevel::Debug;
|
||||
}
|
||||
|
||||
struct LogEntry {
|
||||
LogLevel level;
|
||||
std::string message;
|
||||
std::string source;
|
||||
std::string sourceFile;
|
||||
uint32_t sourceLine = 0;
|
||||
std::string function;
|
||||
std::thread::id threadId;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,94 @@
|
||||
#pragma once
|
||||
#include "ConfigTypes.hpp"
|
||||
#include <atomic>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <shared_mutex>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
class ConfigManager
|
||||
{
|
||||
public:
|
||||
|
||||
using ConfigChangedCallback = std::function<void(const AppConfig&)>;
|
||||
|
||||
// Owned by Core and provided through the service registry — no
|
||||
// global singleton.
|
||||
ConfigManager() = default;
|
||||
|
||||
// Delete copy/move
|
||||
ConfigManager(const ConfigManager&) = delete;
|
||||
ConfigManager& operator=(const ConfigManager&) = delete;
|
||||
|
||||
// Initialize with config file path (call once at startup)
|
||||
[[nodiscard]] bool
|
||||
initialize(const std::filesystem::path& configPath);
|
||||
|
||||
// Initialize with default path (~/.config/echoion/config.json)
|
||||
[[nodiscard]] bool initialize();
|
||||
|
||||
// Get current config (thread-safe)
|
||||
[[nodiscard]] AppConfig getConfig() const;
|
||||
|
||||
// Get config by reference (faster, but hold lock briefly)
|
||||
template <typename Func>
|
||||
auto withConfig(Func&& func) const
|
||||
-> decltype(func(std::declval<const AppConfig&>()))
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return func(config_);
|
||||
}
|
||||
|
||||
// Direct accessors for config sections (convenience methods)
|
||||
[[nodiscard]] const BotConfig& getBot() const;
|
||||
[[nodiscard]] const YouTubeConfig& getYouTube() const;
|
||||
[[nodiscard]] const NetworkConfig& getNetwork() const;
|
||||
[[nodiscard]] const SourcesConfig& getSources() const;
|
||||
[[nodiscard]] const TeamSpeakConfig& getTeamSpeak() const;
|
||||
[[nodiscard]] const SecurityConfig& getSecurity() const;
|
||||
[[nodiscard]] const FeaturesConfig& getFeatures() const;
|
||||
[[nodiscard]] const AdvancedConfig& getAdvanced() const;
|
||||
|
||||
// Reload configuration from file
|
||||
[[nodiscard]] bool reload();
|
||||
|
||||
// Save current configuration to file
|
||||
[[nodiscard]] bool save();
|
||||
|
||||
// Update config (and optionally save)
|
||||
void updateConfig(const AppConfig& config, bool saveToFile = true);
|
||||
|
||||
// Check if initialized
|
||||
[[nodiscard]] bool isInitialized() const;
|
||||
|
||||
// Get config file path
|
||||
[[nodiscard]] std::filesystem::path getConfigPath() const;
|
||||
|
||||
// Get default config path (~/.config/echoion/config.json)
|
||||
[[nodiscard]] static std::filesystem::path getDefaultConfigPath();
|
||||
|
||||
// Subscribe to config changes
|
||||
void onConfigChanged(ConfigChangedCallback callback);
|
||||
|
||||
// Create default config file if it doesn't exist
|
||||
[[nodiscard]] bool createDefaultConfigIfNeeded();
|
||||
|
||||
private:
|
||||
|
||||
mutable std::shared_mutex mutex_;
|
||||
AppConfig config_;
|
||||
std::filesystem::path configPath_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
std::vector<ConfigChangedCallback> callbacks_;
|
||||
mutable std::shared_mutex callbackMutex_;
|
||||
|
||||
void notifyCallbacks();
|
||||
[[nodiscard]] bool loadFromFileInternal();
|
||||
[[nodiscard]] bool saveToFileInternal();
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,326 @@
|
||||
#pragma once
|
||||
#include "AudioTypes.hpp"
|
||||
#include "NetworkTypes.hpp"
|
||||
#include "Types.hpp"
|
||||
#include <chrono>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
using ConfigValue = std::variant<std::monostate, bool, int64_t, double,
|
||||
std::string, std::vector<std::string>>;
|
||||
|
||||
struct ConfigEntry {
|
||||
std::string key;
|
||||
ConfigValue value;
|
||||
std::string description;
|
||||
bool isSecret;
|
||||
std::optional<ConfigValue> defaultValue;
|
||||
std::optional<std::string> category;
|
||||
};
|
||||
|
||||
// Core Bot Settings
|
||||
struct BotConfig {
|
||||
std::string botName = "Echoion";
|
||||
std::string commandPrefix = "!";
|
||||
// Default bot language ("en" or "ru"). Applies to users who have
|
||||
// not picked a per-user language. Anything else normalises to "en".
|
||||
std::string language = "en";
|
||||
float defaultVolume = 0.5f;
|
||||
uint32_t maxQueueSize = 100;
|
||||
// How long the playback engine waits (emitting silence) for a
|
||||
// late stream resolve before skipping the track.
|
||||
std::chrono::milliseconds trackTimeout =
|
||||
std::chrono::milliseconds(10000);
|
||||
// Crossfade between tracks; 0 = plain gapless handoff.
|
||||
std::chrono::milliseconds crossfade = std::chrono::milliseconds(0);
|
||||
bool allowPlaylistImports = true;
|
||||
};
|
||||
|
||||
// YouTube Integration Settings
|
||||
struct YouTubeConfig {
|
||||
std::optional<std::string> youtubeApiKey;
|
||||
std::optional<std::string> youtubeCookiesPath;
|
||||
std::optional<std::string> cookiesFromBrowser;
|
||||
size_t ytDlpMaxConcurrent = 4;
|
||||
bool ytDlpAsyncEnabled = true;
|
||||
bool enableUrlShortening = true;
|
||||
};
|
||||
|
||||
// Network & Proxy Settings
|
||||
struct NetworkConfig {
|
||||
std::optional<Void::Net::ProxyConfig> proxy;
|
||||
bool rpcEnabled = true;
|
||||
uint16_t rpcPort = 8765;
|
||||
std::string rpcBindAddress = "127.0.0.1";
|
||||
};
|
||||
|
||||
// Browser web interface (EchoionWeb). Serves the public dashboard and
|
||||
// same-origin RPC bridge. Watch Together is deployed independently and
|
||||
// linked through watchUrl.
|
||||
struct WebConfig {
|
||||
bool enabled = false;
|
||||
uint16_t port = 8080;
|
||||
std::string bindAddress = "127.0.0.1";
|
||||
std::string webRoot = "./web";
|
||||
// Explicit RPC WebSocket URL the browser should use. When empty the
|
||||
// UI derives ws://<page-host>:<rpcPort> from the served config.
|
||||
std::string rpcUrl;
|
||||
// Public address users reach the web interface at (e.g.
|
||||
// "https://bot.example.com"). Required by the internal URL
|
||||
// shortener and also used by !help when set; serving is unaffected.
|
||||
std::string publicUrl;
|
||||
// External VoidWatch deployment. Echoion only presents this link
|
||||
// and redirects the retired local /watch entrypoint to it.
|
||||
std::string watchUrl;
|
||||
// Allow the Now Playing view to show the current song's video
|
||||
// (muted, synced). Users can still disable it locally; this is
|
||||
// the server-wide off switch, surfaced through /config.json.
|
||||
bool nowPlayingVideo = true;
|
||||
// Forwarded client addresses are trusted only when the immediate
|
||||
// peer belongs to one of these IPv4/IPv6 CIDRs. Empty is safest and
|
||||
// ignores X-Forwarded-For entirely.
|
||||
std::vector<std::string> trustedProxyCidrs;
|
||||
};
|
||||
|
||||
struct UrlShorteningConfig {
|
||||
bool enabled = false;
|
||||
std::string provider = "url-shortener-internal";
|
||||
std::vector<std::string> sources = {"youtube"};
|
||||
std::chrono::milliseconds timeout = std::chrono::milliseconds(3000);
|
||||
};
|
||||
|
||||
struct PluginsConfig {
|
||||
// Empty resolves to a plugins.d directory beside the main config.
|
||||
std::string configDirectory;
|
||||
};
|
||||
|
||||
// Music source resolution chain. Default order tries the native
|
||||
// innertube YouTube path and Yandex Music first, then falls back to
|
||||
// (optionally proxied) yt-dlp last.
|
||||
struct SourcesConfig {
|
||||
std::vector<std::string> order = {"innertube", "yandex",
|
||||
"direct-url", "ytdlp-direct",
|
||||
"ytdlp-proxied"};
|
||||
// How long a failing source is skipped before being retried.
|
||||
std::chrono::milliseconds failureCooldown =
|
||||
std::chrono::milliseconds(300000); // 5m
|
||||
// Hedged stream resolution: when the first source hasn't
|
||||
// answered within this delay, the second candidate races it
|
||||
// (first success wins). 0 disables hedging.
|
||||
std::chrono::milliseconds hedgeDelay =
|
||||
std::chrono::milliseconds(300);
|
||||
// Native innertube player API (fastest YouTube path; one HTTP
|
||||
// POST). youtubei is geo-blocked without a proxy, so with
|
||||
// requireProxy the source is skipped when none is configured.
|
||||
bool innertubeEnabled = true;
|
||||
bool innertubeRequireProxy = true;
|
||||
// Native Yandex Music (unofficial API). Full tracks require an
|
||||
// OAuth token from an account with Plus; without one, yandex
|
||||
// URLs fall back to ytdlp-direct.
|
||||
bool yandexEnabled = true;
|
||||
std::optional<std::string> yandexToken;
|
||||
};
|
||||
|
||||
// TeamSpeak Server Connection
|
||||
struct TeamSpeakConfig {
|
||||
std::string address = "localhost";
|
||||
uint16_t port = 9987;
|
||||
std::string serverPassword;
|
||||
std::string nickname = "EchoionBot";
|
||||
std::optional<std::string> defaultChannelId;
|
||||
std::optional<std::string> channelPassword;
|
||||
std::vector<uint64_t> adminGroups;
|
||||
std::vector<uint64_t> djGroups;
|
||||
std::vector<uint64_t> bannedGroups;
|
||||
};
|
||||
|
||||
// Security & Authentication
|
||||
struct SecurityConfig {
|
||||
bool requireAuthForAdmin = true;
|
||||
uint32_t maxLoginAttempts = 5;
|
||||
std::chrono::milliseconds lockoutDuration =
|
||||
std::chrono::milliseconds(300000);
|
||||
std::chrono::milliseconds sessionTimeout =
|
||||
std::chrono::milliseconds(3600000);
|
||||
bool enableAuditLog = true;
|
||||
std::optional<std::string> apiKey;
|
||||
// Reserved, not currently honored: the web UI and /rpc bridge are
|
||||
// same-origin behind the web server, so no CORS headers are
|
||||
// emitted.
|
||||
bool allowCors = false;
|
||||
std::vector<std::string> corsOrigins;
|
||||
};
|
||||
|
||||
// Feature Toggles
|
||||
struct FeaturesConfig {
|
||||
bool enableHotReload = true;
|
||||
bool enableAutoReload = false;
|
||||
bool enableAutoUpdateCheck = true;
|
||||
|
||||
// Playback behavior
|
||||
bool autoStartOnSubscribe = true;
|
||||
bool pauseOnEmptySubscribers = true;
|
||||
bool resumeOnSubscriberReturn = true;
|
||||
// Radio mode: when the queue runs dry, enqueue tracks related to
|
||||
// the last played one (via Invidious recommendations).
|
||||
bool autoplay = false;
|
||||
|
||||
// Loudness normalization: slow AGC toward the target RMS level
|
||||
// so quiet and loud tracks play back at a similar volume.
|
||||
bool normalizeLoudness = false;
|
||||
float targetLoudnessDb = -14.0f;
|
||||
|
||||
// Queue management: initial state on cold start ("off"/"random",
|
||||
// "off"/"all"). Runtime toggles are not written back.
|
||||
std::string shuffleMode = "off";
|
||||
std::string repeatMode = "off";
|
||||
uint32_t maxHistorySize = 50;
|
||||
|
||||
// Vote-to-skip: votes needed to skip the current track.
|
||||
// 0 = majority of online subscribers.
|
||||
uint32_t voteSkipThreshold = 0;
|
||||
};
|
||||
|
||||
// Advanced Settings
|
||||
struct AdvancedConfig {
|
||||
// Local audio track cache (downloaded/streamed files reused
|
||||
// across plays and restarts).
|
||||
bool cacheEnabled = true;
|
||||
std::string cacheMaxSize = "1GB";
|
||||
uint32_t cacheTTL = 86400; // seconds
|
||||
uint32_t tempCleanupInterval = 3600; // seconds
|
||||
};
|
||||
|
||||
// Process logging. The active file is always archived at process startup,
|
||||
// then rotated by size while the bot is running.
|
||||
struct LoggingConfig {
|
||||
bool console = true;
|
||||
std::string level = "debug";
|
||||
std::string fileName = "echoion.log";
|
||||
uint64_t maxFileSizeBytes = 10 * 1024 * 1024;
|
||||
uint32_t maxFiles = 10;
|
||||
};
|
||||
|
||||
// Component updater. Runtime means the complete relocatable daemon bundle,
|
||||
// not only the echoiond ELF. Core and managed extension plugins may use
|
||||
// independent channels, but the updater still enforces the compatibility
|
||||
// metadata carried by the selected feed releases.
|
||||
struct UpdatePublicKey {
|
||||
std::string id;
|
||||
std::string ed25519;
|
||||
};
|
||||
|
||||
struct UpdateSourceConfig {
|
||||
// "direct" addresses one feed document. "component-layout"
|
||||
// addresses a channel root containing catalog.json and component
|
||||
// discovery documents.
|
||||
std::string kind = "direct";
|
||||
// Empty is only meaningful for the built-in "official" source and
|
||||
// resolves to the URL injected by the release build.
|
||||
std::string url;
|
||||
std::vector<UpdatePublicKey> publicKeys;
|
||||
bool allowUnsigned = false;
|
||||
// Environment variable name only. Secret values are never
|
||||
// persisted.
|
||||
std::string bearerTokenEnv;
|
||||
};
|
||||
|
||||
struct UpdateComponentConfig {
|
||||
bool enabled = true;
|
||||
std::string source = "official";
|
||||
std::string channel = "stable";
|
||||
bool autoApply = true;
|
||||
};
|
||||
|
||||
struct PluginUpdateOverride {
|
||||
std::string source = "official";
|
||||
std::string channel = "stable";
|
||||
bool autoApply = true;
|
||||
};
|
||||
|
||||
struct PluginUpdatesConfig {
|
||||
bool enabled = true;
|
||||
std::string source = "official";
|
||||
std::string channel = "stable";
|
||||
bool autoApply = true;
|
||||
bool managedOnly = true;
|
||||
std::map<std::string, PluginUpdateOverride> overrides;
|
||||
};
|
||||
|
||||
struct UpdateMaintenanceWindow {
|
||||
// HH:MM in UTC. The updater validates the value before saving it.
|
||||
std::string start = "03:00";
|
||||
std::chrono::milliseconds duration = std::chrono::hours(2);
|
||||
};
|
||||
|
||||
struct UpdatesConfig {
|
||||
bool enabled = true;
|
||||
std::chrono::milliseconds checkInterval = std::chrono::hours(6);
|
||||
std::chrono::milliseconds jitter = std::chrono::minutes(30);
|
||||
UpdateMaintenanceWindow maintenanceWindowUtc;
|
||||
std::chrono::milliseconds maxRuntimeDeferral =
|
||||
std::chrono::hours(24);
|
||||
// Number of previous healthy versions retained in addition to
|
||||
// active.
|
||||
uint32_t retainHealthyVersions = 2;
|
||||
std::map<std::string, UpdateSourceConfig> sources = {{
|
||||
"official",
|
||||
UpdateSourceConfig{.kind = "component-layout",
|
||||
.url = {},
|
||||
.publicKeys = {},
|
||||
.allowUnsigned = false,
|
||||
.bearerTokenEnv = {}},
|
||||
}};
|
||||
UpdateComponentConfig runtime;
|
||||
UpdateComponentConfig core;
|
||||
PluginUpdatesConfig plugins;
|
||||
};
|
||||
|
||||
// Connection settings passed across the Echoion host interface.
|
||||
struct ServerConfig {
|
||||
std::string address;
|
||||
uint16_t port = 0;
|
||||
std::string serverPassword;
|
||||
std::string nickname;
|
||||
std::optional<std::string> defaultChannelId;
|
||||
std::optional<std::string> channelPassword;
|
||||
std::vector<uint64_t> adminGroups;
|
||||
std::vector<uint64_t> djGroups;
|
||||
std::vector<uint64_t> bannedGroups;
|
||||
};
|
||||
|
||||
struct AdminCredentials {
|
||||
std::string username;
|
||||
std::string passwordHash;
|
||||
std::optional<std::string> salt;
|
||||
std::vector<std::string> permissions;
|
||||
std::chrono::system_clock::time_point createdAt;
|
||||
std::optional<std::chrono::system_clock::time_point> lastLogin;
|
||||
bool isActive;
|
||||
};
|
||||
|
||||
struct AppConfig {
|
||||
BotConfig bot;
|
||||
YouTubeConfig youtube;
|
||||
NetworkConfig network;
|
||||
SourcesConfig sources;
|
||||
TeamSpeakConfig teamspeak;
|
||||
SecurityConfig security;
|
||||
FeaturesConfig features;
|
||||
AdvancedConfig advanced;
|
||||
LoggingConfig logging;
|
||||
UpdatesConfig updates;
|
||||
UrlShorteningConfig urlShortening;
|
||||
PluginsConfig plugins;
|
||||
AdminCredentials admin;
|
||||
WebConfig web;
|
||||
std::map<std::string, ConfigEntry> custom;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,370 @@
|
||||
#pragma once
|
||||
|
||||
#include "TrackTypes.hpp"
|
||||
#include "Types.hpp"
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <shared_mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
// Forward declaration
|
||||
class DatabaseImpl;
|
||||
|
||||
// Database configuration
|
||||
struct DatabaseConfig {
|
||||
std::string path = "echoion.db";
|
||||
bool walMode = true; // Write-Ahead Logging for better concurrency
|
||||
int maxConnections = 4;
|
||||
std::chrono::seconds busyTimeout{5000};
|
||||
};
|
||||
|
||||
// Playlist with tracks
|
||||
struct Playlist {
|
||||
uint64_t id;
|
||||
std::string name;
|
||||
std::string description;
|
||||
uint64_t createdBy;
|
||||
std::chrono::system_clock::time_point createdAt;
|
||||
std::chrono::system_clock::time_point updatedAt;
|
||||
std::vector<TrackInfo> tracks;
|
||||
bool isPublic = false;
|
||||
std::string externalId; // YouTube playlist ID, etc.
|
||||
};
|
||||
|
||||
// Playback history entry
|
||||
struct PlaybackHistoryEntry {
|
||||
uint64_t id;
|
||||
TrackInfo track;
|
||||
uint64_t playedBy;
|
||||
std::chrono::system_clock::time_point playedAt;
|
||||
std::chrono::milliseconds duration; // How long it played
|
||||
bool completed = false; // Did it play to the end
|
||||
};
|
||||
|
||||
// User favorites
|
||||
struct FavoriteTrack {
|
||||
TrackInfo track;
|
||||
uint64_t userId;
|
||||
std::chrono::system_clock::time_point addedAt;
|
||||
};
|
||||
|
||||
// Statistics
|
||||
struct PlaybackStatistics {
|
||||
uint64_t totalPlays = 0;
|
||||
uint64_t totalTracks = 0;
|
||||
uint64_t totalPlaytimeMs = 0;
|
||||
std::optional<TrackInfo> mostPlayedTrack;
|
||||
uint64_t mostPlayedCount = 0;
|
||||
};
|
||||
|
||||
// Server-wide aggregate statistics (web dashboard)
|
||||
struct AggregateStats {
|
||||
uint64_t tracksToday = 0; // completed plays today
|
||||
uint64_t listeningMsToday = 0; // summed play duration today
|
||||
uint64_t queueAdditionsToday = 0;
|
||||
uint64_t skipsToday = 0;
|
||||
uint64_t playsTotal = 0;
|
||||
uint64_t skipsTotal = 0;
|
||||
// Most active requesters, most additions first.
|
||||
struct TopRequester {
|
||||
std::string uid; // TeamSpeak uid (may be empty for old rows)
|
||||
std::string nickname;
|
||||
uint64_t count = 0;
|
||||
};
|
||||
std::vector<TopRequester> topRequesters;
|
||||
// Source split over the whole history
|
||||
uint64_t youtubeCount = 0;
|
||||
uint64_t yandexCount = 0;
|
||||
uint64_t otherCount = 0;
|
||||
};
|
||||
|
||||
// Main database interface
|
||||
class Database
|
||||
{
|
||||
public:
|
||||
|
||||
Database();
|
||||
~Database();
|
||||
|
||||
// Non-copyable
|
||||
Database(const Database&) = delete;
|
||||
Database& operator=(const Database&) = delete;
|
||||
|
||||
// Initialization
|
||||
Api::Result<void> initialize(const DatabaseConfig& config = {});
|
||||
void shutdown();
|
||||
[[nodiscard]] bool isInitialized() const;
|
||||
|
||||
// Migrations
|
||||
Api::Result<void> migrate(); // Run pending migrations
|
||||
[[nodiscard]] int getCurrentVersion() const;
|
||||
|
||||
// ===== Playlists =====
|
||||
|
||||
// Create a new playlist
|
||||
[[nodiscard]] Api::Result<uint64_t>
|
||||
createPlaylist(const std::string& name,
|
||||
const std::string& description,
|
||||
uint64_t createdBy,
|
||||
bool isPublic = false,
|
||||
const std::string& externalId = "");
|
||||
|
||||
// Get or create playlist by external ID (e.g., YouTube playlist ID)
|
||||
// Returns existing playlist ID if found, creates new one otherwise
|
||||
[[nodiscard]] Api::Result<uint64_t>
|
||||
getOrCreatePlaylistByExternalId(const std::string& externalId,
|
||||
const std::string& name,
|
||||
const std::string& description,
|
||||
uint64_t createdBy,
|
||||
bool isPublic = false);
|
||||
|
||||
// Get playlist by ID
|
||||
[[nodiscard]] Api::Result<std::optional<Playlist>>
|
||||
getPlaylist(uint64_t id);
|
||||
|
||||
// Get all playlists for a user
|
||||
[[nodiscard]] Api::Result<std::vector<Playlist>>
|
||||
getUserPlaylists(uint64_t userId);
|
||||
|
||||
// Get every playlist (used by the RPC GetPlaylists endpoint).
|
||||
[[nodiscard]] Api::Result<std::vector<Playlist>>
|
||||
getAllPlaylists();
|
||||
|
||||
// Update playlist
|
||||
Api::Result<void> updatePlaylist(
|
||||
uint64_t id,
|
||||
const std::optional<std::string>& name = std::nullopt,
|
||||
const std::optional<std::string>& description = std::nullopt,
|
||||
const std::optional<bool>& isPublic = std::nullopt);
|
||||
|
||||
// Delete playlist
|
||||
Api::Result<void> deletePlaylist(uint64_t id);
|
||||
|
||||
// Add track to playlist
|
||||
Api::Result<void> addTrackToPlaylist(uint64_t playlistId,
|
||||
const TrackInfo& track,
|
||||
uint32_t position = 0);
|
||||
|
||||
// Remove track from playlist
|
||||
Api::Result<void> removeTrackFromPlaylist(uint64_t playlistId,
|
||||
uint64_t trackId);
|
||||
|
||||
// Reorder playlist tracks
|
||||
Api::Result<void> reorderPlaylistTrack(uint64_t playlistId,
|
||||
uint64_t trackId,
|
||||
uint32_t newPosition);
|
||||
|
||||
// ===== Playback History =====
|
||||
|
||||
// Record a playback
|
||||
Api::Result<void> recordPlayback(const TrackInfo& track,
|
||||
uint64_t playedBy,
|
||||
std::chrono::milliseconds duration,
|
||||
bool completed);
|
||||
|
||||
// Get playback history for a user
|
||||
[[nodiscard]] Api::Result<std::vector<PlaybackHistoryEntry>>
|
||||
getPlaybackHistory(uint64_t userId,
|
||||
size_t limit = 100,
|
||||
size_t offset = 0);
|
||||
|
||||
// Get recently played tracks
|
||||
[[nodiscard]] Api::Result<std::vector<TrackInfo>>
|
||||
getRecentlyPlayed(uint64_t userId, size_t limit = 20);
|
||||
|
||||
// Record a skipped track (playback aborted by user action)
|
||||
Api::Result<void> recordSkip(const TrackInfo& track,
|
||||
uint64_t playedBy);
|
||||
|
||||
// Log a queue addition (daily stats / top requesters)
|
||||
Api::Result<void> logQueueAddition(const std::string& uid,
|
||||
const std::string& nickname);
|
||||
|
||||
// ===== Favorites =====
|
||||
|
||||
// Add track to favorites
|
||||
Api::Result<void> addFavorite(uint64_t userId,
|
||||
const TrackInfo& track);
|
||||
|
||||
// Remove track from favorites
|
||||
Api::Result<void> removeFavorite(uint64_t userId,
|
||||
const std::string& trackUrl);
|
||||
|
||||
// Check if track is favorited
|
||||
[[nodiscard]] Api::Result<bool>
|
||||
isFavorite(uint64_t userId, const std::string& trackUrl);
|
||||
|
||||
// Get all favorites for a user
|
||||
[[nodiscard]] Api::Result<std::vector<FavoriteTrack>>
|
||||
getFavorites(uint64_t userId);
|
||||
|
||||
// ===== Statistics =====
|
||||
|
||||
// Get playback statistics
|
||||
[[nodiscard]] Api::Result<PlaybackStatistics> getStatistics(
|
||||
uint64_t userId,
|
||||
std::optional<std::chrono::system_clock::time_point> since =
|
||||
std::nullopt);
|
||||
|
||||
// Get most played tracks
|
||||
[[nodiscard]] Api::Result<
|
||||
std::vector<std::pair<TrackInfo, uint64_t>>>
|
||||
getMostPlayed(uint64_t userId, size_t limit = 10);
|
||||
|
||||
// Get server-wide aggregate statistics (web dashboard)
|
||||
[[nodiscard]] Api::Result<AggregateStats> getAggregateStats();
|
||||
|
||||
// ===== Key/value store =====
|
||||
// Small persisted state (healthy instance lists, ...). Values
|
||||
// are opaque strings (callers serialize as needed).
|
||||
[[nodiscard]] Api::Result<std::optional<std::string>>
|
||||
getKv(const std::string& key);
|
||||
Api::Result<void> setKv(const std::string& key,
|
||||
const std::string& value);
|
||||
|
||||
// ===== Cached avatars (web UI) =====
|
||||
// TeamSpeak avatar images persisted by uid so the web UI can show
|
||||
// them even when the client is offline or out of the bot's view
|
||||
// (the live TS avatar cache only holds in-view clients). `data` is
|
||||
// base64-encoded image bytes.
|
||||
struct CachedAvatar {
|
||||
std::string uid;
|
||||
std::string mime;
|
||||
std::string dataBase64;
|
||||
// The source myTeamSpeak avatar URL, so an offline user's
|
||||
// avatar can be re-fetched even when the image bytes were
|
||||
// never stored. Empty for legacy/file avatars.
|
||||
std::string url;
|
||||
};
|
||||
// Image (mime + base64 data + url) for one uid, or nullopt if none.
|
||||
[[nodiscard]] Api::Result<std::optional<CachedAvatar>>
|
||||
getCachedAvatar(const std::string& uid);
|
||||
// Insert or replace the cached avatar image for a uid (keeps any
|
||||
// previously stored url).
|
||||
Api::Result<void> putCachedAvatar(const std::string& uid,
|
||||
const std::string& mime,
|
||||
const std::string& dataBase64);
|
||||
// Record just the source url for a uid (upsert), so it survives to
|
||||
// be re-fetched after the user goes offline.
|
||||
Api::Result<void> putCachedAvatarUrl(const std::string& uid,
|
||||
const std::string& url);
|
||||
|
||||
// ===== Subscriptions =====
|
||||
|
||||
// Subscriber info
|
||||
struct SubscriberInfo {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
std::chrono::system_clock::time_point subscribedAt;
|
||||
};
|
||||
|
||||
// Add a subscriber (by UID)
|
||||
Api::Result<void> addSubscriber(const std::string& uid,
|
||||
const std::string& nickname);
|
||||
|
||||
// Remove a subscriber (by UID)
|
||||
Api::Result<void> removeSubscriber(const std::string& uid);
|
||||
|
||||
// Check if client is subscribed (by UID)
|
||||
[[nodiscard]] Api::Result<bool>
|
||||
isSubscriber(const std::string& uid);
|
||||
|
||||
// Get all subscribers
|
||||
[[nodiscard]] Api::Result<std::vector<SubscriberInfo>>
|
||||
getAllSubscribers();
|
||||
|
||||
// Get subscriber count
|
||||
[[nodiscard]] Api::Result<size_t> getSubscriberCount();
|
||||
|
||||
// Clear all subscribers
|
||||
Api::Result<void> clearAllSubscribers();
|
||||
|
||||
// ===== RPC Authentication =====
|
||||
|
||||
// RPC token info
|
||||
struct RpcTokenInfo {
|
||||
std::string uid;
|
||||
std::string token;
|
||||
std::chrono::system_clock::time_point createdAt;
|
||||
std::chrono::system_clock::time_point lastUsedAt;
|
||||
bool isActive = true;
|
||||
};
|
||||
|
||||
// Generate new RPC token for subscriber
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
generateRpcToken(const std::string& uid);
|
||||
|
||||
// Get existing RPC token for subscriber (if any)
|
||||
[[nodiscard]] Api::Result<std::optional<std::string>>
|
||||
getExistingRpcToken(const std::string& uid);
|
||||
|
||||
// Validate RPC token
|
||||
[[nodiscard]] Api::Result<bool>
|
||||
validateRpcToken(const std::string& token);
|
||||
|
||||
// Get UID from RPC token
|
||||
[[nodiscard]] Api::Result<std::optional<std::string>>
|
||||
getUidFromRpcToken(const std::string& token);
|
||||
|
||||
// Revoke RPC token
|
||||
Api::Result<void> revokeRpcToken(const std::string& token);
|
||||
|
||||
// Get subscriber UID by nickname (case-insensitive)
|
||||
[[nodiscard]] Api::Result<std::optional<std::string>>
|
||||
getSubscriberByNickname(const std::string& nickname);
|
||||
|
||||
// Get all subscriber UIDs
|
||||
[[nodiscard]] Api::Result<std::vector<std::string>>
|
||||
getAllSubscriberUids();
|
||||
|
||||
// ===== Cache Management =====
|
||||
|
||||
// Clear old history (keep last N entries)
|
||||
Api::Result<void> trimHistory(size_t keepCount = 10000);
|
||||
|
||||
// Clear all data for a user
|
||||
Api::Result<void> clearUserData(uint64_t userId);
|
||||
|
||||
// Vacuum database (reclaim space)
|
||||
Api::Result<void> vacuum();
|
||||
|
||||
// ===== Raw Query (for advanced use) =====
|
||||
|
||||
using RowCallback = std::function<void(
|
||||
const std::vector<std::optional<std::string>>&)>;
|
||||
Api::Result<void> executeQuery(const std::string& sql,
|
||||
RowCallback callback = nullptr);
|
||||
|
||||
private:
|
||||
|
||||
std::unique_ptr<DatabaseImpl> impl_;
|
||||
mutable std::shared_mutex
|
||||
mutex_; // Shared mutex for read/write concurrency
|
||||
std::atomic<bool> shutdown_{
|
||||
false}; // Flag to prevent operations after shutdown
|
||||
};
|
||||
|
||||
// Database manager (singleton)
|
||||
class DatabaseManager
|
||||
{
|
||||
public:
|
||||
|
||||
static Database& instance();
|
||||
|
||||
static Api::Result<void>
|
||||
initialize(const DatabaseConfig& config = {});
|
||||
static void shutdown();
|
||||
|
||||
private:
|
||||
|
||||
DatabaseManager() = default;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,148 @@
|
||||
#pragma once
|
||||
|
||||
// Domain event types published on the application event bus. The bus itself
|
||||
// is Void::EventBus::EventBus (owned by Core); there is no echoion wrapper.
|
||||
|
||||
#include "ConfigTypes.hpp"
|
||||
#include "PluginTypes.hpp"
|
||||
#include "TrackTypes.hpp"
|
||||
#include "Types.hpp"
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Api::Events
|
||||
{
|
||||
|
||||
// Playback events
|
||||
struct PlaybackStarted {
|
||||
TrackInfo track;
|
||||
uint64_t clientId;
|
||||
std::chrono::milliseconds position;
|
||||
};
|
||||
|
||||
struct PlaybackPaused {
|
||||
TrackInfo track;
|
||||
std::chrono::milliseconds position;
|
||||
};
|
||||
|
||||
struct PlaybackResumed {
|
||||
TrackInfo track;
|
||||
std::chrono::milliseconds position;
|
||||
};
|
||||
|
||||
struct PlaybackStopped {
|
||||
std::optional<TrackInfo> lastTrack;
|
||||
std::chrono::milliseconds finalPosition;
|
||||
};
|
||||
|
||||
struct PlaybackPositionChanged {
|
||||
TrackInfo track;
|
||||
std::chrono::milliseconds position;
|
||||
std::chrono::milliseconds duration;
|
||||
float progressPercent; // 0.0 - 100.0
|
||||
};
|
||||
|
||||
struct TrackFinished {
|
||||
TrackInfo track;
|
||||
bool autoSkipped;
|
||||
std::chrono::milliseconds finalPosition;
|
||||
};
|
||||
|
||||
struct VolumeChanged {
|
||||
float oldVolume;
|
||||
float newVolume;
|
||||
uint64_t changedByClientId;
|
||||
};
|
||||
|
||||
struct ShuffleChanged {
|
||||
bool enabled;
|
||||
uint64_t changedByClientId;
|
||||
};
|
||||
|
||||
struct RepeatChanged {
|
||||
bool enabled;
|
||||
uint64_t changedByClientId;
|
||||
};
|
||||
|
||||
// Queue events
|
||||
struct TrackQueued {
|
||||
TrackInfo track;
|
||||
uint64_t queueId;
|
||||
uint64_t addedByClientId;
|
||||
uint32_t position;
|
||||
uint32_t queueLength;
|
||||
};
|
||||
|
||||
struct TrackRemoved {
|
||||
TrackInfo track;
|
||||
uint64_t queueId;
|
||||
uint64_t removedByClientId;
|
||||
uint32_t queueLength;
|
||||
};
|
||||
|
||||
struct QueueCleared {
|
||||
uint64_t clearedByClientId;
|
||||
uint32_t previousLength;
|
||||
};
|
||||
|
||||
struct QueueShuffled {
|
||||
uint64_t triggeredByClientId;
|
||||
};
|
||||
|
||||
struct QueueReordered {
|
||||
uint64_t queueId;
|
||||
uint32_t oldPosition;
|
||||
uint32_t newPosition;
|
||||
uint64_t changedByClientId;
|
||||
};
|
||||
|
||||
// Playlist events
|
||||
struct PlaylistLoadStarted {
|
||||
std::string playlistId;
|
||||
uint64_t requestedByClientId;
|
||||
uint64_t databasePlaylistId = 0;
|
||||
};
|
||||
|
||||
struct PlaylistTrackLoaded {
|
||||
std::string playlistId;
|
||||
TrackInfo track;
|
||||
uint32_t loadedCount;
|
||||
uint32_t totalCount;
|
||||
uint64_t databasePlaylistId = 0;
|
||||
};
|
||||
|
||||
struct PlaylistLoadCompleted {
|
||||
std::string playlistId;
|
||||
uint32_t totalTracksLoaded;
|
||||
bool success;
|
||||
std::optional<std::string> error;
|
||||
};
|
||||
|
||||
// Subscription events
|
||||
struct UserSubscribed {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
uint64_t clientId;
|
||||
};
|
||||
|
||||
struct UserUnsubscribed {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
uint64_t clientId;
|
||||
};
|
||||
|
||||
// Error events
|
||||
struct PlaybackError {
|
||||
ErrorCode code;
|
||||
std::string message;
|
||||
std::optional<TrackInfo> track;
|
||||
};
|
||||
|
||||
// Configuration events
|
||||
struct ConfigReloaded {
|
||||
BotConfig newConfig;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api::Events
|
||||
@@ -0,0 +1,176 @@
|
||||
#pragma once
|
||||
|
||||
#include "OpaqueHandle.hpp"
|
||||
#include "PluginTypes.hpp"
|
||||
#include "StateBlob.hpp"
|
||||
#include "Types.hpp"
|
||||
#include <PluginInterface.hpp>
|
||||
#include <expected>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
// Forward declarations - Core provides implementations
|
||||
struct TrackInfo;
|
||||
struct QueueEntry;
|
||||
struct PlaylistInfo;
|
||||
|
||||
// Minimal playback state for the host boundary.
|
||||
struct PlaybackSummary {
|
||||
std::optional<TrackSummary> currentTrack;
|
||||
bool isPlaying = false;
|
||||
bool isPaused = false;
|
||||
std::chrono::milliseconds position{0};
|
||||
float volume = 0.5f;
|
||||
bool repeat = false;
|
||||
bool shuffle = false;
|
||||
};
|
||||
|
||||
// Callback types for async operations
|
||||
using TrackCallback = std::function<void(const TrackSummary&)>;
|
||||
using StateCallback = std::function<void(const PlaybackSummary&)>;
|
||||
|
||||
// Forward declarations
|
||||
class ICoreInterface;
|
||||
using CoreInterfacePtr = std::shared_ptr<ICoreInterface>;
|
||||
using CoreCreateFunc = std::function<CoreInterfacePtr()>;
|
||||
using CoreDestroyFunc = std::function<void(ICoreInterface*)>;
|
||||
|
||||
// Core interface used by the standalone host to communicate with Core.
|
||||
// MINIMAL VERSION - breaks dependencies on Core-specific types
|
||||
class ICoreInterface
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~ICoreInterface() = default;
|
||||
|
||||
// Lifecycle
|
||||
// The host passes a config path; Core loads it internally.
|
||||
virtual Result<void>
|
||||
initialize(const std::filesystem::path& configPath) = 0;
|
||||
virtual Result<void> shutdown() = 0;
|
||||
virtual bool isInitialized() const noexcept = 0;
|
||||
|
||||
// Playback control - using string identifiers instead of TrackInfo
|
||||
virtual Result<void> play(const std::string& trackId) = 0;
|
||||
virtual Result<void> pause() = 0;
|
||||
virtual Result<void> resume() = 0;
|
||||
virtual Result<void> stop() = 0;
|
||||
virtual Result<void> skip(uint32_t count = 1) = 0;
|
||||
virtual Result<void> seek(std::chrono::milliseconds position) = 0;
|
||||
virtual Result<void> setVolume(float volume) = 0;
|
||||
|
||||
// Queue management - using string identifiers
|
||||
virtual Result<uint64_t> queueTrack(const std::string& trackId,
|
||||
uint64_t clientId) = 0;
|
||||
virtual Result<void> removeFromQueue(uint64_t queueId) = 0;
|
||||
virtual Result<void> clearQueue() = 0;
|
||||
|
||||
virtual Result<void> moveInQueue(uint64_t queueId,
|
||||
uint32_t newPosition) = 0;
|
||||
|
||||
// Track info - return summaries instead of full TrackInfo
|
||||
[[nodiscard]] virtual Result<std::optional<TrackSummary>>
|
||||
getCurrentTrackSummary() const = 0;
|
||||
[[nodiscard]] virtual Result<PlaybackSummary>
|
||||
getPlaybackSummary() const = 0;
|
||||
|
||||
// Playlist - using string identifiers
|
||||
virtual Result<void> loadPlaylist(const std::string& playlistId,
|
||||
uint64_t clientId) = 0;
|
||||
[[nodiscard]] virtual Result<std::vector<std::string>>
|
||||
getPlaylistIds() const = 0;
|
||||
|
||||
// Configuration - using serialization instead of AppConfig
|
||||
// Plugin sends JSON string, Core parses internally
|
||||
virtual Result<void>
|
||||
updateConfigJson(const std::string& configJson) = 0;
|
||||
[[nodiscard]] virtual Result<std::string> getConfigJson() const = 0;
|
||||
|
||||
// Hot reload - using serialization instead of HotReloadState
|
||||
// Returns opaque handle that Plugin just passes back
|
||||
[[nodiscard]] virtual Result<std::string> prepareForHotReload() = 0;
|
||||
virtual Result<void>
|
||||
restoreAfterHotReload(const std::string& state) = 0;
|
||||
|
||||
// Decoupled state management - Plugin never knows state internals
|
||||
// Core handles all serialization/deserialization internally
|
||||
// State format can change without Plugin rebuild
|
||||
[[nodiscard]] virtual StateBlob saveState() = 0;
|
||||
virtual Result<void> restoreState(const StateBlob& state) = 0;
|
||||
|
||||
// Version info for state compatibility checking
|
||||
[[nodiscard]] virtual uint32_t getStateFormatVersion() const = 0;
|
||||
[[nodiscard]] virtual bool
|
||||
canRestoreStateVersion(uint32_t version) const = 0;
|
||||
|
||||
// Event handling
|
||||
virtual void
|
||||
registerEventCallback(const EventCallback& callback) = 0;
|
||||
virtual void
|
||||
unregisterEventCallback(const EventCallback& callback) = 0;
|
||||
|
||||
// Plugin event processing
|
||||
virtual Result<void> onPluginEvent(const PluginEvent& event) = 0;
|
||||
|
||||
// Status
|
||||
[[nodiscard]] virtual std::string getVersion() const = 0;
|
||||
[[nodiscard]] virtual std::chrono::system_clock::time_point
|
||||
getUptime() const = 0;
|
||||
|
||||
// Plugin interface
|
||||
virtual void
|
||||
setPluginInterface(PluginInterfacePtr pluginInterface) = 0;
|
||||
|
||||
// Trigger auto-connect (call after setPluginInterface)
|
||||
virtual void triggerAutoConnect() = 0;
|
||||
|
||||
// === Advanced methods for Core-to-Core communication (not for
|
||||
// Plugin) === These are only called by Core implementations, not
|
||||
// Plugin They use OpaqueHandle for type safety without exposing
|
||||
// types
|
||||
|
||||
// Full TrackInfo access (for internal use)
|
||||
[[nodiscard]] virtual Result<OpaqueHandle<TrackInfo>>
|
||||
getCurrentTrackHandle() const = 0;
|
||||
|
||||
// Full QueueEntry access (for internal use)
|
||||
[[nodiscard]] virtual Result<std::vector<OpaqueHandle<QueueEntry>>>
|
||||
getQueueHandles() const = 0;
|
||||
|
||||
// Raw config access (for internal use)
|
||||
[[nodiscard]] virtual Result<AppConfigHandle>
|
||||
getConfigHandle() const = 0;
|
||||
virtual Result<void>
|
||||
updateConfigFromHandle(AppConfigHandle config) = 0;
|
||||
|
||||
// Reload configuration from the config file on disk.
|
||||
// NOTE: append-only. ICoreInterface is the hot-reload ABI contract
|
||||
// between the (already-loaded) Plugin and a freshly reloaded Core.
|
||||
// Inserting/removing a virtual method anywhere above shifts every
|
||||
// later vtable slot, so the old Plugin would call the wrong methods
|
||||
// on the new Core (state-transfer corruption on hot reload). Only
|
||||
// ever add new virtuals at the very end.
|
||||
virtual Result<void> reloadConfig() = 0;
|
||||
|
||||
// Managed extension reconciliation for the host updater. The
|
||||
// request and response are versioned JSON documents so the plugin
|
||||
// package format can evolve without exposing Core implementation
|
||||
// types here. Append-only ABI: do not move this entry above
|
||||
// existing methods.
|
||||
[[nodiscard]] virtual Result<std::string>
|
||||
managePluginsJson(const std::string& /*requestJson*/)
|
||||
{
|
||||
return fail(
|
||||
ErrorCode::NotSupported,
|
||||
"managed plugin updates are not supported by this Core");
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include "CoreInterface.hpp"
|
||||
|
||||
// Platform-specific export macros
|
||||
#ifdef _WIN32
|
||||
#ifdef ECHOION_API_EXPORT
|
||||
#define ECHOION_API __declspec(dllexport)
|
||||
#else
|
||||
#define ECHOION_API __declspec(dllimport)
|
||||
#endif
|
||||
#else
|
||||
#define ECHOION_API __attribute__((visibility("default")))
|
||||
#endif
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
// API export functions
|
||||
extern "C" {
|
||||
// Create a new core instance
|
||||
ECHOION_API CoreInterfacePtr CreateCore();
|
||||
|
||||
// Destroy a core instance
|
||||
ECHOION_API void DestroyCore(ICoreInterface* core);
|
||||
|
||||
// Get API version
|
||||
ECHOION_API const char* GetApiVersion();
|
||||
|
||||
// Check if API is compatible
|
||||
ECHOION_API bool IsApiCompatible(uint32_t major, uint32_t minor);
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
// Opaque handle types to avoid including full headers
|
||||
// These are used in interfaces to break dependencies
|
||||
|
||||
// Forward declarations for Core types (Plugin never needs full definition)
|
||||
struct AppConfig;
|
||||
struct HotReloadState;
|
||||
struct PlaybackState;
|
||||
struct TrackInfo;
|
||||
struct QueueEntry;
|
||||
|
||||
// Opaque handle wrapper - type-safe void pointer replacement
|
||||
template <typename T> class OpaqueHandle
|
||||
{
|
||||
public:
|
||||
|
||||
OpaqueHandle() = default;
|
||||
explicit OpaqueHandle(std::shared_ptr<T> ptr) : ptr_(std::move(ptr))
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] bool isValid() const { return ptr_ != nullptr; }
|
||||
[[nodiscard]] T* get() const { return ptr_.get(); }
|
||||
[[nodiscard]] T& operator*() const { return *ptr_; }
|
||||
[[nodiscard]] T* operator->() const { return ptr_.get(); }
|
||||
|
||||
void reset() { ptr_.reset(); }
|
||||
void reset(T* ptr) { ptr_.reset(ptr); }
|
||||
|
||||
[[nodiscard]] std::shared_ptr<T> toSharedPtr() const
|
||||
{
|
||||
return ptr_;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::shared_ptr<T> ptr_;
|
||||
};
|
||||
|
||||
// Specific handle types
|
||||
using AppConfigHandle = OpaqueHandle<AppConfig>;
|
||||
using HotReloadStateHandle = OpaqueHandle<HotReloadState>;
|
||||
using PlaybackStateHandle = OpaqueHandle<PlaybackState>;
|
||||
using TrackInfoHandle = OpaqueHandle<TrackInfo>;
|
||||
using QueueEntryHandle = OpaqueHandle<QueueEntry>;
|
||||
|
||||
// Serialization helpers for cross-boundary communication
|
||||
using SerializedConfig = std::string; // JSON string
|
||||
using SerializedState = std::string; // JSON string
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,213 @@
|
||||
#pragma once
|
||||
|
||||
#include "PluginTypes.hpp"
|
||||
#include "Types.hpp"
|
||||
#include <expected>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
// Forward declarations
|
||||
class IPluginInterface;
|
||||
using PluginInterfacePtr = std::shared_ptr<IPluginInterface>;
|
||||
|
||||
// Plugin interface that the Core will use
|
||||
// MINIMAL VERSION - only depends on Types.hpp and PluginTypes.hpp
|
||||
// NO dependencies on TrackTypes, ConfigTypes, RpcTypes, etc.
|
||||
class IPluginInterface
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~IPluginInterface() = default;
|
||||
|
||||
// Lifecycle
|
||||
virtual Result<void> initialize() = 0;
|
||||
virtual Result<void> shutdown() = 0;
|
||||
|
||||
// Client operations
|
||||
[[nodiscard]] virtual Result<std::vector<ClientInfo>>
|
||||
getClients() = 0;
|
||||
[[nodiscard]] virtual Result<std::optional<ClientInfo>>
|
||||
getClient(uint64_t clientId) = 0;
|
||||
// Network address of a client as reported by TeamSpeak
|
||||
// (CONNECTION_CLIENT_IP). Requires the bot to hold the
|
||||
// b_client_remoteaddress_view permission; hosts that cannot
|
||||
// resolve the address return nullopt.
|
||||
[[nodiscard]] virtual Result<std::optional<std::string>>
|
||||
getClientIp(uint64_t /*clientId*/)
|
||||
{
|
||||
return std::optional<std::string>{};
|
||||
}
|
||||
// Local filesystem path of the client's avatar image as cached
|
||||
// by the TeamSpeak client (getAvatar). The cache is only
|
||||
// populated for clients the TS client has seen; nullopt when the
|
||||
// client has no avatar or it is not (yet) downloaded.
|
||||
[[nodiscard]] virtual Result<std::optional<std::string>>
|
||||
getClientAvatarPath(uint64_t /*clientId*/)
|
||||
{
|
||||
return std::optional<std::string>{};
|
||||
}
|
||||
// The client's myTeamSpeak avatar URL, if set. Modern clients store
|
||||
// their avatar as a public HTTPS URL (CLIENT_MYTS_AVATAR, formatted
|
||||
// "<version>,<url>") rather than the legacy file-transfer avatar.
|
||||
// Returns the bare URL, or nullopt when unset/legacy.
|
||||
[[nodiscard]] virtual Result<std::optional<std::string>>
|
||||
getClientAvatarUrl(uint64_t /*clientId*/)
|
||||
{
|
||||
return std::optional<std::string>{};
|
||||
}
|
||||
// Actively fetch a client's avatar from the server into `destDir`
|
||||
// (used when it isn't in the TS client's own cache — e.g. the
|
||||
// client is not in view). Returns the local path once the file is
|
||||
// present; returns nullopt when the client has no avatar or the
|
||||
// download was just triggered and hasn't finished yet (a later
|
||||
// call returns the path). Downloads run asynchronously.
|
||||
[[nodiscard]] virtual Result<std::optional<std::string>>
|
||||
requestClientAvatar(uint64_t /*clientId*/,
|
||||
const std::string& /*destDir*/)
|
||||
{
|
||||
return std::optional<std::string>{};
|
||||
}
|
||||
virtual Result<void> moveClient(uint64_t clientId,
|
||||
uint64_t channelId) = 0;
|
||||
virtual Result<void> kickClient(uint64_t clientId,
|
||||
const std::string& reason) = 0;
|
||||
virtual Result<void>
|
||||
kickClientFromChannel(uint64_t /*clientId*/,
|
||||
const std::string& /*reason*/)
|
||||
{
|
||||
return fail(ErrorCode::NotSupported,
|
||||
"channel kick is not supported by this host");
|
||||
}
|
||||
virtual Result<void> banClient(uint64_t /*clientId*/,
|
||||
uint64_t /*durationSeconds*/,
|
||||
const std::string& /*reason*/)
|
||||
{
|
||||
return fail(ErrorCode::NotSupported,
|
||||
"bans are not supported by this host");
|
||||
}
|
||||
[[nodiscard]] virtual Result<std::vector<BanInfo>> getBans()
|
||||
{
|
||||
return fail(ErrorCode::NotSupported,
|
||||
"ban listing is not supported by this host");
|
||||
}
|
||||
virtual Result<void> unban(uint64_t /*banId*/)
|
||||
{
|
||||
return fail(ErrorCode::NotSupported,
|
||||
"unban is not supported by this host");
|
||||
}
|
||||
|
||||
// Channel operations
|
||||
[[nodiscard]] virtual Result<std::vector<ChannelInfo>>
|
||||
getChannels() const = 0;
|
||||
[[nodiscard]] virtual Result<std::optional<ChannelInfo>>
|
||||
getChannel(uint64_t channelId) const = 0;
|
||||
virtual Result<uint64_t>
|
||||
createChannel(const ChannelCreateOptions& /*options*/)
|
||||
{
|
||||
return fail(ErrorCode::NotSupported,
|
||||
"channel creation is not supported by this host");
|
||||
}
|
||||
virtual Result<void>
|
||||
editChannel(uint64_t /*channelId*/,
|
||||
const ChannelEditOptions& /*options*/)
|
||||
{
|
||||
return fail(ErrorCode::NotSupported,
|
||||
"channel editing is not supported by this host");
|
||||
}
|
||||
virtual Result<void> reorderChannel(uint64_t /*channelId*/,
|
||||
uint64_t /*parentId*/,
|
||||
uint64_t /*orderAfterId*/)
|
||||
{
|
||||
return fail(ErrorCode::NotSupported,
|
||||
"channel reordering is not supported by this host");
|
||||
}
|
||||
virtual Result<void> deleteChannel(uint64_t /*channelId*/,
|
||||
bool /*force*/)
|
||||
{
|
||||
return fail(ErrorCode::NotSupported,
|
||||
"channel deletion is not supported by this host");
|
||||
}
|
||||
|
||||
// Server-group administration. Membership changes use TeamSpeak's
|
||||
// stable client database id, not the connection-scoped client id.
|
||||
[[nodiscard]] virtual Result<std::vector<ServerGroupInfo>>
|
||||
getServerGroups()
|
||||
{
|
||||
return fail(ErrorCode::NotSupported,
|
||||
"server groups are not supported by this host");
|
||||
}
|
||||
virtual Result<void>
|
||||
addClientToServerGroup(uint64_t /*groupId*/,
|
||||
uint64_t /*clientDatabaseId*/)
|
||||
{
|
||||
return fail(
|
||||
ErrorCode::NotSupported,
|
||||
"server-group membership is not supported by this host");
|
||||
}
|
||||
virtual Result<void>
|
||||
removeClientFromServerGroup(uint64_t /*groupId*/,
|
||||
uint64_t /*clientDatabaseId*/)
|
||||
{
|
||||
return fail(
|
||||
ErrorCode::NotSupported,
|
||||
"server-group membership is not supported by this host");
|
||||
}
|
||||
[[nodiscard]] virtual Result<ServerInfo> getTeamSpeakServerInfo()
|
||||
{
|
||||
return fail(ErrorCode::NotSupported,
|
||||
"server information is not supported by this host");
|
||||
}
|
||||
|
||||
// Messaging
|
||||
virtual Result<void>
|
||||
sendTextMessage(uint64_t targetId,
|
||||
const std::string& message) = 0;
|
||||
virtual Result<void>
|
||||
sendChannelMessage(uint64_t channelId,
|
||||
const std::string& message) = 0;
|
||||
virtual Result<void>
|
||||
sendServerMessage(const std::string& message) = 0;
|
||||
|
||||
// Audio
|
||||
virtual Result<void>
|
||||
sendAudioData(const std::span<const short>& data) = 0;
|
||||
virtual Result<void>
|
||||
setWhisperList(const std::vector<uint64_t>& clientIds) = 0;
|
||||
|
||||
// Server connection
|
||||
// ServerConfig is defined in PluginTypes.hpp (self-contained)
|
||||
virtual Result<void>
|
||||
connectToServer(const ServerConfig& config) = 0;
|
||||
virtual Result<void> disconnectFromServer() = 0;
|
||||
[[nodiscard]] virtual bool isConnected() const = 0;
|
||||
virtual Result<void> reconnect() = 0;
|
||||
|
||||
// Event subscription
|
||||
virtual void
|
||||
registerEventCallback(const EventCallback& callback) = 0;
|
||||
virtual void
|
||||
unregisterEventCallback(const EventCallback& callback) = 0;
|
||||
|
||||
// Host-owned control plane. Keep this generic JSON operation at the
|
||||
// very end of the ABI so updater/service operations can evolve
|
||||
// without shifting existing vtable entries. Hosts that do not
|
||||
// expose a control plane retain the previous behavior through this
|
||||
// default.
|
||||
[[nodiscard]] virtual Result<std::string>
|
||||
hostControl(const std::string& /*method*/,
|
||||
const std::string& /*requestJson*/)
|
||||
{
|
||||
return fail(ErrorCode::NotSupported,
|
||||
"host control is not supported by this host");
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,207 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api/module/Module.hpp>
|
||||
#include <echoion/api/module/ModuleAbi.h>
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Api::Module
|
||||
{
|
||||
namespace Detail
|
||||
{
|
||||
inline echoion_string_view_v1
|
||||
stringView(const std::string_view value) noexcept
|
||||
{
|
||||
return {.data = value.data(), .size = value.size()};
|
||||
}
|
||||
|
||||
inline echoion_status_v1
|
||||
status(const Void::Result::Result<void>& result) noexcept
|
||||
{
|
||||
return result ? ECHOION_STATUS_OK_V1 : ECHOION_STATUS_INTERNAL_V1;
|
||||
}
|
||||
} // namespace Detail
|
||||
|
||||
// Transitional adapter for existing C++ lifecycle implementations. The
|
||||
// exported descriptor and calls are pure C. C++ ownership and exceptions
|
||||
// remain confined to the module that created the opaque instance.
|
||||
template <Void::Plugin::module_factory_fn Factory>
|
||||
struct LegacyModuleAbi final {
|
||||
struct Instance {
|
||||
std::unique_ptr<Void::Plugin::IModule> module;
|
||||
std::string readinessDetail;
|
||||
};
|
||||
|
||||
static echoion_status_v1
|
||||
create(const echoion_module_host_v1* host,
|
||||
echoion_module_instance_v1* output) noexcept
|
||||
{
|
||||
static_cast<void>(host);
|
||||
if (output == nullptr) {
|
||||
return ECHOION_STATUS_INVALID_ARGUMENT_V1;
|
||||
}
|
||||
try {
|
||||
auto module = Factory();
|
||||
if (!module) {
|
||||
return ECHOION_STATUS_INTERNAL_V1;
|
||||
}
|
||||
auto instance = std::make_unique<Instance>(Instance{
|
||||
.module = std::move(module), .readinessDetail = {}});
|
||||
*output = instance.release();
|
||||
return ECHOION_STATUS_OK_V1;
|
||||
} catch (...) {
|
||||
return ECHOION_STATUS_INTERNAL_V1;
|
||||
}
|
||||
}
|
||||
|
||||
static void destroy(echoion_module_instance_v1 value) noexcept
|
||||
{
|
||||
std::unique_ptr<Instance> instance{
|
||||
static_cast<Instance*>(value)};
|
||||
}
|
||||
|
||||
static echoion_status_v1
|
||||
activate(echoion_module_instance_v1 value) noexcept
|
||||
{
|
||||
Instance* instance = checked(value);
|
||||
if (instance == nullptr) {
|
||||
return ECHOION_STATUS_INVALID_ARGUMENT_V1;
|
||||
}
|
||||
try {
|
||||
instance->module->on_load();
|
||||
return ECHOION_STATUS_OK_V1;
|
||||
} catch (...) {
|
||||
return ECHOION_STATUS_INTERNAL_V1;
|
||||
}
|
||||
}
|
||||
|
||||
static echoion_status_v1
|
||||
quiesce(echoion_module_instance_v1 value,
|
||||
const std::int64_t deadlineNanoseconds) noexcept
|
||||
{
|
||||
Instance* instance = checked(value);
|
||||
if (instance == nullptr || deadlineNanoseconds < 0) {
|
||||
return ECHOION_STATUS_INVALID_ARGUMENT_V1;
|
||||
}
|
||||
try {
|
||||
const auto deadline = std::chrono::steady_clock::time_point{
|
||||
std::chrono::nanoseconds{deadlineNanoseconds}};
|
||||
return Detail::status(instance->module->quiesce(deadline));
|
||||
} catch (...) {
|
||||
return ECHOION_STATUS_INTERNAL_V1;
|
||||
}
|
||||
}
|
||||
|
||||
static echoion_status_v1
|
||||
checkpoint(echoion_module_instance_v1 value,
|
||||
echoion_write_bytes_fn_v1 writer,
|
||||
void* writerContext) noexcept
|
||||
{
|
||||
Instance* instance = checked(value);
|
||||
if (instance == nullptr || writer == nullptr) {
|
||||
return ECHOION_STATUS_INVALID_ARGUMENT_V1;
|
||||
}
|
||||
try {
|
||||
const std::string encoded =
|
||||
Void::Json::serialize(instance->module->checkpoint());
|
||||
return writer(
|
||||
writerContext,
|
||||
{.data = reinterpret_cast<const std::uint8_t*>(
|
||||
encoded.data()),
|
||||
.size = encoded.size()});
|
||||
} catch (...) {
|
||||
return ECHOION_STATUS_INTERNAL_V1;
|
||||
}
|
||||
}
|
||||
|
||||
static echoion_status_v1
|
||||
restore(echoion_module_instance_v1 value,
|
||||
const echoion_bytes_view_v1 state) noexcept
|
||||
{
|
||||
Instance* instance = checked(value);
|
||||
if (instance == nullptr ||
|
||||
(state.data == nullptr && state.size != 0)) {
|
||||
return ECHOION_STATUS_INVALID_ARGUMENT_V1;
|
||||
}
|
||||
try {
|
||||
const std::string_view encoded =
|
||||
state.size == 0
|
||||
? std::string_view{}
|
||||
: std::string_view{
|
||||
reinterpret_cast<const char*>(state.data),
|
||||
state.size};
|
||||
const auto parsed = Void::Json::parse(encoded);
|
||||
if (!parsed) {
|
||||
return ECHOION_STATUS_INVALID_ARGUMENT_V1;
|
||||
}
|
||||
return Detail::status(instance->module->restore(*parsed));
|
||||
} catch (...) {
|
||||
return ECHOION_STATUS_INTERNAL_V1;
|
||||
}
|
||||
}
|
||||
|
||||
static echoion_status_v1
|
||||
readiness(echoion_module_instance_v1 value,
|
||||
echoion_module_readiness_v1* output) noexcept
|
||||
{
|
||||
Instance* instance = checked(value);
|
||||
if (instance == nullptr || output == nullptr ||
|
||||
output->struct_size < sizeof(echoion_module_readiness_v1)) {
|
||||
return ECHOION_STATUS_INVALID_ARGUMENT_V1;
|
||||
}
|
||||
try {
|
||||
const auto result = instance->module->readiness();
|
||||
instance->readinessDetail = result.detail;
|
||||
output->ready = result.ready ? 1U : 0U;
|
||||
output->detail =
|
||||
Detail::stringView(instance->readinessDetail);
|
||||
return ECHOION_STATUS_OK_V1;
|
||||
} catch (...) {
|
||||
return ECHOION_STATUS_INTERNAL_V1;
|
||||
}
|
||||
}
|
||||
|
||||
static echoion_status_v1
|
||||
deactivate(echoion_module_instance_v1 value) noexcept
|
||||
{
|
||||
Instance* instance = checked(value);
|
||||
if (instance == nullptr) {
|
||||
return ECHOION_STATUS_INVALID_ARGUMENT_V1;
|
||||
}
|
||||
try {
|
||||
return Detail::status(instance->module->deactivate());
|
||||
} catch (...) {
|
||||
return ECHOION_STATUS_INTERNAL_V1;
|
||||
}
|
||||
}
|
||||
|
||||
inline static const echoion_module_api_v1 api{
|
||||
.struct_size = sizeof(echoion_module_api_v1),
|
||||
.abi_version = ECHOION_MODULE_ABI_VERSION,
|
||||
.create = create,
|
||||
.destroy = destroy,
|
||||
.activate = activate,
|
||||
.quiesce = quiesce,
|
||||
.checkpoint = checkpoint,
|
||||
.restore = restore,
|
||||
.readiness = readiness,
|
||||
.deactivate = deactivate,
|
||||
.reserved = {},
|
||||
};
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] static Instance*
|
||||
checked(echoion_module_instance_v1 value) noexcept
|
||||
{
|
||||
return static_cast<Instance*>(value);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api::Module
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api/module/ModuleAbi.h>
|
||||
|
||||
#include <Void/Plugin/Module.hpp>
|
||||
|
||||
#if defined(_WIN32)
|
||||
#if defined(ECHOION_MODULE_BUILD)
|
||||
#define ECHOION_MODULE_EXPORT __declspec(dllexport)
|
||||
#else
|
||||
#define ECHOION_MODULE_EXPORT __declspec(dllimport)
|
||||
#endif
|
||||
#else
|
||||
#define ECHOION_MODULE_EXPORT __attribute__((visibility("default")))
|
||||
#endif
|
||||
|
||||
namespace Echoion::Api::Module
|
||||
{
|
||||
using Void::Plugin::ActivationPolicy;
|
||||
using Void::Plugin::IModule;
|
||||
using Void::Plugin::module_factory_fn;
|
||||
using Void::Plugin::module_query_fn;
|
||||
using Void::Plugin::ModuleDependency;
|
||||
using Void::Plugin::ModuleDescriptor;
|
||||
using Void::Plugin::ModuleHost;
|
||||
using Void::Plugin::ModuleReadiness;
|
||||
|
||||
inline constexpr auto descriptorVersion =
|
||||
Void::Plugin::MODULE_DESCRIPTOR_VERSION;
|
||||
inline constexpr const char* querySymbol = "echoion_module_query";
|
||||
inline constexpr const char* stableQuerySymbol =
|
||||
ECHOION_MODULE_ABI_QUERY_SYMBOL;
|
||||
|
||||
} // namespace Echoion::Api::Module
|
||||
|
||||
extern "C" ECHOION_MODULE_EXPORT const Void::Plugin::ModuleDescriptor*
|
||||
echoion_module_query();
|
||||
@@ -0,0 +1,131 @@
|
||||
#ifndef ECHOION_API_MODULE_MODULE_ABI_H
|
||||
#define ECHOION_API_MODULE_MODULE_ABI_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#if defined(_WIN32)
|
||||
#if defined(ECHOION_MODULE_BUILD)
|
||||
#define ECHOION_MODULE_ABI_EXPORT __declspec(dllexport)
|
||||
#else
|
||||
#define ECHOION_MODULE_ABI_EXPORT __declspec(dllimport)
|
||||
#endif
|
||||
#else
|
||||
#define ECHOION_MODULE_ABI_EXPORT __attribute__((visibility("default")))
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define ECHOION_MODULE_ABI_VERSION 1U
|
||||
#define ECHOION_MODULE_ABI_QUERY_SYMBOL "echoion_module_abi_query"
|
||||
|
||||
typedef struct echoion_string_view_v1 {
|
||||
const char* data;
|
||||
size_t size;
|
||||
} echoion_string_view_v1;
|
||||
|
||||
typedef struct echoion_bytes_view_v1 {
|
||||
const uint8_t* data;
|
||||
size_t size;
|
||||
} echoion_bytes_view_v1;
|
||||
|
||||
typedef enum echoion_status_v1 {
|
||||
ECHOION_STATUS_OK_V1 = 0,
|
||||
ECHOION_STATUS_INVALID_ARGUMENT_V1 = 1,
|
||||
ECHOION_STATUS_INCOMPATIBLE_V1 = 2,
|
||||
ECHOION_STATUS_UNAVAILABLE_V1 = 3,
|
||||
ECHOION_STATUS_INTERNAL_V1 = 4
|
||||
} echoion_status_v1;
|
||||
|
||||
typedef enum echoion_activation_policy_v1 {
|
||||
ECHOION_ACTIVATION_RELOADABLE_V1 = 0,
|
||||
ECHOION_ACTIVATION_RESTART_REQUIRED_V1 = 1,
|
||||
ECHOION_ACTIVATION_INSTALLER_REQUIRED_V1 = 2
|
||||
} echoion_activation_policy_v1;
|
||||
|
||||
typedef void* echoion_module_instance_v1;
|
||||
|
||||
typedef echoion_status_v1 (*echoion_write_bytes_fn_v1)(
|
||||
void* context, echoion_bytes_view_v1 value);
|
||||
|
||||
typedef echoion_status_v1 (*echoion_query_service_fn_v1)(
|
||||
void* context, echoion_string_view_v1 service_id, uint32_t minimum_version,
|
||||
const void** service);
|
||||
|
||||
typedef void (*echoion_log_fn_v1)(void* context, uint32_t level,
|
||||
echoion_string_view_v1 message);
|
||||
|
||||
typedef struct echoion_module_host_v1 {
|
||||
size_t struct_size;
|
||||
uint32_t abi_version;
|
||||
void* context;
|
||||
echoion_query_service_fn_v1 query_service;
|
||||
echoion_log_fn_v1 log;
|
||||
const void* reserved[8];
|
||||
} echoion_module_host_v1;
|
||||
|
||||
typedef struct echoion_module_readiness_v1 {
|
||||
size_t struct_size;
|
||||
uint8_t ready;
|
||||
uint8_t reserved_bytes[7];
|
||||
echoion_string_view_v1 detail;
|
||||
} echoion_module_readiness_v1;
|
||||
|
||||
typedef struct echoion_module_api_v1 {
|
||||
size_t struct_size;
|
||||
uint32_t abi_version;
|
||||
echoion_status_v1 (*create)(const echoion_module_host_v1* host,
|
||||
echoion_module_instance_v1* instance);
|
||||
void (*destroy)(echoion_module_instance_v1 instance);
|
||||
echoion_status_v1 (*activate)(echoion_module_instance_v1 instance);
|
||||
echoion_status_v1 (*quiesce)(echoion_module_instance_v1 instance,
|
||||
int64_t steady_clock_deadline_nanoseconds);
|
||||
echoion_status_v1 (*checkpoint)(echoion_module_instance_v1 instance,
|
||||
echoion_write_bytes_fn_v1 writer,
|
||||
void* writer_context);
|
||||
echoion_status_v1 (*restore)(echoion_module_instance_v1 instance,
|
||||
echoion_bytes_view_v1 state);
|
||||
echoion_status_v1 (*readiness)(echoion_module_instance_v1 instance,
|
||||
echoion_module_readiness_v1* readiness);
|
||||
echoion_status_v1 (*deactivate)(echoion_module_instance_v1 instance);
|
||||
const void* reserved[8];
|
||||
} echoion_module_api_v1;
|
||||
|
||||
typedef struct echoion_module_dependency_v1 {
|
||||
size_t struct_size;
|
||||
echoion_string_view_v1 component_id;
|
||||
echoion_string_view_v1 version_range;
|
||||
echoion_string_view_v1 abi_hash;
|
||||
uint8_t optional;
|
||||
uint8_t reserved_bytes[7];
|
||||
} echoion_module_dependency_v1;
|
||||
|
||||
typedef struct echoion_module_descriptor_v1 {
|
||||
size_t struct_size;
|
||||
uint32_t abi_version;
|
||||
echoion_string_view_v1 component_id;
|
||||
uint32_t version_major;
|
||||
uint32_t version_minor;
|
||||
uint32_t version_patch;
|
||||
echoion_string_view_v1 version_prerelease;
|
||||
echoion_string_view_v1 abi_hash;
|
||||
const echoion_module_dependency_v1* dependencies;
|
||||
size_t dependency_count;
|
||||
echoion_activation_policy_v1 activation_policy;
|
||||
const echoion_module_api_v1* api;
|
||||
const void* reserved[8];
|
||||
} echoion_module_descriptor_v1;
|
||||
|
||||
typedef const echoion_module_descriptor_v1* (*echoion_module_abi_query_fn_v1)(
|
||||
void);
|
||||
|
||||
ECHOION_MODULE_ABI_EXPORT const echoion_module_descriptor_v1*
|
||||
echoion_module_abi_query(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <future>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
// Network client interface. Speaks Void::Net types directly — there is no
|
||||
// echoion-side HTTP/proxy mirror.
|
||||
class INetworkClient
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~INetworkClient() = default;
|
||||
|
||||
// Initialize with optional proxy
|
||||
virtual Result<void> initialize(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy =
|
||||
std::nullopt) = 0;
|
||||
virtual void shutdown() = 0;
|
||||
|
||||
// Synchronous requests
|
||||
[[nodiscard]] virtual Result<Void::Net::Response>
|
||||
get(std::string_view url,
|
||||
const std::vector<Void::Net::Header>& headers = {}) = 0;
|
||||
[[nodiscard]] virtual Result<Void::Net::Response>
|
||||
post(std::string_view url, std::string_view body,
|
||||
const std::vector<Void::Net::Header>& headers = {}) = 0;
|
||||
[[nodiscard]] virtual Result<Void::Net::Response>
|
||||
request(const Void::Net::Request& req) = 0;
|
||||
|
||||
// Proxy configuration
|
||||
virtual void
|
||||
setProxy(const std::optional<Void::Net::ProxyConfig>& proxy) = 0;
|
||||
[[nodiscard]] virtual std::optional<Void::Net::ProxyConfig>
|
||||
getProxy() const = 0;
|
||||
virtual void clearProxy() = 0;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
// echoion no longer mirrors HTTP/proxy types — they are Void::Net's. This
|
||||
// header forwards to Void::Net so existing includes keep resolving
|
||||
// Void::Net::Request / Response / Header / Method / ProxyConfig.
|
||||
#include <Void/Net/Http.hpp>
|
||||
@@ -0,0 +1,111 @@
|
||||
#pragma once
|
||||
|
||||
#include <PluginTypes.hpp>
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Plugin/Module.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
struct ExtensionCommand {
|
||||
std::string name;
|
||||
std::vector<std::string> aliases;
|
||||
std::string description;
|
||||
std::string usage;
|
||||
std::uint8_t category = 5;
|
||||
bool adminOnly = false;
|
||||
};
|
||||
|
||||
struct ExtensionRpc {
|
||||
std::string name;
|
||||
bool adminOnly = false;
|
||||
};
|
||||
|
||||
struct ExtensionMediaSource {
|
||||
std::string name;
|
||||
bool supportsSearch = false;
|
||||
};
|
||||
|
||||
struct ExtensionWebAsset {
|
||||
std::string id;
|
||||
std::string javascript;
|
||||
std::string css;
|
||||
};
|
||||
|
||||
struct ExtensionCommandRequest {
|
||||
std::string command;
|
||||
std::string arguments;
|
||||
std::uint64_t clientId = 0;
|
||||
std::string invokerName;
|
||||
};
|
||||
|
||||
struct ExtensionRpcRequest {
|
||||
std::string method;
|
||||
std::string params;
|
||||
std::uint64_t clientId = 0;
|
||||
};
|
||||
|
||||
struct ExtensionStream {
|
||||
std::string url;
|
||||
bool localFile = false;
|
||||
};
|
||||
|
||||
// Native, trusted Echoion extension contract. Calls are always made while
|
||||
// the host holds a Void::Plugin::PluginHandle, so a hot reload cannot
|
||||
// unmap code that is still executing.
|
||||
class IExtensionPlugin : public Void::Plugin::IModule
|
||||
{
|
||||
public:
|
||||
[[nodiscard]] virtual std::vector<ExtensionCommand> commands() const
|
||||
{
|
||||
return {};
|
||||
}
|
||||
[[nodiscard]] virtual std::vector<ExtensionRpc> rpcMethods() const
|
||||
{
|
||||
return {};
|
||||
}
|
||||
[[nodiscard]] virtual std::vector<ExtensionMediaSource> mediaSources() const
|
||||
{
|
||||
return {};
|
||||
}
|
||||
[[nodiscard]] virtual std::vector<ExtensionWebAsset> webAssets() const
|
||||
{
|
||||
return {};
|
||||
}
|
||||
virtual Result<std::string> executeCommand(
|
||||
const ExtensionCommandRequest&)
|
||||
{
|
||||
return fail(ErrorCode::NotSupported, "extension command is not supported");
|
||||
}
|
||||
virtual Result<std::string> callRpc(const ExtensionRpcRequest&)
|
||||
{
|
||||
return fail(ErrorCode::NotSupported, "extension RPC is not supported");
|
||||
}
|
||||
virtual void onEvent(const PluginEvent&) {}
|
||||
[[nodiscard]] virtual bool canHandleMedia(
|
||||
std::string_view, const std::string&) const
|
||||
{
|
||||
return false;
|
||||
}
|
||||
virtual Result<SearchResult> searchMedia(
|
||||
std::string_view, std::string_view)
|
||||
{
|
||||
return fail(ErrorCode::NotSupported, "extension search is not supported");
|
||||
}
|
||||
virtual Result<TrackInfo> resolveMedia(
|
||||
std::string_view, const std::string&)
|
||||
{
|
||||
return fail(ErrorCode::NotSupported, "extension resolve is not supported");
|
||||
}
|
||||
virtual Result<ExtensionStream> streamMedia(
|
||||
std::string_view, const TrackInfo&)
|
||||
{
|
||||
return fail(ErrorCode::NotSupported, "extension stream is not supported");
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
#pragma once
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
// ===== Plugin Event Types =====
|
||||
|
||||
enum class PluginEventType : uint8_t {
|
||||
ClientConnected = 0,
|
||||
ClientDisconnected,
|
||||
ClientMoved,
|
||||
TextMessageReceived,
|
||||
VoiceDataReceived,
|
||||
PlayRequested,
|
||||
PauseRequested,
|
||||
SkipRequested,
|
||||
StopRequested,
|
||||
TrackQueued,
|
||||
TrackRemoved,
|
||||
QueueCleared,
|
||||
QueueUpdated,
|
||||
PlaybackStarted,
|
||||
PlaybackPaused,
|
||||
PlaybackResumed,
|
||||
PlaybackStopped,
|
||||
TrackFinished,
|
||||
TrackSkipped,
|
||||
VolumeChanged,
|
||||
SeekPosition,
|
||||
HotReloadRequested,
|
||||
HotReloadCompleted,
|
||||
ConfigurationChanged,
|
||||
// Appended: fired once the TeamSpeak connection is fully established
|
||||
// (client list available), so the core can resolve online subscribers.
|
||||
ConnectionEstablished,
|
||||
// Appended for the authoritative TeamSpeak directory cache. Hosts may
|
||||
// emit either event after refreshing their local topology mirror.
|
||||
ClientUpdated,
|
||||
ChannelUpdated
|
||||
};
|
||||
|
||||
// Minimal track info for the host boundary (no internal types)
|
||||
struct TrackSummary {
|
||||
std::string id;
|
||||
std::string title;
|
||||
std::string artist;
|
||||
std::optional<std::chrono::milliseconds> duration;
|
||||
};
|
||||
|
||||
struct PluginEvent {
|
||||
PluginEventType type;
|
||||
std::optional<std::string> clientName = {};
|
||||
std::optional<TrackSummary> trackSummary =
|
||||
{}; // Opaque summary instead of full TrackInfo
|
||||
uint64_t clientId = 0;
|
||||
std::optional<uint64_t> targetChannelId = {};
|
||||
std::optional<std::string> message = {};
|
||||
std::optional<float> volume = {};
|
||||
std::optional<int> queuePosition = {};
|
||||
std::chrono::system_clock::time_point timestamp = {};
|
||||
};
|
||||
|
||||
// ===== Connection Types =====
|
||||
|
||||
struct ClientInfo {
|
||||
uint64_t id = 0;
|
||||
std::optional<uint64_t> databaseId;
|
||||
std::string nickname;
|
||||
std::optional<std::string> uniqueIdentifier;
|
||||
uint64_t channelId = 0;
|
||||
bool isTalking = false;
|
||||
bool isMuted = false;
|
||||
bool isDeafened = false;
|
||||
bool isAway = false;
|
||||
bool isQuery = false;
|
||||
std::vector<uint64_t> serverGroups;
|
||||
};
|
||||
|
||||
struct ChannelInfo {
|
||||
uint64_t id = 0;
|
||||
std::string name;
|
||||
std::optional<uint64_t> parentId;
|
||||
uint64_t order = 0;
|
||||
bool isDefault = false;
|
||||
bool isPermanent = false;
|
||||
bool isSemiPermanent = false;
|
||||
bool hasPassword = false;
|
||||
uint32_t maxClients = 0;
|
||||
uint32_t currentClients = 0;
|
||||
};
|
||||
|
||||
struct ChannelCreateOptions {
|
||||
std::string name;
|
||||
std::optional<uint64_t> parentId;
|
||||
std::optional<uint64_t> orderAfterId;
|
||||
std::optional<std::string> topic;
|
||||
std::optional<std::string> description;
|
||||
std::optional<std::string> password;
|
||||
uint32_t maxClients = 0;
|
||||
bool permanent = true;
|
||||
};
|
||||
|
||||
struct ChannelEditOptions {
|
||||
std::optional<std::string> name;
|
||||
std::optional<std::string> topic;
|
||||
std::optional<std::string> description;
|
||||
std::optional<std::string> password;
|
||||
std::optional<uint32_t> maxClients;
|
||||
std::optional<bool> permanent;
|
||||
};
|
||||
|
||||
struct ServerGroupInfo {
|
||||
uint64_t id = 0;
|
||||
std::string name;
|
||||
bool isDefault = false;
|
||||
};
|
||||
|
||||
struct BanInfo {
|
||||
uint64_t id = 0;
|
||||
std::optional<std::string> uniqueIdentifier;
|
||||
std::optional<std::string> nickname;
|
||||
std::string reason;
|
||||
uint64_t createdAt = 0;
|
||||
uint64_t durationSeconds = 0; // 0 means permanent
|
||||
};
|
||||
|
||||
struct ServerInfo {
|
||||
uint64_t id = 0;
|
||||
std::string name;
|
||||
std::string welcomeMessage;
|
||||
uint32_t maxClients = 0;
|
||||
uint32_t currentClients = 0;
|
||||
uint64_t defaultChannelId = 0;
|
||||
};
|
||||
|
||||
// ===== Callback Types =====
|
||||
|
||||
using EventCallback = std::function<void(const PluginEvent&)>;
|
||||
using CommandHandler = std::function<void(
|
||||
uint64_t clientId, const std::vector<std::string>& args)>;
|
||||
|
||||
struct CommandInfo {
|
||||
std::string name;
|
||||
std::string description;
|
||||
std::vector<std::string> aliases;
|
||||
std::optional<std::string> usage;
|
||||
bool requiresAdmin = false;
|
||||
CommandHandler handler;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,52 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Api::Plugin::ShortUrl
|
||||
{
|
||||
template <typename T> using Result = std::expected<T, std::string>;
|
||||
|
||||
[[nodiscard]] Result<Void::Json::Value>
|
||||
parseConfigObject(const char* config);
|
||||
[[nodiscard]] Result<std::string>
|
||||
requireString(const Void::Json::Value& object, std::string_view key);
|
||||
[[nodiscard]] Result<std::string>
|
||||
optionalString(const Void::Json::Value& object, std::string_view key,
|
||||
std::string_view fallback = {});
|
||||
[[nodiscard]] Result<bool> optionalBool(const Void::Json::Value& object,
|
||||
std::string_view key,
|
||||
bool fallback);
|
||||
[[nodiscard]] Result<std::int64_t>
|
||||
optionalInteger(const Void::Json::Value& object, std::string_view key,
|
||||
std::int64_t fallback, std::int64_t minimum,
|
||||
std::int64_t maximum);
|
||||
|
||||
[[nodiscard]] bool
|
||||
containsControlCharacters(std::string_view value) noexcept;
|
||||
[[nodiscard]] std::string trimAscii(std::string_view value);
|
||||
[[nodiscard]] bool isHeaderName(std::string_view value) noexcept;
|
||||
[[nodiscard]] bool isBase62(std::string_view value) noexcept;
|
||||
|
||||
/// Validate an absolute HTTP(S) URL without making a network request.
|
||||
[[nodiscard]] Result<void>
|
||||
validateHttpUrl(std::string_view value, bool requireHttps,
|
||||
std::size_t maximumLength = 8192);
|
||||
|
||||
/// Reject address literals and well-known hostnames that are not publicly
|
||||
/// routable. DNS-backed validation lives in the external provider because
|
||||
/// only it opens outbound connections.
|
||||
[[nodiscard]] bool isObviouslyPrivateHost(std::string_view host) noexcept;
|
||||
|
||||
/// Expand ${url} and ${env:NAME}. Environment variables are read without
|
||||
/// being copied into diagnostics; a missing variable reports only its name.
|
||||
[[nodiscard]] Result<std::string>
|
||||
expandTemplate(std::string_view input, std::string_view url,
|
||||
bool encodeSubstitutions = false);
|
||||
|
||||
} // namespace Echoion::Api::Plugin::ShortUrl
|
||||
@@ -0,0 +1,185 @@
|
||||
#pragma once
|
||||
|
||||
#include "ConfigTypes.hpp"
|
||||
#include "TrackTypes.hpp"
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
enum class RpcMethod : uint8_t {
|
||||
// Playback control
|
||||
Play = 0,
|
||||
Pause,
|
||||
Resume,
|
||||
Stop,
|
||||
Skip,
|
||||
Seek,
|
||||
SetVolume,
|
||||
|
||||
// Queue management
|
||||
QueueTrack,
|
||||
RemoveFromQueue,
|
||||
ClearQueue,
|
||||
GetQueue,
|
||||
MoveInQueue,
|
||||
|
||||
// Track info
|
||||
GetCurrentTrack,
|
||||
GetTrackInfo,
|
||||
SearchTracks,
|
||||
|
||||
// Playlist
|
||||
LoadPlaylist,
|
||||
SavePlaylist,
|
||||
GetPlaylists,
|
||||
DeletePlaylist,
|
||||
|
||||
// Configuration
|
||||
GetConfig,
|
||||
SetConfig,
|
||||
ReloadConfig,
|
||||
|
||||
// Plugin/Core management
|
||||
GetStatus,
|
||||
HotReload,
|
||||
Shutdown,
|
||||
|
||||
// Admin
|
||||
Authenticate,
|
||||
Logout,
|
||||
GetAuditLog,
|
||||
ManageUsers,
|
||||
|
||||
// Server info
|
||||
GetServerInfo,
|
||||
RequestLoginToken,
|
||||
ValidateLoginToken,
|
||||
|
||||
// Playback mode (appended; numeric values are server-internal and
|
||||
// only need to stay self-consistent — the wire contract is the name)
|
||||
ToggleShuffle,
|
||||
ToggleRepeat,
|
||||
ShuffleQueue,
|
||||
|
||||
// Library (appended)
|
||||
GetPlaylist, // playlist contents by id
|
||||
GetHistory, // recently played tracks
|
||||
GetStats, // playback statistics
|
||||
|
||||
// Web UI (appended)
|
||||
GetFavorites, // authenticated user's favorites
|
||||
AddFavorite, // add a track to favorites
|
||||
RemoveFavorite, // remove by track url
|
||||
VoteSkip, // vote to skip the current track
|
||||
Announce, // admin: broadcast an announcement
|
||||
GetAggregateStats, // server-wide dashboard statistics
|
||||
|
||||
// Web UI round 2 (appended)
|
||||
AuthenticateByAddress, // sign in by matching the caller's IP against
|
||||
// online subscribers' TeamSpeak addresses
|
||||
RestartWebInterface, // admin: stop+start the web server in place
|
||||
ToggleAutoplay, // admin: flip radio mode (autoplay)
|
||||
|
||||
// Web UI round 3 (appended)
|
||||
GetUserPrefs, // per-user preferences (language, …) from the kv store
|
||||
SetUserPrefs, // update per-user preferences; keys shared with the
|
||||
// chat commands (e.g. !lang) so both stay in sync
|
||||
|
||||
// Values 49-51 are reserved for retired browser features.
|
||||
// Web UI round 5 (appended): lyrics for the current track (lrclib)
|
||||
GetLyrics = 52, // plain + time-synced lyrics for the now-playing track
|
||||
|
||||
// Values 53-66 belonged to the removed experimental TeamSpeak
|
||||
// listening-room API. Keep later values stable for stored audit rows.
|
||||
GetCapabilities = 67,
|
||||
GetPluginExtensions,
|
||||
PluginCall,
|
||||
|
||||
// Values 70-72 are reserved for retired browser features.
|
||||
// TeamSpeak directory and administration; 53-66 stay reserved.
|
||||
GetTeamSpeakDirectory = 73,
|
||||
MoveTeamSpeakClient,
|
||||
KickTeamSpeakClient,
|
||||
BanTeamSpeakClient,
|
||||
GetTeamSpeakBans,
|
||||
UnbanTeamSpeakClient,
|
||||
CreateTeamSpeakChannel,
|
||||
EditTeamSpeakChannel,
|
||||
ReorderTeamSpeakChannel,
|
||||
DeleteTeamSpeakChannel,
|
||||
GetTeamSpeakServerGroups,
|
||||
AddTeamSpeakServerGroupMember,
|
||||
RemoveTeamSpeakServerGroupMember,
|
||||
SendTeamSpeakPrivateMessage,
|
||||
SendTeamSpeakChannelMessage,
|
||||
SendTeamSpeakServerMessage,
|
||||
|
||||
// Component updater (append-only; values 89-99).
|
||||
GetUpdateStatus,
|
||||
GetUpdateConfig,
|
||||
SetUpdateConfig,
|
||||
CheckForUpdates,
|
||||
ApplyUpdate,
|
||||
RollbackUpdate,
|
||||
ConfirmUnsignedUpdate,
|
||||
PreviewUpdateTransaction,
|
||||
ApplyUpdateTransaction,
|
||||
RollbackUpdateGeneration,
|
||||
GetUpdateHistory
|
||||
};
|
||||
|
||||
struct RpcRequest {
|
||||
uint64_t id;
|
||||
RpcMethod method;
|
||||
std::optional<std::string> params;
|
||||
std::optional<std::string> authToken;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
struct RpcResponse {
|
||||
uint64_t requestId;
|
||||
bool success;
|
||||
std::optional<std::string> result;
|
||||
std::optional<std::string>
|
||||
error; // JSON string: {"code":N,"message":"...","source":"..."}
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
struct RpcNotification {
|
||||
std::string event;
|
||||
std::optional<std::string> data;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
using RpcHandler = std::function<RpcResponse(const RpcRequest &)>;
|
||||
|
||||
struct RpcEndpoint {
|
||||
RpcMethod method;
|
||||
std::string name;
|
||||
std::string description;
|
||||
bool requiresAuth;
|
||||
RpcHandler handler;
|
||||
};
|
||||
|
||||
// Hot reload state preservation
|
||||
struct HotReloadState {
|
||||
PlaybackState playback;
|
||||
std::vector<QueueEntry> queue;
|
||||
std::optional<std::string> currentStreamUrl;
|
||||
std::chrono::milliseconds playbackPosition;
|
||||
BotConfig config;
|
||||
std::map<std::string, std::string> sessionData;
|
||||
bool autoplay = false;
|
||||
|
||||
[[nodiscard]] bool shouldPreservePlayback() const noexcept
|
||||
{
|
||||
return playback.isPlaying && playback.currentTrack.has_value();
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,202 @@
|
||||
#pragma once
|
||||
|
||||
#include "AudioTypes.hpp"
|
||||
#include "Types.hpp"
|
||||
#include <Void/Data/Reflect.hpp> // Void::Json::Value + ReflectError
|
||||
#include <chrono>
|
||||
#include <expected>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
enum class TrackSource : uint8_t {
|
||||
Unknown = 0,
|
||||
YouTube,
|
||||
SoundCloud,
|
||||
Spotify,
|
||||
LocalFile,
|
||||
URL,
|
||||
// Appended after URL so existing uint8_t-serialized history rows
|
||||
// keep their meaning.
|
||||
Yandex,
|
||||
// Media returned by an extension plugin. Keep this distinct from
|
||||
// Unknown so source allowlists never have to permit unknown values.
|
||||
Plugin
|
||||
};
|
||||
|
||||
struct TrackInfo {
|
||||
std::string id;
|
||||
std::string title;
|
||||
std::string artist;
|
||||
std::string album;
|
||||
std::optional<std::string> thumbnailUrl;
|
||||
std::optional<std::chrono::milliseconds> duration;
|
||||
TrackSource source;
|
||||
std::string originalUrl;
|
||||
std::optional<std::string>
|
||||
shortenedUrl; // provider-generated public link
|
||||
std::optional<std::string> streamUrl;
|
||||
std::optional<AudioStreamInfo> audioInfo;
|
||||
std::chrono::system_clock::time_point addedAt;
|
||||
std::string requestedBy;
|
||||
|
||||
// Format track as markdown link: [Title](shortenedUrl)
|
||||
// Only uses a successfully generated shortened URL; returns no link
|
||||
// if unavailable.
|
||||
[[nodiscard]] std::string formatWithLink() const
|
||||
{
|
||||
if (shortenedUrl.has_value() && !shortenedUrl->empty()) {
|
||||
return std::format("[{}]({})", title, *shortenedUrl);
|
||||
}
|
||||
return std::format("[{}]",
|
||||
title); // No link if no shortened URL
|
||||
}
|
||||
|
||||
// Format track with artist and link
|
||||
// Only uses a successfully generated shortened URL; returns text if
|
||||
// unavailable.
|
||||
[[nodiscard]] std::string formatWithArtistAndLink() const
|
||||
{
|
||||
std::string displayTitle = title;
|
||||
if (!artist.empty()) {
|
||||
displayTitle = std::format("{} by {}", title, artist);
|
||||
}
|
||||
if (shortenedUrl.has_value() && !shortenedUrl->empty()) {
|
||||
return std::format("[{}]({})", displayTitle, *shortenedUrl);
|
||||
}
|
||||
return displayTitle; // No link if no shortened URL
|
||||
}
|
||||
|
||||
// ── Void::Json customization ──────────────────────────────────
|
||||
// TrackInfo holds chrono and an optional nested AudioStreamInfo,
|
||||
// neither of which Void::Json reflection covers, so it provides an
|
||||
// explicit serializer. chrono is stored as integer milliseconds and
|
||||
// the enum as its underlying value (stable round-trips). The
|
||||
// transient audioInfo (re-derived on playback) is intentionally not
|
||||
// persisted.
|
||||
[[nodiscard]] Void::Json::Value to_json() const
|
||||
{
|
||||
using Void::Json::Value;
|
||||
Value out = Void::Json::object();
|
||||
auto& o = out.as_object();
|
||||
o.emplace_back("id", Value{id});
|
||||
o.emplace_back("title", Value{title});
|
||||
o.emplace_back("artist", Value{artist});
|
||||
o.emplace_back("album", Value{album});
|
||||
o.emplace_back("thumbnailUrl", thumbnailUrl
|
||||
? Value{*thumbnailUrl}
|
||||
: Value{nullptr});
|
||||
o.emplace_back(
|
||||
"durationMs",
|
||||
duration ? Value{static_cast<double>(duration->count())}
|
||||
: Value{nullptr});
|
||||
o.emplace_back("source",
|
||||
Value{static_cast<double>(
|
||||
static_cast<std::uint8_t>(source))});
|
||||
o.emplace_back("originalUrl", Value{originalUrl});
|
||||
o.emplace_back("shortenedUrl", shortenedUrl ? Value{*shortenedUrl}
|
||||
: Value{nullptr});
|
||||
o.emplace_back("streamUrl",
|
||||
streamUrl ? Value{*streamUrl} : Value{nullptr});
|
||||
o.emplace_back(
|
||||
"addedAtMs",
|
||||
Value{static_cast<double>(
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
addedAt.time_since_epoch())
|
||||
.count())});
|
||||
o.emplace_back("requestedBy", Value{requestedBy});
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] static std::expected<TrackInfo, Void::Json::ReflectError>
|
||||
from_json(const Void::Json::Value& j)
|
||||
{
|
||||
TrackInfo t;
|
||||
const auto str = [&](const char* k) -> std::string {
|
||||
const auto* v = j.find(k);
|
||||
return (v && v->is_string()) ? v->as_string()
|
||||
: std::string{};
|
||||
};
|
||||
const auto optStr =
|
||||
[&](const char* k) -> std::optional<std::string> {
|
||||
const auto* v = j.find(k);
|
||||
if (v && v->is_string()) {
|
||||
return v->as_string();
|
||||
}
|
||||
return std::nullopt;
|
||||
};
|
||||
t.id = str("id");
|
||||
t.title = str("title");
|
||||
t.artist = str("artist");
|
||||
t.album = str("album");
|
||||
t.thumbnailUrl = optStr("thumbnailUrl");
|
||||
if (const auto* d = j.find("durationMs");
|
||||
d && d->is_number()) {
|
||||
t.duration = std::chrono::milliseconds(
|
||||
static_cast<std::int64_t>(d->as_number()));
|
||||
}
|
||||
if (const auto* s = j.find("source"); s && s->is_number()) {
|
||||
t.source = static_cast<TrackSource>(
|
||||
static_cast<std::uint8_t>(s->as_number()));
|
||||
} else {
|
||||
t.source = TrackSource::Unknown;
|
||||
}
|
||||
t.originalUrl = str("originalUrl");
|
||||
t.shortenedUrl = optStr("shortenedUrl");
|
||||
t.streamUrl = optStr("streamUrl");
|
||||
if (const auto* a = j.find("addedAtMs");
|
||||
a && a->is_number()) {
|
||||
t.addedAt = std::chrono::system_clock::time_point(
|
||||
std::chrono::milliseconds(
|
||||
static_cast<std::int64_t>(a->as_number())));
|
||||
}
|
||||
t.requestedBy = str("requestedBy");
|
||||
return t;
|
||||
}
|
||||
};
|
||||
|
||||
struct PlaylistInfo {
|
||||
std::string id;
|
||||
std::string name;
|
||||
std::string description;
|
||||
std::optional<std::string> thumbnailUrl;
|
||||
std::string owner;
|
||||
std::vector<TrackInfo> tracks;
|
||||
std::chrono::system_clock::time_point createdAt;
|
||||
std::chrono::system_clock::time_point updatedAt;
|
||||
};
|
||||
|
||||
struct QueueEntry {
|
||||
uint64_t queueId;
|
||||
TrackInfo track;
|
||||
std::chrono::system_clock::time_point addedAt;
|
||||
std::string addedBy;
|
||||
bool isPlaying;
|
||||
std::optional<std::chrono::milliseconds> position;
|
||||
};
|
||||
|
||||
struct PlaybackState {
|
||||
std::optional<QueueEntry> currentTrack;
|
||||
std::vector<QueueEntry> queue;
|
||||
bool isPlaying;
|
||||
bool isPaused;
|
||||
std::chrono::milliseconds position;
|
||||
std::chrono::milliseconds buffered;
|
||||
float volume;
|
||||
bool repeat;
|
||||
bool shuffle;
|
||||
std::chrono::system_clock::time_point lastUpdate;
|
||||
};
|
||||
|
||||
struct SearchResult {
|
||||
std::vector<TrackInfo> tracks;
|
||||
std::vector<PlaylistInfo> playlists;
|
||||
std::string query;
|
||||
std::optional<std::string> nextPageToken;
|
||||
uint32_t totalResults;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,147 @@
|
||||
#pragma once
|
||||
|
||||
#include "Types.hpp"
|
||||
#include <Void/Containers/BufferPool.hpp>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
// Reusable int16 audio sample buffer, recycled by the pool on drop.
|
||||
using AudioSampleBuffer = Void::BufferPool::BufferPool<int16_t>::Buffer;
|
||||
|
||||
// Specialized audio buffer pool for int16 (direct TeamSpeak compatibility).
|
||||
// Backed by Void::BufferPool, which pools by power-of-two size class and
|
||||
// reuses storage across acquisitions (grow-on-demand, no fixed capacity).
|
||||
class AudioBufferPool
|
||||
{
|
||||
public:
|
||||
|
||||
static constexpr size_t DEFAULT_BUFFER_SIZE =
|
||||
1920; // 48000Hz * 2ch * 20ms
|
||||
static constexpr size_t DEFAULT_POOL_SIZE =
|
||||
256; // pre-warm hint (buffers)
|
||||
|
||||
static AudioBufferPool& instance();
|
||||
|
||||
void initialize(size_t bufferSize = DEFAULT_BUFFER_SIZE,
|
||||
size_t poolSize = DEFAULT_POOL_SIZE);
|
||||
void shutdown();
|
||||
|
||||
// Borrow an int16 buffer of the configured size. An empty Buffer is
|
||||
// returned if the pool has not been initialized.
|
||||
[[nodiscard]] AudioSampleBuffer acquireBuffer();
|
||||
|
||||
// Get buffer size
|
||||
[[nodiscard]] size_t getBufferSize() const { return bufferSize_; }
|
||||
|
||||
// Get stats
|
||||
[[nodiscard]] size_t getAvailableBuffers() const;
|
||||
[[nodiscard]] size_t getTotalBuffers() const;
|
||||
|
||||
private:
|
||||
|
||||
AudioBufferPool() = default;
|
||||
|
||||
std::unique_ptr<Void::BufferPool::BufferPool<int16_t>> pool_;
|
||||
size_t bufferSize_ = DEFAULT_BUFFER_SIZE;
|
||||
};
|
||||
|
||||
// Zero-copy audio buffer view
|
||||
template <typename T> class AudioBufferView
|
||||
{
|
||||
public:
|
||||
|
||||
AudioBufferView() = default;
|
||||
|
||||
AudioBufferView(T* data, size_t size, size_t channels = 2)
|
||||
: data_(data), size_(size), channels_(channels)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] T* data() { return data_; }
|
||||
[[nodiscard]] const T* data() const { return data_; }
|
||||
[[nodiscard]] size_t size() const { return size_; }
|
||||
[[nodiscard]] size_t channels() const { return channels_; }
|
||||
[[nodiscard]] size_t samplesPerChannel() const
|
||||
{
|
||||
return size_ / channels_;
|
||||
}
|
||||
|
||||
[[nodiscard]] T* channel(size_t ch) { return data_ + ch; }
|
||||
|
||||
[[nodiscard]] T& sample(size_t frame, size_t ch)
|
||||
{
|
||||
return data_[frame * channels_ + ch];
|
||||
}
|
||||
|
||||
[[nodiscard]] const T& sample(size_t frame, size_t ch) const
|
||||
{
|
||||
return data_[frame * channels_ + ch];
|
||||
}
|
||||
|
||||
// Span for single channel
|
||||
[[nodiscard]] std::span<T> getChannelSpan(size_t ch)
|
||||
{
|
||||
return std::span<T>(data_ + ch, size_, channels_);
|
||||
}
|
||||
|
||||
// Span for all data
|
||||
[[nodiscard]] std::span<T> getSpan()
|
||||
{
|
||||
return std::span<T>(data_, size_);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool empty() const
|
||||
{
|
||||
return data_ == nullptr || size_ == 0;
|
||||
}
|
||||
|
||||
void clear()
|
||||
{
|
||||
if (data_) {
|
||||
std::memset(data_, 0, size_ * sizeof(T));
|
||||
}
|
||||
}
|
||||
|
||||
// Apply gain in-place
|
||||
void applyGain(float gain)
|
||||
{
|
||||
if (!data_) {
|
||||
return;
|
||||
}
|
||||
for (size_t i = 0; i < size_; ++i) {
|
||||
data_[i] *= gain;
|
||||
}
|
||||
}
|
||||
|
||||
// Mix another buffer into this one
|
||||
void mix(const AudioBufferView& other, float gain = 1.0f)
|
||||
{
|
||||
if (!data_ || !other.data_) {
|
||||
return;
|
||||
}
|
||||
size_t mixSize = std::min(size_, other.size_);
|
||||
for (size_t i = 0; i < mixSize; ++i) {
|
||||
data_[i] += other.data_[i] * gain;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
T* data_ = nullptr;
|
||||
size_t size_ = 0;
|
||||
size_t channels_ = 2;
|
||||
};
|
||||
|
||||
// Audio buffer view types - using int16 (short) for direct TeamSpeak
|
||||
// compatibility
|
||||
using Int16AudioView = AudioBufferView<int16_t>;
|
||||
|
||||
// Deprecated: Float audio view is no longer used, all audio is int16
|
||||
using FloatAudioView = AudioBufferView<float>;
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,143 @@
|
||||
#pragma once
|
||||
|
||||
#include "TrackTypes.hpp"
|
||||
#include "Types.hpp"
|
||||
#include <chrono>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
// YouTube-specific types for the extracted client algorithm
|
||||
|
||||
struct YouTubeFormat {
|
||||
std::string itag;
|
||||
std::string mimeType;
|
||||
std::optional<std::string> url;
|
||||
std::optional<std::string> signatureCipher;
|
||||
int32_t bitrate;
|
||||
int32_t width;
|
||||
int32_t height;
|
||||
std::optional<std::string> qualityLabel;
|
||||
std::optional<std::string> audioQuality;
|
||||
int32_t audioSampleRate;
|
||||
int32_t audioChannels;
|
||||
bool hasVideo;
|
||||
bool hasAudio;
|
||||
};
|
||||
|
||||
struct YouTubeVideoDetails {
|
||||
std::string videoId;
|
||||
std::string title;
|
||||
std::string author;
|
||||
std::optional<std::chrono::seconds> lengthSeconds;
|
||||
std::vector<YouTubeFormat> formats;
|
||||
std::vector<YouTubeFormat> adaptiveFormats;
|
||||
std::optional<std::string> playerJsUrl;
|
||||
std::optional<std::string> streamingData;
|
||||
};
|
||||
|
||||
struct YouTubeSearchResult {
|
||||
std::string videoId;
|
||||
std::string title;
|
||||
std::string channelTitle;
|
||||
std::optional<std::chrono::seconds> duration;
|
||||
std::optional<std::string> thumbnailUrl;
|
||||
std::string publishedAt;
|
||||
uint64_t viewCount;
|
||||
};
|
||||
|
||||
struct YouTubePlaylistItem {
|
||||
std::string videoId;
|
||||
std::string title;
|
||||
std::optional<std::chrono::seconds> duration;
|
||||
std::optional<std::string> thumbnailUrl;
|
||||
};
|
||||
|
||||
struct YouTubePlaylist {
|
||||
std::string playlistId;
|
||||
std::string title;
|
||||
std::string author;
|
||||
std::vector<YouTubePlaylistItem> videos;
|
||||
std::optional<std::string> continuationToken;
|
||||
};
|
||||
|
||||
struct YouTubePlayerConfig {
|
||||
std::string innertubeApiKey;
|
||||
std::string innertubeClientName;
|
||||
std::string innertubeClientVersion;
|
||||
std::string contextClientName;
|
||||
std::string contextClientVersion;
|
||||
std::string visitorData;
|
||||
std::optional<std::string> poToken;
|
||||
};
|
||||
|
||||
struct YouTubeClientContext {
|
||||
std::string hl = "en";
|
||||
std::string gl = "US";
|
||||
std::string clientName = "WEB";
|
||||
std::string clientVersion;
|
||||
std::optional<std::string> visitorData;
|
||||
std::optional<std::string> userAgent;
|
||||
};
|
||||
|
||||
// Convert YouTube types to generic TrackInfo
|
||||
[[nodiscard]] inline TrackInfo
|
||||
ConvertToTrackInfo(const YouTubeVideoDetails& details)
|
||||
{
|
||||
TrackInfo info;
|
||||
info.id = details.videoId;
|
||||
info.title = details.title;
|
||||
info.artist = details.author;
|
||||
if (details.lengthSeconds.has_value()) {
|
||||
info.duration =
|
||||
std::chrono::milliseconds(*details.lengthSeconds * 1000);
|
||||
}
|
||||
info.source = TrackSource::YouTube;
|
||||
info.originalUrl = "https://youtube.com/watch?v=" + details.videoId;
|
||||
return info;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline TrackInfo
|
||||
ConvertToTrackInfo(const YouTubeSearchResult& result)
|
||||
{
|
||||
TrackInfo info;
|
||||
info.id = result.videoId;
|
||||
info.title = result.title;
|
||||
info.artist = result.channelTitle;
|
||||
if (result.duration.has_value()) {
|
||||
info.duration = std::chrono::milliseconds(*result.duration * 1000);
|
||||
}
|
||||
info.thumbnailUrl = result.thumbnailUrl;
|
||||
info.source = TrackSource::YouTube;
|
||||
info.originalUrl = "https://youtube.com/watch?v=" + result.videoId;
|
||||
return info;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline PlaylistInfo
|
||||
ConvertToPlaylistInfo(const YouTubePlaylist& playlist)
|
||||
{
|
||||
PlaylistInfo info;
|
||||
info.id = playlist.playlistId;
|
||||
info.name = playlist.title;
|
||||
info.owner = playlist.author;
|
||||
// Convert playlist items to tracks
|
||||
for (const auto& item : playlist.videos) {
|
||||
TrackInfo track;
|
||||
track.id = item.videoId;
|
||||
track.title = item.title;
|
||||
track.source = TrackSource::YouTube;
|
||||
track.originalUrl = "https://youtube.com/watch?v=" + item.videoId;
|
||||
if (item.duration.has_value()) {
|
||||
track.duration =
|
||||
std::chrono::milliseconds(*item.duration * 1000);
|
||||
}
|
||||
track.thumbnailUrl = item.thumbnailUrl;
|
||||
info.tracks.push_back(std::move(track));
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api
|
||||
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Canonicalize, hash, classify, and version Echoion module contracts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
SEMVER = re.compile(
|
||||
r"^(?P<major>0|[1-9][0-9]*)\."
|
||||
r"(?P<minor>0|[1-9][0-9]*)\."
|
||||
r"(?P<patch>0|[1-9][0-9]*)$"
|
||||
)
|
||||
|
||||
|
||||
def load_contract(path: Path) -> Any:
|
||||
with path.open(encoding="utf-8") as source:
|
||||
contract = json.load(source)
|
||||
if not isinstance(contract, dict) or contract.get("schemaVersion") != 1:
|
||||
raise ValueError(f"{path}: unsupported ABI contract schema")
|
||||
return contract
|
||||
|
||||
|
||||
def canonical_bytes(contract: Any) -> bytes:
|
||||
return (
|
||||
json.dumps(
|
||||
contract,
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
+ "\n"
|
||||
).encode()
|
||||
|
||||
|
||||
def contract_hash(contract: Any) -> str:
|
||||
return "sha256:" + hashlib.sha256(canonical_bytes(contract)).hexdigest()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Compatibility:
|
||||
compatible: bool
|
||||
changed: bool
|
||||
|
||||
|
||||
def compare_contract(old: Any, new: Any) -> Compatibility:
|
||||
"""Return whether new is an append-only superset of old."""
|
||||
if type(old) is not type(new):
|
||||
return Compatibility(False, True)
|
||||
if isinstance(old, dict):
|
||||
changed = len(old) != len(new)
|
||||
for key, old_value in old.items():
|
||||
if key not in new:
|
||||
return Compatibility(False, True)
|
||||
result = compare_contract(old_value, new[key])
|
||||
if not result.compatible:
|
||||
return result
|
||||
changed = changed or result.changed
|
||||
return Compatibility(True, changed)
|
||||
if isinstance(old, list):
|
||||
if len(new) < len(old):
|
||||
return Compatibility(False, True)
|
||||
changed = len(new) != len(old)
|
||||
for index, old_value in enumerate(old):
|
||||
result = compare_contract(old_value, new[index])
|
||||
if not result.compatible:
|
||||
return result
|
||||
changed = changed or result.changed
|
||||
return Compatibility(True, changed)
|
||||
return Compatibility(old == new, old != new)
|
||||
|
||||
|
||||
def classify(
|
||||
old_contract: Any,
|
||||
new_contract: Any,
|
||||
old_source_sha: str,
|
||||
new_source_sha: str,
|
||||
kind: str,
|
||||
) -> str:
|
||||
if old_source_sha == new_source_sha:
|
||||
if canonical_bytes(old_contract) != canonical_bytes(new_contract):
|
||||
raise ValueError("ABI contract changed without a source SHA change")
|
||||
return "unchanged"
|
||||
if kind in {"executable", "assets"}:
|
||||
return "patch"
|
||||
|
||||
comparison = compare_contract(old_contract, new_contract)
|
||||
if not comparison.compatible:
|
||||
return "major"
|
||||
return "minor" if comparison.changed else "patch"
|
||||
|
||||
|
||||
def derive_version(current: str, change: str) -> str:
|
||||
match = SEMVER.fullmatch(current)
|
||||
if match is None:
|
||||
raise ValueError(f"component version is not stable SemVer: {current}")
|
||||
major, minor, patch = (
|
||||
int(match.group("major")),
|
||||
int(match.group("minor")),
|
||||
int(match.group("patch")),
|
||||
)
|
||||
if change == "unchanged":
|
||||
return current
|
||||
if change == "patch":
|
||||
return f"{major}.{minor}.{patch + 1}"
|
||||
if change == "minor":
|
||||
return f"{major}.{minor + 1}.0"
|
||||
if change == "major":
|
||||
return f"{major + 1}.0.0"
|
||||
raise ValueError(f"unsupported change classification: {change}")
|
||||
|
||||
|
||||
def write_or_print(payload: bytes, output: Path | None) -> None:
|
||||
if output is None:
|
||||
sys.stdout.buffer.write(payload)
|
||||
return
|
||||
temporary = output.with_name(output.name + ".tmp")
|
||||
temporary.write_bytes(payload)
|
||||
temporary.replace(output)
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser()
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
canonical = subparsers.add_parser("canonicalize")
|
||||
canonical.add_argument("contract", type=Path)
|
||||
canonical.add_argument("--output", type=Path)
|
||||
|
||||
digest = subparsers.add_parser("hash")
|
||||
digest.add_argument("contract", type=Path)
|
||||
|
||||
classify_parser = subparsers.add_parser("classify")
|
||||
classify_parser.add_argument("old_contract", type=Path)
|
||||
classify_parser.add_argument("new_contract", type=Path)
|
||||
classify_parser.add_argument("--old-source-sha", required=True)
|
||||
classify_parser.add_argument("--new-source-sha", required=True)
|
||||
classify_parser.add_argument(
|
||||
"--kind",
|
||||
choices=("module", "library", "executable", "assets"),
|
||||
default="module",
|
||||
)
|
||||
|
||||
derive = subparsers.add_parser("derive-version")
|
||||
derive.add_argument("current")
|
||||
derive.add_argument(
|
||||
"change", choices=("unchanged", "patch", "minor", "major")
|
||||
)
|
||||
return parser
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = build_parser().parse_args()
|
||||
try:
|
||||
if args.command == "canonicalize":
|
||||
write_or_print(
|
||||
canonical_bytes(load_contract(args.contract)), args.output
|
||||
)
|
||||
elif args.command == "hash":
|
||||
print(contract_hash(load_contract(args.contract)))
|
||||
elif args.command == "classify":
|
||||
print(
|
||||
classify(
|
||||
load_contract(args.old_contract),
|
||||
load_contract(args.new_contract),
|
||||
args.old_source_sha,
|
||||
args.new_source_sha,
|
||||
args.kind,
|
||||
)
|
||||
)
|
||||
elif args.command == "derive-version":
|
||||
print(derive_version(args.current, args.change))
|
||||
else:
|
||||
raise AssertionError(args.command)
|
||||
except (OSError, json.JSONDecodeError, ValueError) as error:
|
||||
print(f"abi-contract: {error}", file=sys.stderr)
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,319 @@
|
||||
#include <echoion/api/plugin/ShortUrlSupport.hpp>
|
||||
|
||||
#include <Void/Net/Url.hpp>
|
||||
#include <Void/Text/Url.hpp>
|
||||
|
||||
#include <boost/asio/ip/address.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <format>
|
||||
#include <limits>
|
||||
|
||||
namespace Echoion::Api::Plugin::ShortUrl
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] bool validEnvironmentName(std::string_view name) noexcept
|
||||
{
|
||||
if (name.empty() ||
|
||||
!(std::isalpha(static_cast<unsigned char>(name.front())) != 0 ||
|
||||
name.front() == '_')) {
|
||||
return false;
|
||||
}
|
||||
return std::ranges::all_of(
|
||||
name.substr(1), [](const char character) {
|
||||
const auto value = static_cast<unsigned char>(character);
|
||||
return std::isalnum(value) != 0 || character == '_';
|
||||
});
|
||||
}
|
||||
|
||||
[[nodiscard]] bool
|
||||
isPrivateV4(const boost::asio::ip::address_v4 address) noexcept
|
||||
{
|
||||
const auto value = address.to_uint();
|
||||
const auto first = static_cast<unsigned>((value >> 24U) & 0xffU);
|
||||
const auto second = static_cast<unsigned>((value >> 16U) & 0xffU);
|
||||
const auto third = static_cast<unsigned>((value >> 8U) & 0xffU);
|
||||
|
||||
return first == 0U || first == 10U || first == 127U ||
|
||||
(first == 100U && second >= 64U && second <= 127U) ||
|
||||
(first == 169U && second == 254U) ||
|
||||
(first == 172U && second >= 16U && second <= 31U) ||
|
||||
(first == 192U && second == 168U) ||
|
||||
(first == 192U && second == 0U && third <= 2U) ||
|
||||
(first == 198U && (second == 18U || second == 19U)) ||
|
||||
(first == 198U && second == 51U && third == 100U) ||
|
||||
(first == 203U && second == 0U && third == 113U) ||
|
||||
first >= 224U;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool
|
||||
isPrivateV6(const boost::asio::ip::address_v6 address) noexcept
|
||||
{
|
||||
const auto bytes = address.to_bytes();
|
||||
if (address.is_unspecified() || address.is_loopback() ||
|
||||
address.is_link_local() || address.is_multicast()) {
|
||||
return true;
|
||||
}
|
||||
if (address.is_v4_mapped()) {
|
||||
const boost::asio::ip::address_v4::bytes_type mapped{
|
||||
bytes[12], bytes[13], bytes[14], bytes[15]};
|
||||
return isPrivateV4(boost::asio::ip::address_v4{mapped});
|
||||
}
|
||||
|
||||
const bool uniqueLocal = (bytes[0] & 0xfeU) == 0xfcU;
|
||||
const bool documentation = bytes[0] == 0x20U && bytes[1] == 0x01U &&
|
||||
bytes[2] == 0x0dU && bytes[3] == 0xb8U;
|
||||
return uniqueLocal || documentation;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Result<Void::Json::Value> parseConfigObject(const char* config)
|
||||
{
|
||||
if (config == nullptr || *config == '\0') {
|
||||
return std::unexpected{"plugin configuration is required"};
|
||||
}
|
||||
auto parsed = Void::Json::parse(config);
|
||||
if (!parsed) {
|
||||
return std::unexpected{
|
||||
std::format("invalid plugin configuration at {}:{}: {}",
|
||||
parsed.error().line, parsed.error().col,
|
||||
parsed.error().message)};
|
||||
}
|
||||
if (!parsed->is_object()) {
|
||||
return std::unexpected{
|
||||
"plugin configuration must be a JSON object"};
|
||||
}
|
||||
return std::move(*parsed);
|
||||
}
|
||||
|
||||
Result<std::string> requireString(const Void::Json::Value& object,
|
||||
const std::string_view key)
|
||||
{
|
||||
const auto* value = object.find(key);
|
||||
if (value == nullptr || !value->is_string() ||
|
||||
value->as_string().empty()) {
|
||||
return std::unexpected{std::format(
|
||||
"configuration field '{}' must be a non-empty string", key)};
|
||||
}
|
||||
return value->as_string();
|
||||
}
|
||||
|
||||
Result<std::string> optionalString(const Void::Json::Value& object,
|
||||
const std::string_view key,
|
||||
const std::string_view fallback)
|
||||
{
|
||||
const auto* value = object.find(key);
|
||||
if (value == nullptr) {
|
||||
return std::string{fallback};
|
||||
}
|
||||
if (!value->is_string()) {
|
||||
return std::unexpected{
|
||||
std::format("configuration field '{}' must be a string", key)};
|
||||
}
|
||||
return value->as_string();
|
||||
}
|
||||
|
||||
Result<bool> optionalBool(const Void::Json::Value& object,
|
||||
const std::string_view key, const bool fallback)
|
||||
{
|
||||
const auto* value = object.find(key);
|
||||
if (value == nullptr) {
|
||||
return fallback;
|
||||
}
|
||||
if (!value->is_bool()) {
|
||||
return std::unexpected{
|
||||
std::format("configuration field '{}' must be a boolean", key)};
|
||||
}
|
||||
return value->as_bool();
|
||||
}
|
||||
|
||||
Result<std::int64_t> optionalInteger(const Void::Json::Value& object,
|
||||
const std::string_view key,
|
||||
const std::int64_t fallback,
|
||||
const std::int64_t minimum,
|
||||
const std::int64_t maximum)
|
||||
{
|
||||
const auto* value = object.find(key);
|
||||
if (value == nullptr) {
|
||||
return fallback;
|
||||
}
|
||||
if (!value->is_number()) {
|
||||
return std::unexpected{std::format(
|
||||
"configuration field '{}' must be an integer", key)};
|
||||
}
|
||||
const auto number = value->as_number();
|
||||
if (!std::isfinite(number) || std::floor(number) != number ||
|
||||
number < static_cast<double>(minimum) ||
|
||||
number > static_cast<double>(maximum)) {
|
||||
return std::unexpected{std::format(
|
||||
"configuration field '{}' must be between {} and {}", key,
|
||||
minimum, maximum)};
|
||||
}
|
||||
return static_cast<std::int64_t>(number);
|
||||
}
|
||||
|
||||
bool containsControlCharacters(const std::string_view value) noexcept
|
||||
{
|
||||
return std::ranges::any_of(value, [](const char character) {
|
||||
const auto byte = static_cast<unsigned char>(character);
|
||||
return byte < 0x20U || byte == 0x7fU;
|
||||
});
|
||||
}
|
||||
|
||||
std::string trimAscii(const std::string_view value)
|
||||
{
|
||||
const auto isSpace = [](const char character) {
|
||||
return std::isspace(static_cast<unsigned char>(character)) != 0;
|
||||
};
|
||||
const auto first = std::ranges::find_if_not(value, isSpace);
|
||||
const auto last =
|
||||
std::find_if_not(value.rbegin(), value.rend(), isSpace).base();
|
||||
if (first >= last) {
|
||||
return {};
|
||||
}
|
||||
return {first, last};
|
||||
}
|
||||
|
||||
bool isHeaderName(const std::string_view value) noexcept
|
||||
{
|
||||
if (value.empty()) {
|
||||
return false;
|
||||
}
|
||||
constexpr std::string_view separators{"()<>@,;:\\\"/[]?={} \t"};
|
||||
return std::ranges::all_of(value, [separators](const char character) {
|
||||
const auto byte = static_cast<unsigned char>(character);
|
||||
return byte > 0x20U && byte < 0x7fU &&
|
||||
separators.find(character) == std::string_view::npos;
|
||||
});
|
||||
}
|
||||
|
||||
bool isBase62(const std::string_view value) noexcept
|
||||
{
|
||||
return !value.empty() && std::ranges::all_of(value, [](const char c) {
|
||||
return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') ||
|
||||
(c >= 'a' && c <= 'z');
|
||||
});
|
||||
}
|
||||
|
||||
Result<void> validateHttpUrl(const std::string_view value,
|
||||
const bool requireHttps,
|
||||
const std::size_t maximumLength)
|
||||
{
|
||||
if (value.empty() || value.size() > maximumLength ||
|
||||
containsControlCharacters(value) ||
|
||||
std::ranges::any_of(value, [](const char c) {
|
||||
return std::isspace(static_cast<unsigned char>(c)) != 0;
|
||||
})) {
|
||||
return std::unexpected{
|
||||
"URL is empty, too long, or contains whitespace"};
|
||||
}
|
||||
const auto parsed = Void::Net::Url::parse(value);
|
||||
if (!parsed || parsed->host.empty() ||
|
||||
(parsed->scheme != "http" && parsed->scheme != "https")) {
|
||||
return std::unexpected{"URL must be an absolute HTTP(S) URL"};
|
||||
}
|
||||
if (requireHttps && parsed->scheme != "https") {
|
||||
return std::unexpected{"URL must use HTTPS"};
|
||||
}
|
||||
|
||||
const auto schemeEnd = value.find("://");
|
||||
const auto authorityEnd = value.find_first_of("/?#", schemeEnd + 3U);
|
||||
const auto authority =
|
||||
value.substr(schemeEnd + 3U, authorityEnd == std::string_view::npos
|
||||
? std::string_view::npos
|
||||
: authorityEnd - schemeEnd - 3U);
|
||||
if (authority.find('@') != std::string_view::npos) {
|
||||
return std::unexpected{"URL userinfo is not allowed"};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
bool isObviouslyPrivateHost(const std::string_view host) noexcept
|
||||
{
|
||||
std::string lower;
|
||||
lower.reserve(host.size());
|
||||
std::ranges::transform(
|
||||
host, std::back_inserter(lower), [](const char c) {
|
||||
return static_cast<char>(
|
||||
std::tolower(static_cast<unsigned char>(c)));
|
||||
});
|
||||
while (!lower.empty() && lower.back() == '.') {
|
||||
lower.pop_back();
|
||||
}
|
||||
if (lower == "localhost" || lower.ends_with(".localhost") ||
|
||||
lower.ends_with(".local") || lower.ends_with(".internal")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
boost::system::error_code error;
|
||||
const auto address = boost::asio::ip::make_address(lower, error);
|
||||
if (error) {
|
||||
return false;
|
||||
}
|
||||
return address.is_v4() ? isPrivateV4(address.to_v4())
|
||||
: isPrivateV6(address.to_v6());
|
||||
}
|
||||
|
||||
Result<std::string> expandTemplate(const std::string_view input,
|
||||
const std::string_view url,
|
||||
const bool encodeSubstitutions)
|
||||
{
|
||||
const auto appendReplacement =
|
||||
[encodeSubstitutions](std::string& destination,
|
||||
const std::string_view replacement) {
|
||||
if (encodeSubstitutions) {
|
||||
destination.append(
|
||||
Void::Encoding::Url::query_encode(replacement));
|
||||
} else {
|
||||
destination.append(replacement);
|
||||
}
|
||||
};
|
||||
std::string output;
|
||||
output.reserve(input.size() + url.size());
|
||||
std::size_t position{};
|
||||
while (position < input.size()) {
|
||||
const auto marker = input.find("${", position);
|
||||
if (marker == std::string_view::npos) {
|
||||
output.append(input.substr(position));
|
||||
break;
|
||||
}
|
||||
output.append(input.substr(position, marker - position));
|
||||
const auto end = input.find('}', marker + 2U);
|
||||
if (end == std::string_view::npos) {
|
||||
return std::unexpected{"unterminated template placeholder"};
|
||||
}
|
||||
const auto token = input.substr(marker + 2U, end - marker - 2U);
|
||||
if (token == "url") {
|
||||
appendReplacement(output, url);
|
||||
} else if (token.starts_with("env:")) {
|
||||
const auto name = token.substr(4U);
|
||||
if (!validEnvironmentName(name)) {
|
||||
return std::unexpected{
|
||||
"invalid environment placeholder name"};
|
||||
}
|
||||
const std::string ownedName{name};
|
||||
const char* value = std::getenv(ownedName.c_str());
|
||||
if (value == nullptr) {
|
||||
return std::unexpected{std::format(
|
||||
"required environment variable '{}' is not set", name)};
|
||||
}
|
||||
if (containsControlCharacters(value)) {
|
||||
return std::unexpected{std::format(
|
||||
"environment variable '{}' contains control characters",
|
||||
name)};
|
||||
}
|
||||
appendReplacement(output, value);
|
||||
} else {
|
||||
return std::unexpected{std::format(
|
||||
"unsupported template placeholder '${{{}}}'", token)};
|
||||
}
|
||||
position = end + 1U;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api::Plugin::ShortUrl
|
||||
@@ -0,0 +1,95 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SPEC = importlib.util.spec_from_file_location(
|
||||
"abi_contract", ROOT / "scripts" / "abi_contract.py"
|
||||
)
|
||||
assert SPEC is not None and SPEC.loader is not None
|
||||
ABI = importlib.util.module_from_spec(SPEC)
|
||||
sys.modules[SPEC.name] = ABI
|
||||
SPEC.loader.exec_module(ABI)
|
||||
|
||||
|
||||
class AbiContractTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.contract = ABI.load_contract(
|
||||
ROOT / "abi" / "echoion-module-v1.json"
|
||||
)
|
||||
|
||||
def classify(self, updated: object, old: str = "a", new: str = "b") -> str:
|
||||
return ABI.classify(self.contract, updated, old, new, "module")
|
||||
|
||||
def test_canonical_hash_is_stable(self) -> None:
|
||||
reordered = {
|
||||
key: self.contract[key] for key in reversed(self.contract.keys())
|
||||
}
|
||||
self.assertEqual(
|
||||
ABI.contract_hash(self.contract), ABI.contract_hash(reordered)
|
||||
)
|
||||
|
||||
def test_unchanged_source_reuses_version_and_artifact(self) -> None:
|
||||
self.assertEqual(
|
||||
ABI.classify(
|
||||
self.contract, copy.deepcopy(self.contract), "same", "same", "module"
|
||||
),
|
||||
"unchanged",
|
||||
)
|
||||
self.assertEqual(ABI.derive_version("2.0.0", "unchanged"), "2.0.0")
|
||||
|
||||
def test_implementation_only_change_increments_patch(self) -> None:
|
||||
self.assertEqual(self.classify(copy.deepcopy(self.contract)), "patch")
|
||||
self.assertEqual(ABI.derive_version("2.0.0", "patch"), "2.0.1")
|
||||
|
||||
def test_append_only_change_increments_minor(self) -> None:
|
||||
updated = copy.deepcopy(self.contract)
|
||||
updated["types"][0]["fields"].append(
|
||||
{
|
||||
"name": "future_field",
|
||||
"type": "uint64_t",
|
||||
"ownership": "value",
|
||||
}
|
||||
)
|
||||
self.assertEqual(self.classify(updated), "minor")
|
||||
self.assertEqual(ABI.derive_version("2.3.9", "minor"), "2.4.0")
|
||||
|
||||
def test_reordered_retyped_and_renamed_fields_are_breaking(self) -> None:
|
||||
for mutate in (
|
||||
lambda fields: fields.reverse(),
|
||||
lambda fields: fields[0].update(type="uint64_t"),
|
||||
lambda fields: fields[0].update(name="renamed"),
|
||||
):
|
||||
with self.subTest(mutate=mutate):
|
||||
updated = copy.deepcopy(self.contract)
|
||||
mutate(updated["types"][0]["fields"])
|
||||
self.assertEqual(self.classify(updated), "major")
|
||||
self.assertEqual(ABI.derive_version("2.3.9", "major"), "3.0.0")
|
||||
|
||||
def test_contract_change_without_source_change_is_rejected(self) -> None:
|
||||
updated = copy.deepcopy(self.contract)
|
||||
updated["types"].append({"name": "future", "fields": []})
|
||||
with self.assertRaisesRegex(
|
||||
ValueError, "without a source SHA change"
|
||||
):
|
||||
self.classify(updated, "same", "same")
|
||||
|
||||
def test_executable_and_assets_changes_increment_patch(self) -> None:
|
||||
incompatible = {"schemaVersion": 1}
|
||||
for kind in ("executable", "assets"):
|
||||
with self.subTest(kind=kind):
|
||||
self.assertEqual(
|
||||
ABI.classify(
|
||||
self.contract, incompatible, "old", "new", kind
|
||||
),
|
||||
"patch",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile the public module ABI as both C and C++."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
HEADER = ROOT / "include"
|
||||
|
||||
|
||||
class ModuleAbiCTests(unittest.TestCase):
|
||||
def compile(self, compiler: str, suffix: str, standard: str) -> None:
|
||||
with tempfile.TemporaryDirectory(
|
||||
prefix="echoion-module-abi."
|
||||
) as directory:
|
||||
source = Path(directory) / f"consumer.{suffix}"
|
||||
source.write_text(
|
||||
"""
|
||||
#include <echoion/api/module/ModuleAbi.h>
|
||||
|
||||
int main(void) {
|
||||
#ifdef __cplusplus
|
||||
echoion_module_descriptor_v1 descriptor = {};
|
||||
#else
|
||||
echoion_module_descriptor_v1 descriptor = {0};
|
||||
#endif
|
||||
descriptor.struct_size = sizeof(descriptor);
|
||||
descriptor.abi_version = ECHOION_MODULE_ABI_VERSION;
|
||||
return descriptor.api == 0 ? 0 : 1;
|
||||
}
|
||||
"""
|
||||
)
|
||||
result = subprocess.run(
|
||||
[
|
||||
compiler,
|
||||
standard,
|
||||
"-Wall",
|
||||
"-Wextra",
|
||||
"-Wpedantic",
|
||||
"-Werror",
|
||||
"-I",
|
||||
str(HEADER),
|
||||
"-fsyntax-only",
|
||||
str(source),
|
||||
],
|
||||
check=False,
|
||||
text=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def test_header_is_c11(self) -> None:
|
||||
self.compile(os.environ.get("CC", "cc"), "c", "-std=c11")
|
||||
|
||||
def test_header_is_cpp20(self) -> None:
|
||||
self.compile(os.environ.get("CXX", "c++"), "cpp", "-std=c++20")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user