relay: post under the author's own nickname
A relay (and the gateway's lookup session, for server chat) takes the author's nickname for each post, sends the text as written and takes its own name back, so messages read as written by the user in TeamSpeak. While someone has the nickname it uses Nick1 to Nick3, as TeamSpeak names a second client of the same name; relay.format ([Nick] text) is only the fallback when it can take none of them. Posts through one session are serialized, since each borrows a nickname. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
This commit is contained in:
9 files changed
+204
-51
No files matched your search
@@ -160,7 +160,7 @@ pub static KEYS: &[KeyDef] = &[
|
||||
"relay.format",
|
||||
Kind::Str,
|
||||
"\"[{nick}] {text}\"",
|
||||
"How posts appear in TeamSpeak; {nick} and {text} are replaced",
|
||||
"How posts appear when the relay cannot take the user's nickname; {nick} and {text} are replaced",
|
||||
),
|
||||
key(
|
||||
"relay.idle_teardown_secs",
|
||||
|
||||
@@ -19,8 +19,8 @@ use voelin_gateway_proto::{
|
||||
Action, ActivityEntry, ErrorCode, EventInfo, HistoryEntry, PinInfo, StreamEntry, TopicInfo,
|
||||
UniqueIds, UserRef, feature, identity_level, verify_auth,
|
||||
};
|
||||
use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor, relay_text};
|
||||
use voelin_observer::{Observer, ObserverConfig, RelayConfig, RelayPool};
|
||||
use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
|
||||
use voelin_observer::{Observer, ObserverConfig, RelayConfig, RelayPool, post_as};
|
||||
use voelin_query::{Command, Connect, QueryClient};
|
||||
|
||||
use crate::config::{Bootstrap, Layers, Runtime};
|
||||
@@ -206,6 +206,8 @@ pub struct Hub {
|
||||
/// Serializes rebuilding the relay pool.
|
||||
relay_rebuild: tokio::sync::Mutex<()>,
|
||||
lookup: QueryClient,
|
||||
/// One server-chat post at a time: each borrows the poster's nickname.
|
||||
lookup_posting: tokio::sync::Mutex<()>,
|
||||
perms: PermResolver,
|
||||
groups: GroupResolver,
|
||||
pub db: Db,
|
||||
@@ -268,6 +270,7 @@ impl Hub {
|
||||
relays: RwLock::new(relays),
|
||||
relay_rebuild: Default::default(),
|
||||
lookup,
|
||||
lookup_posting: Default::default(),
|
||||
perms,
|
||||
groups: GroupResolver::default(),
|
||||
db,
|
||||
@@ -751,16 +754,20 @@ impl Hub {
|
||||
}
|
||||
None => text.to_string(),
|
||||
};
|
||||
let full = relay_text(&rt.relay.format, &user.nickname, &relayed);
|
||||
// Posts go out under the user's nickname; `relay.format` only when the
|
||||
// session cannot take it.
|
||||
match target {
|
||||
ChatTarget::Server => {
|
||||
for part in voelin_model::split_message(&full, 1024) {
|
||||
self.lookup
|
||||
.send(
|
||||
&Command::new("sendtextmessage").arg("targetmode", 3).arg("msg", part),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
let _posting = self.lookup_posting.lock().await;
|
||||
post_as(
|
||||
&self.lookup,
|
||||
&lookup_nickname(&rt.relay.nickname),
|
||||
&user.nickname,
|
||||
&relayed,
|
||||
&rt.relay.format,
|
||||
|part| Command::new("sendtextmessage").arg("targetmode", 3).arg("msg", part),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
ChatTarget::Channel(cid) => {
|
||||
if !self.readers.lock().unwrap().contains_key(cid) {
|
||||
@@ -768,8 +775,7 @@ impl Hub {
|
||||
self.add_reader(*cid).await?;
|
||||
self.remove_reader(*cid);
|
||||
}
|
||||
// The pool's format is `{text}`: `full` is already formatted.
|
||||
self.relays().send(*cid, &user.nickname, &full).await?;
|
||||
self.relays().post(*cid, &user.nickname, &relayed, &rt.relay.format).await?;
|
||||
}
|
||||
ChatTarget::Private(_) => unreachable!("checked by require_post"),
|
||||
}
|
||||
@@ -797,14 +803,17 @@ impl Hub {
|
||||
fn new_relay_pool(connect: &Connect, nickname: &str) -> RelayPool {
|
||||
let mut config = RelayConfig::new(connect.clone());
|
||||
config.nickname = nickname.to_string();
|
||||
// Posts are formatted by the hub, with the current settings.
|
||||
config.format = "{text}".into();
|
||||
RelayPool::new(config)
|
||||
}
|
||||
|
||||
/// The lookup session's own name, given `relay.nickname`.
|
||||
fn lookup_nickname(nickname: &str) -> String {
|
||||
format!("{nickname} Gateway")
|
||||
}
|
||||
|
||||
async fn set_lookup_nickname(lookup: &QueryClient, nickname: &str) {
|
||||
let _ = lookup
|
||||
.send(&Command::new("clientupdate").arg("client_nickname", format!("{nickname} Gateway")))
|
||||
.send(&Command::new("clientupdate").arg("client_nickname", lookup_nickname(nickname)))
|
||||
.await;
|
||||
}
|
||||
|
||||
|
||||
@@ -49,8 +49,12 @@ pub struct State {
|
||||
pub server_groups: HashMap<u64, Vec<u64>>,
|
||||
/// (target mode, channel of the posting connection, text)
|
||||
pub posted: Vec<(u8, u64, String)>,
|
||||
/// The nickname of the posting connection, for each of `posted`.
|
||||
pub posters: Vec<String>,
|
||||
/// Nicknames set with clientupdate.
|
||||
pub nicknames: Vec<String>,
|
||||
/// The current nickname of each query connection.
|
||||
names: HashMap<u16, String>,
|
||||
/// Connections that registered for server events (the observer).
|
||||
observers: Vec<mpsc::UnboundedSender<String>>,
|
||||
/// Relay connections by channel.
|
||||
@@ -120,6 +124,17 @@ impl FakeServer {
|
||||
self.state.lock().unwrap().posted.clone()
|
||||
}
|
||||
|
||||
/// What was posted as `(nickname of the poster, text)`.
|
||||
pub fn posted_by(&self) -> Vec<(String, String)> {
|
||||
let s = self.state.lock().unwrap();
|
||||
s.posters.iter().cloned().zip(s.posted.iter().map(|p| p.2.clone())).collect()
|
||||
}
|
||||
|
||||
/// The nickname a query connection has now.
|
||||
pub fn nickname_of(&self, clid: u16) -> Option<String> {
|
||||
self.state.lock().unwrap().names.get(&clid).cloned()
|
||||
}
|
||||
|
||||
async fn connection(self, stream: tokio::net::TcpStream) {
|
||||
let (r, mut w) = stream.into_split();
|
||||
let mut lines = BufReader::new(r).lines();
|
||||
@@ -192,6 +207,12 @@ impl FakeServer {
|
||||
"whoami" => data(vec![format!("client_id={clid} client_channel_id={channel}")]),
|
||||
"clientupdate" => {
|
||||
if let Some(nick) = arg("client_nickname") {
|
||||
let in_use = s.online.iter().any(|c| c.nickname == nick)
|
||||
|| s.names.iter().any(|(id, n)| *id != clid && *n == nick);
|
||||
if in_use {
|
||||
return "error id=513 msg=nickname\\sis\\salready\\sin\\suse\n\r".into();
|
||||
}
|
||||
s.names.insert(clid, nick.clone());
|
||||
s.nicknames.push(nick);
|
||||
}
|
||||
ok
|
||||
@@ -262,6 +283,8 @@ impl FakeServer {
|
||||
"sendtextmessage" => {
|
||||
let mode = num("targetmode") as u8;
|
||||
s.posted.push((mode, *channel, arg("msg").unwrap_or_default()));
|
||||
let poster = s.names.get(&clid).cloned().unwrap_or_default();
|
||||
s.posters.push(poster);
|
||||
ok
|
||||
}
|
||||
_ => ok,
|
||||
|
||||
@@ -173,7 +173,11 @@ async fn chat_pins_reactions_topics() {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!((id, message.text.as_str()), (hello.id, "hello"));
|
||||
assert!(fx.fake.posted().contains(&(2, 1, "[Bob] hello".into())));
|
||||
// Under Bob's name: "Bob1", as Bob is online with voice as "Bob". The
|
||||
// relay takes its own name back after the post.
|
||||
assert!(fx.fake.posted().contains(&(2, 1, "hello".into())));
|
||||
assert!(fx.fake.posted_by().contains(&("Bob1".into(), "hello".into())));
|
||||
assert_eq!(fx.fake.state.lock().unwrap().nicknames.last().unwrap(), "Chat Relay 1");
|
||||
|
||||
// Pins: moderators only by default; Alice is an admin.
|
||||
assert_eq!(code(b.pin(hello.id).await), ErrorCode::Forbidden);
|
||||
@@ -213,7 +217,7 @@ async fn chat_pins_reactions_topics() {
|
||||
assert_eq!(t.id, topic.id);
|
||||
let in_topic = b.post(LOBBY, "saturday?".into(), Some(topic.id)).await.unwrap();
|
||||
assert_eq!(in_topic.topic_id, Some(topic.id));
|
||||
assert!(fx.fake.posted().contains(&(2, 1, "[Bob] [#Plans] saturday?".into())));
|
||||
assert!(fx.fake.posted_by().contains(&("Bob1".into(), "[#Plans] saturday?".into())));
|
||||
expect(
|
||||
&mut c_rx,
|
||||
"prefixed chat event",
|
||||
@@ -456,7 +460,7 @@ async fn admin_settings_apply_live() {
|
||||
|
||||
// Feature switches reach connected clients at once.
|
||||
let first = b.post(LOBBY, "one".into(), None).await.unwrap();
|
||||
assert!(fx.fake.posted().contains(&(2, 1, "<Bob> one".into())));
|
||||
assert!(fx.fake.posted_by().contains(&("Bob1".into(), "one".into())));
|
||||
let entry = a.config_set("features.pins".into(), json!(false)).await.unwrap();
|
||||
assert_eq!(entry.source, voelin_gateway_proto::ConfigSource::Db);
|
||||
expect(
|
||||
@@ -506,10 +510,22 @@ async fn admin_settings_apply_live() {
|
||||
// 0: no limit.
|
||||
a.config_set("limits.posts_per_window".into(), json!(0)).await.unwrap();
|
||||
|
||||
// Relay settings apply without a restart.
|
||||
// Relay settings apply without a restart. The format is for posts the
|
||||
// relay cannot make under Bob's name: every variant of it is taken.
|
||||
for (clid, nick) in [(21, "Bob1"), (22, "Bob2"), (23, "Bob3")] {
|
||||
fx.fake.add_online(Online {
|
||||
clid,
|
||||
cid: 2,
|
||||
uid: format!("other-{nick}"),
|
||||
nickname: nick.into(),
|
||||
server_groups: Vec::new(),
|
||||
streaming: false,
|
||||
});
|
||||
}
|
||||
a.config_set("relay.format".into(), json!("{nick}: {text}")).await.unwrap();
|
||||
b.post(LOBBY, "two".into(), None).await.unwrap();
|
||||
assert!(fx.fake.posted().contains(&(2, 1, "Bob: two".into())));
|
||||
assert!(fx.fake.posted_by().contains(&("Chat Relay 1".into(), "Bob: two".into())));
|
||||
a.config_set("relay.nickname".into(), json!("Bridge")).await.unwrap();
|
||||
for _ in 0..100 {
|
||||
if fx.fake.state.lock().unwrap().nicknames.iter().any(|n| n == "Bridge 1") {
|
||||
|
||||
@@ -42,6 +42,8 @@ token_ttl_hours = 720
|
||||
|
||||
[relay]
|
||||
nickname = "Chat Relay"
|
||||
# Posts go out under the user's nickname; this form only when the relay
|
||||
# cannot take it.
|
||||
format = "[{nick}] {text}"
|
||||
idle_teardown_secs = 120
|
||||
# Each relay is one query connection; stay below the server's per-IP limit.
|
||||
|
||||
@@ -14,4 +14,4 @@ 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};
|
||||
pub use relay::{RelayConfig, RelayEvent, RelayPool, post_as};
|
||||
@@ -3,7 +3,7 @@
|
||||
//! 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`.
|
||||
//! posts messages on behalf of users under their own nickname ([`post_as`]).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -23,13 +23,17 @@ const ERR_ALREADY_MEMBER: u32 = 770;
|
||||
|
||||
/// TeamSpeak's limit for one text message.
|
||||
const MAX_MESSAGE_BYTES: usize = 1024;
|
||||
/// TeamSpeak's limits for a nickname, in characters.
|
||||
const MIN_NICKNAME_CHARS: usize = 3;
|
||||
const MAX_NICKNAME_CHARS: usize = 30;
|
||||
|
||||
#[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.
|
||||
/// How posts appear when the relay cannot take the author's nickname
|
||||
/// ([`post_as`]), with `{nick}` and `{text}` placeholders.
|
||||
pub format: String,
|
||||
}
|
||||
|
||||
@@ -49,6 +53,10 @@ pub enum RelayEvent {
|
||||
|
||||
struct Session {
|
||||
client: QueryClient,
|
||||
/// The relay's own nickname, taken back after each post.
|
||||
nickname: String,
|
||||
/// One post at a time: each borrows the author's nickname.
|
||||
posting: Arc<Mutex<()>>,
|
||||
task: JoinHandle<()>,
|
||||
}
|
||||
|
||||
@@ -92,7 +100,7 @@ impl RelayPool {
|
||||
return Err(voelin_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;
|
||||
let nickname = 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.
|
||||
@@ -104,7 +112,7 @@ impl RelayPool {
|
||||
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 });
|
||||
sessions.insert(channel, Session { client, nickname, posting: Default::default(), task });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -126,48 +134,118 @@ impl RelayPool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Post `text` in `channel` on behalf of `nick`, opening a relay if needed.
|
||||
/// Post `text` in `channel` as `nick` wrote it ([`post_as`]), opening a
|
||||
/// relay if needed.
|
||||
pub async fn send(
|
||||
&self,
|
||||
channel: ChannelId,
|
||||
nick: &str,
|
||||
text: &str,
|
||||
) -> voelin_query::Result<()> {
|
||||
self.post(channel, nick, text, &self.config.format).await
|
||||
}
|
||||
|
||||
/// [`RelayPool::send`] with another fallback `format` than the pool's.
|
||||
pub async fn post(
|
||||
&self,
|
||||
channel: ChannelId,
|
||||
nick: &str,
|
||||
text: &str,
|
||||
format: &str,
|
||||
) -> voelin_query::Result<()> {
|
||||
self.open(channel).await?;
|
||||
let client = match self.sessions.lock().await.get(&channel) {
|
||||
Some(s) => s.client.clone(),
|
||||
let (client, nickname, posting) = match self.sessions.lock().await.get(&channel) {
|
||||
Some(s) => (s.client.clone(), s.nickname.clone(), s.posting.clone()),
|
||||
None => return Err(voelin_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(())
|
||||
let _posting = posting.lock().await;
|
||||
post_as(&client, &nickname, nick, text, format, |part| {
|
||||
Command::new("sendtextmessage")
|
||||
.arg("targetmode", 2)
|
||||
.arg("target", channel)
|
||||
.arg("msg", part)
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// Post `text` through the query session `client` as if `nick` wrote it: the
|
||||
/// session takes the nickname for the post (or `nick1`, `nick2`, … while
|
||||
/// someone has it, as TeamSpeak names a second client of the same name) and
|
||||
/// goes back to `own_nickname` afterwards, so it never keeps someone's name.
|
||||
/// When it cannot take any (too short, refused), the post goes out under the
|
||||
/// session's own name as `format` (`{nick}`, `{text}`). `command` makes the
|
||||
/// `sendtextmessage` for one part of the text.
|
||||
///
|
||||
/// Callers serialize posts through one session: each borrows a nickname.
|
||||
pub async fn post_as(
|
||||
client: &QueryClient,
|
||||
own_nickname: &str,
|
||||
nick: &str,
|
||||
text: &str,
|
||||
format: &str,
|
||||
command: impl Fn(String) -> Command,
|
||||
) -> voelin_query::Result<()> {
|
||||
let taken = take_nickname(client, nick).await;
|
||||
let full = if taken { text.to_owned() } else { relay_text(format, nick, text) };
|
||||
let mut result = Ok(());
|
||||
for part in split_message(&full, MAX_MESSAGE_BYTES) {
|
||||
result = client.send(&command(part)).await.map(drop);
|
||||
if result.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if taken && !own_nickname.is_empty() {
|
||||
set_nickname(client, own_nickname).await;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Name the session `nick` or a numbered variant; whether it did.
|
||||
async fn take_nickname(client: &QueryClient, nick: &str) -> bool {
|
||||
for nickname in author_nicknames(nick) {
|
||||
match client.send(&Command::new("clientupdate").arg("client_nickname", &nickname)).await {
|
||||
Ok(_) => return true,
|
||||
Err(voelin_query::Error::Query(e)) if e.id == ERR_NICKNAME_IN_USE => continue,
|
||||
Err(e) => {
|
||||
debug!(%e, "could not take the author's nickname");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The names a post by `nick` may go out under, in order: the nickname
|
||||
/// itself, then `nick1` to `nick3`, each within TeamSpeak's length limits.
|
||||
fn author_nicknames(nick: &str) -> Vec<String> {
|
||||
let nick = nick.trim();
|
||||
if nick.chars().count() < MIN_NICKNAME_CHARS {
|
||||
return Vec::new();
|
||||
}
|
||||
let fit = |suffix: &str| {
|
||||
let head: String = nick.chars().take(MAX_NICKNAME_CHARS - suffix.len()).collect();
|
||||
format!("{}{suffix}", head.trim_end())
|
||||
};
|
||||
std::iter::once(fit("")).chain((1..=3).map(|n| fit(&n.to_string()))).collect()
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
/// cosmetic, so failing keeps the server-assigned one. The name it got.
|
||||
async fn set_nickname(client: &QueryClient, base: &str) -> String {
|
||||
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,
|
||||
Ok(_) => return nickname,
|
||||
Err(voelin_query::Error::Query(e)) if e.id == ERR_NICKNAME_IN_USE => continue,
|
||||
Err(e) => {
|
||||
warn!(%e, %nickname, "could not set relay nickname");
|
||||
return;
|
||||
return base.to_owned();
|
||||
}
|
||||
}
|
||||
}
|
||||
warn!(base, "all relay nicknames in use");
|
||||
base.to_owned()
|
||||
}
|
||||
|
||||
async fn forward(
|
||||
@@ -193,3 +271,22 @@ async fn forward(
|
||||
}
|
||||
let _ = events.send(RelayEvent::Closed { channel, reason: "connection closed".into() });
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn posts_go_out_under_the_authors_name_then_numbered_variants() {
|
||||
assert_eq!(author_nicknames(" Alice "), ["Alice", "Alice1", "Alice2", "Alice3"]);
|
||||
// Too short for TeamSpeak: the relay's own name and the format.
|
||||
assert!(author_nicknames("Al").is_empty());
|
||||
let long = "x".repeat(40);
|
||||
let names = author_nicknames(&long);
|
||||
assert_eq!(names[0], "x".repeat(30));
|
||||
assert_eq!(names[1], format!("{}1", "x".repeat(29)));
|
||||
assert!(names.iter().all(|n| n.chars().count() <= MAX_NICKNAME_CHARS));
|
||||
// Characters, not bytes.
|
||||
assert_eq!(author_nicknames(&"é".repeat(31))[0].chars().count(), 30);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user