Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-15 19:49:57 +03:00
1 parent 01362d2e51
commit 39aff68d8d
29 files changed
+2061 -1818

No files matched your search

+29 -1
View File
@@ -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");
+134 -131
View File
@@ -1,8 +1,9 @@
#include "PluginTypes.hpp"
#include "echoion/core/ConfigLoader.hpp"
#include "echoion/core/Core.hpp"
#include "echoion/core/ListeningRoomManager.hpp"
#include "echoion/core/PluginHost.hpp"
#include "echoion/core/RpcDtos.hpp"
#include "echoion/core/TeamSpeakDirectoryService.hpp"
#include "echoion/core/i18n/Localization.hpp"
#include "echoion/core/state/StateSerializer.hpp"
#include "echoion/core/state/StateVersions.hpp"
@@ -30,8 +31,9 @@ namespace Echoion::Core
{
namespace
{
// Decode a base64 string to raw bytes (used for custom emoji images
// served over HTTP). Returns empty on malformed input.
// Decode cached avatar bytes before serving them over HTTP. Returns
// empty on malformed input.
#ifdef ECHOION_WITH_WEB
std::string decodeBase64(const std::string& in)
{
static constexpr auto val = [](char c) -> int {
@@ -73,6 +75,7 @@ namespace Echoion::Core
}
return out;
}
#endif
// Encode raw bytes to base64 (used to persist TeamSpeak avatar images
// in the database so they survive the client going
@@ -288,8 +291,7 @@ namespace Echoion::Core
if (!musicResult) {
return std::unexpected(musicResult.error());
}
listeningRooms_ = std::make_shared<ListeningRoomManager>(
networkClient_, configManager_, eventBus_);
directoryService_ = std::make_shared<TeamSpeakDirectoryService>();
// Initialize command manager
commandManager_ = std::make_unique<CommandManager>();
@@ -484,31 +486,73 @@ namespace Echoion::Core
std::format("RPC server started on port {}", rpcPort));
setupRpcHandlers();
setupEventBusSubscriptions();
if (listeningRooms_) {
listeningRooms_->setChangeCallback([server = rpcServer_] {
server->broadcastEvent("listening_rooms.updated", "{}");
});
}
}
extensionPlugins_ = std::make_shared<PluginHost>(
*commandManager_, musicManager_,
[this](uint64_t clientId) { return isAdmin(clientId); });
if (rpcServer_) {
extensionPlugins_->setChangeCallback([server = rpcServer_] {
server->broadcastEvent("plugins.updated", "{}");
});
}
extensionPlugins_->loadDirectory(configPath.parent_path() / "plugins");
#ifdef ECHOION_WITH_WEB
// Browser web interface (independent of the RPC transport above).
if (config_.web.enabled) {
webServer_ = std::make_shared<Web::HttpServer>();
// Watch-together control requires a signed-in user; the web
// server validates tokens through Core (it has no DB handle).
webServer_->setIdentityResolver(
[this](const std::string& token)
-> std::optional<Web::WatchSessionManager::Identity> {
auto identity = identityForToken(token);
if (!identity) {
return std::nullopt;
webServer_->setDashboardProvider([this] {
using Void::Json::Value;
auto dashboard = directoryService_->publicJson();
auto playback = Void::Json::object({{"isPlaying", Value{false}},
{"isPaused", Value{false}},
{"positionMs", Value{0LL}},
{"volume", Value{0.0}},
{"track", Value{nullptr}}});
if (musicManager_) {
if (auto state = musicManager_->getPlaybackState(); state) {
auto& out = playback.as_object();
out.clear();
out.emplace_back("isPlaying", Value{state->isPlaying});
out.emplace_back("isPaused", Value{state->isPaused});
out.emplace_back("positionMs",
Value{static_cast<long long>(
state->position.count())});
out.emplace_back(
"volume",
Value{static_cast<double>(state->volume)});
if (state->currentTrack) {
const auto& track = state->currentTrack->track;
out.emplace_back(
"track",
Void::Json::object(
{{"id", Value{track.id}},
{"title", Value{track.title}},
{"artist", Value{track.artist}},
{"album", Value{track.album}},
{"thumbnailUrl",
track.thumbnailUrl
? Value{*track.thumbnailUrl}
: Value{nullptr}},
{"durationMs",
track.duration
? Value{static_cast<long long>(
track.duration->count())}
: Value{nullptr}}}));
} else {
out.emplace_back("track", Value{nullptr});
}
}
return Web::WatchSessionManager::Identity{
.uid = identity->uid,
.nickname = identity->nickname,
.isAdmin = identity->isAdmin};
});
}
dashboard.as_object().emplace_back("playback",
std::move(playback));
std::string body = Void::Json::serialize(dashboard);
return Web::HttpServer::DashboardSnapshot{
.body = body,
.etag = std::format("\"{:x}\"",
std::hash<std::string>{}(body))};
});
// Avatar images for GET /avatar/<uid>: resolve the uid to an online
// client and serve its TeamSpeak avatar. Sources, in order: the TS
// client's own cache (in-view clients), an active file-transfer
@@ -582,31 +626,12 @@ namespace Echoion::Core
// Offline or live miss: persisted bytes / stored-url.
return fromStore(uid);
});
// Custom emoji images for GET /emoji/<name>: decode the stored
// base64 payload to raw bytes with its mime type.
webServer_->setEmojiProvider(
[this](const std::string& name)
-> std::optional<Web::HttpServer::AvatarImage> {
if (!database_) {
return std::nullopt;
}
auto emoji = database_->getCustomEmoji(name);
if (!emoji || !emoji->has_value()) {
return std::nullopt;
}
auto bytes = decodeBase64((*emoji)->dataBase64);
if (bytes.empty()) {
return std::nullopt;
}
return Web::HttpServer::AvatarImage{
.contentType = (*emoji)->mime,
.bytes = std::move(bytes)};
});
Web::HttpServer::Config webCfg;
webCfg.port = config_.web.port;
webCfg.bindAddress = config_.web.bindAddress;
webCfg.webRoot = config_.web.webRoot;
webCfg.rpcUrl = config_.web.rpcUrl;
webCfg.watchUrl = config_.web.watchUrl;
webCfg.nowPlayingVideo = config_.web.nowPlayingVideo;
webCfg.rpcPort =
config_.network.rpcPort > 0 ? config_.network.rpcPort : 8765;
@@ -663,9 +688,6 @@ namespace Echoion::Core
if (musicManager_) {
registry_.provide<MusicManager>(musicManager_);
}
if (listeningRooms_) {
registry_.provide<ListeningRoomManager>(listeningRooms_);
}
if (rpcServer_) {
registry_.provide<RpcServer>(rpcServer_);
}
@@ -711,27 +733,26 @@ namespace Echoion::Core
musicManager_->shutdown();
}
if (listeningRooms_) {
listeningRooms_->shutdown();
listeningRooms_.reset();
}
if (networkClient_) {
networkClient_->shutdown();
}
if (rpcServer_) {
rpcServer_->stop();
rpcServer_.reset();
}
extensionPlugins_.reset();
#ifdef ECHOION_WITH_WEB
// Providers and the RPC bridge capture Core services, so drain all HTTP
// workers before destroying any of those dependencies.
if (webServer_) {
webServer_->stop();
webServer_.reset();
}
#endif
if (networkClient_) {
networkClient_->shutdown();
}
directoryService_.reset();
if (rpcServer_) {
rpcServer_->stop();
rpcServer_.reset();
}
if (database_) {
database_->shutdown();
database_.reset();
@@ -1119,7 +1140,6 @@ namespace Echoion::Core
{
// Update local config copy
config_ = config;
if (commandManager_) {
commandManager_->setPrefix(config.bot.commandPrefix);
commandManager_->setServerConfig(config);
@@ -1201,7 +1221,6 @@ namespace Echoion::Core
// Update local config
config_ = *configResult;
// Keep the shared ConfigManager in sync so components that read through
// it (cookies, API key, etc.) see the reloaded values.
configManager_.updateConfig(config_, false);
@@ -1383,19 +1402,12 @@ namespace Echoion::Core
state.playback.shuffle = ps->shuffle;
state.playback.repeat = ps->repeat;
}
if (listeningRooms_) {
for (auto& saved : listeningRooms_->snapshot()) {
StateV1::ListeningRoomState room;
room.name = std::move(saved.name);
room.ownerId = saved.ownerId;
room.members = std::move(saved.members);
room.playback = std::move(saved.state.playback);
room.queue = std::move(saved.state.queue);
room.currentStreamUrl = std::move(saved.state.currentStreamUrl);
room.playbackPositionMs = saved.state.playbackPosition.count();
room.config = std::move(saved.state.config);
room.autoplay = saved.state.autoplay;
state.listeningRooms.push_back(std::move(room));
if (extensionPlugins_) {
for (auto& plugin : extensionPlugins_->snapshotStates()) {
state.extensionPlugins.push_back(
{.name = std::move(plugin.name),
.json = std::move(plugin.json),
.version = plugin.version});
}
}
@@ -1425,8 +1437,16 @@ namespace Echoion::Core
}
const StateV1& stateData = *result;
pendingListeningRoomState_ = Void::Json::serialize(
Void::Json::to_json(stateData.listeningRooms));
if (extensionPlugins_) {
std::vector<PluginHost::State> states;
states.reserve(stateData.extensionPlugins.size());
for (const auto& plugin : stateData.extensionPlugins) {
states.push_back({.name = plugin.name,
.json = plugin.json,
.version = plugin.version});
}
extensionPlugins_->restoreStates(states);
}
// MusicManager already reloads its persisted session (queue + modes)
// from the database at startup. Only fall back to re-adding from this
@@ -1573,6 +1593,12 @@ namespace Echoion::Core
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Core not initialized");
}
if (extensionPlugins_) {
extensionPlugins_->dispatch(event);
}
if (directoryService_) {
directoryService_->handleEvent(event.type);
}
// Debug logging for command events
if (event.type == Api::PluginEventType::TextMessageReceived &&
@@ -1677,9 +1703,6 @@ namespace Echoion::Core
if (musicManager_) {
musicManager_->onClientDisconnected(event.clientId);
}
if (listeningRooms_) {
std::ignore = listeningRooms_->leave(event.clientId);
}
break;
default:
@@ -1701,43 +1724,8 @@ namespace Echoion::Core
void Core::setPluginInterface(Api::PluginInterfacePtr pluginInterface)
{
pluginInterface_ = std::move(pluginInterface);
if (listeningRooms_) {
listeningRooms_->setPluginInterface(pluginInterface_);
if (!pendingListeningRoomState_.empty()) {
auto json = Void::Json::parse(pendingListeningRoomState_);
if (json) {
auto saved = Void::Json::from_json<
std::vector<StateV1::ListeningRoomState>>(*json);
if (saved) {
std::vector<ListeningRoomManager::PersistedRoom> rooms;
rooms.reserve(saved->size());
for (auto& source : *saved) {
Api::HotReloadState state;
state.playback = std::move(source.playback);
state.queue = std::move(source.queue);
state.currentStreamUrl =
std::move(source.currentStreamUrl);
state.playbackPosition = std::chrono::milliseconds(
source.playbackPositionMs);
state.config = std::move(source.config);
state.autoplay = source.autoplay;
rooms.push_back(
{.name = std::move(source.name),
.ownerId = source.ownerId,
.members = std::move(source.members),
.state = std::move(state)});
}
if (auto restored = listeningRooms_->restore(rooms);
!restored) {
Void::Log::error(
"Core",
"Failed to restore listening rooms: {}",
restored.error().message);
}
}
}
pendingListeningRoomState_.clear();
}
if (directoryService_) {
directoryService_->setPluginInterface(pluginInterface_);
}
Void::Log::info("Core", "{}",
std::format("Plugin interface set (this={})",
@@ -1925,16 +1913,12 @@ namespace Echoion::Core
bool Core::isAdmin(uint64_t clientId) const
{
std::lock_guard<std::mutex> lock(adminMutex_);
return std::find(adminClients_.begin(), adminClients_.end(),
clientId) != adminClients_.end();
return hasLiveTeamSpeakRole(clientId, config_.teamspeak.adminGroups);
}
bool Core::isDj(uint64_t clientId) const
{
std::lock_guard<std::mutex> lock(adminMutex_);
return std::find(djClients_.begin(), djClients_.end(), clientId) !=
djClients_.end();
return hasLiveTeamSpeakRole(clientId, config_.teamspeak.djGroups);
}
std::optional<Core::RpcIdentity> Core::rpcIdentity(uint64_t clientId) const
@@ -1947,6 +1931,34 @@ namespace Echoion::Core
return std::nullopt;
}
bool Core::hasLiveTeamSpeakRole(
uint64_t clientId, const std::vector<uint64_t>& configuredGroups) const
{
const auto identity = rpcIdentity(clientId);
if (!identity || configuredGroups.empty() || !pluginInterface_) {
return false;
}
const auto clients = pluginInterface_->getClients();
if (!clients) {
return false;
}
for (const auto& client : *clients) {
if (client.uniqueIdentifier != identity->uid) {
continue;
}
for (const auto group : client.serverGroups) {
if (std::find(configuredGroups.begin(), configuredGroups.end(),
group) != configuredGroups.end()) {
return true;
}
}
return false;
}
return false;
}
std::optional<Core::TokenIdentity>
Core::identityForToken(const std::string& token)
{
@@ -2013,15 +2025,6 @@ namespace Echoion::Core
if (rpcServer_) {
rpcServer_->addAuthenticatedClient(clientId);
}
if (identity.isAdmin || identity.isDj) {
std::lock_guard<std::mutex> lock(adminMutex_);
if (identity.isAdmin) {
adminClients_.push_back(clientId);
}
if (identity.isDj) {
djClients_.push_back(clientId);
}
}
{
std::lock_guard<std::mutex> lock(rpcIdentityMutex_);
rpcIdentities_[clientId] =
+728 -572
View File
File diff suppressed because it is too large. Load diff
+4 -95
View File
@@ -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)
{
-457
View File
@@ -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);
}
}
}
+8 -1
View File
@@ -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.
@@ -459,6 +461,11 @@ 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
+400
View File
@@ -0,0 +1,400 @@
#include "echoion/core/PluginHost.hpp"
#include "echoion/core/CommandManager.hpp"
#include "echoion/core/MusicManager.hpp"
#include "echoion/core/sources/TrackSource.hpp"
#include <Void/Log/Log.hpp>
#include <Void/Plugin/Loader.hpp>
#include <algorithm>
#include <utility>
namespace Echoion::Core
{
namespace
{
class ExtensionCommandAdapter final : public Command
{
public:
ExtensionCommandAdapter(Void::Plugin::PluginManager& plugins,
std::string plugin, Api::ExtensionCommand command)
: plugins_(plugins), plugin_(std::move(plugin)),
command_(std::move(command))
{
}
void execute(const CommandContext& context) override
{
try {
auto pin = plugins_.acquire(plugin_);
auto* extension = pin
? dynamic_cast<Api::IExtensionPlugin*>(pin.get()) : nullptr;
if (!extension) {
context.reply("Plugin is temporarily unavailable.");
return;
}
auto result = extension->executeCommand({
.command = command_.name,
.arguments = context.args,
.clientId = context.clientId,
.invokerName = std::string(context.invokerName)});
context.reply(result ? *result : result.error().message);
} catch (const std::exception& error) {
Void::Log::error("PluginHost", "Plugin '{}' command '{}' threw: {}",
plugin_, command_.name, error.what());
context.reply("Plugin command failed.");
} catch (...) {
Void::Log::error("PluginHost", "Plugin '{}' command '{}' threw",
plugin_, command_.name);
context.reply("Plugin command failed.");
}
}
std::string_view getDescription() const override
{
return command_.description;
}
std::string_view getUsage() const override { return command_.usage; }
CommandCategory getCategory() const override
{
return static_cast<CommandCategory>(
std::min<std::uint8_t>(command_.category,
static_cast<std::uint8_t>(CommandCategory::Admin)));
}
std::vector<std::string_view> getAliases() const override
{
std::vector<std::string_view> aliases;
aliases.reserve(command_.aliases.size());
for (const auto& alias : command_.aliases) aliases.push_back(alias);
return aliases;
}
bool requiresAdmin() const override { return command_.adminOnly; }
private:
Void::Plugin::PluginManager& plugins_;
std::string plugin_;
Api::ExtensionCommand command_;
};
}
class PluginTrackSource final : public ITrackSource
{
public:
PluginTrackSource(std::weak_ptr<PluginHost> host,
Void::Plugin::PluginManager& plugins, std::string plugin,
Api::ExtensionMediaSource source)
: host_(std::move(host)), plugins_(plugins), plugin_(std::move(plugin)),
source_(std::move(source))
{
}
std::string_view name() const override { return source_.name; }
bool canHandle(const std::string& query) const override
{
try {
auto pin = plugins_.acquire(plugin_);
auto* extension = pin
? dynamic_cast<Api::IExtensionPlugin*>(pin.get()) : nullptr;
return extension && declaredBy(*extension) &&
extension->canHandleMedia(source_.name, query);
} catch (...) {
return false;
}
}
bool isAvailable() const override
{
try {
if (host_.expired()) return false;
auto pin = plugins_.acquire(plugin_);
auto* extension = pin
? dynamic_cast<Api::IExtensionPlugin*>(pin.get()) : nullptr;
return extension && declaredBy(*extension);
} catch (...) {
return false;
}
}
bool supportsSearch() const override
{
try {
auto pin = plugins_.acquire(plugin_);
auto* extension = pin
? dynamic_cast<Api::IExtensionPlugin*>(pin.get()) : nullptr;
if (!extension) return false;
auto descriptors = extension->mediaSources();
auto descriptor = std::ranges::find(
descriptors, source_.name, &Api::ExtensionMediaSource::name);
return descriptor != descriptors.end() && descriptor->supportsSearch;
} catch (...) {
return false;
}
}
[[nodiscard]] bool represents(std::string_view plugin,
std::string_view source) const
{
return plugin_ == plugin && source_.name == source;
}
Api::Result<Api::SearchResult> search(std::string_view query) override
{
try {
auto pin = plugins_.acquire(plugin_);
auto* extension = pin
? dynamic_cast<Api::IExtensionPlugin*>(pin.get()) : nullptr;
if (!extension) return Api::fail(Api::ErrorCode::ServiceUnavailable,
"plugin media source unavailable");
return extension->searchMedia(source_.name, query);
} catch (const std::exception& error) {
return Api::fail(Api::ErrorCode::UnknownError, error.what());
} catch (...) {
return Api::fail(Api::ErrorCode::UnknownError,
"plugin media search threw an exception");
}
}
Api::Result<Api::TrackInfo> resolve(const std::string& query) override
{
try {
auto pin = plugins_.acquire(plugin_);
auto* extension = pin
? dynamic_cast<Api::IExtensionPlugin*>(pin.get()) : nullptr;
if (!extension) return Api::fail(Api::ErrorCode::ServiceUnavailable,
"plugin media source unavailable");
return extension->resolveMedia(source_.name, query);
} catch (const std::exception& error) {
return Api::fail(Api::ErrorCode::UnknownError, error.what());
} catch (...) {
return Api::fail(Api::ErrorCode::UnknownError,
"plugin media resolve threw an exception");
}
}
Api::Result<StreamHandle> getStream(const Api::TrackInfo& track) override
{
try {
auto pin = plugins_.acquire(plugin_);
auto* extension = pin
? dynamic_cast<Api::IExtensionPlugin*>(pin.get()) : nullptr;
if (!extension) return Api::fail(Api::ErrorCode::ServiceUnavailable,
"plugin media source unavailable");
auto result = extension->streamMedia(source_.name, track);
if (!result) return std::unexpected(result.error());
return StreamHandle{.url = std::move(result->url),
.isLocalFile = result->localFile, .sourceName = source_.name};
} catch (const std::exception& error) {
return Api::fail(Api::ErrorCode::UnknownError, error.what());
} catch (...) {
return Api::fail(Api::ErrorCode::UnknownError,
"plugin media stream threw an exception");
}
}
private:
[[nodiscard]] bool declaredBy(Api::IExtensionPlugin& extension) const
{
auto descriptors = extension.mediaSources();
return std::ranges::find(descriptors, source_.name,
&Api::ExtensionMediaSource::name) != descriptors.end();
}
std::weak_ptr<PluginHost> host_;
Void::Plugin::PluginManager& plugins_;
std::string plugin_;
Api::ExtensionMediaSource source_;
};
PluginHost::PluginHost(CommandManager& commands,
std::shared_ptr<MusicManager> music, std::function<bool(uint64_t)> isAdmin,
std::function<void(std::shared_ptr<ITrackSource>)> mediaSink)
: commands_(commands), music_(std::move(music)),
isAdmin_(std::move(isAdmin)), mediaSink_(std::move(mediaSink)),
plugins_(Void::Plugin::PluginManager::Options{
.dlclose_on_swap = false,
.copy_on_load = true,
.config_provider = {},
.instance_validator = [](Void::Plugin::IPlugin& plugin,
const Void::Plugin::PluginInfo&) {
return dynamic_cast<Api::IExtensionPlugin*>(&plugin) != nullptr;
}})
{
reloadCallback_ = plugins_.on_reloaded(
[this](std::string_view name) { publish(name); });
}
PluginHost::~PluginHost()
{
plugins_.remove_on_reloaded(reloadCallback_);
for (const auto& name : plugins_.names()) unpublish(name);
}
void PluginHost::loadDirectory(const std::filesystem::path& directory)
{
for (auto& [path, result] : plugins_.load_directory(directory)) {
if (!result) {
Void::Log::warn("PluginHost", "Failed to load '{}': {}",
path.string(), Void::Plugin::to_string(result.error()));
continue;
}
publish(*result);
plugins_.watch(*result);
}
}
void PluginHost::setChangeCallback(std::function<void()> callback)
{
std::lock_guard lock(mutex_);
changeCallback_ = std::move(callback);
}
void PluginHost::notifyChanged() const
{
std::function<void()> callback;
{
std::lock_guard lock(mutex_);
callback = changeCallback_;
}
if (callback) callback();
}
void PluginHost::publish(std::string_view name)
{
unpublish(name);
auto pin = plugins_.acquire(name);
auto* extension = pin
? dynamic_cast<Api::IExtensionPlugin*>(pin.get()) : nullptr;
if (!extension) return;
std::vector<Api::ExtensionCommand> commands;
std::vector<Api::ExtensionMediaSource> mediaSources;
try {
commands = extension->commands();
mediaSources = extension->mediaSources();
} catch (const std::exception& error) {
Void::Log::error("PluginHost", "Plugin '{}' descriptors threw: {}",
name, error.what());
return;
} catch (...) {
Void::Log::error("PluginHost", "Plugin '{}' descriptors threw", name);
return;
}
for (const auto& descriptor : commands) {
auto command = std::make_shared<ExtensionCommandAdapter>(
plugins_, std::string(name), descriptor);
if (!commands_.registerExternalCommand(
std::string(name), descriptor.name, std::move(command))) {
Void::Log::warn("PluginHost", "Command '{}' from '{}' conflicts",
descriptor.name, name);
}
}
for (auto source : mediaSources) {
{
std::lock_guard lock(mutex_);
if (std::ranges::any_of(sources_, [&](const auto& existing) {
return existing->represents(name, source.name);
})) continue;
}
auto proxy = std::make_shared<PluginTrackSource>(
weak_from_this(), plugins_, std::string(name), std::move(source));
music_->addTrackSource(proxy);
if (mediaSink_) mediaSink_(proxy);
std::lock_guard lock(mutex_);
sources_.push_back(std::move(proxy));
}
Void::Log::info("PluginHost", "Published Echoion plugin '{}'", name);
notifyChanged();
}
void PluginHost::unpublish(std::string_view name)
{
commands_.unregisterExternalCommands(name);
}
void PluginHost::dispatch(const Api::PluginEvent& event) const
{
for (const auto& name : plugins_.names()) {
try {
auto pin = plugins_.acquire(name);
if (auto* extension = pin
? dynamic_cast<Api::IExtensionPlugin*>(pin.get()) : nullptr) {
extension->onEvent(event);
}
} catch (const std::exception& error) {
Void::Log::error("PluginHost", "Plugin '{}' event handler threw: {}",
name, error.what());
} catch (...) {
Void::Log::error("PluginHost", "Plugin '{}' event handler threw", name);
}
}
}
Api::Result<std::string> PluginHost::call(
std::string_view plugin, std::string_view method, std::string params,
uint64_t clientId) const
{
try {
auto pin = plugins_.acquire(plugin);
auto* extension = pin
? dynamic_cast<Api::IExtensionPlugin*>(pin.get()) : nullptr;
if (!extension) return Api::fail(Api::ErrorCode::NotFound,
"plugin not found");
auto rpc = extension->rpcMethods();
auto descriptor = std::ranges::find(rpc, method, &Api::ExtensionRpc::name);
if (descriptor == rpc.end()) return Api::fail(Api::ErrorCode::NotFound,
"plugin RPC method not found");
if (descriptor->adminOnly && (!isAdmin_ || !isAdmin_(clientId))) {
return Api::fail(Api::ErrorCode::PermissionDenied,
"admin privileges required");
}
return extension->callRpc({.method = std::string(method),
.params = std::move(params), .clientId = clientId});
} catch (const std::exception& error) {
Void::Log::error("PluginHost", "Plugin '{}' RPC '{}' threw: {}",
plugin, method, error.what());
return Api::fail(Api::ErrorCode::UnknownError, "plugin RPC failed");
} catch (...) {
Void::Log::error("PluginHost", "Plugin '{}' RPC '{}' threw", plugin, method);
return Api::fail(Api::ErrorCode::UnknownError, "plugin RPC failed");
}
}
std::vector<Api::ExtensionWebAsset> PluginHost::webAssets() const
{
std::vector<Api::ExtensionWebAsset> assets;
for (const auto& name : plugins_.names()) {
try {
auto pin = plugins_.acquire(name);
if (auto* extension = pin
? dynamic_cast<Api::IExtensionPlugin*>(pin.get()) : nullptr) {
auto current = extension->webAssets();
assets.insert(assets.end(), std::make_move_iterator(current.begin()),
std::make_move_iterator(current.end()));
}
} catch (const std::exception& error) {
Void::Log::error("PluginHost", "Plugin '{}' web assets threw: {}",
name, error.what());
} catch (...) {
Void::Log::error("PluginHost", "Plugin '{}' web assets threw", name);
}
}
return assets;
}
std::vector<std::string> PluginHost::names() const { return plugins_.names(); }
std::vector<PluginHost::State> PluginHost::snapshotStates() const
{
std::vector<State> states;
for (const auto& name : plugins_.names()) {
if (auto state = plugins_.serialize_state(name)) {
states.push_back({.name = name, .json = std::move(state->json),
.version = state->version});
}
}
return states;
}
void PluginHost::restoreStates(const std::vector<State>& states)
{
for (const auto& state : states) {
if (!plugins_.deserialize_state(state.name, state.json, state.version)) {
Void::Log::warn("PluginHost", "Plugin '{}' rejected restored state",
state.name);
}
}
}
}
+10 -5
View File
@@ -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;
+265
View File
@@ -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
+42 -32
View File
@@ -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);
}
+6 -27
View File
@@ -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