tsctl: headless CLI for connecting, channel tree and chat
- identity new/show (JSON identity files with hash-cash level) - versions: list signed client versions from Versions.csv - connect <addr> tree | chat server|channel|client | listen | repl with --client-version, --privilege-key, --server-password, --channel and --log-commands Verified against local TeamSpeak 3.13 and TeamSpeak 6.0.0-beta13.1 containers: connect, subscribe-all tree, server and channel chat round-trips between two clients. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
7 files changed
+4865
No files matched your search
Generated
+3936
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "tsctl"
|
||||
version = "0.1.0"
|
||||
description = "Headless command-line client for TeamSpeak 3/6 servers, used for development and integration tests."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
base64 = "0.22"
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
dirs = "6"
|
||||
futures = "0.3"
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = ["io-std", "io-util", "macros", "rt-multi-thread", "signal", "time"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tsclientlib = { path = "../../crates/proto/tsclientlib" }
|
||||
tsproto-packets = { path = "../../crates/proto/tsproto-packets" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,58 @@
|
||||
//! Load, create and store client identities as JSON files.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use tsclientlib::Identity;
|
||||
|
||||
pub fn default_path() -> PathBuf {
|
||||
dirs::config_dir().unwrap_or_else(|| PathBuf::from(".")).join("tsctl").join("identity.json")
|
||||
}
|
||||
|
||||
pub fn load(path: &Path) -> Result<Identity> {
|
||||
let data = fs::read_to_string(path)
|
||||
.with_context(|| format!("failed to read identity {}", path.display()))?;
|
||||
serde_json::from_str(&data).with_context(|| format!("invalid identity {}", path.display()))
|
||||
}
|
||||
|
||||
pub fn save(path: &Path, identity: &Identity) -> Result<()> {
|
||||
if let Some(dir) = path.parent() {
|
||||
fs::create_dir_all(dir).with_context(|| format!("failed to create {}", dir.display()))?;
|
||||
}
|
||||
let data = serde_json::to_string_pretty(identity)?;
|
||||
fs::write(path, data).with_context(|| format!("failed to write {}", path.display()))
|
||||
}
|
||||
|
||||
/// Create a new identity with at least the given security level.
|
||||
///
|
||||
/// Levels above ~24 take minutes; the work runs on the calling thread.
|
||||
pub fn create(level: u8) -> Identity {
|
||||
let mut identity = Identity::create();
|
||||
if identity.level() < level {
|
||||
identity.upgrade_level(level);
|
||||
}
|
||||
identity
|
||||
}
|
||||
|
||||
pub fn uid(identity: &Identity) -> String {
|
||||
identity.key().to_pub().get_uid()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
let dir = std::env::temp_dir().join(format!("tsctl-id-test-{}", std::process::id()));
|
||||
let path = dir.join("id.json");
|
||||
let identity = create(8);
|
||||
assert!(identity.level() >= 8);
|
||||
save(&path, &identity).unwrap();
|
||||
let loaded = load(&path).unwrap();
|
||||
assert_eq!(uid(&loaded), uid(&identity));
|
||||
assert_eq!(loaded.counter(), identity.counter());
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
//! `tsctl`: headless TeamSpeak 3/6 client for development and integration tests.
|
||||
|
||||
mod identity;
|
||||
mod session;
|
||||
mod tree;
|
||||
mod versions;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::{Args, Parser, Subcommand};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(version, about)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum Command {
|
||||
/// Manage the client identity (the key pair that gives the client its unique id).
|
||||
Identity {
|
||||
#[command(subcommand)]
|
||||
command: IdentityCommand,
|
||||
},
|
||||
/// List the signed client versions that can be sent in `clientinit`.
|
||||
Versions {
|
||||
/// Only show versions whose platform or version contains this text.
|
||||
filter: Option<String>,
|
||||
},
|
||||
/// Connect to a server and run an action.
|
||||
Connect(ConnectArgs),
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum IdentityCommand {
|
||||
/// Create a new identity and store it.
|
||||
New {
|
||||
/// Minimum security level (hash cash). Servers commonly require 8.
|
||||
#[arg(long, default_value_t = 8)]
|
||||
level: u8,
|
||||
/// Where to store the identity [default: <config dir>/tsctl/identity.json].
|
||||
#[arg(long)]
|
||||
out: Option<PathBuf>,
|
||||
/// Overwrite an existing file.
|
||||
#[arg(long)]
|
||||
force: bool,
|
||||
},
|
||||
/// Print uid and security level of a stored identity.
|
||||
Show {
|
||||
#[arg(long)]
|
||||
identity: Option<PathBuf>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub struct ConnectArgs {
|
||||
/// Server address: host, host:port, or a TeamSpeak server nickname.
|
||||
address: String,
|
||||
/// Nickname to use.
|
||||
#[arg(long, default_value = "tsctl")]
|
||||
nick: String,
|
||||
/// Identity file. Without it a temporary identity is generated.
|
||||
#[arg(long, env = "TSCTL_IDENTITY")]
|
||||
identity: Option<PathBuf>,
|
||||
/// Signed client version: `default`, an index or `<platform>@<version>` from `tsctl versions`.
|
||||
#[arg(long, default_value = "default")]
|
||||
client_version: String,
|
||||
/// Server password.
|
||||
#[arg(long, env = "TSCTL_SERVER_PASSWORD")]
|
||||
server_password: Option<String>,
|
||||
/// Privilege key (token) to redeem after connecting, e.g. the ServerAdmin key a new server prints.
|
||||
#[arg(long, env = "TSCTL_PRIVILEGE_KEY")]
|
||||
privilege_key: Option<String>,
|
||||
/// Channel to join, as a path like `Lobby/Sub`.
|
||||
#[arg(long)]
|
||||
channel: Option<String>,
|
||||
/// Log every command sent and received.
|
||||
#[arg(long)]
|
||||
log_commands: bool,
|
||||
/// Give up connecting after this many seconds.
|
||||
#[arg(long, default_value_t = 30)]
|
||||
connect_timeout: u64,
|
||||
#[command(subcommand)]
|
||||
action: Action,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
pub enum Action {
|
||||
/// Subscribe to all channels and print the channel tree with its clients.
|
||||
Tree {
|
||||
/// How long to wait for subscription results before printing.
|
||||
#[arg(long, default_value_t = 1500)]
|
||||
settle_ms: u64,
|
||||
},
|
||||
/// Send a text message and exit.
|
||||
Chat {
|
||||
#[command(subcommand)]
|
||||
target: ChatTarget,
|
||||
},
|
||||
/// Print text messages and client events until interrupted.
|
||||
Listen {
|
||||
/// Print events as JSON lines instead of text.
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
/// Exit successfully once a text message containing this text arrives.
|
||||
#[arg(long)]
|
||||
expect: Option<String>,
|
||||
/// Exit after this many seconds; fails if `--expect` was not satisfied.
|
||||
#[arg(long)]
|
||||
timeout: Option<u64>,
|
||||
},
|
||||
/// Interactive session. Type `/help` for commands.
|
||||
Repl,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug, Clone)]
|
||||
pub enum ChatTarget {
|
||||
/// Send to the server chat (everyone on the server).
|
||||
Server { message: String },
|
||||
/// Send to the chat of the channel we are in.
|
||||
Channel { message: String },
|
||||
/// Send a private message to a client id.
|
||||
Client { clid: u16, message: String },
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn")),
|
||||
)
|
||||
.with_writer(std::io::stderr)
|
||||
.init();
|
||||
|
||||
let cli = Cli::parse();
|
||||
match cli.command {
|
||||
Command::Identity { command } => run_identity(command),
|
||||
Command::Versions { filter } => {
|
||||
for (i, v) in versions::known_versions().iter().enumerate() {
|
||||
let matches = filter
|
||||
.as_deref()
|
||||
.is_none_or(|f| v.platform.contains(f) || v.version.contains(f));
|
||||
if matches {
|
||||
println!("{i:>3} {}@{}", v.platform, v.version);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Command::Connect(args) => {
|
||||
let rt = tokio::runtime::Runtime::new()?;
|
||||
rt.block_on(session::run(args))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_identity(command: IdentityCommand) -> Result<()> {
|
||||
match command {
|
||||
IdentityCommand::New { level, out, force } => {
|
||||
let path = out.unwrap_or_else(identity::default_path);
|
||||
if path.exists() && !force {
|
||||
anyhow::bail!("{} already exists, pass --force to overwrite", path.display());
|
||||
}
|
||||
let id = identity::create(level);
|
||||
identity::save(&path, &id)?;
|
||||
println!("uid: {}", identity::uid(&id));
|
||||
println!("level: {}", id.level());
|
||||
println!("saved: {}", path.display());
|
||||
Ok(())
|
||||
}
|
||||
IdentityCommand::Show { identity: path } => {
|
||||
let path = path.unwrap_or_else(identity::default_path);
|
||||
let id = identity::load(&path)?;
|
||||
println!("uid: {}", identity::uid(&id));
|
||||
println!("level: {}", id.level());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectArgs {
|
||||
fn connect_timeout(&self) -> Duration {
|
||||
Duration::from_secs(self.connect_timeout)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
//! Connected actions: tree, chat, listen, repl.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use futures::prelude::*;
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use tokio::time::{Instant, timeout_at};
|
||||
use tracing::{info, warn};
|
||||
use tsclientlib::events::{Event, PropertyId, PropertyValue};
|
||||
use tsclientlib::messages::c2s::{OutTokenUseMessage, OutTokenUsePart};
|
||||
use tsclientlib::prelude::*;
|
||||
use tsclientlib::{
|
||||
ChannelId, ClientId, Connection, DisconnectOptions, MessageHandle, MessageTarget, StreamItem,
|
||||
data,
|
||||
};
|
||||
use tsproto_packets::packets::OutCommand;
|
||||
|
||||
use crate::{Action, ChatTarget, ConnectArgs, identity, tree, versions};
|
||||
|
||||
pub async fn run(args: ConnectArgs) -> Result<()> {
|
||||
let mut options = Connection::build(args.address.clone())
|
||||
.name(args.nick.clone())
|
||||
.log_commands(args.log_commands);
|
||||
if let Some(version) = versions::resolve(&args.client_version)? {
|
||||
options = options.version(version);
|
||||
}
|
||||
if let Some(path) = &args.identity {
|
||||
options = options.identity(identity::load(path)?);
|
||||
}
|
||||
if let Some(password) = &args.server_password {
|
||||
options = options.password(password.clone());
|
||||
}
|
||||
if let Some(channel) = &args.channel {
|
||||
options = options.channel(channel.clone());
|
||||
}
|
||||
|
||||
let mut con = options.connect().context("failed to start connection")?;
|
||||
wait_connected(&mut con, Instant::now() + args.connect_timeout()).await?;
|
||||
info!(address = %args.address, "connected");
|
||||
|
||||
if let Some(token) = &args.privilege_key {
|
||||
let cmd = OutTokenUseMessage::new(&mut std::iter::once(OutTokenUsePart {
|
||||
token: token.as_str().into(),
|
||||
}));
|
||||
send_and_wait(&mut con, cmd, "tokenuse").await?;
|
||||
info!("privilege key redeemed");
|
||||
}
|
||||
|
||||
let result = match &args.action {
|
||||
Action::Tree { settle_ms } => print_tree(&mut con, Duration::from_millis(*settle_ms)).await,
|
||||
Action::Chat { target } => send_chat(&mut con, target).await,
|
||||
Action::Listen { json, expect, timeout } => {
|
||||
listen(&mut con, *json, expect.as_deref(), timeout.map(Duration::from_secs)).await
|
||||
}
|
||||
Action::Repl => repl(&mut con).await,
|
||||
};
|
||||
|
||||
disconnect(con).await;
|
||||
result
|
||||
}
|
||||
|
||||
/// What to do after handling one stream item.
|
||||
enum Flow {
|
||||
Continue,
|
||||
Stop,
|
||||
}
|
||||
|
||||
/// How [`pump`] ended.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum PumpEnd {
|
||||
Stopped,
|
||||
Deadline,
|
||||
Interrupted,
|
||||
}
|
||||
|
||||
/// Drive the connection, handing every item to `handler` until it returns
|
||||
/// [`Flow::Stop`], the deadline passes, or Ctrl-C is pressed.
|
||||
async fn pump(
|
||||
con: &mut Connection,
|
||||
deadline: Option<Instant>,
|
||||
mut handler: impl FnMut(&mut Connection, StreamItem) -> Result<Flow>,
|
||||
) -> Result<PumpEnd> {
|
||||
loop {
|
||||
let item = {
|
||||
let mut events = con.events();
|
||||
let next = async {
|
||||
match deadline {
|
||||
Some(deadline) => timeout_at(deadline, events.next()).await.ok(),
|
||||
None => Some(events.next().await),
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
item = next => item,
|
||||
_ = tokio::signal::ctrl_c() => return Ok(PumpEnd::Interrupted),
|
||||
}
|
||||
};
|
||||
match item {
|
||||
None => return Ok(PumpEnd::Deadline),
|
||||
Some(None) => bail!("disconnected from server"),
|
||||
Some(Some(item)) => {
|
||||
if let Flow::Stop = handler(con, item?)? {
|
||||
return Ok(PumpEnd::Stopped);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_connected(con: &mut Connection, deadline: Instant) -> Result<()> {
|
||||
let end = pump(con, Some(deadline), |_, item| {
|
||||
Ok(match item {
|
||||
StreamItem::BookEvents(_) => Flow::Stop,
|
||||
StreamItem::IdentityLevelIncreasing(level) => {
|
||||
eprintln!("server requires identity level {level}, improving identity...");
|
||||
Flow::Continue
|
||||
}
|
||||
_ => Flow::Continue,
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
match end {
|
||||
PumpEnd::Stopped => Ok(()),
|
||||
PumpEnd::Deadline => bail!("timed out while connecting"),
|
||||
PumpEnd::Interrupted => bail!("interrupted"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn disconnect(mut con: Connection) {
|
||||
if let Err(error) = con.disconnect(DisconnectOptions::new()) {
|
||||
warn!(%error, "failed to disconnect cleanly");
|
||||
return;
|
||||
}
|
||||
let drain = con.events().for_each(|_| future::ready(()));
|
||||
if tokio::time::timeout(Duration::from_secs(5), drain).await.is_err() {
|
||||
warn!("timed out waiting for disconnect");
|
||||
}
|
||||
}
|
||||
|
||||
/// Send a command and wait until the server acknowledges it.
|
||||
async fn send_and_wait(con: &mut Connection, cmd: OutCommand, what: &str) -> Result<()> {
|
||||
let handle = cmd.send_with_result(con)?;
|
||||
let mut result = None;
|
||||
let end = pump(con, Some(Instant::now() + Duration::from_secs(10)), |_, item| {
|
||||
Ok(match item {
|
||||
StreamItem::MessageResult(h, r) if h == handle => {
|
||||
result = Some(r);
|
||||
Flow::Stop
|
||||
}
|
||||
_ => Flow::Continue,
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
match (end, result) {
|
||||
(_, Some(Ok(()))) => Ok(()),
|
||||
(_, Some(Err(error))) => bail!("{what} failed: {error}"),
|
||||
(PumpEnd::Interrupted, None) => bail!("interrupted"),
|
||||
_ => bail!("{what}: no answer from server"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn print_tree(con: &mut Connection, settle: Duration) -> Result<()> {
|
||||
let cmd = con.get_state()?.server.set_subscribed(true);
|
||||
send_and_wait(con, cmd, "channelsubscribeall").await?;
|
||||
// Clients of newly subscribed channels arrive right after the answer.
|
||||
pump(con, Some(Instant::now() + settle), |_, _| Ok(Flow::Continue)).await?;
|
||||
print!("{}", tree::from_state(con.get_state()?));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn chat_command(state: &data::Connection, target: &ChatTarget) -> OutCommand {
|
||||
match target {
|
||||
ChatTarget::Server { message } => state.server.send_textmessage(message),
|
||||
ChatTarget::Channel { message } => state.send_message(MessageTarget::Channel, message),
|
||||
ChatTarget::Client { clid, message } => {
|
||||
state.send_message(MessageTarget::Client(ClientId(*clid)), message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_chat(con: &mut Connection, target: &ChatTarget) -> Result<()> {
|
||||
let cmd = chat_command(con.get_state()?, target);
|
||||
send_and_wait(con, cmd, "sendtextmessage").await
|
||||
}
|
||||
|
||||
fn target_label(target: &MessageTarget) -> &'static str {
|
||||
match target {
|
||||
MessageTarget::Server => "server",
|
||||
MessageTarget::Channel => "channel",
|
||||
MessageTarget::Client(_) => "private",
|
||||
MessageTarget::Poke(_) => "poke",
|
||||
}
|
||||
}
|
||||
|
||||
fn channel_name(state: &data::Connection, id: ChannelId) -> String {
|
||||
state.channels.get(&id).map(|c| c.name.clone()).unwrap_or_else(|| format!("cid {}", id.0))
|
||||
}
|
||||
|
||||
/// One line describing an event, or `None` for events not worth printing.
|
||||
fn describe(state: &data::Connection, event: &Event) -> Option<String> {
|
||||
match event {
|
||||
Event::Message { target, invoker, message } => Some(format!(
|
||||
"[{}] {} (clid {}): {message}",
|
||||
target_label(target),
|
||||
invoker.name,
|
||||
invoker.id.0
|
||||
)),
|
||||
Event::PropertyAdded { id: PropertyId::Client(clid), extra, .. } => {
|
||||
let client = state.clients.get(clid)?;
|
||||
let reason = extra.reason.map(|r| format!(" ({r:?})")).unwrap_or_default();
|
||||
Some(format!(
|
||||
"+ {} (clid {}) in #{}{reason}",
|
||||
client.name,
|
||||
clid.0,
|
||||
channel_name(state, client.channel)
|
||||
))
|
||||
}
|
||||
Event::PropertyRemoved {
|
||||
id: PropertyId::Client(clid),
|
||||
old: PropertyValue::Client(client),
|
||||
..
|
||||
} => Some(format!("- {} (clid {}) left", client.name, clid.0)),
|
||||
Event::PropertyChanged {
|
||||
id: PropertyId::ClientChannel(clid),
|
||||
old: PropertyValue::ChannelId(from),
|
||||
..
|
||||
} => {
|
||||
let client = state.clients.get(clid)?;
|
||||
Some(format!(
|
||||
"> {} (clid {}) moved #{} -> #{}",
|
||||
client.name,
|
||||
clid.0,
|
||||
channel_name(state, *from),
|
||||
channel_name(state, client.channel)
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Print book events; returns `true` if a text message contained `expect`.
|
||||
fn print_events(
|
||||
state: &data::Connection,
|
||||
events: &[Event],
|
||||
json: bool,
|
||||
expect: Option<&str>,
|
||||
) -> Result<bool> {
|
||||
let mut matched = false;
|
||||
for event in events {
|
||||
if let (Event::Message { message, .. }, Some(expect)) = (event, expect) {
|
||||
matched |= message.contains(expect);
|
||||
}
|
||||
if json {
|
||||
println!("{}", serde_json::to_string(event)?);
|
||||
} else if let Some(line) = describe(state, event) {
|
||||
println!("{line}");
|
||||
}
|
||||
}
|
||||
Ok(matched)
|
||||
}
|
||||
|
||||
async fn listen(
|
||||
con: &mut Connection,
|
||||
json: bool,
|
||||
expect: Option<&str>,
|
||||
timeout: Option<Duration>,
|
||||
) -> Result<()> {
|
||||
let deadline = timeout.map(|t| Instant::now() + t);
|
||||
let end = pump(con, deadline, |con, item| {
|
||||
if let StreamItem::BookEvents(events) = item
|
||||
&& print_events(con.get_state()?, &events, json, expect)?
|
||||
{
|
||||
return Ok(Flow::Stop);
|
||||
}
|
||||
Ok(Flow::Continue)
|
||||
})
|
||||
.await?;
|
||||
match (end, expect) {
|
||||
(PumpEnd::Deadline, Some(expect)) => bail!("timed out waiting for message {expect:?}"),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
const REPL_HELP: &str = "\
|
||||
commands:
|
||||
<text> send to the current channel
|
||||
/server <text> send to the server chat
|
||||
/channel <text> send to the current channel
|
||||
/msg <clid> <text> send a private message
|
||||
/tree print the channel tree
|
||||
/whoami print own client and channel
|
||||
/quit disconnect";
|
||||
|
||||
enum ReplInput {
|
||||
Item(Option<Result<StreamItem, tsclientlib::Error>>),
|
||||
Line(Option<String>),
|
||||
Interrupted,
|
||||
}
|
||||
|
||||
async fn repl(con: &mut Connection) -> Result<()> {
|
||||
let cmd = con.get_state()?.server.set_subscribed(true);
|
||||
cmd.send(con)?;
|
||||
println!("connected, type /help for commands");
|
||||
let mut lines = BufReader::new(tokio::io::stdin()).lines();
|
||||
let mut pending: Option<MessageHandle> = None;
|
||||
loop {
|
||||
let input = {
|
||||
let mut events = con.events();
|
||||
tokio::select! {
|
||||
item = events.next() => ReplInput::Item(item),
|
||||
line = lines.next_line() => ReplInput::Line(line?),
|
||||
_ = tokio::signal::ctrl_c() => ReplInput::Interrupted,
|
||||
}
|
||||
};
|
||||
match input {
|
||||
ReplInput::Interrupted | ReplInput::Line(None) => return Ok(()),
|
||||
ReplInput::Item(None) => bail!("disconnected from server"),
|
||||
ReplInput::Item(Some(item)) => match item? {
|
||||
StreamItem::BookEvents(events) => {
|
||||
print_events(con.get_state()?, &events, false, None)?;
|
||||
}
|
||||
StreamItem::MessageResult(handle, Err(error)) => {
|
||||
println!("error (command {}): {error}", handle.0);
|
||||
}
|
||||
StreamItem::MessageResult(handle, Ok(())) if Some(handle) == pending => {
|
||||
pending = None;
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
ReplInput::Line(Some(line)) => {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (command, rest) = line.split_once(' ').unwrap_or((line, ""));
|
||||
let target = match command {
|
||||
"/help" => {
|
||||
println!("{REPL_HELP}");
|
||||
continue;
|
||||
}
|
||||
"/quit" | "/exit" => return Ok(()),
|
||||
"/tree" => {
|
||||
print!("{}", tree::from_state(con.get_state()?));
|
||||
continue;
|
||||
}
|
||||
"/whoami" => {
|
||||
let state = con.get_state()?;
|
||||
let own = &state.clients[&state.own_client];
|
||||
println!(
|
||||
"{} (clid {}) in #{}",
|
||||
own.name,
|
||||
own.id.0,
|
||||
channel_name(state, own.channel)
|
||||
);
|
||||
continue;
|
||||
}
|
||||
"/server" => ChatTarget::Server { message: rest.into() },
|
||||
"/channel" => ChatTarget::Channel { message: rest.into() },
|
||||
"/msg" => {
|
||||
let Some((clid, message)) = rest.split_once(' ') else {
|
||||
println!("usage: /msg <clid> <text>");
|
||||
continue;
|
||||
};
|
||||
let Ok(clid) = clid.parse() else {
|
||||
println!("invalid client id {clid:?}");
|
||||
continue;
|
||||
};
|
||||
ChatTarget::Client { clid, message: message.into() }
|
||||
}
|
||||
c if c.starts_with('/') => {
|
||||
println!("unknown command {c}, try /help");
|
||||
continue;
|
||||
}
|
||||
_ => ChatTarget::Channel { message: line.into() },
|
||||
};
|
||||
let cmd = chat_command(con.get_state()?, &target);
|
||||
pending = Some(cmd.send_with_result(con)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
//! Render the channel tree of a connection as text.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
|
||||
use tsclientlib::data;
|
||||
use tsclientlib::{ChannelId, ClientType};
|
||||
|
||||
/// Minimal channel view, so the ordering logic can be tested without a connection.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ChannelNode {
|
||||
pub id: ChannelId,
|
||||
pub parent: ChannelId,
|
||||
/// Id of the sibling this channel is sorted below, `0` for the first one.
|
||||
pub order: ChannelId,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ClientNode {
|
||||
pub channel: ChannelId,
|
||||
pub name: String,
|
||||
pub talk_power: i32,
|
||||
pub is_query: bool,
|
||||
pub input_muted: bool,
|
||||
pub output_muted: bool,
|
||||
pub away: bool,
|
||||
}
|
||||
|
||||
/// Sort siblings by following the `order` links (each channel names the
|
||||
/// sibling directly above it). Channels whose predecessor is missing are
|
||||
/// appended at the end, sorted by id, so nothing is ever dropped.
|
||||
pub fn order_siblings(mut siblings: Vec<&ChannelNode>) -> Vec<&ChannelNode> {
|
||||
siblings.sort_by_key(|c| c.id.0);
|
||||
let mut by_prev: HashMap<ChannelId, &ChannelNode> = HashMap::new();
|
||||
for c in &siblings {
|
||||
by_prev.entry(c.order).or_insert(c);
|
||||
}
|
||||
let mut sorted = Vec::with_capacity(siblings.len());
|
||||
let mut prev = ChannelId(0);
|
||||
while let Some(c) = by_prev.remove(&prev) {
|
||||
sorted.push(c);
|
||||
prev = c.id;
|
||||
}
|
||||
for c in siblings {
|
||||
if !sorted.iter().any(|s| s.id == c.id) {
|
||||
sorted.push(c);
|
||||
}
|
||||
}
|
||||
sorted
|
||||
}
|
||||
|
||||
pub fn render(server_name: &str, channels: &[ChannelNode], clients: &[ClientNode]) -> String {
|
||||
let mut out = String::new();
|
||||
let _ = writeln!(out, "{server_name}");
|
||||
render_level(&mut out, channels, clients, ChannelId(0), 0);
|
||||
out
|
||||
}
|
||||
|
||||
fn render_level(
|
||||
out: &mut String,
|
||||
channels: &[ChannelNode],
|
||||
clients: &[ClientNode],
|
||||
parent: ChannelId,
|
||||
depth: usize,
|
||||
) {
|
||||
let siblings = order_siblings(channels.iter().filter(|c| c.parent == parent).collect());
|
||||
let indent = " ".repeat(depth);
|
||||
for channel in siblings {
|
||||
let _ = writeln!(out, "{indent}# {} (cid {})", channel.name, channel.id.0);
|
||||
let mut members: Vec<_> =
|
||||
clients.iter().filter(|c| c.channel == channel.id && !c.is_query).collect();
|
||||
members.sort_by(|a, b| b.talk_power.cmp(&a.talk_power).then_with(|| a.name.cmp(&b.name)));
|
||||
for client in members {
|
||||
let mut flags = Vec::new();
|
||||
if client.input_muted {
|
||||
flags.push("mic off");
|
||||
}
|
||||
if client.output_muted {
|
||||
flags.push("sound off");
|
||||
}
|
||||
if client.away {
|
||||
flags.push("away");
|
||||
}
|
||||
let flags =
|
||||
if flags.is_empty() { String::new() } else { format!(" [{}]", flags.join(", ")) };
|
||||
let _ = writeln!(out, "{indent} - {}{flags}", client.name);
|
||||
}
|
||||
render_level(out, channels, clients, channel.id, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_state(state: &data::Connection) -> String {
|
||||
let channels: Vec<_> = state
|
||||
.channels
|
||||
.values()
|
||||
.map(|c| ChannelNode { id: c.id, parent: c.parent, order: c.order, name: c.name.clone() })
|
||||
.collect();
|
||||
let clients: Vec<_> = state
|
||||
.clients
|
||||
.values()
|
||||
.map(|c| ClientNode {
|
||||
channel: c.channel,
|
||||
name: c.name.clone(),
|
||||
talk_power: c.talk_power,
|
||||
is_query: matches!(c.client_type, ClientType::Query { .. }),
|
||||
input_muted: c.input_muted,
|
||||
output_muted: c.output_muted,
|
||||
away: c.away_message.is_some(),
|
||||
})
|
||||
.collect();
|
||||
render(&state.server.name, &channels, &clients)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ch(id: u64, parent: u64, order: u64, name: &str) -> ChannelNode {
|
||||
ChannelNode {
|
||||
id: ChannelId(id),
|
||||
parent: ChannelId(parent),
|
||||
order: ChannelId(order),
|
||||
name: name.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn cl(channel: u64, name: &str, talk_power: i32) -> ClientNode {
|
||||
ClientNode {
|
||||
channel: ChannelId(channel),
|
||||
name: name.into(),
|
||||
talk_power,
|
||||
is_query: false,
|
||||
input_muted: false,
|
||||
output_muted: false,
|
||||
away: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follows_order_links() {
|
||||
// Display order: 7, 3, 5 (ids deliberately not sorted).
|
||||
let channels = [ch(5, 0, 3, "c"), ch(3, 0, 7, "b"), ch(7, 0, 0, "a")];
|
||||
let sorted = order_siblings(channels.iter().collect());
|
||||
let names: Vec<_> = sorted.iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(names, ["a", "b", "c"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_channels_with_broken_links() {
|
||||
let channels = [ch(1, 0, 0, "a"), ch(2, 0, 99, "orphan")];
|
||||
let sorted = order_siblings(channels.iter().collect());
|
||||
assert_eq!(sorted.len(), 2);
|
||||
assert_eq!(sorted[1].name, "orphan");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_nested_tree() {
|
||||
let channels = [ch(1, 0, 0, "Lobby"), ch(2, 0, 1, "Games"), ch(3, 2, 0, "Squad")];
|
||||
let mut query = cl(1, "serveradmin", 0);
|
||||
query.is_query = true;
|
||||
let mut muted = cl(3, "Bob", 0);
|
||||
muted.input_muted = true;
|
||||
let clients = [cl(1, "Alice", 10), cl(1, "Zed", 50), query, muted];
|
||||
let text = render("Test Server", &channels, &clients);
|
||||
assert_eq!(
|
||||
text,
|
||||
"Test Server\n\
|
||||
# Lobby (cid 1)\n \
|
||||
- Zed\n \
|
||||
- Alice\n\
|
||||
# Games (cid 2)\n \
|
||||
# Squad (cid 3)\n \
|
||||
- Bob [mic off]\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Known signed client versions.
|
||||
//!
|
||||
//! `clientinit` must carry a `client_version_sign` produced by TeamSpeak's
|
||||
//! private key, so a client can only claim versions from this list of captured
|
||||
//! signatures (the `Versions.csv` declaration file).
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use base64::prelude::*;
|
||||
use tsclientlib::Version;
|
||||
|
||||
const VERSIONS_CSV: &str =
|
||||
include_str!("../../../crates/proto/tsproto-structs/declarations/Versions.csv");
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct KnownVersion {
|
||||
pub version: String,
|
||||
pub platform: String,
|
||||
pub signature: String,
|
||||
}
|
||||
|
||||
impl KnownVersion {
|
||||
pub fn to_version(&self) -> Result<Version> {
|
||||
let signature = BASE64_STANDARD
|
||||
.decode(&self.signature)
|
||||
.with_context(|| format!("invalid signature for {}@{}", self.platform, self.version))?;
|
||||
Ok(Version::Custom {
|
||||
platform: self.platform.clone(),
|
||||
version: self.version.clone(),
|
||||
signature,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn known_versions() -> Vec<KnownVersion> {
|
||||
VERSIONS_CSV
|
||||
.lines()
|
||||
.skip(1)
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.filter_map(|l| {
|
||||
// The version string contains no commas, the signature is base64.
|
||||
let mut parts = l.splitn(3, ',');
|
||||
Some(KnownVersion {
|
||||
version: parts.next()?.to_string(),
|
||||
platform: parts.next()?.to_string(),
|
||||
signature: parts.next()?.trim().to_string(),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Resolve a `--client-version` argument.
|
||||
///
|
||||
/// Accepts `default` (the library default), an index into [`known_versions`],
|
||||
/// or `<platform>@<version>` with the exact strings from `tsctl versions`.
|
||||
pub fn resolve(spec: &str) -> Result<Option<Version>> {
|
||||
if spec == "default" {
|
||||
return Ok(None);
|
||||
}
|
||||
let versions = known_versions();
|
||||
if let Ok(i) = spec.parse::<usize>() {
|
||||
let Some(v) = versions.get(i) else {
|
||||
bail!("version index {i} out of range (0..{})", versions.len());
|
||||
};
|
||||
return v.to_version().map(Some);
|
||||
}
|
||||
let Some((platform, version)) = spec.split_once('@') else {
|
||||
bail!("expected `default`, an index or `<platform>@<version>`, got {spec:?}");
|
||||
};
|
||||
match versions.iter().find(|v| v.platform == platform && v.version == version) {
|
||||
Some(v) => v.to_version().map(Some),
|
||||
None => bail!("unknown client version {spec:?}, see `tsctl versions`"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_all_rows() {
|
||||
let versions = known_versions();
|
||||
assert!(versions.len() > 50);
|
||||
for v in &versions {
|
||||
let signature = BASE64_STANDARD.decode(&v.signature).unwrap();
|
||||
assert_eq!(signature.len(), 64, "{v:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_specs() {
|
||||
assert!(resolve("default").unwrap().is_none());
|
||||
let by_index = resolve("0").unwrap().unwrap();
|
||||
let first = &known_versions()[0];
|
||||
let by_name = resolve(&format!("{}@{}", first.platform, first.version)).unwrap().unwrap();
|
||||
assert_eq!(by_index, by_name);
|
||||
assert_eq!(by_name.get_platform(), first.platform);
|
||||
assert!(resolve("Nope@1.0").is_err());
|
||||
assert!(resolve("100000").is_err());
|
||||
assert!(resolve("garbage").is_err());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user