Rename the project to Voelin; packages hold only the app, tsgw is a Linux server package
The product is Voelin (app id io.github.faumaray.Voelin), everywhere: - crates tsc-* -> voelin-* (and voelin-fuzz), the desktop binary tsc-desktop -> voelin, the development CLI tsctl -> voelinctl; - the Android app: applicationId, Kotlin package io.github.faumaray.voelin, VoelinApp, libvoelin_android.so (JNI class names follow); - TSC_* environment variables -> VOELIN_*, Gradle properties tsc.* -> voelin.*, signing secrets VOELIN_SIGNING_*; - the data/config/cache/state folder tsc -> voelin, the keyring service, thread names, the dev compose project; - desktop file, metainfo, icon, Flatpak manifest, NSIS installer, docs. The gateway keeps its name: bin tsgw (crate voelin-gateway), TSGW_* env vars, the tsgw.v1+json protocol, the tsgw image. The window title and the About page show "Voelin <version>" from voelin_platform::APP_NAME. Packages (scripts/package.sh): the app only (voelin, voelin.exe, APKs, Flatpak). voelinctl is a development tool and in no package. tsgw is for servers and now its own Linux package, tsgw_<v>_amd64.deb and tsgw-<v>-linux-x86_64.tar.gz, with a sandboxed systemd unit (packaging/linux/tsgw.service; /etc/tsgw config, /var/lib/tsgw state) and dependencies of its own (no GUI libraries). docs/gateway-admin.md has an Install section. Fixes: - package-windows: makensis on Windows found no file through "D:/a/..." paths; pass Windows paths (cygpath -w). - StartupWMClass is the app id, which the app sets as its X11 WM_CLASS (it was the binary name, so desktops could not match the window). - Gradle wrapper download timeout 10 s -> 60 s (slow proxies). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
197 files changed
+1357
-1210
No files matched your search
@@ -0,0 +1,189 @@
|
||||
//! `voelinctl gateway`: talk to a tsgw gateway as a user.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use clap::Args;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use tokio::time::{Instant, timeout_at};
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
use voelin_gateway_proto::{ClientMsg, Envelope, ServerMsg, sign_challenge};
|
||||
use voelin_model::{ChatTarget, Presence};
|
||||
|
||||
#[derive(Args, Debug, Clone)]
|
||||
pub struct GatewayArgs {
|
||||
/// Gateway URL, e.g. ws://127.0.0.1:7788/v1.
|
||||
pub url: String,
|
||||
/// Identity file (must have connected to the server with voice once).
|
||||
#[arg(long, env = "VOELINCTL_IDENTITY")]
|
||||
pub identity: PathBuf,
|
||||
/// Receive presence and print the tree.
|
||||
#[arg(long)]
|
||||
pub presence: bool,
|
||||
/// Open a chat: `server` or `channel:<cid>`. Repeatable.
|
||||
#[arg(long = "open")]
|
||||
pub open: Vec<String>,
|
||||
/// Send a message: `<target>=<text>`, e.g. `channel:1=hello`.
|
||||
#[arg(long = "send")]
|
||||
pub send: Vec<String>,
|
||||
/// Print stored history of a target.
|
||||
#[arg(long)]
|
||||
pub history: Option<String>,
|
||||
/// Stop after this many seconds.
|
||||
#[arg(long, default_value_t = 10)]
|
||||
pub seconds: u64,
|
||||
/// Exit successfully when a chat message containing this text arrives.
|
||||
#[arg(long)]
|
||||
pub expect: Option<String>,
|
||||
/// Exit successfully when a client with this nickname is present.
|
||||
#[arg(long)]
|
||||
pub expect_client: Option<String>,
|
||||
}
|
||||
|
||||
fn parse_target(s: &str) -> Result<ChatTarget> {
|
||||
match s.split_once(':') {
|
||||
None if s == "server" => Ok(ChatTarget::Server),
|
||||
Some(("channel", cid)) => Ok(ChatTarget::Channel(cid.parse().context("channel id")?)),
|
||||
_ => bail!("target must be `server` or `channel:<cid>`, got {s:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run(args: GatewayArgs) -> Result<()> {
|
||||
let identity = crate::identity::load(&args.identity)?;
|
||||
let mut request = args.url.as_str().into_client_request()?;
|
||||
request
|
||||
.headers_mut()
|
||||
.insert("Sec-WebSocket-Protocol", voelin_gateway_proto::SUBPROTOCOL.parse()?);
|
||||
let (mut ws, _) = tokio_tungstenite::connect_async(request)
|
||||
.await
|
||||
.with_context(|| format!("failed to connect to {}", args.url))?;
|
||||
let deadline = Instant::now() + Duration::from_secs(args.seconds);
|
||||
|
||||
macro_rules! send {
|
||||
($id:expr, $msg:expr) => {
|
||||
ws.send(Message::Text(serde_json::to_string(&Envelope::with_id($id, $msg))?.into()))
|
||||
.await?
|
||||
};
|
||||
}
|
||||
|
||||
// Hello -> Auth -> AuthOk
|
||||
let (gateway_id, server_uid, nonce) = match next(&mut ws, deadline).await? {
|
||||
ServerMsg::Hello { gateway_id, server_uid, nonce, server_name, .. } => {
|
||||
eprintln!("gateway for {server_name:?}");
|
||||
(gateway_id, server_uid, nonce)
|
||||
}
|
||||
other => bail!("expected hello, got {other:?}"),
|
||||
};
|
||||
let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs() as i64;
|
||||
let key = identity.key();
|
||||
send!(
|
||||
1,
|
||||
ClientMsg::Auth {
|
||||
omega: key.to_pub().to_ts(),
|
||||
key_offset: identity.counter(),
|
||||
ts,
|
||||
signature: sign_challenge(key, &gateway_id, &server_uid, &nonce, ts),
|
||||
nickname: String::new(),
|
||||
}
|
||||
);
|
||||
match next(&mut ws, deadline).await? {
|
||||
ServerMsg::AuthOk { uid, .. } => eprintln!("logged in as {uid}"),
|
||||
ServerMsg::Error { code, message } => bail!("login refused: {code:?}: {message}"),
|
||||
other => bail!("unexpected {other:?}"),
|
||||
}
|
||||
|
||||
let mut id = 1;
|
||||
if args.presence {
|
||||
id += 1;
|
||||
send!(id, ClientMsg::SubscribePresence);
|
||||
}
|
||||
for target in &args.open {
|
||||
id += 1;
|
||||
send!(id, ClientMsg::OpenChat { target: parse_target(target)? });
|
||||
}
|
||||
for spec in &args.send {
|
||||
let (target, text) =
|
||||
spec.split_once('=').ok_or_else(|| anyhow!("--send needs <target>=<text>"))?;
|
||||
id += 1;
|
||||
send!(id, ClientMsg::SendChat { target: parse_target(target)?, text: text.to_string() });
|
||||
}
|
||||
if let Some(target) = &args.history {
|
||||
id += 1;
|
||||
send!(id, ClientMsg::History { target: parse_target(target)?, before: None, limit: 50 });
|
||||
}
|
||||
|
||||
let mut presence = Presence::default();
|
||||
loop {
|
||||
let msg = match next(&mut ws, deadline).await {
|
||||
Ok(m) => m,
|
||||
Err(e) if e.to_string() == "timeout" => break,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
match msg {
|
||||
ServerMsg::PresenceSnapshot { snapshot, .. } => {
|
||||
presence = Presence::from_snapshot(snapshot);
|
||||
println!(
|
||||
"presence: {} channels, {} clients",
|
||||
presence.channels.len(),
|
||||
presence.clients.len()
|
||||
);
|
||||
for c in presence.clients.values() {
|
||||
let channel =
|
||||
presence.channels.get(&c.channel).map(|c| c.name.as_str()).unwrap_or("?");
|
||||
println!(" {} in #{channel}", c.nickname);
|
||||
}
|
||||
}
|
||||
ServerMsg::PresenceDelta { seq, delta } => {
|
||||
presence.apply(&delta);
|
||||
println!("delta {seq}: {}", serde_json::to_string(&delta)?);
|
||||
}
|
||||
ServerMsg::ChatEvent { id, message } => {
|
||||
println!(
|
||||
"chat #{id} {:?} {}: {}",
|
||||
message.target, message.author_name, message.text
|
||||
);
|
||||
if args.expect.as_ref().is_some_and(|e| message.text.contains(e.as_str())) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
ServerMsg::History { messages } => {
|
||||
println!("history: {} messages", messages.len());
|
||||
for m in messages {
|
||||
println!(" #{} {}: {}", m.id, m.message.author_name, m.message.text);
|
||||
}
|
||||
}
|
||||
ServerMsg::Error { code, message } => println!("error: {code:?}: {message}"),
|
||||
ServerMsg::Ok | ServerMsg::Pong => {}
|
||||
other => println!("{other:?}"),
|
||||
}
|
||||
if let Some(nick) = &args.expect_client
|
||||
&& presence.clients.values().any(|c| &c.nickname == nick)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if args.expect.is_some() || args.expect_client.is_some() {
|
||||
bail!("expected event did not arrive");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn next<S>(ws: &mut S, deadline: Instant) -> Result<ServerMsg>
|
||||
where
|
||||
S: StreamExt<Item = Result<Message, tokio_tungstenite::tungstenite::Error>> + Unpin,
|
||||
{
|
||||
loop {
|
||||
let msg = timeout_at(deadline, ws.next()).await.map_err(|_| anyhow!("timeout"))?;
|
||||
match msg {
|
||||
Some(Ok(Message::Text(text))) => {
|
||||
let env: Envelope<ServerMsg> = serde_json::from_str(text.as_str())?;
|
||||
return Ok(env.msg);
|
||||
}
|
||||
Some(Ok(Message::Close(_))) | None => bail!("gateway closed the connection"),
|
||||
Some(Ok(_)) => continue,
|
||||
Some(Err(e)) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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("voelinctl").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!("voelinctl-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,243 @@
|
||||
//! `voelinctl`: headless TeamSpeak 3/6 client for development and integration tests.
|
||||
|
||||
mod gateway;
|
||||
mod identity;
|
||||
mod observe;
|
||||
mod query;
|
||||
mod session;
|
||||
mod stream;
|
||||
mod tree;
|
||||
mod versions;
|
||||
mod voice;
|
||||
|
||||
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),
|
||||
/// Run ServerQuery commands (raw TCP, SSH or HTTP WebQuery).
|
||||
Query(query::QueryArgs),
|
||||
/// Watch who is in which channel through ServerQuery, without appearing on the server.
|
||||
Observe(observe::ObserveArgs),
|
||||
/// Read and write a channel's chat through an invisible query relay.
|
||||
Relay(observe::RelayArgs),
|
||||
/// Use a tsgw gateway as a user: presence, chat, history.
|
||||
Gateway(gateway::GatewayArgs),
|
||||
}
|
||||
|
||||
#[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>/voelinctl/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 = "voelinctl")]
|
||||
nick: String,
|
||||
/// Identity file. Without it a temporary identity is generated.
|
||||
#[arg(long, env = "VOELINCTL_IDENTITY")]
|
||||
identity: Option<PathBuf>,
|
||||
/// Signed client version: `default`, an index or `<platform>@<version>` from `voelinctl versions`.
|
||||
#[arg(long, default_value = "default")]
|
||||
client_version: String,
|
||||
/// Server password.
|
||||
#[arg(long, env = "VOELINCTL_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 = "VOELINCTL_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>,
|
||||
},
|
||||
/// Send a raw, already escaped command (e.g. `serveredit virtualserver_name=Test\\sServer`)
|
||||
/// and wait for the result. Combine with `--log-commands` to see the answer.
|
||||
Raw { command: String },
|
||||
/// Send or record voice in the current channel.
|
||||
Voice {
|
||||
#[command(subcommand)]
|
||||
command: VoiceCommand,
|
||||
},
|
||||
/// TeamSpeak 6 streams (screen sharing): start, list or watch.
|
||||
Stream(stream::StreamArgs),
|
||||
/// Interactive session. Type `/help` for commands.
|
||||
Repl,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug, Clone)]
|
||||
pub enum VoiceCommand {
|
||||
/// Talk: send a WAV file or a test tone, in real time.
|
||||
Send {
|
||||
/// WAV file to send (any sample rate; resampled to 48 kHz).
|
||||
file: Option<PathBuf>,
|
||||
/// Send a sine tone of this frequency instead of a file.
|
||||
#[arg(long, conflicts_with = "file")]
|
||||
tone: Option<f32>,
|
||||
/// Tone length in seconds.
|
||||
#[arg(long, default_value_t = 3.0)]
|
||||
seconds: f32,
|
||||
/// Use the stereo Opus Music codec instead of mono Opus Voice.
|
||||
#[arg(long)]
|
||||
music: bool,
|
||||
},
|
||||
/// Listen: mix everything said in the channel into a stereo 48 kHz WAV file.
|
||||
Record {
|
||||
out: PathBuf,
|
||||
/// Recording length in seconds.
|
||||
#[arg(long, default_value_t = 5.0)]
|
||||
seconds: f32,
|
||||
/// Fail unless the recording contains this tone frequency (for tests).
|
||||
#[arg(long)]
|
||||
expect_tone: Option<f32>,
|
||||
},
|
||||
}
|
||||
|
||||
#[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))
|
||||
}
|
||||
Command::Query(args) => tokio::runtime::Runtime::new()?.block_on(query::run(args)),
|
||||
Command::Observe(args) => tokio::runtime::Runtime::new()?.block_on(observe::observe(args)),
|
||||
Command::Relay(args) => tokio::runtime::Runtime::new()?.block_on(observe::relay(args)),
|
||||
Command::Gateway(args) => tokio::runtime::Runtime::new()?.block_on(gateway::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());
|
||||
println!("omega: {}", id.key().to_pub().to_ts());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectArgs {
|
||||
fn connect_timeout(&self) -> Duration {
|
||||
Duration::from_secs(self.connect_timeout)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
//! `voelinctl observe` and `voelinctl relay`: invisible presence and channel chat.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use clap::Args;
|
||||
use tokio::sync::broadcast::error::RecvError;
|
||||
use tokio::time::{Instant, timeout_at};
|
||||
use voelin_model::{ChatMessage, ChatTarget, Presence, PresenceDelta};
|
||||
use voelin_observer::{
|
||||
Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool,
|
||||
};
|
||||
|
||||
use crate::query::QueryConnArgs;
|
||||
|
||||
#[derive(Args, Debug, Clone)]
|
||||
pub struct ObserveArgs {
|
||||
#[command(flatten)]
|
||||
pub conn: QueryConnArgs,
|
||||
/// Stop after this many seconds (default: until Ctrl-C).
|
||||
#[arg(long)]
|
||||
pub seconds: Option<u64>,
|
||||
/// Print events as JSON lines.
|
||||
#[arg(long)]
|
||||
pub json: bool,
|
||||
/// Resync interval in seconds.
|
||||
#[arg(long, default_value_t = 10)]
|
||||
pub poll: u64,
|
||||
/// Exit successfully once a client with this nickname is seen (for tests).
|
||||
#[arg(long)]
|
||||
pub expect_client: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug, Clone)]
|
||||
pub struct RelayArgs {
|
||||
#[command(flatten)]
|
||||
pub conn: QueryConnArgs,
|
||||
/// Channel id to relay.
|
||||
#[arg(long)]
|
||||
pub channel: u64,
|
||||
/// Post this message after opening the relay.
|
||||
#[arg(long)]
|
||||
pub send: Option<String>,
|
||||
/// Name shown in relayed posts.
|
||||
#[arg(long, default_value = "voelinctl")]
|
||||
pub nick: String,
|
||||
/// Stop after this many seconds (default: until Ctrl-C).
|
||||
#[arg(long)]
|
||||
pub seconds: Option<u64>,
|
||||
/// Exit successfully once a message containing this text arrives.
|
||||
#[arg(long)]
|
||||
pub expect: Option<String>,
|
||||
}
|
||||
|
||||
fn print_chat(msg: &ChatMessage) {
|
||||
let target = match &msg.target {
|
||||
ChatTarget::Server => "server".to_string(),
|
||||
ChatTarget::Channel(cid) => format!("channel {cid}"),
|
||||
ChatTarget::Private(_) => "private".to_string(),
|
||||
};
|
||||
println!("[{target}] {}: {}", msg.author_name, msg.text);
|
||||
}
|
||||
|
||||
fn print_tree(p: &Presence) {
|
||||
let channels: Vec<_> = p
|
||||
.channels
|
||||
.values()
|
||||
.map(|c| crate::tree::ChannelNode {
|
||||
id: tsclientlib::ChannelId(c.id),
|
||||
parent: tsclientlib::ChannelId(c.parent),
|
||||
order: tsclientlib::ChannelId(c.order),
|
||||
name: c.name.clone(),
|
||||
})
|
||||
.collect();
|
||||
let clients: Vec<_> = p
|
||||
.clients
|
||||
.values()
|
||||
.map(|c| crate::tree::ClientNode {
|
||||
channel: tsclientlib::ChannelId(c.channel),
|
||||
name: c.nickname.clone(),
|
||||
talk_power: 0,
|
||||
is_query: c.is_query,
|
||||
input_muted: c.input_muted,
|
||||
output_muted: c.output_muted,
|
||||
away: c.away.is_some(),
|
||||
streaming: c.streaming == Some(true),
|
||||
})
|
||||
.collect();
|
||||
print!(
|
||||
"{}",
|
||||
crate::tree::render(
|
||||
&format!("{} (via query, invisible)", p.server_name),
|
||||
&channels,
|
||||
&clients
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
fn describe(p: &Presence, d: &PresenceDelta) -> String {
|
||||
let name = |id: &u16| {
|
||||
p.clients.get(id).map(|c| c.nickname.clone()).unwrap_or_else(|| format!("clid {id}"))
|
||||
};
|
||||
let channel = |id: &u64| {
|
||||
p.channels.get(id).map(|c| c.name.clone()).unwrap_or_else(|| format!("cid {id}"))
|
||||
};
|
||||
match d {
|
||||
PresenceDelta::ClientJoined(c) => format!("+ {} in #{}", c.nickname, channel(&c.channel)),
|
||||
PresenceDelta::ClientLeft { id } => format!("- {} left", name(id)),
|
||||
PresenceDelta::ClientMoved { id, channel: to } => {
|
||||
format!("> {} moved to #{}", name(id), channel(to))
|
||||
}
|
||||
PresenceDelta::ClientChanged(c) => format!(
|
||||
"~ {} changed (muted: {}, away: {})",
|
||||
c.nickname,
|
||||
c.input_muted,
|
||||
c.away.is_some()
|
||||
),
|
||||
PresenceDelta::ChannelAdded(c) => format!("+ channel #{}", c.name),
|
||||
PresenceDelta::ChannelChanged(c) => format!("~ channel #{}", c.name),
|
||||
PresenceDelta::ChannelRemoved { id } => format!("- channel {}", channel(id)),
|
||||
PresenceDelta::ServerRenamed { name } => format!("~ server renamed to {name}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn observe(args: ObserveArgs) -> Result<()> {
|
||||
let mut config = ObserverConfig::new(args.conn.connect_config());
|
||||
config.poll_interval = Duration::from_secs(args.poll);
|
||||
let observer = Observer::spawn(config);
|
||||
let mut events = observer.subscribe();
|
||||
let deadline = args.seconds.map(|s| Instant::now() + Duration::from_secs(s));
|
||||
loop {
|
||||
let next = async {
|
||||
match deadline {
|
||||
Some(d) => timeout_at(d, events.recv()).await.ok(),
|
||||
None => Some(events.recv().await),
|
||||
}
|
||||
};
|
||||
let event = tokio::select! {
|
||||
e = next => e,
|
||||
_ = tokio::signal::ctrl_c() => return Ok(()),
|
||||
};
|
||||
let event = match event {
|
||||
None => break,
|
||||
Some(Ok(e)) => e,
|
||||
Some(Err(RecvError::Lagged(n))) => {
|
||||
eprintln!("(missed {n} events)");
|
||||
continue;
|
||||
}
|
||||
Some(Err(RecvError::Closed)) => bail!("observer stopped"),
|
||||
};
|
||||
let presence = observer.presence();
|
||||
let presence = presence.read().unwrap().clone();
|
||||
if args.json {
|
||||
match &event {
|
||||
ObserverEvent::Snapshot(s) => println!("{}", serde_json::to_string(s)?),
|
||||
ObserverEvent::Delta(d) => println!("{}", serde_json::to_string(d)?),
|
||||
ObserverEvent::Chat(m) => println!("{}", serde_json::to_string(m)?),
|
||||
ObserverEvent::Disconnected(r) => {
|
||||
println!("{}", serde_json::json!({"disconnected": r}))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match &event {
|
||||
ObserverEvent::Snapshot(_) => print_tree(&presence),
|
||||
ObserverEvent::Delta(d) => println!("{}", describe(&presence, d)),
|
||||
ObserverEvent::Chat(m) => print_chat(m),
|
||||
ObserverEvent::Disconnected(r) => println!("! disconnected: {r}"),
|
||||
}
|
||||
}
|
||||
if let Some(nick) = &args.expect_client
|
||||
&& presence.clients.values().any(|c| &c.nickname == nick)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if let Some(nick) = &args.expect_client {
|
||||
bail!("client {nick:?} not seen");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn relay(args: RelayArgs) -> Result<()> {
|
||||
let pool = RelayPool::new(RelayConfig::new(args.conn.connect_config()));
|
||||
let mut events = pool.subscribe();
|
||||
pool.open(args.channel).await?;
|
||||
println!("relaying channel {}", args.channel);
|
||||
if let Some(text) = &args.send {
|
||||
pool.send(args.channel, &args.nick, text).await?;
|
||||
println!("sent");
|
||||
}
|
||||
let result = relay_loop(&args, &mut events).await;
|
||||
pool.close_all().await;
|
||||
result
|
||||
}
|
||||
|
||||
async fn relay_loop(
|
||||
args: &RelayArgs,
|
||||
events: &mut tokio::sync::broadcast::Receiver<RelayEvent>,
|
||||
) -> Result<()> {
|
||||
let deadline = args.seconds.map(|s| Instant::now() + Duration::from_secs(s));
|
||||
loop {
|
||||
let next = async {
|
||||
match deadline {
|
||||
Some(d) => timeout_at(d, events.recv()).await.ok(),
|
||||
None => Some(events.recv().await),
|
||||
}
|
||||
};
|
||||
let event = tokio::select! {
|
||||
e = next => e,
|
||||
_ = tokio::signal::ctrl_c() => return Ok(()),
|
||||
};
|
||||
match event {
|
||||
None => break,
|
||||
Some(Ok(RelayEvent::Message(m))) => {
|
||||
print_chat(&m);
|
||||
if args.expect.as_ref().is_some_and(|e| m.text.contains(e.as_str())) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Some(Ok(RelayEvent::Closed { reason, .. })) => bail!("relay closed: {reason}"),
|
||||
Some(Err(RecvError::Lagged(_))) => {}
|
||||
Some(Err(RecvError::Closed)) => break,
|
||||
}
|
||||
}
|
||||
if let Some(expect) = &args.expect {
|
||||
bail!("no message containing {expect:?}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//! `voelinctl query`: ServerQuery commands and events.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::Args;
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use voelin_query::{Command, Connect, LineOptions, QueryClient, Row, Transport};
|
||||
|
||||
/// How to reach and log into a ServerQuery interface.
|
||||
#[derive(Args, Debug, Clone)]
|
||||
pub struct QueryConnArgs {
|
||||
/// Transport: raw (TS3 only), ssh or http.
|
||||
#[arg(value_enum)]
|
||||
pub transport: TransportArg,
|
||||
/// host:port of the query interface (e.g. 127.0.0.1:10022).
|
||||
pub addr: String,
|
||||
/// Login name (raw/SSH).
|
||||
#[arg(long, default_value = "serveradmin")]
|
||||
pub user: String,
|
||||
/// Password (raw/SSH) or API key (HTTP). Without it, HTTP runs as guest.
|
||||
#[arg(long, env = "VOELINCTL_QUERY_SECRET", hide_env_values = true)]
|
||||
pub secret: Option<String>,
|
||||
/// Select the virtual server by its voice port instead of id 1.
|
||||
#[arg(long)]
|
||||
pub server_port: Option<u16>,
|
||||
/// Our IP is on the server's query allowlist: skip client-side rate limiting.
|
||||
#[arg(long)]
|
||||
pub allowlisted: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug, Clone)]
|
||||
pub struct QueryArgs {
|
||||
#[command(flatten)]
|
||||
pub conn: QueryConnArgs,
|
||||
/// After the commands, print events for this many seconds.
|
||||
#[arg(long)]
|
||||
pub events: Option<u64>,
|
||||
/// Command line to run, e.g. `clientlist -uid`. Without one, commands are read from stdin.
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
pub command: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(clap::ValueEnum, Clone, Copy, Debug)]
|
||||
pub enum TransportArg {
|
||||
Raw,
|
||||
Ssh,
|
||||
Http,
|
||||
}
|
||||
|
||||
impl QueryConnArgs {
|
||||
pub fn connect_config(&self) -> Connect {
|
||||
Connect {
|
||||
transport: match self.transport {
|
||||
TransportArg::Raw => Transport::Raw,
|
||||
TransportArg::Ssh => Transport::Ssh,
|
||||
TransportArg::Http => Transport::Http,
|
||||
},
|
||||
addr: self.addr.clone(),
|
||||
user: self.user.clone(),
|
||||
secret: self.secret.clone(),
|
||||
server_port: self.server_port,
|
||||
server_id: None,
|
||||
line: LineOptions {
|
||||
rate_limit: if self.allowlisted { None } else { LineOptions::default().rate_limit },
|
||||
..Default::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn print_rows(rows: &[Row]) {
|
||||
for row in rows {
|
||||
let fields: Vec<String> = row.0.iter().map(|(k, v)| format!("{k}={v}")).collect();
|
||||
println!("{}", fields.join(" "));
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run(args: QueryArgs) -> Result<()> {
|
||||
let (client, events) = QueryClient::connect(&args.conn.connect_config())
|
||||
.await
|
||||
.context("query connection failed")?;
|
||||
|
||||
if args.command.is_empty() {
|
||||
let mut lines = BufReader::new(tokio::io::stdin()).lines();
|
||||
while let Some(line) = lines.next_line().await? {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
run_line(&client, &line).await;
|
||||
}
|
||||
} else {
|
||||
let line = args.command.join(" ");
|
||||
let Some(cmd) = Command::parse(&line) else { bail!("empty command") };
|
||||
print_rows(&client.send(&cmd).await?);
|
||||
}
|
||||
|
||||
if let Some(secs) = args.events {
|
||||
let Some(mut events) = events else { bail!("this transport has no events") };
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(secs);
|
||||
while let Ok(Some(event)) = tokio::time::timeout_at(deadline, events.recv()).await {
|
||||
print!("{}: ", event.name);
|
||||
print_rows(&event.rows);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_line(client: &QueryClient, line: &str) {
|
||||
let Some(cmd) = Command::parse(line) else { return };
|
||||
match client.send(&cmd).await {
|
||||
Ok(rows) => {
|
||||
print_rows(&rows);
|
||||
println!("ok");
|
||||
}
|
||||
Err(error) => println!("error: {error}"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
//! 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, InMessage, MessageHandle, MessageTarget,
|
||||
StreamItem, data,
|
||||
};
|
||||
use tsproto_packets::packets::{Direction, Flags, OutCommand, PacketType};
|
||||
|
||||
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::Raw { command } => {
|
||||
let cmd = OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, command);
|
||||
send_and_wait(&mut con, cmd, "command").await.map(|()| println!("ok"))
|
||||
}
|
||||
Action::Voice { command } => crate::voice::run(&mut con, command).await,
|
||||
Action::Stream(stream) => crate::stream::run(&mut con, stream).await,
|
||||
Action::Repl => repl(&mut con).await,
|
||||
};
|
||||
|
||||
disconnect(con).await;
|
||||
result
|
||||
}
|
||||
|
||||
/// What to do after handling one stream item.
|
||||
pub(crate) enum Flow {
|
||||
Continue,
|
||||
Stop,
|
||||
}
|
||||
|
||||
/// How [`pump`] ended.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) 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.
|
||||
pub(crate) 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)
|
||||
))
|
||||
}
|
||||
Event::PropertyChanged { id: PropertyId::ClientIsStreaming(clid), .. } => {
|
||||
let client = state.clients.get(clid)?;
|
||||
let what = if client.is_streaming == Some(true) { "started" } else { "stopped" };
|
||||
Some(format!("* {} (clid {}) {what} streaming", client.name, clid.0))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One line for TeamSpeak 6 stream notifications, `None` for other messages.
|
||||
fn describe_message(msg: &InMessage) -> Option<String> {
|
||||
let lines: Vec<String> = match msg {
|
||||
InMessage::StreamStarted(m) => m
|
||||
.iter()
|
||||
.map(|p| {
|
||||
format!(
|
||||
"* stream {} started by clid {} (name {:?}, type {:?}, bitrate {:?}, audio {:?})",
|
||||
p.stream_id,
|
||||
p.client_id.0,
|
||||
p.stream_name.as_deref().unwrap_or(""),
|
||||
p.stream_type,
|
||||
p.bitrate,
|
||||
p.audio
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
InMessage::StreamStopped(m) => {
|
||||
m.iter().map(|p| format!("* stream {} stopped", p.stream_id)).collect()
|
||||
}
|
||||
InMessage::JoinStreamRequest(m) => m
|
||||
.iter()
|
||||
.map(|p| format!("* clid {} asks to join stream {}", p.client_id.0, p.stream_id))
|
||||
.collect(),
|
||||
InMessage::StreamSignaling(m) => m
|
||||
.iter()
|
||||
.map(|p| {
|
||||
format!("* signaling from clid {} on {}: {}", p.client_id.0, p.stream_id, p.json)
|
||||
})
|
||||
.collect(),
|
||||
InMessage::StreamClientJoined(m) => m
|
||||
.iter()
|
||||
.map(|p| format!("* clid {} joined stream {}", p.client_id.0, p.stream_id))
|
||||
.collect(),
|
||||
InMessage::StreamClientLeft(m) => m
|
||||
.iter()
|
||||
.map(|p| format!("* clid {} left stream {}", p.client_id.0, p.stream_id))
|
||||
.collect(),
|
||||
_ => return None,
|
||||
};
|
||||
Some(lines.join("\n"))
|
||||
}
|
||||
|
||||
/// 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| {
|
||||
match item {
|
||||
StreamItem::BookEvents(events) => {
|
||||
if print_events(con.get_state()?, &events, json, expect)? {
|
||||
return Ok(Flow::Stop);
|
||||
}
|
||||
}
|
||||
StreamItem::MessageEvent(msg) if !json => {
|
||||
if let Some(line) = describe_message(&msg) {
|
||||
println!("{line}");
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
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
|
||||
/raw <command> send a raw, already escaped command
|
||||
/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::MessageEvent(msg) => {
|
||||
if let Some(line) = describe_message(&msg) {
|
||||
println!("{line}");
|
||||
}
|
||||
}
|
||||
StreamItem::MessageResult(handle, Err(error)) => {
|
||||
println!("error (command {}): {error}", handle.0);
|
||||
}
|
||||
StreamItem::MessageResult(handle, Ok(())) if Some(handle) == pending => {
|
||||
println!("ok (command {})", handle.0);
|
||||
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;
|
||||
}
|
||||
"/raw" => {
|
||||
let cmd = OutCommand::new(
|
||||
Direction::C2S,
|
||||
Flags::empty(),
|
||||
PacketType::Command,
|
||||
rest,
|
||||
);
|
||||
pending = Some(cmd.send_with_result(con)?);
|
||||
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,658 @@
|
||||
//! `voelinctl connect ... stream start|list|watch`: TeamSpeak 6 streams.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::{Args, Subcommand};
|
||||
use futures::prelude::*;
|
||||
use tokio::io::{AsyncBufReadExt, BufReader, Lines, Stdin};
|
||||
use tokio::time::{Instant, Interval, sleep_until};
|
||||
use tsclientlib::events::{Event, PropertyId};
|
||||
use tsclientlib::prelude::*;
|
||||
use tsclientlib::{ClientId, Connection, MessageHandle, StreamItem};
|
||||
use voelin_core::media::voelin_media::capture::SourceId;
|
||||
use voelin_core::media::voelin_media::{Codecs, VideoFrame, convert};
|
||||
use voelin_core::media::{
|
||||
CaptureBackend, EncodedSource, Latest, Streamer, StreamerConfig, VideoPipeline, peer_config,
|
||||
stream_codec,
|
||||
};
|
||||
use voelin_model::ServerFlavor;
|
||||
use voelin_stream::{
|
||||
EndReason, FrameSource, MediaKind, Output, PeerConfig, Request, StreamEvent, StreamInfo,
|
||||
StreamNotification, StreamSetup, StreamerEvent, StreamerOptions, Streams, WatchEvent,
|
||||
};
|
||||
|
||||
#[derive(Args, Debug, Clone)]
|
||||
pub struct StreamArgs {
|
||||
#[command(subcommand)]
|
||||
command: StreamCommand,
|
||||
/// Media over 127.0.0.1 only (both ends on this machine), no STUN.
|
||||
#[arg(long, global = true)]
|
||||
loopback: bool,
|
||||
/// STUN server (`host:port`) for a public candidate; repeatable [default: TeamSpeak's].
|
||||
#[arg(long, global = true)]
|
||||
stun: Vec<String>,
|
||||
/// Do not use STUN.
|
||||
#[arg(long, global = true, conflicts_with = "stun")]
|
||||
no_stun: bool,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug, Clone)]
|
||||
pub enum StreamCommand {
|
||||
/// Stream in our channel: the screen (VP8) and system audio (Opus).
|
||||
/// Without `--auto-accept`, answer join requests on stdin: `accept
|
||||
/// <clid>`, `deny <clid>`, `kick <clid>`, `stop`.
|
||||
Start {
|
||||
/// Stream name.
|
||||
#[arg(long, default_value = "voelinctl")]
|
||||
name: String,
|
||||
/// What to capture: `synthetic` (a moving test pattern and a tone),
|
||||
/// `x11[:<monitor>]`, `screen[:<monitor>]` (this session's backend),
|
||||
/// `window:<id>` or `portal` (the desktop's dialog).
|
||||
#[arg(long, default_value = "screen")]
|
||||
source: String,
|
||||
/// Same as `--source synthetic`.
|
||||
#[arg(long, conflicts_with = "source")]
|
||||
synthetic: bool,
|
||||
/// Size of the test pattern.
|
||||
#[arg(long, default_value = "1280x720")]
|
||||
size: String,
|
||||
/// Accept every viewer.
|
||||
#[arg(long)]
|
||||
auto_accept: bool,
|
||||
/// Stop after this many seconds [default: until Ctrl-C].
|
||||
#[arg(long)]
|
||||
seconds: Option<u64>,
|
||||
/// Video frames per second.
|
||||
#[arg(long, default_value_t = 30)]
|
||||
fps: u32,
|
||||
/// Video bitrate in kbit/s (announced in `setupstream` too).
|
||||
#[arg(long, default_value_t = 4608)]
|
||||
bitrate: u32,
|
||||
/// No audio track.
|
||||
#[arg(long)]
|
||||
no_audio: bool,
|
||||
},
|
||||
/// List the streams in our channel.
|
||||
List {
|
||||
/// How long to collect stream announcements before printing.
|
||||
#[arg(long, default_value_t = 1500)]
|
||||
settle_ms: u64,
|
||||
},
|
||||
/// Watch a stream (the first one that shows up if neither `--id` nor
|
||||
/// `--streamer-nick` is given).
|
||||
Watch {
|
||||
/// Stream id.
|
||||
#[arg(long)]
|
||||
id: Option<String>,
|
||||
/// Nickname of the streamer.
|
||||
#[arg(long)]
|
||||
streamer_nick: Option<String>,
|
||||
/// Exit successfully once this many video frames were decoded.
|
||||
#[arg(long)]
|
||||
expect_frames: Option<u64>,
|
||||
/// Give up after this many seconds; fails if `--expect-frames` was not reached.
|
||||
#[arg(long)]
|
||||
timeout: Option<u64>,
|
||||
/// Save the last decoded picture as PNG.
|
||||
#[arg(long)]
|
||||
save_frame: Option<PathBuf>,
|
||||
},
|
||||
}
|
||||
|
||||
pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> {
|
||||
let (own, version) = {
|
||||
let state = con.get_state()?;
|
||||
(state.own_client, state.server.version.clone())
|
||||
};
|
||||
if !ServerFlavor::from_version_string(&version).capabilities().streams {
|
||||
bail!("streams need a TeamSpeak 6 server (this one is {version})");
|
||||
}
|
||||
let mut config = if args.loopback { PeerConfig::loopback() } else { PeerConfig::default() };
|
||||
if !args.stun.is_empty() {
|
||||
config.stun_servers = args.stun.clone();
|
||||
} else if args.no_stun {
|
||||
config.stun_servers.clear();
|
||||
}
|
||||
// Offer the codec we encode, accept what we decode.
|
||||
let codecs = Arc::new(Codecs::new());
|
||||
let config = peer_config(&codecs, config);
|
||||
let codec = stream_codec(&codecs, &config);
|
||||
let mut driver = Driver { streams: Streams::new(own, config), pending: HashMap::new() };
|
||||
let result = match &args.command {
|
||||
StreamCommand::Start {
|
||||
name,
|
||||
source,
|
||||
synthetic,
|
||||
size,
|
||||
auto_accept,
|
||||
seconds,
|
||||
fps,
|
||||
bitrate,
|
||||
no_audio,
|
||||
} => {
|
||||
let source = if *synthetic { "synthetic" } else { source.as_str() };
|
||||
let (source, backend) = parse_source(source)?;
|
||||
let Some(codec) = codec else { bail!("no video encoder in this build") };
|
||||
let config = StreamerConfig {
|
||||
source,
|
||||
backend,
|
||||
fps: *fps,
|
||||
bitrate_kbps: *bitrate,
|
||||
codec,
|
||||
audio: !no_audio,
|
||||
synthetic_size: parse_size(size)?,
|
||||
..StreamerConfig::default()
|
||||
};
|
||||
let streamer = Streamer::start(&codecs, config).await.context("capture")?;
|
||||
println!("capturing with {} ({codec})", streamer.backend());
|
||||
if let Some(e) = streamer.audio_error() {
|
||||
println!("no system audio: {e}");
|
||||
}
|
||||
let setup = StreamSetup {
|
||||
name: name.clone(),
|
||||
bitrate: *bitrate,
|
||||
audio: streamer.has_audio(),
|
||||
..Default::default()
|
||||
};
|
||||
let options = StreamerOptions { setup, auto_accept: *auto_accept };
|
||||
let source = EncodedSource::new(streamer);
|
||||
start(con, &mut driver, options, source, seconds.map(Duration::from_secs)).await
|
||||
}
|
||||
StreamCommand::List { settle_ms } => {
|
||||
list(con, &mut driver, Duration::from_millis(*settle_ms)).await
|
||||
}
|
||||
StreamCommand::Watch { id, streamer_nick, expect_frames, timeout, save_frame } => {
|
||||
let target = Target { id: id.clone(), streamer_nick: streamer_nick.clone() };
|
||||
let timeout = timeout.map(Duration::from_secs);
|
||||
let expect = *expect_frames;
|
||||
let save = save_frame.as_deref();
|
||||
watch(con, &mut driver, codecs, &target, expect, timeout, save).await
|
||||
}
|
||||
};
|
||||
driver.finish(con).await;
|
||||
result
|
||||
}
|
||||
|
||||
/// `synthetic`, `x11[:<monitor>]`, `screen[:<monitor>]`, `window:<id>`, `portal`.
|
||||
fn parse_source(spec: &str) -> Result<(SourceId, CaptureBackend)> {
|
||||
let (kind, arg) = spec.split_once(':').map_or((spec, None), |(k, a)| (k, Some(a)));
|
||||
let number = |default: u64| -> Result<u64> {
|
||||
arg.map_or(Ok(default), |a| {
|
||||
let a = a.trim_start_matches("0x");
|
||||
let radix = if a.len() < arg.unwrap_or_default().len() { 16 } else { 10 };
|
||||
u64::from_str_radix(a, radix).with_context(|| format!("bad number in {spec:?}"))
|
||||
})
|
||||
};
|
||||
Ok(match kind {
|
||||
"synthetic" => (SourceId::Synthetic, CaptureBackend::Auto),
|
||||
"portal" => (SourceId::Portal, CaptureBackend::Auto),
|
||||
"x11" => (SourceId::Monitor(number(0)? as u32), CaptureBackend::X11),
|
||||
"screen" | "monitor" => (SourceId::Monitor(number(0)? as u32), CaptureBackend::Auto),
|
||||
"window" if arg.is_some() => (SourceId::Window(number(0)?), CaptureBackend::Auto),
|
||||
_ => bail!("unknown source {spec:?}: synthetic, x11[:N], screen[:N], window:<id>, portal"),
|
||||
})
|
||||
}
|
||||
|
||||
/// `<width>x<height>`.
|
||||
fn parse_size(size: &str) -> Result<(u32, u32)> {
|
||||
let parsed = size.split_once('x').and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?)));
|
||||
parsed.with_context(|| format!("bad size {size:?}, expected e.g. 1280x720"))
|
||||
}
|
||||
|
||||
/// What woke the driver.
|
||||
enum Wake {
|
||||
/// Connection or peer activity; the new events are returned by `flush`.
|
||||
Stream,
|
||||
Tick,
|
||||
Line(Option<String>),
|
||||
Interrupted,
|
||||
Deadline,
|
||||
}
|
||||
|
||||
/// Runs the stream sessions on the connection.
|
||||
struct Driver {
|
||||
streams: Streams,
|
||||
/// Stream commands waiting for the server's answer.
|
||||
pending: HashMap<MessageHandle, Request>,
|
||||
}
|
||||
|
||||
impl Driver {
|
||||
/// Wait for the next input and handle it.
|
||||
async fn next(
|
||||
&mut self,
|
||||
con: &mut Connection,
|
||||
deadline: Option<Instant>,
|
||||
tick: Option<&mut Interval>,
|
||||
lines: Option<&mut Lines<BufReader<Stdin>>>,
|
||||
) -> Result<Wake> {
|
||||
let item = {
|
||||
let mut events = con.events();
|
||||
let deadline = async {
|
||||
match deadline {
|
||||
Some(d) => sleep_until(d).await,
|
||||
None => future::pending().await,
|
||||
}
|
||||
};
|
||||
let tick = async {
|
||||
match tick {
|
||||
Some(t) => t.tick().await,
|
||||
None => future::pending().await,
|
||||
}
|
||||
};
|
||||
let line = async {
|
||||
match lines {
|
||||
Some(l) => l.next_line().await,
|
||||
None => future::pending().await,
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
item = events.next() => item,
|
||||
() = self.streams.wait_peers() => return Ok(Wake::Stream),
|
||||
_ = tick => return Ok(Wake::Tick),
|
||||
line = line => return Ok(Wake::Line(line?)),
|
||||
_ = tokio::signal::ctrl_c() => return Ok(Wake::Interrupted),
|
||||
() = deadline => return Ok(Wake::Deadline),
|
||||
}
|
||||
};
|
||||
match item {
|
||||
None => bail!("disconnected from server"),
|
||||
Some(item) => self.item(con, item?).await?,
|
||||
}
|
||||
Ok(Wake::Stream)
|
||||
}
|
||||
|
||||
async fn item(&mut self, con: &mut Connection, item: StreamItem) -> Result<()> {
|
||||
match item {
|
||||
StreamItem::MessageEvent(msg) => {
|
||||
for n in StreamNotification::from_message(&msg) {
|
||||
self.streams.handle_notification(n).await;
|
||||
}
|
||||
}
|
||||
StreamItem::MessageResult(handle, result) => {
|
||||
if let (Some(request), Err(e)) = (self.pending.remove(&handle), result) {
|
||||
self.streams.request_failed(&request, &e.to_string());
|
||||
}
|
||||
}
|
||||
StreamItem::BookEvents(events) => {
|
||||
let state = con.get_state()?;
|
||||
for e in &events {
|
||||
if let Event::PropertyChanged {
|
||||
id: PropertyId::ClientIsStreaming(clid), ..
|
||||
} = e && let Some(streaming) =
|
||||
state.clients.get(clid).and_then(|c| c.is_streaming)
|
||||
{
|
||||
self.streams.set_client_streaming(*clid, streaming);
|
||||
}
|
||||
}
|
||||
self.streams.retain_streamers(|c| state.clients.contains_key(&c));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Send the sessions' requests; returns their events.
|
||||
fn flush(&mut self, con: &mut Connection) -> Result<Vec<StreamEvent>> {
|
||||
let mut events = Vec::new();
|
||||
while let Some(output) = self.streams.poll_output() {
|
||||
match output {
|
||||
Output::Request(request) => {
|
||||
let handle = request.to_command().send_with_result(con)?;
|
||||
self.pending.insert(handle, request);
|
||||
}
|
||||
Output::Event(e) => events.push(e),
|
||||
}
|
||||
}
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
/// Stop streaming and watching; wait briefly for the server's answers.
|
||||
async fn finish(&mut self, con: &mut Connection) {
|
||||
self.streams.close();
|
||||
if self.flush(con).is_err() {
|
||||
return;
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
while !self.pending.is_empty() {
|
||||
match self.next(con, Some(deadline), None, None).await {
|
||||
Ok(Wake::Stream) => {
|
||||
if self.flush(con).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn nick(con: &Connection, client: ClientId) -> String {
|
||||
con.get_state()
|
||||
.ok()
|
||||
.and_then(|s| s.clients.get(&client).map(|c| c.name.clone()))
|
||||
.unwrap_or_else(|| "?".into())
|
||||
}
|
||||
|
||||
fn end_text(reason: &EndReason) -> String {
|
||||
match reason {
|
||||
EndReason::Local => "stopped".into(),
|
||||
EndReason::Denied => "denied by the streamer".into(),
|
||||
EndReason::Stopped => "the stream was stopped".into(),
|
||||
EndReason::Removed(reason) => format!("removed by the streamer ({reason:?})"),
|
||||
EndReason::Failed(e) => format!("failed: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn start(
|
||||
con: &mut Connection,
|
||||
driver: &mut Driver,
|
||||
options: StreamerOptions,
|
||||
mut source: EncodedSource,
|
||||
length: Option<Duration>,
|
||||
) -> Result<()> {
|
||||
let auto_accept = options.auto_accept;
|
||||
driver.streams.start(options)?;
|
||||
let deadline = length.map(|l| Instant::now() + l);
|
||||
let mut tick = tokio::time::interval(source.interval());
|
||||
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
let mut lines = (!auto_accept).then(|| BufReader::new(tokio::io::stdin()).lines());
|
||||
let (mut live, mut video, mut audio) = (false, 0u64, 0u64);
|
||||
let mut frames = Vec::new();
|
||||
loop {
|
||||
let wake = driver.next(con, deadline, live.then_some(&mut tick), lines.as_mut()).await?;
|
||||
match wake {
|
||||
Wake::Stream => {}
|
||||
Wake::Tick => {
|
||||
source.poll_frames(std::time::Instant::now(), &mut frames);
|
||||
let connected =
|
||||
driver.streams.streamer().is_some_and(|s| s.has_connected_viewers());
|
||||
for frame in frames.drain(..) {
|
||||
if connected {
|
||||
match frame.kind {
|
||||
MediaKind::Video => video += 1,
|
||||
MediaKind::Audio => audio += 1,
|
||||
}
|
||||
}
|
||||
driver.streams.write_frame(&frame);
|
||||
}
|
||||
}
|
||||
Wake::Line(None) => lines = None,
|
||||
Wake::Line(Some(line)) => {
|
||||
if let Err(e) = command_line(driver, &line).await {
|
||||
println!("{e}");
|
||||
}
|
||||
}
|
||||
Wake::Interrupted | Wake::Deadline => {
|
||||
driver.streams.stop()?;
|
||||
}
|
||||
}
|
||||
for event in driver.flush(con)? {
|
||||
let StreamEvent::Streamer(event) = event else { continue };
|
||||
match event {
|
||||
StreamerEvent::Live { id } => {
|
||||
live = true;
|
||||
println!("stream {id} is live");
|
||||
}
|
||||
StreamerEvent::Request { viewer, message } => {
|
||||
println!(
|
||||
"{} (clid {}) asks to watch: {message:?}; type `accept {}` or `deny {}`",
|
||||
nick(con, viewer),
|
||||
viewer.0,
|
||||
viewer.0,
|
||||
viewer.0
|
||||
);
|
||||
}
|
||||
StreamerEvent::Viewers(viewers) => {
|
||||
let list: Vec<String> = viewers
|
||||
.iter()
|
||||
.map(|v| {
|
||||
format!("{} (clid {}, {:?})", nick(con, v.client), v.client.0, v.state)
|
||||
})
|
||||
.collect();
|
||||
println!("viewers: [{}]", list.join(", "));
|
||||
}
|
||||
StreamerEvent::KeyframeRequest => source.request_keyframe(),
|
||||
StreamerEvent::Ended(reason) => {
|
||||
println!("sent {video} video / {audio} audio frames to connected viewers");
|
||||
let stats = source.streamer().stats();
|
||||
if let Some(e) = &stats.error {
|
||||
println!("last encoder error: {e}");
|
||||
}
|
||||
return match reason {
|
||||
EndReason::Local => Ok(()),
|
||||
other => bail!("stream ended: {}", end_text(&other)),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `accept <clid>`, `deny <clid>`, `kick <clid>`, `stop` while streaming.
|
||||
async fn command_line(driver: &mut Driver, line: &str) -> Result<()> {
|
||||
let mut words = line.split_whitespace();
|
||||
let command = words.next().unwrap_or_default();
|
||||
let client = words.next().and_then(|w| w.parse().ok()).map(ClientId);
|
||||
match (command, client) {
|
||||
("accept", Some(c)) => driver.streams.respond(c, true).await?,
|
||||
("deny", Some(c)) => driver.streams.respond(c, false).await?,
|
||||
("kick", Some(c)) => driver.streams.kick(c)?,
|
||||
("stop" | "quit", _) => driver.streams.stop()?,
|
||||
("", _) => {}
|
||||
_ => bail!("commands: accept <clid>, deny <clid>, kick <clid>, stop"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn list(con: &mut Connection, driver: &mut Driver, settle: Duration) -> Result<()> {
|
||||
let deadline = Instant::now() + settle;
|
||||
loop {
|
||||
match driver.next(con, Some(deadline), None, None).await? {
|
||||
Wake::Deadline | Wake::Interrupted => break,
|
||||
_ => {
|
||||
driver.flush(con)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let streams: Vec<&StreamInfo> = driver.streams.directory().iter().collect();
|
||||
for s in &streams {
|
||||
println!(
|
||||
"{} {:?} by {} (clid {}), {} kbit/s{}",
|
||||
s.id,
|
||||
s.name,
|
||||
nick(con, s.streamer),
|
||||
s.streamer.0,
|
||||
s.bitrate,
|
||||
if s.audio { ", audio" } else { "" }
|
||||
);
|
||||
}
|
||||
// Streams that started before we connected are only known by the flag.
|
||||
let state = con.get_state()?;
|
||||
let mut unannounced = 0;
|
||||
for c in state.clients.values() {
|
||||
if c.is_streaming == Some(true) && !streams.iter().any(|s| s.streamer == c.id) {
|
||||
println!("? {} (clid {}) is streaming; id not announced to us", c.name, c.id.0);
|
||||
unannounced += 1;
|
||||
}
|
||||
}
|
||||
if streams.is_empty() && unannounced == 0 {
|
||||
println!("no streams");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Target {
|
||||
id: Option<String>,
|
||||
streamer_nick: Option<String>,
|
||||
}
|
||||
|
||||
impl Target {
|
||||
/// The stream to watch and its streamer, once known.
|
||||
fn find(&self, con: &Connection, streams: &Streams) -> Option<(String, ClientId)> {
|
||||
let state = con.get_state().ok()?;
|
||||
let streamer = match &self.streamer_nick {
|
||||
Some(nick) => Some(state.clients.values().find(|c| c.name == *nick)?.id),
|
||||
None => None,
|
||||
};
|
||||
let own = streams.own_client();
|
||||
let found = streams.directory().iter().find(|s| {
|
||||
s.streamer != own
|
||||
&& self.id.as_ref().is_none_or(|id| *id == s.id)
|
||||
&& streamer.is_none_or(|c| c == s.streamer)
|
||||
});
|
||||
if let Some(s) = found {
|
||||
return Some((s.id.clone(), s.streamer));
|
||||
}
|
||||
// A known id of a stream that was not announced to us: its streamer
|
||||
// is the named client, or the only other client that streams.
|
||||
let id = self.id.clone()?;
|
||||
let streamer = streamer.or_else(|| {
|
||||
let mut streaming = state
|
||||
.clients
|
||||
.values()
|
||||
.filter(|c| c.id != own && c.is_streaming == Some(true))
|
||||
.map(|c| c.id);
|
||||
let first = streaming.next()?;
|
||||
streaming.next().is_none().then_some(first)
|
||||
})?;
|
||||
Some((id, streamer))
|
||||
}
|
||||
}
|
||||
|
||||
/// Save a picture as an RGBA PNG.
|
||||
fn save_png(picture: &VideoFrame, path: &Path) -> Result<()> {
|
||||
let rgba = convert::to_rgba_vec(picture)?;
|
||||
let file = std::io::BufWriter::new(std::fs::File::create(path)?);
|
||||
let mut encoder = png::Encoder::new(file, picture.width, picture.height);
|
||||
encoder.set_color(png::ColorType::Rgba);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
encoder.write_header()?.write_image_data(&rgba)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn watch(
|
||||
con: &mut Connection,
|
||||
driver: &mut Driver,
|
||||
codecs: Arc<Codecs>,
|
||||
target: &Target,
|
||||
expect: Option<u64>,
|
||||
timeout: Option<Duration>,
|
||||
save: Option<&Path>,
|
||||
) -> Result<()> {
|
||||
let deadline = timeout.map(|t| Instant::now() + t);
|
||||
let mut watching: Option<String> = None;
|
||||
let (mut video, mut audio) = (0u64, 0u64);
|
||||
let mut codec = None;
|
||||
let mut waiting_told = false;
|
||||
// Decoding runs on its own thread; the loop checks its progress.
|
||||
let latest = Arc::new(Latest::new());
|
||||
let keyframe_wanted = Arc::new(AtomicBool::new(false));
|
||||
let decoder = VideoPipeline::new(
|
||||
codecs,
|
||||
{
|
||||
let latest = latest.clone();
|
||||
move |picture| {
|
||||
latest.put(picture);
|
||||
}
|
||||
},
|
||||
{
|
||||
let wanted = keyframe_wanted.clone();
|
||||
move || wanted.store(true, Ordering::Relaxed)
|
||||
},
|
||||
);
|
||||
let mut tick = tokio::time::interval(Duration::from_millis(100));
|
||||
let mut first_picture = true;
|
||||
let mut last_picture: Option<VideoFrame> = None;
|
||||
let summary = |video: u64, audio: u64, decoder: &VideoPipeline| {
|
||||
let stats = decoder.stats();
|
||||
println!(
|
||||
"received {video} video / {audio} audio frames, decoded {} pictures{}",
|
||||
stats.decoded,
|
||||
stats.error.map(|e| format!(" (last error: {e})")).unwrap_or_default()
|
||||
);
|
||||
};
|
||||
let save_last = |last: &Option<VideoFrame>| -> Result<()> {
|
||||
match (save, last) {
|
||||
(Some(path), Some(picture)) => {
|
||||
save_png(picture, path)?;
|
||||
println!("saved {}", path.display());
|
||||
Ok(())
|
||||
}
|
||||
(Some(_), None) => bail!("no picture to save"),
|
||||
(None, _) => Ok(()),
|
||||
}
|
||||
};
|
||||
loop {
|
||||
if let Some(picture) = latest.take() {
|
||||
if first_picture {
|
||||
println!("first picture decoded ({}x{})", picture.width, picture.height);
|
||||
first_picture = false;
|
||||
}
|
||||
last_picture = Some(picture);
|
||||
}
|
||||
if let Some(id) = &watching
|
||||
&& keyframe_wanted.swap(false, Ordering::Relaxed)
|
||||
{
|
||||
driver.streams.request_keyframe(id);
|
||||
}
|
||||
if expect.is_some_and(|n| decoder.stats().decoded >= n) {
|
||||
summary(video, audio, &decoder);
|
||||
return save_last(&last_picture);
|
||||
}
|
||||
if watching.is_none() {
|
||||
if let Some((id, streamer)) = target.find(con, &driver.streams) {
|
||||
println!("watching {id} of {} (clid {})", nick(con, streamer), streamer.0);
|
||||
driver.streams.watch_from(&id, streamer, "")?;
|
||||
watching = Some(id);
|
||||
} else if !waiting_told {
|
||||
println!("waiting for a stream");
|
||||
waiting_told = true;
|
||||
}
|
||||
}
|
||||
for event in driver.flush(con)? {
|
||||
let StreamEvent::Watch { id, event } = event else { continue };
|
||||
if Some(&id) != watching.as_ref() {
|
||||
continue;
|
||||
}
|
||||
match event {
|
||||
WatchEvent::Accepted => println!("accepted, connecting"),
|
||||
WatchEvent::Connected => println!("connected"),
|
||||
WatchEvent::Frame(f) => {
|
||||
match f.kind {
|
||||
MediaKind::Video => video += 1,
|
||||
MediaKind::Audio => audio += 1,
|
||||
}
|
||||
if f.kind == MediaKind::Video && codec.replace(f.codec).is_none() {
|
||||
println!("first video frame ({:?}, {} bytes)", f.codec, f.data.len());
|
||||
}
|
||||
decoder.push(f);
|
||||
}
|
||||
WatchEvent::Ended(reason) => {
|
||||
summary(video, audio, &decoder);
|
||||
match expect {
|
||||
Some(n) => bail!("{} before {n} pictures were decoded", end_text(&reason)),
|
||||
None => {
|
||||
println!("{}", end_text(&reason));
|
||||
return save_last(&last_picture.or_else(|| latest.take()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
match driver.next(con, deadline, Some(&mut tick), None).await? {
|
||||
Wake::Deadline | Wake::Interrupted => {
|
||||
summary(video, audio, &decoder);
|
||||
return match expect {
|
||||
Some(n) => bail!("timed out waiting for {n} decoded pictures"),
|
||||
None => save_last(&last_picture.or_else(|| latest.take())),
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
//! Render the channel tree of a connection as text.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
|
||||
use tsclientlib::data;
|
||||
use tsclientlib::{ChannelId, ClientType};
|
||||
use voelin_model::ServerFlavor;
|
||||
|
||||
/// 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,
|
||||
pub streaming: 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");
|
||||
}
|
||||
if client.streaming {
|
||||
flags.push("streaming");
|
||||
}
|
||||
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(),
|
||||
streaming: c.is_streaming == Some(true),
|
||||
})
|
||||
.collect();
|
||||
let flavor = match ServerFlavor::from_version_string(&state.server.version) {
|
||||
ServerFlavor::Ts3(v) => format!("TeamSpeak 3 {v}"),
|
||||
ServerFlavor::Ts6(v) => format!("TeamSpeak 6 {v}"),
|
||||
ServerFlavor::Unknown(v) => format!("unknown version {v:?}"),
|
||||
};
|
||||
render(&format!("{} ({flavor})", 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,
|
||||
streaming: 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;
|
||||
muted.streaming = 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, streaming]\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 `voelinctl 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 `voelinctl 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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
//! `voelinctl connect ... voice send|record`.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use tokio::time::Instant;
|
||||
use tsclientlib::{ClientId, Connection, StreamItem};
|
||||
use tsproto_packets::packets::AudioData;
|
||||
use voelin_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
|
||||
use voelin_audio::{Framer, Mixer, VoiceCodec, VoiceEncoder, resample, wav};
|
||||
|
||||
use crate::VoiceCommand;
|
||||
use crate::session::{Flow, PumpEnd, pump};
|
||||
|
||||
const FRAME: Duration = Duration::from_millis(20);
|
||||
|
||||
pub async fn run(con: &mut Connection, command: &VoiceCommand) -> Result<()> {
|
||||
match command {
|
||||
VoiceCommand::Send { file, tone, seconds, music } => {
|
||||
let codec = if *music { VoiceCodec::Music } else { VoiceCodec::Voice };
|
||||
let samples = match (file, tone) {
|
||||
(Some(path), _) => load(path, codec.channels())?,
|
||||
(None, Some(freq)) => {
|
||||
pcm::from_mono(&pcm::sine(*freq, *seconds, 0.5), codec.channels())
|
||||
}
|
||||
(None, None) => bail!("pass a WAV file or --tone <hz>"),
|
||||
};
|
||||
send(con, codec, &samples).await
|
||||
}
|
||||
VoiceCommand::Record { out, seconds, expect_tone } => {
|
||||
let samples = record(con, Duration::from_secs_f32(*seconds)).await?;
|
||||
let clip = wav::Clip { samples, channels: 2, rate: SAMPLE_RATE };
|
||||
wav::write(out, &clip)?;
|
||||
let mono = pcm::to_mono(&clip.samples, 2);
|
||||
println!(
|
||||
"recorded {:.1} s to {} (energy {:.5})",
|
||||
mono.len() as f32 / SAMPLE_RATE as f32,
|
||||
out.display(),
|
||||
pcm::energy(&mono)
|
||||
);
|
||||
if let Some(freq) = expect_tone {
|
||||
let ratio = pcm::voiced_tone_ratio(&mono, *freq, SAMPLE_RATE);
|
||||
println!("{freq} Hz tone ratio: {ratio:.3}");
|
||||
if ratio < 0.5 {
|
||||
bail!("expected a {freq} Hz tone, ratio {ratio:.3} < 0.5");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a WAV file and convert it to 48 kHz with the codec's channel count.
|
||||
fn load(path: &std::path::Path, channels: usize) -> Result<Vec<f32>> {
|
||||
let clip = wav::read(path).with_context(|| format!("failed to read {}", path.display()))?;
|
||||
let samples = resample::resample_all(&clip.samples, clip.channels, clip.rate, SAMPLE_RATE)?;
|
||||
let mono = pcm::to_mono(&samples, clip.channels);
|
||||
Ok(pcm::from_mono(&mono, channels))
|
||||
}
|
||||
|
||||
/// Send in real time: one frame every 20 ms, driving the connection in between.
|
||||
async fn send(con: &mut Connection, codec: VoiceCodec, samples: &[f32]) -> Result<()> {
|
||||
let mut encoder = VoiceEncoder::new(codec)?;
|
||||
let mut frames = Vec::new();
|
||||
let mut framer = Framer::new(codec.frame_len());
|
||||
framer.push(samples, |f| frames.push(f.to_vec()));
|
||||
framer.flush(|f| frames.push(f.to_vec()));
|
||||
|
||||
let mut next = Instant::now();
|
||||
for frame in &frames {
|
||||
con.send_audio(encoder.encode(frame)?)?;
|
||||
next += FRAME;
|
||||
if pump(con, Some(next), |_, _| Ok(Flow::Continue)).await? == PumpEnd::Interrupted {
|
||||
break;
|
||||
}
|
||||
}
|
||||
con.send_audio(encoder.end_of_stream())?;
|
||||
// Let the last packets go out.
|
||||
pump(con, Some(Instant::now() + Duration::from_millis(200)), |_, _| Ok(Flow::Continue)).await?;
|
||||
println!("sent {} frames ({:.1} s)", frames.len(), frames.len() as f32 * 0.02);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Collect voice for `length`, mixing all speakers into stereo.
|
||||
async fn record(con: &mut Connection, length: Duration) -> Result<Vec<f32>> {
|
||||
let mut mixer = Mixer::new();
|
||||
let mut out = Vec::new();
|
||||
let end = Instant::now() + length;
|
||||
let mut next = Instant::now() + FRAME;
|
||||
while next <= end {
|
||||
let end = pump(con, Some(next), |_, item| {
|
||||
if let StreamItem::Audio(packet) = item {
|
||||
let from = match packet.data().data() {
|
||||
AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from,
|
||||
_ => return Ok(Flow::Continue),
|
||||
};
|
||||
// Late or duplicate packets are expected on UDP; the mixer drops them.
|
||||
let _ = mixer.handle_packet(ClientId(from), packet);
|
||||
}
|
||||
Ok(Flow::Continue)
|
||||
})
|
||||
.await?;
|
||||
let mut frame = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut frame);
|
||||
out.extend_from_slice(&frame);
|
||||
if end == PumpEnd::Interrupted {
|
||||
break;
|
||||
}
|
||||
next += FRAME;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
Reference in new issue
Block a user