Files
VoelinClient/crates/voelin-core/src/link/mod.rs
T
faumarayandClaude Sonnet 5.5 1edc52ce74 Make the engine's link vocabulary private and the options neutral
VoiceOptions is a struct of its own, no longer an alias of the TeamSpeak
link's options: identity is an IdentityBlob and client_version a spec for
ts::versions::resolve, which rides the address as the link parameter
client_version and which the TeamSpeak connector resolves (a spec it refuses
fails the connect in words). SessionLink builds the connect parameters
(link/connect.rs: the bookmark's link, the hello, the credential of the
identity's kind, now also a Voelin key's signer) and session.rs holds it
directly: the ServerLink trait between them was redundant. The trait lives
on in the TeamSpeak module (ts/ts_link.rs, with the TeamSpeak-typed
ConnectOptions) for TsLink and the in-memory link of the tests.

ServerLink, TsLink, LinkCtx, LinkCmd, LinkEvent and Remote are crate-private,
Engine::start_with_link is gone, and the three tests that needed the inner
link (tests/link_fake.rs) are unit tests of link/ now. The rg over the crate
for tsclientlib, tsproto and voelin_query, outside ts/ and the three files
that use them privately (gateway.rs, query.rs, stream.rs), is empty. The UI
and voelinctl get compile fixes: the identity blob and the spec string.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 06:59:44 +03:00

323 lines
10 KiB
Rust

