voelin-core: files, avatars, icons, pokes, offline messages, contacts

The new UI needs a channel file browser, avatars and icons, pokes,
direct messages to anyone, the offline message inbox and a friends list.
The voice connection can do all of it; the engine did not offer it.

Files (module files): ListFiles, DownloadFile (to disk as <path>.part,
renamed when complete, resumable, or into memory), DownloadChatFile for
a FileRef from a chat message, UploadFile, CancelTransfer, DeleteFiles,
RenameFile, CreateDirectory. Transfers stream in 64 KiB pieces and
report Requested/Started/Progress (files.progress_interval_ms)/Done/
Failed/Cancelled; requests and transfers carry an id the caller picks.

Avatars and icons are fetched by themselves (cache.fetch_images) into a
content-addressed disk cache (module cache: avatars by MD5, icons by id,
LRU bounded by cache.max_mb, 0 = no limit, use times kept as file times,
concurrent downloads of one file deduplicated across sessions) and
reported as AvatarReady / IconReady. SetAvatar uploads ours and
announces its hash, or removes it.

Pokes are a command and a distinct event (they were stored as private
messages before). A failing voice command (e.g. a private message to a
client who left) is now an error event instead of ending the connection.
Offline messages (module offline) list, read, send, delete and mark.

Contacts (module contacts) are engine-wide and stored in the client
database: SetContact / RemoveContact, ContactsChanged, FriendPresence
across all sessions, last seen time and server, per-person volume and
mute applied in every session, blocked authors flagged in chat and
their pokes and private messages hidden or flagged (privacy.block_mode),
and stream.permissions = friends lets friends watch without asking.

ServerDetails and Groups events report the server's details and groups
when they change. The book mapping moved to its own module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-28 19:50:39 +00:00
1 parent 1eb3c5ecd5
commit f24da42aab
16 files changed
+3119 -388

No files matched your search

