diff --git a/Cargo.lock b/Cargo.lock index 3d625b6..1c3488b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9143,11 +9143,14 @@ name = "voelin-gateway-proto" version = "0.1.0" dependencies = [ "base64 0.22.1", + "futures-util", "serde", "serde_json", "sha-1", "sha2 0.10.9", "thiserror 2.0.21", + "tokio", + "tokio-tungstenite 0.30.0", "tsproto", "tsproto-types", "voelin-model", diff --git a/crates/voelin-gateway-proto/Cargo.toml b/crates/voelin-gateway-proto/Cargo.toml index 32e96e7..64ad14b 100644 --- a/crates/voelin-gateway-proto/Cargo.toml +++ b/crates/voelin-gateway-proto/Cargo.toml @@ -8,13 +8,20 @@ license.workspace = true repository.workspace = true publish.workspace = true +[features] +# A typed WebSocket client (`voelin_gateway_proto::client`). +client = ["dep:futures-util", "dep:tokio", "dep:tokio-tungstenite"] + [dependencies] base64 = "0.22" +futures-util = { version = "0.3.34", features = ["sink"], optional = true } serde = { version = "1", features = ["derive"] } serde_json = "1" sha1 = { package = "sha-1", version = "0.10" } sha2 = "0.10" thiserror = "2" +tokio = { version = "1", features = ["macros", "rt", "sync"], optional = true } +tokio-tungstenite = { version = "0.30", optional = true } voelin-model = { path = "../voelin-model" } tsproto-types = { path = "../proto/tsproto-types" } diff --git a/crates/voelin-gateway-proto/src/client.rs b/crates/voelin-gateway-proto/src/client.rs new file mode 100644 index 0000000..48b6c7c --- /dev/null +++ b/crates/voelin-gateway-proto/src/client.rs @@ -0,0 +1,734 @@ +//! A typed client (feature `client`): log in, send requests and await their +//! answers, receive pushes. +//! +//! [`GatewayClient`] is a cheap handle to a task that owns the WebSocket. +//! Requests get an envelope id; the answer with the same id completes the +//! request. Everything else (pushes, answers to requests sent with +//! [`GatewayClient::send`]) arrives on the [`Push`] receiver. +//! +//! ```no_run +//! # async fn demo(key: tsproto_types::crypto::EccKeyPrivP256) -> Result<(), voelin_gateway_proto::client::ClientError> { +//! use voelin_gateway_proto::client::{Login, connect}; +//! use voelin_model::ChatTarget; +//! let login = Login::Identity { key, key_offset: 0 }; +//! let (client, mut pushes) = connect("ws://127.0.0.1:7788/v1", login).await?; +//! if client.has(voelin_gateway_proto::feature::PINS) { +//! let pins = client.pins(ChatTarget::Channel(1)).await?; +//! } +//! while let Some(push) = pushes.recv().await { /* ... */ } +//! # Ok(()) } +//! ``` + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, RwLock}; + +use futures_util::{Sink, SinkExt, Stream, StreamExt}; +use tokio::sync::{mpsc, oneshot}; +use tokio_tungstenite::tungstenite::{self, Message}; +use tsproto_types::crypto::EccKeyPrivP256; +use voelin_model::{ChannelId, ChatMessage, ChatTarget, PresenceDelta, PresenceSnapshot}; + +use crate::messages::{ClientMsg, Envelope, ErrorCode, HistoryEntry, ServerMsg}; +use crate::types::*; + +/// How to log in. +pub enum Login { + /// Sign the challenge with a TeamSpeak identity. + Identity { + key: EccKeyPrivP256, + /// Hash-cash counter of the identity. + key_offset: u64, + }, + /// A token from an earlier login ([`GatewayClient::token`]). + Token(String), +} + +#[derive(Debug, thiserror::Error)] +pub enum ClientError { + /// The gateway answered with an error. + #[error("{code:?}: {message}")] + Gateway { code: ErrorCode, message: String }, + /// The gateway answered with a message that does not fit the request. + #[error("unexpected answer: {0}")] + Unexpected(String), + #[error("connection closed")] + Closed, + #[error("websocket: {0}")] + WebSocket(#[from] tungstenite::Error), + #[error("invalid message: {0}")] + Json(#[from] serde_json::Error), +} + +impl ClientError { + /// The gateway's error code, if the gateway refused the request. + pub fn code(&self) -> Option { + match self { + ClientError::Gateway { code, .. } => Some(*code), + _ => None, + } + } + + fn unexpected(msg: ServerMsg) -> Self { + ClientError::Unexpected(format!("{msg:?}")) + } +} + +/// Messages the gateway sends on its own, or answers to requests nobody +/// waits for. +#[derive(Clone, Debug, PartialEq)] +pub enum Push { + PresenceSnapshot(PresenceSnapshot), + PresenceDelta(PresenceDelta), + /// A message in an open chat (sessions without [`GatewayClient::enable`]). + Chat { + id: i64, + message: ChatMessage, + }, + /// A message in an open chat, with its gateway metadata. + Message(HistoryEntry), + Pinned { + target: ChatTarget, + pin: PinInfo, + }, + Unpinned { + target: ChatTarget, + message_id: i64, + by: UserRef, + }, + Reaction { + target: ChatTarget, + message_id: i64, + emoji: String, + user: UserRef, + added: bool, + count: u32, + }, + TopicUpdated(TopicInfo), + EventUpdated(EventInfo), + EventDeleted(i64), + EventReminder { + event: EventInfo, + starts_in_ms: i64, + }, + StreamStarted(StreamEntry), + StreamUpdated(StreamEntry), + StreamEnded { + id: String, + reason: String, + }, + ActivityAdded(ActivityEntry), + /// The features available to this user changed; also in + /// [`GatewayClient::capabilities`]. + Capabilities(Vec), + /// A request sent with [`GatewayClient::send`] failed. + Error { + code: ErrorCode, + message: String, + }, + /// Anything else, e.g. `ok` answers to [`GatewayClient::send`]. + Other(ServerMsg), + /// The connection ended; the last push. + Disconnected(Option), +} + +impl From for Push { + fn from(msg: ServerMsg) -> Self { + match msg { + ServerMsg::PresenceSnapshot { snapshot, .. } => Push::PresenceSnapshot(snapshot), + ServerMsg::PresenceDelta { delta, .. } => Push::PresenceDelta(delta), + ServerMsg::ChatEvent { id, message } => Push::Chat { id, message }, + ServerMsg::Message { entry } => Push::Message(entry), + ServerMsg::Pinned { target, pin } => Push::Pinned { target, pin }, + ServerMsg::Unpinned { target, message_id, by } => { + Push::Unpinned { target, message_id, by } + } + ServerMsg::Reaction { target, message_id, emoji, user, added, count } => { + Push::Reaction { target, message_id, emoji, user, added, count } + } + ServerMsg::TopicUpdated { topic } => Push::TopicUpdated(topic), + ServerMsg::EventUpdated { event } => Push::EventUpdated(event), + ServerMsg::EventDeleted { id } => Push::EventDeleted(id), + ServerMsg::EventReminder { event, starts_in_ms } => { + Push::EventReminder { event, starts_in_ms } + } + ServerMsg::StreamStarted { stream } => Push::StreamStarted(stream), + ServerMsg::StreamUpdated { stream } => Push::StreamUpdated(stream), + ServerMsg::StreamEnded { id, reason } => Push::StreamEnded { id, reason }, + ServerMsg::ActivityAdded { entry } => Push::ActivityAdded(entry), + ServerMsg::Capabilities { capabilities } => Push::Capabilities(capabilities), + ServerMsg::Error { code, message } => Push::Error { code, message }, + other => Push::Other(other), + } + } +} + +/// What the gateway said about itself and the user at login. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SessionInfo { + pub gateway_id: String, + pub server_uid: String, + pub server_name: String, + /// The user's unique id on the server. + pub uid: String, + pub token: String, + /// Unix seconds. + pub token_expires: i64, +} + +struct Outgoing { + id: u64, + msg: ClientMsg, + reply: Option>, +} + +/// Handle to a logged-in gateway connection. Clones share the connection; +/// it closes when the last handle is dropped. +#[derive(Clone)] +pub struct GatewayClient { + out: mpsc::UnboundedSender, + info: Arc, + capabilities: Arc>>, + next_id: Arc, +} + +/// Connect to `url` (e.g. `ws://127.0.0.1:7788/v1`) and log in. +pub async fn connect( + url: &str, + login: Login, +) -> Result<(GatewayClient, mpsc::UnboundedReceiver), ClientError> { + use tokio_tungstenite::tungstenite::client::IntoClientRequest; + let mut request = url.into_client_request()?; + request.headers_mut().insert( + "Sec-WebSocket-Protocol", + tungstenite::http::HeaderValue::from_static(crate::SUBPROTOCOL), + ); + let (ws, _) = tokio_tungstenite::connect_async(request).await?; + GatewayClient::start(ws, login).await +} + +fn now_secs() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or_default() +} + +async fn recv(ws: &mut S) -> Result, ClientError> +where + S: Stream> + Unpin, +{ + loop { + match ws.next().await { + Some(Ok(Message::Text(text))) => return Ok(serde_json::from_str(text.as_str())?), + Some(Ok(Message::Close(_))) | None => return Err(ClientError::Closed), + Some(Ok(_)) => continue, + Some(Err(e)) => return Err(e.into()), + } + } +} + +async fn send_frame(ws: &mut S, id: u64, msg: ClientMsg) -> Result<(), ClientError> +where + S: Sink + Unpin, +{ + let text = serde_json::to_string(&Envelope::with_id(id, msg))?; + ws.send(Message::Text(text.into())).await?; + Ok(()) +} + +impl GatewayClient { + /// Log in over an open WebSocket (subprotocol [`crate::SUBPROTOCOL`]) and + /// start the connection task. + pub async fn start( + mut ws: S, + login: Login, + ) -> Result<(Self, mpsc::UnboundedReceiver), ClientError> + where + S: Stream> + + Sink + + Unpin + + Send + + 'static, + { + let (gateway_id, server_uid, server_name, nonce) = match recv(&mut ws).await?.msg { + ServerMsg::Hello { gateway_id, server_uid, server_name, nonce, .. } => { + (gateway_id, server_uid, server_name, nonce) + } + other => return Err(ClientError::unexpected(other)), + }; + let msg = match login { + Login::Identity { key, key_offset } => { + let ts = now_secs(); + ClientMsg::Auth { + omega: key.to_pub().to_ts(), + key_offset, + ts, + signature: crate::sign_challenge(&key, &gateway_id, &server_uid, &nonce, ts), + nickname: String::new(), + } + } + Login::Token(token) => ClientMsg::Resume { token, nickname: String::new() }, + }; + send_frame(&mut ws, 1, msg).await?; + let (uid, token, token_expires, capabilities) = match recv(&mut ws).await?.msg { + ServerMsg::AuthOk { uid, token, token_expires, capabilities } => { + (uid, token, token_expires, capabilities) + } + ServerMsg::Error { code, message } => { + return Err(ClientError::Gateway { code, message }); + } + other => return Err(ClientError::unexpected(other)), + }; + let info = Arc::new(SessionInfo { + gateway_id, + server_uid, + server_name, + uid, + token, + token_expires, + }); + let capabilities = Arc::new(RwLock::new(capabilities)); + let (out, out_rx) = mpsc::unbounded_channel(); + let (push_tx, pushes) = mpsc::unbounded_channel(); + tokio::spawn(run(ws, out_rx, push_tx, capabilities.clone())); + Ok((Self { out, info, capabilities, next_id: Arc::new(AtomicU64::new(2)) }, pushes)) + } + + pub fn info(&self) -> &SessionInfo { + &self.info + } + + /// The user's unique id on the server. + pub fn uid(&self) -> &str { + &self.info.uid + } + + /// Log in again with this instead of a signature ([`Login::Token`]). + pub fn token(&self) -> &str { + &self.info.token + } + + /// Features available to this user (see [`crate::feature`]); kept up to + /// date while connected. Hide what is missing. + pub fn capabilities(&self) -> Vec { + self.capabilities.read().unwrap().clone() + } + + pub fn has(&self, feature: &str) -> bool { + self.capabilities.read().unwrap().iter().any(|c| c == feature) + } + + pub fn is_connected(&self) -> bool { + !self.out.is_closed() + } + + /// Send without waiting; the answer arrives as a [`Push`]. + pub fn send(&self, msg: ClientMsg) -> Result<(), ClientError> { + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + self.out.send(Outgoing { id, msg, reply: None }).map_err(|_| ClientError::Closed) + } + + /// Send and wait for the answer. An `error` answer is returned as + /// [`ClientError::Gateway`]. + pub async fn request(&self, msg: ClientMsg) -> Result { + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + let (reply, rx) = oneshot::channel(); + self.out.send(Outgoing { id, msg, reply: Some(reply) }).map_err(|_| ClientError::Closed)?; + match rx.await.map_err(|_| ClientError::Closed)? { + ServerMsg::Error { code, message } => Err(ClientError::Gateway { code, message }), + msg => Ok(msg), + } + } + + async fn ok(&self, msg: ClientMsg) -> Result<(), ClientError> { + match self.request(msg).await? { + ServerMsg::Ok => Ok(()), + other => Err(ClientError::unexpected(other)), + } + } +} + +/// Typed requests. Chat and presence pushes need the matching +/// open/subscribe request; extension pushes for open chats need +/// [`GatewayClient::enable`]. +impl GatewayClient { + /// Start the presence stream; the snapshot arrives as a push. + pub fn subscribe_presence(&self) -> Result<(), ClientError> { + self.send(ClientMsg::SubscribePresence) + } + + pub async fn unsubscribe_presence(&self) -> Result<(), ClientError> { + self.ok(ClientMsg::UnsubscribePresence).await + } + + pub async fn open_chat(&self, target: ChatTarget) -> Result<(), ClientError> { + self.ok(ClientMsg::OpenChat { target }).await + } + + pub async fn close_chat(&self, target: ChatTarget) -> Result<(), ClientError> { + self.ok(ClientMsg::CloseChat { target }).await + } + + pub async fn send_chat(&self, target: ChatTarget, text: String) -> Result<(), ClientError> { + self.ok(ClientMsg::SendChat { target, text }).await + } + + pub async fn ping(&self) -> Result<(), ClientError> { + match self.request(ClientMsg::Ping).await? { + ServerMsg::Pong => Ok(()), + other => Err(ClientError::unexpected(other)), + } + } + + /// Receive the extension pushes for open chats; returns the features enabled. + pub async fn enable(&self, features: Vec) -> Result, ClientError> { + match self.request(ClientMsg::Enable { features }).await? { + ServerMsg::Enabled { features } => Ok(features), + other => Err(ClientError::unexpected(other)), + } + } + + /// What the user may do, server-wide or in `channel`. + pub async fn permissions( + &self, + channel: Option, + ) -> Result, ClientError> { + match self.request(ClientMsg::Permissions { channel }).await? { + ServerMsg::Permissions { actions, .. } => Ok(actions), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn history(&self, query: HistoryQuery) -> Result { + match self.request(ClientMsg::QueryHistory(query)).await? { + ServerMsg::HistoryPage(page) => Ok(page), + other => Err(ClientError::unexpected(other)), + } + } + + /// New and changed messages since `since_rev`; returns them with the + /// revision to pass next time and whether more are waiting. + pub async fn sync( + &self, + target: ChatTarget, + since_rev: i64, + limit: Option, + ) -> Result<(Vec, i64, bool), ClientError> { + match self.request(ClientMsg::Sync { target, since_rev, limit }).await? { + ServerMsg::SyncPage { messages, rev, has_more, .. } => Ok((messages, rev, has_more)), + other => Err(ClientError::unexpected(other)), + } + } + + /// Post, optionally into a topic; returns the stored message. + pub async fn post( + &self, + target: ChatTarget, + text: String, + topic: Option, + ) -> Result { + match self.request(ClientMsg::Post { target, text, topic }).await? { + ServerMsg::Posted { entry } => Ok(entry), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn pin(&self, message_id: i64) -> Result<(), ClientError> { + self.ok(ClientMsg::Pin { message_id }).await + } + + pub async fn unpin(&self, message_id: i64) -> Result<(), ClientError> { + self.ok(ClientMsg::Unpin { message_id }).await + } + + pub async fn pins(&self, target: ChatTarget) -> Result, ClientError> { + match self.request(ClientMsg::ListPins { target }).await? { + ServerMsg::Pins { pins, .. } => Ok(pins), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn react(&self, message_id: i64, emoji: String) -> Result<(), ClientError> { + self.ok(ClientMsg::React { message_id, emoji }).await + } + + pub async fn unreact(&self, message_id: i64, emoji: String) -> Result<(), ClientError> { + self.ok(ClientMsg::Unreact { message_id, emoji }).await + } + + pub async fn reactors( + &self, + message_id: i64, + emoji: String, + ) -> Result, ClientError> { + match self.request(ClientMsg::Reactors { message_id, emoji }).await? { + ServerMsg::Reactors { users, .. } => Ok(users), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn create_topic( + &self, + target: ChatTarget, + title: String, + message_id: Option, + ) -> Result { + self.topic(ClientMsg::CreateTopic { target, title, message_id }).await + } + + pub async fn update_topic( + &self, + topic_id: i64, + title: Option, + archived: Option, + ) -> Result { + self.topic(ClientMsg::UpdateTopic { topic_id, title, archived }).await + } + + async fn topic(&self, msg: ClientMsg) -> Result { + match self.request(msg).await? { + ServerMsg::Topic { topic } => Ok(topic), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn topics( + &self, + target: ChatTarget, + include_archived: bool, + ) -> Result, ClientError> { + match self.request(ClientMsg::ListTopics { target, include_archived }).await? { + ServerMsg::Topics { topics, .. } => Ok(topics), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn create_event(&self, event: EventSpec) -> Result { + self.event_reply(ClientMsg::CreateEvent { event }).await + } + + pub async fn update_event(&self, id: i64, event: EventSpec) -> Result { + self.event_reply(ClientMsg::UpdateEvent { id, event }).await + } + + pub async fn delete_event(&self, id: i64) -> Result<(), ClientError> { + self.ok(ClientMsg::DeleteEvent { id }).await + } + + /// One event with its attendees. + pub async fn event(&self, id: i64) -> Result { + self.event_reply(ClientMsg::GetEvent { id }).await + } + + pub async fn events(&self, query: EventQuery) -> Result, ClientError> { + match self.request(ClientMsg::ListEvents(query)).await? { + ServerMsg::Events { events } => Ok(events), + other => Err(ClientError::unexpected(other)), + } + } + + /// Answer an event; `None` withdraws the answer. + pub async fn rsvp( + &self, + event_id: i64, + status: Option, + ) -> Result { + self.event_reply(ClientMsg::Rsvp { event_id, status }).await + } + + async fn event_reply(&self, msg: ClientMsg) -> Result { + match self.request(msg).await? { + ServerMsg::Event { event } => Ok(event), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn subscribe_events(&self) -> Result<(), ClientError> { + self.ok(ClientMsg::SubscribeEvents).await + } + + pub async fn unsubscribe_events(&self) -> Result<(), ClientError> { + self.ok(ClientMsg::UnsubscribeEvents).await + } + + pub async fn register_stream(&self, stream: StreamSpec) -> Result { + self.stream_reply(ClientMsg::RegisterStream(stream)).await + } + + pub async fn update_stream( + &self, + stream_id: String, + title: Option, + viewers: Option, + ) -> Result { + self.stream_reply(ClientMsg::UpdateStream { stream_id, title, viewers }).await + } + + async fn stream_reply(&self, msg: ClientMsg) -> Result { + match self.request(msg).await? { + ServerMsg::Stream { stream } => Ok(stream), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn unregister_stream(&self, stream_id: String) -> Result<(), ClientError> { + self.ok(ClientMsg::UnregisterStream { stream_id }).await + } + + pub async fn streams(&self) -> Result, ClientError> { + self.streams_reply(ClientMsg::ListStreams).await + } + + /// Returns the directory; changes follow as pushes. + pub async fn subscribe_streams(&self) -> Result, ClientError> { + self.streams_reply(ClientMsg::SubscribeStreams).await + } + + async fn streams_reply(&self, msg: ClientMsg) -> Result, ClientError> { + match self.request(msg).await? { + ServerMsg::Streams { streams } => Ok(streams), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn unsubscribe_streams(&self) -> Result<(), ClientError> { + self.ok(ClientMsg::UnsubscribeStreams).await + } + + /// Newest first; returns the entries and whether older ones exist. + pub async fn activity( + &self, + before: Option, + limit: Option, + ) -> Result<(Vec, bool), ClientError> { + match self.request(ClientMsg::ListActivity { before, limit }).await? { + ServerMsg::Activity { entries, has_more } => Ok((entries, has_more)), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn subscribe_activity(&self) -> Result<(), ClientError> { + self.ok(ClientMsg::SubscribeActivity).await + } + + pub async fn unsubscribe_activity(&self) -> Result<(), ClientError> { + self.ok(ClientMsg::UnsubscribeActivity).await + } + + pub async fn config_list(&self) -> Result, ClientError> { + self.config_entries(ClientMsg::ConfigList).await + } + + /// Read the gateway's file again; returns the resulting configuration. + pub async fn config_reload(&self) -> Result, ClientError> { + self.config_entries(ClientMsg::ConfigReload).await + } + + async fn config_entries(&self, msg: ClientMsg) -> Result, ClientError> { + match self.request(msg).await? { + ServerMsg::Config { entries } => Ok(entries), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn config_get(&self, key: String) -> Result { + self.config_value(ClientMsg::ConfigGet { key }).await + } + + pub async fn config_set( + &self, + key: String, + value: serde_json::Value, + ) -> Result { + self.config_value(ClientMsg::ConfigSet { key, value }).await + } + + pub async fn config_reset(&self, key: String) -> Result { + self.config_value(ClientMsg::ConfigReset { key }).await + } + + async fn config_value(&self, msg: ClientMsg) -> Result { + match self.request(msg).await? { + ServerMsg::ConfigValue { entry } => Ok(entry), + other => Err(ClientError::unexpected(other)), + } + } + + pub async fn perm_list(&self) -> Result, ClientError> { + self.perm_rules(ClientMsg::PermList).await + } + + pub async fn perm_set( + &self, + action: Action, + rule: PermRule, + ) -> Result, ClientError> { + self.perm_rules(ClientMsg::PermSet { action, rule }).await + } + + pub async fn perm_reset(&self, action: Action) -> Result, ClientError> { + self.perm_rules(ClientMsg::PermReset { action }).await + } + + async fn perm_rules(&self, msg: ClientMsg) -> Result, ClientError> { + match self.request(msg).await? { + ServerMsg::PermRules { rules } => Ok(rules), + other => Err(ClientError::unexpected(other)), + } + } +} + +/// The connection task: frames out, answers to their requests, pushes to +/// the receiver. +async fn run( + mut ws: S, + mut out: mpsc::UnboundedReceiver, + pushes: mpsc::UnboundedSender, + capabilities: Arc>>, +) where + S: Stream> + + Sink + + Unpin + + Send + + 'static, +{ + let mut pending: HashMap> = HashMap::new(); + let reason = loop { + tokio::select! { + frame = recv(&mut ws) => { + let env = match frame { + Ok(env) => env, + // A push of a type this version does not know. + Err(ClientError::Json(_)) => continue, + Err(ClientError::Closed) => break None, + Err(e) => break Some(e.to_string()), + }; + if let ServerMsg::Capabilities { capabilities: caps } = &env.msg { + *capabilities.write().unwrap() = caps.clone(); + } + match env.id.and_then(|id| pending.remove(&id)) { + Some(waiter) => { + let _ = waiter.send(env.msg); + } + None => { + let _ = pushes.send(env.msg.into()); + } + } + } + msg = out.recv() => { + let Some(Outgoing { id, msg, reply }) = msg else { + let _ = ws.close().await; + break None; + }; + if let Some(reply) = reply { + pending.insert(id, reply); + } + if let Err(e) = send_frame(&mut ws, id, msg).await { + break Some(e.to_string()); + } + } + } + }; + let _ = pushes.send(Push::Disconnected(reason)); +} diff --git a/crates/voelin-gateway-proto/src/lib.rs b/crates/voelin-gateway-proto/src/lib.rs index 3062125..6e5cf0c 100644 --- a/crates/voelin-gateway-proto/src/lib.rs +++ b/crates/voelin-gateway-proto/src/lib.rs @@ -3,22 +3,34 @@ //! //! Transport: WebSocket, subprotocol [`SUBPROTOCOL`], one JSON [`Envelope`] //! per text frame. Within version 1 changes are additive only: new message -//! types and optional fields. Unknown fields must be ignored. +//! types and optional fields. Unknown fields must be ignored. The gateway +//! answers message types it does not know with [`ErrorCode::UnknownType`] +//! and keeps the connection; it only pushes newer message types to clients +//! that asked for them. //! //! Authentication proves ownership of a TeamSpeak identity: the gateway sends //! a nonce in [`ServerMsg::Hello`], the client answers with //! [`ClientMsg::Auth`], an ECDSA P-256 signature over [`challenge`] made with //! the identity's private key. The unique id is derived from the public key, //! exactly as the TeamSpeak server does. +//! +//! Besides presence and chat, gateways can offer pins, reactions, topics, +//! scheduled events, a directory of running streams, an activity feed and +//! runtime administration; [`ServerMsg::Hello`] lists what is enabled +//! ([`feature`]). The `client` feature adds a typed client ([`client`]). mod auth; +#[cfg(feature = "client")] +pub mod client; mod messages; +mod types; pub use auth::{ AuthError, MAX_CLOCK_SKEW_SECS, UniqueIds, challenge, identity_level, sign_challenge, verify_auth, }; pub use messages::*; +pub use types::*; /// WebSocket subprotocol. pub const SUBPROTOCOL: &str = "tsgw.v1+json"; diff --git a/crates/voelin-gateway-proto/src/messages.rs b/crates/voelin-gateway-proto/src/messages.rs index 9b8c8f0..2f47a4a 100644 --- a/crates/voelin-gateway-proto/src/messages.rs +++ b/crates/voelin-gateway-proto/src/messages.rs @@ -1,7 +1,14 @@ //! Messages in both directions. +//! +//! The first block of each enum is the original protocol; everything after +//! it was added later. A client only receives the newer pushes after it sent +//! [`ClientMsg::Enable`] (chat extensions) or the matching subscribe request, +//! so older clients never see a message type they do not know. use serde::{Deserialize, Serialize}; -use voelin_model::{ChatMessage, ChatTarget, PresenceDelta, PresenceSnapshot}; +use voelin_model::{ChannelId, ChatMessage, ChatTarget, PresenceDelta, PresenceSnapshot}; + +use crate::types::*; /// Every frame: `{"v":1,"id":7,"type":"send_chat","data":{...}}`. /// @@ -62,6 +69,7 @@ pub enum ClientMsg { text: String, }, /// Up to `limit` messages before message id `before` (latest when absent). + /// [`ClientMsg::QueryHistory`] has more ways to page. History { target: ChatTarget, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -69,6 +77,173 @@ pub enum ClientMsg { limit: u32, }, Ping, + + // Extensions. Gateways without them answer `error` with `unknown_type`; + // the capabilities in `hello` and `auth_ok` say what is there. + /// Receive the extension pushes for open chats: [`ServerMsg::Message`] + /// instead of [`ServerMsg::ChatEvent`], and pins, reactions and topics of + /// the listed features (empty: all). Answer: [`ServerMsg::Enabled`]. + Enable { + #[serde(default)] + features: Vec, + }, + /// What this user may do, server-wide or in a channel. Answer: + /// [`ServerMsg::Permissions`]. + Permissions { + #[serde(default, skip_serializing_if = "Option::is_none")] + channel: Option, + }, + /// Page through stored messages. Answer: [`ServerMsg::HistoryPage`]. + QueryHistory(HistoryQuery), + /// Messages of a chat that are new or changed (pins, reactions, topic) + /// since revision `since_rev`, by revision. Answer: [`ServerMsg::SyncPage`]. + Sync { + target: ChatTarget, + #[serde(default)] + since_rev: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + limit: Option, + }, + /// Like [`ClientMsg::SendChat`], optionally into a topic; answered with + /// the stored message ([`ServerMsg::Posted`]). + Post { + target: ChatTarget, + text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + topic: Option, + }, + Pin { + message_id: i64, + }, + Unpin { + message_id: i64, + }, + /// Answer: [`ServerMsg::Pins`]. + ListPins { + target: ChatTarget, + }, + React { + message_id: i64, + emoji: String, + }, + Unreact { + message_id: i64, + emoji: String, + }, + /// Who reacted with `emoji`. Answer: [`ServerMsg::Reactors`]. + Reactors { + message_id: i64, + emoji: String, + }, + /// Start a topic, from a message or standalone. Answer: [`ServerMsg::Topic`]. + CreateTopic { + target: ChatTarget, + title: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + message_id: Option, + }, + /// Rename or (un)archive a topic. Answer: [`ServerMsg::Topic`]. + UpdateTopic { + topic_id: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + archived: Option, + }, + /// Answer: [`ServerMsg::Topics`], most recently active first. + ListTopics { + target: ChatTarget, + #[serde(default)] + include_archived: bool, + }, + /// Answer: [`ServerMsg::Event`]. + CreateEvent { + event: EventSpec, + }, + /// Answer: [`ServerMsg::Event`]. + UpdateEvent { + id: i64, + event: EventSpec, + }, + DeleteEvent { + id: i64, + }, + /// One event with its attendees. Answer: [`ServerMsg::Event`]. + GetEvent { + id: i64, + }, + /// Answer: [`ServerMsg::Events`], by start time. + ListEvents(EventQuery), + /// Answer an invitation; `None` withdraws the answer. Answer: [`ServerMsg::Event`]. + Rsvp { + event_id: i64, + #[serde(default)] + status: Option, + }, + /// Receive [`ServerMsg::EventUpdated`], [`ServerMsg::EventDeleted`] and + /// [`ServerMsg::EventReminder`]. + SubscribeEvents, + UnsubscribeEvents, + /// Add the user's running stream to the directory. Answer: [`ServerMsg::Stream`]. + RegisterStream(StreamSpec), + /// Answer: [`ServerMsg::Stream`]. + UpdateStream { + stream_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + viewers: Option, + }, + UnregisterStream { + stream_id: String, + }, + /// Answer: [`ServerMsg::Streams`]. + ListStreams, + /// Answered with [`ServerMsg::Streams`], then [`ServerMsg::StreamStarted`], + /// [`ServerMsg::StreamUpdated`] and [`ServerMsg::StreamEnded`] as they happen. + SubscribeStreams, + UnsubscribeStreams, + /// Newest first, entries with an id below `before`. Answer: [`ServerMsg::Activity`]. + ListActivity { + #[serde(default, skip_serializing_if = "Option::is_none")] + before: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + limit: Option, + }, + /// Receive [`ServerMsg::ActivityAdded`]. + SubscribeActivity, + UnsubscribeActivity, + /// Administration (needs the `admin` capability). Answer: [`ServerMsg::Config`]. + ConfigList, + /// Answer: [`ServerMsg::ConfigValue`]. + ConfigGet { + key: String, + }, + /// Store a value in the gateway's database; it wins over the command + /// line, environment and file and applies at once. Answer: + /// [`ServerMsg::ConfigValue`]. + ConfigSet { + key: String, + value: serde_json::Value, + }, + /// Drop the stored value (back to command line, environment, file or + /// default). Answer: [`ServerMsg::ConfigValue`]. + ConfigReset { + key: String, + }, + /// Read the file again (like `SIGHUP`). Answer: [`ServerMsg::Config`]. + ConfigReload, + /// Answer: [`ServerMsg::PermRules`]. + PermList, + /// Set the rule of an action. Answer: [`ServerMsg::PermRules`]. + PermSet { + action: Action, + rule: PermRule, + }, + /// Back to the file's rule or the built-in default. Answer: [`ServerMsg::PermRules`]. + PermReset { + action: Action, + }, } /// Gateway to client. @@ -81,7 +256,7 @@ pub enum ServerMsg { server_uid: String, server_name: String, nonce: String, - /// Optional features, e.g. `history`. + /// Enabled features, see [`crate::feature`]. #[serde(default)] capabilities: Vec, }, @@ -91,6 +266,10 @@ pub enum ServerMsg { token: String, /// Unix time in seconds. token_expires: i64, + /// Features for this user: those of `hello`, plus `admin` if the user + /// may administer the gateway. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + capabilities: Vec, }, /// Presence restricted to what this user may see. `seq` restarts at 0 with /// each snapshot and increases by one per delta. @@ -117,12 +296,171 @@ pub enum ServerMsg { message: String, }, Pong, + + // Extensions: answers to the new requests, and pushes (without `id`) for + // sessions that asked for them. + Enabled { + features: Vec, + }, + /// Push: the features available to this user changed. + Capabilities { + capabilities: Vec, + }, + Permissions { + #[serde(default, skip_serializing_if = "Option::is_none")] + channel: Option, + actions: Vec, + }, + HistoryPage(HistoryPage), + SyncPage { + target: ChatTarget, + /// By revision. + messages: Vec, + /// Pass as `since_rev` next time. + rev: i64, + #[serde(default)] + has_more: bool, + }, + /// Push: a message in an open chat, for sessions that sent [`ClientMsg::Enable`]. + Message { + entry: HistoryEntry, + }, + Posted { + entry: HistoryEntry, + }, + /// Push to sessions with the chat open. + Pinned { + target: ChatTarget, + pin: PinInfo, + }, + /// Push to sessions with the chat open. + Unpinned { + target: ChatTarget, + message_id: i64, + by: UserRef, + }, + Pins { + target: ChatTarget, + pins: Vec, + }, + /// Push to sessions with the chat open: `user` added or removed `emoji`; + /// `count` is the new total for that emoji. + Reaction { + target: ChatTarget, + message_id: i64, + emoji: String, + user: UserRef, + added: bool, + count: u32, + }, + Reactors { + message_id: i64, + emoji: String, + users: Vec, + }, + Topic { + topic: TopicInfo, + }, + /// Push to sessions with the chat open: created, renamed, archived or + /// new activity. + TopicUpdated { + topic: TopicInfo, + }, + Topics { + target: ChatTarget, + topics: Vec, + }, + Event { + event: EventInfo, + }, + Events { + events: Vec, + }, + /// Push: created or changed (including RSVP counts and going live). + EventUpdated { + event: EventInfo, + }, + /// Push. + EventDeleted { + id: i64, + }, + /// Push at the configured times before an event starts (0: it starts). + EventReminder { + event: EventInfo, + starts_in_ms: i64, + }, + Stream { + stream: StreamEntry, + }, + Streams { + streams: Vec, + }, + /// Push. + StreamStarted { + stream: StreamEntry, + }, + /// Push. + StreamUpdated { + stream: StreamEntry, + }, + /// Push. + StreamEnded { + id: String, + reason: String, + }, + /// Newest first. + Activity { + entries: Vec, + #[serde(default)] + has_more: bool, + }, + /// Push. + ActivityAdded { + entry: ActivityEntry, + }, + Config { + entries: Vec, + }, + ConfigValue { + entry: ConfigEntry, + }, + PermRules { + rules: Vec, + }, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +/// A stored message. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct HistoryEntry { + /// Stable gateway id; orders the messages of a chat. pub id: i64, pub message: ChatMessage, + /// The topic the message was posted in. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub topic_id: Option, + /// In order of the first reaction. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub reactions: Vec, + #[serde(default, skip_serializing_if = "is_false")] + pub pinned: bool, + /// Revision of the last change (post, pin, reaction, topic), for + /// [`ClientMsg::Sync`]. + #[serde(default, skip_serializing_if = "is_zero")] + pub rev: i64, +} + +impl HistoryEntry { + pub fn new(id: i64, message: ChatMessage) -> Self { + Self { id, message, topic_id: None, reactions: Vec::new(), pinned: false, rev: 0 } + } +} + +fn is_false(b: &bool) -> bool { + !*b +} + +fn is_zero(n: &i64) -> bool { + *n == 0 } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -145,41 +483,20 @@ pub enum ErrorCode { /// Temporary problem talking to the TeamSpeak server. Unavailable, Internal, + /// The message type is not known to this gateway. + UnknownType, + /// The message, topic, event, stream or key does not exist (any more). + NotFound, + /// A quota set by the gateway's admin is reached. + QuotaExceeded, + /// Too many requests; try again later. + RateLimited, + /// The feature is turned off on this gateway. + FeatureDisabled, + /// Sent by a newer gateway. + #[serde(other)] + Unknown, } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn envelope_json_shape() { - let env = Envelope::with_id( - 7, - ClientMsg::SendChat { target: ChatTarget::Channel(5), text: "hi".into() }, - ); - let json = serde_json::to_string(&env).unwrap(); - assert_eq!( - json, - r#"{"v":1,"id":7,"type":"send_chat","data":{"target":{"kind":"channel","id":5},"text":"hi"}}"# - ); - let back: Envelope = serde_json::from_str(&json).unwrap(); - assert_eq!(back, env); - - let ping = serde_json::to_string(&Envelope::new(ClientMsg::Ping)).unwrap(); - assert_eq!(ping, r#"{"v":1,"type":"ping"}"#); - assert_eq!( - serde_json::to_string(&Envelope::new(ServerMsg::Ok)).unwrap(), - r#"{"v":1,"type":"ok"}"# - ); - } - - #[test] - fn ignores_unknown_fields() { - let json = r#"{"v":1,"type":"history","data":{"target":{"kind":"server"},"limit":5,"future":true},"extra":1}"#; - let env: Envelope = serde_json::from_str(json).unwrap(); - assert_eq!( - env.msg, - ClientMsg::History { target: ChatTarget::Server, before: None, limit: 5 } - ); - } -} +mod tests; diff --git a/crates/voelin-gateway-proto/src/messages/tests.rs b/crates/voelin-gateway-proto/src/messages/tests.rs new file mode 100644 index 0000000..abcb46e --- /dev/null +++ b/crates/voelin-gateway-proto/src/messages/tests.rs @@ -0,0 +1,435 @@ +use serde_json::json; +use voelin_model::ClientInfo; + +use super::*; + +fn chat(text: &str) -> ChatMessage { + ChatMessage { + target: ChatTarget::Channel(5), + author_name: "Alice".into(), + author_uid: Some("uid-a".into()), + author_id: None, + text: text.into(), + ts_ms: 1_700_000_000_123, + via_relay: true, + } +} + +fn entry() -> HistoryEntry { + HistoryEntry { + id: 42, + message: chat("hi"), + topic_id: Some(3), + reactions: vec![ReactionCount { emoji: "👍".into(), count: 2, me: true }], + pinned: true, + rev: 1_700_000_000_123_001, + } +} + +fn user() -> UserRef { + UserRef { uid: "uid-a".into(), name: "Alice".into() } +} + +fn topic() -> TopicInfo { + TopicInfo { + id: 3, + target: ChatTarget::Channel(5), + title: "Raid".into(), + creator: user(), + created_ms: 1, + root_message_id: Some(42), + last_activity_ms: 2, + message_count: 7, + archived: false, + } +} + +fn event() -> EventInfo { + EventInfo { + id: 9, + spec: EventSpec { + title: "Movie night".into(), + description: "bring snacks".into(), + start_ms: 1000, + end_ms: Some(2000), + channel: Some(5), + kind: EventKind::Stream, + stream_title: Some("Film".into()), + stream_game: None, + host_uid: None, + }, + creator: user(), + created_ms: 1, + updated_ms: 2, + going: 3, + maybe: 1, + not_going: 0, + my_rsvp: Some(RsvpStatus::Going), + attendees: vec![Attendee { user: user(), status: RsvpStatus::Going, ts_ms: 5 }], + live_stream: Some("s-1".into()), + } +} + +fn stream() -> StreamEntry { + StreamEntry { + id: "s-1".into(), + stream_id: Some("s-1".into()), + streamer: user(), + client_id: Some(7), + channel: Some(5), + title: "Coding".into(), + kind: "screen".into(), + started_ms: 10, + viewers: Some(2), + source: StreamSource::Registered, + event_id: Some(9), + } +} + +fn activity() -> ActivityEntry { + ActivityEntry { + id: 1, + ts_ms: 10, + kind: activity_kind::STREAM_STARTED.into(), + actor: Some(user()), + channel: Some(5), + ref_id: Some("s-1".into()), + text: "Alice started streaming".into(), + data: json!({"title": "Coding"}), + } +} + +fn config_entry() -> ConfigEntry { + ConfigEntry { + key: "history.retention_days".into(), + value: json!(0), + source: ConfigSource::Db, + default: json!(0), + value_type: "int".into(), + description: "days".into(), + bootstrap: false, + } +} + +fn rule() -> PermRule { + PermRule { everyone: false, server_groups: vec![6], channel_groups: vec![5] } +} + +fn roundtrip(msg: M) +where + M: Serialize + for<'de> Deserialize<'de> + PartialEq + std::fmt::Debug + Clone, +{ + let env = Envelope::with_id(3, msg); + let json = serde_json::to_string(&env).unwrap(); + let back: Envelope = serde_json::from_str(&json).unwrap_or_else(|e| panic!("{json}: {e}")); + assert_eq!(back, env, "{json}"); +} + +#[test] +fn envelope_json_shape() { + let env = Envelope::with_id( + 7, + ClientMsg::SendChat { target: ChatTarget::Channel(5), text: "hi".into() }, + ); + let json = serde_json::to_string(&env).unwrap(); + assert_eq!( + json, + r#"{"v":1,"id":7,"type":"send_chat","data":{"target":{"kind":"channel","id":5},"text":"hi"}}"# + ); + let back: Envelope = serde_json::from_str(&json).unwrap(); + assert_eq!(back, env); + + let ping = serde_json::to_string(&Envelope::new(ClientMsg::Ping)).unwrap(); + assert_eq!(ping, r#"{"v":1,"type":"ping"}"#); + assert_eq!( + serde_json::to_string(&Envelope::new(ServerMsg::Ok)).unwrap(), + r#"{"v":1,"type":"ok"}"# + ); +} + +#[test] +fn ignores_unknown_fields() { + let json = r#"{"v":1,"type":"history","data":{"target":{"kind":"server"},"limit":5,"future":true},"extra":1}"#; + let env: Envelope = serde_json::from_str(json).unwrap(); + assert_eq!(env.msg, ClientMsg::History { target: ChatTarget::Server, before: None, limit: 5 }); +} + +#[test] +fn every_client_message_roundtrips() { + let target = ChatTarget::Channel(5); + let msgs = vec![ + ClientMsg::Auth { + omega: "o".into(), + key_offset: 1, + ts: 2, + signature: "s".into(), + nickname: "n".into(), + }, + ClientMsg::Resume { token: "t".into(), nickname: "n".into() }, + ClientMsg::SubscribePresence, + ClientMsg::UnsubscribePresence, + ClientMsg::OpenChat { target: target.clone() }, + ClientMsg::CloseChat { target: ChatTarget::Server }, + ClientMsg::SendChat { target: target.clone(), text: "x".into() }, + ClientMsg::History { target: target.clone(), before: Some(3), limit: 10 }, + ClientMsg::Ping, + ClientMsg::Enable { features: vec![feature::PINS.into()] }, + ClientMsg::Permissions { channel: Some(5) }, + ClientMsg::QueryHistory(HistoryQuery { + target: target.clone(), + before: Some(100), + after: Some(10), + before_ms: Some(5), + after_ms: Some(1), + limit: Some(500), + topic: Some(3), + exclude_topics: true, + }), + ClientMsg::QueryHistory(HistoryQuery::latest(ChatTarget::Server, None)), + ClientMsg::Sync { target: target.clone(), since_rev: 77, limit: None }, + ClientMsg::Post { target: target.clone(), text: "t".into(), topic: Some(3) }, + ClientMsg::Pin { message_id: 1 }, + ClientMsg::Unpin { message_id: 1 }, + ClientMsg::ListPins { target: target.clone() }, + ClientMsg::React { message_id: 1, emoji: "🏳️‍🌈".into() }, + ClientMsg::Unreact { message_id: 1, emoji: "👍🏽".into() }, + ClientMsg::Reactors { message_id: 1, emoji: "👍".into() }, + ClientMsg::CreateTopic { target: target.clone(), title: "t".into(), message_id: Some(1) }, + ClientMsg::UpdateTopic { topic_id: 3, title: None, archived: Some(true) }, + ClientMsg::ListTopics { target: target.clone(), include_archived: true }, + ClientMsg::CreateEvent { event: event().spec }, + ClientMsg::UpdateEvent { id: 9, event: EventSpec::default() }, + ClientMsg::DeleteEvent { id: 9 }, + ClientMsg::GetEvent { id: 9 }, + ClientMsg::ListEvents(EventQuery { + from_ms: Some(1), + to_ms: None, + channel: Some(5), + limit: None, + }), + ClientMsg::Rsvp { event_id: 9, status: Some(RsvpStatus::Maybe) }, + ClientMsg::Rsvp { event_id: 9, status: None }, + ClientMsg::SubscribeEvents, + ClientMsg::UnsubscribeEvents, + ClientMsg::RegisterStream(StreamSpec { + stream_id: "s-1".into(), + client_id: Some(7), + channel: Some(5), + title: "t".into(), + kind: "screen".into(), + viewers: None, + }), + ClientMsg::UpdateStream { + stream_id: "s-1".into(), + title: Some("u".into()), + viewers: Some(4), + }, + ClientMsg::UnregisterStream { stream_id: "s-1".into() }, + ClientMsg::ListStreams, + ClientMsg::SubscribeStreams, + ClientMsg::UnsubscribeStreams, + ClientMsg::ListActivity { before: Some(10), limit: Some(20) }, + ClientMsg::SubscribeActivity, + ClientMsg::UnsubscribeActivity, + ClientMsg::ConfigList, + ClientMsg::ConfigGet { key: "a.b".into() }, + ClientMsg::ConfigSet { key: "a.b".into(), value: json!([1, 2]) }, + ClientMsg::ConfigReset { key: "a.b".into() }, + ClientMsg::ConfigReload, + ClientMsg::PermList, + ClientMsg::PermSet { action: Action::Pin, rule: rule() }, + ClientMsg::PermReset { action: Action::Admin }, + ]; + for msg in msgs { + roundtrip(msg); + } +} + +#[test] +fn every_server_message_roundtrips() { + let target = ChatTarget::Channel(5); + let msgs = vec![ + ServerMsg::Hello { + gateway_id: "g".into(), + server_uid: "s".into(), + server_name: "n".into(), + nonce: "x".into(), + capabilities: vec![feature::PINS.into()], + }, + ServerMsg::AuthOk { + uid: "u".into(), + token: "t".into(), + token_expires: 5, + capabilities: vec![feature::ADMIN.into()], + }, + ServerMsg::PresenceSnapshot { + seq: 0, + snapshot: PresenceSnapshot { + server_name: "s".into(), + channels: vec![], + clients: vec![ClientInfo { id: 1, nickname: "a".into(), ..Default::default() }], + }, + }, + ServerMsg::PresenceDelta { seq: 1, delta: PresenceDelta::ClientLeft { id: 1 } }, + ServerMsg::ChatEvent { id: 1, message: chat("x") }, + ServerMsg::History { messages: vec![entry(), HistoryEntry::new(1, chat("y"))] }, + ServerMsg::Ok, + ServerMsg::Error { code: ErrorCode::QuotaExceeded, message: "m".into() }, + ServerMsg::Pong, + ServerMsg::Enabled { features: vec!["pins".into()] }, + ServerMsg::Capabilities { capabilities: vec!["events".into()] }, + ServerMsg::Permissions { channel: None, actions: vec![Action::React, Action::Moderate] }, + ServerMsg::HistoryPage(HistoryPage { + target: target.clone(), + topic: Some(3), + messages: vec![entry()], + has_more: true, + }), + ServerMsg::SyncPage { + target: target.clone(), + messages: vec![entry()], + rev: 9, + has_more: false, + }, + ServerMsg::Message { entry: entry() }, + ServerMsg::Posted { entry: entry() }, + ServerMsg::Pinned { + target: target.clone(), + pin: PinInfo { entry: entry(), by: user(), ts_ms: 4 }, + }, + ServerMsg::Unpinned { target: target.clone(), message_id: 42, by: user() }, + ServerMsg::Pins { + target: target.clone(), + pins: vec![PinInfo { entry: entry(), by: user(), ts_ms: 4 }], + }, + ServerMsg::Reaction { + target: target.clone(), + message_id: 42, + emoji: "🎉".into(), + user: user(), + added: true, + count: 3, + }, + ServerMsg::Reactors { message_id: 42, emoji: "🎉".into(), users: vec![user()] }, + ServerMsg::Topic { topic: topic() }, + ServerMsg::TopicUpdated { topic: topic() }, + ServerMsg::Topics { target: target.clone(), topics: vec![topic()] }, + ServerMsg::Event { event: event() }, + ServerMsg::Events { events: vec![event()] }, + ServerMsg::EventUpdated { event: event() }, + ServerMsg::EventDeleted { id: 9 }, + ServerMsg::EventReminder { event: event(), starts_in_ms: 900_000 }, + ServerMsg::Stream { stream: stream() }, + ServerMsg::Streams { streams: vec![stream()] }, + ServerMsg::StreamStarted { stream: stream() }, + ServerMsg::StreamUpdated { stream: stream() }, + ServerMsg::StreamEnded { id: "s-1".into(), reason: "left".into() }, + ServerMsg::Activity { entries: vec![activity()], has_more: true }, + ServerMsg::ActivityAdded { entry: activity() }, + ServerMsg::Config { entries: vec![config_entry()] }, + ServerMsg::ConfigValue { entry: config_entry() }, + ServerMsg::PermRules { + rules: vec![ + PermRuleInfo { + action: Action::Pin, + rule: Some(rule()), + source: ConfigSource::Db, + default: "moderators".into(), + }, + PermRuleInfo { + action: Action::React, + rule: None, + source: ConfigSource::Default, + default: "everyone".into(), + }, + ], + }, + ]; + for msg in msgs { + roundtrip(msg); + } +} + +#[test] +fn new_json_shapes() { + let json = serde_json::to_value(Envelope::with_id( + 4, + ClientMsg::QueryHistory(HistoryQuery { + after: Some(10), + limit: Some(2), + ..HistoryQuery::latest(ChatTarget::Channel(1), None) + }), + )) + .unwrap(); + assert_eq!( + json, + json!({"v":1,"id":4,"type":"query_history","data":{"target":{"kind":"channel","id":1},"after":10,"limit":2}}) + ); + // The event spec is flattened into the event. + let json = serde_json::to_value(event()).unwrap(); + assert_eq!(json["title"], "Movie night"); + assert_eq!(json["kind"], "stream"); + assert_eq!(json["my_rsvp"], "going"); + let json = + serde_json::to_value(ClientMsg::PermSet { action: Action::CreateTopic, rule: rule() }) + .unwrap(); + assert_eq!( + json, + json!({"type":"perm_set","data":{"action":"create_topic","rule":{"server_groups":[6],"channel_groups":[5]}}}) + ); + // Plain entries stay as small as before. + let json = serde_json::to_value(HistoryEntry::new(1, chat("x"))).unwrap(); + assert_eq!(json.as_object().unwrap().keys().collect::>(), ["id", "message"]); +} + +#[test] +fn old_clients_read_extended_replies() { + // What a client built against the first protocol version sees. + #[derive(Deserialize)] + #[serde(tag = "type", content = "data", rename_all = "snake_case")] + enum OldServerMsg { + AuthOk { uid: String }, + History { messages: Vec }, + } + #[derive(Deserialize)] + struct OldEntry { + id: i64, + } + let auth = serde_json::to_string(&ServerMsg::AuthOk { + uid: "u".into(), + token: "t".into(), + token_expires: 1, + capabilities: vec!["admin".into()], + }) + .unwrap(); + assert!( + matches!(serde_json::from_str(&auth).unwrap(), OldServerMsg::AuthOk { uid } if uid == "u") + ); + let history = serde_json::to_string(&ServerMsg::History { messages: vec![entry()] }).unwrap(); + match serde_json::from_str(&history).unwrap() { + OldServerMsg::History { messages } => assert_eq!(messages[0].id, 42), + _ => panic!(), + } +} + +#[test] +fn newer_enum_values_do_not_break_parsing() { + let msg: ServerMsg = + serde_json::from_str(r#"{"type":"error","data":{"code":"from_the_future","message":"m"}}"#) + .unwrap(); + assert_eq!(msg, ServerMsg::Error { code: ErrorCode::Unknown, message: "m".into() }); + let spec: EventSpec = + serde_json::from_str(r#"{"title":"t","start_ms":1,"kind":"tournament"}"#).unwrap(); + assert_eq!(spec.kind, EventKind::Unknown); + let a: Vec = serde_json::from_str(r#"["pin","launch_rockets"]"#).unwrap(); + assert_eq!(a, [Action::Pin, Action::Unknown]); + assert_eq!(Action::parse("create_event"), Some(Action::CreateEvent)); + assert_eq!(Action::parse("unknown"), None); + for a in Action::ALL { + assert_eq!(serde_json::to_value(a).unwrap(), a.as_str()); + } + for s in [RsvpStatus::Going, RsvpStatus::Maybe, RsvpStatus::NotGoing] { + assert_eq!(RsvpStatus::parse(s.as_str()), s); + assert_eq!(serde_json::to_value(s).unwrap(), s.as_str()); + } +} diff --git a/crates/voelin-gateway-proto/src/types.rs b/crates/voelin-gateway-proto/src/types.rs new file mode 100644 index 0000000..0c89332 --- /dev/null +++ b/crates/voelin-gateway-proto/src/types.rs @@ -0,0 +1,466 @@ +//! Data carried by the extension messages: pins, reactions, topics, events, +//! the stream directory, the activity feed and administration. +//! +//! Enums that a newer gateway may extend have an `Unknown` fallback, so an +//! older client can still read the message. Kinds that are expected to grow +//! (activity) are plain strings. + +use serde::{Deserialize, Serialize}; +use voelin_model::{ChannelId, ChatTarget, ClientId}; + +use crate::messages::HistoryEntry; + +/// Feature names in [`crate::ServerMsg::Hello`] and [`crate::ServerMsg::AuthOk`]. +pub mod feature { + /// Presence stream ([`crate::ClientMsg::SubscribePresence`]). + pub const PRESENCE: &str = "presence"; + /// Channel and server chat through relays. + pub const RELAY: &str = "relay"; + /// Stored chat history, [`crate::ClientMsg::QueryHistory`] and [`crate::ClientMsg::Sync`]. + pub const HISTORY: &str = "history"; + pub const PINS: &str = "pins"; + pub const REACTIONS: &str = "reactions"; + pub const TOPICS: &str = "topics"; + pub const EVENTS: &str = "events"; + pub const STREAMS: &str = "streams"; + pub const ACTIVITY: &str = "activity"; + /// Only in [`crate::ServerMsg::AuthOk`]: the user may change the gateway's + /// configuration and permission rules. + pub const ADMIN: &str = "admin"; +} + +/// Activity kinds in [`ActivityEntry::kind`]. Clients show unknown kinds by +/// their [`ActivityEntry::text`]. +pub mod activity_kind { + pub const STREAM_STARTED: &str = "stream_started"; + pub const STREAM_ENDED: &str = "stream_ended"; + pub const EVENT_CREATED: &str = "event_created"; + pub const EVENT_CANCELLED: &str = "event_cancelled"; + pub const EVENT_STARTING: &str = "event_starting"; + pub const TOPIC_CREATED: &str = "topic_created"; + pub const PINNED: &str = "pinned"; +} + +fn is_false(b: &bool) -> bool { + !*b +} + +/// A user as the gateway knows them: unique id and last nickname. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct UserRef { + pub uid: String, + pub name: String, +} + +/// One emoji on a message. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReactionCount { + /// Any Unicode string, usually one emoji. + pub emoji: String, + pub count: u32, + /// The requesting user reacted with this emoji. + #[serde(default, skip_serializing_if = "is_false")] + pub me: bool, +} + +/// Parameters of [`crate::ClientMsg::QueryHistory`]. +/// +/// Without cursors the latest `limit` messages are returned. With `before` +/// (or `before_ms`) only, the `limit` messages right before it. With `after` +/// (or `after_ms`), the `limit` messages right after it, oldest first, up to +/// `before` if given. Pages are always ordered oldest first. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct HistoryQuery { + pub target: ChatTarget, + /// Messages with a smaller id. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub before: Option, + /// Messages with a larger id. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub after: Option, + /// Messages sent before this time (Unix milliseconds). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub before_ms: Option, + /// Messages sent after this time (Unix milliseconds). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub after_ms: Option, + /// Page size. Absent: everything in range, unless the gateway's admin set + /// a maximum page size. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, + /// Only the messages of this topic. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub topic: Option, + /// Only messages outside topics. + #[serde(default, skip_serializing_if = "is_false")] + pub exclude_topics: bool, +} + +impl HistoryQuery { + /// The latest messages of `target`. + pub fn latest(target: ChatTarget, limit: Option) -> Self { + Self { + target, + before: None, + after: None, + before_ms: None, + after_ms: None, + limit, + topic: None, + exclude_topics: false, + } + } +} + +/// Answer to [`crate::ClientMsg::QueryHistory`]. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct HistoryPage { + pub target: ChatTarget, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub topic: Option, + /// Oldest first. + pub messages: Vec, + /// More messages exist beyond this page in the paging direction (older + /// without `after`, newer with it). + #[serde(default)] + pub has_more: bool, +} + +/// A pinned message. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PinInfo { + pub entry: HistoryEntry, + pub by: UserRef, + pub ts_ms: i64, +} + +/// A topic (thread) in a chat. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicInfo { + pub id: i64, + pub target: ChatTarget, + pub title: String, + pub creator: UserRef, + pub created_ms: i64, + /// The message the topic was started from. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub root_message_id: Option, + pub last_activity_ms: i64, + pub message_count: u64, + #[serde(default, skip_serializing_if = "is_false")] + pub archived: bool, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EventKind { + #[default] + General, + /// A scheduled stream; linked to the stream directory once live. + Stream, + /// Sent by a newer gateway. + #[serde(other)] + Unknown, +} + +/// What the creator of an event sets. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct EventSpec { + pub title: String, + #[serde(default)] + pub description: String, + /// Unix milliseconds. + pub start_ms: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end_ms: Option, + /// Server-wide when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub channel: Option, + #[serde(default)] + pub kind: EventKind, + /// For streams: the expected stream title. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stream_title: Option, + /// For streams: the game or subject. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stream_game: Option, + /// Whose stream links to the event; the creator when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host_uid: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RsvpStatus { + Going, + Maybe, + NotGoing, + #[serde(other)] + Unknown, +} + +impl RsvpStatus { + pub fn as_str(self) -> &'static str { + match self { + RsvpStatus::Going => "going", + RsvpStatus::Maybe => "maybe", + RsvpStatus::NotGoing => "not_going", + RsvpStatus::Unknown => "unknown", + } + } + + pub fn parse(s: &str) -> Self { + match s { + "going" => RsvpStatus::Going, + "maybe" => RsvpStatus::Maybe, + "not_going" => RsvpStatus::NotGoing, + _ => RsvpStatus::Unknown, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Attendee { + pub user: UserRef, + pub status: RsvpStatus, + pub ts_ms: i64, +} + +/// A scheduled event. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EventInfo { + pub id: i64, + #[serde(flatten)] + pub spec: EventSpec, + pub creator: UserRef, + pub created_ms: i64, + pub updated_ms: i64, + #[serde(default)] + pub going: u32, + #[serde(default)] + pub maybe: u32, + #[serde(default)] + pub not_going: u32, + /// The requesting user's answer. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub my_rsvp: Option, + /// Everyone who answered; only in [`crate::ClientMsg::GetEvent`] replies. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub attendees: Vec, + /// Directory id of the stream while the host is live. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub live_stream: Option, +} + +/// Parameters of [`crate::ClientMsg::ListEvents`]. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct EventQuery { + /// Events that end (or, without an end, start) at or after this time. + /// Default: now. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub from_ms: Option, + /// Events that start before this time. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub to_ms: Option, + /// Only events in this channel. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub channel: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +/// What a streamer registers. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct StreamSpec { + /// The TeamSpeak 6 stream id (from `notifystreamstarted`). + pub stream_id: String, + /// The streamer's voice client id, so the gateway can drop the entry + /// when the client leaves or stops streaming. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub channel: Option, + #[serde(default)] + pub title: String, + /// Free form, e.g. `screen`, `window`, `camera`, `game`. + #[serde(default)] + pub kind: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub viewers: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum StreamSource { + /// Registered by the streamer's app; has a stream id. + Registered, + /// Seen by the gateway (`client_is_streaming`) without a registration; + /// the stream id is unknown. + Detected, + #[serde(other)] + Unknown, +} + +/// An entry in the stream directory. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct StreamEntry { + /// Directory id: the stream id when known, otherwise `client/`. + pub id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stream_id: Option, + pub streamer: UserRef, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub channel: Option, + #[serde(default)] + pub title: String, + #[serde(default)] + pub kind: String, + pub started_ms: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub viewers: Option, + pub source: StreamSource, + /// The scheduled event this stream belongs to. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub event_id: Option, +} + +/// An entry in the server's activity feed. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ActivityEntry { + pub id: i64, + pub ts_ms: i64, + /// One of [`activity_kind`], or something newer. + pub kind: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub actor: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub channel: Option, + /// Id of what the entry is about (message, topic, event or stream id). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ref_id: Option, + /// Human-readable summary, for kinds the client does not know. + pub text: String, + /// Kind-specific details. + #[serde(default, skip_serializing_if = "serde_json::Value::is_null")] + pub data: serde_json::Value, +} + +/// Where a configuration value comes from, highest precedence first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ConfigSource { + /// Set at runtime ([`crate::ClientMsg::ConfigSet`]), stored in the gateway's database. + Db, + /// `tsgw --set key=value`. + Cli, + /// `TSGW_` environment variable. + Env, + /// `tsgw.toml`. + File, + Default, + #[serde(other)] + Unknown, +} + +/// One configuration key. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ConfigEntry { + /// Dotted key, e.g. `history.retention_days`. + pub key: String, + /// Effective value (secrets are masked). + pub value: serde_json::Value, + pub source: ConfigSource, + pub default: serde_json::Value, + /// `bool`, `int`, `string`, `int_list`, `string_list` or `rule`. + #[serde(rename = "type")] + pub value_type: String, + pub description: String, + /// Only read from the file, environment or command line at start; + /// cannot be set at runtime. + #[serde(default, skip_serializing_if = "is_false")] + pub bootstrap: bool, +} + +/// Something a permission rule can allow. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Action { + /// React to messages. + React, + /// Pin and unpin messages. + Pin, + /// Start topics. + CreateTopic, + /// Schedule events. + CreateEvent, + /// Answer event invitations. + Rsvp, + /// Register streams in the directory. + Stream, + /// Edit and delete other users' topics, events and pins. + Moderate, + /// Change the gateway's configuration and permission rules. + Admin, + #[serde(other)] + Unknown, +} + +impl Action { + /// Every action that rules can be set for. + pub const ALL: [Action; 8] = [ + Action::React, + Action::Pin, + Action::CreateTopic, + Action::CreateEvent, + Action::Rsvp, + Action::Stream, + Action::Moderate, + Action::Admin, + ]; + + pub fn as_str(self) -> &'static str { + match self { + Action::React => "react", + Action::Pin => "pin", + Action::CreateTopic => "create_topic", + Action::CreateEvent => "create_event", + Action::Rsvp => "rsvp", + Action::Stream => "stream", + Action::Moderate => "moderate", + Action::Admin => "admin", + Action::Unknown => "unknown", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|a| a.as_str() == s) + } +} + +/// Who may do an action: members of any of the listed TeamSpeak server +/// groups, or of any listed channel group in the channel concerned, or +/// everyone. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PermRule { + #[serde(default, skip_serializing_if = "is_false")] + pub everyone: bool, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub server_groups: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub channel_groups: Vec, +} + +/// The rule for one action. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PermRuleInfo { + pub action: Action, + /// The configured rule; `None` when the built-in default applies. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rule: Option, + /// Where the rule comes from. + pub source: ConfigSource, + /// What the built-in default allows. + pub default: String, +} diff --git a/crates/voelin-gateway/src/session.rs b/crates/voelin-gateway/src/session.rs index 861b832..e6afb8d 100644 --- a/crates/voelin-gateway/src/session.rs +++ b/crates/voelin-gateway/src/session.rs @@ -127,13 +127,13 @@ impl Session { info!(uid = %user.uid, nickname = %user.nickname, "user logged in"); let uid = user.uid.clone(); self.user = Some(user); - Ok(vec![ServerMsg::AuthOk { uid, token, token_expires }]) + Ok(vec![ServerMsg::AuthOk { uid, token, token_expires, capabilities: Vec::new() }]) } ClientMsg::Resume { token, .. } => { let (user, token, token_expires) = self.hub.resume(&token).await?; let uid = user.uid.clone(); self.user = Some(user); - Ok(vec![ServerMsg::AuthOk { uid, token, token_expires }]) + Ok(vec![ServerMsg::AuthOk { uid, token, token_expires, capabilities: Vec::new() }]) } ClientMsg::SubscribePresence => { self.user()?; @@ -204,7 +204,7 @@ impl Session { .history(&target, before, limit.min(200)) .map_err(|e| Denied(ErrorCode::Internal, e.to_string()))? .into_iter() - .map(|(id, message)| HistoryEntry { id, message }) + .map(|(id, message)| HistoryEntry::new(id, message)) .collect(); Ok(vec![ServerMsg::History { messages }]) }