Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6555d4c69 | ||
|
|
c2ec314eb9 | ||
|
|
16d9a667eb | ||
|
|
d456257d0c | ||
|
|
cbb178d83d | ||
|
|
29c7e60733 | ||
|
|
4b6f3165b2 | ||
|
|
b08f8ad29b | ||
|
|
915e2ab981 | ||
|
|
9637f1eef7 | ||
|
|
a277f2102b | ||
|
|
dfbbdaaf01 | ||
|
|
7975f2b38e | ||
|
|
9f06af6c80 | ||
|
|
39aff68d8d |
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
|
||||
+147
-11
@@ -1,5 +1,47 @@
|
||||
cmake_minimum_required(VERSION 4.0.0)
|
||||
project(EchoionCore VERSION 1.0.0 LANGUAGES CXX)
|
||||
if(NOT DEFINED ECHOION_PRODUCT_VERSION)
|
||||
set(ECHOION_PRODUCT_VERSION 0.0.0)
|
||||
endif()
|
||||
if(NOT DEFINED ECHOION_COMPONENT_VERSION)
|
||||
set(ECHOION_COMPONENT_VERSION "${ECHOION_PRODUCT_VERSION}")
|
||||
endif()
|
||||
project(EchoionCore VERSION "${ECHOION_COMPONENT_VERSION}" LANGUAGES CXX)
|
||||
|
||||
set(ECHOION_LICENSE_ROOT_KEY_ID "" CACHE STRING
|
||||
"Pinned EchoionLicensing root key id")
|
||||
set(ECHOION_LICENSE_ROOT_PUBLIC_KEY "" CACHE STRING
|
||||
"Pinned base64url Ed25519 EchoionLicensing root public key")
|
||||
set(ECHOION_PRODUCT_VERSION "${ECHOION_COMPONENT_VERSION}" CACHE STRING
|
||||
"Echoion product version bound into licensing decisions")
|
||||
set(ECHOION_BUILD_SIGNATURE "development:${ECHOION_COMPONENT_VERSION}" CACHE STRING
|
||||
"Immutable signed-build identifier used by licensing revocation")
|
||||
option(ECHOION_ALLOW_DEVELOPMENT_LICENSE_KEYS
|
||||
"Allow opt-in trust keys from config (never enable for releases)" OFF)
|
||||
|
||||
if(PROJECT_IS_TOP_LEVEL)
|
||||
set(BUILD_SHARED_LIBS ON CACHE BOOL
|
||||
"Build shared component dependencies" FORCE)
|
||||
file(DOWNLOAD
|
||||
https://github.com/cpm-cmake/CPM.cmake/releases/download/v0.40.8/CPM.cmake
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake"
|
||||
EXPECTED_HASH
|
||||
SHA256=78ba32abdf798bc616bab7c73aac32a17bbd7b06ad9e26a6add69de8f3ae4791)
|
||||
include("${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake")
|
||||
CPMAddPackage(
|
||||
NAME Void
|
||||
GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/voidlibrary.git
|
||||
GIT_TAG main
|
||||
OPTIONS "VOID_ENABLE_TESTING OFF")
|
||||
CPMAddPackage(
|
||||
NAME EchoionApi
|
||||
GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/echoionapi.git
|
||||
GIT_TAG main)
|
||||
option(BUILD_TESTS "Build component tests" ON)
|
||||
if(BUILD_TESTS)
|
||||
enable_testing()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
@@ -11,6 +53,20 @@ file(GLOB_RECURSE CORE_SOURCES
|
||||
"src/**.cpp"
|
||||
)
|
||||
add_library(EchoionCore SHARED ${CORE_SOURCES})
|
||||
target_compile_definitions(EchoionCore PRIVATE
|
||||
ECHOION_CORE_VERSION="${ECHOION_COMPONENT_VERSION}"
|
||||
ECHOION_MODULE_BUILD
|
||||
ECHOION_COMPONENT_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
|
||||
ECHOION_COMPONENT_VERSION_MINOR=${PROJECT_VERSION_MINOR}
|
||||
ECHOION_COMPONENT_VERSION_PATCH=${PROJECT_VERSION_PATCH}
|
||||
ECHOION_LICENSE_ROOT_KEY_ID="${ECHOION_LICENSE_ROOT_KEY_ID}"
|
||||
ECHOION_LICENSE_ROOT_PUBLIC_KEY="${ECHOION_LICENSE_ROOT_PUBLIC_KEY}"
|
||||
ECHOION_PRODUCT_VERSION="${ECHOION_PRODUCT_VERSION}"
|
||||
ECHOION_BUILD_SIGNATURE="${ECHOION_BUILD_SIGNATURE}")
|
||||
if(ECHOION_ALLOW_DEVELOPMENT_LICENSE_KEYS)
|
||||
target_compile_definitions(EchoionCore PRIVATE
|
||||
ECHOION_ALLOW_DEVELOPMENT_LICENSE_KEYS)
|
||||
endif()
|
||||
|
||||
add_library(Echoion::Core ALIAS EchoionCore)
|
||||
|
||||
@@ -37,14 +93,15 @@ target_link_libraries(EchoionCore PUBLIC
|
||||
Echoion::ApiPluginInterface
|
||||
Echoion::ApiCoreInterface
|
||||
Echoion::ApiUtils
|
||||
Echoion::ApiModuleAbi
|
||||
)
|
||||
|
||||
find_package(PkgConfig REQUIRED)
|
||||
pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET
|
||||
libavformat
|
||||
libavcodec
|
||||
libswresample
|
||||
libavutil
|
||||
libavformat>=59
|
||||
libavcodec>=59
|
||||
libswresample>=4
|
||||
libavutil>=57
|
||||
)
|
||||
|
||||
CPMAddPackage(
|
||||
@@ -110,6 +167,12 @@ endif()
|
||||
find_package(Threads REQUIRED)
|
||||
find_package(OpenSSL REQUIRED)
|
||||
find_package(SQLite3 REQUIRED)
|
||||
# FindSQLite3 exposed only SQLite::SQLite3 before CMake 4.3. Keep the
|
||||
# component's preferred target name available across the supported CMake 4.x
|
||||
# range; an alias created inside sibling VoidLibrary is not visible here.
|
||||
if(NOT TARGET SQLite3::SQLite3 AND TARGET SQLite::SQLite3)
|
||||
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
|
||||
endif()
|
||||
find_package(TBB REQUIRED)
|
||||
|
||||
target_link_libraries(EchoionCore
|
||||
@@ -131,7 +194,11 @@ target_link_libraries(EchoionCore
|
||||
Void::Net
|
||||
Void::Sqlite
|
||||
Void::Service
|
||||
Void::ShortUrl
|
||||
Void::Plugin
|
||||
Void::Crypto
|
||||
Void::Update
|
||||
Void::Security
|
||||
PRIVATE
|
||||
Threads::Threads
|
||||
qjs
|
||||
@@ -149,6 +216,21 @@ else()
|
||||
target_compile_options(EchoionCore PRIVATE -Wall -Wextra -Wpedantic)
|
||||
endif()
|
||||
|
||||
if(BUILD_TESTS)
|
||||
include("${Void_SOURCE_DIR}/cmake/VoidTesting.cmake")
|
||||
|
||||
add_executable(echoion_log_rotation_tests
|
||||
tests/test_log_rotation.cpp
|
||||
src/LogRotation.cpp
|
||||
)
|
||||
target_include_directories(echoion_log_rotation_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
)
|
||||
target_compile_features(echoion_log_rotation_tests PRIVATE cxx_std_26)
|
||||
add_test(NAME echoion_log_rotation_tests
|
||||
COMMAND echoion_log_rotation_tests)
|
||||
endif()
|
||||
|
||||
# Precompiled headers for the heavy translation units (MusicManager.cpp ~2.4k
|
||||
# lines, Core.cpp, YouTubeClient.cpp). These pull in the same expensive standard
|
||||
# and Void headers, so compiling them once cuts a large slice off build time.
|
||||
@@ -199,6 +281,9 @@ install(EXPORT EchoionCoreTargets
|
||||
DESTINATION lib/cmake/EchoionCore
|
||||
)
|
||||
|
||||
install(FILES abi/module.json
|
||||
DESTINATION share/echoion/components/EchoionCore/${PROJECT_VERSION}/abi)
|
||||
|
||||
# Package config files
|
||||
include(CMakePackageConfigHelpers)
|
||||
write_basic_package_version_file(
|
||||
@@ -220,13 +305,64 @@ install(FILES
|
||||
)
|
||||
|
||||
if(BUILD_TESTS)
|
||||
add_executable(echoion_core_room_state_tests
|
||||
tests/test_listening_room_state.cpp)
|
||||
target_include_directories(echoion_core_room_state_tests PRIVATE
|
||||
add_executable(echoion_core_config_loader_tests
|
||||
tests/test_config_loader.cpp)
|
||||
target_include_directories(echoion_core_config_loader_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_link_libraries(echoion_core_config_loader_tests PRIVATE EchoionCore)
|
||||
add_test(NAME echoion_core_config_loader_tests
|
||||
COMMAND echoion_core_config_loader_tests)
|
||||
|
||||
add_executable(echoion_core_gapless_handoff_tests
|
||||
tests/test_gapless_handoff.cpp)
|
||||
target_include_directories(echoion_core_gapless_handoff_tests PRIVATE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/include)
|
||||
target_compile_features(echoion_core_gapless_handoff_tests PRIVATE cxx_std_23)
|
||||
add_test(NAME echoion_core_gapless_handoff_tests
|
||||
COMMAND echoion_core_gapless_handoff_tests)
|
||||
|
||||
add_executable(echoion_core_license_verifier_tests
|
||||
tests/test_license_verifier.cpp)
|
||||
target_include_directories(echoion_core_license_verifier_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_link_libraries(echoion_core_room_state_tests PRIVATE EchoionCore)
|
||||
add_test(NAME echoion_core_room_state_tests
|
||||
COMMAND echoion_core_room_state_tests)
|
||||
target_link_libraries(echoion_core_license_verifier_tests PRIVATE
|
||||
EchoionCore OpenSSL::Crypto)
|
||||
add_test(NAME echoion_core_license_verifier_tests
|
||||
COMMAND echoion_core_license_verifier_tests)
|
||||
|
||||
add_executable(echoion_core_extension_state_tests
|
||||
tests/test_extension_state.cpp)
|
||||
target_include_directories(echoion_core_extension_state_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_link_libraries(echoion_core_extension_state_tests PRIVATE EchoionCore)
|
||||
add_test(NAME echoion_core_extension_state_tests
|
||||
COMMAND echoion_core_extension_state_tests)
|
||||
|
||||
add_executable(echoion_core_teamspeak_directory_tests
|
||||
tests/test_teamspeak_directory.cpp
|
||||
src/TeamSpeakDirectoryService.cpp)
|
||||
target_include_directories(echoion_core_teamspeak_directory_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_link_libraries(echoion_core_teamspeak_directory_tests PRIVATE EchoionCore)
|
||||
add_test(NAME echoion_core_teamspeak_directory_tests
|
||||
COMMAND echoion_core_teamspeak_directory_tests)
|
||||
|
||||
add_executable(echoion_core_url_shortener_tests
|
||||
tests/test_url_shortener.cpp)
|
||||
target_include_directories(echoion_core_url_shortener_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_link_libraries(echoion_core_url_shortener_tests PRIVATE EchoionCore)
|
||||
add_test(NAME echoion_core_url_shortener_tests
|
||||
COMMAND echoion_core_url_shortener_tests)
|
||||
|
||||
add_executable(echoion_core_plugin_compatibility_tests
|
||||
tests/test_plugin_compatibility.cpp)
|
||||
target_include_directories(echoion_core_plugin_compatibility_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src")
|
||||
target_link_libraries(echoion_core_plugin_compatibility_tests PRIVATE
|
||||
EchoionCore)
|
||||
void_add_tests(echoion_core_plugin_compatibility_tests)
|
||||
endif()
|
||||
|
||||
option(BUNDLE_FFMPEG "Bundle FFmpeg libraries with installation" OFF)
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"contractId": "echoion.module.core",
|
||||
"descriptor": "echoion_module_descriptor_v1",
|
||||
"querySymbol": "echoion_module_abi_query",
|
||||
"moduleId": "EchoionCore",
|
||||
"activation": "reloadable",
|
||||
"dependencies": [
|
||||
{
|
||||
"moduleId": "EchoionApi",
|
||||
"versionRange": "^2.0.0",
|
||||
"abiHash": "sha256:d50293d345a97e52f9844088bdd42277f566bc815a21b7636d3e053f06c6c113"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"componentId": "EchoionCore",
|
||||
"productCompatibility": ">=2.0.0 <3.0.0",
|
||||
"publishNightly": true,
|
||||
"cmakeOptions": {}
|
||||
}
|
||||
@@ -120,6 +120,9 @@ namespace Echoion::Core
|
||||
getCommand(std::string_view name) const;
|
||||
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>>
|
||||
getAllCommands() const;
|
||||
[[nodiscard]] bool registerExternalCommand(
|
||||
std::string owner, std::string primaryName, CommandPtr command);
|
||||
void unregisterExternalCommands(std::string_view owner);
|
||||
|
||||
// Get commands visible to a specific client (for help)
|
||||
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>>
|
||||
@@ -202,6 +205,8 @@ namespace Echoion::Core
|
||||
|
||||
// List for generating help: {"play", PlayCommand}
|
||||
std::vector<CommandEntry> uniqueCommands_;
|
||||
std::map<std::string, std::vector<CommandPtr>, std::less<>>
|
||||
externalCommands_;
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <Types.hpp>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
@@ -22,6 +23,12 @@ namespace Echoion::Core
|
||||
[[nodiscard]] static Api::Result<Api::AppConfig>
|
||||
loadFromFile(const std::filesystem::path& path);
|
||||
|
||||
// Parse, migrate, and normalize a complete JSON configuration. This
|
||||
// is shared by file loading and live configuration updates so
|
||||
// legacy fields have identical behavior through both entry points.
|
||||
[[nodiscard]] static Api::Result<Api::AppConfig>
|
||||
loadFromJson(std::string_view json);
|
||||
|
||||
// Save configuration to JSON file
|
||||
[[nodiscard]] static Api::Result<void>
|
||||
saveToFile(const std::filesystem::path& path,
|
||||
@@ -34,7 +41,8 @@ namespace Echoion::Core
|
||||
[[nodiscard]] static Api::AppConfig createDefaultConfig();
|
||||
|
||||
// Clamp/normalize values that carry hard limits after loading
|
||||
// (e.g. the yt-dlp concurrency cap). Applied by loadFromFile.
|
||||
// (e.g. the yt-dlp concurrency cap). Applied by all load/update
|
||||
// paths.
|
||||
static void normalize(Api::AppConfig& config);
|
||||
};
|
||||
|
||||
|
||||
@@ -6,18 +6,19 @@
|
||||
#include "MusicManager.hpp"
|
||||
#include "NetworkClient.hpp"
|
||||
#include "RpcServer.hpp"
|
||||
#include "licensing/LicenseManager.hpp"
|
||||
#ifdef ECHOION_WITH_WEB
|
||||
#include "echoion/web/HttpServer.hpp"
|
||||
#endif
|
||||
#include <ConfigManager.hpp>
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <CoreInterface.hpp>
|
||||
#include <Void/Async/EventBus.hpp>
|
||||
#include <Database.hpp>
|
||||
#include <RpcTypes.hpp>
|
||||
#include <StateBlob.hpp>
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/EventBus.hpp>
|
||||
#include <Void/Service/Registry.hpp>
|
||||
#include <atomic>
|
||||
#include <map>
|
||||
@@ -35,7 +36,8 @@ namespace Void::Logging
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
class ListeningRoomManager;
|
||||
class PluginHost;
|
||||
class TeamSpeakDirectoryService;
|
||||
|
||||
// Main Core implementation of ICoreInterface
|
||||
class Core : public Api::ICoreInterface
|
||||
@@ -135,6 +137,8 @@ namespace Echoion::Core
|
||||
void setAudioDataCallback(
|
||||
const MusicManager::AudioDataCallback& callback);
|
||||
Api::Result<void> reloadConfig() override;
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
managePluginsJson(const std::string& requestJson) override;
|
||||
|
||||
// Internal implementations using full types
|
||||
Api::Result<void> playTrack(const Api::TrackInfo& track);
|
||||
@@ -167,12 +171,13 @@ namespace Echoion::Core
|
||||
void updateWhisperList();
|
||||
void setupRpcHandlers();
|
||||
void setupEventBusSubscriptions() noexcept;
|
||||
void applyUrlShorteningConfig();
|
||||
|
||||
// Fetch an online client's avatar bytes (TS local cache, then the
|
||||
// myTeamSpeak URL, then a legacy file-transfer download) and persist
|
||||
// them — and the myTS URL — to the database keyed by uid. Returns
|
||||
// {contentType, bytes} on success. Web-agnostic; used by both the
|
||||
// avatar HTTP provider and the background warmer.
|
||||
// myTeamSpeak URL, then a legacy file-transfer download) and
|
||||
// persist them — and the myTS URL — to the database keyed by uid.
|
||||
// Returns {contentType, bytes} on success. Web-agnostic; used by
|
||||
// both the avatar HTTP provider and the background warmer.
|
||||
[[nodiscard]] std::optional<std::pair<std::string, std::string>>
|
||||
fetchClientAvatarBytes(const std::string& uid,
|
||||
uint64_t clientId);
|
||||
@@ -183,18 +188,22 @@ namespace Echoion::Core
|
||||
|
||||
// Build the console + split-file logging stack and install it as
|
||||
// the global Void::Log sink (logSink_ must outlive logging).
|
||||
void installLogging();
|
||||
void installLogging(const std::filesystem::path& logDirectory,
|
||||
const Api::LoggingConfig& config);
|
||||
|
||||
// Guard helper: ok if initialized, else a ServiceUnavailable error.
|
||||
[[nodiscard]] Api::Result<void> requireInitialized() const noexcept;
|
||||
// Normal bot operations are denied while licensing is update-only.
|
||||
[[nodiscard]] Api::Result<void> requireOperational() const noexcept;
|
||||
|
||||
// Components
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::unique_ptr<Licensing::LicenseManager> licenseManager_;
|
||||
std::shared_ptr<LyricsService> lyricsService_;
|
||||
std::shared_ptr<MusicManager> musicManager_;
|
||||
std::shared_ptr<ListeningRoomManager> listeningRooms_;
|
||||
std::string pendingListeningRoomState_;
|
||||
std::unique_ptr<CommandManager> commandManager_;
|
||||
std::shared_ptr<PluginHost> extensionPlugins_;
|
||||
std::shared_ptr<TeamSpeakDirectoryService> directoryService_;
|
||||
Api::PluginInterfacePtr pluginInterface_;
|
||||
|
||||
// State
|
||||
@@ -210,12 +219,6 @@ namespace Echoion::Core
|
||||
std::vector<Api::EventCallback> eventCallbacks_;
|
||||
mutable std::mutex eventMutex_;
|
||||
|
||||
// Admin / DJ tracking (RPC clients whose TeamSpeak identity is in
|
||||
// a configured teamspeak.adminGroups / djGroups server group).
|
||||
std::vector<uint64_t> adminClients_;
|
||||
std::vector<uint64_t> djClients_;
|
||||
mutable std::mutex adminMutex_;
|
||||
|
||||
// Authenticated RPC client -> stable TS uid + nickname, resolved
|
||||
// at token auth. Keys per-user features (favorites, vote-skip).
|
||||
struct RpcIdentity {
|
||||
@@ -226,10 +229,12 @@ namespace Echoion::Core
|
||||
mutable std::mutex rpcIdentityMutex_;
|
||||
[[nodiscard]] std::optional<RpcIdentity>
|
||||
rpcIdentity(uint64_t clientId) const;
|
||||
[[nodiscard]] bool hasLiveTeamSpeakRole(
|
||||
uint64_t clientId,
|
||||
const std::vector<uint64_t>& configuredGroups) const;
|
||||
|
||||
// Full identity behind an RPC token: uid, display nickname and
|
||||
// admin standing. Shared by token auth, IP autologin and the
|
||||
// watch-together identity resolver.
|
||||
// admin standing. Shared by token auth and IP autologin.
|
||||
struct TokenIdentity {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
@@ -238,8 +243,9 @@ namespace Echoion::Core
|
||||
};
|
||||
[[nodiscard]] std::optional<TokenIdentity>
|
||||
identityForToken(const std::string& token);
|
||||
// Mark an RPC connection authenticated as `identity` (auth set,
|
||||
// admin list, per-client identity map).
|
||||
// Mark an RPC connection authenticated as `identity` and retain its
|
||||
// stable TeamSpeak identity. Roles are checked live for each
|
||||
// request.
|
||||
void registerRpcAuth(uint64_t clientId,
|
||||
const TokenIdentity& identity);
|
||||
// Guards RestartWebInterface against overlapping restarts.
|
||||
@@ -249,7 +255,8 @@ namespace Echoion::Core
|
||||
std::shared_ptr<Api::Database> database_;
|
||||
|
||||
// Background avatar cache warmer + the uids already cached this
|
||||
// session (so we don't re-download an unchanged avatar every cycle).
|
||||
// session (so we don't re-download an unchanged avatar every
|
||||
// cycle).
|
||||
std::jthread avatarWarmer_;
|
||||
std::unordered_set<std::string> warmedUids_;
|
||||
|
||||
@@ -257,9 +264,9 @@ namespace Echoion::Core
|
||||
std::shared_ptr<RpcServer> rpcServer_;
|
||||
|
||||
#ifdef ECHOION_WITH_WEB
|
||||
// Browser web interface: serves the static UI and hosts the
|
||||
// independent sync-watch WebSocket. Bot control from the browser
|
||||
// goes straight to the RPC server, so this holds no bot handles.
|
||||
// Browser web interface: serves the static dashboard and
|
||||
// same-origin RPC bridge. Bot control still terminates at the RPC
|
||||
// server.
|
||||
std::shared_ptr<Web::HttpServer> webServer_;
|
||||
#endif
|
||||
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
|
||||
#include <PluginInterface.hpp>
|
||||
#include <Void/Async/EventBus.hpp>
|
||||
|
||||
#include <map>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
class NetworkClient;
|
||||
|
||||
class ListeningRoomManager final
|
||||
{
|
||||
public:
|
||||
struct RoomSummary {
|
||||
std::string name;
|
||||
uint64_t ownerId{};
|
||||
std::vector<uint64_t> members;
|
||||
bool isPlaying{};
|
||||
bool isPaused{};
|
||||
std::size_t queueSize{};
|
||||
};
|
||||
struct PersistedRoom {
|
||||
std::string name;
|
||||
uint64_t ownerId{};
|
||||
std::vector<uint64_t> members;
|
||||
Api::HotReloadState state;
|
||||
};
|
||||
|
||||
ListeningRoomManager(std::shared_ptr<NetworkClient> network,
|
||||
Api::ConfigManager& config, Void::EventBus::EventBus& events);
|
||||
~ListeningRoomManager();
|
||||
ListeningRoomManager(const ListeningRoomManager&) = delete;
|
||||
ListeningRoomManager& operator=(const ListeningRoomManager&) = delete;
|
||||
|
||||
void setPluginInterface(Api::PluginInterfacePtr plugin);
|
||||
void setChangeCallback(std::function<void()> callback);
|
||||
[[nodiscard]] Api::Result<void>
|
||||
create(std::string name, uint64_t ownerId);
|
||||
[[nodiscard]] Api::Result<void> remove(const std::string& name,
|
||||
uint64_t requesterId);
|
||||
[[nodiscard]] Api::Result<void> join(const std::string& name,
|
||||
uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<void> leave(uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::string> play(const std::string& name,
|
||||
std::string query, uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<void> pause(const std::string& name,
|
||||
uint64_t requesterId);
|
||||
[[nodiscard]] Api::Result<void> resume(const std::string& name,
|
||||
uint64_t requesterId);
|
||||
[[nodiscard]] Api::Result<void> stop(const std::string& name,
|
||||
uint64_t requesterId);
|
||||
[[nodiscard]] Api::Result<void> skip(const std::string& name,
|
||||
uint64_t requesterId);
|
||||
[[nodiscard]] Api::Result<void> removeQueueEntry(const std::string& name,
|
||||
uint64_t queueId, uint64_t requesterId);
|
||||
[[nodiscard]] Api::Result<void> moveQueueEntry(const std::string& name,
|
||||
uint64_t queueId, uint32_t newPosition, uint64_t requesterId);
|
||||
[[nodiscard]] Api::Result<void> clearQueue(const std::string& name,
|
||||
uint64_t requesterId);
|
||||
[[nodiscard]] Api::Result<std::vector<Api::QueueEntry>>
|
||||
queue(const std::string& name) const;
|
||||
[[nodiscard]] std::vector<RoomSummary> list() const;
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
roomForClient(uint64_t clientId) const;
|
||||
[[nodiscard]] std::vector<PersistedRoom> snapshot() const;
|
||||
[[nodiscard]] Api::Result<void>
|
||||
restore(const std::vector<PersistedRoom>& rooms);
|
||||
void shutdown();
|
||||
|
||||
private:
|
||||
struct Room {
|
||||
std::string name;
|
||||
uint64_t ownerId{};
|
||||
Api::IPluginInterface::AudioStreamId streamId{};
|
||||
std::set<uint64_t> members;
|
||||
std::unique_ptr<MusicManager> music;
|
||||
};
|
||||
|
||||
[[nodiscard]] Api::ServerConfig serverConfigFor(
|
||||
const std::string& roomName) const;
|
||||
[[nodiscard]] Api::Result<void> refreshRecipients(Room& room);
|
||||
[[nodiscard]] Room* findLocked(const std::string& name);
|
||||
[[nodiscard]] const Room* findLocked(const std::string& name) const;
|
||||
|
||||
std::shared_ptr<NetworkClient> network_;
|
||||
Api::ConfigManager& config_;
|
||||
Void::EventBus::EventBus& events_;
|
||||
Api::PluginInterfacePtr plugin_;
|
||||
std::map<std::string, std::unique_ptr<Room>> rooms_;
|
||||
std::map<uint64_t, std::string> membership_;
|
||||
mutable std::mutex mutex_;
|
||||
std::function<void()> changeCallback_;
|
||||
void notifyChanged() const;
|
||||
};
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
[[nodiscard]] inline Api::Result<std::string>
|
||||
validateListeningRoomName(std::string name)
|
||||
{
|
||||
const auto first = name.find_first_not_of(" \t\r\n");
|
||||
if (first == std::string::npos) return Api::fail(
|
||||
Api::ErrorCode::InvalidArgument, "room name is required");
|
||||
const auto last = name.find_last_not_of(" \t\r\n");
|
||||
name = name.substr(first, last - first + 1);
|
||||
if (name.size() > 48 || std::ranges::any_of(name,
|
||||
[](unsigned char value) { return std::iscntrl(value) != 0; })) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"room name must be 1-48 printable characters");
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::string
|
||||
canonicalListeningRoomName(std::string_view name)
|
||||
{
|
||||
std::string key{name};
|
||||
std::ranges::transform(key, key.begin(), [](unsigned char value) {
|
||||
return static_cast<char>(std::tolower(value));
|
||||
});
|
||||
return key;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <filesystem>
|
||||
#include <system_error>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
// Archive a non-empty active log into <directory>/history and prune the
|
||||
// oldest archives. This is intentionally performed before opening the
|
||||
// logger so every process start gets a fresh active file.
|
||||
[[nodiscard]] std::error_code
|
||||
rotateLogOnStartup(const std::filesystem::path& activeLog,
|
||||
std::size_t maxFiles) noexcept;
|
||||
} // namespace Echoion::Core
|
||||
@@ -80,7 +80,15 @@ namespace Echoion::Core
|
||||
// Re-apply the source-chain settings (order, cooldown, instance
|
||||
// lists) after a config reload.
|
||||
void applySourcesConfig(const Api::SourcesConfig& sources);
|
||||
|
||||
void addTrackSource(std::shared_ptr<ITrackSource> source);
|
||||
void setSharedYouTubeClient(std::shared_ptr<YouTubeClient> client)
|
||||
{
|
||||
youTubeClient_ = std::move(client);
|
||||
}
|
||||
[[nodiscard]] std::shared_ptr<YouTubeClient> sharedYouTubeClient() const
|
||||
{
|
||||
return youTubeClient_;
|
||||
}
|
||||
// Re-apply bot settings (queue size, track timeout, playlist
|
||||
// import gate) after a config reload. Does not touch the live
|
||||
// volume.
|
||||
|
||||
@@ -25,19 +25,25 @@ namespace Echoion::Core
|
||||
NetworkClient();
|
||||
~NetworkClient() override;
|
||||
|
||||
Api::Result<void> initialize(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy =
|
||||
std::nullopt) override;
|
||||
Api::Result<void>
|
||||
initialize(const std::optional<Void::Net::ProxyConfig>& proxy =
|
||||
std::nullopt) override;
|
||||
void shutdown() override;
|
||||
|
||||
// Synchronous requests
|
||||
[[nodiscard]] Api::Result<Void::Net::Response>
|
||||
get(std::string_view url,
|
||||
const std::vector<Void::Net::Header>& headers = {}) override;
|
||||
[[nodiscard]] Api::Result<Void::Net::Response>
|
||||
post(std::string_view url, std::string_view body,
|
||||
const std::vector<Void::Net::Header>& headers = {})
|
||||
override;
|
||||
[[nodiscard]] Api::Result<Void::Net::Response> get(
|
||||
std::string_view url,
|
||||
const std::vector<Void::Net::Header>& headers = {}) override;
|
||||
[[nodiscard]] Api::Result<Void::Net::Response> post(
|
||||
std::string_view url, std::string_view body,
|
||||
const std::vector<Void::Net::Header>& headers = {}) override;
|
||||
// Security-sensitive HTTPS request. Unlike legacy media scraping
|
||||
// requests, this always verifies the peer certificate and follows
|
||||
// no redirects so credentials cannot be forwarded to another
|
||||
// origin.
|
||||
[[nodiscard]] Api::Result<Void::Net::Response> postVerifiedTls(
|
||||
std::string_view url, std::string_view body,
|
||||
const std::vector<Void::Net::Header>& headers = {});
|
||||
[[nodiscard]] Api::Result<Void::Net::Response>
|
||||
request(const Void::Net::Request& req) override;
|
||||
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
#pragma once
|
||||
|
||||
#include <ExtensionPlugin.hpp>
|
||||
#include <NetworkTypes.hpp>
|
||||
#include <Void/Plugin/Manager.hpp>
|
||||
#include <Void/Service/PluginService.hpp>
|
||||
#include <Void/Service/Registry.hpp>
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
class CommandManager;
|
||||
class MusicManager;
|
||||
class ITrackSource;
|
||||
|
||||
class PluginHost final : public std::enable_shared_from_this<PluginHost>
|
||||
{
|
||||
public:
|
||||
|
||||
struct Configuration {
|
||||
std::filesystem::path configDirectory;
|
||||
std::filesystem::path stateDirectory;
|
||||
std::string publicUrl;
|
||||
std::optional<Void::Net::ProxyConfig> proxy;
|
||||
std::string shortenerProvider = "url-shortener-internal";
|
||||
};
|
||||
|
||||
PluginHost(CommandManager& commands,
|
||||
std::shared_ptr<MusicManager>
|
||||
music,
|
||||
std::function<bool(uint64_t)>
|
||||
isAdmin,
|
||||
std::function<void(std::shared_ptr<ITrackSource>)>
|
||||
mediaSink,
|
||||
Configuration configuration);
|
||||
~PluginHost();
|
||||
|
||||
void loadDirectory(const std::filesystem::path& directory);
|
||||
void loadManagedDirectory(const std::filesystem::path& directory);
|
||||
// Bind and validate cross-plugin services after every startup
|
||||
// directory has been loaded.
|
||||
[[nodiscard]] bool finalizeLoading();
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
manage(const std::string& requestJson);
|
||||
void setChangeCallback(std::function<void()> callback);
|
||||
void dispatch(const Api::PluginEvent& event) const;
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
call(std::string_view plugin, std::string_view method,
|
||||
std::string params, uint64_t clientId) const;
|
||||
[[nodiscard]] std::vector<Api::ExtensionWebAsset> webAssets() const;
|
||||
[[nodiscard]] std::vector<std::string> names() const;
|
||||
[[nodiscard]] bool reconfigure(Configuration configuration);
|
||||
[[nodiscard]] std::shared_ptr<Void::ShortUrl::IShortener>
|
||||
shortener() const;
|
||||
[[nodiscard]] Void::ShortUrl::ResolveResult
|
||||
resolveShortLink(std::string_view key) const;
|
||||
struct State {
|
||||
std::string name;
|
||||
std::string json;
|
||||
std::uint32_t version{};
|
||||
};
|
||||
[[nodiscard]] std::vector<State> snapshotStates() const;
|
||||
void restoreStates(const std::vector<State>& states);
|
||||
|
||||
private:
|
||||
|
||||
void publish(std::string name);
|
||||
void unpublish(std::string name);
|
||||
void notifyChanged() const;
|
||||
[[nodiscard]] std::string
|
||||
pluginConfiguration(std::string_view name) const;
|
||||
[[nodiscard]] bool bindShortenerServices();
|
||||
|
||||
CommandManager& commands_;
|
||||
std::shared_ptr<MusicManager> music_;
|
||||
std::function<bool(uint64_t)> isAdmin_;
|
||||
std::function<void(std::shared_ptr<ITrackSource>)> mediaSink_;
|
||||
Void::Plugin::PluginManager plugins_;
|
||||
Void::Service::ServiceRegistry shortenerRegistry_;
|
||||
Void::Service::ServiceRegistry internalShortenerRegistry_;
|
||||
std::unique_ptr<
|
||||
Void::Service::PluginServiceBinding<Void::ShortUrl::IShortener>>
|
||||
shortenerBinding_;
|
||||
std::unique_ptr<
|
||||
Void::Service::PluginServiceBinding<Void::ShortUrl::IShortener>>
|
||||
internalShortenerBinding_;
|
||||
Void::Plugin::ReloadCallbackId reloadCallback_{};
|
||||
mutable std::mutex reconfigureMutex_;
|
||||
mutable std::mutex mutex_;
|
||||
Configuration configuration_;
|
||||
std::vector<std::shared_ptr<class PluginTrackSource>> sources_;
|
||||
std::function<void()> changeCallback_;
|
||||
struct ManagedPlugin {
|
||||
std::string version;
|
||||
std::filesystem::path path;
|
||||
};
|
||||
std::filesystem::path managedDirectory_;
|
||||
std::unordered_map<std::string, ManagedPlugin> managed_;
|
||||
std::unordered_map<std::string, std::filesystem::path> loadedPaths_;
|
||||
};
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <TrackTypes.hpp>
|
||||
#include <ExtensionPlugin.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <cstdint>
|
||||
@@ -85,26 +86,6 @@ namespace Echoion::Core::Dto
|
||||
std::string text;
|
||||
};
|
||||
|
||||
struct ListeningRoomRequest {
|
||||
std::string room;
|
||||
};
|
||||
|
||||
struct ListeningRoomPlayRequest {
|
||||
std::string room;
|
||||
std::string query;
|
||||
};
|
||||
|
||||
struct ListeningRoomQueueRequest {
|
||||
std::string room;
|
||||
std::uint64_t queueId = 0;
|
||||
};
|
||||
|
||||
struct ListeningRoomMoveRequest {
|
||||
std::string room;
|
||||
std::uint64_t queueId = 0;
|
||||
std::uint32_t newPosition = 0;
|
||||
};
|
||||
|
||||
// ── RPC handler responses ───────────────────────────────────────────────
|
||||
|
||||
struct Track {
|
||||
@@ -116,7 +97,7 @@ namespace Echoion::Core::Dto
|
||||
int source = 0;
|
||||
std::optional<std::string> thumbnailUrl;
|
||||
std::optional<std::string> url; // originalUrl (play-by-url)
|
||||
// Shortened faumaray.ru link when available; the web UI prefers
|
||||
// Provider-generated shortened link when available; the web UI prefers
|
||||
// it for "open original link" (falls back to url).
|
||||
std::optional<std::string> shortenedUrl;
|
||||
};
|
||||
@@ -201,19 +182,19 @@ namespace Echoion::Core::Dto
|
||||
float volume = 0.0f;
|
||||
};
|
||||
|
||||
struct ListeningRoom {
|
||||
std::string name;
|
||||
std::uint64_t ownerId = 0;
|
||||
std::vector<std::uint64_t> members;
|
||||
bool isPlaying = false;
|
||||
bool isPaused = false;
|
||||
std::uint64_t queueSize = 0;
|
||||
bool isOwner = false;
|
||||
struct Capabilities {
|
||||
bool plugins = false;
|
||||
bool webExtensions = false;
|
||||
};
|
||||
|
||||
struct ListeningRoomList {
|
||||
std::vector<ListeningRoom> rooms;
|
||||
std::optional<std::string> currentRoom;
|
||||
struct PluginCallRequest {
|
||||
std::string plugin;
|
||||
std::string method;
|
||||
std::string params;
|
||||
};
|
||||
|
||||
struct PluginExtensions {
|
||||
std::vector<Api::ExtensionWebAsset> assets;
|
||||
};
|
||||
|
||||
struct Autoplay {
|
||||
@@ -227,26 +208,6 @@ namespace Echoion::Core::Dto
|
||||
std::string language;
|
||||
};
|
||||
|
||||
// Custom emoji metadata (name + mime); the image itself is served at
|
||||
// GET /emoji/<name>, not inlined here.
|
||||
struct CustomEmojiDto {
|
||||
std::string name;
|
||||
std::string mime;
|
||||
std::string addedBy;
|
||||
};
|
||||
struct CustomEmojiList {
|
||||
std::vector<CustomEmojiDto> emojis;
|
||||
};
|
||||
// AddCustomEmoji request: name + mime + base64-encoded image bytes.
|
||||
struct AddEmojiRequest {
|
||||
std::string name;
|
||||
std::string mime;
|
||||
std::string dataBase64;
|
||||
};
|
||||
struct EmojiNameRequest {
|
||||
std::string name;
|
||||
};
|
||||
|
||||
struct QueuedResponse {
|
||||
bool success = true;
|
||||
std::uint64_t queueId = 0;
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
#pragma once
|
||||
|
||||
#include <PluginInterface.hpp>
|
||||
#include <PluginTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
// One authoritative, event-refreshed TeamSpeak topology cache. The public
|
||||
// serializer is deliberately structural: it has no fields for UIDs, groups,
|
||||
// database IDs, addresses, or query clients, so private data cannot leak by
|
||||
// accidentally toggling a flag at the HTTP boundary.
|
||||
class TeamSpeakDirectoryService
|
||||
{
|
||||
public:
|
||||
|
||||
struct Snapshot {
|
||||
Api::ServerInfo server;
|
||||
std::vector<Api::ChannelInfo> channels;
|
||||
std::vector<Api::ClientInfo> clients;
|
||||
bool connected = false;
|
||||
std::uint64_t revision = 0;
|
||||
};
|
||||
|
||||
void setPluginInterface(Api::PluginInterfacePtr plugin);
|
||||
[[nodiscard]] Api::Result<void> refresh();
|
||||
void handleEvent(Api::PluginEventType type);
|
||||
|
||||
[[nodiscard]] Snapshot snapshot() const;
|
||||
[[nodiscard]] Void::Json::Value publicJson() const;
|
||||
[[nodiscard]] Void::Json::Value adminJson() const;
|
||||
|
||||
// TeamSpeak stores a sibling's predecessor id in channel_order.
|
||||
// This helper turns that linked-list representation into display
|
||||
// order and deterministically appends malformed/orphaned entries.
|
||||
[[nodiscard]] static std::vector<Api::ChannelInfo>
|
||||
orderChannels(std::vector<Api::ChannelInfo> channels);
|
||||
|
||||
private:
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
Api::PluginInterfacePtr plugin_;
|
||||
Snapshot snapshot_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,58 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
#include "NetworkClient.hpp"
|
||||
#include <NetworkTypes.hpp>
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <string_view>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// URL shortener service for faumaray.ru
|
||||
// Thin Core adapter around the universal Void ShortUrl service. It owns no
|
||||
// provider and performs no HTTP itself: the getter returns a pinned service
|
||||
// instance for each operation, making calls safe across plugin hot reloads.
|
||||
class UrlShortener
|
||||
{
|
||||
public:
|
||||
|
||||
explicit UrlShortener(std::shared_ptr<NetworkClient> networkClient);
|
||||
~UrlShortener();
|
||||
using ProviderGetter = std::function<
|
||||
std::shared_ptr<Void::ShortUrl::IShortener>()>;
|
||||
|
||||
void setProvider(ProviderGetter provider);
|
||||
void setSources(const std::vector<std::string>& sources);
|
||||
|
||||
// Shorten a YouTube URL via faumaray.ru
|
||||
// Returns shortened URL in format: https://faumaray.ru/xxxxx
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
shortenYouTubeUrl(std::string_view videoId);
|
||||
|
||||
// Shorten any URL via faumaray.ru
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
shortenUrl(std::string_view originalUrl);
|
||||
|
||||
// Get cached shortened URL if available
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
getCachedUrl(std::string_view originalUrl) const;
|
||||
|
||||
// Clear the URL cache
|
||||
void clearCache();
|
||||
|
||||
// Set cache TTL (default: 24 hours)
|
||||
void setCacheTtl(std::chrono::hours ttl);
|
||||
shortenUrl(std::string_view originalUrl,
|
||||
Api::TrackSource source) const;
|
||||
|
||||
private:
|
||||
|
||||
struct CacheEntry {
|
||||
std::string shortenedUrl;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
[[nodiscard]] bool sourceAllowed(Api::TrackSource source) const;
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
mutable std::mutex cacheMutex_;
|
||||
std::unordered_map<std::string, CacheEntry> cache_;
|
||||
std::chrono::hours cacheTtl_{24};
|
||||
|
||||
// Clean expired entries from cache
|
||||
void cleanExpiredCache();
|
||||
mutable std::mutex mutex_;
|
||||
ProviderGetter provider_;
|
||||
std::unordered_set<Api::TrackSource> sources_ = {
|
||||
Api::TrackSource::YouTube};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -102,8 +102,7 @@ namespace Echoion::Core
|
||||
nullptr,
|
||||
std::function<void()> onComplete = nullptr);
|
||||
|
||||
// Extract video ID from various YouTube URL formats (handles
|
||||
// redirects for short URLs)
|
||||
// Extract a video ID from known YouTube URL formats or a bare ID.
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
extractVideoId(std::string_view url);
|
||||
[[nodiscard]] static std::optional<std::string>
|
||||
@@ -119,7 +118,6 @@ namespace Echoion::Core
|
||||
// Get best audio stream URL using yt-dlp
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
getAudioStreamUrl(std::string_view videoId);
|
||||
|
||||
// Resolve a stream URL for any yt-dlp-supported page URL
|
||||
// (SoundCloud, Bandcamp, VK, radio pages, ...). When useProxy is
|
||||
// false the configured proxy is explicitly bypassed with a
|
||||
@@ -154,6 +152,14 @@ namespace Echoion::Core
|
||||
|
||||
// Enable/disable URL shortening for track links
|
||||
void setUrlShorteningEnabled(bool enabled);
|
||||
void setUrlShortenerProvider(UrlShortener::ProviderGetter provider);
|
||||
void setUrlShorteningSources(
|
||||
const std::vector<std::string>& sources);
|
||||
void setUrlShorteningTimeout(std::chrono::milliseconds timeout);
|
||||
// Apply the provider-neutral policy to resolved tracks from any
|
||||
// source. Operations are best-effort and timeout-bounded.
|
||||
void populateShortenedUrls(std::vector<Api::TrackInfo>& tracks);
|
||||
void populateShortenedUrl(Api::TrackInfo& track);
|
||||
|
||||
// Gate yt-dlp's periodic background self-update
|
||||
// (features.enableAutoUpdateCheck). Set before initialize().
|
||||
@@ -209,9 +215,7 @@ namespace Echoion::Core
|
||||
mutable std::mutex configMutex_;
|
||||
size_t maxConcurrentResolutions_ = 4;
|
||||
bool urlShorteningEnabled_ = true;
|
||||
std::chrono::milliseconds urlShorteningTimeout_{3000};
|
||||
|
||||
// Populate shortened URLs for tracks
|
||||
void populateShortenedUrls(std::vector<Api::TrackInfo>& tracks);
|
||||
void populateShortenedUrl(Api::TrackInfo& track);
|
||||
};
|
||||
} // namespace Echoion::Core
|
||||
@@ -132,9 +132,12 @@ namespace Echoion::Core
|
||||
std::unique_ptr<Void::Concurrency::ThreadPool> pool_;
|
||||
|
||||
// yt-dlp download URLs
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_LINUX =
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_LINUX_X86_64 =
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/"
|
||||
"yt-dlp";
|
||||
"yt-dlp_linux";
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_LINUX_AARCH64 =
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/"
|
||||
"yt-dlp_linux_aarch64";
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_WINDOWS =
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/"
|
||||
"yt-dlp.exe";
|
||||
|
||||
@@ -94,7 +94,7 @@ namespace Echoion::Core
|
||||
return escapeMarkdown(text);
|
||||
}
|
||||
|
||||
// The best public link for a track: the shortened faumaray link when
|
||||
// The best public link for a track: the provider-generated short link when
|
||||
// available, otherwise the original source URL (e.g. the YouTube or
|
||||
// Yandex Music page). Used so every list — search, queue, history,
|
||||
// favorites, stats — links to the real track, never the CDN/stream URL.
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
#include "ReloadConfigCommand.hpp"
|
||||
#include "RemoveCommand.hpp"
|
||||
#include "RepeatCommand.hpp"
|
||||
#include "RoomCommand.hpp"
|
||||
#include "ResumeCommand.hpp"
|
||||
#include "RpcInfoCommand.hpp"
|
||||
#include "SearchCommand.hpp"
|
||||
|
||||
@@ -1,218 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/ListeningRoomManager.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <charconv>
|
||||
#include <cctype>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
class RoomCommand final : public Command
|
||||
{
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
auto rooms = ctx.service<ListeningRoomManager>();
|
||||
if (!rooms) {
|
||||
ctx.reply(ctx.tr("Listening rooms are currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto [action, argument] = split(ctx.args);
|
||||
if (action.empty() || action == "list") {
|
||||
list(ctx, *rooms);
|
||||
return;
|
||||
}
|
||||
if (action == "help") {
|
||||
help(ctx);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action == "create") {
|
||||
reply(ctx, rooms->create(argument, ctx.clientId),
|
||||
ctx.trf("Created and joined room '{}'.", argument));
|
||||
return;
|
||||
}
|
||||
if (action == "join") {
|
||||
reply(ctx, rooms->join(argument, ctx.clientId),
|
||||
ctx.trf("Joined room '{}'.", argument));
|
||||
return;
|
||||
}
|
||||
if (action == "leave") {
|
||||
reply(ctx, rooms->leave(ctx.clientId),
|
||||
ctx.tr("Left the listening room."));
|
||||
return;
|
||||
}
|
||||
|
||||
const auto current = rooms->roomForClient(ctx.clientId);
|
||||
if (!current) {
|
||||
ctx.reply(ctx.trf(
|
||||
"Join a room first with {}room join <name>.", ctx.prefix));
|
||||
return;
|
||||
}
|
||||
if (action == "delete") {
|
||||
reply(ctx, rooms->remove(*current, ctx.clientId),
|
||||
ctx.trf("Deleted room '{}'.", *current));
|
||||
} else if (action == "play") {
|
||||
if (argument.empty()) {
|
||||
help(ctx);
|
||||
return;
|
||||
}
|
||||
auto result = rooms->play(*current, argument, ctx.clientId);
|
||||
if (!result) {
|
||||
ctx.reply(ctx.trf("Room action failed: {}",
|
||||
result.error().message));
|
||||
} else {
|
||||
ctx.reply(ctx.trf("Added to '{}': {}", *current, *result));
|
||||
}
|
||||
} else if (action == "pause") {
|
||||
reply(ctx, rooms->pause(*current, ctx.clientId),
|
||||
ctx.trf("Paused room '{}'.", *current));
|
||||
} else if (action == "resume") {
|
||||
reply(ctx, rooms->resume(*current, ctx.clientId),
|
||||
ctx.trf("Resumed room '{}'.", *current));
|
||||
} else if (action == "stop") {
|
||||
reply(ctx, rooms->stop(*current, ctx.clientId),
|
||||
ctx.trf("Stopped room '{}'.", *current));
|
||||
} else if (action == "skip") {
|
||||
reply(ctx, rooms->skip(*current, ctx.clientId),
|
||||
ctx.trf("Skipped in room '{}'.", *current));
|
||||
} else if (action == "clear") {
|
||||
reply(ctx, rooms->clearQueue(*current, ctx.clientId),
|
||||
ctx.trf("Cleared queue for '{}'.", *current));
|
||||
} else if (action == "remove") {
|
||||
const auto queueId = number(argument);
|
||||
if (!queueId) {
|
||||
help(ctx);
|
||||
return;
|
||||
}
|
||||
reply(ctx, rooms->removeQueueEntry(
|
||||
*current, *queueId, ctx.clientId),
|
||||
ctx.trf("Removed queue entry {}.", *queueId));
|
||||
} else if (action == "move") {
|
||||
auto [queueIdText, positionText] = split(argument);
|
||||
const auto queueId = number(queueIdText);
|
||||
const auto position = number(positionText);
|
||||
if (!queueId || !position || *position == 0) {
|
||||
help(ctx);
|
||||
return;
|
||||
}
|
||||
reply(ctx, rooms->moveQueueEntry(*current, *queueId,
|
||||
static_cast<uint32_t>(*position - 1), ctx.clientId),
|
||||
ctx.trf("Moved queue entry {} to position {}.",
|
||||
*queueId, *position));
|
||||
} else if (action == "queue") {
|
||||
queue(ctx, *rooms, *current);
|
||||
} else {
|
||||
help(ctx);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view getDescription() const override
|
||||
{
|
||||
return "Creates, joins and controls independent listening rooms.";
|
||||
}
|
||||
[[nodiscard]] std::string_view getUsage() const override
|
||||
{
|
||||
return "<list|create|join|leave|delete|play|pause|resume|stop|skip|queue|remove|move|clear>";
|
||||
}
|
||||
[[nodiscard]] CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
|
||||
private:
|
||||
static std::pair<std::string, std::string> split(std::string_view input)
|
||||
{
|
||||
const auto first = input.find_first_not_of(" \t");
|
||||
if (first == std::string_view::npos) return {};
|
||||
const auto separator = input.find_first_of(" \t", first);
|
||||
std::string action(input.substr(first, separator - first));
|
||||
std::ranges::transform(action, action.begin(),
|
||||
[](unsigned char value) { return std::tolower(value); });
|
||||
if (separator == std::string_view::npos) return {action, {}};
|
||||
const auto argumentStart = input.find_first_not_of(" \t", separator);
|
||||
return {action, argumentStart == std::string_view::npos
|
||||
? std::string{} : std::string(input.substr(argumentStart))};
|
||||
}
|
||||
|
||||
static std::optional<uint64_t> number(std::string_view text)
|
||||
{
|
||||
uint64_t value = 0;
|
||||
const auto [end, error] = std::from_chars(
|
||||
text.data(), text.data() + text.size(), value);
|
||||
return error == std::errc{} && end == text.data() + text.size()
|
||||
? std::optional<uint64_t>{value} : std::nullopt;
|
||||
}
|
||||
|
||||
static void list(const CommandContext& ctx, ListeningRoomManager& rooms)
|
||||
{
|
||||
const auto all = rooms.list();
|
||||
if (all.empty()) {
|
||||
ctx.reply(ctx.trf("No listening rooms. Create one with {}room create <name>.",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
const auto current = rooms.roomForClient(ctx.clientId);
|
||||
std::stringstream output;
|
||||
output << ctx.tr("Listening rooms:") << '\n';
|
||||
for (const auto& room : all) {
|
||||
const bool selected = current == room.name;
|
||||
output << (selected ? "**> " : "- ")
|
||||
<< escapeMarkdown(room.name) << (selected ? "** " : " ")
|
||||
<< ctx.trf("({} listeners, {} queued{})", room.members.size(),
|
||||
room.queueSize, room.isPlaying ? ", playing" : "") << '\n';
|
||||
}
|
||||
ctx.reply(output.str());
|
||||
}
|
||||
|
||||
static void queue(const CommandContext& ctx, ListeningRoomManager& rooms,
|
||||
const std::string& name)
|
||||
{
|
||||
auto entries = rooms.queue(name);
|
||||
if (!entries) {
|
||||
ctx.reply(ctx.trf("Room action failed: {}", entries.error().message));
|
||||
return;
|
||||
}
|
||||
std::stringstream output;
|
||||
output << ctx.trf("Queue for '{}' ({} tracks):", name, entries->size());
|
||||
for (std::size_t index = 0; index < entries->size(); ++index) {
|
||||
output << '\n' << index + 1 << ". "
|
||||
<< trackLink((*entries)[index].track) << " `#"
|
||||
<< (*entries)[index].queueId << '`';
|
||||
}
|
||||
ctx.reply(output.str());
|
||||
}
|
||||
|
||||
static void reply(const CommandContext& ctx, const Api::Result<void>& result,
|
||||
std::string_view success)
|
||||
{
|
||||
if (result) {
|
||||
ctx.reply(success);
|
||||
} else {
|
||||
ctx.reply(ctx.trf("Room action failed: {}", result.error().message));
|
||||
}
|
||||
}
|
||||
|
||||
static void help(const CommandContext& ctx)
|
||||
{
|
||||
ctx.reply(ctx.trf(
|
||||
"Room commands:\n"
|
||||
"`{}room list`\n`{}room create <name>`\n"
|
||||
"`{}room join <name>`\n`{}room leave`\n"
|
||||
"`{}room play <song>`\n`{}room pause|resume|stop|skip`\n"
|
||||
"`{}room queue`\n`{}room remove <queue-id>`\n"
|
||||
"`{}room move <queue-id> <position>`\n"
|
||||
"`{}room clear`\n`{}room delete`",
|
||||
ctx.prefix, ctx.prefix, ctx.prefix, ctx.prefix, ctx.prefix,
|
||||
ctx.prefix, ctx.prefix, ctx.prefix, ctx.prefix, ctx.prefix,
|
||||
ctx.prefix));
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Core::Detail
|
||||
{
|
||||
[[nodiscard]] inline std::optional<std::uint64_t>
|
||||
uintField(const Void::Json::Value& object, std::string_view key)
|
||||
{
|
||||
const auto* value = object.find(key);
|
||||
if (!value || !value->is_number()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const auto number = value->as_number();
|
||||
// A double equal to 2^64 is what uint64_t::max() rounds to, so use
|
||||
// an exclusive 2^64 bound before converting. Floating-to-integer
|
||||
// conversion outside the destination range is undefined behavior.
|
||||
constexpr double kUint64Limit = 18446744073709551616.0;
|
||||
if (!std::isfinite(number) || number < 0.0 ||
|
||||
std::trunc(number) != number || number >= kUint64Limit) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return static_cast<std::uint64_t>(number);
|
||||
}
|
||||
} // namespace Echoion::Core::Detail
|
||||
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
|
||||
#include "echoion/core/NetworkClient.hpp"
|
||||
#include "echoion/core/licensing/LicenseVerifier.hpp"
|
||||
|
||||
#include <ConfigTypes.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
namespace Echoion::Core::Licensing
|
||||
{
|
||||
class LicenseManager
|
||||
{
|
||||
public:
|
||||
|
||||
LicenseManager(Api::LicensingConfig config,
|
||||
std::shared_ptr<NetworkClient>
|
||||
network,
|
||||
std::filesystem::path stateDirectory);
|
||||
~LicenseManager();
|
||||
|
||||
LicenseManager(const LicenseManager&) = delete;
|
||||
LicenseManager& operator=(const LicenseManager&) = delete;
|
||||
|
||||
/// Load a still-valid cached lease and then attempt an online
|
||||
/// refresh. A failed refresh retains a valid cache; otherwise
|
||||
/// operation remains update-only.
|
||||
void initialize();
|
||||
void shutdown();
|
||||
void refreshNow();
|
||||
|
||||
[[nodiscard]] bool canOperate() const noexcept;
|
||||
[[nodiscard]] LeaseStatus status() const;
|
||||
[[nodiscard]] std::string deviceId() const;
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] Void::Result::Result<LeaseStatus>
|
||||
verifyBundle(std::string_view bundle,
|
||||
std::string_view expectedChallenge);
|
||||
[[nodiscard]] std::string loadOrCreateDeviceId();
|
||||
void installStatus(LeaseStatus status);
|
||||
void installFailure(std::string reason,
|
||||
bool retainValidLease = true);
|
||||
void run(std::stop_token stopToken);
|
||||
|
||||
Api::LicensingConfig config_;
|
||||
std::shared_ptr<NetworkClient> network_;
|
||||
std::filesystem::path stateDirectory_;
|
||||
Void::Update::Keyring rootKeys_;
|
||||
std::string deviceId_;
|
||||
std::atomic<bool> operational_{false};
|
||||
std::atomic<std::int64_t> operationalUntilUnix_{0};
|
||||
mutable std::mutex mutex_;
|
||||
LeaseStatus status_;
|
||||
std::jthread refreshThread_;
|
||||
std::uint64_t minimumSequence_{0};
|
||||
};
|
||||
} // namespace Echoion::Core::Licensing
|
||||
@@ -0,0 +1,60 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Update/Feed.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core::Licensing
|
||||
{
|
||||
enum class Mode { Active, UpdateOnly };
|
||||
|
||||
struct LeaseContext {
|
||||
std::string productId;
|
||||
std::string productVersion;
|
||||
std::string deviceId;
|
||||
std::string buildSignature;
|
||||
std::string challenge;
|
||||
std::chrono::system_clock::time_point now;
|
||||
std::chrono::milliseconds maximumLeaseLifetime{
|
||||
std::chrono::hours(24)};
|
||||
std::uint64_t minimumSequence{0};
|
||||
};
|
||||
|
||||
struct LeaseStatus {
|
||||
Mode mode{Mode::UpdateOnly};
|
||||
std::string reason;
|
||||
std::string licenseId;
|
||||
std::uint64_t sequence{0};
|
||||
std::chrono::system_clock::time_point refreshAfter;
|
||||
std::chrono::system_clock::time_point expiresAt;
|
||||
std::vector<std::string> entitlements;
|
||||
};
|
||||
|
||||
/// Decode a base64/base64url Ed25519 public key and add it to a keyring.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
addPublicKey(Void::Update::Keyring& keyring, std::string_view keyId,
|
||||
std::string_view encodedKey);
|
||||
|
||||
/// Verify a root-signed keyset and append currently valid, non-revoked
|
||||
/// lease signing keys. The pinned root itself remains in the returned
|
||||
/// keyring so a direct emergency root-signed lease can still be accepted.
|
||||
[[nodiscard]] Void::Result::Result<Void::Update::Keyring>
|
||||
verifyKeyset(std::string_view envelopeJson,
|
||||
const Void::Update::Keyring& rootKeys,
|
||||
std::chrono::system_clock::time_point now);
|
||||
|
||||
/// Verify the signed lease and signed revocation snapshot as one decision.
|
||||
/// Any malformed, expired, replayed, mismatched, or revoked input fails
|
||||
/// closed into UpdateOnly through the returned error.
|
||||
[[nodiscard]] Void::Result::Result<LeaseStatus>
|
||||
verifyLease(std::string_view leaseEnvelopeJson,
|
||||
std::string_view revocationEnvelopeJson,
|
||||
const Void::Update::Keyring& leaseKeys,
|
||||
const LeaseContext& context);
|
||||
} // namespace Echoion::Core::Licensing
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
namespace Echoion::Core::PlaybackDetail
|
||||
{
|
||||
/// A boundary can be emitted without padding when the outgoing tail and
|
||||
/// already-decoded incoming PCM together fill one device frame.
|
||||
[[nodiscard]] constexpr bool
|
||||
canFillDeviceFrame(std::size_t outgoingSamples,
|
||||
std::size_t incomingSamples,
|
||||
std::size_t frameSamples) noexcept
|
||||
{
|
||||
return frameSamples > 0 && outgoingSamples > 0 &&
|
||||
outgoingSamples < frameSamples &&
|
||||
incomingSamples >= frameSamples - outgoingSamples;
|
||||
}
|
||||
} // namespace Echoion::Core::PlaybackDetail
|
||||
@@ -21,6 +21,7 @@ namespace Echoion::Core
|
||||
public:
|
||||
|
||||
void setSources(std::vector<std::shared_ptr<ITrackSource>> sources);
|
||||
void addSource(std::shared_ptr<ITrackSource> source);
|
||||
|
||||
// Reorder/enable per config; names not found are ignored, sources
|
||||
// not named are dropped from the chain.
|
||||
@@ -59,9 +60,9 @@ namespace Echoion::Core
|
||||
std::chrono::steady_clock::time_point cooldownUntil{};
|
||||
};
|
||||
|
||||
[[nodiscard]] std::vector<SourceState*>
|
||||
[[nodiscard]] std::vector<std::shared_ptr<ITrackSource>>
|
||||
candidatesFor(const std::string& query, bool needSearch);
|
||||
void reportFailure(SourceState& state);
|
||||
void reportFailure(const std::shared_ptr<ITrackSource>& source);
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::vector<std::shared_ptr<ITrackSource>> allSources_;
|
||||
|
||||
@@ -46,16 +46,10 @@ namespace Echoion::Core
|
||||
std::string lastActivity; // ISO 8601
|
||||
};
|
||||
|
||||
struct ListeningRoomState {
|
||||
struct ExtensionPluginState {
|
||||
std::string name;
|
||||
uint64_t ownerId = 0;
|
||||
std::vector<uint64_t> members;
|
||||
Echoion::Api::PlaybackState playback;
|
||||
std::vector<QueueEntry> queue;
|
||||
std::optional<std::string> currentStreamUrl;
|
||||
int64_t playbackPositionMs = 0;
|
||||
BotConfig config;
|
||||
bool autoplay = false;
|
||||
std::string json;
|
||||
std::uint32_t version = 0;
|
||||
};
|
||||
|
||||
// Main state
|
||||
@@ -65,7 +59,7 @@ namespace Echoion::Core
|
||||
bool autoplay = false; // Radio mode on/off (persisted for restart)
|
||||
std::vector<QueueEntryState> queue;
|
||||
std::vector<SessionState> sessions;
|
||||
std::vector<ListeningRoomState> listeningRooms;
|
||||
std::vector<ExtensionPluginState> extensionPlugins;
|
||||
|
||||
// Version info
|
||||
uint32_t version = 1;
|
||||
|
||||
+29
-1
@@ -614,6 +614,35 @@ namespace Echoion::Core
|
||||
permissionCheck_ = std::move(func);
|
||||
}
|
||||
|
||||
bool CommandManager::registerExternalCommand(
|
||||
std::string owner, std::string primaryName, CommandPtr command)
|
||||
{
|
||||
if (owner.empty() || primaryName.empty() || !command) return false;
|
||||
std::lock_guard lock(mutex_);
|
||||
if (commands_.contains(primaryName)) return false;
|
||||
commands_[primaryName] = command;
|
||||
uniqueCommands_.push_back({std::move(primaryName), command});
|
||||
for (auto alias : command->getAliases()) {
|
||||
if (!commands_.contains(alias)) commands_[std::string(alias)] = command;
|
||||
}
|
||||
externalCommands_[std::move(owner)].push_back(std::move(command));
|
||||
return true;
|
||||
}
|
||||
|
||||
void CommandManager::unregisterExternalCommands(std::string_view owner)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
auto found = externalCommands_.find(owner);
|
||||
if (found == externalCommands_.end()) return;
|
||||
const auto owns = [&](const CommandPtr& command) {
|
||||
return std::ranges::find(found->second, command) != found->second.end();
|
||||
};
|
||||
std::erase_if(commands_, [&](const auto& entry) { return owns(entry.second); });
|
||||
std::erase_if(uniqueCommands_,
|
||||
[&](const CommandEntry& entry) { return owns(entry.instance); });
|
||||
externalCommands_.erase(found);
|
||||
}
|
||||
|
||||
void CommandManager::setServerConfig(const Api::AppConfig& config)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
@@ -640,7 +669,6 @@ namespace Echoion::Core
|
||||
registerCommand<ShuffleCommand>("shuffle");
|
||||
registerCommand<AutoplayCommand>("autoplay");
|
||||
registerCommand<RepeatCommand>("repeat");
|
||||
registerCommand<RoomCommand>("room");
|
||||
registerCommand<PlaylistCommand>("playlist");
|
||||
registerCommand<NowPlayingCommand>("np");
|
||||
registerCommand<LyricsCommand>("lyrics");
|
||||
|
||||
+172
-15
@@ -1,13 +1,17 @@
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include "Types.hpp"
|
||||
#include "echoion/core/ConfigLoader.hpp"
|
||||
#include <AudioTypes.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <ranges>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
@@ -23,29 +27,172 @@ namespace Echoion::Core
|
||||
if (config.bot.language != "en" && config.bot.language != "ru") {
|
||||
config.bot.language = "en";
|
||||
}
|
||||
|
||||
const std::filesystem::path logFile{config.logging.fileName};
|
||||
if (config.logging.fileName.empty() || logFile.is_absolute() ||
|
||||
logFile.has_parent_path() || logFile.filename() != logFile ||
|
||||
logFile == "." || logFile == "..") {
|
||||
config.logging.fileName = "echoion.log";
|
||||
}
|
||||
config.logging.maxFileSizeBytes = std::clamp<uint64_t>(
|
||||
config.logging.maxFileSizeBytes, 64 * 1024, 1024ULL * 1024 * 1024);
|
||||
config.logging.maxFiles =
|
||||
std::clamp<uint32_t>(config.logging.maxFiles, 1, 1000);
|
||||
config.logging.queueCapacity =
|
||||
std::clamp<uint32_t>(config.logging.queueCapacity, 16, 1'000'000);
|
||||
static constexpr std::array<std::string_view, 8> kLogLevels = {
|
||||
"trace", "debug", "info", "warning",
|
||||
"warn", "error", "critical", "fatal"};
|
||||
if (std::ranges::find(kLogLevels, config.logging.level) ==
|
||||
kLogLevels.end()) {
|
||||
config.logging.level = "debug";
|
||||
}
|
||||
static constexpr std::array<std::string_view, 3> kLogFormats = {
|
||||
"pattern", "json", "logfmt"};
|
||||
if (std::ranges::find(kLogFormats, config.logging.format) ==
|
||||
kLogFormats.end()) {
|
||||
config.logging.format = "pattern";
|
||||
}
|
||||
if (config.logging.pattern.empty() ||
|
||||
config.logging.pattern.size() > 4096) {
|
||||
config.logging.pattern =
|
||||
"[{time}] [{level}] [{thread}] {file} - {message}";
|
||||
}
|
||||
static constexpr std::array<std::string_view, 3> kLogModes = {
|
||||
"async", "immediate", "buffered"};
|
||||
if (std::ranges::find(kLogModes, config.logging.mode) ==
|
||||
kLogModes.end()) {
|
||||
config.logging.mode = "async";
|
||||
}
|
||||
static constexpr std::array<std::string_view, 3> kOverflowPolicies = {
|
||||
"block", "drop-newest", "drop-oldest"};
|
||||
if (std::ranges::find(kOverflowPolicies,
|
||||
config.logging.overflowPolicy) ==
|
||||
kOverflowPolicies.end()) {
|
||||
config.logging.overflowPolicy = "block";
|
||||
}
|
||||
|
||||
config.licensing.refreshInterval =
|
||||
std::clamp(config.licensing.refreshInterval,
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::minutes(15)),
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::hours(12)));
|
||||
config.licensing.retryInterval =
|
||||
std::clamp(config.licensing.retryInterval,
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::seconds(30)),
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::hours(1)));
|
||||
config.licensing.maximumLeaseLifetime =
|
||||
std::clamp(config.licensing.maximumLeaseLifetime,
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::hours(1)),
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::hours(24)));
|
||||
if (config.licensing.productId.empty() ||
|
||||
config.licensing.productId.size() > 128) {
|
||||
config.licensing.productId = "echoion";
|
||||
}
|
||||
if (config.licensing.activationTokenEnv.empty() ||
|
||||
config.licensing.activationTokenEnv.size() > 128) {
|
||||
config.licensing.activationTokenEnv = "ECHOION_LICENSE_TOKEN";
|
||||
}
|
||||
if (!config.licensing.serviceUrl.empty() &&
|
||||
!config.licensing.serviceUrl.starts_with("https://")) {
|
||||
config.licensing.serviceUrl.clear();
|
||||
}
|
||||
|
||||
// Keep partially specified updater sections usable. Security-sensitive
|
||||
// URL/key validation happens in the host updater before the policy is
|
||||
// persisted or used; normalization here only supplies structural
|
||||
// defaults for older configuration files.
|
||||
if (!config.updates.sources.contains("official")) {
|
||||
config.updates.sources.emplace("official",
|
||||
Api::UpdateSourceConfig{});
|
||||
}
|
||||
auto normalizeComponent = [](Api::UpdateComponentConfig& component) {
|
||||
if (component.source.empty()) {
|
||||
component.source = "official";
|
||||
}
|
||||
if (component.channel.empty()) {
|
||||
component.channel = "stable";
|
||||
}
|
||||
};
|
||||
normalizeComponent(config.updates.runtime);
|
||||
normalizeComponent(config.updates.core);
|
||||
if (config.updates.plugins.source.empty()) {
|
||||
config.updates.plugins.source = "official";
|
||||
}
|
||||
if (config.updates.plugins.channel.empty()) {
|
||||
config.updates.plugins.channel = "stable";
|
||||
}
|
||||
|
||||
if (config.urlShortening.provider.empty()) {
|
||||
config.urlShortening.provider = "url-shortener-internal";
|
||||
}
|
||||
if (config.urlShortening.enabled &&
|
||||
config.urlShortening.provider == "url-shortener-internal" &&
|
||||
config.web.publicUrl.empty()) {
|
||||
config.urlShortening.enabled = false;
|
||||
Void::Log::warn(
|
||||
"ConfigLoader", "{}",
|
||||
"Internal URL shortening was disabled because web.publicUrl is "
|
||||
"empty; configure the bot's public URL before enabling "
|
||||
"url-shortener-internal");
|
||||
}
|
||||
config.urlShortening.timeout = std::clamp(
|
||||
config.urlShortening.timeout, std::chrono::milliseconds(100),
|
||||
std::chrono::milliseconds(30000));
|
||||
const auto validSource = [](std::string_view source) {
|
||||
static constexpr std::array<std::string_view, 6> kSources = {
|
||||
"youtube", "yandex", "url", "soundcloud", "spotify", "plugin"};
|
||||
return std::ranges::find(kSources, source) != kSources.end();
|
||||
};
|
||||
std::erase_if(
|
||||
config.urlShortening.sources,
|
||||
[&](const std::string& source) { return !validSource(source); });
|
||||
std::ranges::sort(config.urlShortening.sources);
|
||||
auto unique = std::ranges::unique(config.urlShortening.sources);
|
||||
config.urlShortening.sources.erase(unique.begin(), unique.end());
|
||||
}
|
||||
|
||||
Api::Result<Api::AppConfig>
|
||||
ConfigLoader::loadFromFile(const std::filesystem::path& path)
|
||||
{
|
||||
if (!std::filesystem::exists(path)) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
std::format("Configuration file not found: {}",
|
||||
path.string()));
|
||||
return Api::fail(
|
||||
Api::ErrorCode::NotFound,
|
||||
std::format("Configuration file not found: {}", path.string()));
|
||||
}
|
||||
|
||||
std::ifstream file(path);
|
||||
if (!file.is_open()) {
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
std::format("Failed to open configuration file: {}",
|
||||
path.string()));
|
||||
return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied,
|
||||
std::format("Failed to open configuration file: {}",
|
||||
path.string()));
|
||||
}
|
||||
|
||||
std::string content((std::istreambuf_iterator<char>(file)),
|
||||
std::istreambuf_iterator<char>());
|
||||
file.close();
|
||||
|
||||
auto parsed = Void::Json::parse(content);
|
||||
auto config = loadFromJson(content);
|
||||
if (!config) {
|
||||
return std::unexpected(config.error());
|
||||
}
|
||||
|
||||
std::cout << std::format("[INFO] Configuration loaded from {}",
|
||||
path.string())
|
||||
<< '\n';
|
||||
return config;
|
||||
}
|
||||
|
||||
Api::Result<Api::AppConfig>
|
||||
ConfigLoader::loadFromJson(std::string_view json)
|
||||
{
|
||||
auto parsed = Void::Json::parse(json);
|
||||
if (!parsed) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::ParseError,
|
||||
@@ -66,11 +213,15 @@ namespace Echoion::Core
|
||||
}
|
||||
|
||||
Api::AppConfig config = std::move(*result);
|
||||
// Legacy files only had youtube.enableUrlShortening. An explicitly
|
||||
// present new section always wins, including enabled=false.
|
||||
if (parsed->find("urlShortening") == nullptr) {
|
||||
config.urlShortening.enabled = config.youtube.enableUrlShortening;
|
||||
config.urlShortening.provider = "url-shortener-internal";
|
||||
config.urlShortening.sources = {"youtube"};
|
||||
}
|
||||
normalize(config);
|
||||
|
||||
std::cout << std::format("[INFO] Configuration loaded from {}",
|
||||
path.string())
|
||||
<< '\n';
|
||||
return config;
|
||||
}
|
||||
|
||||
@@ -82,15 +233,17 @@ namespace Echoion::Core
|
||||
Void::Json::to_json(config), {.pretty = true});
|
||||
std::ofstream file(path);
|
||||
if (!file.is_open()) {
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
std::format("Failed to write configuration file: {}",
|
||||
path.string()));
|
||||
return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied,
|
||||
std::format("Failed to write configuration file: {}",
|
||||
path.string()));
|
||||
}
|
||||
|
||||
file << json;
|
||||
file.close();
|
||||
|
||||
Void::Log::info("ConfigLoader", "{}",
|
||||
Void::Log::info(
|
||||
"ConfigLoader", "{}",
|
||||
std::format("Configuration saved to {}", path.string()));
|
||||
return {};
|
||||
}
|
||||
@@ -130,6 +283,10 @@ namespace Echoion::Core
|
||||
config.youtube.ytDlpMaxConcurrent = 4;
|
||||
config.youtube.ytDlpAsyncEnabled = true;
|
||||
config.youtube.enableUrlShortening = true;
|
||||
config.urlShortening.enabled = false;
|
||||
config.urlShortening.provider = "url-shortener-internal";
|
||||
config.urlShortening.sources = {"youtube"};
|
||||
config.urlShortening.timeout = std::chrono::milliseconds(3000);
|
||||
|
||||
// Default network config
|
||||
config.network.rpcEnabled = true;
|
||||
|
||||
+577
-277
File diff suppressed because it is too large.
Load diff
+770
-571
File diff suppressed because it is too large.
Load diff
+4
-95
@@ -359,28 +359,14 @@ namespace Echoion::Api
|
||||
"Database migration 8 applied: track_thumbnail columns added");
|
||||
}
|
||||
|
||||
// Migration 9: custom emojis for the web UI (admin-managed image
|
||||
// emotes, referenced by :name: shortcodes in watch chat/reactions).
|
||||
// Migration 9 belonged to a retired embedded browser feature. Preserve
|
||||
// its version slot so existing databases and later migrations remain
|
||||
// compatible, but new Echoion databases no longer create its tables.
|
||||
if (currentVersion < 9) {
|
||||
const char* migration9 = R"(
|
||||
CREATE TABLE IF NOT EXISTS custom_emojis (
|
||||
name TEXT PRIMARY KEY,
|
||||
mime TEXT NOT NULL,
|
||||
data TEXT NOT NULL, -- base64-encoded image bytes
|
||||
added_by TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
)";
|
||||
|
||||
if (auto r = impl_->voidDb.exec(migration9); !r) {
|
||||
return fail(ErrorCode::DatabaseError, r.error().message());
|
||||
}
|
||||
|
||||
[[maybe_unused]] auto ins = impl_->voidDb.exec(
|
||||
"INSERT INTO schema_migrations (version) VALUES (9)");
|
||||
|
||||
Void::Log::info("Database", "{}",
|
||||
"Database migration 9 applied: custom_emojis table added");
|
||||
Void::Log::info("Database", "{}", "Database migration 9 retired");
|
||||
}
|
||||
|
||||
// Migration 10: cached TeamSpeak avatars for the web UI, keyed by uid,
|
||||
@@ -1451,83 +1437,6 @@ namespace Echoion::Api
|
||||
return {};
|
||||
}
|
||||
|
||||
Result<std::vector<Database::CustomEmoji>> Database::getCustomEmojis()
|
||||
{
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
auto stmtRes = impl_->voidDb.prepare(
|
||||
"SELECT name, mime, data, added_by FROM custom_emojis "
|
||||
"ORDER BY name;");
|
||||
if (!stmtRes) {
|
||||
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
||||
}
|
||||
auto& stmt = *stmtRes;
|
||||
std::vector<CustomEmoji> out;
|
||||
while (stmt.step().value_or(false)) {
|
||||
out.push_back(CustomEmoji{.name = stmt.column_text(0),
|
||||
.mime = stmt.column_text(1),
|
||||
.dataBase64 = stmt.column_text(2),
|
||||
.addedBy = stmt.column_text(3)});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Result<std::optional<Database::CustomEmoji>>
|
||||
Database::getCustomEmoji(const std::string& name)
|
||||
{
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
auto stmtRes = impl_->voidDb.prepare(
|
||||
"SELECT name, mime, data, added_by FROM custom_emojis "
|
||||
"WHERE name = ?;");
|
||||
if (!stmtRes) {
|
||||
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
||||
}
|
||||
auto& stmt = *stmtRes;
|
||||
stmt.bind(1, name);
|
||||
if (stmt.step().value_or(false)) {
|
||||
return std::optional<CustomEmoji>{
|
||||
CustomEmoji{.name = stmt.column_text(0),
|
||||
.mime = stmt.column_text(1),
|
||||
.dataBase64 = stmt.column_text(2),
|
||||
.addedBy = stmt.column_text(3)}};
|
||||
}
|
||||
return std::optional<CustomEmoji>{};
|
||||
}
|
||||
|
||||
Result<void> Database::addCustomEmoji(const std::string& name,
|
||||
const std::string& mime,
|
||||
const std::string& dataBase64,
|
||||
const std::string& addedBy)
|
||||
{
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
auto stmtRes = impl_->voidDb.prepare(R"(
|
||||
INSERT OR REPLACE INTO custom_emojis (name, mime, data, added_by)
|
||||
VALUES (?, ?, ?, ?);
|
||||
)");
|
||||
if (!stmtRes) {
|
||||
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
||||
}
|
||||
auto& stmt = *stmtRes;
|
||||
stmt.bind(1, name).bind(2, mime).bind(3, dataBase64).bind(4, addedBy);
|
||||
if (auto stepRes = stmt.step(); !stepRes) {
|
||||
return fail(ErrorCode::DatabaseError, stepRes.error().message());
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Result<void> Database::removeCustomEmoji(const std::string& name)
|
||||
{
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
auto stmtRes =
|
||||
impl_->voidDb.prepare("DELETE FROM custom_emojis WHERE name = ?;");
|
||||
if (!stmtRes) {
|
||||
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
||||
}
|
||||
auto& stmt = *stmtRes;
|
||||
stmt.bind(1, name);
|
||||
[[maybe_unused]] auto stepRes = stmt.step();
|
||||
return {};
|
||||
}
|
||||
|
||||
Result<std::optional<Database::CachedAvatar>>
|
||||
Database::getCachedAvatar(const std::string& uid)
|
||||
{
|
||||
|
||||
+1
-1
@@ -115,7 +115,7 @@ extern "C"
|
||||
return Void::Plugin::PluginInfo{
|
||||
.abi_version = Void::Plugin::ABI_VERSION,
|
||||
.name = "Echoion",
|
||||
.plugin_version = Echoion::Api::VERSION_STRING,
|
||||
.plugin_version = ECHOION_CORE_VERSION,
|
||||
.description = "Echoion TeamSpeak music bot core"};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,457 +0,0 @@
|
||||
#include "echoion/core/ListeningRoomManager.hpp"
|
||||
#include "echoion/core/ListeningRoomName.hpp"
|
||||
|
||||
#include "echoion/core/NetworkClient.hpp"
|
||||
|
||||
#include <Void/Log/Log.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <utility>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
ListeningRoomManager::ListeningRoomManager(
|
||||
std::shared_ptr<NetworkClient> network, Api::ConfigManager& config,
|
||||
Void::EventBus::EventBus& events)
|
||||
: network_(std::move(network)), config_(config), events_(events)
|
||||
{
|
||||
}
|
||||
|
||||
ListeningRoomManager::~ListeningRoomManager() { shutdown(); }
|
||||
|
||||
void ListeningRoomManager::setPluginInterface(
|
||||
Api::PluginInterfacePtr plugin)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
plugin_ = std::move(plugin);
|
||||
}
|
||||
|
||||
void ListeningRoomManager::setChangeCallback(std::function<void()> callback)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
changeCallback_ = std::move(callback);
|
||||
}
|
||||
|
||||
void ListeningRoomManager::notifyChanged() const
|
||||
{
|
||||
if (changeCallback_) changeCallback_();
|
||||
}
|
||||
|
||||
Api::ServerConfig ListeningRoomManager::serverConfigFor(
|
||||
const std::string& roomName) const
|
||||
{
|
||||
const auto& source = config_.getTeamSpeak();
|
||||
Api::ServerConfig result;
|
||||
result.address = source.address;
|
||||
result.port = source.port;
|
||||
result.serverPassword = source.serverPassword;
|
||||
result.nickname = source.nickname.empty() ? "Echoion" : source.nickname;
|
||||
result.nickname += "/" + roomName;
|
||||
result.defaultChannelId = source.defaultChannelId;
|
||||
result.channelPassword = source.channelPassword;
|
||||
result.adminGroups = source.adminGroups;
|
||||
result.djGroups = source.djGroups;
|
||||
result.bannedGroups = source.bannedGroups;
|
||||
return result;
|
||||
}
|
||||
|
||||
Api::Result<void> ListeningRoomManager::create(
|
||||
std::string name, uint64_t ownerId)
|
||||
{
|
||||
auto validName = validateListeningRoomName(std::move(name));
|
||||
if (!validName || ownerId == 0) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
validName ? "room owner is required" : validName.error().message);
|
||||
}
|
||||
name = std::move(*validName);
|
||||
const auto key = canonicalListeningRoomName(name);
|
||||
std::lock_guard lock(mutex_);
|
||||
if (!plugin_) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"TeamSpeak host is not available");
|
||||
}
|
||||
if (rooms_.contains(key)) {
|
||||
return Api::fail(Api::ErrorCode::AlreadyExists,
|
||||
"listening room already exists");
|
||||
}
|
||||
if (membership_.contains(ownerId)) {
|
||||
return Api::fail(Api::ErrorCode::AlreadyExists,
|
||||
"owner already belongs to another listening room");
|
||||
}
|
||||
|
||||
Api::IPluginInterface::AudioStreamOptions streamOptions;
|
||||
streamOptions.name = name;
|
||||
streamOptions.server = serverConfigFor(name);
|
||||
streamOptions.recipients = {ownerId};
|
||||
auto stream = plugin_->createAudioStream(streamOptions);
|
||||
if (!stream) return std::unexpected(stream.error());
|
||||
|
||||
auto room = std::make_unique<Room>();
|
||||
room->name = name;
|
||||
room->ownerId = ownerId;
|
||||
room->streamId = *stream;
|
||||
room->members.insert(ownerId);
|
||||
room->music = std::make_unique<MusicManager>();
|
||||
room->music->setConfigManager(&config_);
|
||||
room->music->setEventBus(&events_);
|
||||
room->music->setAudioDataCallback(
|
||||
[plugin = plugin_, streamId = *stream](std::span<const short> data) {
|
||||
if (!data.empty()) {
|
||||
std::ignore = plugin->sendAudioDataToStream(streamId, data);
|
||||
}
|
||||
});
|
||||
room->music->setClientInfoCallback(
|
||||
[plugin = plugin_](uint64_t clientId)
|
||||
-> std::optional<std::pair<std::string, std::string>> {
|
||||
auto client = plugin->getClient(clientId);
|
||||
if (!client || !client->has_value() ||
|
||||
!client->value().uniqueIdentifier) return std::nullopt;
|
||||
return std::pair{*client->value().uniqueIdentifier,
|
||||
client->value().nickname};
|
||||
});
|
||||
if (auto initialized = room->music->initialize(network_, nullptr);
|
||||
!initialized) {
|
||||
std::ignore = plugin_->destroyAudioStream(*stream);
|
||||
return std::unexpected(initialized.error());
|
||||
}
|
||||
membership_[ownerId] = key;
|
||||
rooms_.emplace(key, std::move(room));
|
||||
Void::Log::info("ListeningRooms", "Created room '{}' for client {}",
|
||||
name, ownerId);
|
||||
notifyChanged();
|
||||
return {};
|
||||
}
|
||||
|
||||
Api::Result<void> ListeningRoomManager::remove(
|
||||
const std::string& name, uint64_t requesterId)
|
||||
{
|
||||
std::unique_ptr<Room> room;
|
||||
Api::PluginInterfacePtr plugin;
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
auto iterator = rooms_.find(canonicalListeningRoomName(name));
|
||||
if (iterator == rooms_.end())
|
||||
return Api::fail(Api::ErrorCode::NotFound, "listening room not found");
|
||||
if (iterator->second->ownerId != requesterId)
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
"only the room owner may delete it");
|
||||
for (auto member : iterator->second->members) membership_.erase(member);
|
||||
room = std::move(iterator->second);
|
||||
rooms_.erase(iterator);
|
||||
plugin = plugin_;
|
||||
}
|
||||
room->music->shutdown();
|
||||
notifyChanged();
|
||||
if (plugin) return plugin->destroyAudioStream(room->streamId);
|
||||
return {};
|
||||
}
|
||||
|
||||
Api::Result<void> ListeningRoomManager::refreshRecipients(Room& room)
|
||||
{
|
||||
if (!plugin_) return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"TeamSpeak host is not available");
|
||||
return plugin_->setAudioStreamRecipients(room.streamId,
|
||||
{room.members.begin(), room.members.end()});
|
||||
}
|
||||
|
||||
Api::Result<void> ListeningRoomManager::join(
|
||||
const std::string& name, uint64_t clientId)
|
||||
{
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
const auto* destination = findLocked(name);
|
||||
if (!destination) return Api::fail(Api::ErrorCode::NotFound,
|
||||
"listening room not found");
|
||||
const auto current = membership_.find(clientId);
|
||||
if (current != membership_.end()) {
|
||||
const auto currentRoom = rooms_.find(current->second);
|
||||
if (currentRoom != rooms_.end() &&
|
||||
currentRoom->second.get() == destination) return {};
|
||||
}
|
||||
}
|
||||
if (auto left = leave(clientId); !left) return left;
|
||||
std::lock_guard lock(mutex_);
|
||||
auto* room = findLocked(name);
|
||||
if (!room) return Api::fail(Api::ErrorCode::NotFound,
|
||||
"listening room not found");
|
||||
room->members.insert(clientId);
|
||||
for (const auto& [key, candidate] : rooms_) {
|
||||
if (candidate.get() == room) {
|
||||
membership_[clientId] = key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
auto refreshed = refreshRecipients(*room);
|
||||
notifyChanged();
|
||||
return refreshed;
|
||||
}
|
||||
|
||||
Api::Result<void> ListeningRoomManager::leave(uint64_t clientId)
|
||||
{
|
||||
std::unique_ptr<Room> emptyRoom;
|
||||
Api::PluginInterfacePtr plugin;
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
auto membership = membership_.find(clientId);
|
||||
if (membership == membership_.end()) return {};
|
||||
const auto key = membership->second;
|
||||
auto iterator = rooms_.find(key);
|
||||
membership_.erase(membership);
|
||||
if (iterator == rooms_.end()) return {};
|
||||
auto& room = *iterator->second;
|
||||
room.members.erase(clientId);
|
||||
if (room.ownerId == clientId && !room.members.empty()) {
|
||||
room.ownerId = *room.members.begin();
|
||||
Void::Log::info("ListeningRooms",
|
||||
"Transferred room '{}' ownership to client {}",
|
||||
room.name, room.ownerId);
|
||||
}
|
||||
if (room.members.empty()) {
|
||||
emptyRoom = std::move(iterator->second);
|
||||
rooms_.erase(iterator);
|
||||
plugin = plugin_;
|
||||
} else {
|
||||
auto refreshed = refreshRecipients(room);
|
||||
notifyChanged();
|
||||
return refreshed;
|
||||
}
|
||||
}
|
||||
emptyRoom->music->shutdown();
|
||||
Void::Log::info("ListeningRooms", "Removed empty room '{}'",
|
||||
emptyRoom->name);
|
||||
notifyChanged();
|
||||
return plugin ? plugin->destroyAudioStream(emptyRoom->streamId)
|
||||
: Api::Result<void>{};
|
||||
}
|
||||
|
||||
Api::Result<std::string> ListeningRoomManager::play(
|
||||
const std::string& name, std::string query, uint64_t clientId)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
auto* room = findLocked(name);
|
||||
if (!room) return Api::fail(Api::ErrorCode::NotFound,
|
||||
"listening room not found");
|
||||
if (!room->members.contains(clientId)) return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied, "join the room before controlling it");
|
||||
auto result = room->music->play(query, clientId);
|
||||
if (result) notifyChanged();
|
||||
return result;
|
||||
}
|
||||
|
||||
Api::Result<void> ListeningRoomManager::pause(
|
||||
const std::string& name, uint64_t requesterId)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
auto* room = findLocked(name);
|
||||
if (!room) return Api::fail(Api::ErrorCode::NotFound, "room not found");
|
||||
if (!room->members.contains(requesterId)) return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied, "join the room before controlling it");
|
||||
auto result = room->music->pause();
|
||||
if (result) notifyChanged();
|
||||
return result;
|
||||
}
|
||||
|
||||
Api::Result<void> ListeningRoomManager::resume(
|
||||
const std::string& name, uint64_t requesterId)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
auto* room = findLocked(name);
|
||||
if (!room) return Api::fail(Api::ErrorCode::NotFound, "room not found");
|
||||
if (!room->members.contains(requesterId)) return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied, "join the room before controlling it");
|
||||
auto result = room->music->resume();
|
||||
if (result) notifyChanged();
|
||||
return result;
|
||||
}
|
||||
|
||||
Api::Result<void> ListeningRoomManager::stop(
|
||||
const std::string& name, uint64_t requesterId)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
auto* room = findLocked(name);
|
||||
if (!room) return Api::fail(Api::ErrorCode::NotFound, "room not found");
|
||||
if (!room->members.contains(requesterId)) return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied, "join the room before controlling it");
|
||||
auto result = room->music->stop();
|
||||
if (result) notifyChanged();
|
||||
return result;
|
||||
}
|
||||
|
||||
Api::Result<void> ListeningRoomManager::skip(
|
||||
const std::string& name, uint64_t requesterId)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
auto* room = findLocked(name);
|
||||
if (!room) return Api::fail(Api::ErrorCode::NotFound, "room not found");
|
||||
if (!room->members.contains(requesterId)) return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied, "join the room before controlling it");
|
||||
auto result = room->music->skip();
|
||||
if (result) notifyChanged();
|
||||
return result;
|
||||
}
|
||||
|
||||
Api::Result<void> ListeningRoomManager::removeQueueEntry(
|
||||
const std::string& name, uint64_t queueId, uint64_t requesterId)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
auto* room = findLocked(name);
|
||||
if (!room) return Api::fail(Api::ErrorCode::NotFound, "room not found");
|
||||
if (!room->members.contains(requesterId)) return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied, "join the room before controlling it");
|
||||
auto queue = room->music->getQueue();
|
||||
if (!queue) return std::unexpected(queue.error());
|
||||
const auto iterator = std::ranges::find(*queue, queueId, &Api::QueueEntry::queueId);
|
||||
if (iterator == queue->end()) return Api::fail(
|
||||
Api::ErrorCode::NotFound, "room queue entry not found");
|
||||
auto result = room->music->removeFromQueue(
|
||||
static_cast<uint32_t>(std::distance(queue->begin(), iterator)));
|
||||
if (result) notifyChanged();
|
||||
return result;
|
||||
}
|
||||
|
||||
Api::Result<void> ListeningRoomManager::moveQueueEntry(
|
||||
const std::string& name, uint64_t queueId, uint32_t newPosition,
|
||||
uint64_t requesterId)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
auto* room = findLocked(name);
|
||||
if (!room) return Api::fail(Api::ErrorCode::NotFound, "room not found");
|
||||
if (!room->members.contains(requesterId)) return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied, "join the room before controlling it");
|
||||
auto queue = room->music->getQueue();
|
||||
if (!queue) return std::unexpected(queue.error());
|
||||
const auto iterator = std::ranges::find(*queue, queueId, &Api::QueueEntry::queueId);
|
||||
if (iterator == queue->end()) return Api::fail(
|
||||
Api::ErrorCode::NotFound, "room queue entry not found");
|
||||
auto result = room->music->moveInQueue(
|
||||
static_cast<uint32_t>(std::distance(queue->begin(), iterator)), newPosition);
|
||||
if (result) notifyChanged();
|
||||
return result;
|
||||
}
|
||||
|
||||
Api::Result<void> ListeningRoomManager::clearQueue(
|
||||
const std::string& name, uint64_t requesterId)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
auto* room = findLocked(name);
|
||||
if (!room) return Api::fail(Api::ErrorCode::NotFound, "room not found");
|
||||
if (!room->members.contains(requesterId)) return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied, "join the room before controlling it");
|
||||
auto result = room->music->clearQueue();
|
||||
if (result) notifyChanged();
|
||||
return result;
|
||||
}
|
||||
|
||||
Api::Result<std::vector<Api::QueueEntry>>
|
||||
ListeningRoomManager::queue(const std::string& name) const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
const auto* room = findLocked(name);
|
||||
if (!room) return Api::fail(Api::ErrorCode::NotFound, "room not found");
|
||||
return room->music->getQueue();
|
||||
}
|
||||
|
||||
std::vector<ListeningRoomManager::RoomSummary>
|
||||
ListeningRoomManager::list() const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
std::vector<RoomSummary> result;
|
||||
result.reserve(rooms_.size());
|
||||
for (const auto& [key, room] : rooms_) {
|
||||
std::ignore = key;
|
||||
auto state = room->music->getPlaybackState();
|
||||
auto queue = room->music->getQueue();
|
||||
result.push_back(RoomSummary{.name = room->name,
|
||||
.ownerId = room->ownerId,
|
||||
.members = {room->members.begin(), room->members.end()},
|
||||
.isPlaying = state && state->isPlaying,
|
||||
.isPaused = state && state->isPaused,
|
||||
.queueSize = queue ? queue->size() : 0});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::optional<std::string> ListeningRoomManager::roomForClient(
|
||||
uint64_t clientId) const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
const auto iterator = membership_.find(clientId);
|
||||
if (iterator == membership_.end()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto room = rooms_.find(iterator->second);
|
||||
return room == rooms_.end() ? std::nullopt
|
||||
: std::optional<std::string>{room->second->name};
|
||||
}
|
||||
|
||||
std::vector<ListeningRoomManager::PersistedRoom>
|
||||
ListeningRoomManager::snapshot() const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
std::vector<PersistedRoom> result;
|
||||
result.reserve(rooms_.size());
|
||||
for (const auto& [key, room] : rooms_) {
|
||||
std::ignore = key;
|
||||
result.push_back(PersistedRoom{
|
||||
.name = room->name, .ownerId = room->ownerId,
|
||||
.members = {room->members.begin(), room->members.end()},
|
||||
.state = room->music->getStateForHotReload()});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Api::Result<void> ListeningRoomManager::restore(
|
||||
const std::vector<PersistedRoom>& rooms)
|
||||
{
|
||||
for (const auto& saved : rooms) {
|
||||
if (auto created = create(saved.name, saved.ownerId); !created) {
|
||||
return std::unexpected(created.error());
|
||||
}
|
||||
for (auto member : saved.members) {
|
||||
if (member != saved.ownerId) {
|
||||
if (auto joined = join(saved.name, member); !joined)
|
||||
return std::unexpected(joined.error());
|
||||
}
|
||||
}
|
||||
std::lock_guard lock(mutex_);
|
||||
auto* room = findLocked(saved.name);
|
||||
if (!room) return Api::fail(Api::ErrorCode::UnknownError,
|
||||
"restored room disappeared");
|
||||
if (auto restored = room->music->restoreFromHotReload(saved.state);
|
||||
!restored) return std::unexpected(restored.error());
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
ListeningRoomManager::Room* ListeningRoomManager::findLocked(
|
||||
const std::string& name)
|
||||
{
|
||||
auto iterator = rooms_.find(canonicalListeningRoomName(name));
|
||||
return iterator == rooms_.end() ? nullptr : iterator->second.get();
|
||||
}
|
||||
|
||||
const ListeningRoomManager::Room* ListeningRoomManager::findLocked(
|
||||
const std::string& name) const
|
||||
{
|
||||
auto iterator = rooms_.find(canonicalListeningRoomName(name));
|
||||
return iterator == rooms_.end() ? nullptr : iterator->second.get();
|
||||
}
|
||||
|
||||
|
||||
void ListeningRoomManager::shutdown()
|
||||
{
|
||||
std::map<std::string, std::unique_ptr<Room>> rooms;
|
||||
Api::PluginInterfacePtr plugin;
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
rooms.swap(rooms_);
|
||||
membership_.clear();
|
||||
plugin = plugin_;
|
||||
}
|
||||
for (auto& [name, room] : rooms) {
|
||||
std::ignore = name;
|
||||
room->music->shutdown();
|
||||
if (plugin) std::ignore = plugin->destroyAudioStream(room->streamId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
#include "echoion/core/LogRotation.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
#include <format>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] std::string archiveTimestamp()
|
||||
{
|
||||
using namespace std::chrono;
|
||||
const auto now = system_clock::now();
|
||||
const auto secondsPart = floor<seconds>(now);
|
||||
const auto micros = duration_cast<microseconds>(now - secondsPart);
|
||||
const std::time_t raw = system_clock::to_time_t(now);
|
||||
std::tm utc{};
|
||||
#ifdef _WIN32
|
||||
gmtime_s(&utc, &raw);
|
||||
#else
|
||||
gmtime_r(&raw, &utc);
|
||||
#endif
|
||||
return std::format("{:04}{:02}{:02}-{:02}{:02}{:02}-{:06}",
|
||||
utc.tm_year + 1900, utc.tm_mon + 1, utc.tm_mday,
|
||||
utc.tm_hour, utc.tm_min, utc.tm_sec,
|
||||
micros.count());
|
||||
}
|
||||
|
||||
[[nodiscard]] bool isArchiveFor(const std::filesystem::path& path,
|
||||
const std::filesystem::path& active)
|
||||
{
|
||||
const auto name = path.filename().string();
|
||||
const auto prefix = active.stem().string() + "-";
|
||||
return name.starts_with(prefix) &&
|
||||
path.extension() == active.extension();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::error_code rotateLogOnStartup(const std::filesystem::path& activeLog,
|
||||
std::size_t maxFiles) noexcept
|
||||
{
|
||||
std::error_code error;
|
||||
const auto status = std::filesystem::symlink_status(activeLog, error);
|
||||
if (error && error != std::errc::no_such_file_or_directory) {
|
||||
return error;
|
||||
}
|
||||
error.clear();
|
||||
|
||||
const bool exists = std::filesystem::exists(status);
|
||||
if (exists && std::filesystem::is_symlink(status)) {
|
||||
return std::make_error_code(
|
||||
std::errc::too_many_symbolic_link_levels);
|
||||
}
|
||||
|
||||
const auto history = activeLog.parent_path() / "history";
|
||||
std::filesystem::create_directories(activeLog.parent_path(), error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
if (exists) {
|
||||
if (!std::filesystem::is_regular_file(status)) {
|
||||
return std::make_error_code(std::errc::invalid_argument);
|
||||
}
|
||||
const auto size = std::filesystem::file_size(activeLog, error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
if (size == 0 || maxFiles == 0) {
|
||||
std::filesystem::remove(activeLog, error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
} else {
|
||||
std::filesystem::create_directories(history, error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
const auto timestamp = archiveTimestamp();
|
||||
auto archived = history / (activeLog.stem().string() + "-" +
|
||||
timestamp +
|
||||
activeLog.extension().string());
|
||||
for (std::size_t suffix = 1;
|
||||
std::filesystem::exists(archived, error) && !error;
|
||||
++suffix) {
|
||||
archived = history / (activeLog.stem().string() + "-" +
|
||||
timestamp + "-" +
|
||||
std::to_string(suffix) +
|
||||
activeLog.extension().string());
|
||||
}
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
std::filesystem::rename(activeLog, archived, error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const auto historyStatus =
|
||||
std::filesystem::symlink_status(history, error);
|
||||
if (error == std::errc::no_such_file_or_directory ||
|
||||
historyStatus.type() == std::filesystem::file_type::not_found) {
|
||||
return {};
|
||||
}
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
if (!std::filesystem::is_directory(historyStatus) ||
|
||||
std::filesystem::is_symlink(historyStatus)) {
|
||||
return std::make_error_code(std::errc::invalid_argument);
|
||||
}
|
||||
std::vector<std::filesystem::path> archives;
|
||||
for (std::filesystem::directory_iterator iterator(history, error), end;
|
||||
!error && iterator != end; iterator.increment(error)) {
|
||||
const auto entryStatus = iterator->symlink_status(error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
if (std::filesystem::is_regular_file(entryStatus) &&
|
||||
isArchiveFor(iterator->path(), activeLog)) {
|
||||
archives.push_back(iterator->path());
|
||||
}
|
||||
}
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
std::ranges::sort(archives);
|
||||
while (archives.size() > maxFiles) {
|
||||
std::filesystem::remove(archives.front(), error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
archives.erase(archives.begin());
|
||||
}
|
||||
return {};
|
||||
}
|
||||
} // namespace Echoion::Core
|
||||
+12
-26
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Text/Url.hpp>
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <charconv>
|
||||
@@ -12,25 +13,6 @@ namespace Echoion::Core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
// Percent-encode a query-parameter value (RFC 3986 unreserved kept).
|
||||
std::string urlEncode(std::string_view s)
|
||||
{
|
||||
static constexpr char hex[] = "0123456789ABCDEF";
|
||||
std::string out;
|
||||
out.reserve(s.size() * 3);
|
||||
for (unsigned char c : s) {
|
||||
if (std::isalnum(c) || c == '-' || c == '_' || c == '.' ||
|
||||
c == '~') {
|
||||
out += static_cast<char>(c);
|
||||
} else {
|
||||
out += '%';
|
||||
out += hex[c >> 4];
|
||||
out += hex[c & 0x0F];
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Read an optional string field from a JSON object value.
|
||||
std::string strField(const Void::Json::Value& obj, std::string_view key)
|
||||
{
|
||||
@@ -131,9 +113,11 @@ namespace Echoion::Core
|
||||
std::string url = std::format(
|
||||
"https://lrclib.net/api/get?artist_name={}&track_name={}"
|
||||
"&duration={}",
|
||||
urlEncode(artist), urlEncode(title), durationSec);
|
||||
Void::Encoding::Url::encode(artist),
|
||||
Void::Encoding::Url::encode(title), durationSec);
|
||||
if (!album.empty()) {
|
||||
url += std::format("&album_name={}", urlEncode(album));
|
||||
url += std::format("&album_name={}",
|
||||
Void::Encoding::Url::encode(album));
|
||||
}
|
||||
if (auto resp = net_->get(url);
|
||||
resp && resp->status == 200 && !resp->body.empty()) {
|
||||
@@ -150,9 +134,10 @@ namespace Echoion::Core
|
||||
// 2) Search fallback — take the first result that carries lyrics.
|
||||
std::string searchUrl =
|
||||
std::format("https://lrclib.net/api/search?track_name={}",
|
||||
urlEncode(title));
|
||||
Void::Encoding::Url::encode(title));
|
||||
if (!artist.empty()) {
|
||||
searchUrl += std::format("&artist_name={}", urlEncode(artist));
|
||||
searchUrl += std::format("&artist_name={}",
|
||||
Void::Encoding::Url::encode(artist));
|
||||
}
|
||||
if (auto resp = net_->get(searchUrl);
|
||||
resp && resp->status == 200 && !resp->body.empty()) {
|
||||
@@ -197,13 +182,14 @@ namespace Echoion::Core
|
||||
}
|
||||
std::string_view tag(raw.data() + pos + 1, close - pos - 1);
|
||||
// A timestamp starts with a digit; [ar:], [ti:] etc. don't.
|
||||
if (!tag.empty() && std::isdigit(static_cast<unsigned char>(
|
||||
tag.front()))) {
|
||||
if (!tag.empty() &&
|
||||
std::isdigit(static_cast<unsigned char>(tag.front()))) {
|
||||
auto colon = tag.find(':');
|
||||
if (colon != std::string_view::npos) {
|
||||
int minutes = 0;
|
||||
double seconds = 0.0;
|
||||
std::from_chars(tag.data(), tag.data() + colon, minutes);
|
||||
std::from_chars(tag.data(), tag.data() + colon,
|
||||
minutes);
|
||||
// Parse the seconds part (may be fractional).
|
||||
std::string sec(tag.substr(colon + 1));
|
||||
try {
|
||||
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
#include <echoion/api/module/LegacyModuleAbi.hpp>
|
||||
|
||||
#include "ModuleContracts.hpp"
|
||||
|
||||
#include <iterator>
|
||||
#include <memory>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::CoreModule
|
||||
{
|
||||
namespace
|
||||
{
|
||||
class LifecycleModule final : public Void::Plugin::IModule
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] std::string_view name() const noexcept override
|
||||
{
|
||||
return "EchoionCore";
|
||||
}
|
||||
};
|
||||
|
||||
std::unique_ptr<Void::Plugin::IModule> createCoreModule()
|
||||
{
|
||||
return std::make_unique<LifecycleModule>();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
const Void::Plugin::ModuleDescriptor& coreModuleDescriptor()
|
||||
{
|
||||
static const Void::Plugin::ModuleDescriptor descriptor{
|
||||
.module_id = "EchoionCore",
|
||||
.component_version =
|
||||
{
|
||||
.major = ECHOION_COMPONENT_VERSION_MAJOR,
|
||||
.minor = ECHOION_COMPONENT_VERSION_MINOR,
|
||||
.patch = ECHOION_COMPONENT_VERSION_PATCH,
|
||||
.pre_release = {},
|
||||
.build = {},
|
||||
},
|
||||
.abi_hash = coreAbiHash,
|
||||
.abi_contract = Void::Json::object({
|
||||
{"schemaVersion", 1},
|
||||
{"contractId", "echoion.module.core"},
|
||||
{"descriptor", "echoion_module_descriptor_v1"},
|
||||
}),
|
||||
.dependencies =
|
||||
{
|
||||
{
|
||||
.module_id = "EchoionApi",
|
||||
.version_range = "^2.0.0",
|
||||
.abi_hash = apiAbiHash,
|
||||
},
|
||||
},
|
||||
.activation_policy = Void::Plugin::ActivationPolicy::Reloadable,
|
||||
.create = createCoreModule,
|
||||
};
|
||||
return descriptor;
|
||||
}
|
||||
|
||||
const echoion_module_descriptor_v1& coreModuleAbiDescriptor()
|
||||
{
|
||||
using Bridge = Api::Module::LegacyModuleAbi<createCoreModule>;
|
||||
static const echoion_module_dependency_v1 dependencies[]{
|
||||
{
|
||||
.struct_size = sizeof(echoion_module_dependency_v1),
|
||||
.component_id = Api::Module::Detail::stringView("EchoionApi"),
|
||||
.version_range =
|
||||
Api::Module::Detail::stringView(">=2.0.0 <3.0.0"),
|
||||
.abi_hash = Api::Module::Detail::stringView(apiAbiHash),
|
||||
.optional = 0,
|
||||
.reserved_bytes = {},
|
||||
},
|
||||
};
|
||||
static const echoion_module_descriptor_v1 descriptor{
|
||||
.struct_size = sizeof(echoion_module_descriptor_v1),
|
||||
.abi_version = ECHOION_MODULE_ABI_VERSION,
|
||||
.component_id = Api::Module::Detail::stringView("EchoionCore"),
|
||||
.version_major = ECHOION_COMPONENT_VERSION_MAJOR,
|
||||
.version_minor = ECHOION_COMPONENT_VERSION_MINOR,
|
||||
.version_patch = ECHOION_COMPONENT_VERSION_PATCH,
|
||||
.version_prerelease = {},
|
||||
.abi_hash = Api::Module::Detail::stringView(coreAbiHash),
|
||||
.dependencies = dependencies,
|
||||
.dependency_count = std::size(dependencies),
|
||||
.activation_policy = ECHOION_ACTIVATION_RELOADABLE_V1,
|
||||
.api = &Bridge::api,
|
||||
.reserved = {},
|
||||
};
|
||||
return descriptor;
|
||||
}
|
||||
} // namespace Echoion::CoreModule
|
||||
|
||||
extern "C" ECHOION_MODULE_EXPORT const Void::Plugin::ModuleDescriptor*
|
||||
echoion_module_query()
|
||||
{
|
||||
return &Echoion::CoreModule::coreModuleDescriptor();
|
||||
}
|
||||
|
||||
extern "C" ECHOION_MODULE_ABI_EXPORT const echoion_module_descriptor_v1*
|
||||
echoion_module_abi_query()
|
||||
{
|
||||
return &Echoion::CoreModule::coreModuleAbiDescriptor();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
namespace Echoion::CoreModule
|
||||
{
|
||||
inline constexpr auto apiAbiHash =
|
||||
"sha256:"
|
||||
"d50293d345a97e52f9844088bdd42277f566bc815a21b7636d3e053f06c6c113";
|
||||
inline constexpr auto coreAbiHash =
|
||||
"sha256:"
|
||||
"9cb668e2a502dcfe02d145ed63635d63619732d77ff5749685834382705e8d21";
|
||||
} // namespace Echoion::CoreModule
|
||||
+50
-30
@@ -60,7 +60,9 @@ namespace Echoion::Core
|
||||
networkConfig.proxy->port));
|
||||
}
|
||||
|
||||
youTubeClient_ = std::make_shared<YouTubeClient>(networkClient_);
|
||||
if (!youTubeClient_) {
|
||||
youTubeClient_ = std::make_shared<YouTubeClient>(networkClient_);
|
||||
}
|
||||
|
||||
// Playlist loading runs off the audio path: it enqueues resolved
|
||||
// tracks via queueTrack and pokes the playback loop on the first one.
|
||||
@@ -103,9 +105,7 @@ namespace Echoion::Core
|
||||
youtubeConfig.ytDlpMaxConcurrent);
|
||||
}
|
||||
|
||||
// Configure URL shortening
|
||||
youTubeClient_->setUrlShorteningEnabled(
|
||||
youtubeConfig.enableUrlShortening);
|
||||
// URL shortening is configured by Core after extension services load.
|
||||
|
||||
auto ytResult = youTubeClient_->initialize();
|
||||
if (!ytResult) {
|
||||
@@ -265,8 +265,6 @@ namespace Echoion::Core
|
||||
youTubeClient_->setMaxConcurrentResolutions(
|
||||
youtube.ytDlpMaxConcurrent);
|
||||
}
|
||||
youTubeClient_->setUrlShorteningEnabled(youtube.enableUrlShortening);
|
||||
|
||||
const bool hasKey = youtube.youtubeApiKey.has_value() &&
|
||||
!youtube.youtubeApiKey->empty();
|
||||
Void::Log::info("MusicManager", "{}",
|
||||
@@ -459,6 +457,13 @@ namespace Echoion::Core
|
||||
Void::Log::info("MusicManager", "{}", "Sources config applied");
|
||||
}
|
||||
|
||||
void MusicManager::addTrackSource(std::shared_ptr<ITrackSource> source)
|
||||
{
|
||||
if (router_) {
|
||||
router_->addSource(std::move(source));
|
||||
}
|
||||
}
|
||||
|
||||
void MusicManager::shutdown()
|
||||
{
|
||||
// Background fetch threads touch queue_/engine_/sources; join them
|
||||
@@ -802,8 +807,8 @@ namespace Echoion::Core
|
||||
// Daily counters / top-requesters stats. clientId 0 is radio/system
|
||||
// (autoplay refill) — automatic adds don't count as user requests.
|
||||
if (database_ && clientId != 0) {
|
||||
(void)database_->logQueueAddition(
|
||||
clientUid(clientId).value_or(""), nicknameFor(clientId));
|
||||
(void)database_->logQueueAddition(clientUid(clientId).value_or(""),
|
||||
nicknameFor(clientId));
|
||||
}
|
||||
|
||||
// Auto-start when idle with an online audience.
|
||||
@@ -946,6 +951,9 @@ namespace Echoion::Core
|
||||
importRunning_ = false;
|
||||
return;
|
||||
}
|
||||
if (youTubeClient_) {
|
||||
youTubeClient_->populateShortenedUrls(*tracks);
|
||||
}
|
||||
size_t queued = 0;
|
||||
for (const auto& track : *tracks) {
|
||||
if (queueTrack(track, clientId)) {
|
||||
@@ -1050,26 +1058,33 @@ namespace Echoion::Core
|
||||
// YouTube search goes through the router (Invidious/Piped/ytdlp);
|
||||
// Yandex is called directly (its canHandle rejects text, so the
|
||||
// router never routes bare queries to it).
|
||||
const auto applyShortening =
|
||||
[this](Api::Result<Api::SearchResult> result) {
|
||||
if (result && youTubeClient_) {
|
||||
youTubeClient_->populateShortenedUrls(result->tracks);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
const auto youtube = [&]() -> Api::Result<Api::SearchResult> {
|
||||
if (router_) {
|
||||
return router_->search(query);
|
||||
return applyShortening(router_->search(query));
|
||||
}
|
||||
if (youTubeClient_) {
|
||||
return youTubeClient_->search(query);
|
||||
return applyShortening(youTubeClient_->search(query));
|
||||
}
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"YouTube search unavailable");
|
||||
};
|
||||
const auto yandex = [&]() -> Api::Result<Api::SearchResult> {
|
||||
if (yandexSource_ && yandexSource_->isAvailable()) {
|
||||
return yandexSource_->search(query);
|
||||
return applyShortening(yandexSource_->search(query));
|
||||
}
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Yandex Music not configured");
|
||||
};
|
||||
const auto soundcloud = [&]() -> Api::Result<Api::SearchResult> {
|
||||
if (youTubeClient_) {
|
||||
return youTubeClient_->searchSoundCloud(query);
|
||||
return applyShortening(youTubeClient_->searchSoundCloud(query));
|
||||
}
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"SoundCloud search unavailable");
|
||||
@@ -1160,6 +1175,9 @@ namespace Echoion::Core
|
||||
auto selected =
|
||||
(*pending)[index - 1]; // Convert to 0-based (copy to modify)
|
||||
selected.requestedBy = invokerName;
|
||||
if (youTubeClient_) {
|
||||
youTubeClient_->populateShortenedUrl(selected);
|
||||
}
|
||||
|
||||
auto result = queueTrack(selected, clientId);
|
||||
if (!result) {
|
||||
@@ -1562,9 +1580,8 @@ namespace Echoion::Core
|
||||
|
||||
// Queue tracks that are both unplayed-recently and within the
|
||||
// radio duration cap. Stops once maxToQueue have been queued.
|
||||
auto queueRadio =
|
||||
[&](const std::vector<Api::TrackInfo>& tracks,
|
||||
size_t maxToQueue) -> size_t {
|
||||
auto queueRadio = [&](const std::vector<Api::TrackInfo>& tracks,
|
||||
size_t maxToQueue) -> size_t {
|
||||
size_t queued = 0;
|
||||
for (const auto& track : tracks) {
|
||||
if (recentUrls.contains(track.originalUrl)) {
|
||||
@@ -1600,14 +1617,13 @@ namespace Echoion::Core
|
||||
related = youTubeClient_->radioMix(seed, 10);
|
||||
}
|
||||
if (related && !related->empty()) {
|
||||
queued = queueRadio(*related, std::numeric_limits<
|
||||
size_t>::max());
|
||||
queued = queueRadio(*related,
|
||||
std::numeric_limits<size_t>::max());
|
||||
if (queued > 0) {
|
||||
Void::Log::info(
|
||||
"MusicManager", "{}",
|
||||
std::format(
|
||||
"Autoplay queued {} related track(s)",
|
||||
queued));
|
||||
std::format("Autoplay queued {} related track(s)",
|
||||
queued));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1621,10 +1637,9 @@ namespace Echoion::Core
|
||||
random && !random->empty()) {
|
||||
queued = queueRadio(*random, 1);
|
||||
if (queued > 0) {
|
||||
Void::Log::info(
|
||||
"MusicManager", "{}",
|
||||
"Autoplay queued a random music video "
|
||||
"(no unplayed related track found)");
|
||||
Void::Log::info("MusicManager", "{}",
|
||||
"Autoplay queued a random music video "
|
||||
"(no unplayed related track found)");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1634,9 +1649,8 @@ namespace Echoion::Core
|
||||
engine_->start();
|
||||
}
|
||||
} else {
|
||||
Void::Log::debug(
|
||||
"MusicManager", "{}",
|
||||
"Autoplay found no track to queue");
|
||||
Void::Log::debug("MusicManager", "{}",
|
||||
"Autoplay found no track to queue");
|
||||
}
|
||||
autoplayFetching_ = false;
|
||||
});
|
||||
@@ -1699,6 +1713,12 @@ namespace Echoion::Core
|
||||
Api::Result<Api::TrackInfo>
|
||||
MusicManager::resolveQuery(const std::string& query)
|
||||
{
|
||||
const auto finalize = [this](Api::Result<Api::TrackInfo> result) {
|
||||
if (result && youTubeClient_) {
|
||||
youTubeClient_->populateShortenedUrl(*result);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
// Playlist URLs are still resolved through the YouTube client (the
|
||||
// router's sources resolve single tracks).
|
||||
if (config_.allowPlaylistImports &&
|
||||
@@ -1710,13 +1730,13 @@ namespace Echoion::Core
|
||||
std::format("Extracted playlist ID: '{}'", *playlistId));
|
||||
auto playlist = youTubeClient_->getPlaylist(*playlistId);
|
||||
if (playlist && !playlist->tracks.empty()) {
|
||||
return playlist->tracks[0];
|
||||
return finalize(playlist->tracks[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (router_) {
|
||||
return router_->resolve(query);
|
||||
return finalize(router_->resolve(query));
|
||||
}
|
||||
|
||||
auto searchResult = youTubeClient_->search(query);
|
||||
@@ -1726,7 +1746,7 @@ namespace Echoion::Core
|
||||
if (searchResult->tracks.empty()) {
|
||||
return Api::fail(Api::ErrorCode::NotFound, "No results found");
|
||||
}
|
||||
return searchResult->tracks[0];
|
||||
return finalize(searchResult->tracks[0]);
|
||||
}
|
||||
|
||||
Api::Result<std::string>
|
||||
|
||||
+46
-7
@@ -1,6 +1,6 @@
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include "echoion/core/NetworkClient.hpp"
|
||||
#include <Void/Functional/Retry.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
@@ -18,8 +18,10 @@ namespace Echoion::Core
|
||||
proxy_ = proxy;
|
||||
}
|
||||
initialized_ = true;
|
||||
Void::Log::info("NetworkClient", "{}", std::format("NetworkClient initialized (proxy: {})",
|
||||
proxy.has_value() ? "enabled" : "disabled"));
|
||||
Void::Log::info(
|
||||
"NetworkClient", "{}",
|
||||
std::format("NetworkClient initialized (proxy: {})",
|
||||
proxy.has_value() ? "enabled" : "disabled"));
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -32,7 +34,8 @@ namespace Echoion::Core
|
||||
// Snapshot the proxy under the lock. setProxy()/initialize() can run on
|
||||
// other threads (config reload, init), and a torn read of the
|
||||
// optional<ProxyConfig> (it holds std::string host/user/pass) could
|
||||
// yield an empty host -> enabled()==false -> a silent direct connection.
|
||||
// yield an empty host -> enabled()==false -> a silent direct
|
||||
// connection.
|
||||
std::optional<Void::Net::ProxyConfig> active;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
@@ -57,15 +60,17 @@ namespace Echoion::Core
|
||||
retryPolicy_, [&] { return executeRequest(req); },
|
||||
[this](const Api::Result<Void::Net::Response>& result) {
|
||||
if (!result) {
|
||||
Void::Log::warn("NetworkClient", "{}", std::format(
|
||||
"Request error: {}, retrying", result.error().message));
|
||||
Void::Log::warn("NetworkClient", "{}",
|
||||
std::format("Request error: {}, retrying",
|
||||
result.error().message));
|
||||
return true;
|
||||
}
|
||||
// Retry only on the configured retryable HTTP statuses.
|
||||
const auto& codes = retryableStatusCodes_;
|
||||
if (std::find(codes.begin(), codes.end(), result->status) !=
|
||||
codes.end()) {
|
||||
Void::Log::warn("NetworkClient", "{}",
|
||||
Void::Log::warn(
|
||||
"NetworkClient", "{}",
|
||||
std::format("Request failed with status {}, retrying",
|
||||
result->status));
|
||||
return true;
|
||||
@@ -122,6 +127,40 @@ namespace Echoion::Core
|
||||
return request(req);
|
||||
}
|
||||
|
||||
Api::Result<Void::Net::Response> NetworkClient::postVerifiedTls(
|
||||
std::string_view url, std::string_view body,
|
||||
const std::vector<Void::Net::Header>& headers)
|
||||
{
|
||||
if (!url.starts_with("https://")) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Verified request requires an HTTPS URL");
|
||||
}
|
||||
std::optional<Void::Net::ProxyConfig> active;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
active = proxy_;
|
||||
}
|
||||
Void::Net::HttpClient client;
|
||||
client.set_verify_tls(true);
|
||||
client.set_max_redirects(0);
|
||||
client.set_max_body_size(1024 * 1024);
|
||||
if (active && active->enabled()) {
|
||||
client.set_proxy(*active);
|
||||
}
|
||||
Void::Net::Request request;
|
||||
request.url = std::string{url};
|
||||
request.method = Void::Net::Method::Post;
|
||||
request.headers = headers;
|
||||
request.body = std::string{body};
|
||||
request.timeout = std::chrono::seconds{15};
|
||||
auto result = client.send(request);
|
||||
if (!result) {
|
||||
return Api::fail(Api::ErrorCode::NetworkError,
|
||||
result.error().message());
|
||||
}
|
||||
return std::move(*result);
|
||||
}
|
||||
|
||||
void NetworkClient::setProxy(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
#include "PluginCompatibility.hpp"
|
||||
|
||||
#include "ModuleContracts.hpp"
|
||||
|
||||
#include <cstddef>
|
||||
#include <exception>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
|
||||
namespace Echoion::Core::Detail
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr std::size_t maximumDescriptorText = 1024;
|
||||
constexpr std::size_t maximumDependencies = 64;
|
||||
|
||||
[[nodiscard]] PluginCompatibility reject(std::string reason)
|
||||
{
|
||||
return {.compatible = false, .reason = std::move(reason)};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool valid(const echoion_string_view_v1 value) noexcept
|
||||
{
|
||||
return value.size <= maximumDescriptorText &&
|
||||
(value.size == 0U || value.data != nullptr);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view
|
||||
view(const echoion_string_view_v1 value) noexcept
|
||||
{
|
||||
return value.data == nullptr
|
||||
? std::string_view{}
|
||||
: std::string_view{value.data, value.size};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
PluginCompatibility
|
||||
checkExtensionDescriptor(const echoion_module_descriptor_v1* descriptor)
|
||||
{
|
||||
if (descriptor == nullptr) {
|
||||
return reject("stable module descriptor is null");
|
||||
}
|
||||
if (descriptor->struct_size < sizeof(echoion_module_descriptor_v1) ||
|
||||
descriptor->abi_version != ECHOION_MODULE_ABI_VERSION) {
|
||||
return reject("stable module descriptor version is incompatible");
|
||||
}
|
||||
if (!valid(descriptor->component_id) ||
|
||||
view(descriptor->component_id).empty() ||
|
||||
descriptor->version_major != ECHOION_COMPONENT_VERSION_MAJOR) {
|
||||
return reject(
|
||||
"component identity or major version is incompatible");
|
||||
}
|
||||
if (descriptor->api == nullptr ||
|
||||
descriptor->api->struct_size < sizeof(echoion_module_api_v1) ||
|
||||
descriptor->api->abi_version != ECHOION_MODULE_ABI_VERSION ||
|
||||
descriptor->api->create == nullptr ||
|
||||
descriptor->api->destroy == nullptr ||
|
||||
descriptor->api->activate == nullptr ||
|
||||
descriptor->api->quiesce == nullptr ||
|
||||
descriptor->api->checkpoint == nullptr ||
|
||||
descriptor->api->restore == nullptr ||
|
||||
descriptor->api->readiness == nullptr ||
|
||||
descriptor->api->deactivate == nullptr) {
|
||||
return reject("stable module function table is incomplete");
|
||||
}
|
||||
if (descriptor->dependency_count > maximumDependencies ||
|
||||
(descriptor->dependency_count != 0U &&
|
||||
descriptor->dependencies == nullptr)) {
|
||||
return reject("stable module dependency table is invalid");
|
||||
}
|
||||
|
||||
bool apiCompatible = false;
|
||||
bool coreCompatible = false;
|
||||
for (std::size_t index = 0; index < descriptor->dependency_count;
|
||||
++index) {
|
||||
const auto& dependency = descriptor->dependencies[index];
|
||||
if (dependency.struct_size < sizeof(echoion_module_dependency_v1) ||
|
||||
!valid(dependency.component_id) ||
|
||||
!valid(dependency.abi_hash)) {
|
||||
return reject("stable module dependency entry is invalid");
|
||||
}
|
||||
const auto component = view(dependency.component_id);
|
||||
const auto abiHash = view(dependency.abi_hash);
|
||||
if (component == "EchoionApi" && dependency.optional == 0U) {
|
||||
apiCompatible = abiHash == CoreModule::apiAbiHash;
|
||||
}
|
||||
if (component == "EchoionCore" && dependency.optional == 0U) {
|
||||
coreCompatible = abiHash == CoreModule::coreAbiHash;
|
||||
}
|
||||
}
|
||||
if (!apiCompatible || !coreCompatible) {
|
||||
return reject("plugin was built for incompatible Echoion APIs");
|
||||
}
|
||||
return {.compatible = true, .reason = {}};
|
||||
}
|
||||
|
||||
PluginCompatibility
|
||||
checkExtensionCandidate(const Void::Plugin::PluginHandle& candidate)
|
||||
{
|
||||
const auto symbol =
|
||||
candidate.raw_symbol(ECHOION_MODULE_ABI_QUERY_SYMBOL);
|
||||
if (symbol == nullptr) {
|
||||
return reject("stable module query symbol is missing");
|
||||
}
|
||||
const auto query =
|
||||
reinterpret_cast<echoion_module_abi_query_fn_v1>(symbol);
|
||||
try {
|
||||
return checkExtensionDescriptor(query());
|
||||
} catch (const std::exception& error) {
|
||||
return reject(std::string{"stable module query threw: "} +
|
||||
error.what());
|
||||
} catch (...) {
|
||||
return reject("stable module query threw");
|
||||
}
|
||||
}
|
||||
} // namespace Echoion::Core::Detail
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api/module/ModuleAbi.h>
|
||||
|
||||
#include <Void/Plugin/Manager.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core::Detail
|
||||
{
|
||||
struct PluginCompatibility {
|
||||
bool compatible{};
|
||||
std::string reason;
|
||||
};
|
||||
|
||||
[[nodiscard]] PluginCompatibility checkExtensionDescriptor(
|
||||
const echoion_module_descriptor_v1* descriptor);
|
||||
[[nodiscard]] PluginCompatibility
|
||||
checkExtensionCandidate(const Void::Plugin::PluginHandle& candidate);
|
||||
} // namespace Echoion::Core::Detail
|
||||
+1141
File diff suppressed because it is too large.
Load diff
+10
-5
@@ -373,11 +373,16 @@ namespace Echoion::Core
|
||||
response.result = *result;
|
||||
} else {
|
||||
response.success = false;
|
||||
response.error = std::format(
|
||||
"{{\"code\":{},\"message\":\"{}\",\"source\":\"{}\"}}",
|
||||
static_cast<uint32_t>(result.error().code),
|
||||
result.error().message,
|
||||
result.error().source);
|
||||
// Error text can include quoted TeamSpeak permission names
|
||||
// or other protocol detail. Serialize it as JSON instead of
|
||||
// interpolating it into JSON syntax so the browser always
|
||||
// receives a decodable error.
|
||||
response.error = Void::Json::serialize(Void::Json::object(
|
||||
{{"code", Void::Json::Value{static_cast<long long>(
|
||||
result.error().code)}},
|
||||
{"message", Void::Json::Value{result.error().message}},
|
||||
{"source",
|
||||
Void::Json::Value{result.error().source}}}));
|
||||
}
|
||||
} else {
|
||||
response.success = false;
|
||||
|
||||
+32
-32
@@ -1,12 +1,14 @@
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include "echoion/core/SignatureCipher.hpp"
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <quickjs.h>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <quickjs.h>
|
||||
#include <regex>
|
||||
|
||||
// Minimal embedded fallback - a stub that logs errors
|
||||
@@ -492,40 +494,38 @@ namespace Echoion::Core
|
||||
std::optional<std::string>
|
||||
SignatureCipher::downloadSolverLibrary(std::string_view url)
|
||||
{
|
||||
// Simple curl-based download with redirect following
|
||||
// -s: silent, -L: follow redirects, -f: fail on HTTP error, -m 30:
|
||||
// timeout 30s
|
||||
std::string cmd =
|
||||
std::format("curl -sLf -m 30 '{}' 2>&1", std::string(url));
|
||||
Void::Log::debug("SignatureCipher", "{}",
|
||||
std::format("Downloading: {}", url));
|
||||
|
||||
Void::Log::debug("SignatureCipher", "{}", std::format("Downloading: {}", url));
|
||||
|
||||
FILE* pipe = popen(cmd.c_str(), "r");
|
||||
if (!pipe) {
|
||||
Void::Log::warn("SignatureCipher", "{}", std::format("Failed to run curl for {}", url));
|
||||
Void::Net::HttpClient client;
|
||||
client.set_verify_tls(true);
|
||||
client.set_max_redirects(5);
|
||||
client.set_max_body_size(16U * 1024U * 1024U);
|
||||
Void::Net::Request request;
|
||||
request.url = std::string(url);
|
||||
request.method = Void::Net::Method::Get;
|
||||
request.timeout = std::chrono::seconds{30};
|
||||
auto response = client.send(request);
|
||||
if (!response) {
|
||||
Void::Log::warn("SignatureCipher", "{}",
|
||||
std::format("Solver download failed for {}: {}",
|
||||
url, response.error().message()));
|
||||
return std::nullopt;
|
||||
}
|
||||
if (!response->ok()) {
|
||||
Void::Log::warn(
|
||||
"SignatureCipher", "{}",
|
||||
std::format("Solver download returned HTTP {} for {}",
|
||||
response->status, url));
|
||||
return std::nullopt;
|
||||
}
|
||||
if (response->body.empty()) {
|
||||
Void::Log::warn("SignatureCipher", "{}",
|
||||
std::format("Downloaded empty file from {}", url));
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::string result;
|
||||
char buffer[4096];
|
||||
while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
|
||||
result += buffer;
|
||||
}
|
||||
|
||||
int status = pclose(pipe);
|
||||
if (status != 0) {
|
||||
Void::Log::warn("SignatureCipher", "{}",
|
||||
std::format("curl failed with status {} for {}", status, url));
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
if (result.empty()) {
|
||||
Void::Log::warn("SignatureCipher", "{}",
|
||||
std::format("Downloaded empty file from {}", url));
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
return result;
|
||||
return std::move(response->body);
|
||||
}
|
||||
|
||||
void SignatureCipher::initSolver()
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
#include "echoion/core/TeamSpeakDirectoryService.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <utility>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
using Void::Json::Value;
|
||||
|
||||
Value optionalId(const std::optional<std::uint64_t>& id)
|
||||
{
|
||||
return id ? Value{static_cast<long long>(*id)} : Value{nullptr};
|
||||
}
|
||||
|
||||
Value publicClient(const Api::ClientInfo& client)
|
||||
{
|
||||
return Void::Json::object({{"nickname", Value{client.nickname}},
|
||||
{"talking", Value{client.isTalking}},
|
||||
{"muted", Value{client.isMuted}},
|
||||
{"deafened", Value{client.isDeafened}},
|
||||
{"away", Value{client.isAway}}});
|
||||
}
|
||||
|
||||
Value adminClient(const Api::ClientInfo& client)
|
||||
{
|
||||
Value::Array_t groups;
|
||||
groups.reserve(client.serverGroups.size());
|
||||
for (const auto group : client.serverGroups) {
|
||||
groups.emplace_back(static_cast<long long>(group));
|
||||
}
|
||||
return Void::Json::object(
|
||||
{{"id", Value{static_cast<long long>(client.id)}},
|
||||
{"databaseId", optionalId(client.databaseId)},
|
||||
{"uid", client.uniqueIdentifier
|
||||
? Value{*client.uniqueIdentifier}
|
||||
: Value{nullptr}},
|
||||
{"nickname", Value{client.nickname}},
|
||||
{"channelId", Value{static_cast<long long>(client.channelId)}},
|
||||
{"talking", Value{client.isTalking}},
|
||||
{"muted", Value{client.isMuted}},
|
||||
{"deafened", Value{client.isDeafened}},
|
||||
{"away", Value{client.isAway}},
|
||||
{"groups", Void::Json::array(std::move(groups))}});
|
||||
}
|
||||
|
||||
Value channelMetadata(const Api::ChannelInfo& channel)
|
||||
{
|
||||
return Void::Json::object(
|
||||
{{"id", Value{static_cast<long long>(channel.id)}},
|
||||
{"name", Value{channel.name}},
|
||||
{"parentId", optionalId(channel.parentId)},
|
||||
{"order", Value{static_cast<long long>(channel.order)}},
|
||||
{"default", Value{channel.isDefault}},
|
||||
{"permanent", Value{channel.isPermanent}},
|
||||
{"semiPermanent", Value{channel.isSemiPermanent}},
|
||||
{"password", Value{channel.hasPassword}},
|
||||
{"maxClients",
|
||||
Value{static_cast<long long>(channel.maxClients)}},
|
||||
{"currentClients",
|
||||
Value{static_cast<long long>(channel.currentClients)}}});
|
||||
}
|
||||
|
||||
Value buildChannelTree(const std::vector<Api::ChannelInfo>& channels,
|
||||
const std::vector<Api::ClientInfo>& clients,
|
||||
const std::optional<std::uint64_t>
|
||||
parent,
|
||||
bool admin)
|
||||
{
|
||||
Value::Array_t result;
|
||||
for (const auto& channel : channels) {
|
||||
if (channel.parentId != parent) {
|
||||
continue;
|
||||
}
|
||||
auto node = channelMetadata(channel);
|
||||
Value::Array_t members;
|
||||
for (const auto& client : clients) {
|
||||
if (client.channelId != channel.id || client.isQuery) {
|
||||
continue;
|
||||
}
|
||||
members.push_back(admin ? adminClient(client)
|
||||
: publicClient(client));
|
||||
}
|
||||
node.as_object().emplace_back(
|
||||
"clients", Void::Json::array(std::move(members)));
|
||||
node.as_object().emplace_back(
|
||||
"channels",
|
||||
buildChannelTree(channels, clients, channel.id, admin));
|
||||
result.push_back(std::move(node));
|
||||
}
|
||||
return Void::Json::array(std::move(result));
|
||||
}
|
||||
|
||||
Value serverJson(const TeamSpeakDirectoryService::Snapshot& snapshot)
|
||||
{
|
||||
const auto visibleClients =
|
||||
std::ranges::count_if(snapshot.clients, [](const auto& client) {
|
||||
return !client.isQuery;
|
||||
});
|
||||
return Void::Json::object(
|
||||
{{"name", Value{snapshot.server.name}},
|
||||
{"connected", Value{snapshot.connected}},
|
||||
{"clientCount", Value{static_cast<long long>(visibleClients)}},
|
||||
{"maxClients",
|
||||
Value{static_cast<long long>(snapshot.server.maxClients)}},
|
||||
{"channelCount",
|
||||
Value{static_cast<long long>(snapshot.channels.size())}},
|
||||
{"revision",
|
||||
Value{static_cast<long long>(snapshot.revision)}}});
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void TeamSpeakDirectoryService::setPluginInterface(
|
||||
Api::PluginInterfacePtr plugin)
|
||||
{
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
plugin_ = std::move(plugin);
|
||||
}
|
||||
(void)refresh();
|
||||
}
|
||||
|
||||
Api::Result<void> TeamSpeakDirectoryService::refresh()
|
||||
{
|
||||
Api::PluginInterfacePtr plugin;
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
plugin = plugin_;
|
||||
}
|
||||
if (!plugin) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"TeamSpeak interface is unavailable");
|
||||
}
|
||||
|
||||
// Host calls may block or invoke callbacks. Never hold the cache lock
|
||||
// while crossing that boundary.
|
||||
auto channelsResult = plugin->getChannels();
|
||||
if (!channelsResult) {
|
||||
return std::unexpected(channelsResult.error());
|
||||
}
|
||||
auto clientsResult = plugin->getClients();
|
||||
if (!clientsResult) {
|
||||
return std::unexpected(clientsResult.error());
|
||||
}
|
||||
|
||||
Snapshot next;
|
||||
next.connected = plugin->isConnected();
|
||||
next.channels = orderChannels(std::move(*channelsResult));
|
||||
for (auto& channel : next.channels) {
|
||||
// TeamSpeak uses 0 as the root parent while the API model uses an
|
||||
// absent value. Normalize once so both serializers build one tree.
|
||||
if (channel.parentId == 0) {
|
||||
channel.parentId.reset();
|
||||
}
|
||||
}
|
||||
next.clients = std::move(*clientsResult);
|
||||
if (auto server = plugin->getTeamSpeakServerInfo(); server) {
|
||||
next.server = std::move(*server);
|
||||
}
|
||||
|
||||
// Counts derived from the same snapshot cannot disagree with the tree,
|
||||
// even when a host does not expose TeamSpeak's aggregate properties.
|
||||
for (auto& channel : next.channels) {
|
||||
channel.currentClients = static_cast<std::uint32_t>(
|
||||
std::ranges::count_if(next.clients, [&](const auto& client) {
|
||||
return !client.isQuery && client.channelId == channel.id;
|
||||
}));
|
||||
}
|
||||
next.server.currentClients = static_cast<std::uint32_t>(
|
||||
std::ranges::count_if(next.clients, [](const auto& client) {
|
||||
return !client.isQuery;
|
||||
}));
|
||||
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
next.revision = snapshot_.revision + 1;
|
||||
snapshot_ = std::move(next);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
void TeamSpeakDirectoryService::handleEvent(Api::PluginEventType type)
|
||||
{
|
||||
switch (type) {
|
||||
case Api::PluginEventType::ConnectionEstablished:
|
||||
case Api::PluginEventType::ClientConnected:
|
||||
case Api::PluginEventType::ClientDisconnected:
|
||||
case Api::PluginEventType::ClientMoved:
|
||||
case Api::PluginEventType::ClientUpdated:
|
||||
case Api::PluginEventType::ChannelUpdated:
|
||||
(void)refresh();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
TeamSpeakDirectoryService::Snapshot
|
||||
TeamSpeakDirectoryService::snapshot() const
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
return snapshot_;
|
||||
}
|
||||
|
||||
Value TeamSpeakDirectoryService::publicJson() const
|
||||
{
|
||||
const auto current = snapshot();
|
||||
return Void::Json::object(
|
||||
{{"server", serverJson(current)},
|
||||
{"channels", buildChannelTree(current.channels, current.clients,
|
||||
std::nullopt, false)}});
|
||||
}
|
||||
|
||||
Value TeamSpeakDirectoryService::adminJson() const
|
||||
{
|
||||
const auto current = snapshot();
|
||||
return Void::Json::object(
|
||||
{{"server", serverJson(current)},
|
||||
{"channels", buildChannelTree(current.channels, current.clients,
|
||||
std::nullopt, true)}});
|
||||
}
|
||||
|
||||
std::vector<Api::ChannelInfo> TeamSpeakDirectoryService::orderChannels(
|
||||
std::vector<Api::ChannelInfo> channels)
|
||||
{
|
||||
std::map<std::optional<std::uint64_t>, std::vector<Api::ChannelInfo>>
|
||||
byParent;
|
||||
for (auto& channel : channels) {
|
||||
byParent[channel.parentId].push_back(std::move(channel));
|
||||
}
|
||||
|
||||
std::vector<Api::ChannelInfo> ordered;
|
||||
ordered.reserve(channels.size());
|
||||
for (auto& [parent, siblings] : byParent) {
|
||||
(void)parent;
|
||||
std::set<std::uint64_t> emitted;
|
||||
std::uint64_t predecessor = 0;
|
||||
for (;;) {
|
||||
auto next =
|
||||
std::ranges::find_if(siblings, [&](const auto& channel) {
|
||||
return channel.order == predecessor &&
|
||||
!emitted.contains(channel.id);
|
||||
});
|
||||
if (next == siblings.end()) {
|
||||
break;
|
||||
}
|
||||
predecessor = next->id;
|
||||
emitted.insert(next->id);
|
||||
ordered.push_back(*next);
|
||||
}
|
||||
std::ranges::sort(siblings, {}, &Api::ChannelInfo::id);
|
||||
for (const auto& orphan : siblings) {
|
||||
if (!emitted.contains(orphan.id)) {
|
||||
ordered.push_back(orphan);
|
||||
}
|
||||
}
|
||||
}
|
||||
return ordered;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
+135
-138
@@ -1,158 +1,155 @@
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include "echoion/core/UrlShortener.hpp"
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <format>
|
||||
|
||||
#include <Void/Log/Log.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <exception>
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
UrlShortener::UrlShortener(std::shared_ptr<NetworkClient> networkClient)
|
||||
: networkClient_(std::move(networkClient))
|
||||
namespace
|
||||
{
|
||||
}
|
||||
|
||||
UrlShortener::~UrlShortener() = default;
|
||||
|
||||
Api::Result<std::string>
|
||||
UrlShortener::shortenYouTubeUrl(std::string_view videoId)
|
||||
{
|
||||
std::string originalUrl =
|
||||
std::format("https://www.youtube.com/watch?v={}", videoId);
|
||||
return shortenUrl(originalUrl);
|
||||
}
|
||||
|
||||
Api::Result<std::string>
|
||||
UrlShortener::shortenUrl(std::string_view originalUrl)
|
||||
{
|
||||
// Check cache first
|
||||
std::string lower(std::string value)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(cacheMutex_);
|
||||
auto it = cache_.find(std::string(originalUrl));
|
||||
if (it != cache_.end()) {
|
||||
auto now = std::chrono::system_clock::now();
|
||||
if (now - it->second.timestamp < cacheTtl_) {
|
||||
Void::Log::debug("UrlShortener", "{}", std::format("URL cache hit: {} -> {}",
|
||||
originalUrl,
|
||||
it->second.shortenedUrl));
|
||||
return it->second.shortenedUrl;
|
||||
}
|
||||
// Expired, remove from cache
|
||||
cache_.erase(it);
|
||||
std::ranges::transform(value, value.begin(), [](unsigned char ch) {
|
||||
return static_cast<char>(std::tolower(ch));
|
||||
});
|
||||
return value;
|
||||
}
|
||||
|
||||
std::optional<Api::TrackSource> sourceFromName(std::string name)
|
||||
{
|
||||
name = lower(std::move(name));
|
||||
if (name == "youtube") {
|
||||
return Api::TrackSource::YouTube;
|
||||
}
|
||||
if (name == "yandex") {
|
||||
return Api::TrackSource::Yandex;
|
||||
}
|
||||
if (name == "url") {
|
||||
return Api::TrackSource::URL;
|
||||
}
|
||||
if (name == "soundcloud") {
|
||||
return Api::TrackSource::SoundCloud;
|
||||
}
|
||||
if (name == "spotify") {
|
||||
return Api::TrackSource::Spotify;
|
||||
}
|
||||
if (name == "plugin") {
|
||||
return Api::TrackSource::Plugin;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
Api::ErrorCode apiError(Void::ShortUrl::ErrorCode code)
|
||||
{
|
||||
using enum Void::ShortUrl::ErrorCode;
|
||||
switch (code) {
|
||||
case invalid_request:
|
||||
return Api::ErrorCode::InvalidArgument;
|
||||
case invalid_url:
|
||||
return Api::ErrorCode::InvalidUrl;
|
||||
case unsupported:
|
||||
return Api::ErrorCode::NotSupported;
|
||||
case not_found:
|
||||
case expired:
|
||||
case revoked:
|
||||
return Api::ErrorCode::NotFound;
|
||||
case conflict:
|
||||
return Api::ErrorCode::AlreadyExists;
|
||||
case unauthorized:
|
||||
return Api::ErrorCode::Unauthorized;
|
||||
case unavailable:
|
||||
case timeout:
|
||||
case rate_limited:
|
||||
return Api::ErrorCode::ServiceUnavailable;
|
||||
case provider_error:
|
||||
case response_too_large:
|
||||
return Api::ErrorCode::NetworkError;
|
||||
case storage:
|
||||
return Api::ErrorCode::DatabaseError;
|
||||
default:
|
||||
return Api::ErrorCode::UnknownError;
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
if (!networkClient_) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Network client not available");
|
||||
void UrlShortener::setProvider(ProviderGetter provider)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
provider_ = std::move(provider);
|
||||
}
|
||||
|
||||
void UrlShortener::setSources(const std::vector<std::string>& sources)
|
||||
{
|
||||
std::unordered_set<Api::TrackSource> parsed;
|
||||
for (const auto& source : sources) {
|
||||
if (auto value = sourceFromName(source)) {
|
||||
parsed.insert(*value);
|
||||
}
|
||||
}
|
||||
std::lock_guard lock(mutex_);
|
||||
sources_ = std::move(parsed);
|
||||
}
|
||||
|
||||
bool UrlShortener::sourceAllowed(Api::TrackSource source) const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
return source != Api::TrackSource::LocalFile &&
|
||||
sources_.contains(source);
|
||||
}
|
||||
|
||||
Api::Result<std::string>
|
||||
UrlShortener::shortenUrl(std::string_view originalUrl,
|
||||
Api::TrackSource source) const
|
||||
{
|
||||
if (originalUrl.empty() || !sourceAllowed(source)) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"URL source is not enabled for shortening");
|
||||
}
|
||||
|
||||
// faumaray.ru API endpoint for URL shortening
|
||||
// POST /shorten with JSON body {"longUrl": "https://..."}
|
||||
// Response: {"shortUrl": "https://faumaray.ru/xxxxx"}
|
||||
std::string apiUrl = "https://faumaray.ru/shorten";
|
||||
|
||||
// Build JSON request body - API expects "longUrl" field
|
||||
std::string jsonBody =
|
||||
std::format(R"({{"longUrl":"{}"}})", originalUrl);
|
||||
|
||||
std::vector<Void::Net::Header> headers = {
|
||||
{"Content-Type", "application/json"},
|
||||
{"User-Agent", "EchoionBot/1.0"}};
|
||||
|
||||
Void::Log::debug("UrlShortener", "{}",
|
||||
std::format("Shortening URL via faumaray.ru: {}", originalUrl));
|
||||
|
||||
auto response = networkClient_->post(apiUrl, jsonBody, headers);
|
||||
|
||||
if (!response) {
|
||||
Void::Log::warn("UrlShortener", "{}", std::format("URL shortening failed: {}",
|
||||
response.error().message));
|
||||
return Api::fail(Api::ErrorCode::NetworkError,
|
||||
"Failed to shorten URL");
|
||||
ProviderGetter getter;
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
getter = provider_;
|
||||
}
|
||||
|
||||
if (!response->ok()) {
|
||||
Void::Log::warn("UrlShortener", "{}", std::format("URL shortening returned HTTP {}",
|
||||
response->status));
|
||||
return Api::fail(Api::ErrorCode::NetworkError,
|
||||
std::format("Shortening service returned HTTP {}",
|
||||
response->status));
|
||||
}
|
||||
|
||||
try {
|
||||
// Parse response - expecting {"shortUrl":
|
||||
// "https://faumaray.ru/xxxxx"}
|
||||
auto parsed = Void::Json::parse(response->body);
|
||||
if (!parsed) {
|
||||
Void::Log::warn("UrlShortener", "{}", "Failed to parse URL shortening response");
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"Failed to parse shortening response");
|
||||
auto provider = getter ? getter() : nullptr;
|
||||
if (!provider || provider->service_version() !=
|
||||
Void::ShortUrl::kServiceVersion) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"URL shortener provider is unavailable");
|
||||
}
|
||||
const auto health = provider->health();
|
||||
if (health.status == Void::ShortUrl::HealthStatus::unhealthy) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
health.message.empty()
|
||||
? "URL shortener provider is unhealthy"
|
||||
: health.message);
|
||||
}
|
||||
|
||||
std::string shortenedUrl;
|
||||
const Void::Json::Value* shortUrl = parsed->find("shortUrl");
|
||||
if (shortUrl && shortUrl->is_string()) {
|
||||
shortenedUrl = shortUrl->as_string();
|
||||
} else {
|
||||
Void::Log::warn("UrlShortener", "{}", "No shortUrl field in response");
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"No shortUrl in response");
|
||||
}
|
||||
|
||||
// Cache the result
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(cacheMutex_);
|
||||
cache_[std::string(originalUrl)] = {
|
||||
.shortenedUrl = shortenedUrl,
|
||||
.timestamp = std::chrono::system_clock::now()};
|
||||
}
|
||||
|
||||
Void::Log::debug("UrlShortener", "{}", std::format("URL shortened: {} -> {}",
|
||||
originalUrl, shortenedUrl));
|
||||
return shortenedUrl;
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::warn("UrlShortener", "{}", std::format(
|
||||
"Exception parsing shortening response: {}", e.what()));
|
||||
return Api::fail(
|
||||
Api::ErrorCode::ParseError, "Exception during URL shortening");
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<std::string>
|
||||
UrlShortener::getCachedUrl(std::string_view originalUrl) const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(cacheMutex_);
|
||||
auto it = cache_.find(std::string(originalUrl));
|
||||
if (it != cache_.end()) {
|
||||
auto now = std::chrono::system_clock::now();
|
||||
if (now - it->second.timestamp < cacheTtl_) {
|
||||
return it->second.shortenedUrl;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
void UrlShortener::clearCache()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(cacheMutex_);
|
||||
cache_.clear();
|
||||
}
|
||||
|
||||
void UrlShortener::setCacheTtl(std::chrono::hours ttl) { cacheTtl_ = ttl; }
|
||||
|
||||
void UrlShortener::cleanExpiredCache()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(cacheMutex_);
|
||||
auto now = std::chrono::system_clock::now();
|
||||
|
||||
for (auto it = cache_.begin(); it != cache_.end();) {
|
||||
if (now - it->second.timestamp >= cacheTtl_) {
|
||||
it = cache_.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
auto result =
|
||||
provider->shorten({.target_url = std::string(originalUrl),
|
||||
.custom_key = {},
|
||||
.expires_at_unix_seconds = 0});
|
||||
if (!result.ok() || result.short_url.empty()) {
|
||||
return Api::fail(apiError(result.error.code),
|
||||
result.error.message.empty()
|
||||
? "URL shortening failed"
|
||||
: result.error.message);
|
||||
}
|
||||
return result.short_url;
|
||||
} catch (const std::exception& error) {
|
||||
Void::Log::warn("UrlShortener", "Provider call failed: {}",
|
||||
error.what());
|
||||
} catch (...) {
|
||||
Void::Log::warn("UrlShortener", "Provider call failed");
|
||||
}
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"URL shortener provider failed");
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
+95
-90
@@ -31,7 +31,7 @@ namespace Echoion::Core
|
||||
YouTubeClient::YouTubeClient(std::shared_ptr<NetworkClient> networkClient)
|
||||
: networkClient_(std::move(networkClient)),
|
||||
ytDlpManager_(std::make_unique<YtDlpManager>(networkClient_)),
|
||||
urlShortener_(std::make_unique<UrlShortener>(networkClient_))
|
||||
urlShortener_(std::make_unique<UrlShortener>())
|
||||
{
|
||||
}
|
||||
|
||||
@@ -492,9 +492,8 @@ namespace Echoion::Core
|
||||
return results;
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult>
|
||||
YouTubeClient::search(std::string_view query,
|
||||
std::optional<std::string> pageToken)
|
||||
Api::Result<Api::SearchResult> YouTubeClient::search(
|
||||
std::string_view query, std::optional<std::string> pageToken)
|
||||
{
|
||||
|
||||
if (!initialized_) {
|
||||
@@ -839,8 +838,7 @@ namespace Echoion::Core
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult> YouTubeClient::searchWithYtDlp(
|
||||
std::string_view query,
|
||||
const std::optional<std::string>& /*pageToken*/)
|
||||
std::string_view query, const std::optional<std::string>& /*pageToken*/)
|
||||
{
|
||||
return searchWithYtDlpProvider(query, "ytsearch5",
|
||||
Api::TrackSource::YouTube);
|
||||
@@ -853,9 +851,10 @@ namespace Echoion::Core
|
||||
Api::TrackSource::SoundCloud);
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult> YouTubeClient::searchWithYtDlpProvider(
|
||||
std::string_view query, std::string_view searchPrefix,
|
||||
Api::TrackSource source)
|
||||
Api::Result<Api::SearchResult>
|
||||
YouTubeClient::searchWithYtDlpProvider(std::string_view query,
|
||||
std::string_view searchPrefix,
|
||||
Api::TrackSource source)
|
||||
{
|
||||
|
||||
if (!ytDlpManager_->isAvailable()) {
|
||||
@@ -1061,10 +1060,9 @@ namespace Echoion::Core
|
||||
// per call; combined with the shuffled results this gives the radio a
|
||||
// varied backstop when no related/unplayed track is available.
|
||||
static const std::array<std::string_view, 10> kQueries = {
|
||||
"popular music", "top hits", "rock music",
|
||||
"electronic music", "hip hop music", "lofi hip hop",
|
||||
"pop music", "jazz music", "indie music",
|
||||
"dance music"};
|
||||
"popular music", "top hits", "rock music", "electronic music",
|
||||
"hip hop music", "lofi hip hop", "pop music", "jazz music",
|
||||
"indie music", "dance music"};
|
||||
|
||||
static thread_local std::mt19937 rng(std::random_device{}());
|
||||
std::uniform_int_distribution<size_t> pick(0, kQueries.size() - 1);
|
||||
@@ -1610,60 +1608,21 @@ namespace Echoion::Core
|
||||
{
|
||||
std::string url_str(url);
|
||||
|
||||
// Handle faumaray.ru redirects using NetworkClient
|
||||
if (url_str.find("faumaray.ru") != std::string::npos &&
|
||||
networkClient_) {
|
||||
Void::Log::debug(
|
||||
"YouTubeClient", "{}",
|
||||
std::format("Following redirect for: {}", url_str));
|
||||
|
||||
std::vector<Void::Net::Header> headers = {
|
||||
{"User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36"}};
|
||||
|
||||
// Make request without following redirects to get the Location
|
||||
// header
|
||||
auto response = networkClient_->get(url_str, headers);
|
||||
|
||||
if (response) {
|
||||
// Check if we got a redirect
|
||||
if (response->status >= 300 && response->status < 400) {
|
||||
auto location = response->header("location");
|
||||
if (location.has_value()) {
|
||||
Void::Log::debug(
|
||||
"YouTubeClient", "{}",
|
||||
std::format("Redirected to: {}", *location));
|
||||
url_str = std::string(*location);
|
||||
}
|
||||
} else if (response->ok()) {
|
||||
// Some shorteners might return the target in the body or we
|
||||
// might need to look at the URL after any automatic
|
||||
// redirect following Try to extract from current URL or
|
||||
// response
|
||||
auto finalUrl = response->header(
|
||||
"x-final-url"); // Some clients add this
|
||||
if (finalUrl.has_value()) {
|
||||
url_str = std::string(*finalUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// More comprehensive regex patterns for YouTube URLs
|
||||
static const std::regex watch_pattern(
|
||||
R"((?:https?://)?(?:www\.)?youtube\.com/watch\?[^\s]*v=([a-zA-Z0-9_-]{11})(?:&[^\s]*)?)",
|
||||
R"(^(?:https?://)?(?:www\.)?youtube\.com/watch\?[^\s]*v=([a-zA-Z0-9_-]{11})(?:&[^\s]*)?$)",
|
||||
std::regex::icase);
|
||||
|
||||
static const std::regex short_pattern(
|
||||
R"((?:https?://)?(?:www\.)?youtu\.be/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?)",
|
||||
R"(^(?:https?://)?(?:www\.)?youtu\.be/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?$)",
|
||||
std::regex::icase);
|
||||
|
||||
static const std::regex embed_pattern(
|
||||
R"((?:https?://)?(?:www\.)?youtube\.com/embed/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?)",
|
||||
R"(^(?:https?://)?(?:www\.)?youtube\.com/embed/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?$)",
|
||||
std::regex::icase);
|
||||
|
||||
static const std::regex shorts_pattern(
|
||||
R"((?:https?://)?(?:www\.)?youtube\.com/shorts/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?)",
|
||||
R"(^(?:https?://)?(?:www\.)?youtube\.com/shorts/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?$)",
|
||||
std::regex::icase);
|
||||
|
||||
// Also match just the video ID (11 characters)
|
||||
@@ -1697,9 +1656,10 @@ namespace Echoion::Core
|
||||
|
||||
bool YouTubeClient::isYouTubeUrl(std::string_view url)
|
||||
{
|
||||
return url.find("faumaray.ru") != std::string::npos ||
|
||||
url.find("youtube.com") != std::string::npos ||
|
||||
url.find("youtu.be") != std::string::npos;
|
||||
static const std::regex youtubeUrlPattern(
|
||||
R"(^(?:https?://)?(?:www\.)?(?:youtube\.com(?:/|$)|youtu\.be(?:/|$)))",
|
||||
std::regex::icase);
|
||||
return std::regex_search(url.begin(), url.end(), youtubeUrlPattern);
|
||||
}
|
||||
|
||||
void YouTubeClient::setUrlShorteningEnabled(bool enabled)
|
||||
@@ -1711,6 +1671,25 @@ namespace Echoion::Core
|
||||
std::format("URL shortening {}", enabled ? "enabled" : "disabled"));
|
||||
}
|
||||
|
||||
void YouTubeClient::setUrlShortenerProvider(
|
||||
UrlShortener::ProviderGetter provider)
|
||||
{
|
||||
urlShortener_->setProvider(std::move(provider));
|
||||
}
|
||||
|
||||
void YouTubeClient::setUrlShorteningSources(
|
||||
const std::vector<std::string>& sources)
|
||||
{
|
||||
urlShortener_->setSources(sources);
|
||||
}
|
||||
|
||||
void YouTubeClient::setUrlShorteningTimeout(
|
||||
std::chrono::milliseconds timeout)
|
||||
{
|
||||
std::lock_guard lock(configMutex_);
|
||||
urlShorteningTimeout_ = timeout;
|
||||
}
|
||||
|
||||
void YouTubeClient::setAutoUpdateEnabled(bool enabled)
|
||||
{
|
||||
if (ytDlpManager_) {
|
||||
@@ -1727,35 +1706,46 @@ namespace Echoion::Core
|
||||
void YouTubeClient::populateShortenedUrl(Api::TrackInfo& track)
|
||||
{
|
||||
bool enabled;
|
||||
std::chrono::milliseconds timeout;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
enabled = urlShorteningEnabled_;
|
||||
timeout = urlShorteningTimeout_;
|
||||
}
|
||||
if (!enabled || !urlShortener_ || track.id.empty()) {
|
||||
if (!enabled || !urlShortener_ ||
|
||||
(track.shortenedUrl && !track.shortenedUrl->empty())) {
|
||||
return;
|
||||
}
|
||||
std::string originalUrl = track.originalUrl;
|
||||
if (originalUrl.empty() && track.source == Api::TrackSource::YouTube &&
|
||||
!track.id.empty()) {
|
||||
originalUrl =
|
||||
std::format("https://www.youtube.com/watch?v={}", track.id);
|
||||
}
|
||||
if (originalUrl.empty()) {
|
||||
return;
|
||||
}
|
||||
const auto source = track.source;
|
||||
|
||||
// Run URL shortening on the shared pool with a timeout. Best-effort: if
|
||||
// it times out we keep the track unshortened. The future is only read
|
||||
// on the ready path (which establishes happens-before), and on timeout
|
||||
// the task keeps running on the pool with its result discarded — no
|
||||
// detached thread and no busy-wait poll.
|
||||
auto trackId = track.id;
|
||||
auto future =
|
||||
pool_.submit([this, trackId]() -> std::optional<std::string> {
|
||||
try {
|
||||
auto result = urlShortener_->shortenYouTubeUrl(trackId);
|
||||
if (result) {
|
||||
return *result;
|
||||
}
|
||||
} catch (...) {
|
||||
// Ignore exceptions - this is best-effort
|
||||
auto future = pool_.submit([this, originalUrl = std::move(originalUrl),
|
||||
source]() -> std::optional<std::string> {
|
||||
try {
|
||||
auto result = urlShortener_->shortenUrl(originalUrl, source);
|
||||
if (result) {
|
||||
return *result;
|
||||
}
|
||||
return std::nullopt;
|
||||
});
|
||||
} catch (...) {
|
||||
// Ignore exceptions - this is best-effort
|
||||
}
|
||||
return std::nullopt;
|
||||
});
|
||||
|
||||
if (future.wait_for(std::chrono::seconds(3)) ==
|
||||
std::future_status::ready) {
|
||||
if (future.wait_for(timeout) == std::future_status::ready) {
|
||||
if (auto shortened = future.get()) {
|
||||
track.shortenedUrl = *shortened;
|
||||
Void::Log::debug("YouTubeClient", "{}",
|
||||
@@ -1765,7 +1755,8 @@ namespace Echoion::Core
|
||||
}
|
||||
} else {
|
||||
Void::Log::warn("YouTubeClient", "{}",
|
||||
"URL shortening timed out after 3s");
|
||||
std::format("URL shortening timed out after {}ms",
|
||||
timeout.count()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1773,9 +1764,11 @@ namespace Echoion::Core
|
||||
std::vector<Api::TrackInfo>& tracks)
|
||||
{
|
||||
bool enabled;
|
||||
std::chrono::milliseconds timeout;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
enabled = urlShorteningEnabled_;
|
||||
timeout = urlShorteningTimeout_;
|
||||
}
|
||||
if (!enabled || !urlShortener_ || tracks.empty()) {
|
||||
return;
|
||||
@@ -1798,30 +1791,42 @@ namespace Echoion::Core
|
||||
slots.reserve(tracks.size());
|
||||
|
||||
for (auto& track : tracks) {
|
||||
if (track.id.empty()) {
|
||||
if (track.shortenedUrl && !track.shortenedUrl->empty()) {
|
||||
continue;
|
||||
}
|
||||
auto trackId = track.id;
|
||||
std::string originalUrl = track.originalUrl;
|
||||
if (originalUrl.empty() &&
|
||||
track.source == Api::TrackSource::YouTube &&
|
||||
!track.id.empty()) {
|
||||
originalUrl =
|
||||
std::format("https://www.youtube.com/watch?v={}", track.id);
|
||||
}
|
||||
if (originalUrl.empty()) {
|
||||
continue;
|
||||
}
|
||||
const auto source = track.source;
|
||||
auto out = std::make_shared<std::optional<std::string>>();
|
||||
auto future = pool_.submit([this, trackId, out]() {
|
||||
try {
|
||||
auto result = urlShortener_->shortenYouTubeUrl(trackId);
|
||||
if (result) {
|
||||
*out = *result;
|
||||
auto future = pool_.submit(
|
||||
[this, originalUrl = std::move(originalUrl), source, out]() {
|
||||
try {
|
||||
auto result =
|
||||
urlShortener_->shortenUrl(originalUrl, source);
|
||||
if (result) {
|
||||
*out = *result;
|
||||
}
|
||||
} catch (...) {
|
||||
// Ignore exceptions - best-effort
|
||||
}
|
||||
} catch (...) {
|
||||
// Ignore exceptions - best-effort
|
||||
}
|
||||
});
|
||||
});
|
||||
slots.push_back({&track, std::move(out), std::move(future)});
|
||||
}
|
||||
|
||||
// Wait for all with an overall 5-second timeout.
|
||||
// Wait for all with the configured overall timeout.
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
for (auto& slot : slots) {
|
||||
auto remaining = std::chrono::seconds(5) -
|
||||
(std::chrono::steady_clock::now() - start);
|
||||
if (remaining <= std::chrono::seconds::zero()) {
|
||||
auto remaining =
|
||||
timeout - (std::chrono::steady_clock::now() - start);
|
||||
if (remaining <= std::chrono::milliseconds::zero()) {
|
||||
break;
|
||||
}
|
||||
slot.future.wait_for(remaining);
|
||||
|
||||
+27
-4
@@ -52,6 +52,10 @@ namespace Echoion::Core
|
||||
}
|
||||
return homeDir / "echoion" / "yt-dlp";
|
||||
#else
|
||||
if (const char* dataHome = std::getenv("XDG_DATA_HOME");
|
||||
dataHome && *dataHome != '\0') {
|
||||
return std::filesystem::path{dataHome} / "echoion" / "yt-dlp";
|
||||
}
|
||||
const char* home = std::getenv("HOME");
|
||||
if (home) {
|
||||
homeDir = home;
|
||||
@@ -83,8 +87,12 @@ namespace Echoion::Core
|
||||
return std::string(YTDLP_DOWNLOAD_WINDOWS);
|
||||
#elif defined(__APPLE__)
|
||||
return std::string(YTDLP_DOWNLOAD_MACOS);
|
||||
#elif defined(__x86_64__) || defined(_M_X64)
|
||||
return std::string(YTDLP_DOWNLOAD_LINUX_X86_64);
|
||||
#elif defined(__aarch64__) || defined(_M_ARM64)
|
||||
return std::string(YTDLP_DOWNLOAD_LINUX_AARCH64);
|
||||
#else
|
||||
return std::string(YTDLP_DOWNLOAD_LINUX);
|
||||
return {};
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -323,6 +331,11 @@ namespace Echoion::Core
|
||||
}
|
||||
|
||||
std::string downloadUrl = getDownloadUrl();
|
||||
if (downloadUrl.empty()) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::ServiceUnavailable,
|
||||
"No standalone yt-dlp release is available for this platform");
|
||||
}
|
||||
Void::Log::info(
|
||||
"YtDlpManager", "{}",
|
||||
std::format("Downloading yt-dlp from: {}", downloadUrl));
|
||||
@@ -441,12 +454,22 @@ namespace Echoion::Core
|
||||
if (!probe || probe->exit_code != 0) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tempPath, ec);
|
||||
std::string details =
|
||||
probe ? std::format("exit code {}", probe->exit_code)
|
||||
: probe.error().message();
|
||||
if (probe) {
|
||||
const auto& output =
|
||||
!probe->err.empty() ? probe->err : probe->out;
|
||||
if (!output.empty()) {
|
||||
constexpr std::size_t maxDiagnosticLength = 1024;
|
||||
details += std::format(
|
||||
"; output: {}", output.substr(0, maxDiagnosticLength));
|
||||
}
|
||||
}
|
||||
return Api::fail(
|
||||
Api::ErrorCode::ServiceUnavailable,
|
||||
std::format("Downloaded yt-dlp failed verification: {}",
|
||||
probe ? std::format("exit code {}",
|
||||
probe->exit_code)
|
||||
: probe.error().message()));
|
||||
details));
|
||||
}
|
||||
|
||||
std::error_code renameEc;
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
#include "echoion/core/licensing/LicenseManager.hpp"
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Security/Security.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <limits>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
|
||||
#ifndef ECHOION_LICENSE_ROOT_KEY_ID
|
||||
#define ECHOION_LICENSE_ROOT_KEY_ID ""
|
||||
#endif
|
||||
#ifndef ECHOION_LICENSE_ROOT_PUBLIC_KEY
|
||||
#define ECHOION_LICENSE_ROOT_PUBLIC_KEY ""
|
||||
#endif
|
||||
#ifndef ECHOION_BUILD_SIGNATURE
|
||||
#define ECHOION_BUILD_SIGNATURE "development"
|
||||
#endif
|
||||
#ifndef ECHOION_PRODUCT_VERSION
|
||||
#define ECHOION_PRODUCT_VERSION "0.0.0"
|
||||
#endif
|
||||
|
||||
namespace Echoion::Core::Licensing
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
readFile(const std::filesystem::path& path)
|
||||
{
|
||||
std::ifstream input(path, std::ios::binary);
|
||||
if (!input) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return std::string{std::istreambuf_iterator<char>{input},
|
||||
std::istreambuf_iterator<char>{}};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool writePrivateFile(const std::filesystem::path& path,
|
||||
std::string_view contents)
|
||||
{
|
||||
std::error_code error;
|
||||
std::filesystem::create_directories(path.parent_path(), error);
|
||||
if (error) {
|
||||
return false;
|
||||
}
|
||||
const auto temporary = path.string() + ".tmp";
|
||||
{
|
||||
std::ofstream output(temporary,
|
||||
std::ios::binary | std::ios::trunc);
|
||||
if (!output) {
|
||||
return false;
|
||||
}
|
||||
output.write(contents.data(),
|
||||
static_cast<std::streamsize>(contents.size()));
|
||||
output.flush();
|
||||
if (!output) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
std::filesystem::permissions(
|
||||
temporary,
|
||||
std::filesystem::perms::owner_read |
|
||||
std::filesystem::perms::owner_write,
|
||||
std::filesystem::perm_options::replace, error);
|
||||
if (error) {
|
||||
std::filesystem::remove(temporary, error);
|
||||
return false;
|
||||
}
|
||||
std::filesystem::rename(temporary, path, error);
|
||||
return !error;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string endpoint(std::string url)
|
||||
{
|
||||
while (url.ends_with('/')) {
|
||||
url.pop_back();
|
||||
}
|
||||
return url + "/api/v1/licenses/refresh";
|
||||
}
|
||||
|
||||
[[nodiscard]] bool isAuthoritativeDenial(long status) noexcept
|
||||
{
|
||||
return status == 401 || status == 402 || status == 403 ||
|
||||
status == 410 || status == 423 || status == 451;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
LicenseManager::LicenseManager(Api::LicensingConfig config,
|
||||
std::shared_ptr<NetworkClient>
|
||||
network,
|
||||
std::filesystem::path stateDirectory)
|
||||
: config_(std::move(config)), network_(std::move(network)),
|
||||
stateDirectory_(std::move(stateDirectory))
|
||||
{
|
||||
}
|
||||
|
||||
LicenseManager::~LicenseManager() { shutdown(); }
|
||||
|
||||
void LicenseManager::initialize()
|
||||
{
|
||||
if (!config_.required) {
|
||||
installStatus(LeaseStatus{.mode = Mode::Active,
|
||||
.reason = "licensing-not-required"});
|
||||
return;
|
||||
}
|
||||
deviceId_ = loadOrCreateDeviceId();
|
||||
if (deviceId_.empty()) {
|
||||
installFailure("cannot create protected device identity");
|
||||
return;
|
||||
}
|
||||
|
||||
if (std::string_view{ECHOION_LICENSE_ROOT_KEY_ID}.empty() ||
|
||||
std::string_view{ECHOION_LICENSE_ROOT_PUBLIC_KEY}.empty()) {
|
||||
installFailure("release has no pinned licensing root key");
|
||||
} else if (auto added =
|
||||
addPublicKey(rootKeys_, ECHOION_LICENSE_ROOT_KEY_ID,
|
||||
ECHOION_LICENSE_ROOT_PUBLIC_KEY);
|
||||
!added) {
|
||||
installFailure(added.error().message());
|
||||
}
|
||||
|
||||
#ifdef ECHOION_ALLOW_DEVELOPMENT_LICENSE_KEYS
|
||||
if (config_.developmentMode) {
|
||||
for (const auto& key : config_.developmentKeys) {
|
||||
if (auto added = addPublicKey(rootKeys_, key.id, key.ed25519);
|
||||
!added) {
|
||||
Void::Log::warn("Licensing", "{}", added.error().message());
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
if (rootKeys_.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto cachedPath =
|
||||
stateDirectory_ / "licensing" / "lease-bundle.json";
|
||||
if (auto cached = readFile(cachedPath)) {
|
||||
auto parsed = Void::Json::parse(*cached);
|
||||
const auto cachedChallenge = parsed && parsed->is_object()
|
||||
? parsed->get_str("challenge")
|
||||
: std::string{};
|
||||
if (auto verified = verifyBundle(*cached, cachedChallenge);
|
||||
verified) {
|
||||
installStatus(std::move(*verified));
|
||||
} else {
|
||||
installFailure("cached lease rejected: " +
|
||||
verified.error().message());
|
||||
}
|
||||
}
|
||||
|
||||
refreshNow();
|
||||
refreshThread_ =
|
||||
std::jthread([this](std::stop_token stopToken) { run(stopToken); });
|
||||
}
|
||||
|
||||
void LicenseManager::shutdown()
|
||||
{
|
||||
if (refreshThread_.joinable()) {
|
||||
refreshThread_.request_stop();
|
||||
refreshThread_.join();
|
||||
}
|
||||
}
|
||||
|
||||
void LicenseManager::refreshNow()
|
||||
{
|
||||
if (!config_.required || rootKeys_.empty() || network_ == nullptr ||
|
||||
config_.serviceUrl.empty()) {
|
||||
return;
|
||||
}
|
||||
auto challenge = Void::Security::random_token();
|
||||
if (!challenge) {
|
||||
installFailure(challenge.error().message());
|
||||
return;
|
||||
}
|
||||
const char* token = std::getenv(config_.activationTokenEnv.c_str());
|
||||
if (token == nullptr || std::string_view{token}.empty()) {
|
||||
installFailure("activation token environment variable is missing");
|
||||
return;
|
||||
}
|
||||
const auto request = Void::Json::object(
|
||||
{{"schemaVersion", 1},
|
||||
{"productId", config_.productId},
|
||||
{"productVersion", ECHOION_PRODUCT_VERSION},
|
||||
{"deviceId", deviceId_},
|
||||
{"buildSignature", ECHOION_BUILD_SIGNATURE},
|
||||
{"challenge", *challenge},
|
||||
{"minimumSequence", static_cast<double>(minimumSequence_)}});
|
||||
const auto body = Void::Json::serialize(request);
|
||||
const std::vector<Void::Net::Header> headers = {
|
||||
{"Content-Type", "application/json"},
|
||||
{"Accept", "application/json"},
|
||||
{"Authorization", std::string{"Bearer "} + token}};
|
||||
auto response = network_->postVerifiedTls(endpoint(config_.serviceUrl),
|
||||
body, headers);
|
||||
if (!response || !response->ok()) {
|
||||
const auto reason =
|
||||
response ? std::format("license server returned HTTP {}",
|
||||
response->status)
|
||||
: "license server request failed";
|
||||
const bool authoritative =
|
||||
response && isAuthoritativeDenial(response->status);
|
||||
if (authoritative) {
|
||||
std::error_code ignored;
|
||||
std::filesystem::remove(stateDirectory_ / "licensing" /
|
||||
"lease-bundle.json",
|
||||
ignored);
|
||||
}
|
||||
installFailure(reason, !authoritative);
|
||||
return;
|
||||
}
|
||||
auto verified = verifyBundle(response->body, *challenge);
|
||||
if (!verified) {
|
||||
installFailure(verified.error().message());
|
||||
return;
|
||||
}
|
||||
if (!writePrivateFile(stateDirectory_ / "licensing" /
|
||||
"lease-bundle.json",
|
||||
response->body)) {
|
||||
Void::Log::warn("Licensing", "{}",
|
||||
"could not persist refreshed license bundle");
|
||||
}
|
||||
installStatus(std::move(*verified));
|
||||
}
|
||||
|
||||
bool LicenseManager::canOperate() const noexcept
|
||||
{
|
||||
if (!operational_.load(std::memory_order_acquire)) {
|
||||
return false;
|
||||
}
|
||||
const auto until =
|
||||
operationalUntilUnix_.load(std::memory_order_acquire);
|
||||
const auto now =
|
||||
std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch())
|
||||
.count();
|
||||
return now <= until;
|
||||
}
|
||||
|
||||
LeaseStatus LicenseManager::status() const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
return status_;
|
||||
}
|
||||
|
||||
std::string LicenseManager::deviceId() const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
return deviceId_;
|
||||
}
|
||||
|
||||
Void::Result::Result<LeaseStatus>
|
||||
LicenseManager::verifyBundle(std::string_view bundle,
|
||||
std::string_view expectedChallenge)
|
||||
{
|
||||
auto root = Void::Json::parse(bundle);
|
||||
if (!root || !root->is_object() ||
|
||||
root->get_num("schemaVersion") != 1 ||
|
||||
root->get_str("challenge") != expectedChallenge) {
|
||||
return Void::Result::fail("Licensing: invalid response binding");
|
||||
}
|
||||
const auto* keysetValue = root->find("keyset");
|
||||
const auto* leaseValue = root->find("lease");
|
||||
const auto* revocationsValue = root->find("revocations");
|
||||
if (keysetValue == nullptr || leaseValue == nullptr ||
|
||||
revocationsValue == nullptr || !keysetValue->is_object() ||
|
||||
!leaseValue->is_object() || !revocationsValue->is_object()) {
|
||||
return Void::Result::fail("Licensing: incomplete server response");
|
||||
}
|
||||
const auto now = std::chrono::system_clock::now();
|
||||
auto keys =
|
||||
verifyKeyset(Void::Json::serialize(*keysetValue), rootKeys_, now);
|
||||
if (!keys) {
|
||||
return std::unexpected{keys.error()};
|
||||
}
|
||||
return verifyLease(
|
||||
Void::Json::serialize(*leaseValue),
|
||||
Void::Json::serialize(*revocationsValue), *keys,
|
||||
LeaseContext{.productId = config_.productId,
|
||||
.productVersion = ECHOION_PRODUCT_VERSION,
|
||||
.deviceId = deviceId_,
|
||||
.buildSignature = ECHOION_BUILD_SIGNATURE,
|
||||
.challenge = std::string{expectedChallenge},
|
||||
.now = now,
|
||||
.maximumLeaseLifetime = config_.maximumLeaseLifetime,
|
||||
.minimumSequence = minimumSequence_});
|
||||
}
|
||||
|
||||
std::string LicenseManager::loadOrCreateDeviceId()
|
||||
{
|
||||
const auto path = stateDirectory_ / "licensing" / "device.id";
|
||||
if (auto existing = readFile(path);
|
||||
existing && !existing->empty() && existing->size() <= 128) {
|
||||
return *existing;
|
||||
}
|
||||
auto created = Void::Security::random_token();
|
||||
if (!created || !writePrivateFile(path, *created)) {
|
||||
return {};
|
||||
}
|
||||
return *created;
|
||||
}
|
||||
|
||||
void LicenseManager::installStatus(LeaseStatus status)
|
||||
{
|
||||
const bool active = status.mode == Mode::Active;
|
||||
std::int64_t operationalUntil = 0;
|
||||
if (active) {
|
||||
operationalUntil =
|
||||
!config_.required
|
||||
? std::numeric_limits<std::int64_t>::max()
|
||||
: std::chrono::duration_cast<std::chrono::seconds>(
|
||||
status.expiresAt.time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
minimumSequence_ = std::max(minimumSequence_, status.sequence);
|
||||
status_ = std::move(status);
|
||||
}
|
||||
operationalUntilUnix_.store(operationalUntil,
|
||||
std::memory_order_release);
|
||||
operational_.store(active, std::memory_order_release);
|
||||
Void::Log::info("Licensing", "{}",
|
||||
active ? "license active" : "update-only mode");
|
||||
}
|
||||
|
||||
void LicenseManager::installFailure(std::string reason,
|
||||
bool retainValidLease)
|
||||
{
|
||||
const auto current = status();
|
||||
if (retainValidLease && current.mode == Mode::Active &&
|
||||
current.expiresAt > std::chrono::system_clock::now()) {
|
||||
Void::Log::warn("Licensing", "{}", std::move(reason));
|
||||
return;
|
||||
}
|
||||
installStatus(
|
||||
LeaseStatus{.mode = Mode::UpdateOnly, .reason = std::move(reason)});
|
||||
}
|
||||
|
||||
void LicenseManager::run(std::stop_token stopToken)
|
||||
{
|
||||
while (!stopToken.stop_requested()) {
|
||||
const auto delay =
|
||||
canOperate() ? config_.refreshInterval : config_.retryInterval;
|
||||
for (auto waited = std::chrono::milliseconds{0};
|
||||
waited < delay && !stopToken.stop_requested();
|
||||
waited += std::chrono::seconds{1}) {
|
||||
std::this_thread::sleep_for(
|
||||
std::min(std::chrono::milliseconds{1000}, delay - waited));
|
||||
}
|
||||
if (!stopToken.stop_requested()) {
|
||||
refreshNow();
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace Echoion::Core::Licensing
|
||||
@@ -0,0 +1,277 @@
|
||||
#include "echoion/core/licensing/LicenseVerifier.hpp"
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Text/Base64.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cctype>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <ranges>
|
||||
|
||||
namespace Echoion::Core::Licensing
|
||||
{
|
||||
namespace
|
||||
{
|
||||
using Clock = std::chrono::system_clock;
|
||||
using Result = Void::Result::Result<void>;
|
||||
|
||||
[[nodiscard]] bool validKeyId(std::string_view value)
|
||||
{
|
||||
return !value.empty() && value.size() <= 128 &&
|
||||
std::ranges::all_of(value, [](unsigned char character) {
|
||||
return std::isalnum(character) != 0 ||
|
||||
character == '.' || character == '_' ||
|
||||
character == '-';
|
||||
});
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Void::Json::Value>
|
||||
parseObject(std::string_view json, std::string_view name)
|
||||
{
|
||||
auto parsed = Void::Json::parse(json);
|
||||
if (!parsed || !parsed->is_object()) {
|
||||
return Void::Result::fail(std::string{name} +
|
||||
" payload is not a JSON object");
|
||||
}
|
||||
return std::move(*parsed);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::string>
|
||||
requiredString(const Void::Json::Value& value, std::string_view key,
|
||||
std::size_t maximum = 512)
|
||||
{
|
||||
const auto* field = value.find(key);
|
||||
if (field == nullptr || !field->is_string() ||
|
||||
field->as_string().empty() ||
|
||||
field->as_string().size() > maximum) {
|
||||
return Void::Result::fail("Licensing: invalid field " +
|
||||
std::string{key});
|
||||
}
|
||||
return field->as_string();
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::uint64_t>
|
||||
requiredUnsigned(const Void::Json::Value& value,
|
||||
std::string_view key)
|
||||
{
|
||||
const auto* field = value.find(key);
|
||||
if (field == nullptr || !field->is_number()) {
|
||||
return Void::Result::fail("Licensing: invalid field " +
|
||||
std::string{key});
|
||||
}
|
||||
const double number = field->as_number();
|
||||
if (!std::isfinite(number) || number < 0.0 ||
|
||||
std::trunc(number) != number ||
|
||||
number > static_cast<double>(
|
||||
std::numeric_limits<std::uint64_t>::max())) {
|
||||
return Void::Result::fail("Licensing: invalid field " +
|
||||
std::string{key});
|
||||
}
|
||||
return static_cast<std::uint64_t>(number);
|
||||
}
|
||||
|
||||
[[nodiscard]] Clock::time_point unixTime(std::uint64_t seconds)
|
||||
{
|
||||
return Clock::time_point{std::chrono::seconds{seconds}};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool stringArrayContains(const Void::Json::Value& object,
|
||||
std::string_view key,
|
||||
std::string_view needle)
|
||||
{
|
||||
const auto* value = object.find(key);
|
||||
if (value == nullptr || !value->is_array()) {
|
||||
return false;
|
||||
}
|
||||
return std::ranges::any_of(
|
||||
value->as_array(), [&](const auto& item) {
|
||||
return item.is_string() && item.as_string() == needle;
|
||||
});
|
||||
}
|
||||
|
||||
[[nodiscard]] std::vector<std::string>
|
||||
stringArray(const Void::Json::Value& object, std::string_view key)
|
||||
{
|
||||
std::vector<std::string> output;
|
||||
const auto* value = object.find(key);
|
||||
if (value == nullptr || !value->is_array()) {
|
||||
return output;
|
||||
}
|
||||
for (const auto& item : value->as_array()) {
|
||||
if (item.is_string() && item.as_string().size() <= 256) {
|
||||
output.push_back(item.as_string());
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<void> addPublicKey(Void::Update::Keyring& keyring,
|
||||
std::string_view keyId,
|
||||
std::string_view encodedKey)
|
||||
{
|
||||
if (!validKeyId(keyId)) {
|
||||
return Void::Result::fail("Licensing: invalid public key id");
|
||||
}
|
||||
auto decoded = Void::Encoding::Base64::decode_url(encodedKey);
|
||||
if (!decoded) {
|
||||
decoded = Void::Encoding::Base64::decode(encodedKey);
|
||||
}
|
||||
if (!decoded || decoded->size() != Void::Crypto::Ed25519PublicKeySize) {
|
||||
return Void::Result::fail("Licensing: invalid Ed25519 public key");
|
||||
}
|
||||
Void::Update::Ed25519PublicKey key{};
|
||||
std::memcpy(key.data(), decoded->data(), decoded->size());
|
||||
keyring.insert_or_assign(std::string{keyId}, key);
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<Void::Update::Keyring>
|
||||
verifyKeyset(std::string_view envelopeJson,
|
||||
const Void::Update::Keyring& rootKeys,
|
||||
Clock::time_point now)
|
||||
{
|
||||
Void::Update::VerificationPolicy policy;
|
||||
policy.now = now;
|
||||
policy.maxEnvelopeBytes = 256 * 1024;
|
||||
policy.maxPayloadBytes = 192 * 1024;
|
||||
auto verified =
|
||||
Void::Update::verifyEnvelope(envelopeJson, rootKeys, policy);
|
||||
if (!verified) {
|
||||
return std::unexpected{verified.error()};
|
||||
}
|
||||
auto document = parseObject(verified->signedPayload, "Keyset");
|
||||
if (!document) {
|
||||
return std::unexpected{document.error()};
|
||||
}
|
||||
if (auto name = requiredString(*document, "document");
|
||||
!name || *name != "echoion-license-keyset") {
|
||||
return Void::Result::fail("Licensing: wrong keyset document");
|
||||
}
|
||||
auto generatedAt = requiredUnsigned(*document, "generatedAt");
|
||||
auto expiresAt = requiredUnsigned(*document, "expiresAt");
|
||||
const auto* keys = document->find("keys");
|
||||
if (!generatedAt || !expiresAt || keys == nullptr ||
|
||||
!keys->is_array() || keys->as_array().size() > 64 ||
|
||||
unixTime(*generatedAt) > now + std::chrono::minutes(5) ||
|
||||
unixTime(*expiresAt) <= now) {
|
||||
return Void::Result::fail("Licensing: invalid or expired keyset");
|
||||
}
|
||||
|
||||
auto output = rootKeys;
|
||||
for (const auto& item : keys->as_array()) {
|
||||
if (!item.is_object() || item.get_bool("revoked", false)) {
|
||||
continue;
|
||||
}
|
||||
auto id = requiredString(item, "id", 256);
|
||||
auto key = requiredString(item, "ed25519", 256);
|
||||
auto notBefore = requiredUnsigned(item, "notBefore");
|
||||
auto notAfter = requiredUnsigned(item, "notAfter");
|
||||
if (!id || !key || !notBefore || !notAfter ||
|
||||
unixTime(*notBefore) > now || unixTime(*notAfter) <= now) {
|
||||
continue;
|
||||
}
|
||||
if (auto added = addPublicKey(output, *id, *key); !added) {
|
||||
return std::unexpected{added.error()};
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
Void::Result::Result<LeaseStatus>
|
||||
verifyLease(std::string_view leaseEnvelopeJson,
|
||||
std::string_view revocationEnvelopeJson,
|
||||
const Void::Update::Keyring& leaseKeys,
|
||||
const LeaseContext& context)
|
||||
{
|
||||
Void::Update::VerificationPolicy policy;
|
||||
policy.now = context.now;
|
||||
policy.maxEnvelopeBytes = 512 * 1024;
|
||||
policy.maxPayloadBytes = 384 * 1024;
|
||||
auto leaseEnvelope =
|
||||
Void::Update::verifyEnvelope(leaseEnvelopeJson, leaseKeys, policy);
|
||||
if (!leaseEnvelope) {
|
||||
return std::unexpected{leaseEnvelope.error()};
|
||||
}
|
||||
auto revocationEnvelope = Void::Update::verifyEnvelope(
|
||||
revocationEnvelopeJson, leaseKeys, policy);
|
||||
if (!revocationEnvelope) {
|
||||
return std::unexpected{revocationEnvelope.error()};
|
||||
}
|
||||
auto lease = parseObject(leaseEnvelope->signedPayload, "Lease");
|
||||
auto revocations =
|
||||
parseObject(revocationEnvelope->signedPayload, "Revocation");
|
||||
if (!lease || !revocations) {
|
||||
return Void::Result::fail("Licensing: malformed signed payload");
|
||||
}
|
||||
|
||||
auto leaseDocument = requiredString(*lease, "document");
|
||||
auto revocationDocument = requiredString(*revocations, "document");
|
||||
auto licenseId = requiredString(*lease, "licenseId");
|
||||
auto accountId = requiredString(*lease, "accountId");
|
||||
auto deviceId = requiredString(*lease, "deviceId");
|
||||
auto productId = requiredString(*lease, "productId");
|
||||
auto productVersion = requiredString(*lease, "productVersion");
|
||||
auto buildSignature = requiredString(*lease, "buildSignature");
|
||||
auto challenge = requiredString(*lease, "challenge");
|
||||
auto status = requiredString(*lease, "status");
|
||||
auto issuedAt = requiredUnsigned(*lease, "issuedAt");
|
||||
auto refreshAfter = requiredUnsigned(*lease, "refreshAfter");
|
||||
auto expiresAt = requiredUnsigned(*lease, "expiresAt");
|
||||
auto sequence = requiredUnsigned(*lease, "sequence");
|
||||
auto revocationSequence =
|
||||
requiredUnsigned(*lease, "revocationSequence");
|
||||
auto snapshotSequence = requiredUnsigned(*revocations, "sequence");
|
||||
auto snapshotExpiresAt = requiredUnsigned(*revocations, "expiresAt");
|
||||
if (!leaseDocument || *leaseDocument != "echoion-license-lease" ||
|
||||
!revocationDocument ||
|
||||
*revocationDocument != "echoion-license-revocations" ||
|
||||
!licenseId || !accountId || !deviceId || !productId ||
|
||||
!productVersion || !buildSignature || !challenge || !status ||
|
||||
!issuedAt || !refreshAfter || !expiresAt || !sequence ||
|
||||
!revocationSequence || !snapshotSequence || !snapshotExpiresAt) {
|
||||
return Void::Result::fail("Licensing: incomplete signed decision");
|
||||
}
|
||||
|
||||
const auto issued = unixTime(*issuedAt);
|
||||
const auto refresh = unixTime(*refreshAfter);
|
||||
const auto expiry = unixTime(*expiresAt);
|
||||
if (*status != "active" || *productId != context.productId ||
|
||||
*productVersion != context.productVersion ||
|
||||
*deviceId != context.deviceId ||
|
||||
*buildSignature != context.buildSignature ||
|
||||
*challenge != context.challenge ||
|
||||
*sequence < context.minimumSequence ||
|
||||
*snapshotSequence < *revocationSequence ||
|
||||
issued > context.now + std::chrono::minutes(5) ||
|
||||
expiry <= context.now || expiry <= issued ||
|
||||
expiry - issued > context.maximumLeaseLifetime ||
|
||||
refresh < issued || refresh > expiry ||
|
||||
unixTime(*snapshotExpiresAt) <= context.now) {
|
||||
return Void::Result::fail("Licensing: lease is inactive, "
|
||||
"mismatched, expired, or replayed");
|
||||
}
|
||||
|
||||
if (stringArrayContains(*revocations, "licenseIds", *licenseId) ||
|
||||
stringArrayContains(*revocations, "accountIds", *accountId) ||
|
||||
stringArrayContains(*revocations, "deviceIds", *deviceId) ||
|
||||
stringArrayContains(*revocations, "buildSignatures",
|
||||
*buildSignature) ||
|
||||
stringArrayContains(*revocations, "productVersions",
|
||||
*productVersion) ||
|
||||
stringArrayContains(*revocations, "keyIds", leaseEnvelope->keyId)) {
|
||||
return Void::Result::fail("Licensing: entitlement was revoked");
|
||||
}
|
||||
|
||||
return LeaseStatus{.mode = Mode::Active,
|
||||
.reason = "active",
|
||||
.licenseId = std::move(*licenseId),
|
||||
.sequence = *sequence,
|
||||
.refreshAfter = refresh,
|
||||
.expiresAt = expiry,
|
||||
.entitlements = stringArray(*lease, "entitlements")};
|
||||
}
|
||||
} // namespace Echoion::Core::Licensing
|
||||
@@ -1,3 +1,4 @@
|
||||
#include "echoion/core/playback/GaplessHandoff.hpp"
|
||||
#include "echoion/core/playback/PlaybackEngine.hpp"
|
||||
|
||||
#include <Void/Log/Log.hpp>
|
||||
@@ -198,8 +199,8 @@ namespace Echoion::Core
|
||||
}
|
||||
while (ring_.size() < MAX_BUFFER_SHORTS &&
|
||||
current_.decoder->getNextChunk(incomingChunk_)) {
|
||||
ring_.append(std::span<const short>(
|
||||
incomingChunk_.data(), incomingChunk_.size()));
|
||||
ring_.append(std::span<const short>(incomingChunk_.data(),
|
||||
incomingChunk_.size()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,8 +216,8 @@ namespace Echoion::Core
|
||||
current_.state == DecoderSlot::State::Active &&
|
||||
next_.state == DecoderSlot::State::Warming &&
|
||||
!host_.repeatEnabled()) {
|
||||
const auto duration = std::chrono::milliseconds(
|
||||
currentDurationMs_.load());
|
||||
const auto duration =
|
||||
std::chrono::milliseconds(currentDurationMs_.load());
|
||||
const auto position = clock_.position();
|
||||
if (duration.count() > 0 &&
|
||||
duration - position <=
|
||||
@@ -256,8 +257,26 @@ namespace Echoion::Core
|
||||
emitChunk(true);
|
||||
} else if (current_.state == DecoderSlot::State::Active &&
|
||||
current_.decoder->isFinished()) {
|
||||
// Flush the tail (shorter than one chunk), zero-padded.
|
||||
// When the warmed decoder already has enough PCM, concatenate
|
||||
// the outgoing tail and incoming head in this same 20ms device
|
||||
// frame. This avoids the zero-padding discontinuity that used
|
||||
// to sound like a short "psst" between tracks.
|
||||
if (!ring_.empty()) {
|
||||
const auto incomingReady =
|
||||
next_.state == DecoderSlot::State::Warming &&
|
||||
next_.decoder &&
|
||||
PlaybackDetail::canFillDeviceFrame(
|
||||
ring_.size(), next_.decoder->queuedSamples(),
|
||||
SHORTS_PER_CHUNK);
|
||||
if (incomingReady) {
|
||||
handleTrackEnd();
|
||||
while (ring_.size() < SHORTS_PER_CHUNK &&
|
||||
current_.state == DecoderSlot::State::Active &&
|
||||
current_.decoder->getNextChunk(incomingChunk_)) {
|
||||
ring_.append(std::span<const short>(
|
||||
incomingChunk_.data(), incomingChunk_.size()));
|
||||
}
|
||||
}
|
||||
emitChunk(true);
|
||||
} else {
|
||||
handleTrackEnd();
|
||||
@@ -465,8 +484,7 @@ namespace Echoion::Core
|
||||
|
||||
void PlaybackEngine::handle(CmdSeek&& cmd)
|
||||
{
|
||||
if (current_.state != DecoderSlot::State::Active ||
|
||||
!current_.decoder) {
|
||||
if (current_.state != DecoderSlot::State::Active || !current_.decoder) {
|
||||
return;
|
||||
}
|
||||
ring_.clear();
|
||||
@@ -478,9 +496,9 @@ namespace Echoion::Core
|
||||
if (result) {
|
||||
clock_.seekTo(cmd.position);
|
||||
} else {
|
||||
Void::Log::error("PlaybackEngine", "{}",
|
||||
std::format("Seek failed: {}",
|
||||
result.error().message));
|
||||
Void::Log::error(
|
||||
"PlaybackEngine", "{}",
|
||||
std::format("Seek failed: {}", result.error().message));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -548,10 +566,9 @@ namespace Echoion::Core
|
||||
return;
|
||||
}
|
||||
const auto position = clock_.position();
|
||||
const bool nearEnd =
|
||||
duration <= PREFETCH_THRESHOLD
|
||||
? position >= std::chrono::seconds(2)
|
||||
: (duration - position) <= PREFETCH_THRESHOLD;
|
||||
const bool nearEnd = duration <= PREFETCH_THRESHOLD
|
||||
? position >= std::chrono::seconds(2)
|
||||
: (duration - position) <= PREFETCH_THRESHOLD;
|
||||
if (!nearEnd) {
|
||||
return;
|
||||
}
|
||||
@@ -571,10 +588,10 @@ namespace Echoion::Core
|
||||
std::async(std::launch::async, [this, entryCopy]() {
|
||||
return host_.resolveStream(entryCopy, false);
|
||||
});
|
||||
Void::Log::info(
|
||||
"PlaybackEngine", "{}",
|
||||
std::format("Prefetching next track: {} - {}",
|
||||
entryCopy.track.title, entryCopy.track.artist));
|
||||
Void::Log::info("PlaybackEngine", "{}",
|
||||
std::format("Prefetching next track: {} - {}",
|
||||
entryCopy.track.title,
|
||||
entryCopy.track.artist));
|
||||
}
|
||||
|
||||
void PlaybackEngine::pollNextResolve()
|
||||
@@ -591,10 +608,9 @@ namespace Echoion::Core
|
||||
|
||||
auto result = slot->resolveFuture.get();
|
||||
if (!result) {
|
||||
Void::Log::warn(
|
||||
"PlaybackEngine", "{}",
|
||||
std::format("Stream resolve failed: {}",
|
||||
result.error().message));
|
||||
Void::Log::warn("PlaybackEngine", "{}",
|
||||
std::format("Stream resolve failed: {}",
|
||||
result.error().message));
|
||||
host_.onPlaybackError(result.error(), slot->entry);
|
||||
const bool wasCurrent = (slot == ¤t_);
|
||||
slot->closeAndReset();
|
||||
@@ -683,15 +699,14 @@ namespace Echoion::Core
|
||||
// handoff).
|
||||
current_.closeAndReset();
|
||||
std::swap(current_, next_);
|
||||
if (!current_.entry ||
|
||||
!host_.takeNextTrack(current_.entry->queueId)) {
|
||||
if (!current_.entry || !host_.takeNextTrack(current_.entry->queueId)) {
|
||||
// Queue changed under the peek: put the tail back as normal
|
||||
// output and advance conventionally later.
|
||||
Void::Log::info("PlaybackEngine", "{}",
|
||||
"Queue changed during crossfade; aborting fade");
|
||||
current_.closeAndReset();
|
||||
ring_.append(std::span<const short>(fadeTail_.data(),
|
||||
fadeTail_.size()));
|
||||
ring_.append(
|
||||
std::span<const short>(fadeTail_.data(), fadeTail_.size()));
|
||||
clearFade();
|
||||
if (!beginNextFromQueue()) {
|
||||
playing_ = false;
|
||||
@@ -892,9 +907,8 @@ namespace Echoion::Core
|
||||
if (hasIncoming) {
|
||||
incoming = static_cast<float>(ring_[i]);
|
||||
if (rampOut > 0) {
|
||||
incoming *= 1.0f -
|
||||
static_cast<float>(i) /
|
||||
static_cast<float>(rampOut);
|
||||
incoming *= 1.0f - static_cast<float>(i) /
|
||||
static_cast<float>(rampOut);
|
||||
} else if (i < rampIn) {
|
||||
incoming *= static_cast<float>(i) /
|
||||
static_cast<float>(rampIn);
|
||||
@@ -910,8 +924,8 @@ namespace Echoion::Core
|
||||
fadeTailPos_ < fadeTail_.size()
|
||||
? static_cast<float>(fadeTail_[fadeTailPos_])
|
||||
: 0.0f;
|
||||
mixed = incoming * std::sin(theta) +
|
||||
tail * std::cos(theta);
|
||||
mixed =
|
||||
incoming * std::sin(theta) + tail * std::cos(theta);
|
||||
if (fadeTailPos_ < fadeTail_.size()) {
|
||||
++fadeTailPos_;
|
||||
}
|
||||
@@ -921,13 +935,12 @@ namespace Echoion::Core
|
||||
// complete so the incoming finishes its rise (or,
|
||||
// with both sources dry, the fade ends and normal
|
||||
// starvation handling resumes).
|
||||
if (hasIncoming ||
|
||||
fadeTailPos_ >= fadeTail_.size()) {
|
||||
if (hasIncoming || fadeTailPos_ >= fadeTail_.size()) {
|
||||
++fadeEnvPos_;
|
||||
}
|
||||
}
|
||||
outChunk_[i] = static_cast<short>(std::clamp(
|
||||
static_cast<int>(mixed), -32768, 32767));
|
||||
outChunk_[i] = static_cast<short>(
|
||||
std::clamp(static_cast<int>(mixed), -32768, 32767));
|
||||
}
|
||||
fadeIncomingStarved_ = starved;
|
||||
if (fadeEnvPos_ >= fadeTail_.size()) {
|
||||
@@ -948,14 +961,13 @@ namespace Echoion::Core
|
||||
for (size_t i = 0; i < filled; ++i) {
|
||||
const int sample = static_cast<int>(
|
||||
static_cast<float>(outChunk_[i]) * gain);
|
||||
outChunk_[i] = static_cast<short>(
|
||||
std::clamp(sample, -32768, 32767));
|
||||
outChunk_[i] =
|
||||
static_cast<short>(std::clamp(sample, -32768, 32767));
|
||||
}
|
||||
}
|
||||
|
||||
// Zero-pad the remainder of a short chunk.
|
||||
std::fill(outChunk_.begin() +
|
||||
static_cast<std::ptrdiff_t>(filled),
|
||||
std::fill(outChunk_.begin() + static_cast<std::ptrdiff_t>(filled),
|
||||
outChunk_.end(), 0);
|
||||
ring_.popFront(consumed);
|
||||
} else {
|
||||
@@ -990,12 +1002,11 @@ namespace Echoion::Core
|
||||
: agcMeanSquare_ + alpha * (chunkMs - agcMeanSquare_);
|
||||
|
||||
const float rmsDb = static_cast<float>(
|
||||
10.0 * std::log10(agcMeanSquare_ /
|
||||
(32768.0 * 32768.0)));
|
||||
10.0 * std::log10(agcMeanSquare_ / (32768.0 * 32768.0)));
|
||||
const float wantedDb = normalizeTargetDb_.load() - rmsDb;
|
||||
|
||||
// Slew: fast attack (turn down), slow release (turn up).
|
||||
constexpr float kAttackPerChunk = 0.4f; // 20 dB/s
|
||||
constexpr float kAttackPerChunk = 0.4f; // 20 dB/s
|
||||
constexpr float kReleasePerChunk = 0.06f; // 3 dB/s
|
||||
const float delta = wantedDb - agcGainDb_;
|
||||
if (delta < 0.0f) {
|
||||
@@ -1011,8 +1022,7 @@ namespace Echoion::Core
|
||||
|
||||
void PlaybackEngine::positionTick()
|
||||
{
|
||||
if (current_.state != DecoderSlot::State::Active ||
|
||||
!current_.entry) {
|
||||
if (current_.state != DecoderSlot::State::Active || !current_.entry) {
|
||||
return;
|
||||
}
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
@@ -1020,9 +1030,9 @@ namespace Echoion::Core
|
||||
return;
|
||||
}
|
||||
lastPositionTick_ = now;
|
||||
host_.onPositionTick(*current_.entry, clock_.position(),
|
||||
std::chrono::milliseconds(
|
||||
currentDurationMs_.load()));
|
||||
host_.onPositionTick(
|
||||
*current_.entry, clock_.position(),
|
||||
std::chrono::milliseconds(currentDurationMs_.load()));
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -38,6 +38,14 @@ namespace Echoion::Core
|
||||
}
|
||||
}
|
||||
|
||||
void SourceRouter::addSource(std::shared_ptr<ITrackSource> source)
|
||||
{
|
||||
if (!source) return;
|
||||
std::lock_guard lock(mutex_);
|
||||
allSources_.push_back(source);
|
||||
chain_.push_back(SourceState{.source = std::move(source)});
|
||||
}
|
||||
|
||||
void SourceRouter::setOrder(const std::vector<std::string>& order)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
@@ -73,13 +81,13 @@ namespace Echoion::Core
|
||||
hedgeDelay_ = std::max(delay, std::chrono::milliseconds(0));
|
||||
}
|
||||
|
||||
std::vector<SourceRouter::SourceState*>
|
||||
SourceRouter::candidatesFor(const std::string& query, bool needSearch)
|
||||
std::vector<std::shared_ptr<ITrackSource>>
|
||||
SourceRouter::candidatesFor(const std::string& query, bool needSearch)
|
||||
{
|
||||
// Callers hold mutex_.
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
std::vector<SourceState*> eligible;
|
||||
std::vector<SourceState*> coolingDown;
|
||||
std::vector<std::shared_ptr<ITrackSource>> eligible;
|
||||
std::vector<std::shared_ptr<ITrackSource>> coolingDown;
|
||||
|
||||
for (auto& state : chain_) {
|
||||
if (needSearch && !state.source->supportsSearch()) {
|
||||
@@ -89,10 +97,10 @@ namespace Echoion::Core
|
||||
continue;
|
||||
}
|
||||
if (state.cooldownUntil > now) {
|
||||
coolingDown.push_back(&state);
|
||||
coolingDown.push_back(state.source);
|
||||
continue;
|
||||
}
|
||||
eligible.push_back(&state);
|
||||
eligible.push_back(state.source);
|
||||
}
|
||||
// A source on cooldown is still tried when nothing else matched —
|
||||
// better a likely-failing attempt than an immediate error.
|
||||
@@ -102,13 +110,17 @@ namespace Echoion::Core
|
||||
return eligible;
|
||||
}
|
||||
|
||||
void SourceRouter::reportFailure(SourceState& state)
|
||||
void SourceRouter::reportFailure(const std::shared_ptr<ITrackSource>& source)
|
||||
{
|
||||
state.cooldownUntil = std::chrono::steady_clock::now() + cooldown_;
|
||||
auto state = std::ranges::find_if(chain_, [&](const SourceState& candidate) {
|
||||
return candidate.source == source;
|
||||
});
|
||||
if (state == chain_.end()) return;
|
||||
state->cooldownUntil = std::chrono::steady_clock::now() + cooldown_;
|
||||
Void::Log::info(
|
||||
"SourceRouter", "{}",
|
||||
std::format("Source '{}' on cooldown for {}s",
|
||||
state.source->name(), cooldown_.count() / 1000));
|
||||
source->name(), cooldown_.count() / 1000));
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult> SourceRouter::search(std::string_view query)
|
||||
@@ -119,17 +131,17 @@ namespace Echoion::Core
|
||||
|
||||
Api::Error lastError{Api::ErrorCode::ServiceUnavailable,
|
||||
"No source can search"};
|
||||
for (auto* state : candidates) {
|
||||
if (!state->source->isAvailable()) {
|
||||
for (const auto& source : candidates) {
|
||||
if (!source->isAvailable()) {
|
||||
continue;
|
||||
}
|
||||
auto result = state->source->search(query);
|
||||
auto result = source->search(query);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
lastError = result.error();
|
||||
std::lock_guard<std::mutex> relock(mutex_);
|
||||
reportFailure(*state);
|
||||
reportFailure(source);
|
||||
}
|
||||
return std::unexpected(lastError);
|
||||
}
|
||||
@@ -142,21 +154,21 @@ namespace Echoion::Core
|
||||
|
||||
Api::Error lastError{Api::ErrorCode::NotFound,
|
||||
"No source can resolve this query"};
|
||||
for (auto* state : candidates) {
|
||||
if (!state->source->isAvailable()) {
|
||||
for (const auto& source : candidates) {
|
||||
if (!source->isAvailable()) {
|
||||
continue;
|
||||
}
|
||||
Void::Log::debug(
|
||||
"SourceRouter", "{}",
|
||||
std::format("Resolving '{}' via {}", query,
|
||||
state->source->name()));
|
||||
auto result = state->source->resolve(query);
|
||||
source->name()));
|
||||
auto result = source->resolve(query);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
lastError = result.error();
|
||||
std::lock_guard<std::mutex> relock(mutex_);
|
||||
reportFailure(*state);
|
||||
reportFailure(source);
|
||||
}
|
||||
return std::unexpected(lastError);
|
||||
}
|
||||
@@ -191,10 +203,10 @@ namespace Echoion::Core
|
||||
const auto hedgeDelay = hedgeDelay_;
|
||||
lock.unlock();
|
||||
|
||||
std::vector<SourceState*> eligible;
|
||||
for (auto* state : candidates) {
|
||||
if (state->source->isAvailable()) {
|
||||
eligible.push_back(state);
|
||||
std::vector<std::shared_ptr<ITrackSource>> eligible;
|
||||
for (const auto& source : candidates) {
|
||||
if (source->isAvailable()) {
|
||||
eligible.push_back(source);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -253,7 +265,7 @@ namespace Echoion::Core
|
||||
}).detach();
|
||||
};
|
||||
|
||||
launch(eligible[0]->source, 0);
|
||||
launch(eligible[0], 0);
|
||||
int launched = 1;
|
||||
std::optional<Api::Result<StreamHandle>> winner;
|
||||
std::array<bool, 2> failed{false, false};
|
||||
@@ -267,7 +279,7 @@ namespace Echoion::Core
|
||||
if (!state->winner) {
|
||||
// A is slow or already failed: bring in B.
|
||||
lk.unlock();
|
||||
launch(eligible[1]->source, 1);
|
||||
launch(eligible[1], 1);
|
||||
launched = 2;
|
||||
lk.lock();
|
||||
state->cv.wait(lk, [&] {
|
||||
@@ -291,11 +303,9 @@ namespace Echoion::Core
|
||||
"SourceRouter", "{}",
|
||||
std::format(
|
||||
"Source '{}' failed stream for '{}': {}",
|
||||
eligible[static_cast<size_t>(slot)]
|
||||
->source->name(),
|
||||
eligible[static_cast<size_t>(slot)]->name(),
|
||||
cacheKey, lastError.message));
|
||||
reportFailure(
|
||||
*eligible[static_cast<size_t>(slot)]);
|
||||
reportFailure(eligible[static_cast<size_t>(slot)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -308,8 +318,8 @@ namespace Echoion::Core
|
||||
// Sequential pass over the remaining candidates (or all of them
|
||||
// when hedging is disabled).
|
||||
for (; index < eligible.size(); ++index) {
|
||||
auto* state = eligible[index];
|
||||
auto handle = state->source->getStream(track);
|
||||
const auto& source = eligible[index];
|
||||
auto handle = source->getStream(track);
|
||||
if (handle) {
|
||||
return finish(std::move(handle));
|
||||
}
|
||||
@@ -317,10 +327,10 @@ namespace Echoion::Core
|
||||
Void::Log::warn(
|
||||
"SourceRouter", "{}",
|
||||
std::format("Source '{}' failed stream for '{}': {}",
|
||||
state->source->name(), cacheKey,
|
||||
source->name(), cacheKey,
|
||||
handle.error().message));
|
||||
std::lock_guard<std::mutex> relock(mutex_);
|
||||
reportFailure(*state);
|
||||
reportFailure(source);
|
||||
}
|
||||
return std::unexpected(lastError);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Text/Url.hpp>
|
||||
#include <format>
|
||||
#include <openssl/evp.h>
|
||||
#include <regex>
|
||||
@@ -62,27 +63,6 @@ namespace Echoion::Core
|
||||
return std::regex_search(url, playlist);
|
||||
}
|
||||
|
||||
std::string percentEncode(std::string_view text)
|
||||
{
|
||||
static constexpr char hex[] = "0123456789ABCDEF";
|
||||
std::string out;
|
||||
out.reserve(text.size() * 3);
|
||||
for (unsigned char c : text) {
|
||||
const bool unreserved = (c >= 'A' && c <= 'Z') ||
|
||||
(c >= 'a' && c <= 'z') ||
|
||||
(c >= '0' && c <= '9') || c == '-' ||
|
||||
c == '_' || c == '.' || c == '~';
|
||||
if (unreserved) {
|
||||
out.push_back(static_cast<char>(c));
|
||||
} else {
|
||||
out.push_back('%');
|
||||
out.push_back(hex[c >> 4]);
|
||||
out.push_back(hex[c & 0xF]);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string str(const Void::Json::Value& v, const char* key)
|
||||
{
|
||||
const auto* f = v.find(key);
|
||||
@@ -198,8 +178,8 @@ namespace Echoion::Core
|
||||
"Yandex Music not configured");
|
||||
}
|
||||
|
||||
auto body =
|
||||
apiGet("/search?type=track&page=0&text=" + percentEncode(query));
|
||||
auto body = apiGet("/search?type=track&page=0&text=" +
|
||||
Void::Encoding::Url::encode(query));
|
||||
if (!body) {
|
||||
return std::unexpected(body.error());
|
||||
}
|
||||
|
||||
@@ -101,33 +101,12 @@ namespace Echoion::Core
|
||||
|
||||
uint32_t StateSerializer::extractVersion(const std::string& jsonStr)
|
||||
{
|
||||
// Quick extraction without full parse
|
||||
// Look for "version": N pattern
|
||||
size_t pos = jsonStr.find("\"version\"");
|
||||
if (pos != std::string::npos) {
|
||||
pos = jsonStr.find(':', pos);
|
||||
if (pos != std::string::npos) {
|
||||
// Skip whitespace
|
||||
pos++;
|
||||
while (pos < jsonStr.size() &&
|
||||
std::isspace(static_cast<unsigned char>(jsonStr[pos]))) {
|
||||
pos++;
|
||||
}
|
||||
// Parse number
|
||||
if (pos < jsonStr.size() &&
|
||||
std::isdigit(static_cast<unsigned char>(jsonStr[pos]))) {
|
||||
try {
|
||||
return static_cast<uint32_t>(
|
||||
std::stoul(jsonStr.substr(pos)));
|
||||
} catch (const std::exception&) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Default to 0 (unknown/legacy)
|
||||
return 0;
|
||||
// Read only the root field. A textual search can accidentally select a
|
||||
// nested schema version (for example an extension plugin's state).
|
||||
auto parsed = Void::Json::parse(jsonStr);
|
||||
if (!parsed || !parsed->is_object()) return 0;
|
||||
const auto version = parsed->get_num("version", 0);
|
||||
return version > 0 ? static_cast<uint32_t>(version) : 0;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,180 @@
|
||||
#include "echoion/core/ConfigLoader.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace
|
||||
{
|
||||
int failures = 0;
|
||||
|
||||
void expect(bool condition, std::string_view message)
|
||||
{
|
||||
if (!condition) {
|
||||
std::cerr << "FAILED: " << message << '\n';
|
||||
++failures;
|
||||
}
|
||||
}
|
||||
|
||||
void expectShortening(std::string_view name, std::string_view json,
|
||||
bool enabled, std::string_view provider)
|
||||
{
|
||||
const auto config = Echoion::Core::ConfigLoader::loadFromJson(json);
|
||||
if (!config) {
|
||||
std::cerr << "FAILED: " << name
|
||||
<< " did not parse: " << config.error().message << '\n';
|
||||
++failures;
|
||||
return;
|
||||
}
|
||||
|
||||
expect(config->urlShortening.enabled == enabled,
|
||||
std::string{name} + " enabled state");
|
||||
expect(config->urlShortening.provider == provider,
|
||||
std::string{name} + " provider");
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
using Echoion::Core::ConfigLoader;
|
||||
|
||||
const auto defaults = ConfigLoader::createDefaultConfig();
|
||||
expect(!defaults.urlShortening.enabled,
|
||||
"generated defaults keep URL shortening disabled");
|
||||
expect(defaults.logging.fileName == "echoion.log" &&
|
||||
defaults.logging.maxFiles == 10,
|
||||
"generated defaults configure bounded rolling logs");
|
||||
|
||||
const auto logging = ConfigLoader::loadFromJson(R"({
|
||||
"logging": {
|
||||
"level": "verbose",
|
||||
"fileName": "../outside.log",
|
||||
"maxFileSizeBytes": 1,
|
||||
"maxFiles": 0,
|
||||
"format": "xml",
|
||||
"pattern": "",
|
||||
"mode": "parallel",
|
||||
"queueCapacity": 1,
|
||||
"overflowPolicy": "discard"
|
||||
}
|
||||
})");
|
||||
expect(logging.has_value(), "logging configuration parses");
|
||||
if (logging) {
|
||||
expect(logging->logging.level == "debug",
|
||||
"invalid log level is normalized");
|
||||
expect(logging->logging.fileName == "echoion.log",
|
||||
"log file cannot escape the state log directory");
|
||||
expect(logging->logging.maxFileSizeBytes == 64 * 1024,
|
||||
"log size is clamped to a safe minimum");
|
||||
expect(logging->logging.maxFiles == 1,
|
||||
"at least one rolled log is retained");
|
||||
expect(logging->logging.format == "pattern" &&
|
||||
!logging->logging.pattern.empty(),
|
||||
"invalid formatter configuration is normalized");
|
||||
expect(logging->logging.mode == "async" &&
|
||||
logging->logging.queueCapacity == 16 &&
|
||||
logging->logging.overflowPolicy == "block",
|
||||
"invalid dispatch configuration is normalized");
|
||||
}
|
||||
const auto parentLog =
|
||||
ConfigLoader::loadFromJson(R"({"logging":{"fileName":".."}})");
|
||||
expect(parentLog && parentLog->logging.fileName == "echoion.log",
|
||||
"parent-directory logging filename is normalized");
|
||||
|
||||
const auto licensing = ConfigLoader::loadFromJson(R"({
|
||||
"licensing": {
|
||||
"required": true,
|
||||
"serviceUrl": "http://downgrade.example",
|
||||
"productId": "",
|
||||
"activationTokenEnv": "",
|
||||
"refreshInterval": "1m",
|
||||
"retryInterval": "1s",
|
||||
"maximumLeaseLifetime": "72h"
|
||||
}
|
||||
})");
|
||||
expect(licensing.has_value(), "licensing configuration parses");
|
||||
if (licensing) {
|
||||
expect(licensing->licensing.required,
|
||||
"licensing required flag is preserved");
|
||||
expect(licensing->licensing.serviceUrl.empty(),
|
||||
"licensing service cannot downgrade from HTTPS");
|
||||
expect(licensing->licensing.productId == "echoion" &&
|
||||
licensing->licensing.activationTokenEnv ==
|
||||
"ECHOION_LICENSE_TOKEN",
|
||||
"licensing identifiers receive safe defaults");
|
||||
expect(licensing->licensing.refreshInterval ==
|
||||
std::chrono::minutes(15) &&
|
||||
licensing->licensing.retryInterval ==
|
||||
std::chrono::seconds(30) &&
|
||||
licensing->licensing.maximumLeaseLifetime ==
|
||||
std::chrono::hours(24),
|
||||
"licensing cadence and offline lease are bounded");
|
||||
}
|
||||
|
||||
expectShortening("legacy disabled",
|
||||
R"({
|
||||
"youtube": {"enableUrlShortening": false},
|
||||
"web": {"publicUrl": "https://bot.example"}
|
||||
})",
|
||||
false, "url-shortener-internal");
|
||||
|
||||
const auto legacyEnabled = ConfigLoader::loadFromJson(R"({
|
||||
"youtube": {"enableUrlShortening": true},
|
||||
"web": {"publicUrl": "https://bot.example"}
|
||||
})");
|
||||
if (!legacyEnabled) {
|
||||
std::cerr << "FAILED: legacy enabled did not parse: "
|
||||
<< legacyEnabled.error().message << '\n';
|
||||
++failures;
|
||||
} else {
|
||||
expect(legacyEnabled->urlShortening.enabled,
|
||||
"legacy enabled flag migrates through JSON updates");
|
||||
expect(legacyEnabled->urlShortening.provider ==
|
||||
"url-shortener-internal",
|
||||
"legacy migration selects internal provider");
|
||||
expect(legacyEnabled->urlShortening.sources.size() == 1 &&
|
||||
legacyEnabled->urlShortening.sources.front() == "youtube",
|
||||
"legacy migration limits shortening to YouTube");
|
||||
}
|
||||
|
||||
expectShortening("explicit section wins",
|
||||
R"({
|
||||
"youtube": {"enableUrlShortening": true},
|
||||
"urlShortening": {
|
||||
"enabled": false,
|
||||
"provider": "url-shortener-internal"
|
||||
},
|
||||
"web": {"publicUrl": "https://bot.example"}
|
||||
})",
|
||||
false, "url-shortener-internal");
|
||||
|
||||
expectShortening("internal provider without public URL",
|
||||
R"({
|
||||
"urlShortening": {
|
||||
"enabled": true,
|
||||
"provider": "url-shortener-internal"
|
||||
}
|
||||
})",
|
||||
false, "url-shortener-internal");
|
||||
|
||||
expectShortening("internal provider with public URL",
|
||||
R"({
|
||||
"urlShortening": {
|
||||
"enabled": true,
|
||||
"provider": "url-shortener-internal"
|
||||
},
|
||||
"web": {"publicUrl": "https://bot.example"}
|
||||
})",
|
||||
true, "url-shortener-internal");
|
||||
|
||||
expectShortening("external provider without public URL",
|
||||
R"({
|
||||
"urlShortening": {
|
||||
"enabled": true,
|
||||
"provider": "url-shortener-external"
|
||||
}
|
||||
})",
|
||||
true, "url-shortener-external");
|
||||
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#include "echoion/core/state/StateSerializer.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
int main()
|
||||
{
|
||||
Echoion::Core::StateV1 state;
|
||||
state.extensionPlugins.push_back({.name = "example", .json = "{\"v\":1}",
|
||||
.version = 3});
|
||||
|
||||
auto blob = Echoion::Core::StateSerializer::serialize(state);
|
||||
std::string json{blob.data.begin(), blob.data.end()};
|
||||
// State written by the removed experimental rooms build must remain safe to
|
||||
// load during a hot reload. Void reflection intentionally ignores unknown
|
||||
// root fields, so the obsolete payload is discarded rather than rejected.
|
||||
json.insert(json.rfind('}'),
|
||||
R"(,"listeningRooms":[{"name":"legacy","subscribers":["uid"]}])");
|
||||
blob.data.assign(json.begin(), json.end());
|
||||
|
||||
const auto restored = Echoion::Core::StateSerializer::deserialize(blob);
|
||||
if (!restored) {
|
||||
std::cerr << "extension state did not deserialize: "
|
||||
<< restored.error().message << '\n';
|
||||
return 1;
|
||||
}
|
||||
if (restored->extensionPlugins.size() != 1 ||
|
||||
restored->extensionPlugins.front().name != "example" ||
|
||||
restored->extensionPlugins.front().version != 3) {
|
||||
std::cerr << "extension plugin state did not round-trip\n";
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#include "echoion/core/playback/GaplessHandoff.hpp"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
namespace
|
||||
{
|
||||
int failures = 0;
|
||||
|
||||
void expect(bool condition, const char* message)
|
||||
{
|
||||
if (!condition) {
|
||||
std::cerr << "FAILED: " << message << '\n';
|
||||
++failures;
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
using Echoion::Core::PlaybackDetail::canFillDeviceFrame;
|
||||
|
||||
expect(canFillDeviceFrame(300, 700, 1000),
|
||||
"outgoing tail and incoming head can exactly fill a frame");
|
||||
expect(canFillDeviceFrame(300, 900, 1000),
|
||||
"extra incoming PCM is retained for the next frame");
|
||||
expect(!canFillDeviceFrame(300, 699, 1000),
|
||||
"handoff waits rather than padding when incoming PCM is short");
|
||||
expect(!canFillDeviceFrame(0, 1000, 1000),
|
||||
"an empty outgoing tail is a normal track-end path");
|
||||
expect(!canFillDeviceFrame(1000, 1000, 1000),
|
||||
"a complete outgoing frame does not need a boundary join");
|
||||
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
#include "echoion/core/licensing/LicenseVerifier.hpp"
|
||||
|
||||
#include <Void/Text/Base64.hpp>
|
||||
|
||||
#include <openssl/evp.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace
|
||||
{
|
||||
constexpr std::string_view seedHex =
|
||||
"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60";
|
||||
constexpr std::string_view publicHex =
|
||||
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a";
|
||||
|
||||
std::string hex(std::string_view value)
|
||||
{
|
||||
std::string output;
|
||||
output.reserve(value.size() / 2);
|
||||
for (std::size_t index = 0; index < value.size(); index += 2) {
|
||||
output.push_back(static_cast<char>(
|
||||
std::stoi(std::string{value.substr(index, 2)}, nullptr, 16)));
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
std::string sign(std::string_view message)
|
||||
{
|
||||
using Key = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
|
||||
using Context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
|
||||
const auto seed = hex(seedHex);
|
||||
Key key{EVP_PKEY_new_raw_private_key(
|
||||
EVP_PKEY_ED25519, nullptr,
|
||||
reinterpret_cast<const unsigned char*>(seed.data()),
|
||||
seed.size()),
|
||||
&EVP_PKEY_free};
|
||||
Context context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
|
||||
if (!key || !context ||
|
||||
EVP_DigestSignInit(context.get(), nullptr, nullptr, nullptr,
|
||||
key.get()) != 1) {
|
||||
return {};
|
||||
}
|
||||
std::string signature(Void::Crypto::Ed25519SignatureSize, '\0');
|
||||
std::size_t size = signature.size();
|
||||
if (EVP_DigestSign(
|
||||
context.get(),
|
||||
reinterpret_cast<unsigned char*>(signature.data()), &size,
|
||||
reinterpret_cast<const unsigned char*>(message.data()),
|
||||
message.size()) != 1) {
|
||||
return {};
|
||||
}
|
||||
signature.resize(size);
|
||||
return signature;
|
||||
}
|
||||
|
||||
std::string envelope(std::string_view payload)
|
||||
{
|
||||
return std::format(
|
||||
"{{\n \"schemaVersion\": 3,\n \"keyId\": \"test-key\",\n"
|
||||
" \"document\": {},\n \"signedPayload\": \"{}\",\n"
|
||||
" \"signature\": \"{}\"\n}}",
|
||||
payload, Void::Encoding::Base64::encode_url(payload),
|
||||
Void::Encoding::Base64::encode_url(sign(payload)));
|
||||
}
|
||||
|
||||
int failures = 0;
|
||||
void expect(bool condition, std::string_view message)
|
||||
{
|
||||
if (!condition) {
|
||||
std::cerr << "FAILED: " << message << '\n';
|
||||
++failures;
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
using namespace Echoion::Core::Licensing;
|
||||
const auto publicKey = hex(publicHex);
|
||||
const auto encodedKey = Void::Encoding::Base64::encode_url(publicKey);
|
||||
Void::Update::Keyring keys;
|
||||
expect(addPublicKey(keys, "test-key", encodedKey).has_value(),
|
||||
"base64url public key is accepted");
|
||||
expect(!addPublicKey(keys, "broken\nkey", encodedKey),
|
||||
"public key ids reject whitespace and control characters");
|
||||
|
||||
constexpr std::uint64_t now = 1'800'000'000;
|
||||
const auto lease = std::format(
|
||||
R"({{"document":"echoion-license-lease","licenseId":"lic-1","accountId":"account-1","deviceId":"device-1","productId":"echoion","productVersion":"2.0.0","buildSignature":"build-1","challenge":"challenge-1","status":"active","issuedAt":{},"refreshAfter":{},"expiresAt":{},"sequence":42,"revocationSequence":8,"entitlements":["runtime","updates"]}})",
|
||||
now - 10, now + 3600, now + 7200);
|
||||
const auto revocations = std::format(
|
||||
R"({{"document":"echoion-license-revocations","sequence":8,"generatedAt":{},"expiresAt":{},"licenseIds":[],"accountIds":[],"deviceIds":[],"buildSignatures":[],"keyIds":[]}})",
|
||||
now - 10, now + 7200);
|
||||
LeaseContext context{
|
||||
.productId = "echoion",
|
||||
.productVersion = "2.0.0",
|
||||
.deviceId = "device-1",
|
||||
.buildSignature = "build-1",
|
||||
.challenge = "challenge-1",
|
||||
.now = std::chrono::system_clock::time_point{std::chrono::seconds{now}},
|
||||
.maximumLeaseLifetime = std::chrono::hours(24),
|
||||
.minimumSequence = 41};
|
||||
|
||||
auto active =
|
||||
verifyLease(envelope(lease), envelope(revocations), keys, context);
|
||||
expect(active && active->mode == Mode::Active && active->sequence == 42,
|
||||
"matching signed lease enables normal operation");
|
||||
|
||||
context.buildSignature = "pirated-build";
|
||||
expect(!verifyLease(envelope(lease), envelope(revocations), keys, context),
|
||||
"build signature mismatch fails closed");
|
||||
context.buildSignature = "build-1";
|
||||
|
||||
const auto revoked = std::format(
|
||||
R"({{"document":"echoion-license-revocations","sequence":9,"generatedAt":{},"expiresAt":{},"licenseIds":["lic-1"],"accountIds":[],"deviceIds":[],"buildSignatures":[],"keyIds":[]}})",
|
||||
now - 10, now + 7200);
|
||||
expect(!verifyLease(envelope(lease), envelope(revoked), keys, context),
|
||||
"specific license revocation fails closed");
|
||||
|
||||
context.minimumSequence = 43;
|
||||
expect(!verifyLease(envelope(lease), envelope(revocations), keys, context),
|
||||
"older lease sequence cannot be replayed");
|
||||
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
#include "echoion/core/state/StateSerializer.hpp"
|
||||
#include "echoion/core/ListeningRoomName.hpp"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
int main()
|
||||
{
|
||||
const auto normalized = Echoion::Core::validateListeningRoomName(" Focus Room ");
|
||||
if (!normalized || *normalized != "Focus Room" ||
|
||||
Echoion::Core::canonicalListeningRoomName(*normalized) != "focus room" ||
|
||||
Echoion::Core::validateListeningRoomName("\n\t") ||
|
||||
Echoion::Core::validateListeningRoomName(std::string(49, 'x'))) {
|
||||
std::cerr << "listening-room name validation failed\n";
|
||||
return 1;
|
||||
}
|
||||
Echoion::Core::StateV1 state;
|
||||
Echoion::Core::StateV1::ListeningRoomState room;
|
||||
room.name = "focus";
|
||||
room.ownerId = 17;
|
||||
room.members = {17, 23};
|
||||
room.playback.isPlaying = true;
|
||||
room.playback.position = std::chrono::milliseconds{42000};
|
||||
room.playbackPositionMs = 42000;
|
||||
room.autoplay = true;
|
||||
state.listeningRooms.push_back(std::move(room));
|
||||
|
||||
const auto blob = Echoion::Core::StateSerializer::serialize(state);
|
||||
const auto restored = Echoion::Core::StateSerializer::deserialize(blob);
|
||||
if (!restored || restored->listeningRooms.size() != 1) {
|
||||
std::cerr << "listening-room state did not round-trip\n";
|
||||
return 1;
|
||||
}
|
||||
const auto& actual = restored->listeningRooms.front();
|
||||
if (actual.name != "focus" || actual.ownerId != 17 ||
|
||||
actual.members != std::vector<uint64_t>({17, 23}) ||
|
||||
actual.playbackPositionMs != 42000 || !actual.autoplay) {
|
||||
std::cerr << "restored listening-room fields differ\n";
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
#include "echoion/core/LogRotation.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <string_view>
|
||||
|
||||
namespace
|
||||
{
|
||||
int failures = 0;
|
||||
|
||||
void expect(bool condition, std::string_view message)
|
||||
{
|
||||
if (!condition) {
|
||||
std::cerr << "FAILED: " << message << '\n';
|
||||
++failures;
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t archiveCount(const std::filesystem::path& history)
|
||||
{
|
||||
std::size_t count = 0;
|
||||
std::error_code error;
|
||||
for (std::filesystem::directory_iterator iterator(history, error), end;
|
||||
!error && iterator != end; iterator.increment(error)) {
|
||||
if (iterator->is_regular_file()) {
|
||||
++count;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
const auto root =
|
||||
std::filesystem::temp_directory_path() / "echoion-log-rotation-test";
|
||||
std::error_code error;
|
||||
std::filesystem::remove_all(root, error);
|
||||
std::filesystem::create_directories(root, error);
|
||||
const auto active = root / "echoion.log";
|
||||
|
||||
{
|
||||
std::ofstream file(active);
|
||||
file << "first run\n";
|
||||
}
|
||||
error = Echoion::Core::rotateLogOnStartup(active, 2);
|
||||
expect(!error, "first startup rotation succeeds");
|
||||
expect(!std::filesystem::exists(active),
|
||||
"startup rotation leaves no old active file");
|
||||
expect(archiveCount(root / "history") == 1, "first run is archived");
|
||||
|
||||
for (int run = 0; run < 3; ++run) {
|
||||
{
|
||||
std::ofstream file(active);
|
||||
file << "run " << run << '\n';
|
||||
}
|
||||
error = Echoion::Core::rotateLogOnStartup(active, 2);
|
||||
expect(!error, "subsequent startup rotation succeeds");
|
||||
}
|
||||
expect(archiveCount(root / "history") == 2,
|
||||
"startup rotation prunes to configured history count");
|
||||
|
||||
{
|
||||
std::ofstream file(active);
|
||||
}
|
||||
error = Echoion::Core::rotateLogOnStartup(active, 2);
|
||||
expect(!error && !std::filesystem::exists(active),
|
||||
"empty active file is removed instead of archived");
|
||||
|
||||
std::filesystem::remove_all(root / "history", error);
|
||||
{
|
||||
std::ofstream invalidHistory(root / "history");
|
||||
invalidHistory << "not a directory\n";
|
||||
}
|
||||
error = Echoion::Core::rotateLogOnStartup(active, 2);
|
||||
expect(error == std::errc::invalid_argument,
|
||||
"non-directory history path was accepted");
|
||||
|
||||
std::filesystem::remove_all(root, error);
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
#include "PluginCompatibility.hpp"
|
||||
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Runner.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <string_view>
|
||||
|
||||
namespace
|
||||
{
|
||||
echoion_string_view_v1 view(const std::string_view value)
|
||||
{
|
||||
return {.data = value.data(), .size = value.size()};
|
||||
}
|
||||
|
||||
echoion_status_v1 create(const echoion_module_host_v1*,
|
||||
echoion_module_instance_v1*)
|
||||
{
|
||||
return ECHOION_STATUS_OK_V1;
|
||||
}
|
||||
void destroy(echoion_module_instance_v1) {}
|
||||
echoion_status_v1 activate(echoion_module_instance_v1)
|
||||
{
|
||||
return ECHOION_STATUS_OK_V1;
|
||||
}
|
||||
echoion_status_v1 quiesce(echoion_module_instance_v1, std::int64_t)
|
||||
{
|
||||
return ECHOION_STATUS_OK_V1;
|
||||
}
|
||||
echoion_status_v1 checkpoint(echoion_module_instance_v1,
|
||||
echoion_write_bytes_fn_v1, void*)
|
||||
{
|
||||
return ECHOION_STATUS_OK_V1;
|
||||
}
|
||||
echoion_status_v1 restore(echoion_module_instance_v1, echoion_bytes_view_v1)
|
||||
{
|
||||
return ECHOION_STATUS_OK_V1;
|
||||
}
|
||||
echoion_status_v1 readiness(echoion_module_instance_v1,
|
||||
echoion_module_readiness_v1*)
|
||||
{
|
||||
return ECHOION_STATUS_OK_V1;
|
||||
}
|
||||
echoion_status_v1 deactivate(echoion_module_instance_v1)
|
||||
{
|
||||
return ECHOION_STATUS_OK_V1;
|
||||
}
|
||||
|
||||
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 = {},
|
||||
};
|
||||
|
||||
std::array<echoion_module_dependency_v1, 2>
|
||||
dependencies(const std::string_view apiHash,
|
||||
const std::string_view coreHash)
|
||||
{
|
||||
return {{
|
||||
{
|
||||
.struct_size = sizeof(echoion_module_dependency_v1),
|
||||
.component_id = view("EchoionApi"),
|
||||
.version_range = view(">=2.0.0 <3.0.0"),
|
||||
.abi_hash = view(apiHash),
|
||||
.optional = 0,
|
||||
.reserved_bytes = {},
|
||||
},
|
||||
{
|
||||
.struct_size = sizeof(echoion_module_dependency_v1),
|
||||
.component_id = view("EchoionCore"),
|
||||
.version_range = view(">=2.0.0 <3.0.0"),
|
||||
.abi_hash = view(coreHash),
|
||||
.optional = 0,
|
||||
.reserved_bytes = {},
|
||||
},
|
||||
}};
|
||||
}
|
||||
|
||||
echoion_module_descriptor_v1
|
||||
descriptor(const std::array<echoion_module_dependency_v1, 2>& values)
|
||||
{
|
||||
return {
|
||||
.struct_size = sizeof(echoion_module_descriptor_v1),
|
||||
.abi_version = ECHOION_MODULE_ABI_VERSION,
|
||||
.component_id = view("EchoionPluginExample"),
|
||||
.version_major = 2,
|
||||
.version_minor = 0,
|
||||
.version_patch = 0,
|
||||
.version_prerelease = {},
|
||||
.abi_hash = view("sha256:example"),
|
||||
.dependencies = values.data(),
|
||||
.dependency_count = values.size(),
|
||||
.activation_policy = ECHOION_ACTIVATION_RELOADABLE_V1,
|
||||
.api = &api,
|
||||
.reserved = {},
|
||||
};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test compatible_v2_extension_descriptor_is_accepted()
|
||||
{
|
||||
const auto values = dependencies(
|
||||
"sha256:"
|
||||
"d50293d345a97e52f9844088bdd42277f566bc815a21b7636d3e053f06c6c113",
|
||||
"sha256:"
|
||||
"9cb668e2a502dcfe02d145ed63635d63619732d77ff5749685834382705e8d21");
|
||||
const auto candidate = descriptor(values);
|
||||
const auto result =
|
||||
Echoion::Core::Detail::checkExtensionDescriptor(&candidate);
|
||||
Void::Testing::expect(result.compatible);
|
||||
}
|
||||
|
||||
Void::Testing::Test legacy_or_mismatched_extension_descriptor_is_rejected()
|
||||
{
|
||||
const auto values = dependencies("sha256:old-api", "sha256:old-core");
|
||||
auto candidate = descriptor(values);
|
||||
auto result = Echoion::Core::Detail::checkExtensionDescriptor(&candidate);
|
||||
Void::Testing::expect(!result.compatible);
|
||||
|
||||
candidate.version_major = 1;
|
||||
result = Echoion::Core::Detail::checkExtensionDescriptor(&candidate);
|
||||
Void::Testing::expect(!result.compatible);
|
||||
|
||||
Void::Testing::expect(
|
||||
!Echoion::Core::Detail::checkExtensionDescriptor(nullptr).compatible);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
return Void::Testing::Runner::instance().main(argc, argv);
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
#include "echoion/core/TeamSpeakDirectoryService.hpp"
|
||||
#include "echoion/core/detail/RpcValidation.hpp"
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
|
||||
#include <cassert>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
class FakePlugin final : public Echoion::Api::IPluginInterface
|
||||
{
|
||||
public:
|
||||
|
||||
Echoion::Api::Result<void> initialize() override { return {}; }
|
||||
Echoion::Api::Result<void> shutdown() override { return {}; }
|
||||
Echoion::Api::Result<std::vector<Echoion::Api::ClientInfo>>
|
||||
getClients() override
|
||||
{
|
||||
return clients;
|
||||
}
|
||||
Echoion::Api::Result<std::optional<Echoion::Api::ClientInfo>>
|
||||
getClient(uint64_t id) override
|
||||
{
|
||||
for (const auto& client : clients) {
|
||||
if (client.id == id) {
|
||||
return client;
|
||||
}
|
||||
}
|
||||
return std::optional<Echoion::Api::ClientInfo>{};
|
||||
}
|
||||
Echoion::Api::Result<void> moveClient(uint64_t, uint64_t) override
|
||||
{
|
||||
return {};
|
||||
}
|
||||
Echoion::Api::Result<void> kickClient(uint64_t,
|
||||
const std::string&) override
|
||||
{
|
||||
return {};
|
||||
}
|
||||
Echoion::Api::Result<std::vector<Echoion::Api::ChannelInfo>>
|
||||
getChannels() const override
|
||||
{
|
||||
return channels;
|
||||
}
|
||||
Echoion::Api::Result<std::optional<Echoion::Api::ChannelInfo>>
|
||||
getChannel(uint64_t id) const override
|
||||
{
|
||||
for (const auto& channel : channels) {
|
||||
if (channel.id == id) {
|
||||
return channel;
|
||||
}
|
||||
}
|
||||
return std::optional<Echoion::Api::ChannelInfo>{};
|
||||
}
|
||||
Echoion::Api::Result<void>
|
||||
sendTextMessage(uint64_t, const std::string&) override
|
||||
{
|
||||
return {};
|
||||
}
|
||||
Echoion::Api::Result<void>
|
||||
sendChannelMessage(uint64_t, const std::string&) override
|
||||
{
|
||||
return {};
|
||||
}
|
||||
Echoion::Api::Result<void>
|
||||
sendServerMessage(const std::string&) override
|
||||
{
|
||||
return {};
|
||||
}
|
||||
Echoion::Api::Result<void>
|
||||
sendAudioData(const std::span<const short>&) override
|
||||
{
|
||||
return {};
|
||||
}
|
||||
Echoion::Api::Result<void>
|
||||
setWhisperList(const std::vector<uint64_t>&) override
|
||||
{
|
||||
return {};
|
||||
}
|
||||
Echoion::Api::Result<void>
|
||||
connectToServer(const Echoion::Api::ServerConfig&) override
|
||||
{
|
||||
return {};
|
||||
}
|
||||
Echoion::Api::Result<void> disconnectFromServer() override
|
||||
{
|
||||
return {};
|
||||
}
|
||||
bool isConnected() const override { return connected; }
|
||||
Echoion::Api::Result<void> reconnect() override { return {}; }
|
||||
void registerEventCallback(
|
||||
const Echoion::Api::EventCallback&) override
|
||||
{
|
||||
}
|
||||
void unregisterEventCallback(
|
||||
const Echoion::Api::EventCallback&) override
|
||||
{
|
||||
}
|
||||
Echoion::Api::Result<Echoion::Api::ServerInfo>
|
||||
getTeamSpeakServerInfo() override
|
||||
{
|
||||
return Echoion::Api::ServerInfo{
|
||||
.name = "Fixture", .welcomeMessage = "", .maxClients = 64};
|
||||
}
|
||||
|
||||
std::vector<Echoion::Api::ClientInfo> clients;
|
||||
std::vector<Echoion::Api::ChannelInfo> channels;
|
||||
bool connected = true;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
using Echoion::Api::ChannelInfo;
|
||||
using Echoion::Api::ClientInfo;
|
||||
using Echoion::Core::TeamSpeakDirectoryService;
|
||||
|
||||
const auto validId = Void::Json::parse(R"({"id":42})");
|
||||
const auto fractionalId = Void::Json::parse(R"({"id":1.5})");
|
||||
const auto negativeId = Void::Json::parse(R"({"id":-1})");
|
||||
const auto overflowingId =
|
||||
Void::Json::parse(R"({"id":18446744073709551616})");
|
||||
const auto enormousId = Void::Json::parse(R"({"id":1e100})");
|
||||
assert(validId && Echoion::Core::Detail::uintField(*validId, "id") == 42);
|
||||
assert(fractionalId &&
|
||||
!Echoion::Core::Detail::uintField(*fractionalId, "id"));
|
||||
assert(negativeId && !Echoion::Core::Detail::uintField(*negativeId, "id"));
|
||||
assert(overflowingId &&
|
||||
!Echoion::Core::Detail::uintField(*overflowingId, "id"));
|
||||
assert(enormousId && !Echoion::Core::Detail::uintField(*enormousId, "id"));
|
||||
|
||||
auto plugin = std::make_shared<FakePlugin>();
|
||||
plugin->channels = {
|
||||
ChannelInfo{.id = 2, .name = "Second", .parentId = 0, .order = 1},
|
||||
ChannelInfo{.id = 1, .name = "First", .parentId = 0, .order = 0},
|
||||
ChannelInfo{.id = 3, .name = "Child", .parentId = 1, .order = 0}};
|
||||
plugin->clients = {ClientInfo{.id = 10,
|
||||
.databaseId = 110,
|
||||
.nickname = "Visible",
|
||||
.uniqueIdentifier = "secret-uid",
|
||||
.channelId = 1,
|
||||
.isTalking = true,
|
||||
.serverGroups = {7}},
|
||||
ClientInfo{.id = 11,
|
||||
.databaseId = std::nullopt,
|
||||
.nickname = "Query Client",
|
||||
.uniqueIdentifier = "query-secret",
|
||||
.channelId = 1,
|
||||
.isQuery = true,
|
||||
.serverGroups = {}}};
|
||||
|
||||
TeamSpeakDirectoryService service;
|
||||
service.setPluginInterface(plugin);
|
||||
const auto publicJson = Void::Json::serialize(service.publicJson());
|
||||
assert(publicJson.contains("Visible"));
|
||||
assert(publicJson.find("First") < publicJson.find("Second"));
|
||||
assert(!publicJson.contains("Query Client"));
|
||||
assert(!publicJson.contains("secret-uid"));
|
||||
assert(!publicJson.contains("databaseId"));
|
||||
assert(!publicJson.contains("groups"));
|
||||
|
||||
const auto adminJson = Void::Json::serialize(service.adminJson());
|
||||
assert(adminJson.contains("secret-uid"));
|
||||
assert(adminJson.contains("databaseId"));
|
||||
assert(!adminJson.contains("Query Client"));
|
||||
|
||||
const auto ordered = TeamSpeakDirectoryService::orderChannels(
|
||||
{ChannelInfo{.id = 2, .name = "", .parentId = std::nullopt, .order = 1},
|
||||
ChannelInfo{.id = 1, .name = "", .parentId = std::nullopt, .order = 0},
|
||||
ChannelInfo{
|
||||
.id = 9, .name = "", .parentId = std::nullopt, .order = 99}});
|
||||
assert(ordered.size() == 3);
|
||||
assert(ordered[0].id == 1);
|
||||
assert(ordered[1].id == 2);
|
||||
assert(ordered[2].id == 9);
|
||||
|
||||
plugin->connected = false;
|
||||
plugin->clients.clear();
|
||||
plugin->channels.clear();
|
||||
service.handleEvent(Echoion::Api::PluginEventType::ChannelUpdated);
|
||||
const auto disconnected = Void::Json::serialize(service.publicJson());
|
||||
assert(disconnected.contains("\"connected\":false"));
|
||||
assert(!disconnected.contains("Visible"));
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
#include "echoion/core/UrlShortener.hpp"
|
||||
#include "echoion/core/YouTubeClient.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace
|
||||
{
|
||||
class FakeShortener final : public Void::ShortUrl::IShortener
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] std::uint32_t
|
||||
service_version() const noexcept override
|
||||
{
|
||||
return version;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view provider_id() const noexcept override
|
||||
{
|
||||
return "test-shortener";
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::ShortUrl::Health health() const override
|
||||
{
|
||||
if (throwFromHealth) {
|
||||
throw std::runtime_error("health failure");
|
||||
}
|
||||
return {.status = healthStatus, .message = {}};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::ShortUrl::ShortenResult
|
||||
shorten(const Void::ShortUrl::ShortenRequest& request) override
|
||||
{
|
||||
++calls;
|
||||
lastTarget = request.target_url;
|
||||
return {
|
||||
.short_url = "https://sho.rt/abc",
|
||||
.key = "abc",
|
||||
.expires_at_unix_seconds = 0,
|
||||
.error = {},
|
||||
};
|
||||
}
|
||||
|
||||
std::uint32_t version{Void::ShortUrl::kServiceVersion};
|
||||
Void::ShortUrl::HealthStatus healthStatus{
|
||||
Void::ShortUrl::HealthStatus::healthy};
|
||||
bool throwFromHealth{false};
|
||||
int calls{0};
|
||||
std::string lastTarget;
|
||||
};
|
||||
|
||||
bool expect(bool condition, std::string_view message)
|
||||
{
|
||||
if (!condition) {
|
||||
std::cerr << message << '\n';
|
||||
}
|
||||
return condition;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
using Echoion::Api::ErrorCode;
|
||||
using Echoion::Api::TrackSource;
|
||||
using Echoion::Core::UrlShortener;
|
||||
using Echoion::Core::YouTubeClient;
|
||||
|
||||
if (!expect(
|
||||
YouTubeClient::isYouTubeUrl(
|
||||
"https://www.youtube.com/watch?v=dQw4w9WgXcQ") &&
|
||||
YouTubeClient::isYouTubeUrl("https://youtu.be/dQw4w9WgXcQ") &&
|
||||
!YouTubeClient::isYouTubeUrl(
|
||||
"https://youtube.com.evil.test/watch?v=dQw4w9WgXcQ") &&
|
||||
!YouTubeClient::isYouTubeUrl(
|
||||
"https://example.test/?next=youtube.com"),
|
||||
"YouTube URL classification accepted a non-YouTube host")) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
auto provider = std::make_shared<FakeShortener>();
|
||||
UrlShortener shortener;
|
||||
shortener.setProvider([provider] { return provider; });
|
||||
|
||||
constexpr std::array sourceCases = {
|
||||
std::pair{"youtube", TrackSource::YouTube},
|
||||
std::pair{"yandex", TrackSource::Yandex},
|
||||
std::pair{"url", TrackSource::URL},
|
||||
std::pair{"soundcloud", TrackSource::SoundCloud},
|
||||
std::pair{"spotify", TrackSource::Spotify},
|
||||
std::pair{"plugin", TrackSource::Plugin},
|
||||
};
|
||||
for (const auto& [name, source] : sourceCases) {
|
||||
shortener.setSources({name});
|
||||
auto result =
|
||||
shortener.shortenUrl("https://example.test/track", source);
|
||||
if (!expect(result && *result == "https://sho.rt/abc",
|
||||
"configured source was not shortened")) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
const int acceptedCalls = provider->calls;
|
||||
shortener.setSources({"url"});
|
||||
for (const auto source :
|
||||
{TrackSource::Unknown, TrackSource::LocalFile, TrackSource::YouTube}) {
|
||||
auto result =
|
||||
shortener.shortenUrl("https://example.test/rejected", source);
|
||||
if (!expect(!result &&
|
||||
result.error().code == ErrorCode::InvalidArgument,
|
||||
"unconfigured or unsafe source was accepted")) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
if (!expect(provider->calls == acceptedCalls,
|
||||
"provider was called for a rejected source")) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
provider->healthStatus = Void::ShortUrl::HealthStatus::unhealthy;
|
||||
auto unhealthy =
|
||||
shortener.shortenUrl("https://example.test/track", TrackSource::URL);
|
||||
if (!expect(!unhealthy &&
|
||||
unhealthy.error().code == ErrorCode::ServiceUnavailable,
|
||||
"unhealthy provider was accepted")) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
provider->healthStatus = Void::ShortUrl::HealthStatus::healthy;
|
||||
provider->version = Void::ShortUrl::kServiceVersion + 1;
|
||||
auto incompatible =
|
||||
shortener.shortenUrl("https://example.test/track", TrackSource::URL);
|
||||
if (!expect(!incompatible &&
|
||||
incompatible.error().code == ErrorCode::ServiceUnavailable,
|
||||
"incompatible provider was accepted")) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
provider->version = Void::ShortUrl::kServiceVersion;
|
||||
provider->throwFromHealth = true;
|
||||
auto throwing =
|
||||
shortener.shortenUrl("https://example.test/track", TrackSource::URL);
|
||||
if (!expect(!throwing &&
|
||||
throwing.error().code == ErrorCode::ServiceUnavailable,
|
||||
"provider exception escaped the adapter")) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user