M3: tsc-query and tsc-observer (invisible presence, relay chat)
- tsc-query: ServerQuery codec (escaping, rows, errors, notifications, command builder/parser), line client for raw TCP and SSH (russh) with events, flood-limit token bucket and keepalive, HTTP WebQuery client. - tsc-model: Presence (snapshot/delta/diff), ChannelInfo, ClientInfo, ChatMessage, relay formatting and message splitting. - tsc-observer: Observer (snapshot, events or polling, resync, reconnect) and RelayPool (one query session per channel, reads channel chat and posts as [Nick] text, unique nicknames, polite quit). - tsctl query/observe/relay; smoke test covers presence and relay on TS3 (raw) and TS6 (SSH). Dev servers enable all query interfaces with a fixed dev password. - docs: query clients are hidden by clients, not the server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
25 files changed
+3555
-52
No files matched your search
@@ -0,0 +1,218 @@
|
||||
//! Query rows and events to model types.
|
||||
|
||||
use tsc_model::{ChannelInfo, ChatMessage, ChatTarget, ClientInfo, PresenceDelta};
|
||||
use tsc_query::{Notification, Row};
|
||||
|
||||
/// From a `channellist -topic -flags -voice -limits` row, or the fields of
|
||||
/// `notifychannelcreated`.
|
||||
pub fn channel_from_row(row: &Row) -> Option<ChannelInfo> {
|
||||
Some(ChannelInfo {
|
||||
id: row.parse("cid")?,
|
||||
parent: row.parse("pid").or_else(|| row.parse("cpid")).unwrap_or(0),
|
||||
order: row.parse("channel_order").unwrap_or(0),
|
||||
name: row.get("channel_name").unwrap_or_default().to_string(),
|
||||
topic: row.get("channel_topic").filter(|t| !t.is_empty()).map(str::to_string),
|
||||
has_password: row.flag("channel_flag_password").unwrap_or(false),
|
||||
max_clients: row.parse::<i32>("channel_maxclients").filter(|m| *m >= 0),
|
||||
needed_subscribe_power: row.parse("channel_needed_subscribe_power").unwrap_or(0),
|
||||
needed_talk_power: row.parse("channel_needed_talk_power").unwrap_or(0),
|
||||
is_default: row.flag("channel_flag_default").unwrap_or(false),
|
||||
})
|
||||
}
|
||||
|
||||
/// Update `channel` with the properties present in `row` (for
|
||||
/// `notifychanneledited`, which only carries what changed).
|
||||
pub fn update_channel(channel: &mut ChannelInfo, row: &Row) {
|
||||
if let Some(name) = row.get("channel_name") {
|
||||
channel.name = name.to_string();
|
||||
}
|
||||
if let Some(topic) = row.get("channel_topic") {
|
||||
channel.topic = Some(topic.to_string()).filter(|t| !t.is_empty());
|
||||
}
|
||||
if let Some(order) = row.parse("channel_order") {
|
||||
channel.order = order;
|
||||
}
|
||||
if let Some(p) = row.flag("channel_flag_password") {
|
||||
channel.has_password = p;
|
||||
}
|
||||
if let Some(m) = row.parse::<i32>("channel_maxclients") {
|
||||
channel.max_clients = Some(m).filter(|m| *m >= 0);
|
||||
}
|
||||
if let Some(p) = row.parse("channel_needed_subscribe_power") {
|
||||
channel.needed_subscribe_power = p;
|
||||
}
|
||||
if let Some(p) = row.parse("channel_needed_talk_power") {
|
||||
channel.needed_talk_power = p;
|
||||
}
|
||||
if let Some(d) = row.flag("channel_flag_default") {
|
||||
channel.is_default = d;
|
||||
}
|
||||
}
|
||||
|
||||
/// From a `clientlist -uid -away -voice -groups -country` row or a
|
||||
/// `notifycliententerview` row (which names the channel `ctid`).
|
||||
pub fn client_from_row(row: &Row) -> Option<ClientInfo> {
|
||||
let away = row.flag("client_away").unwrap_or(false);
|
||||
Some(ClientInfo {
|
||||
id: row.parse("clid")?,
|
||||
uid: row.get("client_unique_identifier").map(str::to_string),
|
||||
nickname: row.get("client_nickname").unwrap_or_default().to_string(),
|
||||
channel: row.parse("cid").or_else(|| row.parse("ctid"))?,
|
||||
is_query: row.parse::<u8>("client_type") == Some(1),
|
||||
away: away.then(|| row.get("client_away_message").unwrap_or_default().to_string()),
|
||||
input_muted: row.flag("client_input_muted").unwrap_or(false),
|
||||
output_muted: row.flag("client_output_muted").unwrap_or(false),
|
||||
talking: row.flag("client_flag_talking"),
|
||||
streaming: row.flag("client_is_streaming"),
|
||||
server_groups: row
|
||||
.get("client_servergroups")
|
||||
.map(|g| g.split(',').filter_map(|g| g.parse().ok()).collect())
|
||||
.unwrap_or_default(),
|
||||
country: row.get("client_country").filter(|c| !c.is_empty()).map(str::to_string),
|
||||
})
|
||||
}
|
||||
|
||||
/// Presence changes carried by a query event. `notifychanneledited` needs the
|
||||
/// current channel state and is handled by the observer.
|
||||
pub fn delta_from_notification(n: &Notification) -> Vec<PresenceDelta> {
|
||||
let rows = n.rows.iter();
|
||||
match n.name.as_str() {
|
||||
"notifycliententerview" => {
|
||||
rows.filter_map(client_from_row).map(PresenceDelta::ClientJoined).collect()
|
||||
}
|
||||
"notifyclientleftview" => rows
|
||||
.filter_map(|r| r.parse("clid"))
|
||||
.map(|id| PresenceDelta::ClientLeft { id })
|
||||
.collect(),
|
||||
"notifyclientmoved" => {
|
||||
// Several clients can move at once; ctid is only in the first row.
|
||||
let ctid = n.rows.first().and_then(|r| r.parse("ctid"));
|
||||
rows.filter_map(|r| {
|
||||
Some(PresenceDelta::ClientMoved {
|
||||
id: r.parse("clid")?,
|
||||
channel: r.parse("ctid").or(ctid)?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
"notifychannelcreated" => {
|
||||
rows.filter_map(channel_from_row).map(PresenceDelta::ChannelAdded).collect()
|
||||
}
|
||||
"notifychanneldeleted" => rows
|
||||
.filter_map(|r| r.parse("cid"))
|
||||
.map(|id| PresenceDelta::ChannelRemoved { id })
|
||||
.collect(),
|
||||
"notifyserveredited" => rows
|
||||
.filter_map(|r| r.get("virtualserver_name"))
|
||||
.map(|name| PresenceDelta::ServerRenamed { name: name.to_string() })
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A `notifytextmessage` as a chat message.
|
||||
pub fn is_text_message(n: &Notification, now_ms: i64) -> Option<ChatMessage> {
|
||||
if n.name != "notifytextmessage" {
|
||||
return None;
|
||||
}
|
||||
let row = n.rows.first()?;
|
||||
let target = match row.parse::<u8>("targetmode")? {
|
||||
3 => ChatTarget::Server,
|
||||
2 => ChatTarget::Channel(0), // filled in by the receiver, who knows its channel
|
||||
1 => ChatTarget::Private(row.get("invokeruid").unwrap_or_default().to_string()),
|
||||
_ => return None,
|
||||
};
|
||||
Some(ChatMessage {
|
||||
target,
|
||||
author_name: row.get("invokername").unwrap_or_default().to_string(),
|
||||
author_uid: row.get("invokeruid").map(str::to_string),
|
||||
author_id: row.parse("invokerid"),
|
||||
text: row.get("msg").unwrap_or_default().to_string(),
|
||||
ts_ms: now_ms,
|
||||
via_relay: true,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tsc_query::{Line, parse_line};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn notify(line: &str) -> Notification {
|
||||
match parse_line(line) {
|
||||
Line::Notify(n) => n,
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clientlist_row() {
|
||||
// Captured from TeamSpeak 6.0.0-beta13.1 (clientlist -uid -away -voice -groups -country).
|
||||
let row = &tsc_query::parse_rows(
|
||||
"clid=7 cid=1 client_database_id=4 client_nickname=sample client_type=0 client_away=0 \
|
||||
client_away_message client_flag_talking=0 client_input_muted=1 client_output_muted=0 \
|
||||
client_unique_identifier=hSC9DusMo3MJwDuA8MuvZBaHfb\\/h77N9WZtYskAFlG0= \
|
||||
client_servergroups=8,9 client_country",
|
||||
)[0];
|
||||
let c = client_from_row(row).unwrap();
|
||||
assert_eq!((c.id, c.channel, c.nickname.as_str()), (7, 1, "sample"));
|
||||
assert!(!c.is_query && c.input_muted && c.away.is_none());
|
||||
assert_eq!(c.talking, Some(false));
|
||||
assert_eq!(c.server_groups, vec![8, 9]);
|
||||
assert_eq!(c.uid.as_deref(), Some("hSC9DusMo3MJwDuA8MuvZBaHfb/h77N9WZtYskAFlG0="));
|
||||
assert_eq!(c.country, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channellist_row() {
|
||||
let row = &tsc_query::parse_rows(
|
||||
"cid=1 pid=0 channel_order=0 channel_name=Default\\sChannel channel_topic=t \
|
||||
channel_flag_default=1 channel_flag_password=0 channel_maxclients=-1 \
|
||||
channel_needed_subscribe_power=0 channel_needed_talk_power=5",
|
||||
)[0];
|
||||
let c = channel_from_row(row).unwrap();
|
||||
assert_eq!(c.name, "Default Channel");
|
||||
assert!(c.is_default && !c.has_password);
|
||||
assert_eq!(c.max_clients, None);
|
||||
assert_eq!(c.needed_talk_power, 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn events_to_deltas() {
|
||||
let n = notify(
|
||||
"notifycliententerview cfid=0 ctid=1 reasonid=0 clid=6 \
|
||||
client_unique_identifier=abc client_nickname=evtest client_type=0",
|
||||
);
|
||||
match &delta_from_notification(&n)[..] {
|
||||
[PresenceDelta::ClientJoined(c)] => assert_eq!((c.id, c.channel), (6, 1)),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
let n = notify("notifyclientmoved ctid=5 reasonid=0 clid=6|clid=7");
|
||||
assert_eq!(
|
||||
delta_from_notification(&n),
|
||||
vec![
|
||||
PresenceDelta::ClientMoved { id: 6, channel: 5 },
|
||||
PresenceDelta::ClientMoved { id: 7, channel: 5 },
|
||||
]
|
||||
);
|
||||
let n = notify("notifyclientleftview cfid=1 ctid=0 reasonid=8 clid=6");
|
||||
assert_eq!(delta_from_notification(&n), vec![PresenceDelta::ClientLeft { id: 6 }]);
|
||||
let n = notify("notifychanneldeleted cid=3 invokerid=0");
|
||||
assert_eq!(delta_from_notification(&n), vec![PresenceDelta::ChannelRemoved { id: 3 }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_messages() {
|
||||
let n = notify(
|
||||
"notifytextmessage targetmode=3 msg=hi\\sall invokerid=5 invokername=Bob invokeruid=u",
|
||||
);
|
||||
let m = is_text_message(&n, 42).unwrap();
|
||||
assert_eq!(m.target, ChatTarget::Server);
|
||||
assert_eq!(
|
||||
(m.text.as_str(), m.author_name.as_str(), m.author_id),
|
||||
("hi all", "Bob", Some(5))
|
||||
);
|
||||
assert!(is_text_message(¬ify("notifyclientleftview clid=1"), 0).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//! Invisible presence and channel-chat relays over ServerQuery.
|
||||
//!
|
||||
//! Query clients do not show up in normal clients' channel trees. The
|
||||
//! [`Observer`] keeps a live [`Presence`](tsc_model::Presence) of a server
|
||||
//! from one query session. A [`RelayPool`] puts one query session into each
|
||||
//! channel whose chat someone wants to read or write without joining it.
|
||||
//!
|
||||
//! Used by the gateway (`tsgw`) for all of its users and by the client for
|
||||
//! users who have their own query credentials.
|
||||
|
||||
mod convert;
|
||||
mod observer;
|
||||
mod relay;
|
||||
|
||||
pub use convert::{channel_from_row, client_from_row, delta_from_notification, is_text_message};
|
||||
pub use observer::{Observer, ObserverConfig, ObserverEvent};
|
||||
pub use relay::{RelayConfig, RelayEvent, RelayPool};
|
||||
@@ -0,0 +1,234 @@
|
||||
//! Keep a server's presence up to date from one query session.
|
||||
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::{broadcast, watch};
|
||||
use tokio::time::{Instant, sleep, sleep_until};
|
||||
use tracing::{debug, info, warn};
|
||||
use tsc_model::{ChatMessage, Presence, PresenceDelta, PresenceSnapshot};
|
||||
use tsc_query::{Command, Connect, Notification, QueryClient};
|
||||
|
||||
use crate::convert::{
|
||||
channel_from_row, client_from_row, delta_from_notification, is_text_message, update_channel,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ObserverConfig {
|
||||
pub connect: Connect,
|
||||
/// Full resync interval. Query sessions receive no `notifyclientupdated`,
|
||||
/// so mute/away changes are only noticed by re-reading the client list.
|
||||
pub poll_interval: Duration,
|
||||
/// Also deliver server chat (`event=textserver`).
|
||||
pub server_chat: bool,
|
||||
/// Wait between reconnect attempts.
|
||||
pub reconnect_delay: Duration,
|
||||
}
|
||||
|
||||
impl ObserverConfig {
|
||||
pub fn new(connect: Connect) -> Self {
|
||||
Self {
|
||||
connect,
|
||||
poll_interval: Duration::from_secs(10),
|
||||
server_chat: true,
|
||||
reconnect_delay: Duration::from_secs(5),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ObserverEvent {
|
||||
/// Full state; sent after every (re)connect.
|
||||
Snapshot(PresenceSnapshot),
|
||||
Delta(PresenceDelta),
|
||||
Chat(ChatMessage),
|
||||
/// Lost the query connection; presence may be stale until the next snapshot.
|
||||
Disconnected(String),
|
||||
}
|
||||
|
||||
/// Handle to a running observer. Dropping it stops the task.
|
||||
pub struct Observer {
|
||||
presence: Arc<RwLock<Presence>>,
|
||||
events: broadcast::Sender<ObserverEvent>,
|
||||
_stop: watch::Sender<()>,
|
||||
}
|
||||
|
||||
impl Observer {
|
||||
pub fn spawn(config: ObserverConfig) -> Self {
|
||||
let presence = Arc::new(RwLock::new(Presence::default()));
|
||||
let (events, _) = broadcast::channel(1024);
|
||||
let (stop, stopped) = watch::channel(());
|
||||
tokio::spawn(run(config, presence.clone(), events.clone(), stopped));
|
||||
Self { presence, events, _stop: stop }
|
||||
}
|
||||
|
||||
/// Receive events. Call [`Observer::snapshot`] after subscribing to get
|
||||
/// the state the events apply to.
|
||||
pub fn subscribe(&self) -> broadcast::Receiver<ObserverEvent> {
|
||||
self.events.subscribe()
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> PresenceSnapshot {
|
||||
self.presence.read().unwrap().snapshot()
|
||||
}
|
||||
|
||||
pub fn presence(&self) -> Arc<RwLock<Presence>> {
|
||||
self.presence.clone()
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(
|
||||
config: ObserverConfig,
|
||||
presence: Arc<RwLock<Presence>>,
|
||||
events: broadcast::Sender<ObserverEvent>,
|
||||
mut stopped: watch::Receiver<()>,
|
||||
) {
|
||||
loop {
|
||||
let result = tokio::select! {
|
||||
r = session(&config, &presence, &events) => r,
|
||||
_ = stopped.changed() => return,
|
||||
};
|
||||
let reason = match result {
|
||||
Ok(()) => "connection closed".to_string(),
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
warn!(%reason, addr = %config.connect.addr, "observer disconnected");
|
||||
let _ = events.send(ObserverEvent::Disconnected(reason));
|
||||
tokio::select! {
|
||||
_ = sleep(config.reconnect_delay) => {}
|
||||
_ = stopped.changed() => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the full state.
|
||||
async fn load(client: &QueryClient) -> tsc_query::Result<Presence> {
|
||||
let info = client.send(&Command::new("serverinfo")).await?;
|
||||
let channels = client
|
||||
.send(&Command::new("channellist").flag("topic").flag("flags").flag("voice").flag("limits"))
|
||||
.await?;
|
||||
let clients = client
|
||||
.send(
|
||||
&Command::new("clientlist")
|
||||
.flag("uid")
|
||||
.flag("away")
|
||||
.flag("voice")
|
||||
.flag("groups")
|
||||
.flag("country"),
|
||||
)
|
||||
.await?;
|
||||
Ok(Presence::from_snapshot(PresenceSnapshot {
|
||||
server_name: info
|
||||
.first()
|
||||
.and_then(|r| r.get("virtualserver_name"))
|
||||
.unwrap_or_default()
|
||||
.to_string(),
|
||||
channels: channels.iter().filter_map(channel_from_row).collect(),
|
||||
clients: clients.iter().filter_map(client_from_row).collect(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn now_ms() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as i64)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
async fn session(
|
||||
config: &ObserverConfig,
|
||||
presence: &RwLock<Presence>,
|
||||
events: &broadcast::Sender<ObserverEvent>,
|
||||
) -> tsc_query::Result<()> {
|
||||
let (client, mut notifications) = QueryClient::connect(&config.connect).await?;
|
||||
if notifications.is_some() {
|
||||
for event in ["server", "channel"] {
|
||||
let mut cmd = Command::new("servernotifyregister").arg("event", event);
|
||||
if event == "channel" {
|
||||
cmd = cmd.arg("id", 0);
|
||||
}
|
||||
client.send(&cmd).await?;
|
||||
}
|
||||
if config.server_chat {
|
||||
client.send(&Command::new("servernotifyregister").arg("event", "textserver")).await?;
|
||||
}
|
||||
}
|
||||
let state = load(&client).await?;
|
||||
info!(
|
||||
server = %state.server_name,
|
||||
channels = state.channels.len(),
|
||||
clients = state.clients.len(),
|
||||
events = notifications.is_some(),
|
||||
"observer connected"
|
||||
);
|
||||
*presence.write().unwrap() = state.clone();
|
||||
let _ = events.send(ObserverEvent::Snapshot(state.snapshot()));
|
||||
|
||||
let mut next_poll = Instant::now() + config.poll_interval;
|
||||
loop {
|
||||
let notification: Option<Notification> = tokio::select! {
|
||||
n = async {
|
||||
match &mut notifications {
|
||||
Some(rx) => rx.recv().await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
} => match n {
|
||||
Some(n) => Some(n),
|
||||
None => return Ok(()),
|
||||
},
|
||||
_ = sleep_until(next_poll) => None,
|
||||
};
|
||||
|
||||
match notification {
|
||||
Some(n) => handle_notification(&n, presence, events),
|
||||
None => {
|
||||
// Resync and publish only what changed.
|
||||
let fresh = load(&client).await?;
|
||||
let deltas = presence.read().unwrap().diff(&fresh);
|
||||
if !deltas.is_empty() {
|
||||
debug!(changes = deltas.len(), "observer resync");
|
||||
}
|
||||
*presence.write().unwrap() = fresh;
|
||||
for d in deltas {
|
||||
let _ = events.send(ObserverEvent::Delta(d));
|
||||
}
|
||||
next_poll = Instant::now() + config.poll_interval;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_notification(
|
||||
n: &Notification,
|
||||
presence: &RwLock<Presence>,
|
||||
events: &broadcast::Sender<ObserverEvent>,
|
||||
) {
|
||||
if let Some(msg) = is_text_message(n, now_ms()) {
|
||||
let _ = events.send(ObserverEvent::Chat(msg));
|
||||
return;
|
||||
}
|
||||
let deltas = if n.name == "notifychanneledited" || n.name == "notifychannelmoved" {
|
||||
let state = presence.read().unwrap();
|
||||
n.rows
|
||||
.iter()
|
||||
.filter_map(|row| {
|
||||
let mut channel = state.channels.get(&row.parse("cid")?)?.clone();
|
||||
update_channel(&mut channel, row);
|
||||
if let Some(parent) = row.parse("cpid") {
|
||||
channel.parent = parent;
|
||||
}
|
||||
if let Some(order) = row.parse("order") {
|
||||
channel.order = order;
|
||||
}
|
||||
Some(PresenceDelta::ChannelChanged(channel))
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
delta_from_notification(n)
|
||||
};
|
||||
let mut state = presence.write().unwrap();
|
||||
for d in deltas {
|
||||
state.apply(&d);
|
||||
let _ = events.send(ObserverEvent::Delta(d));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
//! Channel-chat relays: one query session sitting in each relayed channel.
|
||||
//!
|
||||
//! TeamSpeak only delivers channel chat to clients in that channel, and a
|
||||
//! client can only post to its own channel. A relay session is an invisible
|
||||
//! query client moved into the channel; it forwards what is said there and
|
||||
//! posts messages on behalf of users as `[Nick] text`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::{Mutex, broadcast, mpsc};
|
||||
use tokio::task::JoinHandle;
|
||||
use tracing::{debug, info, warn};
|
||||
use tsc_model::{ChannelId, ChatMessage, ChatTarget, relay_text, split_message};
|
||||
use tsc_query::{Command, Connect, Notification, QueryClient};
|
||||
|
||||
use crate::convert::is_text_message;
|
||||
|
||||
/// `clientupdate client_nickname=` with a name someone else has.
|
||||
const ERR_NICKNAME_IN_USE: u32 = 513;
|
||||
/// `clientmove` into the channel the client is already in.
|
||||
const ERR_ALREADY_MEMBER: u32 = 770;
|
||||
|
||||
/// TeamSpeak's limit for one text message.
|
||||
const MAX_MESSAGE_BYTES: usize = 1024;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RelayConfig {
|
||||
pub connect: Connect,
|
||||
/// Base nickname; the channel id is appended because nicknames are unique.
|
||||
pub nickname: String,
|
||||
/// How posts appear, with `{nick}` and `{text}` placeholders.
|
||||
pub format: String,
|
||||
}
|
||||
|
||||
impl RelayConfig {
|
||||
pub fn new(connect: Connect) -> Self {
|
||||
Self { connect, nickname: "Chat Relay".into(), format: "[{nick}] {text}".into() }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum RelayEvent {
|
||||
/// Someone wrote in a relayed channel (our own posts are not echoed).
|
||||
Message(ChatMessage),
|
||||
/// A relay stopped (connection lost or closed).
|
||||
Closed { channel: ChannelId, reason: String },
|
||||
}
|
||||
|
||||
struct Session {
|
||||
client: QueryClient,
|
||||
task: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
/// Manages relay sessions, at most one per channel.
|
||||
#[derive(Clone)]
|
||||
pub struct RelayPool {
|
||||
config: Arc<RelayConfig>,
|
||||
sessions: Arc<Mutex<HashMap<ChannelId, Session>>>,
|
||||
events: broadcast::Sender<RelayEvent>,
|
||||
}
|
||||
|
||||
impl RelayPool {
|
||||
pub fn new(config: RelayConfig) -> Self {
|
||||
let (events, _) = broadcast::channel(1024);
|
||||
Self { config: Arc::new(config), sessions: Default::default(), events }
|
||||
}
|
||||
|
||||
pub fn subscribe(&self) -> broadcast::Receiver<RelayEvent> {
|
||||
self.events.subscribe()
|
||||
}
|
||||
|
||||
/// Channels with an open relay.
|
||||
pub async fn channels(&self) -> Vec<ChannelId> {
|
||||
self.sessions.lock().await.keys().copied().collect()
|
||||
}
|
||||
|
||||
/// Start relaying a channel (no-op if already open).
|
||||
pub async fn open(&self, channel: ChannelId) -> tsc_query::Result<()> {
|
||||
let mut sessions = self.sessions.lock().await;
|
||||
if sessions.get(&channel).is_some_and(|s| !s.task.is_finished()) {
|
||||
return Ok(());
|
||||
}
|
||||
let (client, notifications) = QueryClient::connect(&self.config.connect).await?;
|
||||
let Some(notifications) = notifications else {
|
||||
return Err(tsc_query::Error::Unsupported("relays need a transport with events"));
|
||||
};
|
||||
let own_id = client.own_client_id().await?;
|
||||
set_nickname(&client, &format!("{} {channel}", self.config.nickname)).await;
|
||||
match client.send(&Command::new("clientmove").arg("clid", own_id).arg("cid", channel)).await
|
||||
{
|
||||
// Query clients start in the default channel.
|
||||
Err(tsc_query::Error::Query(e)) if e.id == ERR_ALREADY_MEMBER => {}
|
||||
other => {
|
||||
other?;
|
||||
}
|
||||
}
|
||||
client.send(&Command::new("servernotifyregister").arg("event", "textchannel")).await?;
|
||||
info!(channel, own_id, "relay opened");
|
||||
let task = tokio::spawn(forward(channel, own_id, notifications, self.events.clone()));
|
||||
sessions.insert(channel, Session { client, task });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop relaying a channel.
|
||||
pub async fn close(&self, channel: ChannelId) {
|
||||
let session = self.sessions.lock().await.remove(&channel);
|
||||
if let Some(session) = session {
|
||||
session.client.quit().await;
|
||||
info!(channel, "relay closed");
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop all relays.
|
||||
pub async fn close_all(&self) {
|
||||
let sessions: Vec<_> = self.sessions.lock().await.drain().collect();
|
||||
for (channel, session) in sessions {
|
||||
session.client.quit().await;
|
||||
info!(channel, "relay closed");
|
||||
}
|
||||
}
|
||||
|
||||
/// Post `text` in `channel` on behalf of `nick`, opening a relay if needed.
|
||||
pub async fn send(&self, channel: ChannelId, nick: &str, text: &str) -> tsc_query::Result<()> {
|
||||
self.open(channel).await?;
|
||||
let client = match self.sessions.lock().await.get(&channel) {
|
||||
Some(s) => s.client.clone(),
|
||||
None => return Err(tsc_query::Error::Closed),
|
||||
};
|
||||
let full = relay_text(&self.config.format, nick, text);
|
||||
for part in split_message(&full, MAX_MESSAGE_BYTES) {
|
||||
client
|
||||
.send(
|
||||
&Command::new("sendtextmessage")
|
||||
.arg("targetmode", 2)
|
||||
.arg("target", channel)
|
||||
.arg("msg", part),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Nicknames are unique per server; try a few numbered variants. The name is
|
||||
/// cosmetic, so failing keeps the server-assigned one.
|
||||
async fn set_nickname(client: &QueryClient, base: &str) {
|
||||
for attempt in 1..=5 {
|
||||
let nickname = if attempt == 1 { base.to_string() } else { format!("{base} ({attempt})") };
|
||||
match client.send(&Command::new("clientupdate").arg("client_nickname", &nickname)).await {
|
||||
Ok(_) => return,
|
||||
Err(tsc_query::Error::Query(e)) if e.id == ERR_NICKNAME_IN_USE => continue,
|
||||
Err(e) => {
|
||||
warn!(%e, %nickname, "could not set relay nickname");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
warn!(base, "all relay nicknames in use");
|
||||
}
|
||||
|
||||
async fn forward(
|
||||
channel: ChannelId,
|
||||
own_id: u16,
|
||||
mut notifications: mpsc::UnboundedReceiver<Notification>,
|
||||
events: broadcast::Sender<RelayEvent>,
|
||||
) {
|
||||
while let Some(n) = notifications.recv().await {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as i64)
|
||||
.unwrap_or_default();
|
||||
let Some(mut msg) = is_text_message(&n, now) else { continue };
|
||||
if msg.author_id == Some(own_id) {
|
||||
continue;
|
||||
}
|
||||
if msg.target == ChatTarget::Channel(0) {
|
||||
msg.target = ChatTarget::Channel(channel);
|
||||
}
|
||||
debug!(channel, author = %msg.author_name, "relayed message");
|
||||
let _ = events.send(RelayEvent::Message(msg));
|
||||
}
|
||||
let _ = events.send(RelayEvent::Closed { channel, reason: "connection closed".into() });
|
||||
}
|
||||
Reference in new issue
Block a user