//! The engine's seam to the server its voice source talks to.
//!
//! A session merges up to three sources (voice, gateway, query). The *voice*
//! source is the connection that is visible on the server, can talk and
//! carries chat, files, pokes, offline messages and streams. The engine holds
//! it as a `voelin_proto::link::Session`, the backend-neutral interface of the
//! protocol repository, and knows nothing else of the server software behind
//! it: which backend makes the `Session` is the scheme of the address, and
//! [`Backends`] is the registry of connectors by scheme
//! ([`Backends::default`] has the TeamSpeak one,
//! [`crate::ts::TsConnector`]; a Voelin host's QUIC connector will be
//! another). [`VoiceOptions`] says what to connect to and as whom.
//!
//! Inside the crate `session.rs` merges and routes, and an adapter below it
//! turns what it asks into `Session` calls and what the `Session` pushes into
//! what it hears (`link/session_link.rs`, with `project.rs` and `media.rs`);
//! `docs/session-seam.md` describes the mapping row by row.
mod backends;
mod connect;
#[cfg(test)]
mod fake_link_tests;
#[cfg(test)]
mod fake_tests;
pub(crate) mod media;
pub(crate) mod project;
mod session_link;
#[cfg(test)]
mod tests;
pub use backends::Backends;
pub(crate) use backends::{
LocalConnected, LocalConnector, LocalCtx, StreamEvent, StreamPort, without_query,
};
pub(crate) use connect::{VERSION_PARAM, connect_params};
pub(crate) use session_link::SessionLink;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::sync::{broadcast, oneshot};
use voelin_audio::{EncodedVoice, VoicePacket};
use voelin_identity::IdentityBlob;
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence};
use voelin_stream::PeerConfig;
use crate::files::{Report, RequestId, Sink, TransferId};
use crate::settings::SharedSettings;
use crate::stream::{OwnStreamEvent, StreamCmd, StreamFrame};
use crate::{BackendInfo, Event, SessionId};
/// What a voice connection needs to know: the server, who to be, where to
/// join ([`Command::ConnectVoice`](crate::Command::ConnectVoice)).
///
/// Nothing in it belongs to one kind of server: what a connector needs of it
/// that is its own (a TeamSpeak identity, the client version to claim) is in
/// the `identity` blob and the `client_version` spec, which the connector of
/// the address reads.
#[derive(Clone, Debug)]
pub struct VoiceOptions {
/// The server: `host[:port]` of a TeamSpeak bookmark, or an address with a
/// scheme (`ts3server://`, `teamspeak://`, a Voelin host's `voelin://`)
/// that picks the connector ([`Backends`]).
pub address: String,
pub nickname: String,
/// The identity to connect with: a TeamSpeak identity
/// ([`crate::ts::identity::to_blob`]) for a TeamSpeak server, a Voelin key
/// for a Voelin host. None lets the connector make one up (a TeamSpeak
/// connection generates an identity, which a server then knows as a new
/// client).
pub identity: Option<IdentityBlob>,
/// The client version a TeamSpeak server is shown, as a spec for
/// [`crate::ts::versions::resolve`] (`default`, `generic`, an index, or
/// `<platform>@<version>`); `None` is the native platform's. A spec that is
/// none ends the connect with the reason. Other backends ignore it.
pub client_version: Option<String>,
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
pub channel: Option<String>,
/// The password of `channel`.
pub channel_password: Option<String>,
/// A privilege key to use when connecting.
pub token: Option<String>,
/// Open the audio devices (capture and playback).
pub audio: bool,
/// Network settings for stream peer connections (TeamSpeak 6).
pub stream_peer: PeerConfig,
}
impl VoiceOptions {
/// Options for `address` and `nickname`; everything else is left to the
/// connector.
pub fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
Self {
address: address.into(),
nickname: nickname.into(),
identity: None,
client_version: None,
server_password: None,
channel: None,
channel_password: None,
token: None,
audio: false,
stream_peer: PeerConfig::default(),
}
}
}
/// What the engine gives a link besides the options: where the connection
/// answers the requests the session need not see, and what it shares with
/// the session's other parts.
#[derive(Clone)]
pub(crate) struct LinkCtx {
pub(crate) session: SessionId,
pub(crate) events: broadcast::Sender<Event>,
/// The frames of watched streams (kept off the event bus).
pub(crate) frames: broadcast::Sender<StreamFrame>,
pub(crate) settings: SharedSettings,
}
impl LinkCtx {
/// The session this connection belongs to.
pub(crate) fn session(&self) -> SessionId {
self.session
}
/// Tell the engine's event bus something (a request's answer, a
/// transfer's progress).
pub(crate) fn emit(&self, event: Event) {
let _ = self.events.send(event);
}
pub(crate) fn done(&self, request: RequestId, result: Result<(), String>) {
self.emit(Event::RequestDone { session: self.session, request, result });
}
}
/// A file on the server: channel, its password, path.
#[derive(Clone, Debug)]
pub(crate) struct Remote {
pub channel: ChannelId,
pub password: Option<String>,
pub path: String,
}
/// A boxed stream of bytes to read: the body of a file the server sends.
pub(crate) type BoxRead = Pin<Box<dyn AsyncRead + Send>>;
/// A connection that can be read and written: a file transfer connection.
pub(crate) trait Duplex: AsyncRead + AsyncWrite + Send {}
impl<T: AsyncRead + AsyncWrite + Send> Duplex for T {}
/// A boxed [`Duplex`].
pub(crate) type BoxDuplex = Pin<Box<dyn Duplex>>;
/// What the session asks of a connection.
pub(crate) enum LinkCmd {
SendChat(ChatTarget, String),
Move(ChannelId, Option<String>),
SetInputMuted(bool),
SetOutputMuted(bool),
/// An encoded voice frame from the audio thread.
Audio(EncodedVoice),
/// A stream command; the link answers on the event bus. Only sent while
/// the connection's capabilities include streams.
Stream(StreamCmd),
Poke {
client: u16,
message: String,
},
ListFiles {
request: RequestId,
dir: Remote,
},
/// Download `file`; `transfer` if the user can cancel it.
Download {
transfer: Option<TransferId>,
file: Remote,
sink: Sink,
report: Report,
},
Upload {
transfer: Option<TransferId>,
file: Remote,
from: PathBuf,
overwrite: bool,
resume: bool,
report: Report,
},
CancelTransfer(TransferId),
/// Open a file of the server for reading, from `offset`: the transfer
/// connection itself, and the file's size in all, once the server has
/// agreed (the text of the failure otherwise). The engine copies the
/// bytes, reports the progress and cancels by dropping the connection, so
/// this does not use [`LinkCmd::Download`]'s sink and report.
OpenRead {
file: Remote,
offset: u64,
reply: oneshot::Sender<Result<(u64, BoxRead), String>>,
},
/// Open a file of the server for writing: the transfer connection and the
/// position the server wants the bytes from (the size it already has, if
/// `resume`). The engine writes the bytes and ends the connection.
OpenWrite {
file: Remote,
/// The file's size in all.
size: u64,
overwrite: bool,
resume: bool,
reply: oneshot::Sender<Result<(u64, BoxDuplex), String>>,
},
DeleteFiles {
/// `None`: best effort, nobody waits for the answer.
request: Option<RequestId>,
channel: ChannelId,
password: Option<String>,
paths: Vec<String>,
},
RenameFile {
request: RequestId,
from: Remote,
to: Remote,
},
CreateDirectory {
request: RequestId,
dir: Remote,
},
/// Announce our avatar's hash (empty: no avatar).
SetAvatarHash {
request: Option<RequestId>,
hash: String,
},
OfflineList {
request: RequestId,
},
OfflineGet {
request: RequestId,
id: u32,
},
OfflineAdd {
request: RequestId,
to_uid: String,
subject: String,
text: String,
},
OfflineDelete {
request: RequestId,
id: u32,
},
OfflineFlag {
request: RequestId,
id: u32,
read: bool,
},
Disconnect,
}
/// What a connection tells the session.
pub(crate) enum LinkEvent {
Connected {
name: String,
/// The server software, and what it can do (the connection knows
/// both from the server's version).
backend: BackendInfo,
capabilities: Capabilities,
/// Our client id when the link connected. TeamSpeak's own reconnect gives
/// a new one, which is not announced; the engine follows it in the
/// snapshots by our unique id.
own_client: u16,
/// The server's unique id.
server_uid: String,
/// Our unique id as the server knows it.
own_uid: Option<String>,
},
/// The server's channels and clients as they are now.
Presence(Box<Presence>),
/// The channel we are in, after every [`LinkEvent::Presence`]. The engine
/// derives it itself, from our own voice state in the snapshots of the
/// `Session` it talks to, and so follows us when TeamSpeak's reconnect makes
/// us another client. What an in-process link such as `TsLink` says here only
/// tells the TeamSpeak `Session` made of it that a move has arrived.
OwnChannel(ChannelId),
Chat(ChatMessage),
Poke {
from: u16,
from_uid: Option<String>,
from_name: String,
message: String,
},
/// Incoming voice for the audio thread.
Audio(VoicePacket),
/// Who is talking (on, and off again when it stopped). The engine derives
/// it from the media of its `Session` (protocol section 6.4). What an
/// in-process link such as `TsLink` says here reaches the engine as a
/// speaking hint next to the media: that is what shows the talkers whose
/// packets the link does not forward as Opus (Speex, CELT).
Talking {
client: u16,
talking: bool,
},
/// Our own stream's life, for the gateway directory.
OwnStream(OwnStreamEvent),
/// An Opus frame (48 kHz) of a watched stream, for the audio thread
/// ([`VoiceOptions::audio`]); `time` is its RTP time on the 48 kHz
/// clock.
StreamAudio {
stream: String,
time: u64,
data: Arc<[u8]>,
},
/// A watched stream ended: its audio leaves the mixer.
StreamAudioEnded(String),
/// A command failed (the connection stays).
Error(String),
/// The connection ended; the reason if it was not asked for. Sent once;
/// the stream task's closing reports may still follow (see the module
/// documentation).
Disconnected(Option<String>),
}