1 parent
5c036d91fb
commit
01362d2e51
14 files changed
+1324
-51
No files matched your search
@@ -640,6 +640,7 @@ namespace Echoion::Core
|
||||
registerCommand<ShuffleCommand>("shuffle");
|
||||
registerCommand<AutoplayCommand>("autoplay");
|
||||
registerCommand<RepeatCommand>("repeat");
|
||||
registerCommand<RoomCommand>("room");
|
||||
registerCommand<PlaylistCommand>("playlist");
|
||||
registerCommand<NowPlayingCommand>("np");
|
||||
registerCommand<LyricsCommand>("lyrics");
|
||||
|
||||
+121
-31
@@ -1,5 +1,7 @@
|
||||
#include "PluginTypes.hpp"
|
||||
#include "echoion/core/ConfigLoader.hpp"
|
||||
#include "echoion/core/Core.hpp"
|
||||
#include "echoion/core/ListeningRoomManager.hpp"
|
||||
#include "echoion/core/RpcDtos.hpp"
|
||||
#include "echoion/core/i18n/Localization.hpp"
|
||||
#include "echoion/core/state/StateSerializer.hpp"
|
||||
@@ -33,11 +35,21 @@ namespace Echoion::Core
|
||||
std::string decodeBase64(const std::string& in)
|
||||
{
|
||||
static constexpr auto val = [](char c) -> int {
|
||||
if (c >= 'A' && c <= 'Z') return c - 'A';
|
||||
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
|
||||
if (c >= '0' && c <= '9') return c - '0' + 52;
|
||||
if (c == '+') return 62;
|
||||
if (c == '/') return 63;
|
||||
if (c >= 'A' && c <= 'Z') {
|
||||
return c - 'A';
|
||||
}
|
||||
if (c >= 'a' && c <= 'z') {
|
||||
return c - 'a' + 26;
|
||||
}
|
||||
if (c >= '0' && c <= '9') {
|
||||
return c - '0' + 52;
|
||||
}
|
||||
if (c == '+') {
|
||||
return 62;
|
||||
}
|
||||
if (c == '/') {
|
||||
return 63;
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
std::string out;
|
||||
@@ -63,18 +75,20 @@ namespace Echoion::Core
|
||||
}
|
||||
|
||||
// Encode raw bytes to base64 (used to persist TeamSpeak avatar images
|
||||
// in the database so they survive the client going offline/out-of-view).
|
||||
// in the database so they survive the client going
|
||||
// offline/out-of-view).
|
||||
std::string encodeBase64(std::string_view in)
|
||||
{
|
||||
static constexpr char tbl[] =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
static constexpr char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij"
|
||||
"klmnopqrstuvwxyz0123456789+/";
|
||||
std::string out;
|
||||
out.reserve((in.size() + 2) / 3 * 4);
|
||||
std::size_t i = 0;
|
||||
while (i + 3 <= in.size()) {
|
||||
const unsigned n = (static_cast<unsigned char>(in[i]) << 16) |
|
||||
(static_cast<unsigned char>(in[i + 1]) << 8) |
|
||||
static_cast<unsigned char>(in[i + 2]);
|
||||
const unsigned n =
|
||||
(static_cast<unsigned char>(in[i]) << 16) |
|
||||
(static_cast<unsigned char>(in[i + 1]) << 8) |
|
||||
static_cast<unsigned char>(in[i + 2]);
|
||||
out.push_back(tbl[(n >> 18) & 0x3F]);
|
||||
out.push_back(tbl[(n >> 12) & 0x3F]);
|
||||
out.push_back(tbl[(n >> 6) & 0x3F]);
|
||||
@@ -99,7 +113,8 @@ namespace Echoion::Core
|
||||
|
||||
// Best content type for avatar bytes: honour a valid image/* hint
|
||||
// (e.g. an HTTP Content-Type), else sniff the magic number.
|
||||
std::string sniffImageMime(std::string_view bytes, std::string_view hint)
|
||||
std::string sniffImageMime(std::string_view bytes,
|
||||
std::string_view hint)
|
||||
{
|
||||
if (hint.starts_with("image/")) {
|
||||
return std::string(hint);
|
||||
@@ -164,7 +179,7 @@ namespace Echoion::Core
|
||||
void Core::installLogging()
|
||||
{
|
||||
logSink_ = buildLogSink();
|
||||
Void::Log::set_sink(Void::Log::make_sink(*logSink_));
|
||||
Void::Log::set_sink(Void::Log::make_sink(logSink_));
|
||||
Void::Log::set_min_level(Void::Log::Level::Debug);
|
||||
}
|
||||
|
||||
@@ -273,6 +288,8 @@ namespace Echoion::Core
|
||||
if (!musicResult) {
|
||||
return std::unexpected(musicResult.error());
|
||||
}
|
||||
listeningRooms_ = std::make_shared<ListeningRoomManager>(
|
||||
networkClient_, configManager_, eventBus_);
|
||||
|
||||
// Initialize command manager
|
||||
commandManager_ = std::make_unique<CommandManager>();
|
||||
@@ -467,6 +484,11 @@ namespace Echoion::Core
|
||||
std::format("RPC server started on port {}", rpcPort));
|
||||
setupRpcHandlers();
|
||||
setupEventBusSubscriptions();
|
||||
if (listeningRooms_) {
|
||||
listeningRooms_->setChangeCallback([server = rpcServer_] {
|
||||
server->broadcastEvent("listening_rooms.updated", "{}");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef ECHOION_WITH_WEB
|
||||
@@ -530,8 +552,7 @@ namespace Echoion::Core
|
||||
if (database_) {
|
||||
[[maybe_unused]] auto put =
|
||||
database_->putCachedAvatar(
|
||||
u, type,
|
||||
encodeBase64(resp->body));
|
||||
u, type, encodeBase64(resp->body));
|
||||
}
|
||||
return Web::HttpServer::AvatarImage{
|
||||
.contentType = std::move(type),
|
||||
@@ -549,7 +570,7 @@ namespace Echoion::Core
|
||||
continue;
|
||||
}
|
||||
if (auto r =
|
||||
fetchClientAvatarBytes(uid, c.id)) {
|
||||
fetchClientAvatarBytes(uid, c.id)) {
|
||||
return Web::HttpServer::AvatarImage{
|
||||
.contentType = std::move(r->first),
|
||||
.bytes = std::move(r->second)};
|
||||
@@ -599,8 +620,8 @@ namespace Echoion::Core
|
||||
|
||||
// Proactively cache avatars for every online client so they stay
|
||||
// available (from the DB / stored myTS URL) once the user goes offline.
|
||||
// A short-cycle poll keeps up with clients whose avatar variables sync a
|
||||
// moment after they come into view.
|
||||
// A short-cycle poll keeps up with clients whose avatar variables sync
|
||||
// a moment after they come into view.
|
||||
avatarWarmer_ = std::jthread([this](std::stop_token st) {
|
||||
while (!st.stop_requested()) {
|
||||
for (int i = 0; i < 30 && !st.stop_requested(); ++i) {
|
||||
@@ -642,6 +663,9 @@ namespace Echoion::Core
|
||||
if (musicManager_) {
|
||||
registry_.provide<MusicManager>(musicManager_);
|
||||
}
|
||||
if (listeningRooms_) {
|
||||
registry_.provide<ListeningRoomManager>(listeningRooms_);
|
||||
}
|
||||
if (rpcServer_) {
|
||||
registry_.provide<RpcServer>(rpcServer_);
|
||||
}
|
||||
@@ -687,6 +711,11 @@ namespace Echoion::Core
|
||||
musicManager_->shutdown();
|
||||
}
|
||||
|
||||
if (listeningRooms_) {
|
||||
listeningRooms_->shutdown();
|
||||
listeningRooms_.reset();
|
||||
}
|
||||
|
||||
if (networkClient_) {
|
||||
networkClient_->shutdown();
|
||||
}
|
||||
@@ -1354,6 +1383,21 @@ 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));
|
||||
}
|
||||
}
|
||||
|
||||
// Serialize using StateSerializer
|
||||
auto blob = StateSerializer::serialize(state);
|
||||
@@ -1381,6 +1425,8 @@ namespace Echoion::Core
|
||||
}
|
||||
|
||||
const StateV1& stateData = *result;
|
||||
pendingListeningRoomState_ = Void::Json::serialize(
|
||||
Void::Json::to_json(stateData.listeningRooms));
|
||||
|
||||
// MusicManager already reloads its persisted session (queue + modes)
|
||||
// from the database at startup. Only fall back to re-adding from this
|
||||
@@ -1509,11 +1555,14 @@ namespace Echoion::Core
|
||||
|
||||
Api::Result<void> Core::onPluginEvent(const Api::PluginEvent& event)
|
||||
{
|
||||
Void::Log::debug(
|
||||
"Core", "{}",
|
||||
std::format("Core::onPluginEvent called (this={}, initialized={})",
|
||||
reinterpret_cast<uintptr_t>(this),
|
||||
initialized_.load()));
|
||||
if (event.type != Api::PluginEventType::VoiceDataReceived) {
|
||||
Void::Log::debug("Core", "{}",
|
||||
std::format("Core::onPluginEvent called (this={}, "
|
||||
"initialized={}, event={})",
|
||||
reinterpret_cast<uintptr_t>(this),
|
||||
initialized_.load(),
|
||||
static_cast<int>(event.type)));
|
||||
}
|
||||
if (!initialized_) {
|
||||
Void::Log::warn(
|
||||
"Core", "{}",
|
||||
@@ -1628,6 +1677,9 @@ namespace Echoion::Core
|
||||
if (musicManager_) {
|
||||
musicManager_->onClientDisconnected(event.clientId);
|
||||
}
|
||||
if (listeningRooms_) {
|
||||
std::ignore = listeningRooms_->leave(event.clientId);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
@@ -1649,6 +1701,44 @@ 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();
|
||||
}
|
||||
}
|
||||
Void::Log::info("Core", "{}",
|
||||
std::format("Plugin interface set (this={})",
|
||||
reinterpret_cast<uintptr_t>(this)));
|
||||
@@ -1904,10 +1994,10 @@ namespace Echoion::Core
|
||||
if (c.uniqueIdentifier != identity.uid) {
|
||||
continue;
|
||||
}
|
||||
identity.isAdmin = inAnyGroup(
|
||||
config_.teamspeak.adminGroups, c.serverGroups);
|
||||
identity.isDj = inAnyGroup(config_.teamspeak.djGroups,
|
||||
c.serverGroups);
|
||||
identity.isAdmin = inAnyGroup(config_.teamspeak.adminGroups,
|
||||
c.serverGroups);
|
||||
identity.isDj =
|
||||
inAnyGroup(config_.teamspeak.djGroups, c.serverGroups);
|
||||
if (identity.nickname.empty()) {
|
||||
identity.nickname = c.nickname;
|
||||
}
|
||||
@@ -1934,8 +2024,8 @@ namespace Echoion::Core
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(rpcIdentityMutex_);
|
||||
rpcIdentities_[clientId] = RpcIdentity{
|
||||
.uid = identity.uid, .nickname = identity.nickname};
|
||||
rpcIdentities_[clientId] =
|
||||
RpcIdentity{.uid = identity.uid, .nickname = identity.nickname};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1952,8 +2042,8 @@ namespace Echoion::Core
|
||||
}
|
||||
std::string type = sniffImageMime(bytes, hint);
|
||||
if (database_) {
|
||||
[[maybe_unused]] auto put = database_->putCachedAvatar(
|
||||
uid, type, encodeBase64(bytes));
|
||||
[[maybe_unused]] auto put =
|
||||
database_->putCachedAvatar(uid, type, encodeBase64(bytes));
|
||||
}
|
||||
return std::pair{std::move(type), std::move(bytes)};
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "echoion/core/Core.hpp"
|
||||
#include "echoion/core/ListeningRoomManager.hpp"
|
||||
#include "echoion/core/RpcDtos.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <Events.hpp>
|
||||
@@ -36,6 +37,21 @@ namespace Echoion::Core
|
||||
if (!rpcServer_) {
|
||||
return;
|
||||
}
|
||||
auto resolveTeamSpeakClient = [this](uint64_t rpcClientId)
|
||||
-> Api::Result<uint64_t> {
|
||||
auto identity = rpcIdentity(rpcClientId);
|
||||
if (!identity) return Api::fail(Api::ErrorCode::NotAuthenticated,
|
||||
"authenticate before using listening rooms");
|
||||
if (!pluginInterface_) return Api::fail(
|
||||
Api::ErrorCode::ServiceUnavailable, "TeamSpeak host unavailable");
|
||||
auto clients = pluginInterface_->getClients();
|
||||
if (!clients) return std::unexpected(clients.error());
|
||||
for (const auto& client : *clients) {
|
||||
if (client.uniqueIdentifier == identity->uid) return client.id;
|
||||
}
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"authenticated TeamSpeak client is not online");
|
||||
};
|
||||
|
||||
// Authentication - expects JSON with either "nickname" (for initial
|
||||
// request) or "token" (for validation). The same handler backs
|
||||
@@ -593,6 +609,204 @@ namespace Echoion::Core
|
||||
return toJson(resp);
|
||||
});
|
||||
|
||||
// Named listening rooms: every room owns an independent playback engine,
|
||||
// Opus encoder and TeamSpeak whisper connection.
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::ListListeningRooms)),
|
||||
[this, resolveTeamSpeakClient](const std::string&, uint64_t rpcId)
|
||||
-> Api::Result<std::string> {
|
||||
if (!listeningRooms_) return Api::fail(
|
||||
Api::ErrorCode::ServiceUnavailable, "listening rooms unavailable");
|
||||
Dto::ListeningRoomList response;
|
||||
const auto client = resolveTeamSpeakClient(rpcId);
|
||||
if (client) {
|
||||
response.currentRoom = listeningRooms_->roomForClient(*client);
|
||||
}
|
||||
for (const auto& room : listeningRooms_->list()) {
|
||||
response.rooms.push_back(Dto::ListeningRoom{
|
||||
.name = room.name, .ownerId = room.ownerId,
|
||||
.members = room.members, .isPlaying = room.isPlaying,
|
||||
.isPaused = room.isPaused,
|
||||
.queueSize = static_cast<uint64_t>(room.queueSize),
|
||||
.isOwner = client && room.ownerId == *client});
|
||||
}
|
||||
return toJson(response);
|
||||
});
|
||||
|
||||
auto roomRequest = [](const std::string& params)
|
||||
-> Api::Result<Dto::ListeningRoomRequest> {
|
||||
auto json = Void::Json::parse(params);
|
||||
if (!json) return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"invalid listening-room request");
|
||||
auto request = Void::Json::from_json<Dto::ListeningRoomRequest>(*json);
|
||||
if (!request || request->room.empty()) return Api::fail(
|
||||
Api::ErrorCode::InvalidArgument, "room name is required");
|
||||
return *request;
|
||||
};
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::CreateListeningRoom)),
|
||||
[this, resolveTeamSpeakClient, roomRequest](const std::string& params,
|
||||
uint64_t rpcId) -> Api::Result<std::string> {
|
||||
auto request = roomRequest(params);
|
||||
if (!request) return std::unexpected(request.error());
|
||||
auto client = resolveTeamSpeakClient(rpcId);
|
||||
if (!client) return std::unexpected(client.error());
|
||||
auto result = listeningRooms_->create(request->room, *client);
|
||||
if (!result) return std::unexpected(result.error());
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::DeleteListeningRoom)),
|
||||
[this, resolveTeamSpeakClient, roomRequest](const std::string& params,
|
||||
uint64_t rpcId) -> Api::Result<std::string> {
|
||||
auto request = roomRequest(params);
|
||||
if (!request) return std::unexpected(request.error());
|
||||
auto client = resolveTeamSpeakClient(rpcId);
|
||||
if (!client) return std::unexpected(client.error());
|
||||
auto result = listeningRooms_->remove(request->room, *client);
|
||||
if (!result) return std::unexpected(result.error());
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::JoinListeningRoom)),
|
||||
[this, resolveTeamSpeakClient, roomRequest](const std::string& params,
|
||||
uint64_t rpcId) -> Api::Result<std::string> {
|
||||
auto request = roomRequest(params);
|
||||
if (!request) return std::unexpected(request.error());
|
||||
auto client = resolveTeamSpeakClient(rpcId);
|
||||
if (!client) return std::unexpected(client.error());
|
||||
auto result = listeningRooms_->join(request->room, *client);
|
||||
if (!result) return std::unexpected(result.error());
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::LeaveListeningRoom)),
|
||||
[this, resolveTeamSpeakClient](const std::string&, uint64_t rpcId)
|
||||
-> Api::Result<std::string> {
|
||||
auto client = resolveTeamSpeakClient(rpcId);
|
||||
if (!client) return std::unexpected(client.error());
|
||||
auto result = listeningRooms_->leave(*client);
|
||||
if (!result) return std::unexpected(result.error());
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::PlayInListeningRoom)),
|
||||
[this, resolveTeamSpeakClient](const std::string& params, uint64_t rpcId)
|
||||
-> Api::Result<std::string> {
|
||||
auto json = Void::Json::parse(params);
|
||||
if (!json) return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"invalid room play request");
|
||||
auto request = Void::Json::from_json<Dto::ListeningRoomPlayRequest>(*json);
|
||||
if (!request || request->room.empty() || request->query.empty())
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"room and query are required");
|
||||
auto client = resolveTeamSpeakClient(rpcId);
|
||||
if (!client) return std::unexpected(client.error());
|
||||
auto result = listeningRooms_->play(
|
||||
request->room, request->query, *client);
|
||||
if (!result) return std::unexpected(result.error());
|
||||
return toJson(Dto::SuccessMessage{.message = *result});
|
||||
});
|
||||
|
||||
const auto registerRoomControl =
|
||||
[this, roomRequest, resolveTeamSpeakClient](Api::RpcMethod method,
|
||||
auto operation) {
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(method)),
|
||||
[roomRequest, operation, resolveTeamSpeakClient](
|
||||
const std::string& params, uint64_t rpcId)
|
||||
-> Api::Result<std::string> {
|
||||
auto request = roomRequest(params);
|
||||
if (!request) return std::unexpected(request.error());
|
||||
auto client = resolveTeamSpeakClient(rpcId);
|
||||
if (!client) return std::unexpected(client.error());
|
||||
auto result = operation(request->room, *client);
|
||||
if (!result) return std::unexpected(result.error());
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
};
|
||||
registerRoomControl(Api::RpcMethod::PauseListeningRoom,
|
||||
[this](const std::string& room, uint64_t client) {
|
||||
return listeningRooms_->pause(room, client);
|
||||
});
|
||||
registerRoomControl(Api::RpcMethod::ResumeListeningRoom,
|
||||
[this](const std::string& room, uint64_t client) {
|
||||
return listeningRooms_->resume(room, client);
|
||||
});
|
||||
registerRoomControl(Api::RpcMethod::StopListeningRoom,
|
||||
[this](const std::string& room, uint64_t client) {
|
||||
return listeningRooms_->stop(room, client);
|
||||
});
|
||||
registerRoomControl(Api::RpcMethod::SkipListeningRoom,
|
||||
[this](const std::string& room, uint64_t client) {
|
||||
return listeningRooms_->skip(room, client);
|
||||
});
|
||||
registerRoomControl(Api::RpcMethod::ClearListeningRoomQueue,
|
||||
[this](const std::string& room, uint64_t client) {
|
||||
return listeningRooms_->clearQueue(room, client);
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::GetListeningRoomQueue)),
|
||||
[this, roomRequest](const std::string& params, uint64_t)
|
||||
-> Api::Result<std::string> {
|
||||
auto request = roomRequest(params);
|
||||
if (!request) return std::unexpected(request.error());
|
||||
auto queue = listeningRooms_->queue(request->room);
|
||||
if (!queue) return std::unexpected(queue.error());
|
||||
Dto::QueueResponse response;
|
||||
for (const auto& entry : *queue) response.queue.push_back(
|
||||
Dto::QueueItem{.queueId = entry.queueId,
|
||||
.track = Dto::toTrack(entry.track),
|
||||
.isPlaying = entry.isPlaying});
|
||||
return toJson(response);
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(
|
||||
Api::RpcMethod::RemoveFromListeningRoomQueue)),
|
||||
[this, resolveTeamSpeakClient](const std::string& params, uint64_t rpcId)
|
||||
-> Api::Result<std::string> {
|
||||
auto json = Void::Json::parse(params);
|
||||
if (!json) return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"invalid room queue request");
|
||||
auto request = Void::Json::from_json<Dto::ListeningRoomQueueRequest>(*json);
|
||||
if (!request || request->room.empty() || request->queueId == 0)
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"room and queueId are required");
|
||||
auto client = resolveTeamSpeakClient(rpcId);
|
||||
if (!client) return std::unexpected(client.error());
|
||||
auto result = listeningRooms_->removeQueueEntry(
|
||||
request->room, request->queueId, *client);
|
||||
if (!result) return std::unexpected(result.error());
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(
|
||||
Api::RpcMethod::MoveInListeningRoomQueue)),
|
||||
[this, resolveTeamSpeakClient](const std::string& params, uint64_t rpcId)
|
||||
-> Api::Result<std::string> {
|
||||
auto json = Void::Json::parse(params);
|
||||
if (!json) return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"invalid room queue move request");
|
||||
auto request = Void::Json::from_json<Dto::ListeningRoomMoveRequest>(*json);
|
||||
if (!request || request->room.empty() || request->queueId == 0)
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"room and queueId are required");
|
||||
auto client = resolveTeamSpeakClient(rpcId);
|
||||
if (!client) return std::unexpected(client.error());
|
||||
auto result = listeningRooms_->moveQueueEntry(request->room,
|
||||
request->queueId, request->newPosition, *client);
|
||||
if (!result) return std::unexpected(result.error());
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::GetCurrentTrack)),
|
||||
[this](const std::string& /*params*/, uint64_t /*clientId*/)
|
||||
|
||||
+66
-20
@@ -3,8 +3,11 @@
|
||||
#include <Void/Plugin/Plugin.hpp>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
@@ -37,16 +40,52 @@ namespace Echoion::Core
|
||||
return "Echoion";
|
||||
}
|
||||
|
||||
// Void::Plugin::PluginLoader calls on_load() once after create
|
||||
// (first load and after a reload swap). Self-initialize from the
|
||||
// default config path so the plugin is ready without host-provided
|
||||
// wiring; idempotent via isInitialized().
|
||||
void configure(std::filesystem::path path)
|
||||
{
|
||||
configPath_ = std::move(path);
|
||||
}
|
||||
|
||||
void stageState(std::string state)
|
||||
{
|
||||
pendingState_ = std::move(state);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool ready() const noexcept { return ready_; }
|
||||
|
||||
// Configuration and state are supplied before on_load(). Keep all
|
||||
// fallible activation work here so void_plugin_ready can make the
|
||||
// manager's eventual swap transactional.
|
||||
void on_load() override
|
||||
{
|
||||
if (!isInitialized()) {
|
||||
(void)initialize(ConfigLoader::getDefaultConfigPath());
|
||||
ready_ = false;
|
||||
const auto path = configPath_.empty()
|
||||
? ConfigLoader::getDefaultConfigPath()
|
||||
: configPath_;
|
||||
if (auto result = initialize(path); !result) {
|
||||
return;
|
||||
}
|
||||
if (pendingState_.has_value()) {
|
||||
if (auto result = restoreAfterHotReload(*pendingState_); !result) {
|
||||
(void)shutdown();
|
||||
return;
|
||||
}
|
||||
pendingState_.reset();
|
||||
}
|
||||
ready_ = true;
|
||||
}
|
||||
|
||||
void on_unload() override
|
||||
{
|
||||
ready_ = false;
|
||||
if (isInitialized()) {
|
||||
(void)shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::filesystem::path configPath_;
|
||||
std::optional<std::string> pendingState_;
|
||||
bool ready_{false};
|
||||
};
|
||||
} // namespace Echoion::Core
|
||||
|
||||
@@ -80,6 +119,23 @@ extern "C"
|
||||
.description = "Echoion TeamSpeak music bot core"};
|
||||
}
|
||||
|
||||
void void_plugin_configure(void* instance, const char* config)
|
||||
{
|
||||
auto* plugin = dynamic_cast<Echoion::Core::CorePlugin*>(
|
||||
static_cast<Void::Plugin::IPlugin*>(instance));
|
||||
if (plugin != nullptr) {
|
||||
plugin->configure(config != nullptr ? std::filesystem::path{config}
|
||||
: std::filesystem::path{});
|
||||
}
|
||||
}
|
||||
|
||||
int void_plugin_ready(void* instance)
|
||||
{
|
||||
auto* plugin = dynamic_cast<Echoion::Core::CorePlugin*>(
|
||||
static_cast<Void::Plugin::IPlugin*>(instance));
|
||||
return plugin != nullptr && plugin->ready() ? 0 : -1;
|
||||
}
|
||||
|
||||
// v2 state protocol — survives layout changes across plugin versions.
|
||||
std::uint32_t void_plugin_state_version()
|
||||
{
|
||||
@@ -109,22 +165,12 @@ extern "C"
|
||||
int void_plugin_deserialize_state(void* instance, const char* json,
|
||||
std::uint32_t /*from_version*/)
|
||||
{
|
||||
auto* core = dynamic_cast<Echoion::Api::ICoreInterface*>(
|
||||
auto* plugin = dynamic_cast<Echoion::Core::CorePlugin*>(
|
||||
static_cast<Void::Plugin::IPlugin*>(instance));
|
||||
if (!core || !json) {
|
||||
if (!plugin || !json) {
|
||||
return -1;
|
||||
}
|
||||
// reload() transfers state before on_load(), so the freshly-created
|
||||
// instance is not yet initialized — bring it up first, then restore.
|
||||
// Idempotent: a no-op once initialized.
|
||||
if (!core->isInitialized()) {
|
||||
auto initResult =
|
||||
core->initialize(Echoion::Core::ConfigLoader::getDefaultConfigPath());
|
||||
if (!initResult) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
auto result = core->restoreAfterHotReload(std::string(json));
|
||||
return result ? 0 : -1;
|
||||
plugin->stageState(json);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
#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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user