Run the engine on voelin_proto::link::Session
The engine's voice source is now a voelin_proto::link::Session obtained from a registry of connectors (docs/session-seam.md, slice 1): - link::Backends keeps the plain connectors of voelin_proto::link::Connectors and the in-process ones that also hand the engine a port for TeamSpeak 6 streams; the scheme of the address picks the connector, an address without one is a TeamSpeak bookmark. - link::SessionLink is the engine's ServerLink. session.rs is unchanged and still speaks LinkCmd and LinkEvent; SessionLink runs the connect sequence (List the server, subscribe HOME, SERVER and LIVE, take the seat), keeps a voelin_model::replica::Replica, projects it into the client's older model (link/project.rs, the fix-ups F1 to F10), frames voice as RTP and derives who talks from the media (link/media.rs), and turns every command into the Session call of its row. Transfers copy through read_file and write_file. - ts_session makes a TeamSpeak connection a Session: LinkSession over any ServerLink translates the link's commands, events and presence snapshots to v1 entities, pushes, answers and RTP; TsConnector makes them for ts3server:// and teamspeak:// addresses with TsLink inside, and LinkConnector for the link of Engine::start_with_link. - voice.rs opens the transfer connection itself for the new OpenRead and OpenWrite commands; files::download and upload are generic over the stream. - Engine::start_with_backends is new; start_with and start_with_link go through the registry. tests/link_fake.rs runs through both adapters; its fixtures are normalised as the design says (an order chain, database ids, talking from media, the server named, channel chat for the channel we are in), and the request id the link sees is the session's own. New unit tests cover every row of the mapping with a recording link, the TeamSpeak session on its own, media framing both ways, the talk tracker, the close table, the error texts, the backend and capability tables, the connect parameters, and the presence round trip on book fixtures and generated presences. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fb8e6b63dd
commit
c473ab216e
18 files changed
+7345
-68
No files matched your search
@@ -25,6 +25,8 @@ media-desktop = ["media", "voelin-media/default"]
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
base64 = "0.22"
|
||||
# The RTP packets of the session seam (`voelin_proto::link::MediaPacket`).
|
||||
bytes = "1"
|
||||
dirs = "6"
|
||||
futures = "0.3"
|
||||
# Finding a server's gateway in DNS (the voice resolver's version).
|
||||
@@ -68,8 +70,7 @@ tsproto-packets = { path = "../proto/tsproto-packets" }
|
||||
tsproto-types = { path = "../proto/tsproto-types" }
|
||||
|
||||
[dev-dependencies]
|
||||
# An HTTP/2 connection in a test (both already in the tree through h2).
|
||||
bytes = "1"
|
||||
# An HTTP/2 connection in a test (already in the tree through h2).
|
||||
http = "1"
|
||||
# Already in the app's graph (reqwest); for one_rustls_crypto_provider.
|
||||
rustls = { version = "0.23", default-features = false }
|
||||
|
||||
@@ -331,4 +331,304 @@ mod tests {
|
||||
let p = presence_from_book(&book, None, |_| false);
|
||||
assert_eq!(avatar(&p, 6).as_deref(), Some("https://a.example/off.png"));
|
||||
}
|
||||
|
||||
// ---- across the session seam ---------------------------------------------
|
||||
|
||||
/// A presence made into the entities the TeamSpeak session writes
|
||||
/// (`ts_session::entities`), pushed the way a host syncs them, and
|
||||
/// projected back by the engine (`link::project`): what the UI is shown
|
||||
/// of what a TeamSpeak link reported (`docs/session-seam.md` section 5.1).
|
||||
fn through_the_seam(presence: &Presence, ts6: bool, own: Option<u16>) -> Presence {
|
||||
use voelin_model::replica::{Replica, SCHEMA_GENERATION, ScopeId};
|
||||
use voelin_proto::link::Features;
|
||||
use voelin_proto::v1::{self, push::Body};
|
||||
|
||||
use crate::link::media::TalkTracker;
|
||||
use crate::link::project::{View, presence as project};
|
||||
use crate::ts_session::entities::build;
|
||||
|
||||
let built = build(presence, ts6, own);
|
||||
let mut replica = Replica::new(SCHEMA_GENERATION);
|
||||
for (scope, layer) in [(ScopeId::Server(1), &built.server), (ScopeId::Live(1), &built.live)]
|
||||
{
|
||||
replica.subscribe(scope);
|
||||
let pushes = [
|
||||
Body::SyncBegin(v1::SyncBegin {
|
||||
scope: Some(scope.to_proto()),
|
||||
mode: v1::SyncMode::Full as i32,
|
||||
epoch: 1,
|
||||
}),
|
||||
Body::Change(v1::Change {
|
||||
scope: Some(scope.to_proto()),
|
||||
rev: 1,
|
||||
put: layer.values().cloned().collect(),
|
||||
del: Vec::new(),
|
||||
}),
|
||||
Body::SyncEnd(v1::SyncEnd {
|
||||
scope: Some(scope.to_proto()),
|
||||
cursor: Some(v1::Cursor { epoch: 1, rev: 1 }),
|
||||
gap: false,
|
||||
}),
|
||||
];
|
||||
for body in pushes {
|
||||
replica.apply_push(&v1::Push { body: Some(body) });
|
||||
}
|
||||
}
|
||||
let features = Features::new(["voice"]);
|
||||
let talking = TalkTracker::default();
|
||||
project(&View {
|
||||
replica: &replica,
|
||||
server: 1,
|
||||
teamspeak: true,
|
||||
version: "",
|
||||
features: &features,
|
||||
streams: ts6,
|
||||
talking: &talking,
|
||||
})
|
||||
}
|
||||
|
||||
/// A TeamSpeak 6 server and some clients with what the book holds of them.
|
||||
fn ts6_presence() -> Presence {
|
||||
let mut book = ts6_book();
|
||||
let list = format!(
|
||||
"channellist {}|{}|{}",
|
||||
channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"),
|
||||
channel(
|
||||
12,
|
||||
1,
|
||||
"Raid",
|
||||
r"channel_banner_gfx_url=http:\/\/127.0.0.1:1\/d.png channel_banner_mode=2"
|
||||
),
|
||||
channel(20, 12, "Last", "channel_banner_gfx_url channel_banner_mode=0"),
|
||||
);
|
||||
book.handle_command(&message(&list)).unwrap();
|
||||
let enter = |clid: u16, channel: u64, groups: &str, away: &str, avatar: &str| {
|
||||
format!(
|
||||
"notifycliententerview reasonid=0 ctid={channel} clid={clid} \
|
||||
client_database_id={} client_nickname=c{clid} client_type=0 cfid=0 \
|
||||
client_unique_identifier=u{clid}= client_flag_avatar=abcdef \
|
||||
client_description=about\\sme client_icon_id=777 client_input_muted=1 \
|
||||
client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \
|
||||
client_output_hardware=1 client_meta_data client_is_recording=1 \
|
||||
client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \
|
||||
client_servergroups={groups} client_away={} client_away_message={away} \
|
||||
client_talk_power=75 client_talk_request=0 client_talk_request_msg \
|
||||
client_is_talker=1 client_is_priority_speaker=1 client_unread_messages=0 \
|
||||
client_nickname_phonetic client_needed_serverquery_view_power=75 \
|
||||
client_is_channel_commander=1 client_country=RU client_badges \
|
||||
client_myteamspeak_id=m{clid} client_integrations{avatar}",
|
||||
100 + u64::from(clid),
|
||||
u8::from(!away.is_empty()),
|
||||
)
|
||||
};
|
||||
for text in [
|
||||
enter(5, 1, "8", "", r" client_myteamspeak_avatar=2,https:\/\/a.example\/on.png"),
|
||||
enter(6, 12, "8,9", "gone\\sfishing", ""),
|
||||
enter(7, 12, "", "", " client_myteamspeak_avatar"),
|
||||
] {
|
||||
book.handle_command(&message(&text)).unwrap();
|
||||
}
|
||||
presence_from_book(&book, Some("ibhejBRSRRI7v+fSsUzpQ33JGK6rf5xKOLelpWUr0sE="), |_| false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_book_is_what_the_ui_is_shown_across_the_seam() {
|
||||
let p = ts6_presence();
|
||||
assert_eq!(p.clients.len(), 3, "the fixture has clients");
|
||||
assert!(p.clients.values().any(|c| c.away.is_some()), "one is away");
|
||||
// A TeamSpeak 6 client the book has no streaming flag of (it was not
|
||||
// sent) is not streaming: v1 has no "unknown" for it.
|
||||
let mut expected = p.clone();
|
||||
for client in expected.clients.values_mut() {
|
||||
client.streaming = Some(client.streaming.unwrap_or(false));
|
||||
}
|
||||
assert_eq!(through_the_seam(&p, true, Some(5)), expected);
|
||||
// The same server as a TeamSpeak 3 one has no streams to tell of.
|
||||
let mut ts3 = p.clone();
|
||||
for client in ts3.clients.values_mut() {
|
||||
client.streaming = None;
|
||||
}
|
||||
assert_eq!(through_the_seam(&ts3, false, Some(5)), ts3);
|
||||
}
|
||||
|
||||
/// A deterministic stream of numbers for the generated presences.
|
||||
struct Numbers(u64);
|
||||
|
||||
impl Numbers {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n
|
||||
}
|
||||
|
||||
fn flag(&mut self) -> bool {
|
||||
self.below(2) == 0
|
||||
}
|
||||
|
||||
fn text(&mut self, prefix: &str) -> String {
|
||||
format!("{prefix}{}", self.below(1000))
|
||||
}
|
||||
}
|
||||
|
||||
/// A presence of the shape a TeamSpeak link reports: sibling channels in an
|
||||
/// order chain, every client with a database id, unique ids that are base64
|
||||
/// (TeamSpeak 3 and 6) or login names, groups of both kinds.
|
||||
fn generated(seed: u64, ts6: bool) -> Presence {
|
||||
use base64::Engine as _;
|
||||
use voelin_model::{
|
||||
BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType,
|
||||
HostMessageMode,
|
||||
};
|
||||
let mut n = Numbers(seed | 1);
|
||||
let mut p = Presence::default();
|
||||
let name = n.text("Server ");
|
||||
p.server_name = name.clone();
|
||||
p.server = voelin_model::ServerDetails {
|
||||
name,
|
||||
uid: Some(n.text("uid")),
|
||||
welcome_message: n.text("welcome "),
|
||||
host_message: n.text("host "),
|
||||
host_message_mode: [
|
||||
HostMessageMode::None,
|
||||
HostMessageMode::Log,
|
||||
HostMessageMode::Modal,
|
||||
][n.below(3) as usize],
|
||||
banner_url: if n.flag() { n.text("https://b/") } else { String::new() },
|
||||
banner_gfx_url: if n.flag() { n.text("https://g/") } else { String::new() },
|
||||
banner_gfx_interval_s: n.below(100),
|
||||
banner_mode: [BannerMode::NoAdjust, BannerMode::IgnoreAspect, BannerMode::KeepAspect]
|
||||
[n.below(3) as usize],
|
||||
host_button_tooltip: if n.flag() { n.text("tip ") } else { String::new() },
|
||||
host_button_url: String::new(),
|
||||
host_button_gfx_url: String::new(),
|
||||
icon: n.below(5) as u32 * 1000,
|
||||
platform: "Linux".into(),
|
||||
version: n.text("6.0."),
|
||||
max_clients: n.below(500) as u16,
|
||||
priority_speaker_dimm_db: -(n.below(30) as i32),
|
||||
default_server_group: Some(1 + n.below(9)),
|
||||
default_channel_group: Some(1 + n.below(9)),
|
||||
};
|
||||
// Groups.
|
||||
for id in 1..=(2 + n.below(4)) {
|
||||
let group = |id: u64, n: &mut Numbers| GroupInfo {
|
||||
id,
|
||||
name: n.text("group "),
|
||||
icon: n.below(3) as u32 * 100,
|
||||
sort_id: n.below(1000) as i32 - 500,
|
||||
naming_mode: [
|
||||
GroupNamingMode::None,
|
||||
GroupNamingMode::Before,
|
||||
GroupNamingMode::After,
|
||||
][n.below(3) as usize],
|
||||
group_type: [GroupType::Regular, GroupType::Template, GroupType::Query]
|
||||
[n.below(3) as usize],
|
||||
};
|
||||
p.server_groups.insert(id, group(id, &mut n));
|
||||
p.channel_groups.insert(id, group(id, &mut n));
|
||||
}
|
||||
// Channels: a tree whose siblings follow each other.
|
||||
let mut next_id = 1;
|
||||
let mut parents = vec![0u64];
|
||||
for _ in 0..(3 + n.below(8)) {
|
||||
let parent = parents[n.below(parents.len() as u64) as usize];
|
||||
let order = p
|
||||
.channels
|
||||
.values()
|
||||
.filter(|c| c.parent == parent)
|
||||
.map(|c| c.id)
|
||||
.next_back()
|
||||
.unwrap_or(0);
|
||||
let id = next_id;
|
||||
next_id += 1;
|
||||
parents.push(id);
|
||||
p.channels.insert(
|
||||
id,
|
||||
ChannelInfo {
|
||||
id,
|
||||
parent,
|
||||
order,
|
||||
name: n.text("channel "),
|
||||
topic: n.flag().then(|| n.text("topic ")),
|
||||
has_password: n.flag(),
|
||||
max_clients: match n.below(3) {
|
||||
0 => None,
|
||||
1 => Some(0),
|
||||
_ => Some(1 + n.below(50) as i32),
|
||||
},
|
||||
needed_subscribe_power: n.below(3) as i32 * 10,
|
||||
needed_talk_power: n.below(3) as i32 * 25,
|
||||
is_default: id == 1,
|
||||
icon: n.below(3) as u32 * 500,
|
||||
banner_gfx_url: n.flag().then(|| n.text("https://c/")),
|
||||
banner_mode: [
|
||||
BannerMode::NoAdjust,
|
||||
BannerMode::IgnoreAspect,
|
||||
BannerMode::KeepAspect,
|
||||
][n.below(3) as usize],
|
||||
},
|
||||
);
|
||||
}
|
||||
// Clients.
|
||||
let channels: Vec<u64> = p.channels.keys().copied().collect();
|
||||
for id in 1..=(1 + n.below(12)) {
|
||||
let id = id as u16;
|
||||
let uid = match n.below(4) {
|
||||
0 => None,
|
||||
1 => Some(n.text("login")),
|
||||
_ => {
|
||||
let bytes: Vec<u8> =
|
||||
(0..if ts6 { 32 } else { 20 }).map(|_| n.below(256) as u8).collect();
|
||||
Some(base64::engine::general_purpose::STANDARD.encode(bytes))
|
||||
}
|
||||
};
|
||||
let channel = channels[n.below(channels.len() as u64) as usize];
|
||||
p.clients.insert(
|
||||
id,
|
||||
ClientInfo {
|
||||
id,
|
||||
uid,
|
||||
nickname: n.text("nick "),
|
||||
channel,
|
||||
is_query: n.below(5) == 0,
|
||||
away: n.flag().then(|| if n.flag() { n.text("away ") } else { String::new() }),
|
||||
input_muted: n.flag(),
|
||||
output_muted: n.flag(),
|
||||
talking: Some(false),
|
||||
streaming: ts6.then(|| n.flag()),
|
||||
server_groups: (0..n.below(3)).map(|_| 1 + n.below(9)).collect(),
|
||||
country: n.flag().then(|| "DE".into()),
|
||||
avatar: n.flag().then(|| n.text("hash")),
|
||||
myts_avatar: n.flag().then(|| n.text("https://a/")),
|
||||
description: n.flag().then(|| n.text("about ")),
|
||||
talk_power: n.below(100) as i32,
|
||||
talker: n.flag(),
|
||||
channel_group: n.flag().then(|| 1 + n.below(9)),
|
||||
badges: (0..n.below(3)).map(|_| n.text("badge")).collect(),
|
||||
icon: n.below(3) as u32 * 111,
|
||||
recording: n.flag(),
|
||||
priority_speaker: n.flag(),
|
||||
channel_commander: n.flag(),
|
||||
database_id: Some(1_000 + u64::from(id)),
|
||||
},
|
||||
);
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_presences_survive_the_seam() {
|
||||
for seed in 1..=200u64 {
|
||||
for ts6 in [false, true] {
|
||||
let p = generated(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15), ts6);
|
||||
let own = p.clients.keys().next().copied();
|
||||
assert_eq!(through_the_seam(&p, ts6, own), p, "seed {seed}, ts6 {ts6}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,6 +184,17 @@ pub(crate) const MAX_PICTURE_BYTES: u64 = 128 << 20;
|
||||
/// does not hold a download slot.
|
||||
pub(crate) const MIN_PICTURE_RATE: u64 = 8 << 10;
|
||||
|
||||
/// How long a picture of `size` bytes may take to arrive: a minute, plus
|
||||
/// its size at [`MIN_PICTURE_RATE`], so large banners arrive on slow
|
||||
/// links while a stalled transfer still ends.
|
||||
pub(crate) fn image_download_time(size: u64) -> std::time::Duration {
|
||||
std::time::Duration::from_secs(60 + size / MIN_PICTURE_RATE)
|
||||
}
|
||||
|
||||
/// How long the server may take to start an image transfer (a busy server
|
||||
/// answers the requests of a large channel tree in turn).
|
||||
pub(crate) const IMAGE_NEGOTIATION: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
|
||||
/// The cache key of a picture on the web: only `http` and `https`
|
||||
/// addresses (blanks around one are not part of it).
|
||||
pub(crate) fn picture_key(url: &str) -> Option<String> {
|
||||
|
||||
@@ -32,13 +32,13 @@
|
||||
//! never downloaded). [`crate::Command::SetAvatar`] uploads our own.
|
||||
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde::Serialize;
|
||||
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt, AsyncWrite, AsyncWriteExt};
|
||||
|
||||
/// Picked by the caller; the answer carries it back.
|
||||
pub type RequestId = u64;
|
||||
@@ -168,9 +168,10 @@ impl Progress<'_> {
|
||||
const CHUNK: usize = 64 * 1024;
|
||||
|
||||
/// Receive a file: `size` bytes in total, `offset` of them already in the
|
||||
/// sink. Reports `Started`, `Progress` and the final state.
|
||||
pub(crate) async fn download(
|
||||
mut stream: TcpStream,
|
||||
/// sink; `stream` carries the rest. Reports `Started`, `Progress` and the
|
||||
/// final state.
|
||||
pub(crate) async fn download<R: AsyncRead + Unpin>(
|
||||
mut stream: R,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
sink: Sink,
|
||||
@@ -185,8 +186,8 @@ pub(crate) async fn download(
|
||||
});
|
||||
}
|
||||
|
||||
async fn receive(
|
||||
stream: &mut TcpStream,
|
||||
async fn receive<R: AsyncRead + Unpin>(
|
||||
stream: &mut R,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
sink: &Sink,
|
||||
@@ -253,26 +254,57 @@ async fn receive(
|
||||
}
|
||||
}
|
||||
|
||||
/// Send `file` from `offset` (`size` bytes in total). Reports `Started`,
|
||||
/// How long a server may take to close a transfer connection after the last
|
||||
/// byte before the upload counts as done anyway.
|
||||
const CLOSE_WAIT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// Send `file` from `offset` (`size` bytes in total) over `stream`, a
|
||||
/// connection the server closes once it has everything. Reports `Started`,
|
||||
/// `Progress` and the final state.
|
||||
pub(crate) async fn upload(
|
||||
mut stream: TcpStream,
|
||||
pub(crate) async fn upload<S: AsyncRead + AsyncWrite + Unpin>(
|
||||
stream: S,
|
||||
file: PathBuf,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
progress_every: Duration,
|
||||
report: Report,
|
||||
) {
|
||||
let (mut read, write) = tokio::io::split(stream);
|
||||
let closed = async move {
|
||||
let _ = tokio::time::timeout(CLOSE_WAIT, read.read(&mut [0u8; 1])).await;
|
||||
Ok(())
|
||||
};
|
||||
upload_to(write, closed, file, size, offset, progress_every, report).await;
|
||||
}
|
||||
|
||||
/// Send `file` from `offset` (`size` bytes in total) into `writer`, then end
|
||||
/// it and wait for `stored`, which resolves once the server has the file.
|
||||
/// Reports `Started`, `Progress` and the final state.
|
||||
pub(crate) async fn upload_to<W, F>(
|
||||
mut writer: W,
|
||||
stored: F,
|
||||
file: PathBuf,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
progress_every: Duration,
|
||||
report: Report,
|
||||
) where
|
||||
W: AsyncWrite + Unpin,
|
||||
F: Future<Output = Result<(), String>>,
|
||||
{
|
||||
report(TransferState::Started { size, offset });
|
||||
let result = send(&mut stream, &file, size, offset, progress_every, &report).await;
|
||||
let result = match send(&mut writer, &file, size, offset, progress_every, &report).await {
|
||||
Ok(()) => stored.await,
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
report(match result {
|
||||
Ok(()) => TransferState::Done { size, path: Some(file), data: None },
|
||||
Err(e) => TransferState::Failed(e),
|
||||
});
|
||||
}
|
||||
|
||||
async fn send(
|
||||
stream: &mut TcpStream,
|
||||
async fn send<W: AsyncWrite + Unpin>(
|
||||
stream: &mut W,
|
||||
path: &Path,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
@@ -300,8 +332,6 @@ async fn send(
|
||||
}
|
||||
stream.flush().await.map_err(|e| e.to_string())?;
|
||||
stream.shutdown().await.map_err(|e| e.to_string())?;
|
||||
// The server closes the connection once it has everything.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(30), stream.read(&mut buf[..1])).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -421,7 +451,7 @@ fn percent_decode(text: &str) -> Option<String> {
|
||||
mod tests {
|
||||
use std::sync::Mutex;
|
||||
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
|
||||
use super::*;
|
||||
|
||||
|
||||
@@ -67,6 +67,7 @@ mod stream_types;
|
||||
#[cfg(feature = "media")]
|
||||
pub mod studio;
|
||||
mod ts_link;
|
||||
mod ts_session;
|
||||
pub mod versions;
|
||||
mod voice;
|
||||
mod web;
|
||||
@@ -91,6 +92,7 @@ pub use files::{Bytes, DownloadTo, FileEntry, RequestId, TransferId, TransferSta
|
||||
pub use gateway::{GatewayRequest, GatewayUpdate};
|
||||
use history::SharedHistory;
|
||||
pub use history::{History, HistoryMessage, HistorySource};
|
||||
pub use link::Backends;
|
||||
pub use link::ConnectOptions;
|
||||
pub use link::ConnectOptions as VoiceOptions;
|
||||
pub use link::ServerLink;
|
||||
@@ -792,19 +794,33 @@ impl Engine {
|
||||
}
|
||||
|
||||
/// Start the engine on the current tokio runtime with `settings` and
|
||||
/// chat `history`, connecting voice with [`TsLink`].
|
||||
/// chat `history`, connecting voice with the engine's own connectors
|
||||
/// ([`Backends::default`]: TeamSpeak 3 and 6).
|
||||
pub fn start_with(settings: Settings, history: History) -> Self {
|
||||
Self::start_with_link(settings, history, Arc::new(TsLink))
|
||||
Self::start_with_backends(settings, history, Backends::default())
|
||||
}
|
||||
|
||||
/// Start the engine on the current tokio runtime with `settings` and
|
||||
/// chat `history`, connecting voice with `link` (every session's voice
|
||||
/// source is one of its connections, see [`link`]).
|
||||
/// source is one of its connections, see [`link`]). The engine reaches
|
||||
/// `link` as a `voelin_proto::link::Session` of its own, for every
|
||||
/// address, like it does a connector's.
|
||||
pub fn start_with_link(
|
||||
settings: Settings,
|
||||
history: History,
|
||||
link: Arc<dyn ServerLink>,
|
||||
) -> Self {
|
||||
let mut backends = Backends::empty();
|
||||
backends.register_local(Arc::new(ts_session::LinkConnector::any(link)));
|
||||
Self::start_with_backends(settings, history, backends)
|
||||
}
|
||||
|
||||
/// Start the engine on the current tokio runtime with `settings` and
|
||||
/// chat `history`, connecting voice with the connectors in `backends`:
|
||||
/// the one for the scheme of a session's address makes its
|
||||
/// `voelin_proto::link::Session`.
|
||||
pub fn start_with_backends(settings: Settings, history: History, backends: Backends) -> Self {
|
||||
let link: Arc<dyn ServerLink> = Arc::new(link::SessionLink::new(backends));
|
||||
let (commands, rx) = mpsc::unbounded_channel();
|
||||
let (events, _) = broadcast::channel(4096);
|
||||
// About a minute of one watched stream.
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
//! The registry of the engine's connectors, by address scheme.
|
||||
//!
|
||||
//! A session's voice source is a `voelin_proto::link::Session`
|
||||
//! (`docs/session-seam.md` section 4.1). Which backend makes it is the
|
||||
//! scheme of the address: [`Backends`] holds the plain connectors of
|
||||
//! `voelin_proto::link::Connectors` (the Voelin protocol's QUIC connector
|
||||
//! later, `FakeConnector` in tests) and the in-process connectors, which
|
||||
//! also hand the engine what a `Session` has no room for yet (the TeamSpeak 6
|
||||
//! stream task, [`StreamPort`]).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use voelin_proto::link::{
|
||||
AccountAgent, BoxFuture, ConnectParams, Connected, Connector, Connectors, HostIdentity,
|
||||
HostTrust, SessionError,
|
||||
};
|
||||
use voelin_stream::PeerConfig;
|
||||
|
||||
use super::LinkCtx;
|
||||
use crate::stream::{OwnStreamEvent, StreamCmd};
|
||||
|
||||
/// The scheme of the TeamSpeak servers a bookmark names without one.
|
||||
pub(crate) const TEAMSPEAK_SCHEME: &str = "ts3server";
|
||||
|
||||
/// What comes back from the stream task of a connection that has one.
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum StreamEvent {
|
||||
/// Our own stream's life, for the gateway directory.
|
||||
OwnStream(OwnStreamEvent),
|
||||
/// An Opus frame of a watched stream, for the audio thread.
|
||||
Audio { stream: String, time: u64, data: Arc<[u8]> },
|
||||
/// A watched stream ended.
|
||||
AudioEnded(String),
|
||||
}
|
||||
|
||||
/// The in-process channel of TeamSpeak 6 streams past the `Session` trait
|
||||
/// (`docs/session-seam.md` section 6.4): TeamSpeak 6 streams are peer to peer
|
||||
/// and not v1 entities yet, so the commands go to the connection's stream
|
||||
/// task and its events come back here.
|
||||
pub(crate) struct StreamPort {
|
||||
send: Box<dyn Fn(StreamCmd) + Send + Sync>,
|
||||
/// What the stream task reports.
|
||||
pub(crate) events: mpsc::UnboundedReceiver<StreamEvent>,
|
||||
}
|
||||
|
||||
impl StreamPort {
|
||||
/// A port whose commands go to `send`.
|
||||
pub(crate) fn new(
|
||||
send: impl Fn(StreamCmd) + Send + Sync + 'static,
|
||||
events: mpsc::UnboundedReceiver<StreamEvent>,
|
||||
) -> Self {
|
||||
Self { send: Box::new(send), events }
|
||||
}
|
||||
|
||||
/// Give the stream task a command.
|
||||
pub(crate) fn send(&self, cmd: StreamCmd) {
|
||||
(self.send)(cmd);
|
||||
}
|
||||
}
|
||||
|
||||
/// What an in-process backend needs besides the connect parameters.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct LocalCtx {
|
||||
/// The session's side of the engine: its id, event bus, frames and
|
||||
/// settings, and the account proof watches.
|
||||
pub(crate) link: LinkCtx,
|
||||
/// Open the audio devices (the stream task plays what streams carry).
|
||||
pub(crate) audio: bool,
|
||||
/// Network settings for stream peer connections.
|
||||
pub(crate) stream_peer: PeerConfig,
|
||||
/// Keeps the senders of `link`'s watches alive when there is no engine.
|
||||
_keep: Option<Arc<dyn std::any::Any + Send + Sync>>,
|
||||
}
|
||||
|
||||
impl LocalCtx {
|
||||
pub(crate) fn new(link: LinkCtx, audio: bool, stream_peer: PeerConfig) -> Self {
|
||||
Self { link, audio, stream_peer, _keep: None }
|
||||
}
|
||||
|
||||
/// A context for a connection made outside an engine (a test or a tool
|
||||
/// that calls a connector itself): a session of its own that nobody
|
||||
/// listens to.
|
||||
pub(crate) fn standalone() -> Self {
|
||||
let (events, _) = tokio::sync::broadcast::channel(16);
|
||||
let (frames, _) = tokio::sync::broadcast::channel(16);
|
||||
let (identity_tx, myts_identity) = watch::channel(None);
|
||||
let (data_tx, myts_data) = watch::channel(None);
|
||||
let link = LinkCtx {
|
||||
session: 0,
|
||||
events,
|
||||
frames,
|
||||
settings: crate::settings::SharedSettings::new(crate::settings::Settings::in_memory()),
|
||||
myts_identity,
|
||||
myts_data,
|
||||
};
|
||||
Self {
|
||||
link,
|
||||
audio: false,
|
||||
stream_peer: PeerConfig::default(),
|
||||
_keep: Some(Arc::new((identity_tx, data_tx))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection an in-process connector made.
|
||||
pub(crate) struct LocalConnected {
|
||||
pub(crate) connected: Connected,
|
||||
/// The stream task's port, for a backend that runs one.
|
||||
pub(crate) streams: Option<StreamPort>,
|
||||
}
|
||||
|
||||
/// A connector that runs in this process and can use the engine's context
|
||||
/// ([`LocalCtx`]); its sessions may come with a [`StreamPort`].
|
||||
pub(crate) trait LocalConnector: Connector {
|
||||
/// Whether this connector serves addresses of `scheme`. By default, the
|
||||
/// schemes it names.
|
||||
fn accepts(&self, scheme: &str) -> bool {
|
||||
self.schemes().contains(&scheme)
|
||||
}
|
||||
|
||||
/// Connect with the engine's context.
|
||||
fn connect_local(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>>;
|
||||
}
|
||||
|
||||
/// The connectors of an engine, found by the scheme of an address.
|
||||
///
|
||||
/// A scheme served by an in-process connector goes to it, one served by a
|
||||
/// plain connector ([`Backends::register`]) to that. An address without a
|
||||
/// scheme is a TeamSpeak bookmark and is taken for a `ts3server` one.
|
||||
#[derive(Clone)]
|
||||
pub struct Backends {
|
||||
connectors: Connectors,
|
||||
locals: Vec<Arc<dyn LocalConnector>>,
|
||||
account: Option<Arc<dyn AccountAgent>>,
|
||||
/// The connections' trust in hosts that are neither valid nor pinned.
|
||||
trust: Option<Arc<dyn HostTrust>>,
|
||||
}
|
||||
|
||||
impl Default for Backends {
|
||||
/// The engine's connectors: TeamSpeak 3 and 6 (`ts3server://` and
|
||||
/// `teamspeak://`, and an address without a scheme).
|
||||
fn default() -> Self {
|
||||
let mut backends = Self::empty();
|
||||
backends.register_local(Arc::new(crate::ts_session::TsConnector::new()));
|
||||
backends
|
||||
}
|
||||
}
|
||||
|
||||
impl Backends {
|
||||
/// No connector at all. ([`Backends::default`] has the TeamSpeak one.)
|
||||
pub fn empty() -> Self {
|
||||
Self { connectors: Connectors::default(), locals: Vec::new(), account: None, trust: None }
|
||||
}
|
||||
|
||||
/// Register a connector for the schemes it names.
|
||||
pub fn register(&mut self, connector: Arc<dyn Connector>) {
|
||||
self.connectors.register(connector);
|
||||
}
|
||||
|
||||
pub(crate) fn register_local(&mut self, connector: Arc<dyn LocalConnector>) {
|
||||
self.locals.push(connector);
|
||||
}
|
||||
|
||||
/// The device's Voelin account, for the connectors that use it (the QUIC
|
||||
/// connector's certificate, the TeamSpeak connector's myTS ID proof).
|
||||
/// None is the default: nothing uses an account yet.
|
||||
pub fn set_account(&mut self, agent: Option<Arc<dyn AccountAgent>>) {
|
||||
self.account = agent;
|
||||
}
|
||||
|
||||
/// The account agent, if one was set ([`Backends::set_account`]).
|
||||
pub fn account(&self) -> Option<Arc<dyn AccountAgent>> {
|
||||
self.account.clone()
|
||||
}
|
||||
|
||||
/// Decide about hosts that are neither valid nor pinned. The default
|
||||
/// refuses them: there is no trust dialog yet, and TeamSpeak has no host
|
||||
/// key.
|
||||
pub fn set_trust(&mut self, trust: Option<Arc<dyn HostTrust>>) {
|
||||
self.trust = trust;
|
||||
}
|
||||
|
||||
pub(crate) fn trust(&self) -> Arc<dyn HostTrust> {
|
||||
self.trust.clone().unwrap_or_else(|| Arc::new(RefuseUnknownHosts))
|
||||
}
|
||||
|
||||
/// The scheme of an address, lowercase; a TeamSpeak bookmark's when there
|
||||
/// is none.
|
||||
pub(crate) fn scheme(address: &str) -> String {
|
||||
match address.split_once("://") {
|
||||
Some((scheme, _)) => scheme.to_ascii_lowercase(),
|
||||
None => TEAMSPEAK_SCHEME.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a session to `params.address` with the connector of its scheme.
|
||||
pub(crate) fn connect(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>> {
|
||||
let scheme = Self::scheme(¶ms.address);
|
||||
if let Some(local) = self.locals.iter().find(|c| c.accepts(&scheme)) {
|
||||
return local.connect_local(params, ctx);
|
||||
}
|
||||
let connect = self.connectors.connect(params);
|
||||
Box::pin(async move {
|
||||
let connected = connect.await?;
|
||||
Ok(LocalConnected { connected, streams: None })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuses every host that asks to be trusted.
|
||||
struct RefuseUnknownHosts;
|
||||
|
||||
impl HostTrust for RefuseUnknownHosts {
|
||||
fn confirm(&self, _host: HostIdentity) -> BoxFuture<bool> {
|
||||
Box::pin(async { false })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_bookmark_without_a_scheme_is_a_teamspeak_server() {
|
||||
assert_eq!(Backends::scheme("ts.example.com:9987"), "ts3server");
|
||||
assert_eq!(Backends::scheme("[::1]:9987"), "ts3server");
|
||||
assert_eq!(Backends::scheme("TS3Server://ts.example.com"), "ts3server");
|
||||
assert_eq!(Backends::scheme("teamspeak://x"), "teamspeak");
|
||||
assert_eq!(Backends::scheme("voelin://host/i/code"), "voelin");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
//! Voice across the seam, engine side (`docs/session-seam.md` section 6.1):
|
||||
//! our encoded frames as RTP on our voice slot, the RTP of other slots as
|
||||
//! the audio thread's packets, and who is talking from the media.
|
||||
//!
|
||||
//! `voelin-audio`'s [`EncodedVoice`] and [`VoicePacket`] stay what the audio
|
||||
//! thread speaks; this is the framing in the v1 media codec
|
||||
//! (`voelin_proto::media`, protocol section 6).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::BytesMut;
|
||||
use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
|
||||
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::opus::{self, Toc};
|
||||
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
|
||||
/// A talker is silent after this long without a packet.
|
||||
pub(crate) const TALK_SILENCE: Duration = Duration::from_millis(400);
|
||||
|
||||
/// Our voice as RTP: the sequence number counts every packet from 0, the
|
||||
/// timestamp starts at 0 and advances by the duration of the previous
|
||||
/// packet, the marker is set on the first packet of a spurt, and the end of a
|
||||
/// spurt is a packet with an empty payload, sent once.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Uplink {
|
||||
sequence: u16,
|
||||
timestamp: u32,
|
||||
/// The ticks the last voice packet spans.
|
||||
ticks: u32,
|
||||
in_spurt: bool,
|
||||
}
|
||||
|
||||
impl Uplink {
|
||||
/// `voice` as the RTP packet of our voice slot.
|
||||
pub(crate) fn frame(&mut self, slot: u32, voice: &EncodedVoice) -> Option<MediaPacket> {
|
||||
let flow = FlowId::new(slot, voice_sub::CHANNEL);
|
||||
// The previous packet's duration has passed.
|
||||
self.timestamp = self.timestamp.wrapping_add(self.ticks);
|
||||
let end = voice.is_end();
|
||||
let mut header = RtpHeader::new(PT_OPUS, self.sequence, self.timestamp);
|
||||
header.marker = !end && !self.in_spurt;
|
||||
self.ticks =
|
||||
if end { 0 } else { opus::packet_ticks(&voice.payload).unwrap_or(OPUS_20_MS_TICKS) };
|
||||
self.in_spurt = !end;
|
||||
self.sequence = self.sequence.wrapping_add(1);
|
||||
let mut out = BytesMut::with_capacity(header.encoded_len() + voice.payload.len());
|
||||
header.write(flow, &mut out).ok()?;
|
||||
out.extend_from_slice(&voice.payload);
|
||||
Some(MediaPacket { flow, rtp: out.freeze() })
|
||||
}
|
||||
}
|
||||
|
||||
/// A voice packet of some slot, taken from its RTP.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Incoming {
|
||||
pub(crate) slot: u32,
|
||||
/// Sent on a whisper sub-flow (1 to 6).
|
||||
pub(crate) whisper: bool,
|
||||
pub(crate) sequence: u16,
|
||||
pub(crate) codec: VoiceCodec,
|
||||
/// Empty: the spurt ends.
|
||||
pub(crate) payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Incoming {
|
||||
/// Parse a media packet. `None` for what is not the voice of a slot:
|
||||
/// feedback, probes, a flow that is no media, a packet that is no RTP.
|
||||
pub(crate) fn parse(packet: &MediaPacket) -> Option<Incoming> {
|
||||
if !packet.flow.is_media() {
|
||||
return None;
|
||||
}
|
||||
let view = RtpView::parse(&packet.rtp).ok()?;
|
||||
let payload = view.payload();
|
||||
// Stereo Opus is music; the jitter buffer decodes both the same way.
|
||||
let codec = match Toc::parse(payload) {
|
||||
Ok(toc) if toc.stereo() => VoiceCodec::Music,
|
||||
_ => VoiceCodec::Voice,
|
||||
};
|
||||
Some(Incoming {
|
||||
slot: packet.flow.slot(),
|
||||
whisper: (voice_sub::FIRST_TALK_TARGET..=voice_sub::LAST_TALK_TARGET)
|
||||
.contains(&packet.flow.sub()),
|
||||
sequence: view.sequence(),
|
||||
codec,
|
||||
payload: payload.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The packet for the audio thread, from `talker`.
|
||||
pub(crate) fn voice(self, talker: u16) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: TalkerId(talker),
|
||||
seq: self.sequence,
|
||||
codec: self.codec,
|
||||
whisper: self.whisper,
|
||||
payload: self.payload,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Who is talking: derived from the media (protocol section 6.4). A talker
|
||||
/// starts with its first packet and stops after [`TALK_SILENCE`] without one.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct TalkTracker {
|
||||
last: HashMap<u16, Instant>,
|
||||
}
|
||||
|
||||
impl TalkTracker {
|
||||
/// A packet of `client` arrived; whether this starts its talking.
|
||||
pub(crate) fn heard(&mut self, client: u16, now: Instant) -> bool {
|
||||
self.last.insert(client, now).is_none()
|
||||
}
|
||||
|
||||
/// The talkers that have been silent long enough, no longer talking.
|
||||
pub(crate) fn expire(&mut self, now: Instant) -> Vec<u16> {
|
||||
let mut silent: Vec<u16> = self
|
||||
.last
|
||||
.iter()
|
||||
.filter(|(_, last)| now.saturating_duration_since(**last) >= TALK_SILENCE)
|
||||
.map(|(client, _)| *client)
|
||||
.collect();
|
||||
silent.sort_unstable();
|
||||
for client in &silent {
|
||||
self.last.remove(client);
|
||||
}
|
||||
silent
|
||||
}
|
||||
|
||||
pub(crate) fn is_talking(&self, client: u16) -> bool {
|
||||
self.last.contains_key(&client)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 20 ms of CELT, mono, one frame.
|
||||
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
|
||||
|
||||
fn voice(payload: &[u8]) -> EncodedVoice {
|
||||
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
|
||||
}
|
||||
|
||||
fn view(packet: &MediaPacket) -> RtpView<'_> {
|
||||
RtpView::parse(&packet.rtp).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn our_voice_is_sequenced_stamped_and_marked() {
|
||||
let mut up = Uplink::default();
|
||||
let first = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
let second = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
assert_eq!((first.flow.slot(), first.flow.sub()), (8, 0));
|
||||
let (a, b) = (view(&first), view(&second));
|
||||
assert_eq!((a.sequence(), a.timestamp(), a.marker()), (0, 0, true));
|
||||
assert_eq!((b.sequence(), b.timestamp(), b.marker()), (1, OPUS_20_MS_TICKS, false));
|
||||
assert_eq!((a.ssrc(), a.payload_type()), (first.flow.0, PT_OPUS));
|
||||
assert_eq!(a.payload(), OPUS_20_MS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_is_one_empty_packet_and_the_next_spurt_has_a_marker() {
|
||||
let mut up = Uplink::default();
|
||||
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
let end = up.frame(8, &voice(&[])).unwrap();
|
||||
assert!(view(&end).payload().is_empty() && !view(&end).marker());
|
||||
assert_eq!(view(&end).sequence(), 1);
|
||||
let next = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
assert!(view(&next).marker());
|
||||
assert_eq!(view(&next).sequence(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sequence_wraps() {
|
||||
let mut up = Uplink { sequence: u16::MAX, ..Default::default() };
|
||||
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
let wrapped = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
assert_eq!(view(&wrapped).sequence(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn received_voice_is_split_into_slot_sub_flow_sequence_and_codec() {
|
||||
let flow = FlowId::new(9, 0);
|
||||
let mut header = RtpHeader::new(PT_OPUS, 513, 0);
|
||||
header.marker = true;
|
||||
let mut rtp = BytesMut::new();
|
||||
header.write(flow, &mut rtp).unwrap();
|
||||
rtp.extend_from_slice(&OPUS_20_MS);
|
||||
let packet = MediaPacket { flow, rtp: rtp.freeze() };
|
||||
let got = Incoming::parse(&packet).unwrap();
|
||||
assert_eq!(
|
||||
got,
|
||||
Incoming {
|
||||
slot: 9,
|
||||
whisper: false,
|
||||
sequence: 513,
|
||||
codec: VoiceCodec::Voice,
|
||||
payload: OPUS_20_MS.to_vec()
|
||||
}
|
||||
);
|
||||
let voice = got.voice(8);
|
||||
assert_eq!((voice.talker, voice.seq, voice.whisper), (TalkerId(8), 513, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whispers_stereo_ends_and_what_is_no_voice() {
|
||||
let packet = |flow: FlowId, payload: &[u8]| {
|
||||
let mut rtp = BytesMut::new();
|
||||
RtpHeader::new(PT_OPUS, 1, 0).write(flow, &mut rtp).unwrap();
|
||||
rtp.extend_from_slice(payload);
|
||||
MediaPacket { flow, rtp: rtp.freeze() }
|
||||
};
|
||||
assert!(Incoming::parse(&packet(FlowId::new(9, 3), &OPUS_20_MS)).unwrap().whisper);
|
||||
assert!(!Incoming::parse(&packet(FlowId::new(9, 7), &OPUS_20_MS)).unwrap().whisper);
|
||||
let stereo = [OPUS_20_MS[0] | 0x04, 1, 2];
|
||||
assert_eq!(
|
||||
Incoming::parse(&packet(FlowId::new(9, 0), &stereo)).unwrap().codec,
|
||||
VoiceCodec::Music
|
||||
);
|
||||
let end = Incoming::parse(&packet(FlowId::new(9, 0), &[])).unwrap();
|
||||
assert!(end.payload.is_empty() && end.voice(8).is_end());
|
||||
// Feedback and probes are no voice.
|
||||
assert!(
|
||||
Incoming::parse(&MediaPacket { flow: FlowId::FEEDBACK, rtp: Default::default() })
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
Incoming::parse(&MediaPacket { flow: FlowId::PROBE, rtp: Default::default() })
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
Incoming::parse(&MediaPacket { flow: FlowId::new(9, 0), rtp: vec![1, 2].into() })
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_talker_starts_with_a_packet_and_stops_400_ms_after_its_last() {
|
||||
let mut talk = TalkTracker::default();
|
||||
let t0 = Instant::now();
|
||||
assert!(talk.heard(8, t0));
|
||||
assert!(!talk.heard(8, t0 + Duration::from_millis(100)), "already talking");
|
||||
assert!(talk.heard(9, t0 + Duration::from_millis(150)));
|
||||
assert!(talk.is_talking(8));
|
||||
// 399 ms after 8's last packet: still talking.
|
||||
assert!(talk.expire(t0 + Duration::from_millis(499)).is_empty());
|
||||
assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [8]);
|
||||
assert!(!talk.is_talking(8) && talk.is_talking(9));
|
||||
assert_eq!(talk.expire(t0 + Duration::from_millis(551)), [9]);
|
||||
// A packet after the silence starts it again.
|
||||
assert!(talk.heard(8, t0 + Duration::from_secs(2)));
|
||||
}
|
||||
}
|
||||
@@ -54,20 +54,34 @@
|
||||
//!
|
||||
//! # Implementations
|
||||
//!
|
||||
//! The engine's own implementation is [`SessionLink`]: it connects through
|
||||
//! [`Backends`], the registry of connectors by address scheme, and talks to
|
||||
//! the `voelin_proto::link::Session` it gets (`session_link.rs`, with
|
||||
//! `project.rs` and `media.rs`). Nothing of a backend shows above it:
|
||||
//! `session.rs` keeps speaking [`LinkCmd`] and [`LinkEvent`], and SessionLink
|
||||
//! turns them into `Session` calls and the session's pushes and media into
|
||||
//! events (`docs/session-seam.md` describes the mapping row by row).
|
||||
//!
|
||||
//! [`TsLink`](crate::TsLink) (`ts_link.rs`, with `voice.rs`) is the
|
||||
//! TeamSpeak 3 and 6 connection of `tsclientlib`; it is the only one for now,
|
||||
//! and [`Engine::start_with_link`](crate::Engine::start_with_link) takes
|
||||
//! another (the tests drive the session with an in-memory one,
|
||||
//! `tests/link_fake.rs`). The decoupling plan moves `TsLink` out of this
|
||||
//! crate into the TeamSpeak gateway (VoelinGateWay, `voelin-gateway-ts`), and
|
||||
//! the Voelin protocol's QUIC transport becomes the other implementation,
|
||||
//! both behind the backend-neutral `voelin_proto::link::Session` of
|
||||
//! VoelinProtocol; `ServerLink` is this crate's side of that seam until then.
|
||||
//! TeamSpeak 3 and 6 connection of `tsclientlib`. It is a `ServerLink` of this
|
||||
//! older vocabulary, and the engine reaches it as a `Session`: the
|
||||
//! `ts_session` module wraps any `ServerLink` in a `Session` (`LinkSession`,
|
||||
//! made by `TsConnector` for `ts3server://` and `teamspeak://` addresses).
|
||||
//! [`Engine::start_with_link`](crate::Engine::start_with_link) takes another
|
||||
//! link the same way (the tests drive the session with an in-memory one,
|
||||
//! `tests/link_fake.rs`), and
|
||||
//! [`Engine::start_with_backends`](crate::Engine::start_with_backends) takes
|
||||
//! connectors of `Session`s. The decoupling plan moves the TeamSpeak side out
|
||||
//! of this crate into the TeamSpeak gateway (VoelinGateWay,
|
||||
//! `voelin-gateway-ts`), and the Voelin protocol's QUIC transport becomes the
|
||||
//! other implementation, both behind the backend-neutral
|
||||
//! `voelin_proto::link::Session` of VoelinProtocol.
|
||||
//!
|
||||
//! # What is still TeamSpeak's
|
||||
//!
|
||||
//! The seam is not backend-neutral yet. What still has TeamSpeak types or
|
||||
//! TeamSpeak's shape, and changes when `TsLink` leaves:
|
||||
//! The vocabulary of [`ServerLink`], and of the engine above it, is not
|
||||
//! backend-neutral yet. What still has TeamSpeak types or TeamSpeak's shape,
|
||||
//! and changes when the TeamSpeak side leaves:
|
||||
//!
|
||||
//! - Types of the TeamSpeak crates: [`ConnectOptions::identity`] and
|
||||
//! [`ConnectOptions::client_version`] (`tsclientlib`), and the account
|
||||
@@ -84,12 +98,27 @@
|
||||
//! protocol: `PeerConfig` in [`ConnectOptions::stream_peer`], `MediaFrame`
|
||||
//! in the frames of watched streams ([`LinkCtx`]), `VideoFormat` in
|
||||
//! `StreamCmd::VideoFrame`, and `VideoCodec` and `FrameSource` of the same
|
||||
//! API (re-exported from [`crate::stream`]).
|
||||
//! API (re-exported from [`crate::stream`]). TeamSpeak 6 streams are peer
|
||||
//! to peer, so their commands and events pass the `Session` through a local
|
||||
//! port for now.
|
||||
|
||||
mod backends;
|
||||
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};
|
||||
pub(crate) use session_link::SessionLink;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::{broadcast, mpsc, watch};
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio::sync::{broadcast, mpsc, oneshot, watch};
|
||||
use voelin_audio::{EncodedVoice, VoicePacket};
|
||||
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence};
|
||||
use voelin_stream::PeerConfig;
|
||||
@@ -197,6 +226,17 @@ pub struct Remote {
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// A boxed stream of bytes to read: the body of a file the server sends.
|
||||
pub type BoxRead = Pin<Box<dyn AsyncRead + Send>>;
|
||||
|
||||
/// A connection that can be read and written: a file transfer connection.
|
||||
pub trait Duplex: AsyncRead + AsyncWrite + Send {}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite + Send> Duplex for T {}
|
||||
|
||||
/// A boxed [`Duplex`].
|
||||
pub type BoxDuplex = Pin<Box<dyn Duplex>>;
|
||||
|
||||
/// What the session asks of a connection.
|
||||
pub enum LinkCmd {
|
||||
SendChat(ChatTarget, String),
|
||||
@@ -232,6 +272,27 @@ pub enum LinkCmd {
|
||||
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>,
|
||||
@@ -0,0 +1,214 @@
|
||||
//! The engine's view of a session's replica, in the client's older model
|
||||
//! (`docs/session-seam.md` section 5.3).
|
||||
//!
|
||||
//! The UI and `session.rs` still speak `Presence`, `ChannelInfo`,
|
||||
//! `ClientInfo`, `ServerDetails` and `ChatMessage`. [`presence`] and
|
||||
//! [`chat_message`] project the replica into them with
|
||||
//! `voelin_model::replica::convert`, and fix up where that says less than the
|
||||
//! older model does (F1 to F10 of the design). The fix-ups apply the
|
||||
//! TeamSpeak gateway's id rules of protocol section 11.1, so the UI keeps the
|
||||
//! ids it has; they go when the UI reads the replica.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use voelin_model::replica::{Replica, convert};
|
||||
use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails};
|
||||
use voelin_proto::link::Features;
|
||||
use voelin_proto::v1::{self, ChannelKind, MessageFlag, RoleScope};
|
||||
|
||||
use super::media::TalkTracker;
|
||||
use crate::ts_session::entities::user_uid;
|
||||
use crate::ts_session::ids::{self, FOREIGN_SYSTEM};
|
||||
|
||||
/// What the projection needs to know besides the replica.
|
||||
pub(crate) struct View<'a> {
|
||||
pub(crate) replica: &'a Replica,
|
||||
/// The server of the session.
|
||||
pub(crate) server: u64,
|
||||
/// The backend is TeamSpeak (`Welcome.host.backend.product`): its id rules
|
||||
/// (channel groups) are undone.
|
||||
pub(crate) teamspeak: bool,
|
||||
/// The version the host said (`Welcome.host.backend.version`).
|
||||
pub(crate) version: &'a str,
|
||||
pub(crate) features: &'a Features,
|
||||
/// Whether the connection has streams (a port, not just the feature).
|
||||
pub(crate) streams: bool,
|
||||
pub(crate) talking: &'a TalkTracker,
|
||||
}
|
||||
|
||||
/// What a `Foreign` of TeamSpeak holds under `key`.
|
||||
fn foreign_value(
|
||||
foreign: Option<&v1::Foreign>,
|
||||
kind: &str,
|
||||
key: &str,
|
||||
) -> Option<serde_json::Value> {
|
||||
let foreign = foreign.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == kind)?;
|
||||
serde_json::from_slice::<serde_json::Value>(&foreign.json).ok()?.get(key).cloned()
|
||||
}
|
||||
|
||||
/// The server's unique id as the client keys its history and aliases by it:
|
||||
/// the host's without the `ts:` of protocol section 11.2 (F3).
|
||||
pub(crate) fn server_key(uid: &str) -> String {
|
||||
uid.strip_prefix("ts:").unwrap_or(uid).to_owned()
|
||||
}
|
||||
|
||||
/// The client's older model of the server (what `LinkEvent::Presence` holds).
|
||||
pub(crate) fn presence(view: &View<'_>) -> Presence {
|
||||
let replica = view.replica;
|
||||
let server = view.server;
|
||||
// F1: only what the older model calls channels.
|
||||
let channels: Vec<&v1::Channel> = replica
|
||||
.channels(server)
|
||||
.filter(|channel| {
|
||||
!matches!(
|
||||
ChannelKind::try_from(channel.kind),
|
||||
Ok(ChannelKind::ServerChat
|
||||
| ChannelKind::Dm
|
||||
| ChannelKind::GroupDm
|
||||
| ChannelKind::Thread)
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let by_id: BTreeMap<u64, &v1::Channel> = channels.iter().map(|c| (c.id, *c)).collect();
|
||||
let channel_infos = convert::channel_infos(&channels)
|
||||
.into_iter()
|
||||
.map(|mut info| {
|
||||
// F7: a limit of 0 is a limit, not "unlimited".
|
||||
let zero = by_id
|
||||
.get(&info.id)
|
||||
.and_then(|c| foreign_value(c.foreign.as_ref(), "channel", "max_clients"));
|
||||
if zero.and_then(|v| v.as_i64()) == Some(0) {
|
||||
info.max_clients = Some(0);
|
||||
}
|
||||
(info.id, info)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let clients = replica
|
||||
.voice_states(server)
|
||||
.filter_map(|voice| {
|
||||
let user = replica.user(voice.user_id);
|
||||
let member = replica.member(server, voice.user_id);
|
||||
let mut client =
|
||||
convert::client_info(voice, user, member, replica.presence_of(voice.user_id))?;
|
||||
// F10: a unique id that is no base64 rides in `Foreign`.
|
||||
client.uid = user.and_then(user_uid);
|
||||
// F2: the client's channel group is TeamSpeak's own number.
|
||||
if view.teamspeak {
|
||||
client.channel_group = client.channel_group.map(ids::channel_group);
|
||||
}
|
||||
// F6: the client's icon.
|
||||
client.icon = foreign_value(member.and_then(|m| m.foreign.as_ref()), "client", "icon")
|
||||
.and_then(|v| v.as_u64())
|
||||
.and_then(|v| u32::try_from(v).ok())
|
||||
.unwrap_or(0);
|
||||
// F8: who is talking comes from the media.
|
||||
client.talking = view.features.has("voice").then(|| view.talking.is_talking(client.id));
|
||||
// F9: the stream flag only where there are streams.
|
||||
if !view.streams {
|
||||
client.streaming = None;
|
||||
}
|
||||
Some((client.id, client))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut server_groups: BTreeMap<u64, GroupInfo> = BTreeMap::new();
|
||||
let mut channel_groups: BTreeMap<u64, GroupInfo> = BTreeMap::new();
|
||||
for role in replica.roles(server) {
|
||||
let mut info = convert::group_info(role);
|
||||
if role.scope == RoleScope::Channel as i32 {
|
||||
if view.teamspeak {
|
||||
info.id = ids::channel_group(info.id);
|
||||
}
|
||||
channel_groups.insert(info.id, info);
|
||||
} else {
|
||||
server_groups.insert(info.id, info);
|
||||
}
|
||||
}
|
||||
|
||||
let details = replica.server(server).map(|stub| server_details(view, stub)).unwrap_or_default();
|
||||
Presence {
|
||||
server_name: details.name.clone(),
|
||||
channels: channel_infos,
|
||||
clients,
|
||||
server: details,
|
||||
server_groups,
|
||||
channel_groups,
|
||||
}
|
||||
}
|
||||
|
||||
/// `convert::server_details` with F2 to F5.
|
||||
fn server_details(view: &View<'_>, server: &v1::Server) -> ServerDetails {
|
||||
let mut details = convert::server_details(server);
|
||||
// F3: the unique id as the client keys it.
|
||||
details.uid = details.uid.as_deref().map(server_key);
|
||||
let foreign = server.foreign.as_ref();
|
||||
// F4: the version the server sent, else the one the host reports.
|
||||
details.version = foreign_value(foreign, "server", "version")
|
||||
.and_then(|v| v.as_str().map(str::to_owned))
|
||||
.filter(|v| !v.is_empty())
|
||||
.unwrap_or_else(|| view.version.to_owned());
|
||||
// F5: the server's platform.
|
||||
details.platform = foreign_value(foreign, "server", "platform")
|
||||
.and_then(|v| v.as_str().map(str::to_owned))
|
||||
.unwrap_or_default();
|
||||
// F2: the default channel group is TeamSpeak's own number.
|
||||
if view.teamspeak {
|
||||
details.default_channel_group = details.default_channel_group.map(ids::channel_group);
|
||||
}
|
||||
details
|
||||
}
|
||||
|
||||
/// Where the older model files the messages of a channel (the replica's
|
||||
/// `chat_target`, with the unique id of F10).
|
||||
fn chat_target(replica: &Replica, channel: u64) -> ChatTarget {
|
||||
let Some(info) = replica.channel(channel) else { return ChatTarget::Channel(channel) };
|
||||
match ChannelKind::try_from(info.kind) {
|
||||
Ok(ChannelKind::ServerChat) => ChatTarget::Server,
|
||||
Ok(ChannelKind::Dm | ChannelKind::GroupDm) => {
|
||||
let own = replica.own_user();
|
||||
info.recipients
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|id| *id != own)
|
||||
.and_then(|id| replica.user(id))
|
||||
.and_then(user_uid)
|
||||
.map_or(ChatTarget::Channel(channel), ChatTarget::Private)
|
||||
}
|
||||
_ => ChatTarget::Channel(channel),
|
||||
}
|
||||
}
|
||||
|
||||
/// A message of the replica as the older model has it.
|
||||
pub(crate) fn chat_message(replica: &Replica, channel: u64, id: u64) -> Option<ChatMessage> {
|
||||
let message = replica.message(channel, id)?;
|
||||
let author = replica.user(message.author_id);
|
||||
let name = Some(message.author_name.as_str())
|
||||
.filter(|name| !name.is_empty())
|
||||
.or_else(|| author.map(|u| u.name.as_str()).filter(|name| !name.is_empty()))
|
||||
.unwrap_or_default();
|
||||
Some(ChatMessage {
|
||||
target: chat_target(replica, channel),
|
||||
author_name: name.to_owned(),
|
||||
author_uid: author.and_then(user_uid),
|
||||
author_id: (message.author_participant != 0)
|
||||
.then(|| u16::try_from(message.author_participant).ok())
|
||||
.flatten(),
|
||||
text: message.text.clone(),
|
||||
ts_ms: message.ts_ms,
|
||||
via_relay: message.flags & MessageFlag::Relayed as u32 != 0,
|
||||
blocked: false,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_ts_prefix_of_a_server_uid_goes() {
|
||||
assert_eq!(server_key("ts:abc="), "abc=");
|
||||
assert_eq!(server_key("abc="), "abc=");
|
||||
assert_eq!(server_key(""), "");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,495 @@
|
||||
//! The TeamSpeak connection's presence as v1 entities (protocol section
|
||||
//! 11.1, "Ids and entities"): the client's older model on one side, the
|
||||
//! protocol's `Server`, `Channel`, `Role`, `User`, `Member`, `Presence` and
|
||||
//! `VoiceState` on the other.
|
||||
//!
|
||||
//! [`build`] is the translation the TeamSpeak `Session` makes of every
|
||||
//! snapshot its link reports; the engine's projection (`link/project.rs`)
|
||||
//! is its reverse, and `docs/session-seam.md` section 5.1 states the rule
|
||||
//! both keep: projecting what was built gives back the snapshot (up to the
|
||||
//! normalisations of section 5.4). What v1 has no field for rides in
|
||||
//! [`Foreign`](v1::Foreign) under [`FOREIGN_SYSTEM`].
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
|
||||
use serde_json::json;
|
||||
use voelin_model::replica::Key;
|
||||
use voelin_model::{
|
||||
BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType,
|
||||
HostMessageMode, Presence, ServerDetails,
|
||||
};
|
||||
use voelin_proto::v1::{self, Entity, entity::Kind};
|
||||
|
||||
use super::ids::{self, FOREIGN_SYSTEM, SERVER_CHAT, SERVER_ID};
|
||||
|
||||
/// Entities by key, as a scope holds them.
|
||||
pub(crate) type Layer = BTreeMap<Key, Entity>;
|
||||
|
||||
/// The entities one snapshot stands for, by scope.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Built {
|
||||
/// SERVER (1): the server, its channels and its roles.
|
||||
pub server: Layer,
|
||||
/// LIVE (1): who is online and where.
|
||||
pub live: Layer,
|
||||
/// The own user, for HOME, when the snapshot holds our client.
|
||||
pub own_user: Option<v1::User>,
|
||||
/// Clients by unique id: their user id and participant id.
|
||||
pub by_uid: HashMap<String, (u64, u32)>,
|
||||
}
|
||||
|
||||
/// The `Foreign` of something v1 has no field for.
|
||||
pub(crate) fn foreign(kind: &str, json: &serde_json::Value) -> v1::Foreign {
|
||||
v1::Foreign {
|
||||
system: FOREIGN_SYSTEM.into(),
|
||||
kind: kind.into(),
|
||||
json: serde_json::to_vec(json).unwrap_or_default().into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn entity(kind: Kind) -> Entity {
|
||||
Entity { kind: Some(kind) }
|
||||
}
|
||||
|
||||
/// A picture known by its id (an icon CRC).
|
||||
fn icon(id: u32) -> Option<v1::Image> {
|
||||
(id != 0).then(|| v1::Image { hash: id.to_string(), ..Default::default() })
|
||||
}
|
||||
|
||||
fn banner_mode(mode: BannerMode) -> v1::BannerMode {
|
||||
match mode {
|
||||
BannerMode::NoAdjust => v1::BannerMode::NoAdjust,
|
||||
BannerMode::IgnoreAspect => v1::BannerMode::IgnoreAspect,
|
||||
BannerMode::KeepAspect => v1::BannerMode::KeepAspect,
|
||||
}
|
||||
}
|
||||
|
||||
fn host_message_mode(mode: HostMessageMode) -> v1::HostMessageMode {
|
||||
match mode {
|
||||
HostMessageMode::None => v1::HostMessageMode::None,
|
||||
HostMessageMode::Log => v1::HostMessageMode::Log,
|
||||
HostMessageMode::Modal => v1::HostMessageMode::Modal,
|
||||
HostMessageMode::ModalQuit => v1::HostMessageMode::ModalQuit,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `Server` entity of a connection.
|
||||
pub(crate) fn server(details: &ServerDetails, name: &str, default_channel: u64) -> v1::Server {
|
||||
let gfx =
|
||||
|url: &str| (!url.is_empty()).then(|| v1::Image { url: url.into(), ..Default::default() });
|
||||
let banner = (!details.banner_url.is_empty()
|
||||
|| !details.banner_gfx_url.is_empty()
|
||||
|| details.banner_gfx_interval_s != 0
|
||||
|| details.banner_mode != BannerMode::NoAdjust)
|
||||
.then(|| v1::Banner {
|
||||
image: gfx(&details.banner_gfx_url),
|
||||
link: details.banner_url.clone(),
|
||||
reload_s: u32::try_from(details.banner_gfx_interval_s).unwrap_or(u32::MAX),
|
||||
mode: banner_mode(details.banner_mode) as i32,
|
||||
});
|
||||
let host_button = (!details.host_button_tooltip.is_empty()
|
||||
|| !details.host_button_url.is_empty()
|
||||
|| !details.host_button_gfx_url.is_empty())
|
||||
.then(|| v1::HostButton {
|
||||
tooltip: details.host_button_tooltip.clone(),
|
||||
url: details.host_button_url.clone(),
|
||||
icon: gfx(&details.host_button_gfx_url),
|
||||
});
|
||||
v1::Server {
|
||||
id: SERVER_ID,
|
||||
name: name.to_owned(),
|
||||
icon: icon(details.icon),
|
||||
banner,
|
||||
host_button,
|
||||
welcome: details.welcome_message.clone(),
|
||||
host_message: details.host_message.clone(),
|
||||
host_message_mode: host_message_mode(details.host_message_mode) as i32,
|
||||
default_channel_id: default_channel,
|
||||
default_role_id: details.default_server_group.unwrap_or(0),
|
||||
default_channel_role_id: details.default_channel_group.map_or(0, ids::channel_role),
|
||||
priority_dim_db: details.priority_speaker_dimm_db,
|
||||
max_members: u32::from(details.max_clients),
|
||||
uid: details.uid.as_deref().map(|uid| format!("ts:{uid}")).unwrap_or_default(),
|
||||
foreign: Some(foreign(
|
||||
"server",
|
||||
&json!({ "platform": details.platform, "version": details.version }),
|
||||
)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The server group or channel group `info` as a role.
|
||||
fn role(info: &GroupInfo, channel: bool) -> v1::Role {
|
||||
v1::Role {
|
||||
id: if channel { ids::channel_role(info.id) } else { info.id },
|
||||
server_id: SERVER_ID,
|
||||
name: info.name.clone(),
|
||||
icon: icon(info.icon),
|
||||
position: info.sort_id.saturating_neg(),
|
||||
scope: if channel { v1::RoleScope::Channel } else { v1::RoleScope::Server } as i32,
|
||||
name_mode: match info.naming_mode {
|
||||
GroupNamingMode::None => v1::NameMode::None,
|
||||
GroupNamingMode::Before => v1::NameMode::Before,
|
||||
GroupNamingMode::After => v1::NameMode::After,
|
||||
} as i32,
|
||||
kind: match info.group_type {
|
||||
GroupType::Template => v1::RoleKind::Template,
|
||||
GroupType::Regular => v1::RoleKind::Regular,
|
||||
GroupType::Query => v1::RoleKind::Query,
|
||||
} as i32,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The sibling chain of each parent as positions: `order` names the sibling
|
||||
/// above, so the chain is followed from 0; siblings that no chain reaches
|
||||
/// (a snapshot with broken orders) follow by id.
|
||||
fn positions(channels: &BTreeMap<ChannelId, ChannelInfo>) -> HashMap<ChannelId, i64> {
|
||||
let mut by_parent: BTreeMap<ChannelId, Vec<&ChannelInfo>> = BTreeMap::new();
|
||||
for channel in channels.values() {
|
||||
by_parent.entry(channel.parent).or_default().push(channel);
|
||||
}
|
||||
let mut positions = HashMap::new();
|
||||
for siblings in by_parent.values() {
|
||||
let mut placed: HashSet<ChannelId> = HashSet::new();
|
||||
let mut next = 0;
|
||||
let mut above = 0;
|
||||
loop {
|
||||
// The sibling whose `order` is the one placed last (lowest id first,
|
||||
// so that two claiming the same place do not depend on map order).
|
||||
let Some(channel) = siblings
|
||||
.iter()
|
||||
.filter(|c| c.order == above && !placed.contains(&c.id))
|
||||
.min_by_key(|c| c.id)
|
||||
else {
|
||||
break;
|
||||
};
|
||||
positions.insert(channel.id, next * 1024);
|
||||
placed.insert(channel.id);
|
||||
above = channel.id;
|
||||
next += 1;
|
||||
}
|
||||
for channel in siblings.iter().filter(|c| !placed.contains(&c.id)) {
|
||||
positions.insert(channel.id, next * 1024);
|
||||
next += 1;
|
||||
}
|
||||
}
|
||||
positions
|
||||
}
|
||||
|
||||
fn channel(info: &ChannelInfo, position: i64) -> v1::Channel {
|
||||
let mut needed = HashMap::new();
|
||||
if info.needed_talk_power != 0 {
|
||||
needed.insert(v1::Power::Talk as u32, info.needed_talk_power);
|
||||
}
|
||||
if info.needed_subscribe_power != 0 {
|
||||
needed.insert(v1::Power::Subscribe as u32, info.needed_subscribe_power);
|
||||
}
|
||||
let banner =
|
||||
(info.banner_gfx_url.is_some() || info.banner_mode != BannerMode::NoAdjust).then(|| {
|
||||
v1::Banner {
|
||||
image: info
|
||||
.banner_gfx_url
|
||||
.as_ref()
|
||||
.map(|url| v1::Image { url: url.clone(), ..Default::default() }),
|
||||
mode: banner_mode(info.banner_mode) as i32,
|
||||
..Default::default()
|
||||
}
|
||||
});
|
||||
v1::Channel {
|
||||
id: info.id,
|
||||
server_id: SERVER_ID,
|
||||
parent_id: info.parent,
|
||||
kind: v1::ChannelKind::Voice as i32,
|
||||
name: info.name.clone(),
|
||||
topic: info.topic.clone().unwrap_or_default(),
|
||||
position,
|
||||
has_password: info.has_password,
|
||||
// A limit of 0 cannot be said with `max_members` (0 is unlimited).
|
||||
max_members: info.max_clients.map_or(0, |n| u32::try_from(n).unwrap_or(0)),
|
||||
needed,
|
||||
icon: icon(info.icon),
|
||||
banner,
|
||||
is_default: info.is_default,
|
||||
foreign: (info.max_clients == Some(0))
|
||||
.then(|| foreign("channel", &json!({ "max_clients": 0 }))),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The user a client is. `Foreign` carries a unique id that is no base64.
|
||||
fn user(client: &ClientInfo, id: u64, ts6: bool) -> v1::User {
|
||||
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
|
||||
let bytes = uid.and_then(ids::uid_bytes);
|
||||
let avatar = (client.avatar.is_some() || client.myts_avatar.is_some()).then(|| v1::Image {
|
||||
hash: client.avatar.clone().unwrap_or_default(),
|
||||
url: client.myts_avatar.clone().unwrap_or_default(),
|
||||
..Default::default()
|
||||
});
|
||||
v1::User {
|
||||
id,
|
||||
uid: bytes.clone().unwrap_or_default().into(),
|
||||
uid_kind: if ts6 { v1::IdKind::Ts6 } else { v1::IdKind::Ts3 } as i32,
|
||||
name: client.nickname.clone(),
|
||||
avatar,
|
||||
badges: client.badges.clone(),
|
||||
country: client.country.clone().unwrap_or_default(),
|
||||
foreign: uid.filter(|_| bytes.is_none()).map(|uid| foreign("user", &json!({ "uid": uid }))),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A user who is on no snapshot (the sender of a message or a poke): its
|
||||
/// unique id and name only. `None` for a unique id with no content.
|
||||
pub(crate) fn bare_user(uid: &str, name: &str, ts6: bool) -> v1::User {
|
||||
user(
|
||||
&ClientInfo { uid: Some(uid.to_owned()), nickname: name.to_owned(), ..Default::default() },
|
||||
ids::synthetic_user(uid),
|
||||
ts6,
|
||||
)
|
||||
}
|
||||
|
||||
/// Everything the snapshot `presence` says, as entities of the scopes of
|
||||
/// server 1. `ts6`: the server is TeamSpeak 6 (the kind of its unique ids).
|
||||
pub(crate) fn build(presence: &Presence, ts6: bool, own_client: Option<u16>) -> Built {
|
||||
let mut built = Built::default();
|
||||
let name =
|
||||
if presence.server.name.is_empty() { &presence.server_name } else { &presence.server.name };
|
||||
let default_channel =
|
||||
presence.channels.values().find(|c| c.is_default).map_or(0, |channel| channel.id);
|
||||
let put = |layer: &mut Layer, kind: Kind| {
|
||||
let entity = entity(kind);
|
||||
if let Some(key) = Key::of(&entity) {
|
||||
layer.insert(key, entity);
|
||||
}
|
||||
};
|
||||
put(&mut built.server, Kind::Server(server(&presence.server, name, default_channel)));
|
||||
put(
|
||||
&mut built.server,
|
||||
Kind::Channel(v1::Channel {
|
||||
id: SERVER_CHAT,
|
||||
server_id: SERVER_ID,
|
||||
kind: v1::ChannelKind::ServerChat as i32,
|
||||
name: "Server chat".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
let positions = positions(&presence.channels);
|
||||
for info in presence.channels.values() {
|
||||
let position = positions.get(&info.id).copied().unwrap_or_default();
|
||||
put(&mut built.server, Kind::Channel(channel(info, position)));
|
||||
}
|
||||
for info in presence.server_groups.values() {
|
||||
put(&mut built.server, Kind::Role(role(info, false)));
|
||||
}
|
||||
for info in presence.channel_groups.values() {
|
||||
put(&mut built.server, Kind::Role(role(info, true)));
|
||||
}
|
||||
let mut used: HashSet<u64> = HashSet::new();
|
||||
for client in presence.clients.values() {
|
||||
// The same identity twice on a server has one database id: the lower
|
||||
// client id keeps it, the other is a user of its own.
|
||||
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
|
||||
let mut id = client.database_id.unwrap_or_else(|| {
|
||||
ids::synthetic_user(&uid.map_or_else(|| format!("client:{}", client.id), str::to_owned))
|
||||
});
|
||||
if !used.insert(id) {
|
||||
id = ids::synthetic_user(&format!("client:{}", client.id));
|
||||
used.insert(id);
|
||||
}
|
||||
let participant = u32::from(client.id);
|
||||
if let Some(uid) = uid {
|
||||
built.by_uid.entry(uid.to_owned()).or_insert((id, participant));
|
||||
}
|
||||
let user = user(client, id, ts6);
|
||||
if Some(client.id) == own_client {
|
||||
built.own_user = Some(user.clone());
|
||||
}
|
||||
put(&mut built.live, Kind::User(user));
|
||||
put(
|
||||
&mut built.live,
|
||||
Kind::Member(v1::Member {
|
||||
server_id: SERVER_ID,
|
||||
user_id: id,
|
||||
roles: client.server_groups.clone(),
|
||||
channel_roles: client
|
||||
.channel_group
|
||||
.map(|group| (client.channel, ids::channel_role(group)))
|
||||
.into_iter()
|
||||
.collect(),
|
||||
description: client.description.clone().unwrap_or_default(),
|
||||
foreign: (client.icon != 0)
|
||||
.then(|| foreign("client", &json!({ "icon": client.icon }))),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&mut built.live,
|
||||
Kind::Presence(v1::Presence {
|
||||
user_id: id,
|
||||
status: if client.away.is_some() { v1::Status::Idle } else { v1::Status::Online }
|
||||
as i32,
|
||||
text: client.away.clone().unwrap_or_default(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&mut built.live,
|
||||
Kind::Voice(v1::VoiceState {
|
||||
server_id: SERVER_ID,
|
||||
participant_id: participant,
|
||||
user_id: id,
|
||||
channel_id: client.channel,
|
||||
slot: slot(client.id),
|
||||
nick: client.nickname.clone(),
|
||||
kind: if client.is_query {
|
||||
v1::ParticipantKind::Query
|
||||
} else {
|
||||
v1::ParticipantKind::User
|
||||
} as i32,
|
||||
self_mute: client.input_muted,
|
||||
self_deaf: client.output_muted,
|
||||
priority_speaker: client.priority_speaker,
|
||||
channel_commander: client.channel_commander,
|
||||
talker: client.talker,
|
||||
talk_power: client.talk_power,
|
||||
recording: client.recording,
|
||||
streaming: client.streaming.unwrap_or(false),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
}
|
||||
built
|
||||
}
|
||||
|
||||
/// The unique id of a user as the client's older model writes it: base64 for
|
||||
/// a TeamSpeak id, or the text kept in `Foreign` when it was no base64 (a
|
||||
/// ServerQuery client's login name). `None` for a user without one.
|
||||
pub(crate) fn user_uid(user: &v1::User) -> Option<String> {
|
||||
let kept = user
|
||||
.foreign
|
||||
.as_ref()
|
||||
.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == "user")
|
||||
.and_then(|f| serde_json::from_slice::<serde_json::Value>(&f.json).ok())
|
||||
.and_then(|json| json.get("uid")?.as_str().map(str::to_owned));
|
||||
kept.or_else(|| voelin_model::replica::convert::uid_text(user))
|
||||
}
|
||||
|
||||
/// The media slot of a client: its id plus one (slot 0 is not a media source).
|
||||
pub(crate) fn slot(client: u16) -> u32 {
|
||||
u32::from(client) + 1
|
||||
}
|
||||
|
||||
/// The key of an entity, as a `Change` deletes it: the key fields only.
|
||||
pub(crate) fn key_only(entity: &Entity) -> Entity {
|
||||
let kind = match entity.kind.as_ref() {
|
||||
Some(Kind::Server(s)) => Kind::Server(v1::Server { id: s.id, ..Default::default() }),
|
||||
Some(Kind::Channel(c)) => Kind::Channel(v1::Channel { id: c.id, ..Default::default() }),
|
||||
Some(Kind::Role(r)) => {
|
||||
Kind::Role(v1::Role { server_id: r.server_id, id: r.id, ..Default::default() })
|
||||
}
|
||||
Some(Kind::Member(m)) => Kind::Member(v1::Member {
|
||||
server_id: m.server_id,
|
||||
user_id: m.user_id,
|
||||
..Default::default()
|
||||
}),
|
||||
Some(Kind::User(u)) => Kind::User(v1::User { id: u.id, ..Default::default() }),
|
||||
Some(Kind::Presence(p)) => {
|
||||
Kind::Presence(v1::Presence { user_id: p.user_id, ..Default::default() })
|
||||
}
|
||||
Some(Kind::Voice(v)) => Kind::Voice(v1::VoiceState {
|
||||
server_id: v.server_id,
|
||||
participant_id: v.participant_id,
|
||||
..Default::default()
|
||||
}),
|
||||
Some(Kind::Message(m)) => {
|
||||
Kind::Message(v1::Message { channel_id: m.channel_id, id: m.id, ..Default::default() })
|
||||
}
|
||||
Some(Kind::Mail(m)) => Kind::Mail(v1::Mail { id: m.id, ..Default::default() }),
|
||||
_ => return entity.clone(),
|
||||
};
|
||||
Entity { kind: Some(kind) }
|
||||
}
|
||||
|
||||
/// What changed from `old` to `new`: the entities to put (new or different)
|
||||
/// and the keys to delete.
|
||||
pub(crate) fn diff(old: &Layer, new: &Layer) -> (Vec<Entity>, Vec<Entity>) {
|
||||
let put = new.iter().filter(|(key, entity)| old.get(*key) != Some(*entity));
|
||||
let del = old.iter().filter(|(key, _)| !new.contains_key(*key));
|
||||
(put.map(|(_, e)| e.clone()).collect(), del.map(|(_, e)| key_only(e)).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn channel_info(id: u64, parent: u64, order: u64) -> ChannelInfo {
|
||||
ChannelInfo { id, parent, order, name: format!("c{id}"), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_order_chain_becomes_positions() {
|
||||
// 3 first, then 1, then 2 under the same parent; 5 alone under 3.
|
||||
let channels: BTreeMap<_, _> = [
|
||||
channel_info(1, 0, 3),
|
||||
channel_info(2, 0, 1),
|
||||
channel_info(3, 0, 0),
|
||||
channel_info(5, 3, 0),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|c| (c.id, c))
|
||||
.collect();
|
||||
let positions = positions(&channels);
|
||||
assert!(positions[&3] < positions[&1] && positions[&1] < positions[&2]);
|
||||
assert_eq!(positions[&5], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn siblings_a_chain_does_not_reach_follow_by_id() {
|
||||
// Both claim the first place, and 4 follows nobody.
|
||||
let channels: BTreeMap<_, _> =
|
||||
[channel_info(1, 0, 0), channel_info(2, 0, 0), channel_info(4, 0, 77)]
|
||||
.into_iter()
|
||||
.map(|c| (c.id, c))
|
||||
.collect();
|
||||
let positions = positions(&channels);
|
||||
assert_eq!((positions[&1], positions[&2], positions[&4]), (0, 1024, 2048));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_identity_twice_keeps_both_clients() {
|
||||
let client = |id, db| ClientInfo {
|
||||
id,
|
||||
uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()),
|
||||
nickname: format!("n{id}"),
|
||||
database_id: Some(db),
|
||||
..Default::default()
|
||||
};
|
||||
let mut presence = Presence::default();
|
||||
for c in [client(3, 77), client(4, 77)] {
|
||||
presence.clients.insert(c.id, c);
|
||||
}
|
||||
let built = build(&presence, false, None);
|
||||
let voices = built.live.keys().filter(|k| matches!(k, Key::Voice { .. })).count();
|
||||
let users = built.live.keys().filter(|k| matches!(k, Key::User { .. })).count();
|
||||
assert_eq!((voices, users), (2, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_deletes_by_key_and_puts_what_differs() {
|
||||
let mut presence = Presence::default();
|
||||
presence.channels.insert(1, channel_info(1, 0, 0));
|
||||
let before = build(&presence, false, None);
|
||||
presence.channels.insert(2, channel_info(2, 0, 1));
|
||||
presence.channels.get_mut(&1).unwrap().name = "renamed".into();
|
||||
let after = build(&presence, false, None);
|
||||
let (put, del) = diff(&before.server, &after.server);
|
||||
assert_eq!(put.len(), 2, "the renamed channel and the new one");
|
||||
assert!(del.is_empty());
|
||||
let (put, del) = diff(&after.server, &before.server);
|
||||
assert_eq!(put.len(), 1, "channel 1 is back to its old name");
|
||||
assert_eq!(del.len(), 1);
|
||||
let Some(Kind::Channel(gone)) = &del[0].kind else { panic!("a channel") };
|
||||
assert_eq!((gone.id, gone.name.as_str()), (2, ""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! Ids and unique ids as the TeamSpeak gateway writes them (protocol
|
||||
//! section 11.1, "Ids"): TeamSpeak's numbers as they are, and a few
|
||||
//! synthetic ones with bit 63 set.
|
||||
//!
|
||||
//! Both sides of the seam use these rules: the TeamSpeak `Session`
|
||||
//! ([`super::LinkSession`]) writes entities with them, and the engine's
|
||||
//! projection (`link/project.rs`) undoes the few that the client's older
|
||||
//! model has no room for.
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
|
||||
/// The only server of a TeamSpeak connection (its virtual server).
|
||||
pub(crate) const SERVER_ID: u64 = 1;
|
||||
|
||||
/// Marks the ids the gateway makes up: the server chat, direct-message
|
||||
/// channels and users it knows by their unique id only.
|
||||
pub(crate) const SYNTHETIC: u64 = 1 << 63;
|
||||
|
||||
/// The channel of the server chat, in the SERVER scope.
|
||||
pub(crate) const SERVER_CHAT: u64 = SYNTHETIC;
|
||||
|
||||
/// Set on the id of a channel group, so that a role id does not mean a server
|
||||
/// group and a channel group at once.
|
||||
pub(crate) const CHANNEL_ROLE: u64 = 1 << 62;
|
||||
|
||||
/// The `Foreign.system` of what the protocol has no field for.
|
||||
pub(crate) const FOREIGN_SYSTEM: &str = "teamspeak";
|
||||
|
||||
/// The role id of a channel group.
|
||||
pub(crate) fn channel_role(group: u64) -> u64 {
|
||||
group | CHANNEL_ROLE
|
||||
}
|
||||
|
||||
/// The channel group a role id stands for (the reverse of [`channel_role`]).
|
||||
pub(crate) fn channel_group(role: u64) -> u64 {
|
||||
role & !CHANNEL_ROLE
|
||||
}
|
||||
|
||||
/// FNV-1a, 64 bits.
|
||||
fn fnv1a(bytes: &[u8]) -> u64 {
|
||||
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for byte in bytes {
|
||||
hash ^= u64::from(*byte);
|
||||
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
hash
|
||||
}
|
||||
|
||||
/// A synthetic id for something known by a name only: bit 63 set and the
|
||||
/// hash of `name` in the low 63 bits (1 if they come out 0, so it is never
|
||||
/// [`SERVER_CHAT`]).
|
||||
fn synthetic(name: &str) -> u64 {
|
||||
let low = fnv1a(name.as_bytes()) & !SYNTHETIC;
|
||||
SYNTHETIC | low.max(1)
|
||||
}
|
||||
|
||||
/// The direct-message channel with the client of this unique id.
|
||||
pub(crate) fn dm_channel(uid: &str) -> u64 {
|
||||
synthetic(uid)
|
||||
}
|
||||
|
||||
/// The user id of a client that has no database id (or that the snapshot
|
||||
/// does not hold): by unique id, else by whatever names it.
|
||||
pub(crate) fn synthetic_user(uid: &str) -> u64 {
|
||||
synthetic(uid)
|
||||
}
|
||||
|
||||
/// The bytes of a unique id, when it is canonical base64 (what TeamSpeak
|
||||
/// writes): decoding and encoding again gives the same text. A ServerQuery
|
||||
/// client's login name, or anything else, is not, and goes into
|
||||
/// [`Foreign`](voelin_proto::v1::Foreign) instead.
|
||||
pub(crate) fn uid_bytes(uid: &str) -> Option<Vec<u8>> {
|
||||
let bytes = STANDARD.decode(uid).ok()?;
|
||||
(STANDARD.encode(&bytes) == uid && !bytes.is_empty()).then_some(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn channel_groups_keep_their_number_below_the_flag() {
|
||||
assert_eq!(channel_role(8), 8 | (1 << 62));
|
||||
assert_eq!(channel_group(channel_role(8)), 8);
|
||||
assert_eq!(channel_group(channel_role(0)), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_ids_have_bit_63_and_are_never_the_server_chat() {
|
||||
for name in ["", "alice=", "client:7", "a-very-long-name-that-hashes-to-something"] {
|
||||
let id = dm_channel(name);
|
||||
assert_ne!(id & SYNTHETIC, 0, "{name}");
|
||||
assert_ne!(id, SERVER_CHAT, "{name}");
|
||||
}
|
||||
assert_eq!(dm_channel("alice="), dm_channel("alice="));
|
||||
assert_ne!(dm_channel("alice="), dm_channel("bob="));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_canonical_base64_is_a_unique_id() {
|
||||
// A TeamSpeak 3 unique id (SHA-1) and a TeamSpeak 6 one (SHA-256).
|
||||
assert_eq!(uid_bytes("uXDkxSZbv0IoA0z/toW3guGpUbI=").map(|b| b.len()), Some(20));
|
||||
assert_eq!(
|
||||
uid_bytes("xEZDkyeGdZ4bOSBCKqzTw8jVz2jsZCrJDRl9F8WWd3M=").map(|b| b.len()),
|
||||
Some(32)
|
||||
);
|
||||
// A ServerQuery login name, a fixture's name, the empty string.
|
||||
for not in ["serveradmin", "alice=", "me=", "", "Af4"] {
|
||||
assert_eq!(uid_bytes(not), None, "{not:?}");
|
||||
}
|
||||
// Non-canonical trailing bits decode but do not round trip.
|
||||
assert_eq!(uid_bytes("Af5="), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! Voice across the seam, TeamSpeak side (`docs/session-seam.md` section
|
||||
//! 6.2): TeamSpeak's Opus packets as RTP on the talker's slot, and RTP on our
|
||||
//! own slot as TeamSpeak's `EncodedVoice`. Nothing is transcoded
|
||||
//! (protocol section 1.2): the Opus payload is the same bytes both ways.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::BytesMut;
|
||||
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
|
||||
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::opus::{self, Toc};
|
||||
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, OPUS_CLOCK_RATE, PT_OPUS};
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
|
||||
use super::entities::slot;
|
||||
|
||||
/// Silence this long between two packets of a talker starts a new talk spurt
|
||||
/// (the marker bit is set on the first packet of it).
|
||||
const SPURT_GAP: Duration = Duration::from_millis(250);
|
||||
|
||||
/// What is kept of the last packet of a talker.
|
||||
struct Talker {
|
||||
timestamp: u32,
|
||||
sequence: u16,
|
||||
at: Instant,
|
||||
/// The 48 kHz ticks the last packet spans.
|
||||
ticks: u32,
|
||||
/// The last packet ended the spurt.
|
||||
ended: bool,
|
||||
}
|
||||
|
||||
/// Wraps what a TeamSpeak connection receives into RTP.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Downlink {
|
||||
talkers: HashMap<u16, Talker>,
|
||||
}
|
||||
|
||||
impl Downlink {
|
||||
/// `packet` as the RTP packet of its talker's slot. The sequence number is
|
||||
/// TeamSpeak's packet id (both 16 bits); the timestamp advances by each
|
||||
/// packet's duration (its Opus table-of-contents byte) on the packet id's
|
||||
/// counter, so it never goes back when the id wraps, and by wall-clock time
|
||||
/// across silences, so a silence is not compressed. The marker is set on
|
||||
/// the first packet after an end or a gap, and an end is an empty payload.
|
||||
pub(super) fn wrap(&mut self, packet: &VoicePacket, now: Instant) -> Option<MediaPacket> {
|
||||
let id = packet.talker.0;
|
||||
let sub = if packet.whisper { voice_sub::FIRST_TALK_TARGET } else { voice_sub::CHANNEL };
|
||||
let flow = FlowId::new(slot(id), sub);
|
||||
let end = packet.is_end();
|
||||
let (timestamp, marker) = match self.talkers.get(&id) {
|
||||
None => (0, !end),
|
||||
Some(last) => {
|
||||
let gap = now.saturating_duration_since(last.at);
|
||||
if last.ended || gap > SPURT_GAP {
|
||||
// A new spurt: the time that passed since the last packet.
|
||||
let wall = (gap.as_micros() * u128::from(OPUS_CLOCK_RATE) / 1_000_000) as u32;
|
||||
(last.timestamp.wrapping_add(last.ticks.max(wall)), !end)
|
||||
} else {
|
||||
let ahead = packet.seq.wrapping_sub(last.sequence);
|
||||
if ahead == 0 || ahead >= 0x8000 {
|
||||
// A duplicate or a late packet: where it belongs, and the
|
||||
// state keeps what the latest packet said.
|
||||
let back = u32::from(last.sequence.wrapping_sub(packet.seq));
|
||||
let at = last.timestamp.wrapping_sub(back * last.ticks);
|
||||
return self.finish(flow, packet, at, false);
|
||||
}
|
||||
(last.timestamp.wrapping_add(u32::from(ahead) * last.ticks), false)
|
||||
}
|
||||
}
|
||||
};
|
||||
let ticks =
|
||||
if end { 0 } else { opus::packet_ticks(&packet.payload).unwrap_or(OPUS_20_MS_TICKS) };
|
||||
self.talkers
|
||||
.insert(id, Talker { timestamp, sequence: packet.seq, at: now, ticks, ended: end });
|
||||
self.finish(flow, packet, timestamp, marker)
|
||||
}
|
||||
|
||||
fn finish(
|
||||
&self,
|
||||
flow: FlowId,
|
||||
packet: &VoicePacket,
|
||||
timestamp: u32,
|
||||
marker: bool,
|
||||
) -> Option<MediaPacket> {
|
||||
let mut header = RtpHeader::new(PT_OPUS, packet.seq, timestamp);
|
||||
header.marker = marker;
|
||||
// An end is an empty payload, also where the server sent one byte.
|
||||
let payload = if packet.is_end() { &[][..] } else { &packet.payload[..] };
|
||||
let mut out = BytesMut::with_capacity(header.encoded_len() + payload.len());
|
||||
header.write(flow, &mut out).ok()?;
|
||||
out.extend_from_slice(payload);
|
||||
Some(MediaPacket { flow, rtp: out.freeze() })
|
||||
}
|
||||
|
||||
/// Forget a talker (it left the server).
|
||||
pub(super) fn forget(&mut self, client: u16) {
|
||||
self.talkers.remove(&client);
|
||||
}
|
||||
}
|
||||
|
||||
/// The voice a media packet of our own slot carries, for TeamSpeak: its
|
||||
/// payload, and `Music` when the Opus packet is stereo. `None` for a packet
|
||||
/// that is no RTP.
|
||||
pub(super) fn uplink(packet: &MediaPacket) -> Option<EncodedVoice> {
|
||||
let view = RtpView::parse(&packet.rtp).ok()?;
|
||||
let payload = view.payload();
|
||||
let codec = match Toc::parse(payload) {
|
||||
Ok(toc) if toc.stereo() => VoiceCodec::Music,
|
||||
_ => VoiceCodec::Voice,
|
||||
};
|
||||
Some(EncodedVoice { codec, payload: payload.to_vec() })
|
||||
}
|
||||
|
||||
/// An RTP packet of voice, for tests of both sides.
|
||||
#[cfg(test)]
|
||||
pub(super) fn rtp_packet(
|
||||
flow: FlowId,
|
||||
sequence: u16,
|
||||
timestamp: u32,
|
||||
marker: bool,
|
||||
payload: &[u8],
|
||||
) -> bytes::Bytes {
|
||||
let mut header = RtpHeader::new(PT_OPUS, sequence, timestamp);
|
||||
header.marker = marker;
|
||||
let mut out = BytesMut::new();
|
||||
header.write(flow, &mut out).unwrap();
|
||||
out.extend_from_slice(payload);
|
||||
out.freeze()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use bytes::Bytes;
|
||||
use voelin_audio::TalkerId;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn voice(talker: u16, seq: u16, payload: &[u8], whisper: bool) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: TalkerId(talker),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper,
|
||||
payload: payload.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
/// An Opus packet of 20 ms in a CELT-only frame (config 16 is 2.5 ms; 19
|
||||
/// is 20 ms), mono, one frame.
|
||||
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
|
||||
|
||||
fn view(packet: &MediaPacket) -> RtpView<'_> {
|
||||
RtpView::parse(&packet.rtp).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spurt_is_sequenced_by_the_packet_id_with_a_marker_on_its_first_packet() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
let first = down.wrap(&voice(7, 65_534, &OPUS_20_MS, false), t0).unwrap();
|
||||
let v = view(&first);
|
||||
assert!(v.marker());
|
||||
assert_eq!((v.ssrc(), first.flow), (FlowId::new(8, 0).0, FlowId::new(8, 0)));
|
||||
assert_eq!((v.sequence(), v.timestamp()), (65_534, 0));
|
||||
// The id wraps; the timestamp keeps counting.
|
||||
let t1 = t0 + Duration::from_millis(20);
|
||||
let second = down.wrap(&voice(7, 65_535, &OPUS_20_MS, false), t1).unwrap();
|
||||
let third =
|
||||
down.wrap(&voice(7, 0, &OPUS_20_MS, false), t1 + Duration::from_millis(20)).unwrap();
|
||||
assert!(!view(&second).marker() && !view(&third).marker());
|
||||
assert_eq!(view(&second).timestamp(), OPUS_20_MS_TICKS);
|
||||
assert_eq!((view(&third).sequence(), view(&third).timestamp()), (0, 2 * OPUS_20_MS_TICKS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_is_an_empty_payload_and_the_next_packet_has_a_marker() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
|
||||
let end = down.wrap(&voice(7, 2, &[], false), t0 + Duration::from_millis(20)).unwrap();
|
||||
assert!(view(&end).payload().is_empty() && !view(&end).marker());
|
||||
// TeamSpeak's single byte after a talk is an end too.
|
||||
let mut down = Downlink::default();
|
||||
down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
|
||||
let end = down.wrap(&voice(7, 2, &[0], false), t0 + Duration::from_millis(20)).unwrap();
|
||||
assert!(view(&end).payload().is_empty());
|
||||
let next =
|
||||
down.wrap(&voice(7, 3, &OPUS_20_MS, false), t0 + Duration::from_millis(60)).unwrap();
|
||||
assert!(view(&next).marker());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_silence_is_not_compressed() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
let first = down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
|
||||
let again =
|
||||
down.wrap(&voice(7, 2, &OPUS_20_MS, false), t0 + Duration::from_secs(2)).unwrap();
|
||||
assert!(view(&again).marker(), "a gap starts a spurt");
|
||||
// Two seconds of wall-clock time are 96,000 ticks of the 48 kHz clock.
|
||||
assert_eq!(view(&again).timestamp() - view(&first).timestamp(), 96_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whispers_ride_sub_flow_1_and_talkers_have_slots_of_their_own() {
|
||||
let mut down = Downlink::default();
|
||||
let now = Instant::now();
|
||||
let whisper = down.wrap(&voice(300, 1, &OPUS_20_MS, true), now).unwrap();
|
||||
assert_eq!((whisper.flow.slot(), whisper.flow.sub()), (301, 1));
|
||||
let channel = down.wrap(&voice(300, 2, &OPUS_20_MS, false), now).unwrap();
|
||||
assert_eq!((channel.flow.slot(), channel.flow.sub()), (301, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_packet_that_is_not_in_order_keeps_the_state_of_the_latest() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0).unwrap();
|
||||
down.wrap(&voice(7, 11, &OPUS_20_MS, false), t0 + Duration::from_millis(20)).unwrap();
|
||||
let late =
|
||||
down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0 + Duration::from_millis(25)).unwrap();
|
||||
assert_eq!(view(&late).timestamp(), 0, "where packet 10 belongs");
|
||||
let next =
|
||||
down.wrap(&voice(7, 12, &OPUS_20_MS, false), t0 + Duration::from_millis(40)).unwrap();
|
||||
assert_eq!(view(&next).timestamp(), 2 * OPUS_20_MS_TICKS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn our_voice_loses_its_header_and_stereo_is_music() {
|
||||
let flow = FlowId::new(8, 0);
|
||||
let mono = MediaPacket { flow, rtp: rtp_packet(flow, 0, 0, true, &OPUS_20_MS) };
|
||||
let voice = uplink(&mono).unwrap();
|
||||
assert_eq!((voice.codec, voice.payload.as_slice()), (VoiceCodec::Voice, &OPUS_20_MS[..]));
|
||||
// The same TOC with the stereo bit.
|
||||
let stereo_toc = [OPUS_20_MS[0] | 0x04, 1, 2];
|
||||
let stereo = MediaPacket { flow, rtp: rtp_packet(flow, 1, 960, false, &stereo_toc) };
|
||||
assert_eq!(uplink(&stereo).unwrap().codec, VoiceCodec::Music);
|
||||
// The end of a spurt: an empty payload.
|
||||
let end = MediaPacket { flow, rtp: rtp_packet(flow, 2, 1920, false, &[]) };
|
||||
assert!(uplink(&end).unwrap().is_end());
|
||||
// Not RTP.
|
||||
assert!(uplink(&MediaPacket { flow, rtp: Bytes::from_static(&[1, 2, 3]) }).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,769 @@
|
||||
//! A TeamSpeak connection as a `voelin_proto::link::Session`
|
||||
//! (`docs/session-seam.md`, "the TeamSpeak side").
|
||||
//!
|
||||
//! [`LinkSession`] is a `Session` over any [`ServerLink`](crate::link::ServerLink):
|
||||
//! it turns the link's `LinkCmd`s and `LinkEvent`s (the client's older,
|
||||
//! TeamSpeak-shaped vocabulary) into v1 entities, pushes and answers. With
|
||||
//! `TsLink` inside it is the in-process TeamSpeak `Session`; with a fake link
|
||||
//! inside it is what the link tests of the engine run through. [`TsConnector`]
|
||||
//! is the `Connector` that makes them for `ts3server://` and `teamspeak://`
|
||||
//! addresses.
|
||||
//!
|
||||
//! This module and the files it is made of are TeamSpeak's: they keep the
|
||||
//! TeamSpeak types (`tsclientlib`'s identity and client version) in
|
||||
//! [`connect_params`] and [`TsConnector`], and everything else is v1 and the
|
||||
//! client's own model. In the second half of the decoupling plan they move,
|
||||
//! with `TsLink`, to the TeamSpeak gateway (`voelin-gateway-ts` of
|
||||
//! VoelinGateWay).
|
||||
|
||||
mod driver;
|
||||
pub(crate) mod entities;
|
||||
pub(crate) mod ids;
|
||||
mod media;
|
||||
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use bytes::Bytes;
|
||||
use tokio::io::{AsyncReadExt, AsyncWrite};
|
||||
use tokio::sync::{broadcast, mpsc, oneshot, watch};
|
||||
use voelin_model::{Link, ServerDetails};
|
||||
use voelin_proto::link::{
|
||||
BoxFuture, CloseReason, ConnectParams, Connected, Connector, Credential, Download, Features,
|
||||
IssuerTrust, LinkStats, MAX_RTP, MediaClass, MediaError, MediaPacket, MediaSink, Placement,
|
||||
Sent, Session, SessionError, Upload, placement, voice_sub,
|
||||
};
|
||||
use voelin_proto::v1::{self, response::Result as Answer};
|
||||
|
||||
use self::driver::{Cmd, Config, Driver, Parts, rejected};
|
||||
use crate::link::{
|
||||
Backends, BoxDuplex, ConnectOptions, LinkCmd, LinkCtx, LinkEvent, LocalConnected,
|
||||
LocalConnector, LocalCtx, ServerLink, StreamPort,
|
||||
};
|
||||
use crate::{BackendInfo, TsLink};
|
||||
|
||||
/// The `Credential::Foreign` kind of a stored TeamSpeak identity.
|
||||
const IDENTITY_KIND: &str = "teamspeak";
|
||||
/// The link parameter that carries the client version to impersonate: the
|
||||
/// JSON of `tsclientlib::Version`, in unpadded URL-safe base64.
|
||||
const VERSION_PARAM: &str = "client_version";
|
||||
/// How long the link may take to report its first snapshot after it said it
|
||||
/// is connected; the snapshot gives the `Welcome` its own user.
|
||||
const FIRST_SNAPSHOT: Duration = Duration::from_millis(250);
|
||||
|
||||
static SESSIONS: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
fn now_ms() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as i64)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
// ---- what the engine hands a connector ------------------------------------
|
||||
|
||||
/// The connect parameters of a TeamSpeak connection, from the options the
|
||||
/// session was asked to connect with (`docs/session-seam.md` section 4.2).
|
||||
///
|
||||
/// The address is the `ts3server://` link of the bookmark (the channel and
|
||||
/// its password ride in it, and so does the client version to claim, until
|
||||
/// v1 has fields for them), the server password is `Hello.password` and the
|
||||
/// privilege key `Hello.invite_code`. The identity goes as
|
||||
/// `Credential::Foreign`; no account is used yet.
|
||||
pub(crate) fn connect_params(
|
||||
options: &ConnectOptions,
|
||||
media: Arc<dyn MediaSink>,
|
||||
backends: &Backends,
|
||||
) -> ConnectParams {
|
||||
let credential = Credential::Foreign {
|
||||
kind: IDENTITY_KIND,
|
||||
blob: options
|
||||
.identity
|
||||
.as_ref()
|
||||
.and_then(|identity| serde_json::to_vec(identity).ok())
|
||||
.map(Bytes::from)
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
let hello = v1::Hello {
|
||||
version: 1,
|
||||
client: Some(v1::ClientInfo {
|
||||
name: "Voelin".into(),
|
||||
version: voelin_platform::crash::app_version().to_owned(),
|
||||
platform: std::env::consts::OS.into(),
|
||||
kind: v1::ClientKind::User as i32,
|
||||
}),
|
||||
nickname: options.nickname.clone(),
|
||||
password: options.server_password.clone().unwrap_or_default(),
|
||||
invite_code: options.token.clone().unwrap_or_default(),
|
||||
..Default::default()
|
||||
};
|
||||
ConnectParams {
|
||||
address: address_link(options),
|
||||
credential,
|
||||
linked: Vec::new(),
|
||||
account: backends.account(),
|
||||
issuer_trust: IssuerTrust::Unknown,
|
||||
hello,
|
||||
host_pin: None,
|
||||
trust: backends.trust(),
|
||||
media,
|
||||
push_capacity: 1024,
|
||||
timeout: Duration::from_secs(35),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `ts3server://` link of the options' address, with the channel to join
|
||||
/// and the client version to claim.
|
||||
fn address_link(options: &ConnectOptions) -> String {
|
||||
let mut link = match Link::parse(&options.address) {
|
||||
Some(Link::Server(link)) => link,
|
||||
// Not a TeamSpeak link, or none: a bookmark's `host[:port]`.
|
||||
_ if !options.address.contains("://") => voelin_model::ServerLink::new(&options.address),
|
||||
// Some other scheme: as given, for the connector of that scheme.
|
||||
_ => return options.address.clone(),
|
||||
};
|
||||
link.channel = options.channel.clone().filter(|c| !c.is_empty()).or(link.channel);
|
||||
link.channel_password =
|
||||
options.channel_password.clone().filter(|p| !p.is_empty()).or(link.channel_password);
|
||||
let mut url = link.to_url();
|
||||
if let Some(version) = options.client_version.as_ref().and_then(|v| serde_json::to_vec(v).ok())
|
||||
{
|
||||
url.push(if url.contains('?') { '&' } else { '?' });
|
||||
url.push_str(VERSION_PARAM);
|
||||
url.push('=');
|
||||
url.push_str(&URL_SAFE_NO_PAD.encode(version));
|
||||
}
|
||||
url
|
||||
}
|
||||
|
||||
/// The options a TeamSpeak link is connected with: the reverse of
|
||||
/// [`connect_params`].
|
||||
fn inner_options(params: &ConnectParams, ctx: &LocalCtx) -> Result<ConnectOptions, SessionError> {
|
||||
let link = match Link::parse(¶ms.address) {
|
||||
Some(Link::Server(link)) => link,
|
||||
_ => {
|
||||
return Err(SessionError::Protocol(format!(
|
||||
"not a TeamSpeak server address: {}",
|
||||
params.address
|
||||
)));
|
||||
}
|
||||
};
|
||||
let identity = match ¶ms.credential {
|
||||
Credential::Foreign { kind: IDENTITY_KIND, blob } if blob.is_empty() => None,
|
||||
Credential::Foreign { kind: IDENTITY_KIND, blob } => {
|
||||
Some(serde_json::from_slice(blob).map_err(|e| {
|
||||
SessionError::Protocol(format!("the TeamSpeak identity cannot be read: {e}"))
|
||||
})?)
|
||||
}
|
||||
_ => {
|
||||
return Err(SessionError::Protocol(
|
||||
"a TeamSpeak server needs a TeamSpeak identity".into(),
|
||||
));
|
||||
}
|
||||
};
|
||||
let client_version = params
|
||||
.address
|
||||
.split_once('?')
|
||||
.and_then(|(_, query)| {
|
||||
query.split('&').find_map(|pair| pair.strip_prefix(&format!("{VERSION_PARAM}=")))
|
||||
})
|
||||
.and_then(|text| URL_SAFE_NO_PAD.decode(text).ok())
|
||||
.and_then(|json| serde_json::from_slice(&json).ok());
|
||||
let nonempty = |text: &str| (!text.is_empty()).then(|| text.to_owned());
|
||||
Ok(ConnectOptions {
|
||||
address: link.address(),
|
||||
nickname: nonempty(¶ms.hello.nickname).or(link.nickname.clone()).unwrap_or_default(),
|
||||
identity,
|
||||
client_version,
|
||||
server_password: nonempty(¶ms.hello.password).or(link.password.clone()),
|
||||
channel: link.channel.clone(),
|
||||
channel_password: link.channel_password.clone(),
|
||||
token: nonempty(¶ms.hello.invite_code).or(link.token.clone()),
|
||||
audio: ctx.audio,
|
||||
stream_peer: ctx.stream_peer.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
// ---- backend and features ---------------------------------------------------
|
||||
|
||||
/// The server software as v1 names it (table 4.7): `teamspeak` with the
|
||||
/// flavor `ts3` or `ts6`; what is not a TeamSpeak product as it is.
|
||||
pub(crate) fn backend_to_v1(backend: &BackendInfo) -> v1::BackendInfo {
|
||||
let (product, flavor) = match backend.product.as_str() {
|
||||
"TeamSpeak 3" => ("teamspeak", "ts3"),
|
||||
"TeamSpeak 6" => ("teamspeak", "ts6"),
|
||||
// A TeamSpeak server the engine does not recognise: the version it
|
||||
// sent, no flavor.
|
||||
"" => ("teamspeak", ""),
|
||||
other => (other, ""),
|
||||
};
|
||||
v1::BackendInfo {
|
||||
product: product.into(),
|
||||
version: backend.version.clone(),
|
||||
flavor: flavor.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The features a TeamSpeak connection offers, from what its link can do
|
||||
/// (`docs/session-seam.md` section 4.7).
|
||||
pub(crate) fn features_of(capabilities: &voelin_model::Capabilities) -> Vec<&'static str> {
|
||||
let mut features =
|
||||
vec!["voice", "chat", "chat.bbcode", "dm", "sync.delta", "roles", "roles.channel"];
|
||||
if capabilities.file_transfer {
|
||||
features.extend(["files", "files.upload"]);
|
||||
}
|
||||
if capabilities.offline_messages {
|
||||
features.push("mailbox");
|
||||
}
|
||||
if capabilities.streams {
|
||||
features.extend(["streams", "streams.p2p", "streams.audio", "streams.approval"]);
|
||||
}
|
||||
features
|
||||
}
|
||||
|
||||
// ---- the session ------------------------------------------------------------
|
||||
|
||||
/// A `Session` over a [`ServerLink`]: the TeamSpeak side of the seam.
|
||||
pub(crate) struct LinkSession {
|
||||
welcome: v1::Welcome,
|
||||
features: Features,
|
||||
cmds: mpsc::UnboundedSender<Cmd>,
|
||||
closed: watch::Receiver<Option<CloseReason>>,
|
||||
own_slot: u32,
|
||||
}
|
||||
|
||||
fn closed_reason(closed: &watch::Receiver<Option<CloseReason>>) -> CloseReason {
|
||||
closed.borrow().clone().unwrap_or_else(|| CloseReason::Network("the connection ended".into()))
|
||||
}
|
||||
|
||||
impl Session for LinkSession {
|
||||
fn welcome(&self) -> &v1::Welcome {
|
||||
&self.welcome
|
||||
}
|
||||
|
||||
fn features(&self) -> Features {
|
||||
self.features.clone()
|
||||
}
|
||||
|
||||
fn request(&self, op: v1::request::Op) -> BoxFuture<Result<Answer, SessionError>> {
|
||||
let closed = self.closed.clone();
|
||||
match placement(&op) {
|
||||
Placement::Invalid => {
|
||||
return Box::pin(async {
|
||||
Err(SessionError::Protocol("a Hello is part of connecting".into()))
|
||||
});
|
||||
}
|
||||
Placement::OwnStream
|
||||
if matches!(op, v1::request::Op::FileRead(_) | v1::request::Op::FileWrite(_)) =>
|
||||
{
|
||||
return Box::pin(async {
|
||||
Err(SessionError::Protocol("files go through read_file and write_file".into()))
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// Queued now, in the order of the calls, not when the future is polled.
|
||||
let (reply, answer) = oneshot::channel();
|
||||
if self.cmds.send(Cmd::Request { op, reply }).is_err() {
|
||||
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
|
||||
}
|
||||
Box::pin(async move {
|
||||
match answer.await {
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn notify(&self, op: v1::request::Op) -> Result<(), SessionError> {
|
||||
if placement(&op) == Placement::Invalid {
|
||||
return Err(SessionError::Protocol("a Hello is part of connecting".into()));
|
||||
}
|
||||
self.cmds
|
||||
.send(Cmd::Notify(op))
|
||||
.map_err(|_| SessionError::Closed(closed_reason(&self.closed)))
|
||||
}
|
||||
|
||||
fn read_file(&self, request: v1::FileRead) -> BoxFuture<Result<Download, SessionError>> {
|
||||
let closed = self.closed.clone();
|
||||
let (reply, answer) = oneshot::channel();
|
||||
if self.cmds.send(Cmd::Read { request, reply }).is_err() {
|
||||
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
|
||||
}
|
||||
Box::pin(async move {
|
||||
match answer.await {
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn write_file(&self, request: v1::FileWrite) -> BoxFuture<Result<Upload, SessionError>> {
|
||||
let closed = self.closed.clone();
|
||||
let (reply, answer) = oneshot::channel();
|
||||
if self.cmds.send(Cmd::Write { request, reply }).is_err() {
|
||||
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
|
||||
}
|
||||
Box::pin(async move {
|
||||
match answer.await {
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn send_media(&self, class: MediaClass, packet: MediaPacket) -> Result<Sent, MediaError> {
|
||||
let flow = packet.flow;
|
||||
if self.closed.borrow().is_some() {
|
||||
return Err(MediaError::Closed);
|
||||
}
|
||||
if packet.rtp.len() > MAX_RTP {
|
||||
return Err(MediaError::TooLarge { len: packet.rtp.len(), max: MAX_RTP });
|
||||
}
|
||||
// Only our voice to the channel: TeamSpeak whispers and priority voice,
|
||||
// like video, are not offered here.
|
||||
if class != MediaClass::Voice
|
||||
|| flow.slot() != self.own_slot
|
||||
|| flow.sub() != voice_sub::CHANNEL
|
||||
{
|
||||
return Err(MediaError::NotOwned(flow));
|
||||
}
|
||||
let voice = media::uplink(&packet).ok_or(MediaError::NotOwned(flow))?;
|
||||
self.cmds.send(Cmd::Audio(voice)).map_err(|_| MediaError::Closed)?;
|
||||
Ok(Sent::Queued)
|
||||
}
|
||||
|
||||
fn stats(&self) -> LinkStats {
|
||||
LinkStats { max_rtp: MAX_RTP, ..Default::default() }
|
||||
}
|
||||
|
||||
fn close(&self, code: v1::CloseCode, reason: &str) {
|
||||
let _ = self.cmds.send(Cmd::Close { code, reason: reason.to_owned() });
|
||||
}
|
||||
|
||||
fn closed(&self) -> BoxFuture<CloseReason> {
|
||||
let mut closed = self.closed.clone();
|
||||
Box::pin(async move {
|
||||
let reason = closed.wait_for(Option::is_some).await.ok().and_then(|r| r.clone());
|
||||
reason.unwrap_or_else(|| closed_reason(&closed))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The write half of an upload: ending it tells the other half of the
|
||||
/// upload that the file is all there.
|
||||
struct UploadBody {
|
||||
inner: tokio::io::WriteHalf<BoxDuplex>,
|
||||
ended: Option<oneshot::Sender<()>>,
|
||||
}
|
||||
|
||||
impl AsyncWrite for UploadBody {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<std::io::Result<usize>> {
|
||||
Pin::new(&mut self.inner).poll_write(cx, buf)
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_flush(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
let done = Pin::new(&mut self.inner).poll_shutdown(cx);
|
||||
if matches!(done, Poll::Ready(Ok(())))
|
||||
&& let Some(ended) = self.ended.take()
|
||||
{
|
||||
let _ = ended.send(());
|
||||
}
|
||||
done
|
||||
}
|
||||
}
|
||||
|
||||
/// An upload over the transfer connection `stream`: the body writes to it,
|
||||
/// and `done` resolves once the body is shut down and the server has closed
|
||||
/// the connection (or 30 s passed), with the file as `stored`.
|
||||
fn upload(stream: BoxDuplex, stored: v1::FileEntry) -> Upload {
|
||||
let (mut read, write) = tokio::io::split(stream);
|
||||
let (ended, shut) = oneshot::channel();
|
||||
let done: BoxFuture<Result<v1::Entities, SessionError>> = Box::pin(async move {
|
||||
if shut.await.is_err() {
|
||||
return Err(rejected(v1::ErrorCode::Cancelled, "the upload was dropped"));
|
||||
}
|
||||
// The server closes the connection once it has everything.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(30), read.read(&mut [0u8; 1])).await;
|
||||
Ok(v1::Entities {
|
||||
items: vec![v1::Entity { kind: Some(v1::entity::Kind::File(stored)) }],
|
||||
..Default::default()
|
||||
})
|
||||
});
|
||||
Upload { body: Box::pin(UploadBody { inner: write, ended: Some(ended) }), done }
|
||||
}
|
||||
|
||||
// ---- the connector ----------------------------------------------------------
|
||||
|
||||
/// The `Connector` of a [`ServerLink`]: its sessions are [`LinkSession`]s.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct LinkConnector {
|
||||
link: Arc<dyn ServerLink>,
|
||||
schemes: &'static [&'static str],
|
||||
/// Serves every scheme (the engine's tests give a link of their own).
|
||||
any: bool,
|
||||
}
|
||||
|
||||
impl LinkConnector {
|
||||
/// A connector for `schemes`.
|
||||
pub(crate) fn new(link: Arc<dyn ServerLink>, schemes: &'static [&'static str]) -> Self {
|
||||
Self { link, schemes, any: false }
|
||||
}
|
||||
|
||||
/// A connector for addresses of every scheme.
|
||||
pub(crate) fn any(link: Arc<dyn ServerLink>) -> Self {
|
||||
Self { link, schemes: &[], any: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl Connector for LinkConnector {
|
||||
fn schemes(&self) -> &'static [&'static str] {
|
||||
self.schemes
|
||||
}
|
||||
|
||||
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
|
||||
let connect = connect_link(self.link.clone(), params, LocalCtx::standalone());
|
||||
Box::pin(async move { Ok(connect.await?.connected) })
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalConnector for LinkConnector {
|
||||
fn accepts(&self, scheme: &str) -> bool {
|
||||
self.any || self.schemes.contains(&scheme)
|
||||
}
|
||||
|
||||
fn connect_local(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>> {
|
||||
Box::pin(connect_link(self.link.clone(), params, ctx))
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects to TeamSpeak 3 and 6 servers (`ts3server://` and `teamspeak://`)
|
||||
/// with `tsclientlib`: [`LinkSession`]s over [`TsLink`].
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct TsConnector(LinkConnector);
|
||||
|
||||
impl TsConnector {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self(LinkConnector::new(Arc::new(TsLink), &["ts3server", "teamspeak"]))
|
||||
}
|
||||
}
|
||||
|
||||
impl Connector for TsConnector {
|
||||
fn schemes(&self) -> &'static [&'static str] {
|
||||
self.0.schemes()
|
||||
}
|
||||
|
||||
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
|
||||
self.0.connect(params)
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalConnector for TsConnector {
|
||||
fn connect_local(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>> {
|
||||
self.0.connect_local(params, ctx)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the link told when it connected.
|
||||
struct Joined {
|
||||
name: String,
|
||||
backend: BackendInfo,
|
||||
capabilities: voelin_model::Capabilities,
|
||||
own_client: u16,
|
||||
server_uid: String,
|
||||
own_uid: Option<String>,
|
||||
}
|
||||
|
||||
fn ended_error(reason: Option<String>) -> SessionError {
|
||||
SessionError::Closed(match reason {
|
||||
Some(reason) => CloseReason::Network(reason),
|
||||
None => CloseReason::Remote { code: v1::CloseCode::Normal as u64, reason: String::new() },
|
||||
})
|
||||
}
|
||||
|
||||
/// Wait for the link to say it is connected (or that it failed).
|
||||
async fn wait_connected(
|
||||
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
|
||||
) -> Result<Joined, SessionError> {
|
||||
loop {
|
||||
match events.recv().await {
|
||||
Some(LinkEvent::Connected {
|
||||
name,
|
||||
backend,
|
||||
capabilities,
|
||||
own_client,
|
||||
server_uid,
|
||||
own_uid,
|
||||
}) => {
|
||||
return Ok(Joined { name, backend, capabilities, own_client, server_uid, own_uid });
|
||||
}
|
||||
Some(LinkEvent::Disconnected(reason)) => return Err(ended_error(reason)),
|
||||
Some(_) => {}
|
||||
None => return Err(ended_error(Some("the connection ended".into()))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a [`LinkSession`] over `link` to the address in `params`.
|
||||
async fn connect_link(
|
||||
link: Arc<dyn ServerLink>,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> Result<LocalConnected, SessionError> {
|
||||
let options = inner_options(¶ms, &ctx)?;
|
||||
let nickname = options.nickname.clone();
|
||||
let (inner_tx, inner_rx) = mpsc::unbounded_channel();
|
||||
let (events_tx, mut events) = mpsc::unbounded_channel();
|
||||
// The link answers requests on a bus of its own: this session reads the
|
||||
// answers, and passes on the rest to the engine's.
|
||||
let (bus_tx, bus) = broadcast::channel(4096);
|
||||
let inner_ctx = LinkCtx { events: bus_tx, ..ctx.link.clone() };
|
||||
link.spawn(options, inner_ctx, inner_rx, events_tx);
|
||||
|
||||
let joined = match tokio::time::timeout(params.timeout, wait_connected(&mut events)).await {
|
||||
Ok(joined) => joined?,
|
||||
Err(_) => {
|
||||
let _ = inner_tx.send(LinkCmd::Disconnect);
|
||||
return Err(SessionError::Timeout);
|
||||
}
|
||||
};
|
||||
// The link reports its first snapshot right after it says it is connected;
|
||||
// the session needs it to know the own user.
|
||||
let mut early: Vec<LinkEvent> = Vec::new();
|
||||
let _ = tokio::time::timeout(FIRST_SNAPSHOT, async {
|
||||
while let Some(event) = events.recv().await {
|
||||
let stop = matches!(event, LinkEvent::Presence(_) | LinkEvent::Disconnected(_));
|
||||
early.push(event);
|
||||
if stop {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
if let Some(LinkEvent::Disconnected(reason)) = early.last() {
|
||||
return Err(ended_error(reason.clone()));
|
||||
}
|
||||
let own_database_id = early.iter().find_map(|event| match event {
|
||||
LinkEvent::Presence(presence) => {
|
||||
presence.clients.get(&joined.own_client).and_then(|c| c.database_id)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
|
||||
let ts6 = joined.backend.product == "TeamSpeak 6";
|
||||
let own_user =
|
||||
own_database_id.or_else(|| joined.own_uid.as_deref().map(ids::synthetic_user)).unwrap_or(0);
|
||||
let features = features_of(&joined.capabilities);
|
||||
let welcome = v1::Welcome {
|
||||
user_id: own_user,
|
||||
session_id: SESSIONS.fetch_add(1, Ordering::Relaxed),
|
||||
uid: joined.own_uid.as_deref().and_then(ids::uid_bytes).unwrap_or_default().into(),
|
||||
host: Some(v1::HostInfo {
|
||||
host_key: Bytes::new(),
|
||||
name: joined.name.clone(),
|
||||
product: joined.backend.product.clone(),
|
||||
version: joined.backend.version.clone(),
|
||||
backend: Some(backend_to_v1(&joined.backend)),
|
||||
icon: None,
|
||||
}),
|
||||
features: features.iter().map(|f| (*f).to_owned()).collect(),
|
||||
limits: Some(v1::Limits {
|
||||
max_message_chars: 1024,
|
||||
max_page: 100,
|
||||
max_subscriptions: 4,
|
||||
max_chat_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS,
|
||||
max_live_subscriptions: 8,
|
||||
..Default::default()
|
||||
}),
|
||||
time_ms: now_ms(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let (cmds_tx, cmds_rx) = mpsc::unbounded_channel();
|
||||
let (pushes_tx, pushes_rx) = mpsc::channel(params.push_capacity.max(16));
|
||||
let (closed_tx, closed_rx) = watch::channel(None);
|
||||
let (port, streams) = if joined.capabilities.streams {
|
||||
let (events_tx, events_rx) = mpsc::unbounded_channel();
|
||||
let cmds = cmds_tx.clone();
|
||||
let send = move |cmd| {
|
||||
let _ = cmds.send(Cmd::Stream(cmd));
|
||||
};
|
||||
(Some(events_tx), Some(StreamPort::new(send, events_rx)))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
let details = ServerDetails { uid: Some(joined.server_uid.clone()), ..Default::default() };
|
||||
let driver = Driver::new(Parts {
|
||||
cfg: Config {
|
||||
ts6,
|
||||
own_client: joined.own_client,
|
||||
nickname,
|
||||
own_uid: joined.own_uid.clone(),
|
||||
files: joined.capabilities.file_transfer,
|
||||
mail: joined.capabilities.offline_messages,
|
||||
},
|
||||
inner: inner_tx,
|
||||
events,
|
||||
early,
|
||||
bus,
|
||||
engine_bus: ctx.link.events.clone(),
|
||||
pushes: pushes_tx,
|
||||
media: params.media.clone(),
|
||||
port,
|
||||
closed: closed_tx,
|
||||
server: entities::server(&details, &joined.name, 0),
|
||||
epoch: u64::try_from(now_ms()).unwrap_or(1).max(1),
|
||||
});
|
||||
let session = LinkSession {
|
||||
welcome,
|
||||
features: Features::new(features),
|
||||
cmds: cmds_tx,
|
||||
closed: closed_rx,
|
||||
own_slot: entities::slot(joined.own_client),
|
||||
};
|
||||
tokio::spawn(driver.run(cmds_rx));
|
||||
Ok(LocalConnected {
|
||||
connected: Connected {
|
||||
session: Arc::new(session),
|
||||
pushes: pushes_rx,
|
||||
// A TeamSpeak server has no host key to pin.
|
||||
host_uid: [0; 32],
|
||||
},
|
||||
streams,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn params(options: &ConnectOptions) -> ConnectParams {
|
||||
let (media, _rx) = voelin_proto::test_util::media_channel();
|
||||
connect_params(options, media, &Backends::empty())
|
||||
}
|
||||
|
||||
fn back(options: &ConnectOptions) -> ConnectOptions {
|
||||
inner_options(¶ms(options), &LocalCtx::standalone()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_options_of_a_bookmark_come_back_as_they_went() {
|
||||
let mut options = ConnectOptions::new("ts.example.com:9988", "nick");
|
||||
let same = back(&options);
|
||||
assert_eq!(
|
||||
(same.address.as_str(), same.nickname.as_str()),
|
||||
("ts.example.com:9988", "nick")
|
||||
);
|
||||
assert!(same.identity.is_none() && same.client_version.is_none());
|
||||
assert!(same.channel.is_none() && same.server_password.is_none() && same.token.is_none());
|
||||
|
||||
// Everything a connection can be told: the server password and the
|
||||
// privilege key go in the hello, the channel and its password in the
|
||||
// link, the identity as a credential.
|
||||
options.server_password = Some("s3cret pass&word".into());
|
||||
options.channel = Some("Games/Raid Night".into());
|
||||
options.channel_password = Some("p w+%".into());
|
||||
options.token = Some("tokenvalue".into());
|
||||
options.identity = Some(tsclientlib::Identity::create());
|
||||
options.client_version = Some(crate::versions::native_version().unwrap());
|
||||
options.audio = false;
|
||||
let sent = params(&options);
|
||||
assert_eq!(sent.hello.password, "s3cret pass&word");
|
||||
assert_eq!(sent.hello.invite_code, "tokenvalue");
|
||||
assert_eq!(sent.hello.nickname, "nick");
|
||||
assert!(
|
||||
sent.address.starts_with("ts3server://ts.example.com?port=9988"),
|
||||
"{}",
|
||||
sent.address
|
||||
);
|
||||
assert!(!sent.address.contains("s3cret") && !sent.address.contains("tokenvalue"));
|
||||
let got = back(&options);
|
||||
assert_eq!(got.address, "ts.example.com:9988");
|
||||
assert_eq!(got.server_password, options.server_password);
|
||||
assert_eq!(got.channel.as_deref(), Some("Games/Raid Night"));
|
||||
assert_eq!(got.channel_password, options.channel_password);
|
||||
assert_eq!(got.token.as_deref(), Some("tokenvalue"));
|
||||
assert_eq!(got.client_version, options.client_version);
|
||||
// The identity is the same key and counters.
|
||||
let (a, b) = (options.identity.as_ref().unwrap(), got.identity.as_ref().unwrap());
|
||||
assert_eq!(serde_json::to_value(a).unwrap(), serde_json::to_value(b).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_channel_by_id_and_an_address_that_is_a_link_are_kept() {
|
||||
let mut options = ConnectOptions::new("[::1]:9987", "nick");
|
||||
options.channel = Some("/12".into());
|
||||
let got = back(&options);
|
||||
assert_eq!(got.address, "[::1]:9987");
|
||||
assert_eq!(got.channel.as_deref(), Some("/12"));
|
||||
|
||||
// A bookmark that is a link keeps its own parameters.
|
||||
let options =
|
||||
ConnectOptions::new("ts3server://ts.example.com?port=1&channel=Lobby", "nick");
|
||||
let got = back(&options);
|
||||
assert_eq!(
|
||||
(got.address.as_str(), got.channel.as_deref()),
|
||||
("ts.example.com:1", Some("Lobby"))
|
||||
);
|
||||
// Another scheme is left as it is for the connector of that scheme.
|
||||
let options = ConnectOptions::new("voelin://host/i/code", "nick");
|
||||
assert_eq!(params(&options).address, "voelin://host/i/code");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_no_teamspeak_identity_is_refused() {
|
||||
let mut sent = params(&ConnectOptions::new("ts.example.com", "nick"));
|
||||
sent.credential = Credential::Voelin(Arc::new(voelin_proto::test_util::FakeSigner));
|
||||
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
|
||||
assert!(matches!(error, SessionError::Protocol(_)));
|
||||
let mut sent = params(&ConnectOptions::new("ts.example.com", "nick"));
|
||||
sent.credential =
|
||||
Credential::Account { kind: "teamspeak", integration_id: Bytes::from_static(b"id") };
|
||||
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
|
||||
let mut sent = params(&ConnectOptions::new("ts.example.com", "nick"));
|
||||
sent.credential =
|
||||
Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(b"not json") };
|
||||
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
|
||||
// A host that wants trust is refused: TeamSpeak has no host key.
|
||||
let backends = Backends::empty();
|
||||
let confirm = backends.trust().confirm(voelin_proto::link::HostIdentity {
|
||||
address: "x".into(),
|
||||
uid: [0; 32],
|
||||
previous: None,
|
||||
});
|
||||
assert!(!futures::executor::block_on(confirm));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_params_carry_what_the_session_needs_and_no_account_yet() {
|
||||
let sent = params(&ConnectOptions::new("ts.example.com", "nick"));
|
||||
assert!(sent.account.is_none());
|
||||
assert_eq!(sent.issuer_trust, IssuerTrust::Unknown);
|
||||
assert!(sent.linked.is_empty() && sent.host_pin.is_none());
|
||||
assert_eq!((sent.push_capacity, sent.timeout), (1024, Duration::from_secs(35)));
|
||||
let client = sent.hello.client.unwrap();
|
||||
assert_eq!(client.name, "Voelin");
|
||||
assert_eq!(sent.hello.version, 1);
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ use std::time::Duration;
|
||||
|
||||
use base64::Engine as _;
|
||||
use futures::prelude::*;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
use tokio::task::AbortHandle;
|
||||
use tokio::time::{Instant, timeout};
|
||||
use tracing::{debug, info, warn};
|
||||
@@ -37,9 +37,9 @@ use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, ServerFlavo
|
||||
use voelin_stream::{ClientState, Request, StreamNotification};
|
||||
|
||||
use crate::book::presence_from_book;
|
||||
use crate::cache;
|
||||
use crate::cache::{self, IMAGE_NEGOTIATION, image_download_time};
|
||||
use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState};
|
||||
use crate::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, Remote};
|
||||
use crate::link::{BoxDuplex, BoxRead, ConnectOptions, LinkCmd, LinkCtx, LinkEvent, Remote};
|
||||
use crate::offline::{OfflineMessage, OfflineMessageInfo};
|
||||
use crate::settings::FILES_PROGRESS_MS;
|
||||
use crate::stream::{StreamCmd, StreamHandle, StreamInput};
|
||||
@@ -172,43 +172,58 @@ enum Job {
|
||||
size: u64,
|
||||
report: Report,
|
||||
},
|
||||
/// The caller wants the connection itself ([`LinkCmd::OpenRead`]).
|
||||
OpenRead(oneshot::Sender<Result<(u64, BoxRead), String>>),
|
||||
/// The caller wants the connection itself ([`LinkCmd::OpenWrite`]).
|
||||
OpenWrite(oneshot::Sender<Result<(u64, BoxDuplex), String>>),
|
||||
}
|
||||
|
||||
impl Job {
|
||||
fn report(&self) -> &Report {
|
||||
/// The job could not be done: tell whoever waits.
|
||||
fn fail(self, text: String) {
|
||||
match self {
|
||||
Job::Download { report, .. } | Job::Upload { report, .. } => report,
|
||||
Job::Download { report, .. } | Job::Upload { report, .. } => {
|
||||
report(TransferState::Failed(text));
|
||||
}
|
||||
Job::OpenRead(reply) => {
|
||||
let _ = reply.send(Err(text));
|
||||
}
|
||||
Job::OpenWrite(reply) => {
|
||||
let _ = reply.send(Err(text));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The user cancelled the transfer before the server opened it.
|
||||
fn cancel(self) {
|
||||
if let Job::Download { report, .. } | Job::Upload { report, .. } = self {
|
||||
report(TransferState::Cancelled);
|
||||
}
|
||||
}
|
||||
|
||||
fn transfer(&self) -> Option<TransferId> {
|
||||
match self {
|
||||
Job::Download { transfer, .. } | Job::Upload { transfer, .. } => *transfer,
|
||||
Job::OpenRead(_) | Job::OpenWrite(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a picture of `size` bytes may take to arrive: a minute, plus
|
||||
/// its size at [`cache::MIN_PICTURE_RATE`], so large banners arrive on slow
|
||||
/// links while a stalled transfer still ends.
|
||||
fn image_download_time(size: u64) -> Duration {
|
||||
Duration::from_secs(60 + size / cache::MIN_PICTURE_RATE)
|
||||
}
|
||||
|
||||
/// How long the server may take to start an image transfer (a busy server
|
||||
/// answers the requests of a large channel tree in turn).
|
||||
const IMAGE_NEGOTIATION: Duration = Duration::from_secs(30);
|
||||
|
||||
/// Bound background image handshakes without imposing a deadline on user transfers.
|
||||
fn expire_image_jobs(jobs: &mut HashMap<FiletransferHandle, Job>, now: Instant) {
|
||||
jobs.retain(|_, job| {
|
||||
if matches!(job, Job::Download { transfer: None, started, .. } if now.duration_since(*started) >= IMAGE_NEGOTIATION) {
|
||||
job.report()(TransferState::Failed("image transfer negotiation timed out".into()));
|
||||
false
|
||||
} else {
|
||||
true
|
||||
let expired: Vec<FiletransferHandle> = jobs
|
||||
.iter()
|
||||
.filter(|(_, job)| {
|
||||
matches!(job, Job::Download { transfer: None, started, .. }
|
||||
if now.duration_since(*started) >= IMAGE_NEGOTIATION)
|
||||
})
|
||||
.map(|(handle, _)| *handle)
|
||||
.collect();
|
||||
for handle in expired {
|
||||
if let Some(job) = jobs.remove(&handle) {
|
||||
job.fail("image transfer negotiation timed out".into());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// A user's transfer, for cancelling.
|
||||
@@ -468,7 +483,7 @@ async fn run_inner(
|
||||
drop(voice.streams.take());
|
||||
// Transfers the server never opened fail; running ones go on.
|
||||
for (_, job) in voice.jobs.drain() {
|
||||
job.report()(TransferState::Failed("disconnected".into()));
|
||||
job.fail("disconnected".into());
|
||||
}
|
||||
let disconnect = shutdown_connection(voice.con).await;
|
||||
result?;
|
||||
@@ -606,6 +621,13 @@ impl Voice {
|
||||
}
|
||||
}
|
||||
StreamItem::FileDownload(handle, download) => {
|
||||
if matches!(self.jobs.get(&handle), Some(Job::OpenRead(_))) {
|
||||
// The caller wants the connection itself.
|
||||
if let Some(Job::OpenRead(reply)) = self.jobs.remove(&handle) {
|
||||
let _ = reply.send(Ok((download.size, Box::pin(download.stream))));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(Job::Download { transfer, offset, sink, report, .. }) =
|
||||
self.jobs.remove(&handle)
|
||||
{
|
||||
@@ -639,6 +661,13 @@ impl Voice {
|
||||
}
|
||||
}
|
||||
StreamItem::FileUpload(handle, upload) => {
|
||||
if matches!(self.jobs.get(&handle), Some(Job::OpenWrite(_))) {
|
||||
// The caller wants the connection itself.
|
||||
if let Some(Job::OpenWrite(reply)) = self.jobs.remove(&handle) {
|
||||
let _ = reply.send(Ok((upload.seek_position, Box::pin(upload.stream))));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(Job::Upload { transfer, from, size, report }) =
|
||||
self.jobs.remove(&handle)
|
||||
{
|
||||
@@ -658,7 +687,7 @@ impl Voice {
|
||||
if let Some(id) = job.transfer() {
|
||||
self.transfers.remove(&id);
|
||||
}
|
||||
job.report()(TransferState::Failed(transfer_error(&error)));
|
||||
job.fail(transfer_error(&error));
|
||||
}
|
||||
}
|
||||
StreamItem::DisconnectedTemporarily(reason) => {
|
||||
@@ -1120,10 +1149,35 @@ impl Voice {
|
||||
self.transfers.insert(id, Slot::Waiting(handle));
|
||||
}
|
||||
}
|
||||
LinkCmd::OpenRead { file, offset, reply } => {
|
||||
let seek = (offset > 0).then_some(offset);
|
||||
let password = file.password.as_deref().filter(|p| !p.is_empty());
|
||||
let channel = tsclientlib::ChannelId(file.channel);
|
||||
match self.con.download_file(channel, &file.path, password, seek) {
|
||||
Ok(handle) => {
|
||||
self.jobs.insert(handle, Job::OpenRead(reply));
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = reply.send(Err(e.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
LinkCmd::OpenWrite { file, size, overwrite, resume, reply } => {
|
||||
let password = file.password.as_deref().filter(|p| !p.is_empty());
|
||||
let channel = tsclientlib::ChannelId(file.channel);
|
||||
match self.con.upload_file(channel, &file.path, password, size, overwrite, resume) {
|
||||
Ok(handle) => {
|
||||
self.jobs.insert(handle, Job::OpenWrite(reply));
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = reply.send(Err(e.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
LinkCmd::CancelTransfer(id) => match self.transfers.remove(&id) {
|
||||
Some(Slot::Waiting(handle)) => {
|
||||
if let Some(job) = self.jobs.remove(&handle) {
|
||||
job.report()(TransferState::Cancelled);
|
||||
job.cancel();
|
||||
}
|
||||
}
|
||||
Some(Slot::Running { task, part, report }) if !task.is_finished() => {
|
||||
|
||||
@@ -9,6 +9,7 @@ use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
use voelin_audio::{TalkerId, VoiceCodec, VoicePacket};
|
||||
use voelin_core::history::MessageSource;
|
||||
use voelin_core::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, ServerLink};
|
||||
use voelin_core::settings::Settings;
|
||||
@@ -19,6 +20,7 @@ use voelin_core::{
|
||||
};
|
||||
use voelin_model::{
|
||||
Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence,
|
||||
ServerDetails,
|
||||
};
|
||||
|
||||
/// A connection the session asked the link for.
|
||||
@@ -167,28 +169,53 @@ fn connected(streams: bool) -> LinkEvent {
|
||||
}
|
||||
}
|
||||
|
||||
/// A client as a TeamSpeak link reports one: with its database id, and not
|
||||
/// talking (who talks comes from the media, which the session derives).
|
||||
fn client(id: u16, nickname: &str, channel: ChannelId) -> ClientInfo {
|
||||
ClientInfo {
|
||||
id,
|
||||
uid: Some(format!("{nickname}=")),
|
||||
nickname: nickname.into(),
|
||||
channel,
|
||||
talking: Some(false),
|
||||
database_id: Some(1_000 + u64::from(id)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Two channels, three clients; we are in the second channel.
|
||||
/// Two channels, three clients; we are in the second channel. The shape is
|
||||
/// what a TeamSpeak link reports: sibling channels form an order chain, the
|
||||
/// server is named and has its unique id.
|
||||
fn presence() -> Presence {
|
||||
let channel = |id, name: &str| ChannelInfo { id, name: name.into(), ..Default::default() };
|
||||
let channel =
|
||||
|id, name: &str, order| ChannelInfo { id, name: name.into(), order, ..Default::default() };
|
||||
let mut presence = Presence { server_name: "Fake Server".into(), ..Default::default() };
|
||||
presence.channels.insert(LOBBY, channel(LOBBY, "Lobby"));
|
||||
presence.channels.insert(GAMES, channel(GAMES, "Games"));
|
||||
for c in [client(ME, "tester", GAMES), client(8, "alice", GAMES), client(9, "bob", LOBBY)] {
|
||||
presence.server = ServerDetails {
|
||||
name: "Fake Server".into(),
|
||||
uid: Some(SERVER_UID.into()),
|
||||
version: backend().version,
|
||||
..Default::default()
|
||||
};
|
||||
presence.channels.insert(LOBBY, channel(LOBBY, "Lobby", 0));
|
||||
presence.channels.insert(GAMES, channel(GAMES, "Games", LOBBY));
|
||||
let me = ClientInfo { uid: Some(ME_UID.into()), ..client(ME, "tester", GAMES) };
|
||||
for c in [me, client(8, "alice", GAMES), client(9, "bob", LOBBY)] {
|
||||
presence.clients.insert(c.id, c);
|
||||
}
|
||||
presence
|
||||
}
|
||||
|
||||
/// One packet of voice from `talker`: what the session derives talking from.
|
||||
fn voice_of(talker: u16) -> LinkEvent {
|
||||
LinkEvent::Audio(VoicePacket {
|
||||
talker: TalkerId(talker),
|
||||
seq: 1,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: vec![1, 2, 3],
|
||||
})
|
||||
}
|
||||
|
||||
fn message(author: &str, text: &str, ts_ms: i64) -> ChatMessage {
|
||||
ChatMessage {
|
||||
target: ChatTarget::Channel(GAMES),
|
||||
@@ -246,7 +273,8 @@ async fn presence_follows_the_link_until_it_disconnects() {
|
||||
assert_eq!(state.presence_source, Some(Source::Voice));
|
||||
|
||||
conn.play([
|
||||
LinkEvent::Talking { client: 8, talking: true },
|
||||
// Alice talks: a packet of her voice (the session derives who talks).
|
||||
voice_of(8),
|
||||
LinkEvent::Poke {
|
||||
from: 8,
|
||||
from_uid: Some("alice=".into()),
|
||||
@@ -333,8 +361,9 @@ async fn commands_reach_the_link() {
|
||||
password: None,
|
||||
path: "/docs/".into(),
|
||||
});
|
||||
let LinkCmd::ListFiles { request, dir } = conn.cmd().await else { panic!("a file list") };
|
||||
assert_eq!((request, dir.channel, dir.path.as_str()), (5, GAMES, "/docs/"));
|
||||
let LinkCmd::ListFiles { dir, .. } = conn.cmd().await else { panic!("a file list") };
|
||||
// The request id is the session's own: the link gets one of its making.
|
||||
assert_eq!((dir.channel, dir.path.as_str()), (GAMES, "/docs/"));
|
||||
|
||||
// No streams in the capabilities: the session refuses them itself.
|
||||
let setup = || StreamSetup { name: "screen".into(), ..Default::default() };
|
||||
@@ -548,6 +577,8 @@ async fn a_replaced_connection_is_ignored() {
|
||||
]);
|
||||
let mut fresh = presence();
|
||||
fresh.clients.remove(&9);
|
||||
// A link that says we are in the lobby shows us in the lobby.
|
||||
fresh.clients.get_mut(&ME).expect("we are on the server").channel = LOBBY;
|
||||
new.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(fresh.clone())),
|
||||
@@ -565,6 +596,10 @@ async fn a_replaced_connection_is_ignored() {
|
||||
assert_eq!(*shown, fresh);
|
||||
let state = h.state(|s| s.own_channel == Some(LOBBY)).await;
|
||||
assert_eq!(state.voice, VoiceState::Connected, "the old disconnect did not count");
|
||||
new.play([LinkEvent::Chat(message("alice", "hello", now_ms()))]);
|
||||
// Channel chat reaches the channel we are in (the lobby, now).
|
||||
new.play([LinkEvent::Chat(ChatMessage {
|
||||
target: ChatTarget::Channel(LOBBY),
|
||||
..message("alice", "hello", now_ms())
|
||||
})]);
|
||||
assert_eq!(h.chat().await.text, "hello", "the old connection's chat never showed");
|
||||
}
|
||||
Reference in new issue
Block a user