Generated
+4
View File
@@ -9095,7 +9095,9 @@ name = "voelin-core"
version = "0.1.0"
dependencies = [
"anyhow",
"base64 0.22.1",
"futures",
"md5",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -9105,11 +9107,13 @@ dependencies = [
"tracing",
"tsclientlib",
"tsproto-packets",
"tsproto-types",
"voelin-audio",
"voelin-gateway-proto",
"voelin-media",
"voelin-model",
"voelin-observer",
"voelin-platform",
"voelin-query",
"voelin-store",
"voelin-stream",
+6 -1
View File
@@ -23,11 +23,13 @@ media-desktop = ["media", "voelin-media/default"]
[dependencies]
anyhow = "1"
base64 = "0.22"
futures = "0.3"
md5 = "0.8"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"] }
tokio = { version = "1", features = ["fs", "io-util", "macros", "net", "rt-multi-thread", "sync", "time"] }
tokio-tungstenite = "0.30"
toml = "1.1.6"
tracing = "0.1"
@@ -36,11 +38,14 @@ voelin-gateway-proto = { path = "../voelin-gateway-proto", features = ["client"]
voelin-media = { path = "../voelin-media", default-features = false, features = ["str0m"], optional = true }
voelin-model = { path = "../voelin-model" }
voelin-observer = { path = "../voelin-observer" }
# Paths only (the cache directory).
voelin-platform = { path = "../voelin-platform", default-features = false }
voelin-query = { path = "../voelin-query" }
voelin-store = { path = "../voelin-store" }
voelin-stream = { path = "../voelin-stream" }
tsclientlib = { path = "../proto/tsclientlib" }
tsproto-packets = { path = "../proto/tsproto-packets" }
tsproto-types = { path = "../proto/tsproto-types" }
[dev-dependencies]
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "test-util"] }
+159
View File
@@ -0,0 +1,159 @@
//! The voice connection's book (tsclientlib) as model types.
use tsclientlib::{ClientType, MaxClients, data};
use voelin_model::{
ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, HostBannerMode,
HostMessageMode, Presence, ServerDetails, parse_badges,
};
fn group_info(
id: u64,
name: &str,
icon: tsclientlib::IconId,
sort_id: i32,
naming_mode: tsclientlib::GroupNamingMode,
group_type: tsclientlib::GroupType,
) -> GroupInfo {
GroupInfo {
id,
name: name.to_owned(),
icon: icon.0,
sort_id,
naming_mode: match naming_mode {
tsclientlib::GroupNamingMode::None => GroupNamingMode::None,
tsclientlib::GroupNamingMode::Before => GroupNamingMode::Before,
tsclientlib::GroupNamingMode::After => GroupNamingMode::After,
},
group_type: match group_type {
tsclientlib::GroupType::Template => GroupType::Template,
tsclientlib::GroupType::Regular => GroupType::Regular,
tsclientlib::GroupType::Query => GroupType::Query,
},
}
}
/// What the server tells about itself; `uid` as the voice source computed it.
fn server_details(server: &data::Server, uid: Option<&str>) -> ServerDetails {
ServerDetails {
name: server.name.clone(),
uid: uid.map(str::to_owned),
welcome_message: server.welcome_message.clone(),
host_message: server.hostmessage.clone(),
host_message_mode: match server.hostmessage_mode {
tsclientlib::HostMessageMode::None => HostMessageMode::None,
tsclientlib::HostMessageMode::Log => HostMessageMode::Log,
tsclientlib::HostMessageMode::Modal => HostMessageMode::Modal,
tsclientlib::HostMessageMode::Modalquit => HostMessageMode::ModalQuit,
},
banner_url: server.hostbanner_url.clone(),
banner_gfx_url: server.hostbanner_gfx_url.clone(),
banner_gfx_interval_s: server.hostbanner_gfx_interval.whole_seconds().max(0) as u64,
banner_mode: match server.hostbanner_mode {
tsclientlib::HostBannerMode::NoAdjust => HostBannerMode::NoAdjust,
tsclientlib::HostBannerMode::AdjustIgnoreAspect => HostBannerMode::IgnoreAspect,
tsclientlib::HostBannerMode::AdjustKeepAspect => HostBannerMode::KeepAspect,
},
host_button_tooltip: server.hostbutton_tooltip.clone(),
host_button_url: server.hostbutton_url.clone(),
host_button_gfx_url: server.hostbutton_gfx_url.clone(),
icon: server.icon.0,
platform: server.platform.clone(),
version: server.version.clone(),
max_clients: server.max_clients,
default_server_group: Some(server.default_server_group.0),
default_channel_group: Some(server.default_channel_group.0),
}
}
/// The presence visible through a voice connection; `server_uid` as
/// the voice source computed it, `talking` the clients talking now.
pub(crate) fn presence_from_book(
book: &data::Connection,
server_uid: Option<&str>,
talking: impl Fn(u16) -> bool,
) -> Presence {
let limit = |m: &Option<MaxClients>| match m {
Some(MaxClients::Limited(n)) => Some(*n as i32),
_ => None,
};
Presence {
server_name: book.server.name.clone(),
server: server_details(&book.server, server_uid),
server_groups: book
.server_groups
.values()
.map(|g| {
let info =
group_info(g.id.0, &g.name, g.icon, g.sort_id, g.naming_mode, g.group_type);
(g.id.0, info)
})
.collect(),
channel_groups: book
.channel_groups
.values()
.map(|g| {
let info =
group_info(g.id.0, &g.name, g.icon, g.sort_id, g.naming_mode, g.group_type);
(g.id.0, info)
})
.collect(),
channels: book
.channels
.values()
.map(|c| {
(
c.id.0,
ChannelInfo {
id: c.id.0,
parent: c.parent.0,
order: c.order.0,
name: c.name.clone(),
topic: c.topic.clone().filter(|t| !t.is_empty()),
has_password: c.has_password.unwrap_or(false),
max_clients: limit(&c.max_clients),
needed_subscribe_power: 0,
needed_talk_power: c.needed_talk_power.unwrap_or(0),
is_default: c.is_default.unwrap_or(false),
icon: c.icon.map_or(0, |i| i.0),
},
)
})
.collect(),
clients: book
.clients
.values()
.map(|c| {
let mut server_groups: Vec<u64> = c.server_groups.iter().map(|g| g.0).collect();
server_groups.sort_unstable();
(
c.id.0,
ClientInfo {
id: c.id.0,
uid: c.uid.as_ref().map(|u| u.as_ref().to_string()),
nickname: c.name.clone(),
channel: c.channel.0,
is_query: matches!(c.client_type, ClientType::Query { .. }),
away: c.away_message.clone(),
input_muted: c.input_muted,
output_muted: c.output_muted,
talking: Some(talking(c.id.0)),
streaming: c.is_streaming,
server_groups,
country: Some(c.country_code.clone()).filter(|c| !c.is_empty()),
avatar: Some(c.avatar_hash.clone()).filter(|h| !h.is_empty()),
description: Some(c.description.clone()).filter(|d| !d.is_empty()),
talk_power: c.talk_power,
talker: c.talk_power_granted,
channel_group: Some(c.channel_group.0),
badges: parse_badges(&c.badges),
icon: c.icon.0,
recording: c.is_recording,
priority_speaker: c.is_priority_speaker,
channel_commander: c.is_channel_commander,
database_id: Some(c.database_id.0),
},
)
})
.collect(),
}
}
+387
View File
@@ -0,0 +1,387 @@
//! The avatar and icon cache: files on disk named by their content.
//!
//! An avatar's name is its MD5 hash (`client_flag_avatar`), an icon's its
//! id (the CRC32 of the image, as TeamSpeak assigns them), so a lookup is a
//! map access, and the same image seen on several servers or under
//! several clients is one file. Keys are relative paths (`avatars/<md5>`,
//! `icons/<id>`).
//!
//! The cache is bounded by `cache.max_mb` (read on every insert; 0: no
//! limit): the least recently used files go first. Use times survive
//! restarts as the files' modification times.
//!
//! Downloads are deduplicated: [`Cache::fetch`] tells the first asker to
//! download (into a temporary path), later askers wait for the same
//! download ([`Cache::finish`] answers them all).
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError, RwLock};
use std::time::SystemTime;
use tracing::debug;
/// Called with the cached file's path, or why it could not be fetched.
pub(crate) type Waiter = Box<dyn FnOnce(Result<PathBuf, String>) + Send>;
/// What [`Cache::fetch`] decided.
pub(crate) enum Fetch {
/// In the cache; the waiter was answered.
Cached,
/// Another download is running; the waiter is answered when it ends.
Waiting,
/// Download into this path, then call [`Cache::finish`].
Download(PathBuf),
}
struct Entry {
size: u64,
tick: u64,
}
#[derive(Default)]
struct Index {
scanned: bool,
entries: HashMap<String, Entry>,
/// Use order: oldest first.
lru: BTreeMap<u64, String>,
total: u64,
next_tick: u64,
in_flight: HashMap<String, Vec<Waiter>>,
temp_serial: u64,
}
/// See the [module docs](self). Cheap to clone.
#[derive(Clone)]
pub struct Cache {
dir: Arc<PathBuf>,
index: Arc<Mutex<Index>>,
}
impl std::fmt::Debug for Cache {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Cache").field("dir", &self.dir).finish()
}
}
/// The cache key of an avatar (its MD5 hash, hex).
pub(crate) fn avatar_key(hash: &str) -> Option<String> {
let valid =
!hash.is_empty() && hash.len() <= 128 && hash.bytes().all(|b| b.is_ascii_hexdigit());
valid.then(|| format!("avatars/{}", hash.to_ascii_lowercase()))
}
/// The cache key of an icon.
pub(crate) fn icon_key(id: u32) -> String {
format!("icons/{id}")
}
impl Cache {
/// A cache in `dir` (created when the first file arrives).
pub fn new(dir: impl Into<PathBuf>) -> Self {
Self { dir: Arc::new(dir.into()), index: Arc::default() }
}
/// The platform's cache directory (`<cache>/voelin/images`).
pub fn default_dir() -> PathBuf {
voelin_platform::paths::cache_dir().join("images")
}
pub fn dir(&self) -> &Path {
&self.dir
}
fn lock(&self) -> std::sync::MutexGuard<'_, Index> {
let mut index = self.index.lock().unwrap_or_else(PoisonError::into_inner);
if !index.scanned {
index.scanned = true;
scan(&self.dir, &mut index);
}
index
}
/// The file of `key` if it is cached (marked as used).
pub fn get(&self, key: &str) -> Option<PathBuf> {
let mut index = self.lock();
self.touch(&mut index, key)
}
fn touch(&self, index: &mut Index, key: &str) -> Option<PathBuf> {
let path = self.dir.join(key);
let tick = index.entries.get(key)?.tick;
if !path.is_file() {
// Deleted behind our back.
let entry = index.entries.remove(key)?;
index.lru.remove(&entry.tick);
index.total = index.total.saturating_sub(entry.size);
return None;
}
index.lru.remove(&tick);
let tick = index.next_tick;
index.next_tick += 1;
index.lru.insert(tick, key.to_owned());
if let Some(e) = index.entries.get_mut(key) {
e.tick = tick;
}
// The use time for the next run (best effort).
if let Ok(file) = std::fs::File::options().append(true).open(&path) {
let _ = file.set_modified(SystemTime::now());
}
Some(path)
}
/// Get `key`, downloading it once however many ask (see [`Fetch`]).
pub(crate) fn fetch(&self, key: &str, waiter: Waiter) -> Fetch {
let mut index = self.lock();
if let Some(path) = self.touch(&mut index, key) {
drop(index);
waiter(Ok(path));
return Fetch::Cached;
}
if let Some(waiters) = index.in_flight.get_mut(key) {
waiters.push(waiter);
return Fetch::Waiting;
}
index.in_flight.insert(key.to_owned(), vec![waiter]);
index.temp_serial += 1;
let temp = self.dir.join("tmp").join(format!(
"{}-{}-{}.part",
key.replace('/', "_"),
std::process::id(),
index.temp_serial
));
Fetch::Download(temp)
}
/// The download of `key` into `temp` ended; keep at most `max_bytes`
/// (0: no limit) and answer everyone waiting.
pub(crate) fn finish(
&self,
key: &str,
temp: &Path,
result: Result<(), String>,
max_bytes: u64,
) {
let result = result.and_then(|()| self.insert_file(key, temp, max_bytes));
let _ = std::fs::remove_file(temp);
let waiters = self.lock().in_flight.remove(key).unwrap_or_default();
for waiter in waiters {
waiter(result.clone());
}
}
/// Put a file we have (e.g. our own avatar) into the cache.
pub(crate) fn insert_copy(
&self,
key: &str,
from: &Path,
max_bytes: u64,
) -> Result<PathBuf, String> {
let temp = self.dir.join("tmp").join(format!("{}.copy", key.replace('/', "_")));
std::fs::create_dir_all(temp.parent().expect("tmp dir")).map_err(|e| e.to_string())?;
std::fs::copy(from, &temp).map_err(|e| e.to_string())?;
let result = self.insert_file(key, &temp, max_bytes);
let _ = std::fs::remove_file(&temp);
result
}
fn insert_file(&self, key: &str, temp: &Path, max_bytes: u64) -> Result<PathBuf, String> {
let path = self.dir.join(key);
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("cache: {e}"))?;
}
let size = std::fs::metadata(temp).map_err(|e| format!("cache: {e}"))?.len();
std::fs::rename(temp, &path).map_err(|e| format!("cache: {e}"))?;
let mut index = self.lock();
if let Some(old) = index.entries.remove(key) {
index.lru.remove(&old.tick);
index.total = index.total.saturating_sub(old.size);
}
let tick = index.next_tick;
index.next_tick += 1;
index.entries.insert(key.to_owned(), Entry { size, tick });
index.lru.insert(tick, key.to_owned());
index.total += size;
self.evict(&mut index, max_bytes, key);
Ok(path)
}
/// Remove least recently used files until the cache fits `max_bytes`
/// (never `keep`, the file just added).
fn evict(&self, index: &mut Index, max_bytes: u64, keep: &str) {
if max_bytes == 0 {
return;
}
while index.total > max_bytes {
let Some((&tick, key)) = index.lru.iter().find(|(_, k)| k.as_str() != keep) else {
break;
};
let key = key.clone();
index.lru.remove(&tick);
if let Some(entry) = index.entries.remove(&key) {
index.total = index.total.saturating_sub(entry.size);
}
if let Err(e) = std::fs::remove_file(self.dir.join(&key)) {
debug!("cache: cannot remove {key}: {e}");
}
}
}
/// Bytes in the cache.
pub fn size(&self) -> u64 {
self.lock().total
}
}
/// Index what is on disk, oldest use first; leftover temporary files go.
fn scan(dir: &Path, index: &mut Index) {
let _ = std::fs::remove_dir_all(dir.join("tmp"));
let mut found = Vec::new();
for sub in ["avatars", "icons"] {
let Ok(entries) = std::fs::read_dir(dir.join(sub)) else { continue };
for entry in entries.flatten() {
let Ok(meta) = entry.metadata() else { continue };
if !meta.is_file() {
continue;
}
let used = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH);
let key = format!("{sub}/{}", entry.file_name().to_string_lossy());
found.push((used, key, meta.len()));
}
}
found.sort();
for (_, key, size) in found {
let tick = index.next_tick;
index.next_tick += 1;
index.total += size;
index.lru.insert(tick, key.clone());
index.entries.insert(key, Entry { size, tick });
}
}
/// The engine's cache: one [`Cache`] that [`crate::Command::AttachCache`]
/// can replace, shared by the sessions.
#[derive(Clone, Debug)]
pub(crate) struct SharedCache(Arc<RwLock<Cache>>);
impl SharedCache {
pub fn new(cache: Cache) -> Self {
Self(Arc::new(RwLock::new(cache)))
}
pub fn current(&self) -> Cache {
self.0.read().unwrap_or_else(PoisonError::into_inner).clone()
}
pub fn replace(&self, cache: Cache) {
*self.0.write().unwrap_or_else(PoisonError::into_inner) = cache;
}
}
#[cfg(test)]
mod tests {
use std::sync::mpsc;
use super::*;
fn temp_dir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"voelin-cache-{tag}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = std::fs::remove_dir_all(&dir);
dir
}
/// Fetch `key` and write `bytes` as its download.
fn put(cache: &Cache, key: &str, bytes: usize, max: u64) -> PathBuf {
let (tx, rx) = mpsc::channel();
let Fetch::Download(temp) = cache.fetch(key, Box::new(move |r| tx.send(r).unwrap())) else {
panic!("{key} should download");
};
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
std::fs::write(&temp, vec![0u8; bytes]).unwrap();
cache.finish(key, &temp, Ok(()), max);
rx.recv().unwrap().unwrap()
}
#[test]
fn fetch_once_then_hit() {
let dir = temp_dir("fetch");
let cache = Cache::new(&dir);
let (tx, rx) = mpsc::channel();
let waiter = |tx: mpsc::Sender<_>| -> Waiter { Box::new(move |r| tx.send(r).unwrap()) };
let key = avatar_key("ABCDEF0123").unwrap();
assert_eq!(key, "avatars/abcdef0123");
let Fetch::Download(temp) = cache.fetch(&key, waiter(tx.clone())) else { panic!() };
// A second asker waits for the same download.
assert!(matches!(cache.fetch(&key, waiter(tx.clone())), Fetch::Waiting));
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
std::fs::write(&temp, b"png").unwrap();
cache.finish(&key, &temp, Ok(()), 0);
let a = rx.recv().unwrap().unwrap();
let b = rx.recv().unwrap().unwrap();
assert_eq!(a, b);
assert_eq!(std::fs::read(&a).unwrap(), b"png");
assert!(!temp.exists());
assert!(matches!(cache.fetch(&key, waiter(tx)), Fetch::Cached));
assert_eq!(rx.recv().unwrap().unwrap(), a);
assert_eq!(cache.get(&key), Some(a));
assert_eq!(cache.size(), 3);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn failed_download_answers_everyone_and_retries() {
let dir = temp_dir("fail");
let cache = Cache::new(&dir);
let (tx, rx) = mpsc::channel();
let tx2 = tx.clone();
let Fetch::Download(temp) = cache.fetch("icons/7", Box::new(move |r| tx.send(r).unwrap()))
else {
panic!()
};
assert!(matches!(
cache.fetch("icons/7", Box::new(move |r| tx2.send(r).unwrap())),
Fetch::Waiting
));
cache.finish("icons/7", &temp, Err("file not found".into()), 0);
assert_eq!(rx.recv().unwrap(), Err("file not found".into()));
assert_eq!(rx.recv().unwrap(), Err("file not found".into()));
assert!(cache.get("icons/7").is_none());
assert!(matches!(cache.fetch("icons/7", Box::new(|_| {})), Fetch::Download(_)));
}
#[test]
fn evicts_least_recently_used_and_survives_restart() {
let dir = temp_dir("lru");
let cache = Cache::new(&dir);
let a = put(&cache, "icons/1", 400, 1000);
let b = put(&cache, "icons/2", 400, 1000);
// `a` is used again: `b` is now the oldest.
assert_eq!(cache.get("icons/1"), Some(a.clone()));
let c = put(&cache, "icons/3", 400, 1000);
assert!(a.exists() && c.exists());
assert!(!b.exists(), "the least recently used file goes");
assert_eq!(cache.size(), 800);
// No limit: nothing goes.
put(&cache, "icons/4", 5000, 0);
assert_eq!(cache.size(), 5800);
// A new instance finds the files.
let again = Cache::new(&dir);
assert_eq!(again.size(), 5800);
assert_eq!(again.get("icons/3"), Some(c));
// A file bigger than the limit stays until the next one comes.
put(&again, "icons/5", 3000, 1000);
assert_eq!(again.size(), 3000);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn keys() {
assert!(avatar_key("").is_none());
assert!(avatar_key("../x").is_none());
assert_eq!(icon_key(4_294_967_295), "icons/4294967295");
}
}
+427
View File
@@ -0,0 +1,427 @@
//! Contacts: friends, blocked people and per-person settings, by unique id,
//! across all sessions.
//!
//! # Contract for the UI
//!
//! - [`crate::Command::SetContact`] adds or changes a contact (all fields;
//! `added_ms` 0 is set to now; `last_seen_*` and an empty nickname keep the stored
//! one), [`crate::Command::RemoveContact`] removes it. Both, and loading
//! the contacts of a newly attached database, emit
//! [`crate::Event::ContactsChanged`] with the full list;
//! [`crate::Engine::contacts`] reads it any time.
//! - [`crate::Event::FriendPresence`] tells where a friend is: every
//! session whose presence (voice, gateway or query) shows them, with
//! client, channel, away and streaming state; an empty list when they
//! left the last one. It comes when that changes, and for every friend
//! when the contacts change.
//! - Blocked contacts: their server and channel messages are reported with
//! [`voelin_model::ChatMessage::blocked`] set (live and from history);
//! their private messages and pokes are dropped or flagged per
//! `privacy.block_mode`.
//! - A contact's `muted` and `volume` apply to their voice in every session
//! (as [`crate::Command::SetClientMuted`] / `SetClientVolume` would).
//! - `stream.permissions = friends` accepts friends' requests to watch our
//! stream and asks for everyone else.
//!
//! Contacts live in the client database ([`crate::History`]'s, table
//! `contacts`), in memory for lookups. When a contact appears on or leaves a
//! server, `last_seen_ms` / `last_server` are updated (in one write per
//! presence change).
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::{Arc, Mutex, PoisonError};
use serde::Serialize;
use tokio::sync::{broadcast, watch};
use tracing::warn;
use voelin_model::{ChannelId, Presence};
use voelin_store::ContactSeen;
pub use voelin_store::{Contact, Relation};
use crate::history::{self, SharedHistory};
use crate::{Event, SessionId};
/// Where a friend is in one session.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct FriendSpot {
pub session: SessionId,
/// The server's name as the session sees it.
pub server_name: String,
pub client: u16,
pub nickname: String,
pub channel: ChannelId,
pub channel_name: String,
/// Away, with the message (empty without one).
pub away: Option<String>,
pub streaming: bool,
}
#[derive(Default)]
struct Inner {
contacts: HashMap<String, Contact>,
/// Last presence per session.
sessions: BTreeMap<SessionId, Arc<Presence>>,
/// Contacts present per session (for sightings).
present: HashMap<SessionId, HashSet<String>>,
/// Friends' spots as last reported (friends seen somewhere only).
reported: HashMap<String, Vec<FriendSpot>>,
}
/// See the [module docs](self). Cheap to clone.
#[derive(Clone)]
pub(crate) struct Contacts {
inner: Arc<Mutex<Inner>>,
events: broadcast::Sender<Event>,
history: SharedHistory,
/// Bumped on every change of the contacts, for sessions.
revision: watch::Sender<u64>,
}
impl Contacts {
pub fn new(events: broadcast::Sender<Event>, history: SharedHistory) -> Self {
Self { inner: Arc::default(), events, history, revision: watch::Sender::new(0) }
}
fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
self.inner.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Told on every change of the contacts.
pub fn watch(&self) -> watch::Receiver<u64> {
self.revision.subscribe()
}
pub fn list(&self) -> Vec<Contact> {
let mut list: Vec<_> = self.lock().contacts.values().cloned().collect();
list.sort_by(|a, b| a.uid.cmp(&b.uid));
list
}
pub fn get(&self, uid: &str) -> Option<Contact> {
self.lock().contacts.get(uid).cloned()
}
pub fn relation(&self, uid: &str) -> Relation {
self.lock().contacts.get(uid).map_or(Relation::Neutral, |c| c.relation)
}
pub fn is_blocked(&self, uid: Option<&str>) -> bool {
uid.is_some_and(|uid| self.relation(uid) == Relation::Blocked)
}
/// Read the contacts of the current database (after it was attached).
pub fn load(&self) {
let this = self.clone();
self.history.current().run_then(
false,
|s| s.contacts(),
move |result| match result {
Ok(list) => {
this.lock().contacts = list.into_iter().map(|c| (c.uid.clone(), c)).collect();
this.changed();
}
Err(e) => warn!("cannot read contacts: {e}"),
},
);
}
/// Add or change a contact.
pub fn set(&self, mut contact: Contact) {
{
let mut inner = self.lock();
if let Some(old) = inner.contacts.get(&contact.uid) {
if contact.added_ms == 0 {
contact.added_ms = old.added_ms;
}
if contact.nickname.is_empty() {
contact.nickname = old.nickname.clone();
}
contact.last_seen_ms = contact.last_seen_ms.max(old.last_seen_ms);
if contact.last_server.is_none() {
contact.last_server = old.last_server.clone();
}
}
if contact.added_ms == 0 {
contact.added_ms = history::now_ms();
}
inner.contacts.insert(contact.uid.clone(), contact.clone());
}
self.history.current().run_then(
false,
move |s| s.put_contact(&contact),
|r| {
if let Err(e) = r {
warn!("cannot store a contact: {e}");
}
},
);
self.changed();
}
pub fn remove(&self, uid: &str) {
if self.lock().contacts.remove(uid).is_none() {
return;
}
let uid = uid.to_owned();
self.history.current().run_then(
false,
move |s| s.delete_contact(&uid),
|r| {
if let Err(e) = r {
warn!("cannot remove a contact: {e}");
}
},
);
self.changed();
}
/// The contacts changed: tell the UI and the sessions, update friends.
fn changed(&self) {
self.revision.send_modify(|r| *r += 1);
let _ = self.events.send(Event::ContactsChanged { contacts: Arc::new(self.list()) });
self.update_friends(true);
}
/// A session published presence (empty when it has none).
pub fn presence(&self, session: SessionId, presence: Arc<Presence>) {
let now = history::now_ms();
let server = Some(presence.server_name.clone()).filter(|n| !n.is_empty());
let seen = {
let mut inner = self.lock();
let here: HashMap<&str, &str> = presence
.clients
.values()
.filter_map(|c| {
let uid = c.uid.as_deref()?;
inner.contacts.contains_key(uid).then_some((uid, c.nickname.as_str()))
})
.collect();
let before = inner.present.remove(&session).unwrap_or_default();
// Sightings: contacts that came or went.
let mut seen: Vec<ContactSeen> = Vec::new();
for (uid, nick) in &here {
if !before.contains(*uid) {
seen.push(ContactSeen {
uid: (*uid).to_owned(),
nickname: (*nick).to_owned(),
ts_ms: now,
server: server.clone(),
});
}
}
for uid in before.iter().filter(|u| !here.contains_key(u.as_str())) {
seen.push(ContactSeen {
uid: uid.clone(),
nickname: String::new(),
ts_ms: now,
server: server.clone(),
});
}
for s in &seen {
if let Some(c) = inner.contacts.get_mut(&s.uid) {
c.last_seen_ms = c.last_seen_ms.max(now);
if server.is_some() {
c.last_server = server.clone();
}
if !s.nickname.is_empty() {
c.nickname = s.nickname.clone();
}
}
}
let present = here.keys().map(|u| (*u).to_owned()).collect();
inner.present.insert(session, present);
inner.sessions.insert(session, presence);
seen
};
if !seen.is_empty() {
self.history.current().run_then(
false,
move |s| s.touch_contacts(&seen),
|r| {
if let Err(e) = r {
warn!("cannot store when contacts were seen: {e}");
}
},
);
}
self.update_friends(false);
}
/// A session ended: its friends are gone from it.
pub fn session_closed(&self, session: SessionId) {
self.presence(session, Arc::new(Presence::default()));
{
let mut inner = self.lock();
inner.sessions.remove(&session);
inner.present.remove(&session);
}
self.update_friends(false);
}
/// Report friends whose spots changed (every friend with `all`).
fn update_friends(&self, all: bool) {
let mut out: Vec<(String, Vec<FriendSpot>)> = Vec::new();
{
let inner = &mut *self.lock();
let friends: HashSet<String> = inner
.contacts
.values()
.filter(|c| c.relation == Relation::Friend)
.map(|c| c.uid.clone())
.collect();
let mut now: HashMap<String, Vec<FriendSpot>> = HashMap::new();
for (session, presence) in &inner.sessions {
for (uid, spot) in spots_in(*session, presence, &friends) {
now.entry(uid).or_default().push(spot);
}
}
let mut uids: HashSet<String> = now.keys().cloned().collect();
uids.extend(inner.reported.keys().cloned());
if all {
uids.extend(friends.iter().cloned());
}
for uid in uids {
let spots = now.remove(&uid).unwrap_or_default();
let before = inner.reported.get(&uid);
if !all && before.map_or(spots.is_empty(), |b| *b == spots) {
continue;
}
if spots.is_empty() {
inner.reported.remove(&uid);
} else {
inner.reported.insert(uid.clone(), spots.clone());
}
out.push((uid, spots));
}
}
out.sort_by(|a, b| a.0.cmp(&b.0));
for (uid, sessions) in out {
let _ = self.events.send(Event::FriendPresence { uid, sessions });
}
}
}
/// Friends' spots in one session's presence.
fn spots_in(
session: SessionId,
presence: &Presence,
friends: &HashSet<String>,
) -> HashMap<String, FriendSpot> {
let mut spots = HashMap::new();
for c in presence.clients.values() {
let Some(uid) = c.uid.as_ref().filter(|u| friends.contains(*u)) else { continue };
// Several connections of one identity: the first.
spots.entry(uid.clone()).or_insert_with(|| FriendSpot {
session,
server_name: presence.server_name.clone(),
client: c.id,
nickname: c.nickname.clone(),
channel: c.channel,
channel_name: presence
.channels
.get(&c.channel)
.map(|ch| ch.name.clone())
.unwrap_or_default(),
away: c.away.clone(),
streaming: c.streaming.unwrap_or(false),
});
}
spots
}
#[cfg(test)]
mod tests {
use voelin_model::{ChannelInfo, ClientInfo};
use super::*;
use crate::History;
fn presence(server: &str, clients: &[(u16, &str, &str)]) -> Arc<Presence> {
let mut p = Presence { server_name: server.into(), ..Presence::default() };
p.channels.insert(1, ChannelInfo { id: 1, name: "Lobby".into(), ..Default::default() });
for (id, uid, nick) in clients {
let c = ClientInfo {
id: *id,
uid: Some((*uid).into()),
nickname: (*nick).into(),
channel: 1,
..Default::default()
};
p.clients.insert(*id, c);
}
Arc::new(p)
}
fn friend(uid: &str) -> Contact {
Contact { relation: Relation::Friend, ..Contact::new(uid) }
}
type Spots = Vec<(SessionId, u16)>;
/// The friend events so far: uid and (session, client) per spot.
fn friend_events(rx: &mut broadcast::Receiver<Event>) -> Vec<(String, Spots)> {
let mut out = Vec::new();
while let Ok(e) = rx.try_recv() {
if let Event::FriendPresence { uid, sessions } = e {
out.push((uid, sessions.iter().map(|s| (s.session, s.client)).collect()));
}
}
out
}
#[tokio::test]
async fn friends_across_sessions() {
let (events, mut rx) = broadcast::channel(64);
let history = SharedHistory::new(History::in_memory());
let contacts = Contacts::new(events, history.clone());
contacts.set(friend("f="));
contacts.set(Contact { relation: Relation::Blocked, ..Contact::new("b=") });
assert_eq!(contacts.relation("b="), Relation::Blocked);
assert!(contacts.is_blocked(Some("b=")));
assert!(!contacts.is_blocked(Some("f=")) && !contacts.is_blocked(None));
// Changing the contacts reports every friend (offline here).
assert!(friend_events(&mut rx).contains(&("f=".into(), vec![])));
contacts.presence(1, presence("A", &[(5, "f=", "Fred"), (6, "x=", "X")]));
assert_eq!(friend_events(&mut rx), [("f=".into(), vec![(1, 5)])]);
// Nothing new: nothing reported.
contacts.presence(1, presence("A", &[(5, "f=", "Fred"), (7, "y=", "Y")]));
assert!(friend_events(&mut rx).is_empty());
contacts.presence(2, presence("B", &[(9, "f=", "Fred")]));
assert_eq!(friend_events(&mut rx), [("f=".into(), vec![(1, 5), (2, 9)])]);
contacts.session_closed(1);
assert_eq!(friend_events(&mut rx), [("f=".into(), vec![(2, 9)])]);
// No friend any more: reported gone.
contacts.set(Contact::new("f="));
assert!(friend_events(&mut rx).contains(&("f=".into(), vec![])));
// Sightings reach the database.
history.current().flush();
let stored = history.current().run(false, |s| s.contact("f=")).await.unwrap().unwrap();
assert_eq!(stored.last_server.as_deref(), Some("B"));
assert_eq!(stored.nickname, "Fred");
assert!(stored.last_seen_ms > 0 && stored.added_ms > 0);
}
#[tokio::test]
async fn load_and_remove() {
let (events, mut rx) = broadcast::channel(64);
let history = SharedHistory::new(History::in_memory());
history.current().run(false, |s| s.put_contact(&friend("a="))).await.unwrap();
let contacts = Contacts::new(events, history.clone());
let mut revision = contacts.watch();
contacts.load();
let loaded = loop {
if let Event::ContactsChanged { contacts } = rx.recv().await.unwrap() {
break contacts;
}
};
assert_eq!(loaded.len(), 1);
assert!(revision.has_changed().unwrap());
revision.mark_unchanged();
contacts.remove("a=");
assert!(revision.has_changed().unwrap());
assert!(contacts.list().is_empty());
assert!(history.current().run(false, |s| s.contacts()).await.unwrap().is_empty());
}
}
+482
View File
@@ -0,0 +1,482 @@
//! Files in channels, avatars and icons (voice connection, TeamSpeak 3 and 6).
//!
//! # Contract for the UI
//!
//! File browser requests carry a [`RequestId`] the caller picks, transfers
//! a [`TransferId`]; answers carry them back:
//!
//! - [`crate::Command::ListFiles`] → [`crate::Event::FileList`] (an empty
//! directory is an empty list, not an error).
//! - [`crate::Command::DeleteFiles`], [`crate::Command::RenameFile`],
//! [`crate::Command::CreateDirectory`] → [`crate::Event::RequestDone`].
//! - [`crate::Command::DownloadFile`], [`crate::Command::DownloadChatFile`]
//! (a file linked in chat, [`voelin_model::FileRef`]),
//! [`crate::Command::UploadFile`] → [`crate::Event::Transfer`]:
//! `Requested`, `Started`, `Progress` (every `files.progress_interval_ms`),
//! then `Done`, `Failed` or `Cancelled` ([`crate::Command::CancelTransfer`]).
//!
//! Downloads stream to disk: into `<path>.part`, renamed to `<path>` when
//! complete (with `resume`, an existing `.part` is continued). Downloads
//! into memory ([`DownloadTo::Memory`]) come back in `Done`. Uploads read
//! the file as they send it. There is no size limit besides the server's
//! quotas.
//!
//! Paths on the server start with `/` (`/docs/report.pdf`); channel 0 holds
//! the server's avatars and icons.
//!
//! Avatars and icons are fetched by themselves (setting
//! `cache.fetch_images`) into the engine's cache ([`crate::cache`]):
//! [`crate::Event::AvatarReady`] when a client's avatar is there (again when
//! its hash changes), [`crate::Event::IconReady`] for every icon a server,
//! group, channel or client uses (ids below 1000 are built into clients and
//! never downloaded). [`crate::Command::SetAvatar`] uploads our own.
use std::fmt;
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;
/// Picked by the caller; the answer carries it back.
pub type RequestId = u64;
/// Picked by the caller; the transfer's events carry it.
pub type TransferId = u64;
/// One entry of a directory listing.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct FileEntry {
pub name: String,
/// Bytes (0 for directories).
pub size: u64,
/// Unix seconds of the last change.
pub modified_s: i64,
pub is_dir: bool,
}
/// Bytes of a download into memory.
#[derive(Clone, PartialEq, Eq)]
pub struct Bytes(pub Arc<[u8]>);
impl fmt::Debug for Bytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Bytes({} bytes)", self.0.len())
}
}
/// Where a download goes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DownloadTo {
/// A file (written as `<path>.part` until complete). `resume`: continue
/// an existing `.part`.
Path { path: PathBuf, resume: bool },
/// Memory: the bytes come in [`TransferState::Done`].
Memory,
}
/// A transfer's progress.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TransferState {
/// Asked the server.
Requested,
/// Data flows; `offset` bytes were there before (resume).
Started {
size: u64,
offset: u64,
},
Progress {
done: u64,
size: u64,
},
Done {
size: u64,
path: Option<PathBuf>,
data: Option<Bytes>,
},
Failed(String),
Cancelled,
}
impl TransferState {
pub fn is_final(&self) -> bool {
matches!(self, Self::Done { .. } | Self::Failed(_) | Self::Cancelled)
}
}
/// Reports a transfer's states.
pub(crate) type Report = Arc<dyn Fn(TransferState) + Send + Sync>;
/// Where a running download writes.
#[derive(Clone, Debug)]
pub(crate) enum Sink {
/// Write `part` (appending with `append`), then rename it to `dest`.
File {
part: PathBuf,
dest: PathBuf,
append: bool,
},
Memory,
}
impl Sink {
pub fn from_target(to: &DownloadTo) -> Self {
match to {
DownloadTo::Path { path, resume } => {
let mut part = path.clone().into_os_string();
part.push(".part");
Sink::File { part: part.into(), dest: path.clone(), append: *resume }
}
DownloadTo::Memory => Sink::Memory,
}
}
/// Bytes already there to resume from.
pub fn offset(&self) -> u64 {
match self {
Sink::File { part, append: true, .. } => std::fs::metadata(part).map_or(0, |m| m.len()),
_ => 0,
}
}
/// The partial file to remove when a transfer is cancelled.
pub fn part(&self) -> Option<&Path> {
match self {
Sink::File { part, .. } => Some(part),
Sink::Memory => None,
}
}
}
/// Rate limit for progress reports.
struct Progress<'a> {
report: &'a Report,
every: Duration,
last: Instant,
}
impl Progress<'_> {
fn update(&mut self, done: u64, size: u64) {
if self.last.elapsed() >= self.every {
self.last = Instant::now();
(self.report)(TransferState::Progress { done, size });
}
}
}
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,
size: u64,
offset: u64,
sink: Sink,
progress_every: Duration,
report: Report,
) {
report(TransferState::Started { size, offset });
let result = receive(&mut stream, size, offset, &sink, progress_every, &report).await;
report(match result {
Ok(done) => done,
Err(e) => TransferState::Failed(e),
});
}
async fn receive(
stream: &mut TcpStream,
size: u64,
offset: u64,
sink: &Sink,
progress_every: Duration,
report: &Report,
) -> Result<TransferState, String> {
let mut progress = Progress { report, every: progress_every, last: Instant::now() };
let mut buf = vec![0u8; CHUNK];
let mut done = offset;
match sink {
Sink::File { part, dest, append } => {
if let Some(dir) = part.parent().filter(|d| !d.as_os_str().is_empty()) {
tokio::fs::create_dir_all(dir)
.await
.map_err(|e| format!("{}: {e}", dir.display()))?;
}
let mut file = tokio::fs::OpenOptions::new()
.create(true)
.write(true)
.append(*append)
.truncate(!*append)
.open(part)
.await
.map_err(|e| format!("{}: {e}", part.display()))?;
let received = async {
while done < size {
let n = stream.read(&mut buf).await.map_err(|e| e.to_string())?;
if n == 0 {
return Err(format!("connection closed after {done} of {size} bytes"));
}
let data = &buf[..n];
file.write_all(data).await.map_err(|e| format!("{}: {e}", part.display()))?;
done += n as u64;
progress.update(done, size);
}
Ok(())
}
.await;
// What arrived stays in the part (to resume), also after an error.
let flushed = file.flush().await.map_err(|e| e.to_string());
drop(file);
received?;
flushed?;
if part != dest {
tokio::fs::rename(part, dest)
.await
.map_err(|e| format!("{}: {e}", dest.display()))?;
}
Ok(TransferState::Done { size, path: Some(dest.clone()), data: None })
}
Sink::Memory => {
let mut data = Vec::with_capacity(usize::try_from(size).unwrap_or(0).min(1 << 24));
while done < size {
let n = stream.read(&mut buf).await.map_err(|e| e.to_string())?;
if n == 0 {
return Err(format!("connection closed after {done} of {size} bytes"));
}
data.extend_from_slice(&buf[..n]);
done += n as u64;
progress.update(done, size);
}
Ok(TransferState::Done { size, path: None, data: Some(Bytes(data.into())) })
}
}
}
/// Send `file` from `offset` (`size` bytes in total). Reports `Started`,
/// `Progress` and the final state.
pub(crate) async fn upload(
mut stream: TcpStream,
file: PathBuf,
size: u64,
offset: u64,
progress_every: Duration,
report: Report,
) {
report(TransferState::Started { size, offset });
let result = send(&mut stream, &file, size, offset, progress_every, &report).await;
report(match result {
Ok(()) => TransferState::Done { size, path: Some(file), data: None },
Err(e) => TransferState::Failed(e),
});
}
async fn send(
stream: &mut TcpStream,
path: &Path,
size: u64,
offset: u64,
progress_every: Duration,
report: &Report,
) -> Result<(), String> {
let mut progress = Progress { report, every: progress_every, last: Instant::now() };
let mut file =
tokio::fs::File::open(path).await.map_err(|e| format!("{}: {e}", path.display()))?;
if offset > 0 {
file.seek(std::io::SeekFrom::Start(offset)).await.map_err(|e| e.to_string())?;
}
let mut buf = vec![0u8; CHUNK];
let mut done = offset;
while done < size {
let want = usize::try_from(size - done).unwrap_or(CHUNK).min(CHUNK);
let n =
file.read(&mut buf[..want]).await.map_err(|e| format!("{}: {e}", path.display()))?;
if n == 0 {
return Err(format!("{} shrank while uploading", path.display()));
}
stream.write_all(&buf[..n]).await.map_err(|e| e.to_string())?;
done += n as u64;
progress.update(done, size);
}
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(())
}
/// A file's MD5 (hex), as `client_flag_avatar` names an avatar.
pub(crate) fn md5_file(path: &Path) -> std::io::Result<String> {
use std::io::Read;
let mut file = std::fs::File::open(path)?;
let mut ctx = md5::Context::new();
let mut buf = vec![0u8; CHUNK];
loop {
let n = file.read(&mut buf)?;
if n == 0 {
break;
}
ctx.consume(&buf[..n]);
}
Ok(format!("{:x}", ctx.finalize()))
}
/// The avatar file of a client on the server: `/avatar_` and the unique
/// id's bytes as letters `a` to `p` (one per nibble), as TeamSpeak 3 and 6
/// servers store them (verified against 3.13.8 and 6.0.0-beta13.1).
pub fn avatar_path(uid: &str) -> Option<String> {
use base64::Engine;
let bytes = base64::engine::general_purpose::STANDARD.decode(uid.trim()).ok()?;
let mut path = String::with_capacity(8 + bytes.len() * 2);
path.push_str("/avatar_");
for b in bytes {
path.push(char::from(b'a' + (b >> 4)));
path.push(char::from(b'a' + (b & 0x0f)));
}
Some(path)
}
/// The file of an icon on the server.
pub fn icon_path(id: u32) -> String {
format!("/icon_{id}")
}
/// Icons below this id are built into clients (group icons 100 to 600).
pub const FIRST_DOWNLOADABLE_ICON: u32 = 1000;
/// `dir` and `name` joined as a server path (`/dir/name`).
pub fn join_path(dir: &str, name: &str) -> String {
let dir = dir.trim_end_matches('/');
let name = name.trim_start_matches('/');
format!("{dir}/{name}")
}
/// A server path in the form the server echoes (`/` for the root, no
/// trailing slash otherwise).
pub(crate) fn normalize_dir(path: &str) -> String {
let trimmed = path.trim_end_matches('/');
if trimmed.is_empty() {
"/".into()
} else if trimmed.starts_with('/') {
trimmed.into()
} else {
format!("/{trimmed}")
}
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use tokio::net::TcpListener;
use super::*;
#[test]
fn avatar_paths() {
// Two bytes 0x01 0xfe: "ab" "po".
assert_eq!(avatar_path("Af4=").as_deref(), Some("/avatar_abpo"));
assert_eq!(avatar_path("not base64!"), None);
assert_eq!(icon_path(123456), "/icon_123456");
}
#[test]
fn paths() {
assert_eq!(join_path("/", "a.txt"), "/a.txt");
assert_eq!(join_path("/docs/", "/a.txt"), "/docs/a.txt");
assert_eq!(normalize_dir(""), "/");
assert_eq!(normalize_dir("/docs/"), "/docs");
assert_eq!(normalize_dir("docs"), "/docs");
}
fn temp(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("voelin-files-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn recorder() -> (Report, Arc<Mutex<Vec<TransferState>>>) {
let states = Arc::new(Mutex::new(Vec::new()));
let s = states.clone();
(Arc::new(move |state| s.lock().unwrap().push(state)), states)
}
/// A server that sends `data` on the first connection.
async fn serve(data: Vec<u8>) -> std::net::SocketAddr {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
let (mut s, _) = listener.accept().await.unwrap();
s.write_all(&data).await.unwrap();
});
addr
}
#[tokio::test]
async fn downloads_to_disk_and_resumes() {
let dir = temp("download");
let dest = dir.join("sub/file.bin");
let data: Vec<u8> = (0..200_000u32).map(|i| i as u8).collect();
// First half: the connection ends early; the part stays.
let addr = serve(data[..100_000].to_vec()).await;
let (report, states) = recorder();
let target = DownloadTo::Path { path: dest.clone(), resume: false };
let sink = Sink::from_target(&target);
let stream = TcpStream::connect(addr).await.unwrap();
download(stream, data.len() as u64, 0, sink, Duration::ZERO, report).await;
let last = states.lock().unwrap().last().cloned().unwrap();
assert!(matches!(last, TransferState::Failed(ref e) if e.contains("100000 of 200000")));
assert!(!dest.exists());
// Resume: the rest.
let target = DownloadTo::Path { path: dest.clone(), resume: true };
let sink = Sink::from_target(&target);
assert_eq!(sink.offset(), 100_000);
let addr = serve(data[100_000..].to_vec()).await;
let (report, states) = recorder();
let stream = TcpStream::connect(addr).await.unwrap();
download(stream, data.len() as u64, 100_000, sink, Duration::ZERO, report).await;
let states = states.lock().unwrap().clone();
assert_eq!(states[0], TransferState::Started { size: 200_000, offset: 100_000 });
assert!(states.iter().any(|s| matches!(s, TransferState::Progress { .. })));
assert_eq!(
states.last().unwrap(),
&TransferState::Done { size: 200_000, path: Some(dest.clone()), data: None }
);
assert_eq!(std::fs::read(&dest).unwrap(), data);
std::fs::remove_dir_all(dir).unwrap();
}
#[tokio::test]
async fn downloads_to_memory() {
let addr = serve(b"hello".to_vec()).await;
let (report, states) = recorder();
let stream = TcpStream::connect(addr).await.unwrap();
download(stream, 5, 0, Sink::Memory, Duration::from_secs(60), report).await;
let last = states.lock().unwrap().last().cloned().unwrap();
let TransferState::Done { data: Some(Bytes(data)), .. } = last else { panic!("{last:?}") };
assert_eq!(&*data, b"hello");
}
#[tokio::test]
async fn uploads_from_offset() {
let dir = temp("upload");
let file = dir.join("up.bin");
std::fs::write(&file, b"0123456789").unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (mut s, _) = listener.accept().await.unwrap();
let mut got = Vec::new();
s.read_to_end(&mut got).await.unwrap();
got
});
let (report, states) = recorder();
let stream = TcpStream::connect(addr).await.unwrap();
upload(stream, file.clone(), 10, 4, Duration::ZERO, report).await;
assert_eq!(server.await.unwrap(), b"456789");
assert!(matches!(states.lock().unwrap().last(), Some(TransferState::Done { .. })));
assert_eq!(md5_file(&file).unwrap(), "781e5e245d69b566979b86e28d23f2c7");
std::fs::remove_dir_all(dir).unwrap();
}
}
+3 -3
View File
@@ -65,7 +65,7 @@ pub(crate) enum GatewayCmd {
pub(crate) enum GatewayEvent {
/// Logged in; requests go through `client`.
Connected(GatewayClient),
Presence(Presence),
Presence(Box<Presence>),
/// A push other than presence.
Push(Box<Push>),
Disconnected(Option<String>),
@@ -132,11 +132,11 @@ async fn run_inner(
Some(Push::Disconnected(Some(reason))) => anyhow::bail!(reason),
Some(Push::PresenceSnapshot(snapshot)) => {
presence = Presence::from_snapshot(snapshot);
let _ = events.send(GatewayEvent::Presence(presence.clone()));
let _ = events.send(GatewayEvent::Presence(Box::new(presence.clone())));
}
Some(Push::PresenceDelta(delta)) => {
presence.apply(&delta);
let _ = events.send(GatewayEvent::Presence(presence.clone()));
let _ = events.send(GatewayEvent::Presence(Box::new(presence.clone())));
}
// Answers to requests sent without waiting.
Some(Push::Other(_) | Push::Error { code: ErrorCode::UnknownType, .. }) => {}
+11 -1
View File
@@ -62,6 +62,7 @@ pub use voelin_store::MessageSource;
use voelin_store::{ChatCursor, WriteOutcome};
use voelin_store::{NewMessage, PageQuery, Reaction, RemoteInfo, Store, StoredMessage, Written};
use crate::contacts::Contacts;
use crate::gateway::{GatewayClient, GatewayUpdate};
use crate::settings::{CHAT_DEDUPE_TOLERANCE_MS, CHAT_HISTORY_PAGE, CHAT_STORE_HISTORY, Settings};
use crate::{Event, SessionId};
@@ -472,6 +473,8 @@ pub(crate) struct ChatCtx {
pub settings: Settings,
/// The key of the server's history.
pub server_uid: String,
/// Messages of blocked contacts are flagged.
pub contacts: Contacts,
}
impl ChatCtx {
@@ -500,6 +503,10 @@ impl ChatCtx {
source: HistorySource,
complete: bool,
) {
let mut messages = messages;
for m in &mut messages {
m.message.blocked = self.contacts.is_blocked(m.message.author_uid.as_deref());
}
self.emit(Event::ChatHistory {
session: self.session,
target: target.clone(),
@@ -524,12 +531,15 @@ impl ChatCtx {
/// [`HistorySource::Live`] from the writer thread.
pub fn store_live(&self, messages: Vec<NewMessage>) {
let (session, events) = (self.session, self.events.clone());
let contacts = self.contacts.clone();
self.history.write(self.memory(), messages, self.tolerance_ms(), move |result| {
for w in result.unwrap_or_default() {
if w.outcome == WriteOutcome::Unchanged {
continue;
}
let message = HistoryMessage::from(w.message);
let mut message = HistoryMessage::from(w.message);
message.message.blocked =
contacts.is_blocked(message.message.author_uid.as_deref());
let _ = events.send(Event::ChatHistory {
session,
target: message.message.target.clone(),
+299 -23
View File
@@ -32,12 +32,24 @@
//! (pins, reactions, topics, events, stream directory, activity,
//! administration) are [`Command::Gateway`] requests and
//! [`Event::Gateway`] updates ([`gateway`]).
//!
//! The voice connection also carries pokes ([`Command::Poke`],
//! [`Event::Poke`]), private messages to any client (a
//! [`ChatTarget::Private`] chat, stored under the peer's unique id), the
//! channels' file browsers, avatars and icons ([`files`], cached in
//! [`cache`]) and offline messages ([`offline`]). Contacts (friends,
//! blocked people, per-person volume) are engine-wide ([`contacts`]).
mod audio;
mod book;
pub mod cache;
pub mod contacts;
pub mod files;
pub mod gateway;
pub mod history;
#[cfg(feature = "media")]
pub mod media;
pub mod offline;
mod query;
mod route;
mod session;
@@ -46,17 +58,27 @@ pub mod stream;
mod voice;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::{broadcast, mpsc};
pub use voelin_audio::settings::TransmitMode;
pub use voelin_audio::{AudioSettings, ProcessingSettings, VadSettings};
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
use voelin_model::{
Capabilities, ChannelId, ChatMessage, ChatTarget, FileRef, GroupInfo, Presence, ServerDetails,
ServerFlavor,
};
use crate::audio::{AudioEvent, AudioHandle, AudioIn};
pub use cache::Cache;
use cache::SharedCache;
use contacts::Contacts;
pub use contacts::{Contact, FriendSpot, Relation};
pub use files::{Bytes, DownloadTo, FileEntry, RequestId, TransferId, TransferState};
pub use gateway::{GatewayRequest, GatewayUpdate};
use history::SharedHistory;
pub use history::{History, HistoryMessage, HistorySource};
pub use offline::{OfflineMessage, OfflineMessageInfo};
pub use route::{ChatRoute, Dedup, route_chat};
use settings::{SettingChange, Settings, SharedSettings};
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
@@ -223,10 +245,141 @@ pub enum Command {
stream_id: String,
volume: f32,
},
/// Poke a client (voice): the server shows it a notification with
/// `message`. Failures come as [`Event::Error`].
Poke {
session: SessionId,
client: u16,
message: String,
},
/// List a directory of a channel's files (voice; `path` `/` for the
/// root), answered with [`Event::FileList`]. See [`files`].
ListFiles {
session: SessionId,
request: RequestId,
channel: ChannelId,
password: Option<String>,
path: String,
},
/// Download a channel's file (`path` like `/dir/name`); progress as
/// [`Event::Transfer`].
DownloadFile {
session: SessionId,
transfer: TransferId,
channel: ChannelId,
password: Option<String>,
path: String,
to: DownloadTo,
},
/// Download a file linked in chat ([`ChatMessage::file_refs`]); fails if
/// the link names another server.
DownloadChatFile {
session: SessionId,
transfer: TransferId,
file: FileRef,
password: Option<String>,
to: DownloadTo,
},
/// Upload a local file as `path` in a channel; progress as
/// [`Event::Transfer`]. `resume` continues a partial upload.
UploadFile {
session: SessionId,
transfer: TransferId,
channel: ChannelId,
password: Option<String>,
path: String,
from: PathBuf,
overwrite: bool,
resume: bool,
},
/// Stop a transfer ([`TransferState::Cancelled`]); a partial download is
/// deleted.
CancelTransfer {
session: SessionId,
transfer: TransferId,
},
/// Delete files or directories of a channel ([`Event::RequestDone`]).
DeleteFiles {
session: SessionId,
request: RequestId,
channel: ChannelId,
password: Option<String>,
paths: Vec<String>,
},
/// Rename or move a file, also into another channel
/// (`to_channel`: channel and its password) ([`Event::RequestDone`]).
RenameFile {
session: SessionId,
request: RequestId,
channel: ChannelId,
password: Option<String>,
from: String,
to: String,
to_channel: Option<(ChannelId, Option<String>)>,
},
CreateDirectory {
session: SessionId,
request: RequestId,
channel: ChannelId,
password: Option<String>,
path: String,
},
/// Our avatar (voice): upload `image` and announce it, or remove it
/// (`None`) ([`Event::RequestDone`]).
SetAvatar {
session: SessionId,
request: RequestId,
image: Option<PathBuf>,
},
/// Report a client's avatar again ([`Event::AvatarReady`]), fetching it
/// if needed (avatars are also fetched by themselves, setting
/// `cache.fetch_images`).
FetchAvatar {
session: SessionId,
client_uid: String,
},
/// Our offline messages ([`Event::OfflineMessages`]); see [`offline`].
ListOfflineMessages {
session: SessionId,
request: RequestId,
},
GetOfflineMessage {
session: SessionId,
request: RequestId,
id: u32,
},
SendOfflineMessage {
session: SessionId,
request: RequestId,
to_uid: String,
subject: String,
text: String,
},
DeleteOfflineMessage {
session: SessionId,
request: RequestId,
id: u32,
},
SetOfflineMessageRead {
session: SessionId,
request: RequestId,
id: u32,
read: bool,
},
/// Close everything of a session.
CloseSession {
session: SessionId,
},
/// Add or change a contact (engine-wide; see [`contacts`]).
SetContact {
contact: Box<Contact>,
},
RemoveContact {
uid: String,
},
/// Keep avatars and icons in this directory from now on (default:
/// [`Cache::default_dir`]).
AttachCache(PathBuf),
/// Set a setting's runtime value (see [`settings`]); invalid values are
/// reported as [`Event::SettingRejected`].
SetSetting {
@@ -404,6 +557,87 @@ pub enum Event {
key: String,
message: String,
},
/// The server's details changed (also in [`Presence::server`]; voice).
ServerDetails {
session: SessionId,
details: Arc<ServerDetails>,
},
/// The server or channel groups changed (also in the presence; voice),
/// in display order.
Groups {
session: SessionId,
server_groups: Arc<Vec<GroupInfo>>,
channel_groups: Arc<Vec<GroupInfo>>,
},
/// Someone poked us. With `blocked` (their contact is blocked,
/// `privacy.block_mode = flag`); with `hide` it never comes.
Poke {
session: SessionId,
from: u16,
from_uid: Option<String>,
from_name: String,
message: String,
blocked: bool,
},
/// Answer to [`Command::ListFiles`].
FileList {
session: SessionId,
request: RequestId,
channel: ChannelId,
/// The listed directory (`/` or `/dir`, no trailing slash).
path: String,
result: Result<Vec<FileEntry>, String>,
},
/// A transfer's progress ([`Command::DownloadFile`], `UploadFile`, …).
Transfer {
session: SessionId,
transfer: TransferId,
state: TransferState,
},
/// Answer to a request without data (file operations, avatar, offline
/// messages).
RequestDone {
session: SessionId,
request: RequestId,
result: Result<(), String>,
},
/// A client's avatar is in the cache: `path`, its MD5 `hash`
/// ([`voelin_model::ClientInfo::avatar`]). Comes when the client appears
/// with an avatar and when it changes.
AvatarReady {
session: SessionId,
client_uid: String,
path: PathBuf,
hash: String,
},
/// An icon (server, group, channel or client) is in the cache.
IconReady {
session: SessionId,
icon: u32,
path: PathBuf,
},
/// Answer to [`Command::ListOfflineMessages`].
OfflineMessages {
session: SessionId,
request: RequestId,
result: Result<Vec<OfflineMessageInfo>, String>,
},
/// Answer to [`Command::GetOfflineMessage`].
OfflineMessage {
session: SessionId,
request: RequestId,
result: Result<OfflineMessage, String>,
},
/// All contacts, after every change.
ContactsChanged {
contacts: Arc<Vec<Contact>>,
},
/// Where a friend is now: one spot per session that sees them (empty:
/// nowhere).
FriendPresence {
uid: String,
sessions: Vec<FriendSpot>,
},
}
/// Handle to the engine. Cheap to clone; all methods are non-blocking.
@@ -413,8 +647,7 @@ pub struct Engine {
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
runtime: tokio::runtime::Handle,
settings: SharedSettings,
history: SharedHistory,
shared: Shared,
}
impl Engine {
@@ -436,29 +669,37 @@ impl Engine {
let (events, _) = broadcast::channel(4096);
// About a minute of one watched stream.
let (frames, _) = broadcast::channel(4096);
let settings = SharedSettings::new(settings);
let history = SharedHistory::new(history);
let shared = Shared { settings: settings.clone(), history: history.clone() };
tokio::spawn(run(rx, events.clone(), frames.clone(), shared));
Self {
commands,
events,
frames,
runtime: tokio::runtime::Handle::current(),
settings,
let shared = Shared {
settings: SharedSettings::new(settings),
contacts: Contacts::new(events.clone(), history.clone()),
history,
}
cache: SharedCache::new(Cache::new(Cache::default_dir())),
};
shared.contacts.load();
tokio::spawn(run(rx, events.clone(), frames.clone(), shared.clone()));
Self { commands, events, frames, runtime: tokio::runtime::Handle::current(), shared }
}
/// The chat history the engine uses.
pub fn history(&self) -> History {
self.history.current()
self.shared.history.current()
}
/// The settings the engine uses (read, watch or change them directly;
/// changes are reported as [`Event::SettingChanged`] all the same).
pub fn settings(&self) -> Settings {
self.settings.current()
self.shared.settings.current()
}
/// All contacts (as the last [`Event::ContactsChanged`] told).
pub fn contacts(&self) -> Vec<Contact> {
self.shared.contacts.list()
}
/// The avatar and icon cache the engine uses.
pub fn cache(&self) -> Cache {
self.shared.cache.current()
}
/// The runtime the engine runs on, for helpers started from other
@@ -492,9 +733,12 @@ enum Input {
}
/// What the engine and its sessions share and commands can replace.
struct Shared {
settings: SharedSettings,
history: SharedHistory,
#[derive(Clone)]
pub(crate) struct Shared {
pub settings: SharedSettings,
pub history: SharedHistory,
pub cache: SharedCache,
pub contacts: Contacts,
}
/// Delete chat history past `chat.retention_days` (0: keep everything).
@@ -516,9 +760,9 @@ async fn run(
mut commands: mpsc::UnboundedReceiver<Command>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
shared: Shared,
engine: Shared,
) {
let Shared { settings: shared, history } = shared;
let Shared { settings: shared, history, cache, contacts } = engine.clone();
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
let mut current = shared.current();
// Pruning: at start, then hourly (and when the setting changes).
@@ -606,6 +850,20 @@ async fn run(
Command::AttachHistory(new) => {
history.replace(new.clone());
prune_history(&current, &new);
// The contacts live in the same database.
contacts.load();
continue;
}
Command::AttachCache(dir) => {
cache.replace(Cache::new(dir));
continue;
}
Command::SetContact { contact } => {
contacts.set(*contact);
continue;
}
Command::RemoveContact { uid } => {
contacts.remove(&uid);
continue;
}
ref command => command_session(command),
@@ -624,8 +882,7 @@ async fn run(
events.clone(),
frames.clone(),
settings.clone(),
shared.clone(),
history.clone(),
engine.clone(),
);
if let Some(profiles) = &srtp_profiles {
s.send(Command::SetSrtpProfiles(profiles.clone()));
@@ -684,6 +941,22 @@ fn command_session(command: &Command) -> SessionId {
| Command::SetStreamVolume { session, .. }
| Command::SetClientVolume { session, .. }
| Command::SetClientMuted { session, .. }
| Command::Poke { session, .. }
| Command::ListFiles { session, .. }
| Command::DownloadFile { session, .. }
| Command::DownloadChatFile { session, .. }
| Command::UploadFile { session, .. }
| Command::CancelTransfer { session, .. }
| Command::DeleteFiles { session, .. }
| Command::RenameFile { session, .. }
| Command::CreateDirectory { session, .. }
| Command::SetAvatar { session, .. }
| Command::FetchAvatar { session, .. }
| Command::ListOfflineMessages { session, .. }
| Command::GetOfflineMessage { session, .. }
| Command::SendOfflineMessage { session, .. }
| Command::DeleteOfflineMessage { session, .. }
| Command::SetOfflineMessageRead { session, .. }
| Command::CloseSession { session } => *session,
Command::SetAudioSettings(_)
| Command::SetSrtpProfiles(_)
@@ -691,7 +964,10 @@ fn command_session(command: &Command) -> SessionId {
| Command::SetSetting { .. }
| Command::ResetSetting { .. }
| Command::AttachSettings(_)
| Command::AttachHistory(_) => {
| Command::AttachHistory(_)
| Command::AttachCache(_)
| Command::SetContact { .. }
| Command::RemoveContact { .. } => {
unreachable!("engine-wide commands have no session")
}
}
+39
View File
@@ -0,0 +1,39 @@
//! Offline messages: mail the server keeps for a unique id until its owner
//! reads it (voice connection; TeamSpeak 3 and 6, capability
//! `offline_messages`).
//!
//! # Contract for the UI
//!
//! - [`crate::Command::ListOfflineMessages`] → [`crate::Event::OfflineMessages`]
//! (our inbox, without texts; empty is an empty list).
//! - [`crate::Command::GetOfflineMessage`] → [`crate::Event::OfflineMessage`]
//! (with the text; the server marks it read).
//! - [`crate::Command::SendOfflineMessage`], [`crate::Command::DeleteOfflineMessage`],
//! [`crate::Command::SetOfflineMessageRead`] → [`crate::Event::RequestDone`].
//!
//! Servers do not announce new offline messages while we are connected;
//! list them after connecting and when the user opens the inbox.
use serde::Serialize;
/// An offline message in the inbox list.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct OfflineMessageInfo {
pub id: u32,
/// The sender's unique id.
pub from_uid: String,
pub subject: String,
/// Unix seconds when it was sent.
pub ts_s: i64,
pub read: bool,
}
/// An offline message with its text.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct OfflineMessage {
pub id: u32,
pub from_uid: String,
pub subject: String,
pub text: String,
pub ts_s: i64,
}
+2 -2
View File
@@ -14,7 +14,7 @@ pub(crate) enum QueryCmd {
}
pub(crate) enum QueryEvent {
Presence(Presence),
Presence(Box<Presence>),
Chat(ChatMessage),
Error(String),
Disconnected,
@@ -35,7 +35,7 @@ pub(crate) async fn run(
e = observed.recv() => match e {
Ok(ObserverEvent::Snapshot(_)) | Ok(ObserverEvent::Delta(_)) | Err(broadcast::error::RecvError::Lagged(_)) => {
let presence = observer.presence().read().unwrap().clone();
let _ = events.send(QueryEvent::Presence(presence));
let _ = events.send(QueryEvent::Presence(Box::new(presence)));
}
Ok(ObserverEvent::Chat(msg)) => {
if open.contains(&msg.target) {
+4 -1
View File
@@ -26,7 +26,10 @@ pub fn route_chat(
match target {
ChatTarget::Server | ChatTarget::Private(_) if voice_channel.is_some() => ChatRoute::Voice,
ChatTarget::Channel(cid) if voice_channel == Some(*cid) => ChatRoute::Voice,
ChatTarget::Private(_) => ChatRoute::Unavailable("private chat needs a voice connection"),
ChatTarget::Private(_) => ChatRoute::Unavailable(
"private messages need a voice connection (gateways and query relays cannot send them \
as you; an offline message reaches clients who are away)",
),
_ if gateway => ChatRoute::Gateway,
_ if query => ChatRoute::Query,
ChatTarget::Channel(_) => ChatRoute::Unavailable(
+491 -18
View File
@@ -6,18 +6,22 @@
//! the address (`voice:<address>`, `gateway:<url>`). The gateway's features
//! are driven through its client ([`crate::gateway`]).
use std::collections::{BTreeMap, HashSet};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::{broadcast, mpsc};
use tokio::sync::{broadcast, mpsc, watch};
use tracing::debug;
use tsclientlib::ClientId;
use voelin_audio::AudioSettings;
use voelin_gateway_proto::{HistoryEntry, StreamEntry, StreamSpec, feature};
use voelin_model::{ChatMessage, ChatTarget, Presence};
use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails};
use voelin_stream::ClientState;
use crate::audio::{self, AudioEvent, AudioHandle, AudioIn};
use crate::cache::{self, Fetch, SharedCache, Waiter};
use crate::contacts::{Contacts, Relation};
use crate::files::{self, DownloadTo, Report, RequestId, Sink, TransferId, TransferState};
use crate::gateway::{
self, ClientError, GatewayClient, GatewayCmd, GatewayEvent, GatewayRequest, GatewayUpdate,
Push, ReactionPush,
@@ -25,13 +29,25 @@ use crate::gateway::{
use crate::history::{self, ChatCtx, HistoryMessage, MessageSource, SharedHistory};
use crate::query::{self, QueryCmd, QueryEvent};
use crate::route::{ChatRoute, Dedup, route_chat};
use crate::settings::SharedSettings;
use crate::settings::{
BlockMode, CACHE_FETCH_IMAGES, CACHE_MAX_MB, PRIVACY_BLOCK_MODE, SharedSettings,
};
use crate::stream::{
LayerSpec, OwnStreamEvent, PeerConfig, SrtpProfile, StreamFrame, StreamHandle, StreamInfo,
StreamInput, StreamKind, kind_name, parse_kind,
};
use crate::voice::{self, VoiceCmd, VoiceEvent};
use crate::{Command, Event, ObserveState, SessionId, SessionState, Source, VoiceState};
use crate::voice::{self, Remote, VoiceCmd, VoiceEvent, VoiceLink};
use crate::{Command, Event, ObserveState, SessionId, SessionState, Shared, Source, VoiceState};
const NO_VOICE: &str = "not connected with voice";
/// Server and channel groups in display order.
type Groups = (Arc<Vec<GroupInfo>>, Arc<Vec<GroupInfo>>);
/// `cache.max_mb` in bytes (0: no limit).
fn max_cache_bytes(settings: &SharedSettings) -> u64 {
settings.current().get(&CACHE_MAX_MB).saturating_mul(1024 * 1024)
}
pub(crate) struct SessionHandle {
tx: mpsc::UnboundedSender<Command>,
@@ -43,11 +59,10 @@ impl SessionHandle {
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
settings: SharedSettings,
history: SharedHistory,
shared: Shared,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
tokio::spawn(Session::new(id, events, frames, audio_settings, settings, history).run(rx));
tokio::spawn(Session::new(id, events, frames, audio_settings, shared).run(rx));
Self { tx }
}
@@ -70,6 +85,8 @@ enum SourceEvent {
Directory(u64, Result<Vec<StreamEntry>, ClientError>),
/// The server's unique id the database remembers for an address.
KnownServer(String),
/// Our avatar file is uploaded (its MD5) or failed: announce it.
AvatarUploaded(u64, RequestId, Result<String, String>),
}
/// Our live stream, for the gateway's directory.
@@ -123,6 +140,20 @@ struct Session {
dedup: Dedup,
sources_tx: mpsc::UnboundedSender<SourceEvent>,
sources_rx: Option<mpsc::UnboundedReceiver<SourceEvent>>,
cache: SharedCache,
contacts: Contacts,
contacts_rx: Option<watch::Receiver<u64>>,
/// Avatars reported per client unique id (their hash), voice only.
avatars: HashMap<String, String>,
/// Icons reported or being fetched, voice only.
icons: HashSet<u32>,
/// Contact volume and mute applied per client.
contact_audio: HashMap<u16, (f32, bool)>,
/// Friends' client ids, as last told to the streams.
stream_friends: BTreeSet<u16>,
/// The server's details and groups as last reported.
details: Option<Arc<ServerDetails>>,
groups: Option<Groups>,
}
impl Session {
@@ -131,11 +162,21 @@ impl Session {
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
settings: SharedSettings,
history: SharedHistory,
shared: Shared,
) -> Self {
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
let Shared { settings, history, cache, contacts } = shared;
let contacts_rx = Some(contacts.watch());
Self {
cache,
contacts,
contacts_rx,
avatars: HashMap::new(),
icons: HashSet::new(),
contact_audio: HashMap::new(),
stream_friends: BTreeSet::new(),
details: None,
groups: None,
id,
events,
state: SessionState::default(),
@@ -187,6 +228,7 @@ impl Session {
async fn run(mut self, mut commands: mpsc::UnboundedReceiver<Command>) {
let mut sources = self.sources_rx.take().expect("receiver");
let mut contacts = self.contacts_rx.take().expect("contacts");
loop {
tokio::select! {
cmd = commands.recv() => match cmd {
@@ -194,9 +236,11 @@ impl Session {
Some(cmd) => self.command(cmd),
},
Some(event) = sources.recv() => self.source_event(event),
Ok(()) = contacts.changed() => self.contacts_changed(),
}
}
self.stop_all();
self.contacts.session_closed(self.id);
}
fn next_generation(&mut self) -> u64 {
@@ -244,8 +288,14 @@ impl Session {
self.forward(out_rx, move |p| SourceEvent::AudioOut(generation, p));
self.forward(audio_rx, move |e| SourceEvent::Audio(generation, e));
}
tokio::spawn(voice::run(*options, cmd_rx, ev_tx));
let link = VoiceLink {
session: self.id,
events: self.events.clone(),
settings: self.settings.clone(),
};
tokio::spawn(voice::run(*options, link, cmd_rx, ev_tx));
self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e));
self.forget_images();
self.voice = Some((generation, cmd_tx));
self.state.voice = VoiceState::Connecting;
self.emit_state();
@@ -427,16 +477,398 @@ impl Session {
s.send(StreamInput::SrtpProfiles(profiles));
}
}
Command::Poke { client, message, .. } => {
self.voice_cmd(VoiceCmd::Poke { client, message });
}
Command::ListFiles { request, channel, password, path, .. } => {
if self.voice.is_none() {
let result = Err(NO_VOICE.into());
let path = files::normalize_dir(&path);
self.emit(Event::FileList { session: self.id, request, channel, path, result });
return;
}
let dir = Remote { channel, password, path };
self.voice_cmd(VoiceCmd::ListFiles { request, dir });
}
Command::DownloadFile { transfer, channel, password, path, to, .. } => {
self.download(transfer, Remote { channel, password, path }, &to);
}
Command::DownloadChatFile { transfer, file, password, to, .. } => {
let elsewhere = file
.server_uid
.as_ref()
.zip(self.state.server_uid.as_ref())
.is_some_and(|(theirs, ours)| theirs != ours);
if elsewhere {
self.transfer_state(
transfer,
TransferState::Failed("the file is on another server".into()),
);
return;
}
let path = file.full_path();
self.download(transfer, Remote { channel: file.channel, password, path }, &to);
}
Command::UploadFile {
transfer,
channel,
password,
path,
from,
overwrite,
resume,
..
} => {
if self.voice.is_none() {
self.transfer_state(transfer, TransferState::Failed(NO_VOICE.into()));
return;
}
let report = self.transfer_report(transfer);
let file = Remote { channel, password, path };
let transfer = Some(transfer);
self.voice_cmd(VoiceCmd::Upload {
transfer,
file,
from,
overwrite,
resume,
report,
});
}
Command::CancelTransfer { transfer, .. } => {
self.voice_cmd(VoiceCmd::CancelTransfer(transfer));
}
Command::DeleteFiles { request, channel, password, paths, .. } => {
let request = Some(request);
self.voice_request(
request,
VoiceCmd::DeleteFiles { request, channel, password, paths },
);
}
Command::RenameFile { request, channel, password, from, to, to_channel, .. } => {
let (to_channel, to_password) = to_channel.unwrap_or((channel, password.clone()));
let from = Remote { channel, password, path: from };
let to = Remote { channel: to_channel, password: to_password, path: to };
self.voice_request(Some(request), VoiceCmd::RenameFile { request, from, to });
}
Command::CreateDirectory { request, channel, password, path, .. } => {
let dir = Remote { channel, password, path };
self.voice_request(Some(request), VoiceCmd::CreateDirectory { request, dir });
}
Command::SetAvatar { request, image, .. } => self.set_avatar(request, image),
Command::FetchAvatar { client_uid, .. } => {
let hash = self
.voice_presence
.as_ref()
.and_then(|p| p.client_by_uid(&client_uid))
.and_then(|c| c.avatar.clone());
if let Some(hash) = hash {
self.fetch_avatar(&client_uid, &hash);
}
}
Command::ListOfflineMessages { request, .. } => {
if self.voice.is_none() {
let result = Err(NO_VOICE.into());
self.emit(Event::OfflineMessages { session: self.id, request, result });
return;
}
self.voice_cmd(VoiceCmd::OfflineList { request });
}
Command::GetOfflineMessage { request, id, .. } => {
if self.voice.is_none() {
let result = Err(NO_VOICE.into());
self.emit(Event::OfflineMessage { session: self.id, request, result });
return;
}
self.voice_cmd(VoiceCmd::OfflineGet { request, id });
}
Command::SendOfflineMessage { request, to_uid, subject, text, .. } => {
let cmd = VoiceCmd::OfflineAdd { request, to_uid, subject, text };
self.voice_request(Some(request), cmd);
}
Command::DeleteOfflineMessage { request, id, .. } => {
self.voice_request(Some(request), VoiceCmd::OfflineDelete { request, id });
}
Command::SetOfflineMessageRead { request, id, read, .. } => {
self.voice_request(Some(request), VoiceCmd::OfflineFlag { request, id, read });
}
// Engine-wide.
Command::CloseSession { .. }
| Command::TestMicrophone { .. }
| Command::SetSetting { .. }
| Command::ResetSetting { .. }
| Command::AttachSettings(_)
| Command::AttachHistory(_) => {}
| Command::AttachHistory(_)
| Command::AttachCache(_)
| Command::SetContact { .. }
| Command::RemoveContact { .. } => {}
}
}
// Files, avatars, icons
/// A request to the voice connection; without one it fails at once.
fn voice_request(&self, request: Option<RequestId>, cmd: VoiceCmd) {
match (&self.voice, request) {
(Some(_), _) => self.voice_cmd(cmd),
(None, Some(request)) => self.emit(Event::RequestDone {
session: self.id,
request,
result: Err(NO_VOICE.into()),
}),
(None, None) => {}
}
}
fn transfer_state(&self, transfer: TransferId, state: TransferState) {
self.emit(Event::Transfer { session: self.id, transfer, state });
}
/// Reports a user's transfer as [`Event::Transfer`].
fn transfer_report(&self, transfer: TransferId) -> Report {
let (session, events) = (self.id, self.events.clone());
Arc::new(move |state| {
let _ = events.send(Event::Transfer { session, transfer, state });
})
}
fn download(&self, transfer: TransferId, file: Remote, to: &DownloadTo) {
if self.voice.is_none() {
self.transfer_state(transfer, TransferState::Failed(NO_VOICE.into()));
return;
}
let report = self.transfer_report(transfer);
let sink = Sink::from_target(to);
self.voice_cmd(VoiceCmd::Download { transfer: Some(transfer), file, sink, report });
}
/// Upload our avatar and announce its hash, or remove it.
fn set_avatar(&mut self, request: RequestId, image: Option<PathBuf>) {
let Some((generation, tx)) = self.voice.clone() else {
let result = Err(NO_VOICE.into());
self.emit(Event::RequestDone { session: self.id, request, result });
return;
};
let Some(image) = image else {
// The file too (best effort), then no hash.
if let Some(path) = self.own_uid.as_deref().and_then(files::avatar_path) {
let cmd = VoiceCmd::DeleteFiles {
request: None,
channel: 0,
password: None,
paths: vec![path],
};
self.voice_cmd(cmd);
}
let hash = String::new();
self.voice_cmd(VoiceCmd::SetAvatarHash { request: Some(request), hash });
return;
};
let (sources, cache, settings) =
(self.sources_tx.clone(), self.cache.current(), self.settings.clone());
tokio::spawn(async move {
let hashed = image.clone();
let hash = match tokio::task::spawn_blocking(move || files::md5_file(&hashed)).await {
Ok(Ok(hash)) => hash,
Ok(Err(e)) => {
let e = format!("{}: {e}", image.display());
let _ = sources.send(SourceEvent::AvatarUploaded(generation, request, Err(e)));
return;
}
Err(e) => {
let e = e.to_string();
let _ = sources.send(SourceEvent::AvatarUploaded(generation, request, Err(e)));
return;
}
};
// Ours is shown without a download.
if let Some(key) = cache::avatar_key(&hash)
&& let Err(e) = cache.insert_copy(&key, &image, max_cache_bytes(&settings))
{
debug!("cannot cache our avatar: {e}");
}
let report: Report = Arc::new(move |state| {
let result = match state {
TransferState::Done { .. } => Ok(hash.clone()),
TransferState::Failed(e) => Err(e),
TransferState::Cancelled => Err("cancelled".into()),
_ => return,
};
let _ = sources.send(SourceEvent::AvatarUploaded(generation, request, result));
});
let file = Remote { channel: 0, password: None, path: "/avatar".into() };
let upload = VoiceCmd::Upload {
transfer: None,
file,
from: image,
overwrite: true,
resume: false,
report,
};
let _ = tx.send(upload);
});
}
/// Forget what was reported about avatars and icons (a new connection
/// reports them again).
fn forget_images(&mut self) {
self.avatars.clear();
self.icons.clear();
self.contact_audio.clear();
self.stream_friends.clear();
self.details = None;
self.groups = None;
}
/// Fetch the avatars and icons of the voice presence that are new.
fn fetch_images(&mut self, p: &Presence) {
if !self.settings.current().get(&CACHE_FETCH_IMAGES) {
return;
}
let mut avatars = HashMap::with_capacity(self.avatars.len());
for c in p.clients.values() {
let (Some(uid), Some(hash)) = (&c.uid, &c.avatar) else { continue };
if self.avatars.get(uid) != Some(hash) {
self.fetch_avatar(uid, hash);
}
avatars.insert(uid.clone(), hash.clone());
}
self.avatars = avatars;
let icons = std::iter::once(p.server.icon)
.chain(p.server_groups.values().map(|g| g.icon))
.chain(p.channel_groups.values().map(|g| g.icon))
.chain(p.channels.values().map(|c| c.icon))
.chain(p.clients.values().map(|c| c.icon))
.filter(|id| *id >= files::FIRST_DOWNLOADABLE_ICON)
.collect::<BTreeSet<u32>>();
for id in icons {
if self.icons.insert(id) {
self.fetch_icon(id);
}
}
}
fn fetch_avatar(&self, uid: &str, hash: &str) {
let Some(key) = cache::avatar_key(hash) else { return };
let (session, events) = (self.id, self.events.clone());
let (client_uid, hash) = (uid.to_owned(), hash.to_owned());
let waiter: Waiter = Box::new(move |result| match result {
Ok(path) => {
let _ = events.send(Event::AvatarReady { session, client_uid, path, hash });
}
Err(e) => debug!(%client_uid, "no avatar: {e}"),
});
self.fetch_image(key, files::avatar_path(uid), waiter);
}
fn fetch_icon(&self, icon: u32) {
let (session, events) = (self.id, self.events.clone());
let waiter: Waiter = Box::new(move |result| match result {
Ok(path) => {
let _ = events.send(Event::IconReady { session, icon, path });
}
Err(e) => debug!(icon, "no icon: {e}"),
});
self.fetch_image(cache::icon_key(icon), Some(files::icon_path(icon)), waiter);
}
/// Get `key` from the cache, downloading `path` of channel 0 once.
fn fetch_image(&self, key: String, path: Option<String>, waiter: Waiter) {
let cache = self.cache.current();
let Fetch::Download(temp) = cache.fetch(&key, waiter) else { return };
let settings = self.settings.clone();
let (Some(path), Some(_)) = (path, &self.voice) else {
cache.finish(&key, &temp, Err(NO_VOICE.into()), max_cache_bytes(&settings));
return;
};
let finish = {
let temp = temp.clone();
move |result: Result<(), String>| {
cache.finish(&key, &temp, result, max_cache_bytes(&settings));
}
};
let report: Report = Arc::new(move |state| match state {
TransferState::Done { .. } => finish(Ok(())),
TransferState::Failed(e) => finish(Err(e)),
TransferState::Cancelled => finish(Err("cancelled".into())),
_ => {}
});
let sink = Sink::File { part: temp.clone(), dest: temp, append: false };
let file = Remote { channel: 0, password: None, path };
self.voice_cmd(VoiceCmd::Download { transfer: None, file, sink, report });
}
// Contacts
/// The contacts changed: apply volumes and friends again.
fn contacts_changed(&mut self) {
if let Some(p) = self.voice_presence.clone() {
self.apply_contacts(&p);
}
}
/// Contacts' volumes and mutes for their clients, friends for the
/// streams (voice presence).
fn apply_contacts(&mut self, p: &Presence) {
let mut friends = BTreeSet::new();
let mut wanted: HashMap<u16, (f32, bool)> = HashMap::new();
for c in p.clients.values() {
let Some(contact) = c.uid.as_deref().and_then(|uid| self.contacts.get(uid)) else {
continue;
};
if contact.relation == Relation::Friend {
friends.insert(c.id);
}
if contact.muted || contact.volume != 1.0 {
wanted.insert(c.id, (contact.volume, contact.muted));
}
}
if let Some(a) = &self.audio {
for (client, (volume, muted)) in &wanted {
if self.contact_audio.get(client) != Some(&(*volume, *muted)) {
a.send(AudioIn::ClientVolume { client: ClientId(*client), volume: *volume });
a.send(AudioIn::ClientMuted { client: ClientId(*client), muted: *muted });
}
}
// No contact setting any more: back to normal.
for client in self.contact_audio.keys().filter(|c| !wanted.contains_key(c)) {
if p.clients.contains_key(client) {
a.send(AudioIn::ClientVolume { client: ClientId(*client), volume: 1.0 });
a.send(AudioIn::ClientMuted { client: ClientId(*client), muted: false });
}
}
self.contact_audio = wanted;
}
if friends != self.stream_friends {
self.stream_friends = friends.clone();
if let Some(s) = &self.streams {
s.send(StreamInput::Friends(friends));
}
}
}
/// Report the server's details and groups when they changed.
fn report_details(&mut self, p: &Presence) {
if self.details.as_deref() != Some(&p.server) {
let details = Arc::new(p.server.clone());
self.details = Some(details.clone());
self.emit(Event::ServerDetails { session: self.id, details });
}
let sorted = |groups| -> Arc<Vec<GroupInfo>> {
Arc::new(Presence::sorted_groups(groups).into_iter().cloned().collect())
};
let groups = (sorted(&p.server_groups), sorted(&p.channel_groups));
if self.groups.as_ref() != Some(&groups) {
self.groups = Some(groups.clone());
let (server_groups, channel_groups) = groups;
self.emit(Event::Groups { session: self.id, server_groups, channel_groups });
}
}
fn block_mode(&self) -> BlockMode {
self.settings.current().get(&PRIVACY_BLOCK_MODE)
}
fn stream_input(&self, input: StreamInput) {
match &self.streams {
Some(s) => s.send(input),
@@ -509,6 +941,7 @@ impl Session {
history: self.history.current(),
settings: self.settings.current(),
server_uid: self.state.server_uid.clone()?,
contacts: self.contacts.clone(),
})
}
@@ -820,6 +1253,20 @@ impl Session {
self.open_histories();
}
}
SourceEvent::AvatarUploaded(g, request, result) => match result {
Ok(hash) if self.is_current(Source::Voice, g) => {
self.voice_cmd(VoiceCmd::SetAvatarHash { request: Some(request), hash });
}
Ok(_) => self.emit(Event::RequestDone {
session: self.id,
request,
result: Err("the voice connection changed".into()),
}),
Err(e) => {
let result = Err(format!("avatar upload: {e}"));
self.emit(Event::RequestDone { session: self.id, request, result });
}
},
_ => debug!("event from a replaced source ignored"),
}
}
@@ -880,9 +1327,22 @@ impl Session {
s.send(StreamInput::Clients(clients));
}
}
self.voice_presence = Some(p);
self.report_details(&p);
self.fetch_images(&p);
self.apply_contacts(&p);
self.voice_presence = Some(*p);
self.publish_presence();
}
VoiceEvent::Poke { from, from_uid, from_name, message } => {
let blocked = self.contacts.is_blocked(from_uid.as_deref());
if blocked && self.block_mode() == BlockMode::Hide {
debug!(?from_uid, "poke of a blocked contact hidden");
return;
}
let session = self.id;
self.emit(Event::Poke { session, from, from_uid, from_name, message, blocked });
}
VoiceEvent::Error(message) => self.error(message),
VoiceEvent::Stream(n) => {
if let Some(s) = &self.streams {
s.send(StreamInput::Notification(n));
@@ -913,6 +1373,7 @@ impl Session {
self.voice = None;
self.voice_presence = None;
self.audio = None;
self.forget_images();
self.state.voice = VoiceState::Disconnected;
self.state.own_channel = None;
self.state.own_client = None;
@@ -948,7 +1409,7 @@ impl Session {
self.open_histories();
}
GatewayEvent::Presence(p) => {
self.gateway_presence = Some(p);
self.gateway_presence = Some(*p);
self.publish_presence();
}
GatewayEvent::Push(push) => self.gateway_push(*push),
@@ -1045,7 +1506,7 @@ impl Session {
self.state.observe = ObserveState::Observing;
self.emit_state();
}
self.query_presence = Some(p);
self.query_presence = Some(*p);
self.publish_presence();
}
QueryEvent::Chat(msg) => self.chat(msg, MessageSource::Query, None),
@@ -1061,7 +1522,9 @@ impl Session {
}
/// A live message: reported, and stored (merged with other copies).
fn chat(&mut self, msg: ChatMessage, source: MessageSource, entry: Option<HistoryEntry>) {
/// Messages of blocked contacts are flagged; their private messages
/// dropped with `privacy.block_mode = hide`.
fn chat(&mut self, mut msg: ChatMessage, source: MessageSource, entry: Option<HistoryEntry>) {
let wanted = match &msg.target {
ChatTarget::Server | ChatTarget::Private(_) => true,
target => self.open_chats.contains(target) || !msg.via_relay,
@@ -1069,6 +1532,14 @@ impl Session {
if !wanted {
return;
}
msg.blocked = self.contacts.is_blocked(msg.author_uid.as_deref());
if msg.blocked
&& matches!(msg.target, ChatTarget::Private(_))
&& self.block_mode() == BlockMode::Hide
{
debug!(author = ?msg.author_uid, "private message of a blocked contact hidden");
return;
}
if let Some(ctx) = self.chat_ctx() {
let stored = match &entry {
Some(entry) => history::gateway_message(&ctx.server_uid, entry),
@@ -1096,6 +1567,8 @@ impl Session {
self.state.presence_source = source;
self.emit_state();
}
self.emit(Event::Presence { session: self.id, presence: Arc::new(presence) });
let presence = Arc::new(presence);
self.contacts.presence(self.id, presence.clone());
self.emit(Event::Presence { session: self.id, presence });
}
}
+52 -3
View File
@@ -1044,8 +1044,8 @@ pub static STREAM_HARDWARE_ACCELERATION: Key<bool> = Key::new(
pub enum StreamPermissions {
/// Every join request is accepted.
Everyone,
/// Friends are accepted. Until there are contacts, every request is
/// shown to the user ([`crate::Event::StreamViewerRequest`]).
/// Friends (contacts marked friend) are accepted; others are shown to
/// the user ([`crate::Event::StreamViewerRequest`]).
Friends,
/// Clients in our channel are accepted, others denied.
#[default]
@@ -1096,8 +1096,53 @@ pub static CHAT_RETENTION_DAYS: Key<u32> = Key::new(
|| 0,
);
/// Size of the avatar and icon cache in MiB; the least recently used files
/// go first. 0: no limit.
pub static CACHE_MAX_MB: Key<u64> = Key::new(
"cache.max_mb",
Kind::UInt { min: 0 },
"Size of the avatar and icon cache in MiB (0: no limit).",
|| 256,
);
/// Download the avatars and icons of servers we are on by themselves.
pub static CACHE_FETCH_IMAGES: Key<bool> = Key::new(
"cache.fetch_images",
Kind::Bool,
"Download avatars and icons of the servers we are on.",
|| true,
);
/// How often a file transfer reports its progress (ms); 0: after every
/// piece received or sent.
pub static FILES_PROGRESS_MS: Key<u32> = Key::new(
"files.progress_interval_ms",
Kind::UInt { min: 0 },
"How often a file transfer reports its progress, in ms (0: continuously).",
|| 250,
);
/// What happens to private messages and pokes of blocked contacts (their
/// channel and server messages are always shown, flagged).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BlockMode {
/// Dropped: neither reported nor stored.
#[default]
Hide,
/// Reported and stored with `blocked` set.
Flag,
}
pub static PRIVACY_BLOCK_MODE: Key<BlockMode> = Key::new(
"privacy.block_mode",
Kind::Choice(&["hide", "flag"]),
"Private messages and pokes of blocked contacts: hide them, or show them flagged.",
BlockMode::default,
);
/// The keys every [`Settings`] knows from the start.
pub fn builtin_keys() -> [&'static dyn Setting; 15] {
pub fn builtin_keys() -> [&'static dyn Setting; 19] {
[
&CRASH_REPORTS,
&AUDIO,
@@ -1114,6 +1159,10 @@ pub fn builtin_keys() -> [&'static dyn Setting; 15] {
&CHAT_HISTORY_PAGE,
&CHAT_DEDUPE_TOLERANCE_MS,
&CHAT_RETENTION_DAYS,
&CACHE_MAX_MB,
&CACHE_FETCH_IMAGES,
&FILES_PROGRESS_MS,
&PRIVACY_BLOCK_MODE,
]
}
+23 -10
View File
@@ -12,7 +12,7 @@
//! cannot. Our own stream's life (live, viewers, ended) goes back to the
//! session ([`OwnStreamEvent`]), which keeps its directory entry.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
@@ -153,6 +153,8 @@ pub(crate) enum StreamInput {
RequestFailed(Request, String),
/// Clients on the server: channel and `client_is_streaming`.
Clients(BTreeMap<u16, ClientState>),
/// Clients that are friends (contacts), for `stream.permissions`.
Friends(BTreeSet<u16>),
/// The registered streams of the gateway's directory (full list).
Directory(Vec<StreamInfo>),
/// The voice connection is gone.
@@ -256,6 +258,7 @@ impl StreamHandle {
live: None,
viewers: 0,
clients: BTreeMap::new(),
friends: BTreeSet::new(),
gateway,
};
tokio::spawn(task.run(rx));
@@ -293,6 +296,8 @@ struct StreamTask {
viewers: u32,
/// The clients as of the last update.
clients: BTreeMap<u16, ClientState>,
/// Friends' client ids (`stream.permissions = friends`).
friends: BTreeSet<u16>,
gateway: Arc<Mutex<GatewayStreams>>,
}
@@ -368,6 +373,10 @@ impl StreamTask {
self.streams.request_failed(&request, &error);
Ok(())
}
StreamInput::Friends(friends) => {
self.friends = friends;
Ok(())
}
StreamInput::Clients(clients) => {
// Streams of clients that left, stopped streaming or are not
// in our channel are gone; unannounced ones are looked up.
@@ -525,8 +534,8 @@ impl StreamTask {
match *self.settings.current().get_arc(&STREAM_PERMISSIONS) {
StreamPermissions::Everyone => Some(true),
StreamPermissions::Nobody => Some(false),
// No contacts yet: ask for everyone.
StreamPermissions::Friends => None,
// Friends are let in; others: ask.
StreamPermissions::Friends => self.friends.contains(&viewer.0).then_some(true),
StreamPermissions::Channel => {
let discovery = self.streams.discovery();
let own = discovery.own_channel();
@@ -989,7 +998,7 @@ mod tests {
assert_eq!(parse_kind("game"), StreamKind::Screen);
}
/// `stream.permissions` answers join requests unless it is `friends`.
/// `stream.permissions` answers join requests (`friends`: friends only, others are asked).
#[tokio::test(flavor = "multi_thread")]
async fn permissions_answer_join_requests() {
let in_channels = |streamer: u64, viewer: u64| {
@@ -998,12 +1007,13 @@ mod tests {
(CLIENTS[1], ClientState { channel: viewer, streaming: Some(false) }),
]))
};
for (permissions, viewer_channel, expected) in [
(StreamPermissions::Everyone, 2, Some(true)),
(StreamPermissions::Channel, 1, Some(true)),
(StreamPermissions::Channel, 2, Some(false)),
(StreamPermissions::Nobody, 1, Some(false)),
(StreamPermissions::Friends, 1, None),
for (permissions, viewer_channel, friend, expected) in [
(StreamPermissions::Everyone, 2, false, Some(true)),
(StreamPermissions::Channel, 1, false, Some(true)),
(StreamPermissions::Channel, 2, false, Some(false)),
(StreamPermissions::Nobody, 1, false, Some(false)),
(StreamPermissions::Friends, 1, false, None),
(StreamPermissions::Friends, 2, true, Some(true)),
] {
let settings = Settings::in_memory();
settings.set(&STREAM_PERMISSIONS, permissions).unwrap();
@@ -1011,6 +1021,9 @@ mod tests {
for h in handles.iter() {
h.send(in_channels(1, viewer_channel));
}
if friend {
handles[0].send(StreamInput::Friends(BTreeSet::from([CLIENTS[1]])));
}
let setup = StreamSetup { name: "p".into(), ..Default::default() };
handles[0].send(StreamInput::Start { setup, auto_accept: false });
let (mut live, mut listed) = (false, false);
File diff suppressed because it is too large. Load diff