Merge pull request #5 from Faumaray/codex/finalize-channel-banners

Complete channel banners and reliable image downloads
This commit is contained in:
faumaray authored and GitHub committed 2026-10-04 20:51:22 +03:00
commit 117a61dfc2
56 files changed
+3123 -361

No files matched your search

Generated
+5
View File
@@ -4063,6 +4063,9 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
dependencies = [
"bytemuck",
"byteorder-lite",
"color_quant",
"gif",
"image-webp",
"moxcms",
"num-traits",
"png",
@@ -9480,6 +9483,7 @@ dependencies = [
"futures",
"hickory-resolver",
"md5",
"reqwest",
"rusqlite",
"serde",
"serde_json",
@@ -9678,6 +9682,7 @@ dependencies = [
"anyhow",
"chrono",
"dirs",
"image",
"miniz_oxide 0.8.9",
"png",
"serde",
+11
View File
@@ -106,3 +106,14 @@ against or offered back to upstream.
handed those fewer than 32 bytes to `from_short`, which refused them: one
identity in 256 (the official client's ones included) could not be imported.
The scalar is padded to 32 bytes now; a test round-trips such keys.
13. **Channel banners** (`tsproto-structs/declarations/Messages.toml`, `Book.toml`).
TeamSpeak 6 channels have a banner picture, `channel_banner_gfx_url` and
`channel_banner_mode`, which its server sends in `channellist`,
`notifychannelcreated` and `notifychanneledited` (verified against
6.0.0-beta13.1; upstream declared them for `channellist` only, so creating
or editing a channel logged "Unknown argument" and lost them). The book's
`Channel` keeps them as `banner_gfx_url` and `banner_mode`. The mode stays
a string, as upstream declared it, so a value the parser does not know
cannot drop the whole channel list; its numbers are those of
`HostBannerMode` (the server's `channeledit` documentation: 0 as it is,
1 stretched, 2 scaled keeping the aspect ratio).
@@ -76,6 +76,8 @@ properties = [
{ name="Icon", type="IconId", opt=true },
{ name="IsPrivate", type="bool", opt=true },
{ name="StorageQuota", type="u32", opt=true },
{ name="BannerGfxUrl", type="str", opt=true, doc="TeamSpeak 6: the address of the channel's banner picture" },
{ name="BannerMode", type="str", opt=true, doc="TeamSpeak 6: how the banner is scaled, the values of `HostBannerMode`" },
{ name="Subscribed", type="bool" },
{ name="PermissionHints", type="ChannelPermissionHint", opt=true },
{ name="OptionalData", type="OptionalChannelData", opt=true },
@@ -24,7 +24,7 @@ fields = [
{ map="cgi", ts="cgi", pretty="ChannelGroupIndex", type="ChannelGroupId" },
{ map="cgid", ts="cgid", pretty="ChannelGroup", type="ChannelGroupId" }, # TODO: Consider name 'ChannelGroup' for consistency
{ map="channel_banner_gfx_url", ts="channel_banner_gfx_url", pretty="BannerGfxUrl", type="str" },
{ map="channel_banner_mode", ts="channel_banner_mode", pretty="BannerMode", type="str" }, # ?? Same as HostBannerMode maybe? There's no ui for this setting
{ map="channel_banner_mode", ts="channel_banner_mode", pretty="BannerMode", type="str" }, # Like HostBannerMode: 0 as it is, 1 stretched, 2 scaled keeping the aspect ratio (TeamSpeak 6 channeledit docs). A string, so an unknown mode cannot drop the channel list
{ map="channel_codec", ts="channel_codec", pretty="Codec", type="Codec" },
{ map="channel_codec_is_unencrypted", ts="channel_codec_is_unencrypted", pretty="IsUnencrypted", type="bool" },
{ map="channel_codec_latency_factor", ts="channel_codec_latency_factor", pretty="CodecLatencyFactor", type="i32" },
@@ -606,10 +606,10 @@ default = { s2c=true, c2s=false, response=true, low=false, np=false }
msg = [
{ name="BanList", notify="notifybanlist", attributes=["banid", "ip", "name", "uid", "mytsid?", "lastnickname", "created", "duration@time", "invokercldbid", "invokername", "invokeruid?", "reason", "enforcements"] },
{ name="ChannelClientPermList", notify="notifychannelclientpermlist", attributes=["cid", "cldbid", "permid?", "permsid?", "permvalue", "permnegated", "permskip"] },
{ name="ChannelCreated", notify="notifychannelcreated", attributes=["cid", "invokerid", "invokername", "invokeruid?", "channel_order", "channel_name", "channel_topic?", "channel_flag_default?", "channel_flag_password?", "channel_flag_permanent?", "channel_flag_semi_permanent?", "channel_codec?", "channel_codec_quality?", "channel_needed_talk_power?", "channel_icon_id?", "channel_maxclients?", "channel_maxfamilyclients?", "channel_codec_latency_factor?", "channel_codec_is_unencrypted?", "channel_delete_delay?", "channel_unique_identifier?", "channel_flag_maxclients_unlimited?", "channel_flag_maxfamilyclients_unlimited?", "channel_flag_maxfamilyclients_inherited?", "channel_name_phonetic?", "channel_storage_quota?", "cpid"] },
{ name="ChannelCreated", notify="notifychannelcreated", attributes=["cid", "invokerid", "invokername", "invokeruid?", "channel_order", "channel_name", "channel_topic?", "channel_flag_default?", "channel_flag_password?", "channel_flag_permanent?", "channel_flag_semi_permanent?", "channel_codec?", "channel_codec_quality?", "channel_needed_talk_power?", "channel_icon_id?", "channel_maxclients?", "channel_maxfamilyclients?", "channel_codec_latency_factor?", "channel_codec_is_unencrypted?", "channel_delete_delay?", "channel_unique_identifier?", "channel_flag_maxclients_unlimited?", "channel_flag_maxfamilyclients_unlimited?", "channel_flag_maxfamilyclients_inherited?", "channel_name_phonetic?", "channel_storage_quota?", "cpid", "channel_banner_gfx_url?", "channel_banner_mode?"] },
{ name="ChannelDeleted", notify="notifychanneldeleted", attributes=["cid", "invokerid", "invokername", "invokeruid?"] },
# Has no invoker when we requested the description with: channelgetdescription cid=1
{ name="ChannelEdited", notify="notifychanneledited", attributes=["cid", "invokerid?", "invokername?", "invokeruid?", "reasonid", "channel_order?", "channel_name?", "channel_topic?", "channel_flag_default?", "channel_flag_password?", "channel_flag_permanent?", "channel_flag_semi_permanent?", "channel_codec?", "channel_codec_quality?", "channel_needed_talk_power?", "channel_icon_id?", "channel_maxclients?", "channel_maxfamilyclients?", "channel_codec_latency_factor?", "channel_codec_is_unencrypted?", "channel_delete_delay?", "channel_flag_maxclients_unlimited?", "channel_flag_maxfamilyclients_unlimited?", "channel_flag_maxfamilyclients_inherited?", "channel_name_phonetic?", "cpid?", "channel_description?"] },
{ name="ChannelEdited", notify="notifychanneledited", attributes=["cid", "invokerid?", "invokername?", "invokeruid?", "reasonid", "channel_order?", "channel_name?", "channel_topic?", "channel_flag_default?", "channel_flag_password?", "channel_flag_permanent?", "channel_flag_semi_permanent?", "channel_codec?", "channel_codec_quality?", "channel_needed_talk_power?", "channel_icon_id?", "channel_maxclients?", "channel_maxfamilyclients?", "channel_codec_latency_factor?", "channel_codec_is_unencrypted?", "channel_delete_delay?", "channel_flag_maxclients_unlimited?", "channel_flag_maxfamilyclients_unlimited?", "channel_flag_maxfamilyclients_inherited?", "channel_name_phonetic?", "cpid?", "channel_description?", "channel_banner_gfx_url?", "channel_banner_mode?"] },
{ name="ChannelGroupClientList", notify="notifychannelgroupclientlist", attributes=["cid", "cldbid", "cgid"] },
{ name="ChannelGroupList", notify="notifychannelgrouplist", attributes=["cgid", "name", "type@group", "iconid", "savedb", "sortid", "namemode", "n_modifyp", "n_member_addp", "n_member_removep?"] },
{ name="ChannelGroupPermList", notify="notifychannelgrouppermlist", attributes=["cgid", "permid?", "permsid?", "permvalue", "permnegated", "permskip"] },
+2
View File
@@ -29,6 +29,8 @@ futures = "0.3"
# Finding a server's gateway in DNS (the voice resolver's version).
hickory-resolver = "0.26"
md5 = "0.8"
# Banners on the web; the client the workspace has (voelin-query, voelin-media).
reqwest = { version = "0.13.5", default-features = false, features = ["rustls"] }
# Reading the official clients' settings.db when importing identities.
rusqlite = { version = "0.40.2", features = ["bundled"] }
serde = { version = "1", features = ["derive"] }
+115 -5
View File
@@ -2,8 +2,8 @@
use tsclientlib::{ClientType, MaxClients, data};
use voelin_model::{
ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, HostBannerMode,
HostMessageMode, Presence, ServerDetails, parse_badges,
BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, HostMessageMode,
Presence, ServerDetails, parse_badges,
};
fn group_info(
@@ -49,9 +49,9 @@ fn server_details(server: &data::Server, uid: Option<&str>) -> ServerDetails {
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,
tsclientlib::HostBannerMode::NoAdjust => BannerMode::NoAdjust,
tsclientlib::HostBannerMode::AdjustIgnoreAspect => BannerMode::IgnoreAspect,
tsclientlib::HostBannerMode::AdjustKeepAspect => BannerMode::KeepAspect,
},
host_button_tooltip: server.hostbutton_tooltip.clone(),
host_button_url: server.hostbutton_url.clone(),
@@ -115,6 +115,12 @@ pub(crate) fn presence_from_book(
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),
banner_gfx_url: c.banner_gfx_url.clone().filter(|u| !u.is_empty()),
// A number the book keeps as text.
banner_mode: c
.banner_mode
.as_deref()
.map_or(BannerMode::NoAdjust, BannerMode::from_wire),
},
)
})
@@ -157,3 +163,107 @@ pub(crate) fn presence_from_book(
.collect(),
}
}
#[cfg(test)]
mod tests {
use tsclientlib::InMessage;
use tsproto_packets::packets::{Direction, Flags, OutPacket, PacketType};
use tsproto_types::crypto::EccKeyPrivP256;
use super::*;
fn message(text: &str) -> InMessage {
let packet = OutPacket::new_with_dir(Direction::S2C, Flags::empty(), PacketType::Command);
InMessage::new(&packet.header(), text.as_bytes()).unwrap()
}
/// Channel banners as a TeamSpeak 6 server (6.0.0-beta13.1) sends them:
/// in the channel list, when a channel is created and when it is edited.
#[test]
fn channel_banners() {
let InMessage::InitServer(init) = message(concat!(
"initserver virtualserver_name=Test virtualserver_welcomemessage ",
"virtualserver_platform=Linux virtualserver_version=6.0.0-beta13.1 ",
"virtualserver_maxclients=32 virtualserver_created=0 ",
"virtualserver_codec_encryption_mode=0 virtualserver_hostmessage ",
"virtualserver_hostmessage_mode=0 virtualserver_default_server_group=8 ",
"virtualserver_default_channel_group=8 virtualserver_hostbanner_url ",
r"virtualserver_hostbanner_gfx_url=https:\/\/example.com\/banner.png ",
"virtualserver_hostbanner_gfx_interval=60 ",
"virtualserver_priority_speaker_dimm_modificator=-18.0000 virtualserver_id=1 ",
"virtualserver_ask_for_privilegekey=0 ",
"virtualserver_hostbutton_tooltip virtualserver_hostbutton_url ",
"virtualserver_hostbutton_gfx_url virtualserver_name_phonetic ",
"virtualserver_icon_id=0 virtualserver_hostbanner_mode=2 ",
"virtualserver_channel_temp_delete_delay_default=0 acn=t aclid=2 pv=7 ",
"client_talk_power=75 client_needed_serverquery_view_power=75",
)) else {
panic!("not an initserver");
};
let mut book = data::Connection::new(EccKeyPrivP256::create().to_pub(), &init);
let channel = |cid: u64, order: u64, name: &str, banner: &str| {
format!(
"cid={cid} cpid=0 channel_name={name} channel_topic channel_codec=4 \
channel_codec_quality=6 channel_maxclients=-1 channel_maxfamilyclients=-1 \
channel_order={order} channel_flag_permanent=1 channel_flag_semi_permanent=0 \
channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 \
channel_codec_is_unencrypted=1 channel_delete_delay=0 \
channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=1 \
channel_flag_maxfamilyclients_inherited=0 channel_needed_talk_power=0 \
channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 {banner} \
channel_storage_quota=4294967295"
)
};
let list = format!(
"channellist {}|{}",
channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"),
channel(
12,
1,
"Raid",
r"channel_banner_gfx_url=http:\/\/127.0.0.1:1\/d.png channel_banner_mode=2"
),
);
for text in [
list.as_str(),
concat!(
"notifychannelcreated cid=13 cpid=0 invokerid=1 invokername=serveradmin ",
"invokeruid=serveradmin channel_name=New channel_order=12 ",
r"channel_flag_permanent=1 channel_banner_gfx_url=https:\/\/example.com\/new.jpg ",
"channel_banner_mode=1",
),
concat!(
"notifychanneledited cid=12 reasonid=10 invokerid=1 invokername=serveradmin ",
"invokeruid=serveradmin channel_banner_mode=1",
),
] {
book.handle_command(&message(text)).unwrap();
}
let p = presence_from_book(&book, None, |_| false);
let banner = |p: &Presence, cid| {
let c = &p.channels[&cid];
(c.banner_gfx_url.clone(), c.banner_mode)
};
assert_eq!(banner(&p, 1), (None, BannerMode::NoAdjust));
assert_eq!(
banner(&p, 12),
(Some("http://127.0.0.1:1/d.png".into()), BannerMode::IgnoreAspect)
);
assert_eq!(
banner(&p, 13),
(Some("https://example.com/new.jpg".into()), BannerMode::IgnoreAspect)
);
// Removing the banner sends an empty address.
book.handle_command(&message(
"notifychanneledited cid=12 reasonid=10 invokerid=1 invokername=x channel_banner_gfx_url",
))
.unwrap();
let p = presence_from_book(&book, None, |_| false);
assert_eq!(p.channels[&12].banner_gfx_url, None);
// The host banner, for comparison.
assert_eq!(p.server.banner_gfx_url, "https://example.com/banner.png");
assert_eq!(p.server.banner_gfx_interval_s, 60);
assert_eq!(p.server.banner_mode, BannerMode::KeepAspect);
assert_eq!(BannerMode::from_wire("7"), BannerMode::NoAdjust);
}
}
+104 -13
View File
@@ -3,8 +3,9 @@
//! 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>`).
//! several clients is one file. Pictures from the web (banners,
//! [`crate::web`]) are named by the MD5 hash of their address. Keys are
//! relative paths (`avatars/<md5>`, `icons/<id>`, `pictures/<md5>`).
//!
//! 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
@@ -76,6 +77,30 @@ pub(crate) fn icon_key(id: u32) -> String {
format!("icons/{id}")
}
/// The largest picture downloaded into the cache, from the web or from the
/// server's files: animated banners of several megabytes are common. The
/// download goes to disk as it arrives, so this bounds the disk, not memory.
pub(crate) const MAX_PICTURE_BYTES: u64 = 64 << 20;
/// The slowest a picture may arrive on average after its first seconds:
/// a large banner on a slow link still arrives, one trickling in forever
/// does not hold a download slot.
pub(crate) const MIN_PICTURE_RATE: u64 = 32 << 10;
/// The cache key of a picture on the web: only `http` and `https`
/// addresses.
pub(crate) fn picture_key(url: &str) -> Option<String> {
let (scheme, rest) = url.split_once("://")?;
let web = scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https");
(web && !rest.is_empty()).then(|| format!("pictures/{:x}", md5::compute(url)))
}
/// The cache key of a picture in a server's files (`ts3image://`): the
/// same address names another file on another server.
pub(crate) fn server_picture_key(server: &str, url: &str) -> String {
format!("pictures/{:x}", md5::compute(format!("{server}\n{url}")))
}
impl Cache {
/// A cache in `dir` (created when the first file arrives).
pub fn new(dir: impl Into<PathBuf>) -> Self {
@@ -106,6 +131,18 @@ impl Cache {
self.touch(&mut index, key)
}
/// The cached server, channel, group or client icon, if available. Not
/// marked as used (no file is opened or touched): the UI asks on every
/// refresh of the server list.
pub fn icon(&self, id: u32) -> Option<PathBuf> {
if id == 0 {
return None;
}
let key = icon_key(id);
let path = self.dir.join(&key);
(self.lock().entries.contains_key(&key) && path.is_file()).then_some(path)
}
fn touch(&self, index: &mut Index, key: &str) -> Option<PathBuf> {
let path = self.dir.join(key);
let tick = index.entries.get(key)?.tick;
@@ -131,9 +168,11 @@ impl Cache {
}
/// Get `key`, downloading it once however many ask (see [`Fetch`]).
pub(crate) fn fetch(&self, key: &str, waiter: Waiter) -> Fetch {
/// With `fresh`, download it again even if it is cached (a picture that
/// changes at its address); the new file replaces the old one.
pub(crate) fn fetch(&self, key: &str, fresh: bool, waiter: Waiter) -> Fetch {
let mut index = self.lock();
if let Some(path) = self.touch(&mut index, key) {
if !fresh && let Some(path) = self.touch(&mut index, key) {
drop(index);
waiter(Ok(path));
return Fetch::Cached;
@@ -237,7 +276,7 @@ impl Cache {
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"] {
for sub in ["avatars", "icons", "pictures"] {
let Ok(entries) = std::fs::read_dir(dir.join(sub)) else { continue };
for entry in entries.flatten() {
let Ok(meta) = entry.metadata() else { continue };
@@ -297,7 +336,8 @@ mod tests {
/// 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 {
let Fetch::Download(temp) = cache.fetch(key, false, Box::new(move |r| tx.send(r).unwrap()))
else {
panic!("{key} should download");
};
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
@@ -314,9 +354,9 @@ mod tests {
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!() };
let Fetch::Download(temp) = cache.fetch(&key, false, waiter(tx.clone())) else { panic!() };
// A second asker waits for the same download.
assert!(matches!(cache.fetch(&key, waiter(tx.clone())), Fetch::Waiting));
assert!(matches!(cache.fetch(&key, false, 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);
@@ -325,10 +365,18 @@ mod tests {
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!(matches!(cache.fetch(&key, false, waiter(tx.clone())), Fetch::Cached));
assert_eq!(rx.recv().unwrap().unwrap(), a);
assert_eq!(cache.get(&key), Some(a));
assert_eq!(cache.get(&key), Some(a.clone()));
assert_eq!(cache.size(), 3);
// Fresh: downloaded again, the new file replaces the old one.
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(tx)) else { panic!() };
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
std::fs::write(&temp, b"newer").unwrap();
cache.finish(&key, &temp, Ok(()), 0);
assert_eq!(rx.recv().unwrap().unwrap(), a);
assert_eq!(std::fs::read(&a).unwrap(), b"newer");
assert_eq!(cache.size(), 5);
std::fs::remove_dir_all(dir).unwrap();
}
@@ -338,19 +386,42 @@ mod tests {
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()))
let Fetch::Download(temp) =
cache.fetch("icons/7", false, Box::new(move |r| tx.send(r).unwrap()))
else {
panic!()
};
assert!(matches!(
cache.fetch("icons/7", Box::new(move |r| tx2.send(r).unwrap())),
cache.fetch("icons/7", false, 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(_)));
assert!(matches!(cache.fetch("icons/7", false, Box::new(|_| {})), Fetch::Download(_)));
}
#[test]
fn failed_picture_refresh_keeps_previous_file_and_can_retry() {
let dir = temp_dir("refresh-fail");
let cache = Cache::new(&dir);
let key = picture_key("https://example.com/banner.png").unwrap();
let path = put(&cache, &key, 32, 0);
let (tx, rx) = mpsc::channel();
let Fetch::Download(temp) = cache.fetch(&key, true, Box::new(move |r| tx.send(r).unwrap()))
else {
panic!("refresh download");
};
std::fs::write(&temp, b"partial download").unwrap();
cache.finish(&key, &temp, Err("connection lost".into()), 0);
assert_eq!(rx.recv().unwrap(), Err("connection lost".into()));
assert!(!temp.exists());
assert_eq!(cache.get(&key), Some(path.clone()));
assert_eq!(std::fs::read(&path).unwrap(), vec![0u8; 32]);
assert_eq!(cache.size(), 32);
assert!(matches!(cache.fetch(&key, true, Box::new(|_| {})), Fetch::Download(_)));
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
@@ -383,5 +454,25 @@ mod tests {
assert!(avatar_key("").is_none());
assert!(avatar_key("../x").is_none());
assert_eq!(icon_key(4_294_967_295), "icons/4294967295");
let url = "https://example.com/banner.png";
assert_eq!(picture_key(url).unwrap(), format!("pictures/{:x}", md5::compute(url)));
assert_ne!(picture_key(url), picture_key("http://example.com/banner.png"));
assert!(picture_key("HTTP://example.com/b.gif").is_some());
for not_web in ["", "file:///etc/passwd", "ftp://h/b.png", "https://", "example.com/b.png"]
{
assert!(picture_key(not_web).is_none(), "{not_web}");
}
}
/// Pictures are cached files like the others (counted after a restart).
#[test]
fn pictures_survive_restart() {
let dir = temp_dir("pictures");
let key = picture_key("https://example.com/b.png").unwrap();
let path = put(&Cache::new(&dir), &key, 10, 0);
let again = Cache::new(&dir);
assert_eq!(again.size(), 10);
assert_eq!(again.get(&key), Some(path));
std::fs::remove_dir_all(dir).unwrap();
}
}
+89
View File
@@ -364,6 +364,59 @@ pub(crate) fn normalize_dir(path: &str) -> String {
}
}
/// A picture in the voice server's files, as banners link one: its
/// channel and path. TeamSpeak 5 and 6 write
/// `ts3image://<host>?port=<port>&channel=<cid>&path=<dir>&filename=<name>`
/// (the file browser's `ts3file://` link with its scheme changed, which is
/// taken as well); TeamSpeak 3's BBCode `ts3image://<name>?channel=<cid>&path=<dir>`.
/// The host is not checked: the file is asked of the server we are on.
pub(crate) fn server_image(url: &str) -> Option<(u64, String)> {
let (scheme, rest) = url.trim().split_once("://")?;
if !scheme.eq_ignore_ascii_case("ts3image") && !scheme.eq_ignore_ascii_case("ts3file") {
return None;
}
let rest = rest.split('#').next().unwrap_or_default();
let (authority, query) = rest.split_once('?').unwrap_or((rest, ""));
let (mut channel, mut dir, mut name, mut port) = (None, None, None, false);
for pair in query.split('&') {
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
match key {
"channel" => channel = value.parse::<u64>().ok(),
"path" => dir = Some(percent_decode(value)?),
"filename" => name = Some(percent_decode(value)?),
"port" => port = true,
_ => {}
}
}
let dir = normalize_dir(dir.as_deref().unwrap_or("/"));
let path = match name {
Some(name) => join_path(&dir, &name),
// TeamSpeak 3: the file's name where the host would be.
None if !port => join_path(&dir, &percent_decode(authority.trim_end_matches('/'))?),
// Only a path: the file itself.
None => dir,
};
(!path.ends_with('/')).then_some((channel?, path))
}
/// `%XX` escapes decoded (a `+` stays one: the clients escape spaces).
fn percent_decode(text: &str) -> Option<String> {
let mut out = Vec::with_capacity(text.len());
let mut bytes = text.bytes();
while let Some(b) = bytes.next() {
if b == b'%' {
let hex = [bytes.next()?, bytes.next()?];
if !hex.iter().all(u8::is_ascii_hexdigit) {
return None;
}
out.push(u8::from_str_radix(std::str::from_utf8(&hex).ok()?, 16).ok()?);
} else {
out.push(b);
}
}
String::from_utf8(out).ok()
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
@@ -389,6 +442,42 @@ mod tests {
assert_eq!(normalize_dir("docs"), "/docs");
}
#[test]
fn server_images() {
// TeamSpeak 5 and 6, as the file browser links a file.
assert_eq!(
server_image(
"ts3image://ts.example.com?port=9987&channel=5&path=%2Fbanners&filename=raid%20night.gif&isDir=0&size=12345"
),
Some((5, "/banners/raid night.gif".into()))
);
assert_eq!(
server_image("TS3FILE://1.2.3.4?port=9987&channel=12&path=/&filename=a+b.png"),
Some((12, "/a+b.png".into()))
);
assert_eq!(
server_image("ts3image://h?port=1&channel=3&path=%2Fdir%2Fx.png"),
Some((3, "/dir/x.png".into()))
);
// TeamSpeak 3's BBCode: the name where the host would be.
assert_eq!(
server_image("ts3image://banner%201.png?channel=1&path=%2F"),
Some((1, "/banner 1.png".into()))
);
assert_eq!(server_image("ts3image://b.png?channel=7"), Some((7, "/b.png".into())));
for refused in [
"https://example.com/b.png",
"ts3image://h?port=1&path=%2F&filename=b.png",
"ts3image://h?port=1&channel=x&filename=b.png",
"ts3image://h?port=1&channel=1&path=%2F",
"ts3image://h?port=1&channel=1&filename=%zz.png",
"ts3image://h?port=1&channel=1&filename=%C3",
"ts3image://",
] {
assert_eq!(server_image(refused), None, "{refused}");
}
}
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);
+19 -2
View File
@@ -39,8 +39,10 @@
//! [`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`]).
//! [`cache`]) and offline messages ([`offline`]). The host banner and
//! channel banners are pictures on the web, fetched into the same cache
//! ([`Event::PictureReady`]). Contacts (friends, blocked people, per-person
//! volume) are engine-wide ([`contacts`]).
mod audio;
mod book;
@@ -62,6 +64,7 @@ pub mod stream;
#[cfg(feature = "media")]
pub mod studio;
mod voice;
mod web;
use std::collections::HashMap;
use std::path::PathBuf;
@@ -590,6 +593,9 @@ pub enum Event {
/// The server's details changed (also in [`Presence::server`]; voice).
ServerDetails {
session: SessionId,
/// The requested voice address that supplied these details. A queued
/// event may outlive a reconnect to another address in this session.
address: String,
details: Arc<ServerDetails>,
},
/// The server or channel groups changed (also in the presence; voice),
@@ -646,6 +652,17 @@ pub enum Event {
icon: u32,
path: PathBuf,
},
/// A picture on the web is in the cache: the host banner
/// ([`ServerDetails::banner_gfx_url`]) or a channel's
/// ([`voelin_model::ChannelInfo::banner_gfx_url`]) at `url` (setting
/// `cache.fetch_images`). Comes again when the host banner was reloaded
/// (`banner_gfx_interval_s`, at least a minute): the file at `path`
/// changed.
PictureReady {
session: SessionId,
url: String,
path: PathBuf,
},
/// Answer to [`Command::ListOfflineMessages`].
OfflineMessages {
session: SessionId,
+662 -38
View File
@@ -9,6 +9,10 @@
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use tokio::time::Instant;
use tokio::sync::{broadcast, mpsc, watch};
use tracing::debug;
@@ -38,6 +42,7 @@ use crate::stream::{
StreamInput, StreamKind, kind_name, parse_kind,
};
use crate::voice::{self, Remote, VoiceCmd, VoiceEvent, VoiceLink};
use crate::web;
use crate::{Command, Event, ObserveState, SessionId, SessionState, Shared, Source, VoiceState};
const NO_VOICE: &str = "not connected with voice";
@@ -108,6 +113,52 @@ enum SourceEvent {
KnownServer(String),
/// Our avatar file is uploaded (its MD5) or failed: announce it.
AvatarUploaded(u64, RequestId, Result<String, String>),
/// Time to fetch the host banner again (`banner_gfx_interval_s`).
ReloadBanner(String),
/// Image completion is checked against the current connection and presence.
ImageFinished(bool, u64, ImageRequest, Result<PathBuf, String>),
}
/// Identity of a wanted image, independent of its transport.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum ImageRequest {
Avatar { uid: String, hash: String },
Icon(u32),
Picture(String),
}
/// An image download over the voice connection, finished in the cache
/// once: with its result, or as failed when the request is dropped
/// unanswered (sent while the connection closes, or still queued when it
/// ends). Otherwise the key would stay in flight, and every later fetch of
/// it, in any session, would wait forever.
struct ImageDownload {
cache: cache::Cache,
key: String,
temp: PathBuf,
settings: SharedSettings,
done: AtomicBool,
}
impl ImageDownload {
fn finish(&self, result: Result<(), String>) {
if !self.done.swap(true, Ordering::AcqRel) {
self.cache.finish(&self.key, &self.temp, result, max_cache_bytes(&self.settings));
}
}
}
impl Drop for ImageDownload {
fn drop(&mut self) {
self.finish(Err("the voice connection closed".into()));
}
}
/// At most three retries (after 1, 4 and 16 seconds) per image version.
/// Keeping exhausted entries prevents presence traffic from causing a retry storm.
struct ImageRetry {
failures: u8,
due: Option<Instant>,
}
/// Our live stream, for the gateway's directory.
@@ -125,6 +176,7 @@ struct Session {
state: SessionState,
generation: u64,
voice: Option<(u64, mpsc::UnboundedSender<VoiceCmd>)>,
voice_address: String,
voice_presence: Option<Presence>,
nickname: String,
gateway: Option<(u64, mpsc::UnboundedSender<GatewayCmd>)>,
@@ -168,6 +220,14 @@ struct Session {
avatars: HashMap<String, String>,
/// Icons reported or being fetched, voice only.
icons: HashSet<u32>,
/// Pictures on the web (banners) reported or being fetched, by address.
pictures: HashSet<String>,
image_epoch: u64,
images_enabled: bool,
image_retries: HashMap<ImageRequest, ImageRetry>,
/// The host banner's address and reload interval (seconds) while it has
/// one, and the timer that asks for the reloads.
banner_reload: Option<(String, u64, tokio::task::AbortHandle)>,
/// Contact volume and mute applied per client.
contact_audio: HashMap<u16, (f32, bool)>,
/// Friends' client ids, as last told to the streams.
@@ -194,6 +254,11 @@ impl Session {
contacts_rx,
avatars: HashMap::new(),
icons: HashSet::new(),
pictures: HashSet::new(),
image_epoch: 0,
images_enabled: settings.current().get(&CACHE_FETCH_IMAGES),
image_retries: HashMap::new(),
banner_reload: None,
contact_audio: HashMap::new(),
stream_friends: BTreeSet::new(),
details: None,
@@ -203,6 +268,7 @@ impl Session {
state: SessionState::default(),
generation: 0,
voice: None,
voice_address: String::new(),
voice_presence: None,
nickname: String::new(),
gateway: None,
@@ -250,6 +316,8 @@ 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");
let mut image_tick = tokio::time::interval(Duration::from_secs(1));
image_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
cmd = commands.recv() => match cmd {
@@ -258,6 +326,7 @@ impl Session {
},
Some(event) = sources.recv() => self.source_event(event),
Ok(()) = contacts.changed() => self.contacts_changed(),
_ = image_tick.tick() => self.retry_images(Instant::now()),
}
}
self.stop_all();
@@ -293,6 +362,8 @@ impl Session {
}
self.stop_streams("voice reconnecting");
let generation = self.next_generation();
self.voice_address = options.address.clone();
self.details = None;
self.nickname = options.nickname.clone();
self.stream_peer = options.stream_peer.clone();
if let Some(profiles) = &self.srtp_profiles {
@@ -590,7 +661,7 @@ impl Session {
.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);
self.fetch_avatar(&client_uid, &hash, true);
}
}
Command::ListOfflineMessages { request, .. } => {
@@ -739,8 +810,11 @@ impl Session {
/// Forget what was reported about avatars and icons (a new connection
/// reports them again).
fn forget_images(&mut self) {
self.image_epoch += 1;
self.image_retries.clear();
self.avatars.clear();
self.icons.clear();
self.pictures.clear();
self.contact_audio.clear();
self.stream_friends.clear();
self.details = None;
@@ -756,7 +830,7 @@ impl Session {
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);
self.fetch_avatar(uid, hash, false);
}
avatars.insert(uid.clone(), hash.clone());
}
@@ -768,6 +842,7 @@ impl Session {
.chain(p.clients.values().map(|c| c.icon))
.filter(|id| *id >= files::FIRST_DOWNLOADABLE_ICON)
.collect::<BTreeSet<u32>>();
self.icons.retain(|id| icons.contains(id));
for id in icons {
if self.icons.insert(id) {
self.fetch_icon(id);
@@ -775,54 +850,236 @@ impl Session {
}
}
fn fetch_avatar(&self, uid: &str, hash: &str) {
fn image_waiter(&self, request: ImageRequest, requested: bool) -> Waiter {
let epoch = if requested {
self.voice.as_ref().map_or(0, |(generation, _)| *generation)
} else {
self.image_epoch
};
let sources = self.sources_tx.clone();
Box::new(move |result| {
let _ = sources.send(SourceEvent::ImageFinished(requested, epoch, request, result));
})
}
fn fetch_avatar(&self, uid: &str, hash: &str, requested: bool) {
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);
let waiter = self
.image_waiter(ImageRequest::Avatar { uid: uid.into(), hash: hash.into() }, requested);
self.fetch_image(key, files::avatar_path(uid).map(|path| (0, path)), false, 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);
let waiter = self.image_waiter(ImageRequest::Icon(icon), false);
self.fetch_image(cache::icon_key(icon), Some((0, files::icon_path(icon))), false, waiter);
}
/// Get `key` from the cache, downloading `path` of channel 0 once.
fn fetch_image(&self, key: String, path: Option<String>, waiter: Waiter) {
fn wants_image(&self, request: &ImageRequest) -> bool {
match request {
ImageRequest::Avatar { uid, hash } => {
self.voice.is_some() && self.avatars.get(uid) == Some(hash)
}
ImageRequest::Icon(id) => self.voice.is_some() && self.icons.contains(id),
ImageRequest::Picture(url) => self.pictures.contains(url),
}
}
fn image_finished(
&mut self,
requested: bool,
epoch: u64,
request: ImageRequest,
result: Result<PathBuf, String>,
) {
let wanted = if requested {
matches!(&request, ImageRequest::Avatar { uid, hash }
if self.voice.is_some() && self.voice_presence.as_ref()
.and_then(|p| p.client_by_uid(uid)).and_then(|c| c.avatar.as_ref()) == Some(hash))
} else {
self.wants_image(&request)
};
let current = if requested {
self.is_current(Source::Voice, epoch)
} else {
epoch == self.image_epoch
};
if !current || !wanted {
return;
}
match result {
Ok(path) => {
self.image_retries.remove(&request);
if !requested && !self.settings.current().get(&CACHE_FETCH_IMAGES) {
return;
}
let session = self.id;
self.emit(match request {
ImageRequest::Avatar { uid: client_uid, hash } => {
Event::AvatarReady { session, client_uid, hash, path }
}
ImageRequest::Icon(icon) => Event::IconReady { session, icon, path },
ImageRequest::Picture(url) => Event::PictureReady { session, url, path },
});
}
Err(error) => {
debug!(?request, %error, "image download failed");
let retry = self
.image_retries
.entry(request)
.or_insert(ImageRetry { failures: 0, due: None });
retry.failures = retry.failures.saturating_add(1);
retry.due = match retry.failures {
1..=3 => {
Some(Instant::now() + Duration::from_secs(1 << (2 * (retry.failures - 1))))
}
_ => None,
};
}
}
}
fn retry_images(&mut self, now: Instant) {
let enabled = self.settings.current().get(&CACHE_FETCH_IMAGES);
if enabled != self.images_enabled {
self.images_enabled = enabled;
self.image_epoch += 1;
self.avatars.clear();
self.icons.clear();
self.pictures.clear();
self.image_retries.clear();
if let Some((.., timer)) = self.banner_reload.take() {
timer.abort();
}
if enabled {
if let Some(presence) = self.voice_presence.clone() {
self.fetch_images(&presence);
}
self.publish_presence();
}
}
let obsolete: Vec<_> =
self.image_retries.keys().filter(|r| !self.wants_image(r)).cloned().collect();
for request in obsolete {
self.image_retries.remove(&request);
}
if !self.settings.current().get(&CACHE_FETCH_IMAGES) {
return;
}
let ready: Vec<_> = self
.image_retries
.iter_mut()
.filter_map(|(request, retry)| {
if retry.due.is_some_and(|due| due <= now) {
retry.due = None;
Some(request.clone())
} else {
None
}
})
.collect();
for request in ready {
match request {
ImageRequest::Avatar { uid, hash } => self.fetch_avatar(&uid, &hash, false),
ImageRequest::Icon(icon) => self.fetch_icon(icon),
ImageRequest::Picture(url) => self.fetch_picture(&url, true),
}
}
}
/// Whether the picture at `url` can be fetched now: on the web, or in
/// the server's files (`ts3image://`) while connected with voice.
fn can_fetch_picture(&self, url: &str) -> bool {
cache::picture_key(url).is_some()
|| (self.voice_presence.is_some() && files::server_image(url).is_some())
}
/// Fetch the banners of the presence shown (any source) that are new,
/// and have the host banner reloaded as often as the server asks.
fn fetch_pictures(&mut self, p: &Presence) {
let enabled = self.settings.current().get(&CACHE_FETCH_IMAGES);
let reload = Some((&p.server.banner_gfx_url, p.server.banner_gfx_interval_s))
.filter(|(url, every)| enabled && self.can_fetch_picture(url) && *every > 0);
if self.banner_reload.as_ref().map(|(url, every, _)| (url, *every)) != reload {
if let Some((.., timer)) = self.banner_reload.take() {
timer.abort();
}
if let Some((url, every_s)) = reload {
let every = std::time::Duration::from_secs(every_s).max(web::MIN_RELOAD);
let tx = self.sources_tx.clone();
let address = url.clone();
// Aborted when the banner changes or the session closes.
let timer = tokio::spawn(async move {
let start = tokio::time::Instant::now() + every;
let mut tick = tokio::time::interval_at(start, every);
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tick.tick().await;
if tx.send(SourceEvent::ReloadBanner(address.clone())).is_err() {
break;
}
}
});
self.banner_reload = Some((url.clone(), every_s, timer.abort_handle()));
}
}
if !enabled {
return;
}
let urls: HashSet<_> = std::iter::once(&p.server.banner_gfx_url)
.chain(p.channels.values().filter_map(|c| c.banner_gfx_url.as_ref()))
.filter(|u| self.can_fetch_picture(u))
.cloned()
.collect();
self.pictures.retain(|url| urls.contains(url));
for url in &urls {
if self.pictures.insert(url.clone()) {
self.fetch_picture(url, false);
}
}
}
/// Get the picture at `url` into the cache (again with `fresh`): from
/// the web, or from the server's files through the voice connection.
fn fetch_picture(&self, url: &str, fresh: bool) {
let waiter = self.image_waiter(ImageRequest::Picture(url.into()), false);
if let Some(file) = files::server_image(url) {
let server = self.state.server_uid.as_deref().unwrap_or(self.voice_address.as_str());
let key = cache::server_picture_key(server, url);
self.fetch_image(key, Some(file), fresh, waiter);
} else {
web::fetch(self.cache.current(), url, fresh, max_cache_bytes(&self.settings), waiter);
}
}
/// Get `key` from the cache, downloading `file` (channel and path) once
/// (again with `fresh`).
fn fetch_image(&self, key: String, file: Option<(u64, String)>, fresh: bool, 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));
let Fetch::Download(temp) = cache.fetch(&key, fresh, waiter) else { return };
let download = ImageDownload {
cache,
key,
temp: temp.clone(),
settings: self.settings.clone(),
done: AtomicBool::new(false),
};
let (Some((channel, path)), Some((_, voice))) = (file, &self.voice) else {
download.finish(Err(NO_VOICE.into()));
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())),
TransferState::Done { .. } => download.finish(Ok(())),
TransferState::Failed(e) => download.finish(Err(e)),
TransferState::Cancelled => download.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 });
let file = Remote { channel, password: None, path };
let failed = report.clone();
if voice.send(VoiceCmd::Download { transfer: None, file, sink, report }).is_err() {
failed(TransferState::Failed(NO_VOICE.into()));
}
}
// Contacts
@@ -879,7 +1136,11 @@ impl Session {
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 });
self.emit(Event::ServerDetails {
session: self.id,
address: self.voice_address.clone(),
details,
});
}
let sorted = |groups| -> Arc<Vec<GroupInfo>> {
Arc::new(Presence::sorted_groups(groups).into_iter().cloned().collect())
@@ -1227,6 +1488,10 @@ impl Session {
}
fn stop_all(&mut self) {
self.forget_images();
if let Some((.., timer)) = self.banner_reload.take() {
timer.abort();
}
self.stop_streams("session closed");
if let Some((_, tx)) = self.voice.take() {
let _ = tx.send(VoiceCmd::Disconnect);
@@ -1302,6 +1567,17 @@ impl Session {
self.emit(Event::RequestDone { session: self.id, request, result });
}
},
SourceEvent::ImageFinished(requested, epoch, request, result) => {
self.image_finished(requested, epoch, request, result);
}
SourceEvent::ReloadBanner(address) => {
if let Some((url, ..)) = &self.banner_reload
&& *url == address
&& self.settings.current().get(&CACHE_FETCH_IMAGES)
{
self.fetch_picture(url, true);
}
}
_ => debug!("event from a replaced source ignored"),
}
}
@@ -1613,8 +1889,356 @@ impl Session {
self.state.presence_source = source;
self.emit_state();
}
self.fetch_pictures(&presence);
let presence = Arc::new(presence);
self.contacts.presence(self.id, presence.clone());
self.emit(Event::Presence { session: self.id, presence });
}
}
#[cfg(test)]
mod banner_tests {
use super::*;
use crate::cache::Cache;
use crate::settings::Settings;
fn session(tag: &str) -> (Session, broadcast::Receiver<Event>) {
let (events, receiver) = broadcast::channel(16);
let (frames, _) = broadcast::channel(1);
let history = SharedHistory::default();
let dir = std::env::temp_dir()
.join(format!("voelin-session-banner-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let shared = Shared {
settings: SharedSettings::new(Settings::default()),
history: history.clone(),
cache: SharedCache::new(Cache::new(dir)),
contacts: Contacts::new(events.clone(), history),
};
(Session::new(1, events, frames, AudioSettings::default(), shared), receiver)
}
#[tokio::test]
async fn server_details_keep_source_address_and_repeat_after_reconnect() {
let (mut session, mut events) = session("details-address");
let mut presence = Presence::default();
presence.server.icon = 1234;
// Tasks are never polled in this test; the test runtime drops them
// without opening any network connections.
for address in ["a.test", "b.test", "b.test"] {
let mut options = crate::VoiceOptions::new(address, "test");
options.audio = false;
session.command(Command::ConnectVoice { session: 1, options: Box::new(options) });
session.report_details(&presence);
let mut reported = Vec::new();
while let Ok(event) = events.try_recv() {
if let Event::ServerDetails { address, details, .. } = event {
reported.push((address, details.icon));
}
}
assert_eq!(reported, vec![(address.to_owned(), 1234)]);
session.report_details(&presence);
assert!(events.try_recv().is_err());
}
session.stop_all();
}
#[tokio::test]
async fn failed_picture_retries_without_presence_update() {
let (mut session, mut events) = session("retry");
let mut presence = Presence::default();
presence.server.banner_gfx_url = "https://example.com/banner.png".into();
let url = &presence.server.banner_gfx_url;
let key = cache::picture_key(url).unwrap();
let request = ImageRequest::Picture(url.clone());
let cache = session.cache.current();
// Own the download so this exercises session completion without network I/O.
let Fetch::Download(temp) = cache.fetch(&key, false, Box::new(|_| {})) else {
panic!("first download");
};
session.fetch_pictures(&presence);
cache.finish(&key, &temp, Err("temporary failure".into()), 0);
let failure = session.sources_rx.as_mut().unwrap().recv().await.unwrap();
session.source_event(failure);
let due = session.image_retries[&request].due.unwrap();
session.retry_images(due - Duration::from_millis(1));
assert_eq!(session.image_retries[&request].due, Some(due));
let Fetch::Download(temp) = cache.fetch(&key, false, Box::new(|_| {})) else {
panic!("retry download");
};
session.retry_images(due);
assert!(session.image_retries[&request].due.is_none());
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
std::fs::write(&temp, b"picture").unwrap();
cache.finish(&key, &temp, Ok(()), 0);
let success = session.sources_rx.as_mut().unwrap().recv().await.unwrap();
session.source_event(success);
assert!(
matches!(events.try_recv(), Ok(Event::PictureReady { url: ready, .. }) if ready == *url)
);
assert!(!session.image_retries.contains_key(&request));
std::fs::remove_dir_all(cache.dir()).unwrap();
}
#[tokio::test]
async fn avatar_and_icon_failures_retry_and_report_success() {
let (mut session, mut events) = session("avatar-icon");
let (tx, mut commands) = mpsc::unbounded_channel();
session.voice = Some((1, tx));
let uid = "Af4=";
let hash = "0123456789abcdef0123456789abcdef";
session.avatars.insert(uid.into(), hash.into());
session.icons.insert(1234);
for request in
[ImageRequest::Avatar { uid: uid.into(), hash: hash.into() }, ImageRequest::Icon(1234)]
{
session.image_finished(
false,
session.image_epoch,
request.clone(),
Err("temporarily unavailable".into()),
);
session.retry_images(session.image_retries[&request].due.unwrap());
let VoiceCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
commands.try_recv().unwrap()
else {
panic!("expected an image download");
};
assert_eq!(
file.path,
if matches!(request, ImageRequest::Icon(_)) {
"/icon_1234"
} else {
"/avatar_abpo"
}
);
std::fs::create_dir_all(part.parent().unwrap()).unwrap();
std::fs::write(&part, b"image").unwrap();
report(TransferState::Done { size: 5, path: Some(part), data: None });
let completion = session.sources_rx.as_mut().unwrap().recv().await.unwrap();
session.source_event(completion);
assert!(!session.image_retries.contains_key(&request));
}
assert!(matches!(events.try_recv(), Ok(Event::AvatarReady { .. })));
assert!(matches!(events.try_recv(), Ok(Event::IconReady { icon: 1234, .. })));
std::fs::remove_dir_all(session.cache.current().dir()).unwrap();
}
/// A banner in the server's files (`ts3image://`) comes through the
/// voice connection's file transfer, from its channel and path.
#[tokio::test]
async fn banners_in_the_server_files_come_through_voice() {
let (mut session, mut events) = session("server-files");
let url = "ts3image://ts.example.test?port=9987&channel=7&path=%2Fbanners&filename=raid%20night.png";
let mut presence = Presence::default();
let channel = voelin_model::ChannelInfo {
id: 7,
banner_gfx_url: Some(url.into()),
..Default::default()
};
presence.channels.insert(7, channel);
// Observed without voice: no file transfer to ask yet.
session.fetch_pictures(&presence);
assert!(session.pictures.is_empty());
let (tx, mut commands) = mpsc::unbounded_channel();
session.voice = Some((1, tx));
session.voice_presence = Some(presence.clone());
session.state.server_uid = Some("server-a".into());
session.fetch_pictures(&presence);
assert!(session.pictures.contains(url));
let VoiceCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
commands.try_recv().unwrap()
else {
panic!("expected a file download");
};
assert_eq!((file.channel, file.path.as_str()), (7, "/banners/raid night.png"));
std::fs::create_dir_all(part.parent().unwrap()).unwrap();
std::fs::write(&part, b"banner").unwrap();
report(TransferState::Done { size: 6, path: Some(part), data: None });
let completion = session.sources_rx.as_mut().unwrap().recv().await.unwrap();
session.source_event(completion);
let Ok(Event::PictureReady { url: ready, path, .. }) = events.try_recv() else {
panic!("expected the banner");
};
assert_eq!(ready, url);
// Named by the server too: the same address elsewhere is another file.
let key = cache::server_picture_key("server-a", url);
assert_eq!(path, session.cache.current().dir().join(key));
assert_eq!(std::fs::read(path).unwrap(), b"banner");
std::fs::remove_dir_all(session.cache.current().dir()).unwrap();
}
/// A request the voice connection drops unanswered (sent while it
/// closes) fails, instead of leaving the picture in flight for good.
#[tokio::test]
async fn a_dropped_image_request_fails_instead_of_waiting_forever() {
let (mut session, _events) = session("dropped");
let (tx, mut commands) = mpsc::unbounded_channel();
session.voice = Some((1, tx));
session.icons.insert(1234);
session.fetch_icon(1234);
drop(commands.try_recv().unwrap());
let Some(SourceEvent::ImageFinished(_, _, ImageRequest::Icon(1234), Err(_))) =
session.sources_rx.as_mut().unwrap().recv().await
else {
panic!("expected the icon to fail");
};
// The next fetch downloads again instead of waiting for the lost one.
let cache = session.cache.current();
let next = cache.fetch(&cache::icon_key(1234), false, Box::new(|_| {}));
assert!(matches!(next, Fetch::Download(_)));
let _ = std::fs::remove_dir_all(cache.dir());
}
#[tokio::test]
async fn retries_are_bounded_and_obey_policy_presence_and_epoch() {
let (mut session, mut events) = session("retry-guards");
let url = "https://example.com/banner.png";
let request = ImageRequest::Picture(url.into());
session.pictures.insert(url.into());
for failure in 1..=4 {
session.image_finished(
false,
session.image_epoch,
request.clone(),
Err("unavailable".into()),
);
let retry = &session.image_retries[&request];
assert_eq!(retry.failures, failure);
assert_eq!(retry.due.is_some(), failure <= 3);
}
assert!(events.try_recv().is_err());
// Disabling fetch invalidates pending retries and completions.
session.image_retries.get_mut(&request).unwrap().due = Some(Instant::now());
session.settings.current().set(&CACHE_FETCH_IMAGES, false).unwrap();
session.retry_images(Instant::now());
assert!(session.image_retries.is_empty());
// Replaced URLs must neither retry nor publish delayed successes.
session.pictures.clear();
session.settings.current().set(&CACHE_FETCH_IMAGES, true).unwrap();
session.retry_images(Instant::now());
assert!(session.image_retries.is_empty());
session.image_finished(false, session.image_epoch, request.clone(), Ok("obsolete".into()));
while let Ok(event) = events.try_recv() {
assert!(!matches!(event, Event::PictureReady { .. }));
}
let old_epoch = session.image_epoch;
session.forget_images();
session.pictures.insert(url.into());
session.image_finished(false, old_epoch, request.clone(), Err("old connection".into()));
session.image_finished(false, old_epoch, request, Ok("old connection".into()));
assert!(session.image_retries.is_empty());
assert!(events.try_recv().is_err());
}
#[tokio::test]
async fn explicit_avatar_request_works_with_automatic_fetching_disabled() {
let (mut session, mut events) = session("explicit-avatar");
session.settings.current().set(&CACHE_FETCH_IMAGES, false).unwrap();
session.retry_images(Instant::now());
let uid = "Af4=";
let hash = "0123456789abcdef0123456789abcdef";
let mut presence = Presence::default();
presence.clients.insert(
1,
voelin_model::ClientInfo {
id: 1,
uid: Some(uid.into()),
avatar: Some(hash.into()),
..Default::default()
},
);
session.voice_presence = Some(presence);
let (tx, _rx) = mpsc::unbounded_channel();
session.voice = Some((1, tx));
let cache = session.cache.current();
let key = cache::avatar_key(hash).unwrap();
let Fetch::Download(temp) = cache.fetch(&key, false, Box::new(|_| {})) else {
panic!("first download");
};
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
std::fs::write(&temp, b"avatar").unwrap();
cache.finish(&key, &temp, Ok(()), 0);
session.command(Command::FetchAvatar { session: 1, client_uid: uid.into() });
let completion = session.sources_rx.as_mut().unwrap().recv().await.unwrap();
session.source_event(completion);
assert!(
matches!(events.try_recv(), Ok(Event::AvatarReady { client_uid, .. }) if client_uid == uid)
);
// A policy change must invalidate automatic completions, not this explicit request.
session.command(Command::FetchAvatar { session: 1, client_uid: uid.into() });
let completion = session.sources_rx.as_mut().unwrap().recv().await.unwrap();
session.settings.current().set(&CACHE_FETCH_IMAGES, true).unwrap();
session.retry_images(Instant::now());
while events.try_recv().is_ok() {}
session.source_event(completion);
assert!(
matches!(events.try_recv(), Ok(Event::AvatarReady { client_uid, .. }) if client_uid == uid)
);
std::fs::remove_dir_all(cache.dir()).unwrap();
}
#[tokio::test]
async fn enabling_images_replays_current_presence_without_server_updates() {
let (mut session, mut events) = session("policy-enable");
let url = "https://example.com/banner.png";
let cache = session.cache.current();
let key = cache::picture_key(url).unwrap();
let Fetch::Download(temp) = cache.fetch(&key, false, Box::new(|_| {})) else {
panic!("first download");
};
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
std::fs::write(&temp, b"cached image").unwrap();
cache.finish(&key, &temp, Ok(()), 0);
let mut presence = Presence::default();
presence.server.banner_gfx_url = url.into();
session.gateway_presence = Some(presence);
session.settings.current().set(&CACHE_FETCH_IMAGES, false).unwrap();
session.retry_images(Instant::now());
session.settings.current().set(&CACHE_FETCH_IMAGES, true).unwrap();
session.retry_images(Instant::now());
let completion = session.sources_rx.as_mut().unwrap().recv().await.unwrap();
session.source_event(completion);
let mut ready = false;
while let Ok(event) = events.try_recv() {
if matches!(event, Event::PictureReady { url: address, .. } if address == url) {
ready = true;
}
}
assert!(ready);
std::fs::remove_dir_all(cache.dir()).unwrap();
}
#[tokio::test]
async fn reload_timer_obeys_policy_and_is_stopped_with_session() {
let (mut session, _) = session("timer");
let mut presence = Presence::default();
presence.server.banner_gfx_url = "https://example.com/banner.png".into();
presence.server.banner_gfx_interval_s = 60;
session.settings.current().set(&CACHE_FETCH_IMAGES, false).unwrap();
session.fetch_pictures(&presence);
assert!(session.banner_reload.is_none());
assert!(session.pictures.is_empty());
let cache = session.cache.current();
let key = cache::picture_key(&presence.server.banner_gfx_url).unwrap();
let _pending = cache.fetch(&key, false, Box::new(|_| {}));
session.settings.current().set(&CACHE_FETCH_IMAGES, true).unwrap();
session.fetch_pictures(&presence);
let timer = session.banner_reload.as_ref().unwrap().2.clone();
session.settings.current().set(&CACHE_FETCH_IMAGES, false).unwrap();
session.fetch_pictures(&presence);
assert!(session.banner_reload.is_none());
tokio::task::yield_now().await;
assert!(timer.is_finished());
session.settings.current().set(&CACHE_FETCH_IMAGES, true).unwrap();
session.fetch_pictures(&presence);
let timer = session.banner_reload.as_ref().unwrap().2.clone();
session.stop_all();
assert!(session.banner_reload.is_none());
tokio::task::yield_now().await;
assert!(timer.is_finished());
}
}
+2 -2
View File
@@ -1125,11 +1125,11 @@ pub static CACHE_MAX_MB: Key<u64> = Key::new(
|| 256,
);
/// Download the avatars and icons of servers we are on by themselves.
/// Download the avatars, icons and banners of servers we are on.
pub static CACHE_FETCH_IMAGES: Key<bool> = Key::new(
"cache.fetch_images",
Kind::Bool,
"Download avatars and icons of the servers we are on.",
"Download avatars, icons and banners of the servers we are on.",
|| true,
);
+110 -12
View File
@@ -28,6 +28,7 @@ use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
use voelin_stream::{PeerConfig, Request, StreamNotification};
use crate::book::presence_from_book;
use crate::cache;
use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState};
use crate::offline::{OfflineMessage, OfflineMessageInfo};
use crate::settings::{FILES_PROGRESS_MS, SharedSettings};
@@ -255,8 +256,19 @@ enum Pending {
/// A transfer the server has not opened yet.
enum Job {
Download { transfer: Option<TransferId>, offset: u64, sink: Sink, report: Report },
Upload { transfer: Option<TransferId>, from: PathBuf, size: u64, report: Report },
Download {
transfer: Option<TransferId>,
offset: u64,
sink: Sink,
report: Report,
started: Instant,
},
Upload {
transfer: Option<TransferId>,
from: PathBuf,
size: u64,
report: Report,
},
}
impl Job {
@@ -273,6 +285,25 @@ impl Job {
}
}
/// How long a picture of `size` bytes may take to arrive: half a minute,
/// plus its size at [`cache::MIN_PICTURE_RATE`], so large banners arrive on
/// slow links while a stalled transfer still ends.
fn image_download_time(size: u64) -> Duration {
Duration::from_secs(30 + size / cache::MIN_PICTURE_RATE)
}
/// Bound background image handshakes without imposing a deadline on user transfers.
fn expire_image_jobs(jobs: &mut HashMap<FiletransferHandle, Job>, now: Instant) {
jobs.retain(|_, job| {
if matches!(job, Job::Download { transfer: None, started, .. } if now.duration_since(*started) >= Duration::from_secs(15)) {
job.report()(TransferState::Failed("image transfer negotiation timed out".into()));
false
} else {
true
}
});
}
/// A user's transfer, for cancelling.
enum Slot {
Waiting(FiletransferHandle),
@@ -427,6 +458,7 @@ impl Voice {
}
fn tick(&mut self) {
expire_image_jobs(&mut self.jobs, Instant::now());
let events = &self.events;
self.talking.retain(|client, last| {
let active = last.elapsed() < Duration::from_millis(400);
@@ -468,18 +500,35 @@ impl Voice {
}
}
StreamItem::FileDownload(handle, download) => {
if let Some(Job::Download { transfer, offset, sink, report }) =
if let Some(Job::Download { transfer, offset, sink, report, .. }) =
self.jobs.remove(&handle)
{
// Pictures (avatars, icons, banners): bounded like the
// banners on the web, the user's own files are not.
if transfer.is_none() && download.size > cache::MAX_PICTURE_BYTES {
let limit = cache::MAX_PICTURE_BYTES >> 20;
report(TransferState::Failed(format!("larger than {limit} MiB")));
return Ok(());
}
let part = sink.part().map(ToOwned::to_owned);
let task = tokio::spawn(files::download(
download.stream,
download.size,
offset,
sink,
self.progress_every(),
report.clone(),
));
let progress = self.progress_every();
let task_report = report.clone();
let deadline = image_download_time(download.size);
let task = tokio::spawn(async move {
let receive = files::download(
download.stream,
download.size,
offset,
sink,
progress,
task_report.clone(),
);
if transfer.is_some() {
receive.await;
} else if timeout(deadline, receive).await.is_err() {
task_report(TransferState::Failed("image download timed out".into()));
}
});
self.running(transfer, task.abort_handle(), part, report);
}
}
@@ -760,7 +809,10 @@ impl Voice {
}
};
report(TransferState::Requested);
self.jobs.insert(handle, Job::Download { transfer, offset, sink, report });
self.jobs.insert(
handle,
Job::Download { transfer, offset, sink, report, started: Instant::now() },
);
if let Some(id) = transfer {
self.transfers.insert(id, Slot::Waiting(handle));
}
@@ -923,3 +975,49 @@ fn transfer_error(error: &tsclientlib::Error) -> String {
e => e.to_string(),
}
}
#[cfg(test)]
mod image_download_tests {
use super::*;
use std::sync::{Arc, Mutex};
#[test]
fn stalled_image_handshake_expires_but_user_transfer_does_not() {
let started = Instant::now();
let reports = Arc::new(Mutex::new(Vec::new()));
let sink = reports.clone();
let report: Report = Arc::new(move |state| sink.lock().unwrap().push(state));
let mut jobs = HashMap::new();
for (id, transfer) in [(1, None), (2, Some(77))] {
jobs.insert(
FiletransferHandle(id),
Job::Download {
transfer,
offset: 0,
sink: Sink::Memory,
report: report.clone(),
started,
},
);
}
expire_image_jobs(&mut jobs, started + Duration::from_secs(14));
assert_eq!(jobs.len(), 2);
assert!(reports.lock().unwrap().is_empty());
expire_image_jobs(&mut jobs, started + Duration::from_secs(15));
assert_eq!(jobs.len(), 1);
assert!(jobs.contains_key(&FiletransferHandle(2)));
assert!(
matches!(&reports.lock().unwrap()[..], [TransferState::Failed(error)] if error.contains("timed out"))
);
expire_image_jobs(&mut jobs, started + Duration::from_secs(60));
assert_eq!(reports.lock().unwrap().len(), 1);
}
#[test]
fn large_pictures_get_time_to_arrive() {
assert_eq!(image_download_time(0), Duration::from_secs(30));
assert_eq!(image_download_time(100 << 10), Duration::from_secs(33));
// The largest picture, at the slowest rate allowed.
assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(30 + 2048));
}
}
+378
View File
@@ -0,0 +1,378 @@
//! Pictures from the web: the host banner and TeamSpeak 6 channel banners,
//! which servers give as `http(s)` addresses on any host.
//!
//! They go into the engine's cache ([`crate::cache`], named by the MD5 hash
//! of the address) like avatars and icons, and only with
//! `cache.fetch_images`: fetching one contacts a host the server chose, as
//! the official client does. A picture is at most
//! [`cache::MAX_PICTURE_BYTES`] and goes to disk as it arrives; it connects
//! within [`CONNECT_TIMEOUT`], and a download fails when nothing arrives for
//! [`READ_TIMEOUT`] or, after [`GRACE`], when it averages less than
//! [`cache::MIN_PICTURE_RATE`]: a large banner on a slow host still arrives.
//! It is kept only if its content is a picture the UI shows (PNG, JPEG,
//! GIF, WebP, SVG), whatever its address or the server say. The client is
//! the workspace's reqwest with rustls: system proxies (`HTTPS_PROXY`,
//! `NO_PROXY`, …) and the platform's certificate store.
//!
//! Banners in the server's own files (`ts3image://`) come through the voice
//! connection instead ([`crate::files::server_image`]).
use std::path::Path;
use std::sync::LazyLock;
use std::time::Duration;
use tokio::io::AsyncWriteExt;
use crate::cache::{self, Cache, Fetch, Waiter};
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const READ_TIMEOUT: Duration = Duration::from_secs(20);
/// How long a download may start slowly before its rate counts.
const GRACE: Duration = Duration::from_secs(30);
/// The first bytes, enough to tell a picture from an error page.
const SNIFF: usize = 1024;
/// The pictures the UI decodes, so a host choosing between formats
/// (`Accept`) does not answer with one it cannot show (AVIF, JPEG XL).
const ACCEPT: &str = "image/png,image/jpeg,image/gif,image/webp,image/svg+xml;q=0.9,*/*;q=0.1";
/// Fetch independent URLs in parallel without letting a large channel tree
/// open unbounded connections or buffer unbounded image data.
static DOWNLOADS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(8);
/// The host banner is reloaded at most this often, whatever the server
/// asks (TeamSpeak 3 and 6 servers refuse intervals below a minute).
pub(crate) const MIN_RELOAD: Duration = Duration::from_secs(60);
static CLIENT: LazyLock<Result<reqwest::Client, String>> = LazyLock::new(|| {
reqwest::Client::builder()
.connect_timeout(CONNECT_TIMEOUT)
.read_timeout(READ_TIMEOUT)
.user_agent(concat!("Voelin/", env!("CARGO_PKG_VERSION")))
.build()
.map_err(|e| e.to_string())
});
/// Get the picture at `url` into `cache`, downloading it once however many
/// ask (again with `fresh`: it changes at its address); `waiter` is told
/// where it is. `max_cache_bytes`: `cache.max_mb` in bytes.
pub(crate) fn fetch(cache: Cache, url: &str, fresh: bool, max_cache_bytes: u64, waiter: Waiter) {
let Some(key) = cache::picture_key(url) else {
waiter(Err("not an http or https address".into()));
return;
};
let Fetch::Download(temp) = cache.fetch(&key, fresh, waiter) else { return };
let url = url.to_owned();
tokio::spawn(async move {
let _permit = DOWNLOADS.acquire().await.expect("download semaphore stays open");
let result = download(&url, &temp, &LIMITS).await;
cache.finish(&key, &temp, result, max_cache_bytes);
});
}
/// How large and how slow a download may be.
struct Limits {
max_bytes: u64,
grace: Duration,
/// Bytes a second, on average since the start, once `grace` is over.
min_rate: u64,
}
const LIMITS: Limits =
Limits { max_bytes: cache::MAX_PICTURE_BYTES, grace: GRACE, min_rate: cache::MIN_PICTURE_RATE };
/// Download the picture at `url` into `to` within `limits`, and only if it
/// is a picture (what arrived stays in `to` on failure; the cache removes it).
async fn download(url: &str, to: &Path, limits: &Limits) -> Result<(), String> {
let client = CLIENT.as_ref().map_err(Clone::clone)?;
let too_big = || format!("larger than {} KiB", limits.max_bytes >> 10);
let mut response = client
.get(url)
.header(reqwest::header::ACCEPT, ACCEPT)
.send()
.await
.and_then(reqwest::Response::error_for_status)
.map_err(|e| e.to_string())?;
if response.content_length().is_some_and(|n| n > limits.max_bytes) {
return Err(too_big());
}
if let Some(dir) = to.parent() {
tokio::fs::create_dir_all(dir).await.map_err(|e| e.to_string())?;
}
let mut file = tokio::fs::File::create(to).await.map_err(|e| e.to_string())?;
let started = tokio::time::Instant::now();
let mut head = Vec::with_capacity(SNIFF);
let mut received = 0u64;
while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? {
received += chunk.len() as u64;
if received > limits.max_bytes {
return Err(too_big());
}
if head.len() < SNIFF {
head.extend_from_slice(&chunk[..chunk.len().min(SNIFF - head.len())]);
// An error page is refused without waiting for all of it.
if head.len() == SNIFF && !is_picture(&head) {
return Err("not a picture".into());
}
}
let elapsed = started.elapsed();
let expected = limits.min_rate.saturating_mul(elapsed.as_millis() as u64) / 1000;
if elapsed > limits.grace && received < expected {
return Err(format!("too slow: {} KiB in {} s", received >> 10, elapsed.as_secs()));
}
file.write_all(&chunk).await.map_err(|e| e.to_string())?;
}
file.flush().await.map_err(|e| e.to_string())?;
drop(file);
if !is_picture(&head) {
return Err("not a picture".into());
}
Ok(())
}
/// Whether `data` is a picture the UI decodes, told by its content as the
/// UI tells it (SVG by its start, without leading blanks).
fn is_picture(data: &[u8]) -> bool {
const STARTS: [&[u8]; 4] = [b"\x89PNG\r\n\x1a\n", b"\xff\xd8\xff", b"GIF87a", b"GIF89a"];
let xml = data.strip_prefix(b"\xef\xbb\xbf").unwrap_or(data).trim_ascii_start();
STARTS.iter().any(|s| data.starts_with(s))
|| xml.starts_with(b"<?xml")
|| xml.starts_with(b"<svg")
|| (data.len() >= 12 && data.starts_with(b"RIFF") && &data[8..12] == b"WEBP")
}
#[cfg(test)]
mod tests {
use std::sync::mpsc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use super::*;
const PNG: &[u8] = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR\0\0\0\x01\0\0\0\x01\x08\x06\0\0\0\x1f\x15\xc4\x89\0\0\0\rIDATx\xdac\xf8\xcf\xc0\xf0\x1f\0\x05\0\x01\xff\x89\x99=\x1d\0\0\0\0IEND\xaeB`\x82";
/// An HTTP server on 127.0.0.1 with a few answers; returns its address.
async fn server() -> String {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
loop {
let Ok((mut socket, _)) = listener.accept().await else { return };
tokio::spawn(async move {
let mut request = Vec::new();
let mut buf = [0u8; 1024];
while !request.windows(4).any(|w| w == b"\r\n\r\n") {
match socket.read(&mut buf).await {
Ok(0) | Err(_) => return,
Ok(n) => request.extend_from_slice(&buf[..n]),
}
}
let path = String::from_utf8_lossy(&request)
.split_whitespace()
.nth(1)
.unwrap_or("/")
.to_owned();
let (status, length, body): (&str, bool, Vec<u8>) = match path.as_str() {
"/banner" => ("200 OK", true, PNG.to_vec()),
"/svg" => {
("200 OK", true, b"<svg xmlns='http://www.w3.org/2000/svg'/>".to_vec())
}
// Above the earlier limits of 4 and 16 MiB.
"/large-banner" => ("200 OK", true, [PNG, &vec![0; 20 << 20]].concat()),
// Too big, as announced or as it comes.
"/big" => ("200 OK", true, [PNG, &[0; 4000]].concat()),
"/big-unannounced" => ("200 OK", false, [PNG, &[0; 4000]].concat()),
"/page" => ("200 OK", true, b"<!DOCTYPE html><html></html>".to_vec()),
"/long-page" => {
("200 OK", false, [b"<!DOCTYPE html>", &[b' '; 4000][..]].concat())
}
// A picture, then a byte every 100 ms.
"/slow" => ("200 OK", true, [PNG, &[0; 20]].concat()),
_ => ("404 Not Found", true, b"no".to_vec()),
};
let mut head = format!("HTTP/1.1 {status}\r\nConnection: close\r\n");
if length {
head += &format!("Content-Length: {}\r\n", body.len());
}
head += "\r\n";
let _ = socket.write_all(head.as_bytes()).await;
if path == "/slow" {
let (picture, rest) = body.split_at(PNG.len());
let _ = socket.write_all(picture).await;
for byte in rest {
tokio::time::sleep(Duration::from_millis(100)).await;
if socket.write_all(&[*byte]).await.is_err() {
return;
}
}
return;
}
let _ = socket.write_all(&body).await;
});
}
});
format!("http://{addr}")
}
fn temp_dir(tag: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("voelin-web-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
dir
}
#[tokio::test]
async fn downloads_pictures_only() {
let base = server().await;
let dir = temp_dir("download");
let to = dir.join("tmp/x.part");
let limits = Limits { max_bytes: 1000, ..LIMITS };
download(&format!("{base}/banner"), &to, &limits).await.unwrap();
assert_eq!(std::fs::read(&to).unwrap(), PNG);
download(&format!("{base}/svg"), &to, &limits).await.unwrap();
for (path, error) in [
("/big", "larger than"),
("/big-unannounced", "larger than"),
("/page", "not a picture"),
("/missing", "404"),
] {
let e = download(&format!("{base}{path}"), &to, &limits).await.unwrap_err();
assert!(e.contains(error), "{path}: {e}");
}
// An error page longer than the first bytes looked at, unannounced.
let e = download(&format!("{base}/long-page"), &to, &LIMITS).await.unwrap_err();
assert!(e.contains("not a picture"), "{e}");
// Nothing listens there.
let port = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap().port();
assert!(download(&format!("http://127.0.0.1:{port}/b"), &to, &limits).await.is_err());
std::fs::remove_dir_all(dir).unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn fetch_into_the_cache() {
let base = server().await;
let dir = temp_dir("fetch");
let cache = Cache::new(&dir);
let (tx, rx) = mpsc::channel();
let waiter = |tx: &mpsc::Sender<_>| -> Waiter {
let tx = tx.clone();
Box::new(move |r| tx.send(r).unwrap())
};
let url = format!("{base}/banner");
fetch(cache.clone(), &url, false, 0, waiter(&tx));
let path = tokio::task::spawn_blocking(move || rx.recv().unwrap()).await.unwrap().unwrap();
assert_eq!(path, dir.join(cache::picture_key(&url).unwrap()));
assert_eq!(std::fs::read(&path).unwrap(), PNG);
// Not on the web: refused at once, nothing cached.
let (tx, rx) = mpsc::channel();
fetch(cache.clone(), "file:///etc/hostname", false, 0, waiter(&tx));
assert!(rx.recv().unwrap().unwrap_err().contains("http"));
// A failed download is reported and leaves nothing behind.
fetch(cache.clone(), &format!("{base}/page"), false, 0, waiter(&tx));
let failed = tokio::task::spawn_blocking(move || rx.recv().unwrap()).await.unwrap();
assert_eq!(failed, Err("not a picture".into()));
assert_eq!(cache.size(), PNG.len() as u64);
std::fs::remove_dir_all(dir).unwrap();
}
#[tokio::test]
async fn banners_above_the_old_limits_are_downloaded() {
let base = server().await;
let dir = temp_dir("large-banner");
let path = dir.join("large");
download(&format!("{base}/large-banner"), &path, &LIMITS).await.unwrap();
assert!(std::fs::metadata(&path).unwrap().len() > 16 << 20);
std::fs::remove_dir_all(dir).unwrap();
}
#[tokio::test]
async fn a_trickling_download_ends_after_its_grace() {
let base = server().await;
let dir = temp_dir("slow");
let to = dir.join("slow");
// Slow, but within its grace: it arrives.
let patient = Limits { grace: Duration::from_secs(60), ..LIMITS };
download(&format!("{base}/slow"), &to, &patient).await.unwrap();
let strict = Limits { grace: Duration::from_millis(150), min_rate: 1 << 20, ..LIMITS };
let e = download(&format!("{base}/slow"), &to, &strict).await.unwrap_err();
assert!(e.contains("too slow"), "{e}");
std::fs::remove_dir_all(dir).unwrap();
}
#[tokio::test]
async fn distinct_banners_download_concurrently_and_duplicates_share_a_request() {
use std::sync::Arc;
use tokio::sync::{Semaphore, mpsc as async_mpsc};
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let (requests, mut received) = async_mpsc::unbounded_channel();
let release = Arc::new(Semaphore::new(0));
let gate = release.clone();
let server = tokio::spawn(async move {
while let Ok((mut socket, _)) = listener.accept().await {
let (requests, gate) = (requests.clone(), gate.clone());
tokio::spawn(async move {
let mut request = Vec::new();
let mut buf = [0; 1024];
while !request.windows(4).any(|w| w == b"\r\n\r\n") {
let n = socket.read(&mut buf).await.unwrap();
assert!(n > 0);
request.extend_from_slice(&buf[..n]);
}
requests.send(()).unwrap();
let permit = gate.acquire().await.unwrap();
permit.forget();
let head = format!(
"HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: {}\r\n\r\n",
PNG.len()
);
socket.write_all(head.as_bytes()).await.unwrap();
socket.write_all(PNG).await.unwrap();
});
}
});
let dir = temp_dir("parallel");
let cache = Cache::new(&dir);
let (completed, mut results) = async_mpsc::unbounded_channel();
for path in ["one", "two", "three", "one"] {
let completed = completed.clone();
fetch(
cache.clone(),
&format!("{base}/{path}"),
false,
0,
Box::new(move |r| {
completed.send(r).unwrap();
}),
);
}
// All three requests arrive before any response is released: no
// slow banner can serialize the other downloads.
for _ in 0..3 {
tokio::time::timeout(Duration::from_secs(5), received.recv()).await.unwrap().unwrap();
}
release.add_permits(3);
for _ in 0..4 {
let path = tokio::time::timeout(Duration::from_secs(5), results.recv())
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(std::fs::read(path).unwrap(), PNG);
}
assert!(received.try_recv().is_err(), "duplicate URL opened another connection");
server.abort();
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn pictures_by_content() {
assert!(is_picture(PNG));
assert!(is_picture(b"\xff\xd8\xff\xe0\0\x10JFIF"));
assert!(is_picture(b"GIF89a\x01\0\x01\0"));
assert!(is_picture(b"RIFF\x24\0\0\0WEBPVP8 "));
assert!(is_picture(b"<?xml version=\"1.0\"?><svg/>"));
assert!(is_picture(b"\xef\xbb\xbf\n <svg/>"));
assert!(is_picture(b" \r\n<svg/>"));
assert!(!is_picture(b"<!DOCTYPE html>"));
assert!(!is_picture(b"RIFF\x24\0\0\0WAVEfmt "));
assert!(!is_picture(b""));
}
}
+321
View File
@@ -122,3 +122,324 @@ async fn ts3_engine() {
engine_roundtrip("127.0.0.1:9987", query(voelin_query::Transport::Raw, "127.0.0.1:10011"))
.await;
}
/// A 1×1 PNG.
const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
/// An HTTP server that fails each URL once with 503, then returns `body`;
/// returns its address. The engine fetches banners itself (the server only
/// passes their addresses on), so it reaches this one.
async fn serve(body: Vec<u8>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let requests = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let count = requests.clone();
let seen = std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashSet::new()));
tokio::spawn(async move {
while let Ok((mut socket, _)) = listener.accept().await {
let body = body.clone();
let count = count.clone();
let seen = seen.clone();
tokio::spawn(async move {
let mut request = Vec::new();
let mut buf = [0u8; 1024];
while !request.windows(4).any(|w| w == b"\r\n\r\n") {
match socket.read(&mut buf).await {
Ok(0) | Err(_) => return,
Ok(n) => request.extend_from_slice(&buf[..n]),
}
}
count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let target =
String::from_utf8_lossy(&request).split_whitespace().nth(1).unwrap().to_owned();
let first = seen.lock().unwrap().insert(target);
if first {
let _ = socket.write_all(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").await;
return;
}
let head = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
let _ = socket.write_all(head.as_bytes()).await;
let _ = socket.write_all(&body).await;
});
}
});
(format!("http://{addr}"), requests)
}
/// Banner policy, channel edits/removal and the host refresh against a real TS6.
/// Override only this test's endpoints to use a private fixture. Server settings
/// and the temporary channel are restored even when the assertions panic.
#[tokio::test(flavor = "multi_thread")]
async fn ts6_banners() {
use base64::Engine as _;
use std::sync::atomic::Ordering;
use voelin_core::settings::CACHE_FETCH_IMAGES;
use voelin_model::BannerMode;
use voelin_query::{Command as Query, QueryClient};
if !live() {
return;
}
let voice_addr =
std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into());
let query_addr =
std::env::var("VOELIN_BANNER_QUERY_ADDR").unwrap_or_else(|_| "127.0.0.1:10022".into());
let png = base64::prelude::BASE64_STANDARD.decode(PNG).unwrap();
let (base, requests) = serve(png.clone()).await;
let (host_url, channel_url) = (format!("{base}/host.png"), format!("{base}/channel.png"));
let (admin, _) =
QueryClient::connect(&query(voelin_query::Transport::Ssh, &query_addr)).await.unwrap();
let info = admin.send(&Query::new("serverinfo")).await.unwrap().remove(0);
let before = |key: &str| info.get(key).unwrap_or_default().to_owned();
let restore = Query::new("serveredit")
.arg("virtualserver_hostbanner_gfx_url", before("virtualserver_hostbanner_gfx_url"))
.arg("virtualserver_hostbanner_mode", before("virtualserver_hostbanner_mode"))
.arg(
"virtualserver_hostbanner_gfx_interval",
before("virtualserver_hostbanner_gfx_interval"),
);
let created = admin
.send(
&Query::new("channelcreate")
.arg("channel_name", format!("banner-{}", std::process::id()))
.arg("channel_flag_permanent", 1)
.arg("channel_banner_gfx_url", &channel_url)
.arg("channel_banner_mode", 1),
)
.await
.unwrap();
let cid = created[0].get("cid").unwrap().to_owned();
let channel_id: u64 = cid.parse().unwrap();
let engine = Engine::start();
engine.settings().set(&CACHE_FETCH_IMAGES, false).unwrap();
let dir = std::env::temp_dir().join(format!("voelin-live-banners-{}", std::process::id()));
engine.send(Command::AttachCache(dir.clone()));
let check = {
let (admin, engine, cid) = (admin.clone(), engine.clone(), cid.clone());
tokio::spawn(async move {
admin
.send(
&Query::new("serveredit")
.arg("virtualserver_hostbanner_gfx_url", &host_url)
.arg("virtualserver_hostbanner_mode", 2)
.arg("virtualserver_hostbanner_gfx_interval", 60),
)
.await
.unwrap();
let mut events = engine.subscribe();
engine.send(Command::ConnectVoice {
session: 1,
options: Box::new(VoiceOptions::new(&voice_addr, "banner-check")),
});
wait_for(&mut events, "banner metadata with fetching disabled", |e| {
assert!(
!matches!(e, Event::PictureReady { .. }),
"disabled image fetching emitted a picture"
);
matches!(e, Event::Presence { presence, .. }
if presence.server.banner_gfx_url == host_url
&& presence.server.banner_mode == BannerMode::KeepAspect
&& presence.channels.get(&channel_id).is_some_and(|c|
c.banner_gfx_url.as_deref() == Some(channel_url.as_str())
&& c.banner_mode == BannerMode::IgnoreAspect))
})
.await;
assert_eq!(
requests.load(Ordering::SeqCst),
0,
"disabled policy must prevent HTTP requests"
);
// A new presence after opting in must fetch both existing banners.
engine.settings().set(&CACHE_FETCH_IMAGES, true).unwrap();
admin
.send(&Query::new("channeledit").arg("cid", &cid).arg("channel_banner_mode", 2))
.await
.unwrap();
let mut seen = std::collections::HashSet::new();
let mut changed_mode = false;
wait_for(&mut events, "both images and changed sizing mode", |e| {
match e {
Event::PictureReady { url, path, .. } => {
assert_eq!(std::fs::read(path).unwrap(), png);
seen.insert(url.clone());
}
Event::Presence { presence, .. } => {
changed_mode = presence
.channels
.get(&channel_id)
.is_some_and(|c| c.banner_mode == BannerMode::KeepAspect);
}
_ => {}
}
changed_mode && seen.contains(&host_url) && seen.contains(&channel_url)
})
.await;
assert_eq!(
requests.load(Ordering::SeqCst),
4,
"both initial URLs must retry once after their 503 response"
);
let replacement = format!("{base}/replacement.png");
admin
.send(
&Query::new("channeledit")
.arg("cid", &cid)
.arg("channel_banner_gfx_url", &replacement)
.arg("channel_banner_mode", 0),
)
.await
.unwrap();
let (mut metadata, mut image) = (false, false);
wait_for(&mut events, "replacement channel banner", |e| {
match e {
Event::Presence { presence, .. } => {
metadata = presence.channels.get(&channel_id).is_some_and(|c| {
c.banner_gfx_url.as_deref() == Some(replacement.as_str())
&& c.banner_mode == BannerMode::NoAdjust
});
}
Event::PictureReady { url, path, .. } if *url == replacement => {
assert_eq!(std::fs::read(path).unwrap(), png);
image = true;
}
_ => {}
}
metadata && image
})
.await;
admin
.send(&Query::new("channeledit").arg("cid", &cid).arg("channel_banner_gfx_url", ""))
.await
.unwrap();
wait_for(&mut events, "channel banner removed", |e| {
matches!(e, Event::Presence { presence, .. } if
presence.channels.get(&channel_id).is_some_and(|c|
c.banner_gfx_url.as_deref().is_none_or(str::is_empty)))
})
.await;
// The same host URL must be downloaded again, bypassing its cached file.
let before_reload = requests.load(Ordering::SeqCst);
let deadline = Instant::now() + Duration::from_secs(75);
loop {
let event = timeout_at(deadline, events.recv())
.await
.expect("host banner did not reload after its 60-second interval")
.unwrap();
if let Event::PictureReady { url, path, .. } = event
&& url == host_url
{
assert_eq!(std::fs::read(path).unwrap(), png);
assert!(
requests.load(Ordering::SeqCst) > before_reload,
"reload must make a fresh HTTP request"
);
break;
}
}
})
};
let result = check.await;
engine.send(Command::CloseSession { session: 1 });
// Attempt both cleanup operations before reporting either failure.
let deleted = admin.send(&Query::new("channeldelete").arg("cid", &cid).arg("force", 1)).await;
let restored = admin.send(&restore).await;
let _ = std::fs::remove_dir_all(dir);
deleted.unwrap();
restored.unwrap();
if let Err(error) = result {
std::panic::resume_unwind(error.into_panic());
}
}
/// Upload through one independent identity/cache and download through another.
/// This proves the server file path and initial avatar metadata, rather than
/// accepting the uploader's local cache insertion as a successful download.
#[tokio::test(flavor = "multi_thread")]
async fn ts6_avatars() {
use base64::Engine as _;
if !live() {
return;
}
let voice_addr =
std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into());
let dir = std::env::temp_dir().join(format!("voelin-live-avatars-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let image = dir.join("upload.png");
let png = base64::prelude::BASE64_STANDARD.decode(PNG).unwrap();
std::fs::write(&image, &png).unwrap();
let uploader = Engine::start();
let reader = Engine::start();
uploader.send(Command::AttachCache(dir.join("uploader")));
reader.send(Command::AttachCache(dir.join("reader")));
let check = {
let (uploader, reader, dir) = (uploader.clone(), reader.clone(), dir.clone());
tokio::spawn(async move {
let nickname = format!("avatar-owner-{}", std::process::id());
let mut owner_events = uploader.subscribe();
uploader.send(Command::ConnectVoice {
session: 1,
options: Box::new(VoiceOptions::new(&voice_addr, &nickname)),
});
let presence = wait_for(&mut owner_events, "avatar owner presence", |event| {
matches!(event, Event::Presence { presence, .. } if presence.clients.values().any(|client| client.nickname == nickname && client.uid.is_some()))
}).await;
let Event::Presence { presence, .. } = presence else { unreachable!() };
let uid = presence
.clients
.values()
.find(|client| client.nickname == nickname)
.unwrap()
.uid
.clone()
.unwrap();
uploader.send(Command::SetAvatar { session: 1, request: 1, image: Some(image) });
let done = wait_for(&mut owner_events, "avatar upload", |event| {
matches!(event, Event::RequestDone { request: 1, .. })
})
.await;
assert!(matches!(done, Event::RequestDone { result: Ok(()), .. }), "{done:?}");
let mut reader_events = reader.subscribe();
reader.send(Command::ConnectVoice {
session: 1,
options: Box::new(VoiceOptions::new(
&voice_addr,
format!("avatar-reader-{}", std::process::id()),
)),
});
let downloaded = wait_for(
&mut reader_events,
"avatar downloaded by independent client",
|event| matches!(event, Event::AvatarReady { client_uid, .. } if *client_uid == uid),
)
.await;
let Event::AvatarReady { path, hash, .. } = downloaded else { unreachable!() };
assert!(path.starts_with(dir.join("reader")));
assert_eq!(std::fs::read(path).unwrap(), png);
assert_eq!(hash, format!("{:x}", md5::compute(&png)));
})
};
let result = check.await;
// The identity was generated for this test; remove its server-side file too.
let mut cleanup = uploader.subscribe();
uploader.send(Command::SetAvatar { session: 1, request: 2, image: None });
let _ = tokio::time::timeout(Duration::from_secs(5), async {
while let Ok(event) = cleanup.recv().await {
if matches!(event, Event::RequestDone { request: 2, .. }) {
break;
}
}
})
.await;
uploader.send(Command::CloseSession { session: 1 });
reader.send(Command::CloseSession { session: 1 });
let _ = std::fs::remove_dir_all(dir);
if let Err(error) = result {
std::panic::resume_unwind(error.into_panic());
}
}
+1 -1
View File
@@ -14,6 +14,6 @@ pub use presence::{
Presence, PresenceDelta, PresenceSnapshot, parse_badges,
};
pub use server::{
Capabilities, HostBannerMode, HostMessageMode, ServerDetails, ServerFlavor, ServerVersion,
BannerMode, Capabilities, HostMessageMode, ServerDetails, ServerFlavor, ServerVersion,
};
pub use tree::{TreeRow, order_siblings, tree_rows};
+11 -1
View File
@@ -13,7 +13,7 @@ use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::server::ServerDetails;
use crate::server::{BannerMode, ServerDetails};
pub type ChannelId = u64;
pub type ClientId = u16;
@@ -32,6 +32,10 @@ fn is_false(b: &bool) -> bool {
!*b
}
fn is_default<T: Default + PartialEq>(v: &T) -> bool {
*v == T::default()
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChannelInfo {
pub id: ChannelId,
@@ -56,6 +60,12 @@ pub struct ChannelInfo {
/// Icon id (`channel_icon_id`); 0: none.
#[serde(default, skip_serializing_if = "is_zero_u32")]
pub icon: u32,
/// The address of the channel's banner picture (TeamSpeak 6,
/// `channel_banner_gfx_url`), drawn behind the channel.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub banner_gfx_url: Option<String>,
#[serde(default, skip_serializing_if = "is_default")]
pub banner_mode: BannerMode,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+16 -3
View File
@@ -116,10 +116,11 @@ pub enum HostMessageMode {
ModalQuit,
}
/// How the host banner image is scaled.
/// How a banner picture (the host banner, a TeamSpeak 6 channel banner) is
/// scaled to its area: `0`, `1` and `2` on the wire.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HostBannerMode {
pub enum BannerMode {
/// As it is.
#[default]
NoAdjust,
@@ -129,6 +130,18 @@ pub enum HostBannerMode {
KeepAspect,
}
impl BannerMode {
/// From its number on the wire; an unknown one shows the picture as it
/// is.
pub fn from_wire(value: &str) -> Self {
match value.trim() {
"1" => Self::IgnoreAspect,
"2" => Self::KeepAspect,
_ => Self::NoAdjust,
}
}
}
/// What a server tells its (voice) clients about itself.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServerDetails {
@@ -152,7 +165,7 @@ pub struct ServerDetails {
#[serde(default)]
pub banner_gfx_interval_s: u64,
#[serde(default)]
pub banner_mode: HostBannerMode,
pub banner_mode: BannerMode,
#[serde(default)]
pub host_button_tooltip: String,
#[serde(default)]
+33 -4
View File
@@ -1,10 +1,10 @@
//! Query rows and events to model types.
use voelin_model::{ChannelInfo, ChatMessage, ChatTarget, ClientInfo, PresenceDelta};
use voelin_model::{BannerMode, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, PresenceDelta};
use voelin_query::{Notification, Row};
/// From a `channellist -topic -flags -voice -limits` row, or the fields of
/// `notifychannelcreated`.
/// From a `channellist -topic -flags -voice -limits -icon -banners` row, or
/// the fields of `notifychannelcreated`.
pub fn channel_from_row(row: &Row) -> Option<ChannelInfo> {
Some(ChannelInfo {
id: row.parse("cid")?,
@@ -18,6 +18,13 @@ pub fn channel_from_row(row: &Row) -> Option<ChannelInfo> {
needed_talk_power: row.parse("channel_needed_talk_power").unwrap_or(0),
is_default: row.flag("channel_flag_default").unwrap_or(false),
icon: row.parse::<i64>("channel_icon_id").map_or(0, |i| i as u32),
banner_gfx_url: row
.get("channel_banner_gfx_url")
.filter(|u| !u.is_empty())
.map(str::to_string),
banner_mode: row
.get("channel_banner_mode")
.map_or(BannerMode::NoAdjust, BannerMode::from_wire),
})
}
@@ -48,6 +55,15 @@ pub fn update_channel(channel: &mut ChannelInfo, row: &Row) {
if let Some(d) = row.flag("channel_flag_default") {
channel.is_default = d;
}
if let Some(i) = row.parse::<i64>("channel_icon_id") {
channel.icon = i as u32;
}
if let Some(url) = row.get("channel_banner_gfx_url") {
channel.banner_gfx_url = Some(url.to_string()).filter(|u| !u.is_empty());
}
if let Some(mode) = row.get("channel_banner_mode") {
channel.banner_mode = BannerMode::from_wire(mode);
}
}
/// From a `clientlist -uid -away -voice -groups -country` row or a
@@ -186,11 +202,24 @@ mod tests {
channel_flag_default=1 channel_flag_password=0 channel_maxclients=-1 \
channel_needed_subscribe_power=0 channel_needed_talk_power=5",
)[0];
let c = channel_from_row(row).unwrap();
let mut c = channel_from_row(row).unwrap();
assert_eq!(c.name, "Default Channel");
assert!(c.is_default && !c.has_password);
assert_eq!(c.max_clients, None);
assert_eq!(c.needed_talk_power, 5);
assert_eq!((c.banner_gfx_url.as_deref(), c.banner_mode), (None, BannerMode::NoAdjust));
// `-banners` (TeamSpeak 6 and 3.13), and the edit that changes them.
let row = &voelin_query::parse_rows(
"cid=2 pid=0 channel_name=Raid channel_banner_gfx_url=https:\\/\\/e.com\\/b.png \
channel_banner_mode=2",
)[0];
let banner = |c: &ChannelInfo| (c.banner_gfx_url.clone(), c.banner_mode);
let raid = channel_from_row(row).unwrap();
assert_eq!(banner(&raid), (Some("https://e.com/b.png".into()), BannerMode::KeepAspect));
update_channel(&mut c, row);
assert_eq!(banner(&c), banner(&raid));
update_channel(&mut c, &voelin_query::parse_rows("cid=1 channel_banner_gfx_url")[0]);
assert_eq!(banner(&c), (None, BannerMode::KeepAspect));
}
#[test]
+9 -1
View File
@@ -105,7 +105,15 @@ async fn run(
async fn load(client: &QueryClient) -> voelin_query::Result<Presence> {
let info = client.send(&Command::new("serverinfo")).await?;
let channels = client
.send(&Command::new("channellist").flag("topic").flag("flags").flag("voice").flag("limits"))
.send(
&Command::new("channellist")
.flag("topic")
.flag("flags")
.flag("voice")
.flag("limits")
.flag("icon")
.flag("banners"),
)
.await?;
let clients = client
.send(
+3 -1
View File
@@ -21,7 +21,9 @@ pub use contacts::{Contact, ContactSeen, Relation};
#[cfg(feature = "keyring")]
pub use secrets::KeyringSecrets;
pub use secrets::{MemorySecrets, Secrets};
pub use store::{Bookmark, IdentityEntry, IdentityOrigin, QueryConfig, QueryTransport, Store};
pub use store::{
Bookmark, CachedServerIcon, IdentityEntry, IdentityOrigin, QueryConfig, QueryTransport, Store,
};
#[derive(Debug, thiserror::Error)]
pub enum Error {
+47
View File
@@ -153,9 +153,33 @@ pub struct Bookmark {
pub query: Option<QueryConfig>,
/// Signed client version to present (`voelinctl versions` spec), `None` for the default.
pub client_version: Option<String>,
/// Last known icon, available before connecting. Bytes live in the image cache.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cached_server_icon: Option<CachedServerIcon>,
}
/// Bind cached metadata to the address that supplied it, so editing a bookmark
/// cannot display another server's icon. Do not persist machine-specific paths.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CachedServerIcon {
pub address: String,
pub id: u32,
}
impl Bookmark {
pub fn server_icon_id(&self) -> Option<u32> {
self.cached_server_icon
.as_ref()
.filter(|icon| icon.address == self.address.trim() && icon.id != 0)
.map(|icon| icon.id)
}
/// Record a server's latest icon; zero removes the previous one.
pub fn remember_server_icon(&mut self, id: u32) {
self.cached_server_icon =
(id != 0).then(|| CachedServerIcon { address: self.address.trim().to_owned(), id });
}
/// Secret key of the server password.
pub fn server_password_key(&self) -> String {
format!("bookmark/{}/server-password", self.id)
@@ -538,6 +562,29 @@ mod tests {
assert_eq!(b.server_password_key(), format!("bookmark/{}/server-password", b.id));
}
#[test]
fn bookmark_icons_survive_reload_and_are_bound_to_the_server_address() {
let store = Store::open_in_memory().unwrap();
let mut bookmark = Bookmark { address: "example.test:9987".into(), ..Default::default() };
bookmark.id = store.add_bookmark(&bookmark).unwrap();
assert_eq!(bookmark.server_icon_id(), None);
bookmark.remember_server_icon(4_000_000_000);
store.update_bookmark(&bookmark).unwrap();
let mut reloaded = store.bookmarks().unwrap().remove(0);
assert_eq!(reloaded.server_icon_id(), Some(4_000_000_000));
reloaded.address = "other.test:9987".into();
assert_eq!(reloaded.server_icon_id(), None);
reloaded.remember_server_icon(42);
assert_eq!(reloaded.server_icon_id(), Some(42));
reloaded.remember_server_icon(0);
assert!(reloaded.cached_server_icon.is_none());
store.update_bookmark(&reloaded).unwrap();
assert_eq!(store.bookmarks().unwrap()[0].server_icon_id(), None);
let old = serde_json::to_value(Bookmark::default()).unwrap();
assert!(old.get("cached_server_icon").is_none());
assert_eq!(serde_json::from_value::<Bookmark>(old).unwrap().server_icon_id(), None);
}
#[test]
fn settings() {
let mut store = Store::open_in_memory().unwrap();
+4
View File
@@ -20,6 +20,10 @@ path = "src/main.rs"
anyhow = "1.0.104"
chrono = { version = "0.4.45", default-features = false, features = ["clock"] }
dirs = "6"
# Slint decodes pictures with `image`, which it builds with PNG and JPEG only;
# avatars, icons and banners on TeamSpeak servers are GIF and WebP too (the
# decoders are in the tree already, for SVG pictures).
image = { version = "0.25", default-features = false, features = ["gif", "webp"] }
# Twemoji archive blocks (raw deflate); already used by png.
miniz_oxide = "0.8"
png = "0.18"
+57 -1
View File
@@ -210,8 +210,17 @@ pub(crate) struct SessionView {
pub avatars: HashMap<String, PathBuf>,
/// Icons in the engine's cache, by icon id ([`Event::IconReady`]).
pub icons: HashMap<u32, PathBuf>,
/// Banners in the engine's cache, by address ([`Event::PictureReady`]).
pub pictures: HashMap<String, PathBuf>,
/// The server's icon id as its voice connection last told it
/// ([`Event::ServerDetails`]); kept while disconnected, for the rail.
pub server_icon: u32,
/// Bookmark address that supplied this session's icon.
pub icon_address: Option<String>,
/// The server groups in display order ([`Event::Groups`]).
pub server_groups: Vec<GroupInfo>,
/// The channel groups ([`Event::Groups`]).
pub channel_groups: Vec<GroupInfo>,
/// What the session's gateway offers (`voelin_gateway_proto::feature`).
pub gateway_caps: Vec<String>,
/// The client whose member card is open.
@@ -241,7 +250,11 @@ impl Default for SessionView {
applied_playback: HashSet::new(),
avatars: HashMap::new(),
icons: HashMap::new(),
pictures: HashMap::new(),
server_icon: 0,
icon_address: None,
server_groups: Vec::new(),
channel_groups: Vec::new(),
gateway_caps: Vec::new(),
member_card: None,
stream_viewers: HashMap::new(),
@@ -301,6 +314,23 @@ impl SessionView {
let uid = self.presence.clients.get(&client)?.uid.as_deref()?;
self.avatars.get(uid)
}
/// The server's icon, if it has one and the engine fetched it.
pub fn server_icon(&self) -> slint::Image {
crate::vm::avatar::image(
self.icons.get(&self.server_icon).filter(|_| self.server_icon != 0),
)
}
/// Icons stay associated with the address that supplied them, including
/// while a reconnect to an edited bookmark is pending or has failed.
pub fn server_icon_for(&self, address: &str) -> slint::Image {
if self.icon_address.as_deref() == Some(address) {
self.server_icon()
} else {
slint::Image::default()
}
}
}
/// The models the Bridge shows, created once and updated row by row
@@ -915,28 +945,54 @@ impl App {
self.gateway_extra(session as i64, &update);
self.gateway_update(session as i64, update);
}
Event::Groups { session, server_groups, .. } => {
Event::Groups { session, server_groups, channel_groups } => {
let view = self.sessions.entry(session as i64).or_default();
view.server_groups = (*server_groups).clone();
// Display order, as TeamSpeak sorts them.
view.server_groups.sort_by_key(|g| (g.sort_id, g.id));
view.channel_groups = (*channel_groups).clone();
if self.current == Some(session as i64) {
self.refresh_tree();
}
}
Event::ServerDetails { session, address, details } => {
self.remember_server_icon(session as i64, &address, details.icon);
self.refresh_servers();
self.refresh_toolbar();
}
// Pictures can arrive after the rows were built: draw them again.
Event::AvatarReady { session, client_uid, path, .. } => {
let view = self.sessions.entry(session as i64).or_default();
// A file that arrives again is decoded again.
crate::images::forget(&path);
view.avatars.insert(client_uid, path);
if self.current == Some(session as i64) {
self.refresh_tree();
self.refresh_chat();
self.refresh_toolbar();
self.refresh_member_card();
self.refresh_streams();
}
}
Event::IconReady { session, icon, path } => {
let view = self.sessions.entry(session as i64).or_default();
crate::images::forget(&path);
view.icons.insert(icon, path);
self.refresh_servers();
if self.current == Some(session as i64) {
self.refresh_tree();
self.refresh_toolbar();
}
}
Event::PictureReady { session, url, path } => {
let view = self.sessions.entry(session as i64).or_default();
// The host banner reloads into the same file.
crate::images::forget(&path);
view.pictures.insert(url, path);
if self.current == Some(session as i64) {
self.refresh_toolbar();
self.refresh_tree();
self.refresh_chat();
}
}
Event::Transfer { session, transfer, state } => {
+29 -26
View File
@@ -63,7 +63,8 @@ impl App {
let name = self
.sessions
.get(&id)
.and_then(|v| v.presence.channels.get(cid).map(|c| c.name.clone()));
.and_then(|v| v.presence.channels.get(cid))
.map(|c| vm::tree::channel_title(c).0.to_owned());
format!("#{}", name.unwrap_or_else(|| cid.to_string()))
}
ChatTarget::Server => "Server".into(),
@@ -375,31 +376,33 @@ impl App {
.unwrap_or_default();
(t, last, time)
})
.map(|(t, last, time)| ChatTab {
last: last.into(),
time: time.into(),
title: t.title.clone().into(),
name: t.title.trim_start_matches(['#', '@']).into(),
kind: match t.target {
ChatTarget::Server => 0,
ChatTarget::Channel(_) => 1,
ChatTarget::Private(_) => 2,
},
id: match t.target {
ChatTarget::Channel(cid) => cid as i32,
_ => 0,
},
unread: t.unread,
topic: match t.target {
ChatTarget::Channel(cid) => view
.presence
.channels
.get(&cid)
.and_then(|c| c.topic.clone())
.unwrap_or_default()
.into(),
_ => Default::default(),
},
.map(|(t, last, time)| {
let channel = match t.target {
ChatTarget::Channel(cid) => view.presence.channels.get(&cid),
_ => None,
};
ChatTab {
last: last.into(),
time: time.into(),
title: t.title.clone().into(),
name: t.title.trim_start_matches(['#', '@']).into(),
kind: match t.target {
ChatTarget::Server => 0,
ChatTarget::Channel(_) => 1,
ChatTarget::Private(_) => 2,
},
id: match t.target {
ChatTarget::Channel(cid) => cid as i32,
_ => 0,
},
unread: t.unread,
topic: channel.and_then(|c| c.topic.clone()).unwrap_or_default().into(),
banner: vm::tree::banner(
&view.pictures,
channel.and_then(|c| c.banner_gfx_url.as_deref()),
),
banner_mode: channel.map_or(0, |c| vm::tree::banner_mode(c.banner_mode)),
}
})
.collect();
vm::list::sync(&self.models.tabs, &tabs);
+168 -13
View File
@@ -58,7 +58,7 @@ use voelin_gateway_proto::{
feature,
};
use voelin_model::{
ChannelInfo, ChatMessage, ChatTarget, ClientInfo, GroupInfo, Presence, ServerFlavor,
BannerMode, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, GroupInfo, Presence, ServerFlavor,
};
use voelin_store::{Bookmark, MessageSource};
@@ -369,6 +369,7 @@ fn demo_ui(app: &mut App) {
gateway_url: None,
query: None,
client_version: None,
cached_server_icon: None,
};
app.bookmarks = vec![
Bookmark {
@@ -385,17 +386,31 @@ fn demo_ui(app: &mut App) {
p.server.welcome_message =
"Welcome to [b]Nightfall Guild[/b]! Raids on Tuesdays and Fridays, all levels welcome."
.into();
// The host banner, a server icon, backgrounds on three channels and an icon
// on another; the pictures arrive below (`demo_pictures`).
p.server.banner_gfx_url = DEMO_HOST_BANNER.into();
p.server.banner_mode = BannerMode::KeepAspect;
p.server.icon = DEMO_SERVER_ICON;
let mut chill = channel(2, 0, 1, "Chill Zone");
chill.max_clients = Some(50);
chill.topic = Some("Hang out, chat, and explore the worlds beyond.".into());
chill.banner_gfx_url = Some(DEMO_CHILL_BANNER.into());
chill.banner_mode = BannerMode::IgnoreAspect;
let mut raid = channel(4, 3, 0, "Raid Night");
raid.banner_gfx_url = Some(DEMO_RAID_BANNER.into());
raid.banner_mode = BannerMode::KeepAspect;
let mut music = channel(5, 0, 3, "Music");
music.icon = DEMO_MUSIC_ICON;
music.banner_gfx_url = Some(DEMO_MUSIC_BANNER.into());
music.banner_mode = BannerMode::NoAdjust;
let mut locked = channel(7, 0, 6, "Officers");
locked.has_password = true;
for c in [
channel(1, 0, 0, "Lobby"),
chill,
channel(3, 0, 2, "Gaming"),
channel(4, 3, 0, "Raid Night"),
channel(5, 0, 3, "Music"),
channel(3, 0, 2, "[cspacer0]Gaming"),
raid,
music,
channel(6, 0, 5, "AFK"),
locked,
] {
@@ -443,7 +458,11 @@ fn demo_ui(app: &mut App) {
let group = |id: u64, sort_id: i32, name: &str| GroupInfo {
id,
name: name.into(),
icon: 0,
icon: match id {
GROUP_ADMIN => DEMO_ADMIN_ICON,
GROUP_MOD => DEMO_MOD_ICON,
_ => 0,
},
sort_id,
..Default::default()
};
@@ -517,6 +536,7 @@ fn demo_ui(app: &mut App) {
for event in events {
app.handle_event(event);
}
demo_pictures(app);
demo_chat(app, session);
demo_social(app);
// No toast over the screenshots.
@@ -981,6 +1001,148 @@ fn demo_social(app: &mut App) {
app.refresh_home();
}
/// Addresses and icon ids of the sample server's pictures.
const DEMO_HOST_BANNER: &str = "https://nightfall.example/banner.png";
const DEMO_CHILL_BANNER: &str = "https://nightfall.example/chill.png";
const DEMO_MUSIC_BANNER: &str = "https://nightfall.example/music.png";
const DEMO_RAID_BANNER: &str = "https://nightfall.example/raid.png";
const DEMO_SERVER_ICON: u32 = 3_120_211_001;
const DEMO_ADMIN_ICON: u32 = 3_120_211_002;
const DEMO_MOD_ICON: u32 = 3_120_211_003;
const DEMO_MUSIC_ICON: u32 = 3_120_211_004;
/// Avatars, icons and banners as the engine reports them once they are in
/// its cache (here a folder of synthetic pictures in the temporary
/// directory).
fn demo_pictures(app: &mut App) {
let session = DEMO as u64;
let dir = std::env::temp_dir().join("voelin-demo-pictures");
let _ = std::fs::create_dir_all(&dir);
let save = |name: &str, png: Vec<u8>| {
let path = dir.join(name);
let _ = std::fs::write(&path, png);
path
};
let mut events = vec![Event::ServerDetails {
session,
address: app.bookmarks.iter().find(|b| b.id == DEMO).unwrap().address.clone(),
details: Arc::new(voelin_model::ServerDetails {
icon: DEMO_SERVER_ICON,
..Default::default()
}),
}];
for (url, picture) in [
(DEMO_HOST_BANNER, demo_picture(256, 256, 3)),
(DEMO_CHILL_BANNER, demo_picture(900, 120, 11)),
(DEMO_RAID_BANNER, demo_picture(240, 240, 5)),
(DEMO_MUSIC_BANNER, demo_picture(180, 36, 7)),
] {
let path = save(url.rsplit('/').next().unwrap_or(url), picture);
events.push(Event::PictureReady { session, url: url.into(), path });
}
for (icon, color, shape) in [
(DEMO_SERVER_ICON, [70, 92, 255], Shape::Moon),
(DEMO_ADMIN_ICON, [242, 178, 44], Shape::Diamond),
(DEMO_MOD_ICON, [45, 196, 132], Shape::Disc),
(DEMO_MUSIC_ICON, [214, 76, 182], Shape::Ring),
] {
let path = save(&icon.to_string(), demo_icon(color, shape));
events.push(Event::IconReady { session, icon, path });
}
// Some people have pictures, the rest initials.
for (sample_session, uid, seed) in [
(session, "demo-2", 1),
(session, "demo-3", 2),
(session, "demo-4", 3),
(session, "demo-7", 4),
(session, "demo-9", 5),
(session + 1, "demo-ivy", 6),
] {
let path = save(&format!("avatar-{uid}"), demo_avatar(seed));
events.push(Event::AvatarReady {
session: sample_session,
client_uid: uid.into(),
path,
hash: String::new(),
});
}
for event in events {
app.handle_event(event);
}
}
/// Shapes of the sample icons.
#[derive(Clone, Copy)]
enum Shape {
Moon,
Diamond,
Disc,
Ring,
}
/// A 32×32 icon: a shape in `color` on transparency; PNG bytes.
fn demo_icon(color: [u8; 3], shape: Shape) -> Vec<u8> {
let size = 32u32;
let mut rgba = Vec::with_capacity((size * size * 4) as usize);
for y in 0..size {
for x in 0..size {
let (dx, dy) = (x as f32 - 15.5, y as f32 - 15.5);
let d = (dx * dx + dy * dy).sqrt();
let inside = match shape {
Shape::Moon => d < 14.0 && ((dx - 6.0).powi(2) + (dy + 5.0).powi(2)).sqrt() > 10.0,
Shape::Diamond => dx.abs() + dy.abs() < 15.0,
Shape::Disc => d < 13.0,
Shape::Ring => (8.0..14.0).contains(&d) || d < 4.0,
};
let [r, g, b] = color;
rgba.extend(if inside { [r, g, b, 255] } else { [0, 0, 0, 0] });
}
}
png_of(size, size, &rgba)
}
/// A 96×96 portrait: a head and shoulders on a gradient; PNG bytes.
fn demo_avatar(seed: u32) -> Vec<u8> {
const SKY: [[f32; 3]; 6] = [
[255.0, 140.0, 90.0],
[90.0, 170.0, 255.0],
[170.0, 110.0, 255.0],
[60.0, 200.0, 170.0],
[250.0, 200.0, 80.0],
[240.0, 110.0, 160.0],
];
let size = 96u32;
let sky = SKY[seed as usize % SKY.len()];
let mut rgba = Vec::with_capacity((size * size * 4) as usize);
for y in 0..size {
for x in 0..size {
let (fx, fy) = (x as f32, y as f32);
let t = (fx + fy) / (2.0 * size as f32);
let mut c =
[sky[0] * (1.0 - 0.45 * t), sky[1] * (1.0 - 0.45 * t), sky[2] * (1.0 - 0.3 * t)];
let head = ((fx - 48.0).powi(2) + (fy - 40.0).powi(2)).sqrt() < 19.0;
let shoulders = ((fx - 48.0) / 36.0).powi(2) + ((fy - 98.0) / 30.0).powi(2) < 1.0;
if head || shoulders {
c = [250.0 - c[0] * 0.25, 244.0 - c[1] * 0.25, 238.0 - c[2] * 0.2];
}
rgba.extend([c[0] as u8, c[1] as u8, c[2] as u8, 255]);
}
}
png_of(size, size, &rgba)
}
/// RGBA pixels as PNG bytes.
fn png_of(width: u32, height: u32, rgba: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let mut encoder = png::Encoder::new(&mut out, width, height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
if let Ok(mut writer) = encoder.write_header() {
let _ = writer.write_image_data(rgba);
}
out
}
/// A painted night: sky, moon, stars, hills and a castle; PNG bytes.
fn demo_picture(width: u32, height: u32, seed: u32) -> Vec<u8> {
let mut rgba = Vec::with_capacity((width * height * 4) as usize);
@@ -1031,14 +1193,7 @@ fn demo_picture(width: u32, height: u32, seed: u32) -> Vec<u8> {
rgba.extend([c[0].min(255.0) as u8, c[1].min(255.0) as u8, c[2].min(255.0) as u8, 255]);
}
}
let mut out = Vec::new();
let mut encoder = png::Encoder::new(&mut out, width, height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
if let Ok(mut writer) = encoder.write_header() {
let _ = writer.write_image_data(&rgba);
}
out
png_of(width, height, &rgba)
}
/// Server group ids of the sample server.
+145 -14
View File
@@ -1,4 +1,4 @@
//! Decoded images by key (emoji now; avatars and server icons later): each
//! Decoded images by key (emoji, avatars, icons and banners): each
//! is decoded once and kept while it fits the budget (setting
//! `ui.image_cache_mb`); the least recently used go first.
//!
@@ -8,6 +8,7 @@
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap};
use std::io::Cursor;
use slint::Image;
@@ -67,6 +68,14 @@ impl<V: Clone> Lru<V> {
Some(value)
}
/// Drop `key`, so the next use loads it again.
pub fn remove(&mut self, key: &str) {
if let Some((_, cost, tick)) = self.entries.remove(key) {
self.order.remove(&tick);
self.used -= cost;
}
}
fn evict(&mut self) {
while self.used > self.budget {
let Some((_, key)) = self.order.pop_first() else { break };
@@ -101,6 +110,9 @@ pub fn usage_text() -> String {
})
}
/// What remembering a picture that cannot be decoded costs in the cache.
const UNDECODABLE_COST: usize = 256;
/// A picture the engine put in its cache (avatars, group and client icons),
/// decoded once and kept by its path.
pub fn file(path: &std::path::Path) -> Image {
@@ -112,27 +124,56 @@ pub fn file(path: &std::path::Path) -> Image {
// (`avatars/<md5>`, `icons/<id>`), and servers keep PNG, JPEG
// and SVG icons alike.
let bytes = std::fs::read(path).ok()?;
let image = Image::load_from_data(&bytes, None).ok()?;
let size = image.size();
Some((image, size.width as usize * size.height as usize * 4))
// One that cannot be shown (too large, not a picture) is
// remembered as such, not read again on every refresh; a
// changed file is forgotten first (`forget`).
Some(decode(&bytes).unwrap_or((Image::default(), UNDECODABLE_COST)))
})
})
.unwrap_or_default()
}
/// Forget the decoded picture of a file that changed (a reloaded banner).
pub fn forget(path: &std::path::Path) {
CACHE.with(|c| c.borrow_mut().remove(&path.to_string_lossy()));
}
/// Compressed pictures can be small on disk but huge when decoded. Check
/// raster dimensions before Slint allocates pixels on the UI thread. SVGs
/// keep Slint's native vector loader and are rasterized at the displayed size.
fn decode(bytes: &[u8]) -> Option<(Image, usize)> {
let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
let cost = if reader.format().is_some() {
let (width, height) = reader.into_dimensions().ok()?;
// At most the default decoded-image cache (64 MiB of RGBA).
if width == 0
|| height == 0
|| width > 16_384
|| height > 16_384
|| u64::from(width) * u64::from(height) * 4 > 64 << 20
{
tracing::debug!(width, height, "image exceeds the decoded raster size limit");
return None;
}
width as usize * height as usize * 4
} else {
let start = bytes.trim_ascii_start();
if !start.starts_with(b"<svg") && !start.starts_with(b"<?xml") {
return None;
}
// Intrinsic SVG dimensions describe coordinates, not an allocated
// pixel buffer. Use the same vector cost as the emoji cache.
return Image::load_from_svg_data(start).ok().map(|image| (image, svg_cost(bytes.len())));
};
Image::load_from_data(bytes, None).ok().map(|image| (image, cost))
}
/// A picture from encoded bytes (PNG, JPEG, GIF, WebP), decoded once and
/// kept by `key`; an empty image if it cannot be decoded.
pub fn picture(key: &str, bytes: &[u8]) -> Image {
let cache_key = format!("picture:{key}");
CACHE
.with(|c| {
c.borrow_mut().get_or_load(&cache_key, || {
let image = Image::load_from_data(bytes, None).ok()?;
let size = image.size();
Some((image, size.width as usize * size.height as usize * 4))
})
})
.unwrap_or_default()
CACHE.with(|c| c.borrow_mut().get_or_load(&cache_key, || decode(bytes))).unwrap_or_default()
}
/// A Twemoji by key; an empty image if there is none.
@@ -182,6 +223,13 @@ mod tests {
assert_eq!(lru.usage(), (0, 0));
// Unknown keys are not cached.
assert_eq!(lru.get_or_load("none", || None), None);
lru.set_budget(10);
get(&mut lru, "a", 4);
lru.remove("a");
lru.remove("never");
assert_eq!((lru.usage(), lru.len()), ((0, 10), 0));
get(&mut lru, "a", 4);
assert_eq!(loads.get(), 7, "loaded again after remove");
}
#[test]
@@ -195,6 +243,53 @@ mod tests {
assert_eq!(picture("test:junk", b"not a picture").size().width, 0);
}
#[test]
fn svg_with_bom_and_whitespace_decodes() {
let svg = b"\xef\xbb\xbf \n<svg xmlns='http://www.w3.org/2000/svg' width='32' height='16'><rect width='32' height='16'/></svg>";
assert_eq!(picture("test:svg-bom", svg).size().width, 32);
}
#[test]
fn large_svg_coordinates_do_not_overflow_the_cache_cost() {
let svg = br#"<svg xmlns="http://www.w3.org/2000/svg" width="3000000000" height="3000000000"><rect width="1" height="1"/></svg>"#;
let (image, cost) = decode(svg).unwrap();
assert!(image.size().width > 0);
assert_eq!(cost, svg_cost(svg.len()));
assert!(picture("test:large-svg", svg).size().width > 0);
}
#[test]
fn oversized_rasters_are_refused_before_pixels_are_read() {
use std::io::Write;
for (width, height) in [(6000, 6000), (16_385, 1), (1, 16_385)] {
let mut bytes = Vec::new();
let mut encoder = png::Encoder::new(&mut bytes, width, height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder.write_header().unwrap();
let mut stream = writer.stream_writer().unwrap();
let row = vec![255; width as usize * 4];
for _ in 0..height {
stream.write_all(&row).unwrap();
}
stream.finish().unwrap();
writer.finish().unwrap();
// A valid solid picture fits the download cap but not the
// decoded budget. Generate it a row at a time, without ever
// allocating the large pixel buffer this test guards against.
assert!(bytes.len() < 4 << 20);
assert_eq!(
image::ImageReader::new(Cursor::new(&bytes))
.with_guessed_format()
.unwrap()
.into_dimensions()
.unwrap(),
(width, height)
);
assert!(decode(&bytes).is_none());
}
}
/// Cached avatars and icons are named without an extension.
#[test]
fn cached_files_decode_by_content() {
@@ -207,11 +302,47 @@ mod tests {
encoder.write_header().unwrap().write_image_data(&[90; 24]).unwrap();
let svg = br#"<?xml version="1.0" encoding="iso-8859-1"?>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16"/></svg>"#;
for (name, bytes, width) in [("287478770", &png[..], 3), ("413901487", &svg[..], 16)] {
// GIF avatars and banners are common on TeamSpeak 3 servers.
let gif = b"GIF89a\x01\0\x01\0\x80\0\0\xff\xff\xff\0\0\0!\xf9\x04\x01\0\0\0\0,\0\0\0\0\x01\0\x01\0\0\x02\x02D\x01\0;";
let mut webp = Vec::new();
image::ImageEncoder::write_image(
image::codecs::webp::WebPEncoder::new_lossless(&mut webp),
&[90; 24],
3,
2,
image::ExtendedColorType::Rgba8,
)
.unwrap();
for (name, bytes, width) in [
("287478770", &png[..], 3),
("413901487", &svg[..], 16),
("gif", &gif[..], 1),
("webp", &webp[..], 3),
] {
let path = dir.join(name);
std::fs::write(&path, bytes).unwrap();
assert_eq!(file(&path).size().width, width, "{name}");
}
// A file that changed is decoded again once forgotten.
let path = dir.join("287478770");
let mut wider = Vec::new();
let mut encoder = png::Encoder::new(&mut wider, 5, 2);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header().unwrap().write_image_data(&[90; 40]).unwrap();
std::fs::write(&path, wider).unwrap();
assert_eq!(file(&path).size().width, 3, "kept until forgotten");
forget(&path);
assert_eq!(file(&path).size().width, 5);
// A file that is no picture is remembered as such until forgotten,
// not read again on every refresh.
let junk = dir.join("junk");
std::fs::write(&junk, b"<!DOCTYPE html>").unwrap();
assert_eq!(file(&junk).size().width, 0);
std::fs::write(&junk, &png).unwrap();
assert_eq!(file(&junk).size().width, 0, "remembered");
forget(&junk);
assert_eq!(file(&junk).size().width, 3);
std::fs::remove_dir_all(dir).unwrap();
}
+115 -3
View File
@@ -7,7 +7,7 @@ use voelin_core::identity::LaunchImport;
use voelin_core::{Command, ObserveState, Source, VoiceOptions, VoiceState};
use voelin_store::{Bookmark, QueryConfig, QueryTransport};
use crate::app::{App, BookmarkForm, Bridge, later};
use crate::app::{App, BookmarkForm, Bridge, SessionView, later};
use crate::vm;
/// The name of the identity the app creates when it has none.
@@ -44,6 +44,9 @@ fn bookmark_from_form(
let mut bookmark = old.cloned().unwrap_or_default();
bookmark.id = form.id as i64;
bookmark.address = form.address.trim().to_string();
if old.is_some_and(|old| old.address != bookmark.address) {
bookmark.cached_server_icon = None;
}
bookmark.name = match form.name.trim() {
"" => bookmark.address.clone(),
name => name.to_string(),
@@ -84,6 +87,24 @@ fn bookmark_from_form(
bookmark
}
/// Apply only details originating from the bookmark's current address.
/// Returns whether its persisted metadata changed.
fn apply_server_icon(
bookmark: &mut Bookmark,
view: &mut SessionView,
address: &str,
icon: u32,
) -> bool {
if bookmark.address != address {
return false;
}
view.icon_address = Some(address.to_owned());
view.server_icon = icon;
let before = bookmark.cached_server_icon.clone();
bookmark.remember_server_icon(icon);
bookmark.cached_server_icon != before
}
impl App {
pub(crate) fn connect_voice(&mut self) {
let channel =
@@ -305,6 +326,34 @@ impl App {
self.refresh_all();
}
/// Keep only metadata supplied by the bookmark's current server.
pub(crate) fn remember_server_icon(&mut self, id: i64, address: &str, icon: u32) {
let Some(bookmark) = self.bookmarks.iter_mut().find(|b| b.id == id) else {
return;
};
let changed =
apply_server_icon(bookmark, self.sessions.entry(id).or_default(), address, icon);
if changed
&& !self.demo_ui
&& let Err(error) = self.store.update_bookmark(bookmark)
{
warn!(%error, "could not keep the server icon");
}
}
pub(crate) fn server_list_icon(&self, bookmark: &Bookmark) -> slint::Image {
let current = self
.sessions
.get(&bookmark.id)
.map(|view| view.server_icon_for(&bookmark.address))
.unwrap_or_default();
if current.size().width > 0 {
current
} else {
vm::servers::cached_icon(bookmark, &self.engine.cache())
}
}
/// The rail: servers with their state, unread count and streams.
pub(crate) fn refresh_servers(&self) {
let Some(ui) = self.ui.upgrade() else { return };
@@ -322,7 +371,8 @@ impl App {
.map(|v| vm::tree::stats(&v.presence))
.unwrap_or_default();
let flavor = view.map(|v| v.extra.flavor.clone()).unwrap_or_default();
vm::servers::item(b, &state, unread, live, detail, flavor)
let icon = self.server_list_icon(b);
vm::servers::item(b, &state, unread, live, detail, flavor, icon)
})
.collect();
vm::list::sync(&self.models.servers, &items);
@@ -337,6 +387,7 @@ impl App {
let bookmark = self.current.and_then(|id| self.bookmark(id));
let view = self.view();
let state = view.map(|v| v.state.clone()).unwrap_or_default();
bridge.set_server_icon(bookmark.map(|b| self.server_list_icon(b)).unwrap_or_default());
bridge.set_server_title(
bookmark.map_or("No server selected".into(), |b| b.name.clone()).into(),
);
@@ -349,12 +400,27 @@ impl App {
.into(),
);
bridge.set_nickname(bookmark.map(|b| b.nickname.clone()).unwrap_or_default().into());
let own = view.zip(state.own_client).and_then(|(v, c)| v.avatar(c));
bridge.set_own_avatar(vm::avatar::image(own));
let banner = |url: Option<&str>| {
view.map(|v| vm::tree::banner(&v.pictures, url)).unwrap_or_default()
};
let details = view.map(|v| &v.presence.server);
bridge.set_server_banner(banner(details.map(|d| d.banner_gfx_url.as_str())));
bridge.set_server_banner_mode(details.map_or(0, |d| vm::tree::banner_mode(d.banner_mode)));
let own_channel =
view.and_then(|v| state.own_channel.and_then(|c| v.presence.channels.get(&c)));
bridge.set_own_channel(own_channel.map(|c| c.name.clone()).unwrap_or_default().into());
bridge.set_own_channel(
own_channel.map(|c| vm::tree::channel_title(c).0).unwrap_or_default().into(),
);
bridge.set_own_channel_topic(
own_channel.and_then(|c| c.topic.clone()).unwrap_or_default().into(),
);
bridge
.set_own_channel_banner(banner(own_channel.and_then(|c| c.banner_gfx_url.as_deref())));
bridge.set_own_channel_banner_mode(
own_channel.map_or(0, |c| vm::tree::banner_mode(c.banner_mode)),
);
bridge.set_own_channel_limit(
own_channel.and_then(|c| c.max_clients).filter(|m| *m >= 0).unwrap_or(-1),
);
@@ -401,7 +467,9 @@ impl App {
filter: "",
avatars: &view.avatars,
icons: &view.icons,
pictures: &view.pictures,
groups: &view.server_groups,
channel_groups: &view.channel_groups,
};
vm::list::sync(&self.models.tree, &vm::tree::rows(&input));
let connected = view.state.voice == VoiceState::Connected;
@@ -482,6 +550,45 @@ mod tests {
use super::*;
#[test]
fn edited_server_rejects_queued_icons_and_failed_reconnect_keeps_them_hidden() {
let path = std::env::temp_dir()
.join(format!("voelin-server-icon-provenance-{}.svg", std::process::id()));
std::fs::write(&path, r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"><rect width="4" height="4" fill="red"/></svg>"#).unwrap();
let mut bookmark = Bookmark { address: "a.test".into(), ..Default::default() };
let mut view = SessionView::default();
view.icons.insert(1234, path.clone());
assert!(apply_server_icon(&mut bookmark, &mut view, "a.test", 1234));
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
bookmark = bookmark_from_form(
Some(&bookmark),
&BookmarkForm { address: "b.test".into(), ..Default::default() },
|| "Me".into(),
);
// Connecting does not retag received imagery. A failed B connection
// must not make A's image appear under B's name.
for state in [VoiceState::Connecting, VoiceState::Disconnected] {
view.state.voice = state;
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 0);
}
assert!(!apply_server_icon(&mut bookmark, &mut view, "a.test", 4321));
assert_eq!(view.server_icon, 1234);
assert_eq!(view.icon_address.as_deref(), Some("a.test"));
assert!(bookmark.server_icon_id().is_none());
// Equal icon IDs on the next server still need new provenance.
assert!(apply_server_icon(&mut bookmark, &mut view, "b.test", 1234));
assert_eq!(bookmark.server_icon_id(), Some(1234));
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
assert!(!apply_server_icon(&mut bookmark, &mut view, "a.test", 0));
assert_eq!(bookmark.server_icon_id(), Some(1234));
assert!(apply_server_icon(&mut bookmark, &mut view, "b.test", 0));
assert!(bookmark.server_icon_id().is_none());
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 0);
std::fs::remove_file(path).unwrap();
}
#[test]
fn the_address_alone_makes_a_server() {
let form = BookmarkForm {
@@ -511,6 +618,10 @@ mod tests {
gateway_url: Some("ws://gw.example.test:7788/v1".into()),
query: Some(QueryConfig { server_port: Some(9988), ..Default::default() }),
client_version: Some("linux".into()),
cached_server_icon: Some(voelin_store::CachedServerIcon {
address: "old.example.test".into(),
id: 1234,
}),
};
let form = BookmarkForm {
id: 7,
@@ -527,6 +638,7 @@ mod tests {
let b = bookmark_from_form(Some(&old), &form, || unreachable!("a nickname was given"));
assert_eq!((b.id, b.name.as_str(), b.nickname.as_str()), (7, "Mine", "Other"));
assert_eq!(b.address, "new.example.test:9988");
assert!(b.cached_server_icon.is_none());
assert_eq!((b.identity, b.default_channel), (Some(2), Some("Lobby/Sub".into())));
assert_eq!(b.client_version.as_deref(), Some("linux"));
assert_eq!(b.gateway_url, None);
+1
View File
@@ -958,6 +958,7 @@ impl App {
subtitle: b.address.clone().into(),
initials: vm::avatar::initials(&b.name).into(),
tint: vm::avatar::tint(&b.name),
avatar: self.server_list_icon(b),
..Default::default()
},
Found::Server(b.id),
+3
View File
@@ -379,6 +379,9 @@ impl App {
}
.into(),
message: v.message.clone().into(),
avatar: crate::vm::avatar::image(
view.and_then(|view| view.avatar(v.client.0)),
),
})
.collect()
})
+43 -1
View File
@@ -6,6 +6,12 @@ use voelin_store::Bookmark;
use crate::app::ServerItem;
use crate::vm::avatar;
/// Restore a known server icon before any session exists. A missing/evicted
/// cache file falls back to initials; the bookmark stores no filesystem path.
pub fn cached_icon(bookmark: &Bookmark, cache: &voelin_core::Cache) -> slint::Image {
avatar::image(bookmark.server_icon_id().and_then(|id| cache.icon(id)).as_ref())
}
/// "offline", "connecting", "observing" or "connected".
pub fn status(state: &SessionState) -> &'static str {
match (state.voice, state.observe) {
@@ -19,7 +25,7 @@ pub fn status(state: &SessionState) -> &'static str {
/// A server of the rail and the home page. `unread`: messages in its
/// chats; `live`: streams on it; `detail`: who is there ("9 online · 7
/// channels"), empty for its address; `flavor`: "TeamSpeak 6" once
/// reached.
/// reached; `icon`: the server's icon (empty: its initials).
pub fn item(
bookmark: &Bookmark,
state: &SessionState,
@@ -27,6 +33,7 @@ pub fn item(
live: bool,
detail: String,
flavor: String,
icon: slint::Image,
) -> ServerItem {
ServerItem {
id: bookmark.id as i32,
@@ -35,6 +42,7 @@ pub fn item(
status: status(state).into(),
initials: avatar::initials(&bookmark.name).into(),
tint: avatar::tint(&bookmark.name),
icon,
unread,
live,
detail: if detail.is_empty() { bookmark.address.clone() } else { detail }.into(),
@@ -90,6 +98,40 @@ pub fn invite_link(address: &str, path: &[&str]) -> String {
mod tests {
use super::*;
#[test]
fn server_icon_is_visible_before_connection_and_missing_files_fall_back() {
let dir =
std::env::temp_dir().join(format!("voelin-server-icon-model-{}", std::process::id()));
std::fs::create_dir_all(dir.join("icons")).unwrap();
let path = dir.join("icons/1234");
let mut bytes = Vec::new();
let mut encoder = png::Encoder::new(&mut bytes, 4, 4);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header().unwrap().write_image_data(&[200; 64]).unwrap();
std::fs::write(&path, bytes).unwrap();
let cache = voelin_core::Cache::new(&dir);
let mut bookmark = Bookmark { address: "example.test".into(), ..Default::default() };
bookmark.remember_server_icon(1234);
let server = item(
&bookmark,
&SessionState::default(),
0,
false,
String::new(),
String::new(),
cached_icon(&bookmark, &cache),
);
assert_eq!(server.status.as_str(), "offline");
assert_eq!(server.icon.size().width, 4);
bookmark.address = "different.test".into();
assert_eq!(cached_icon(&bookmark, &cache).size().width, 0);
bookmark.address = "example.test".into();
std::fs::remove_file(path).unwrap();
assert_eq!(cached_icon(&bookmark, &cache).size().width, 0);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn invite_links() {
assert_eq!(
+177 -22
View File
@@ -4,12 +4,28 @@
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use voelin_model::{ChannelId, ClientInfo, GroupInfo, Presence, TreeRow, tree_rows};
use voelin_model::{
BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, Presence, TreeRow, tree_rows,
};
use crate::app::{MemberItem, TreeItem};
use crate::settings::ClientPlaybackMap;
use crate::vm::avatar;
/// A banner mode as the UI takes it (`TreeItem.banner-mode`).
pub fn banner_mode(mode: BannerMode) -> i32 {
match mode {
BannerMode::NoAdjust => 0,
BannerMode::IgnoreAspect => 1,
BannerMode::KeepAspect => 2,
}
}
/// The picture of a banner address, if the engine fetched it.
pub fn banner(pictures: &HashMap<String, PathBuf>, url: Option<&str>) -> slint::Image {
avatar::image(url.and_then(|u| pictures.get(u)))
}
/// What the tree shows besides the presence.
pub struct TreeInput<'a> {
pub presence: &'a Presence,
@@ -23,11 +39,16 @@ pub struct TreeInput<'a> {
pub filter: &'a str,
/// Avatar pictures in the engine's cache, by unique id.
pub avatars: &'a HashMap<String, PathBuf>,
/// Icons in the engine's cache, by icon id (group icons).
/// Icons in the engine's cache, by icon id (channel, group and client
/// icons).
pub icons: &'a HashMap<u32, PathBuf>,
/// Banner pictures in the engine's cache, by address.
pub pictures: &'a HashMap<String, PathBuf>,
/// The server groups in display order; members are grouped by the
/// first one each client is in.
pub groups: &'a [GroupInfo],
/// The channel groups (their icons).
pub channel_groups: &'a [GroupInfo],
}
impl TreeInput<'_> {
@@ -35,6 +56,26 @@ impl TreeInput<'_> {
avatar::image(client.uid.as_ref().and_then(|uid| self.avatars.get(uid)))
}
/// An icon by id, if the engine fetched it (0: none).
fn icon(&self, id: u32) -> Option<slint::Image> {
let path = self.icons.get(&id).filter(|_| id != 0)?;
Some(avatar::image(Some(path))).filter(|i| i.size().width > 0)
}
/// The icons beside a client, as TeamSpeak shows them: its server
/// groups' in display order, its channel group's, its own.
fn client_icons(&self, client: &ClientInfo) -> Vec<slint::Image> {
let groups = self.groups.iter().filter(|g| client.server_groups.contains(&g.id));
let channel_group =
self.channel_groups.iter().filter(|g| client.channel_group == Some(g.id));
groups
.chain(channel_group)
.map(|g| g.icon)
.chain([client.icon])
.filter_map(|id| self.icon(id))
.collect()
}
/// The group a client is sorted under: the first of its server groups
/// in display order.
fn group_of(&self, client: &ClientInfo) -> Option<&GroupInfo> {
@@ -63,25 +104,50 @@ fn talking(input: &TreeInput, client: &ClientInfo) -> bool {
input.talking.contains(&client.id) || client.talking == Some(true)
}
/// Centered spacer prefixes are presentation metadata, not part of the title.
/// Leave other names untouched rather than guessing at the full spacer syntax.
fn channel_label(name: &str) -> (&str, bool) {
if let Some((suffix, label)) = name.strip_prefix("[cspacer").and_then(|s| s.split_once(']'))
&& suffix.bytes().all(|b| b.is_ascii_digit())
{
return (label, true);
}
(name, false)
}
/// A channel's name as shown, and whether it is a centred spacer. Only
/// top-level channels are spacers, as in TeamSpeak: a sub-channel keeps its
/// name as it is.
pub fn channel_title(channel: &ChannelInfo) -> (&str, bool) {
if channel.parent == 0 { channel_label(&channel.name) } else { (&channel.name, false) }
}
/// The rows of the tree, channels with their clients below.
pub fn rows(input: &TreeInput) -> Vec<TreeItem> {
let p = input.presence;
let rows: Vec<TreeItem> = tree_rows(p, &|cid| input.collapsed.contains(&cid))
.into_iter()
.map(|row| match row {
TreeRow::Channel { depth, channel } => TreeItem {
is_channel: true,
depth: depth as i32,
id: channel.id as i32,
name: channel.name.clone().into(),
own: input.own_channel == Some(channel.id),
locked: channel.has_password,
collapsed: input.collapsed.contains(&channel.id),
local_volume: 100,
members: p.members(channel.id).count() as i32,
max_members: channel.max_clients.filter(|m| *m >= 0).unwrap_or(-1),
..Default::default()
},
TreeRow::Channel { depth, channel } => {
let (name, centered_spacer) = channel_title(channel);
TreeItem {
centered_spacer,
is_channel: true,
depth: depth as i32,
id: channel.id as i32,
name: name.into(),
own: input.own_channel == Some(channel.id),
locked: channel.has_password,
collapsed: input.collapsed.contains(&channel.id),
local_volume: 100,
members: p.members(channel.id).count() as i32,
max_members: channel.max_clients.filter(|m| *m >= 0).unwrap_or(-1),
icon: input.icon(channel.icon).unwrap_or_default(),
banner: banner(input.pictures, channel.banner_gfx_url.as_deref()),
banner_mode: banner_mode(channel.banner_mode),
..Default::default()
}
}
TreeRow::Client { depth, client } => {
let playback = client
.uid
@@ -89,6 +155,7 @@ pub fn rows(input: &TreeInput) -> Vec<TreeItem> {
.and_then(|uid| input.playback.get(uid))
.copied()
.unwrap_or_default();
let mut icons = input.client_icons(client).into_iter();
TreeItem {
is_channel: false,
depth: depth as i32,
@@ -105,6 +172,9 @@ pub fn rows(input: &TreeInput) -> Vec<TreeItem> {
initials: avatar::initials(&client.nickname).into(),
tint: avatar::tint(&client.nickname),
avatar: input.avatar(client),
icon: icons.next().unwrap_or_default(),
icon_2: icons.next().unwrap_or_default(),
icon_3: icons.next().unwrap_or_default(),
..Default::default()
}
}
@@ -174,7 +244,7 @@ impl TreeInput<'_> {
&& c.streaming != Some(true)
&& c.away.is_none();
let status = match self.presence.channels.get(&c.channel) {
Some(channel) if elsewhere => format!("In {}", channel.name),
Some(channel) if elsewhere => format!("In {}", channel_title(channel).0),
_ => status_of(c, talking),
};
MemberItem {
@@ -235,12 +305,7 @@ fn sectioned(
fn group_section(input: &TreeInput, client: &ClientInfo) -> (Section, usize) {
match input.group_of(client) {
Some(g) => (
Section {
title: g.name.clone(),
icon: avatar::image(
Some(g.icon).filter(|i| *i != 0).and_then(|i| input.icons.get(&i)),
),
},
Section { title: g.name.clone(), icon: input.icon(g.icon).unwrap_or_default() },
1 + input.group_rank(client),
),
None => (Section { title: "Online".into(), ..Default::default() }, usize::MAX),
@@ -349,7 +414,9 @@ mod tests {
struct Extras {
avatars: HashMap<String, PathBuf>,
icons: HashMap<u32, PathBuf>,
pictures: HashMap<String, PathBuf>,
groups: Vec<GroupInfo>,
channel_groups: Vec<GroupInfo>,
}
fn input<'a>(
@@ -370,10 +437,98 @@ mod tests {
filter,
avatars: &extras.avatars,
icons: &extras.icons,
pictures: &extras.pictures,
groups: &extras.groups,
channel_groups: &extras.channel_groups,
}
}
/// A PNG of this width in a file (the engine's cache names them without
/// an extension).
fn picture_file(dir: &std::path::Path, name: &str, width: u32) -> PathBuf {
let mut png = Vec::new();
let mut encoder = png::Encoder::new(&mut png, width, 2);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header().unwrap().write_image_data(&vec![120; width as usize * 8]).unwrap();
let path = dir.join(name);
std::fs::write(&path, png).unwrap();
path
}
/// Avatars, channel icons and banners, group and client icons (in
/// TeamSpeak's order, those that arrived) reach the rows.
#[test]
fn pictures_in_rows() {
let dir = std::env::temp_dir().join(format!("voelin-tree-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut p = presence();
let lobby = p.channels.get_mut(&1).unwrap();
lobby.icon = 2001;
lobby.banner_gfx_url = Some("https://e.com/lobby.png".into());
lobby.banner_mode = BannerMode::KeepAspect;
let alice = p.clients.get_mut(&10).unwrap();
alice.uid = Some("alice=".into());
alice.server_groups = vec![7, 6];
alice.channel_group = Some(5);
alice.icon = 4004;
let group = |id, sort_id, icon| GroupInfo { id, icon, sort_id, ..Default::default() };
let e = Extras {
avatars: HashMap::from([("alice=".into(), picture_file(&dir, "avatar", 5))]),
icons: HashMap::from([
(2001, picture_file(&dir, "2001", 7)),
(3003, picture_file(&dir, "3003", 3)),
(4004, picture_file(&dir, "4004", 4)),
(5005, picture_file(&dir, "5005", 6)),
]),
pictures: HashMap::from([(
"https://e.com/lobby.png".into(),
picture_file(&dir, "banner", 9),
)]),
// Group 7 sorts first; group 6's icon has not arrived.
groups: vec![group(7, 10, 3003), group(6, 20, 9999)],
channel_groups: vec![group(5, 0, 5005)],
};
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let rows = rows(&input(&p, &t, &c, &pb, "", &e));
let width = |i: &slint::Image| i.size().width;
let lobby = &rows[0];
assert_eq!((width(&lobby.icon), width(&lobby.banner), lobby.banner_mode), (7, 9, 2));
let alice = &rows[1];
assert_eq!(width(&alice.avatar), 5);
assert_eq!([&alice.icon, &alice.icon_2, &alice.icon_3].map(width), [3, 6, 4]);
// Nothing for the others.
let games = &rows[2];
assert_eq!((width(&games.icon), width(&games.banner), games.banner_mode), (0, 0, 0));
assert_eq!(width(&rows[3].avatar), 0);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn centered_spacer_titles_keep_tree_identity_and_search() {
let mut p = presence();
p.channels.get_mut(&2).unwrap().name = "[cspacer12]Гамесы".into();
let (t, c, pb) = (HashSet::new(), HashSet::from([2]), ClientPlaybackMap::new());
let e = Extras::default();
let rows = rows(&input(&p, &t, &c, &pb, "Гамесы", &e));
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].name, "Гамесы");
assert!(rows[0].centered_spacer && rows[0].collapsed);
assert_eq!(rows[0].id, 2);
assert_eq!(channel_label("[cspacer]Games"), ("Games", true));
for name in ["[cspacerx]Games", "[cspacer2Games", "Games", "[spacer0]Games"] {
assert_eq!(channel_label(name), (name, false));
}
// Only top-level channels are spacers: a sub-channel keeps its name.
p.channels.get_mut(&3).unwrap().name = "[cspacer1]Chess".into();
let (t, c) = (HashSet::new(), HashSet::new());
let found = super::rows(&input(&p, &t, &c, &pb, "Chess", &e));
let chess = found.iter().find(|r| r.is_channel && r.id == 3).unwrap();
assert_eq!((chess.name.as_str(), chess.centered_spacer), ("[cspacer1]Chess", false));
assert_eq!(channel_title(&p.channels[&2]), ("Гамесы", true));
assert_eq!(channel_title(&p.channels[&3]), ("[cspacer1]Chess", false));
}
#[test]
fn tree_rows_and_counts() {
let p = presence();
+5
View File
@@ -214,6 +214,11 @@ export component MainWindow inherits Window {
}
if Nav.narrow && root.chrome: MobileShell {
property <bool> channel-chat: Nav.page == Page.server && !Nav.phone-voice
&& Nav.mobile-tab == MobileTab.chat && !Bridge.viewer-open
&& Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length
&& Bridge.tabs[Bridge.current-tab].kind == 1;
banner: self.channel-chat ? Bridge.tabs[Bridge.current-tab].banner : @image-url("");
title: Nav.page == Page.settings ? @tr("Settings")
: Nav.page == Page.friends ? @tr("Friends")
: Nav.page == Page.messages ? @tr("Messages")
+30 -1
View File
@@ -11,6 +11,8 @@ export struct ServerItem {
// Avatar of a server without an icon.
initials: string,
tint: color,
// The server's icon, empty without one.
icon: image,
// Unread messages in its chats.
unread: int,
// Someone streams in our channel there.
@@ -25,6 +27,8 @@ export struct ServerItem {
export struct TreeItem {
is-channel: bool,
// Recognized centred TeamSpeak spacer; name excludes its wire prefix.
centered-spacer: bool,
depth: int,
id: int,
name: string,
@@ -50,6 +54,16 @@ export struct TreeItem {
// Channels: clients inside, and the limit (-1: none).
members: int,
max-members: int,
// Leading channel icon or trailing client icons, empty where absent: a channel's
// icon; a client's server group icons, its channel group's and its own,
// in that order (the first three).
icon: image,
icon-2: image,
icon-3: image,
// A channel's banner picture (TeamSpeak 6), drawn behind the row;
// Wire sizing metadata; compact decorative backgrounds always cover.
banner: image,
banner-mode: int,
}
// A client for the members panel (everyone on the server) and the voice
@@ -129,6 +143,9 @@ export struct ChatTab {
// The last message ("Mira: the banner I promised") and its time.
last: string,
time: string,
// The channel's banner picture behind the chat's header (as TreeItem).
banner: image,
banner-mode: int,
}
// A piece of a chat line: text, or an emoji shown as an image (`emoji` is
@@ -259,6 +276,8 @@ export struct ViewerItem {
name: string,
state: string,
message: string,
// Their avatar picture, empty without one.
avatar: image,
}
// A capture source for the share dialog.
@@ -800,12 +819,22 @@ export global Bridge {
in property <string> server-title: @tr("No server selected");
// "12 online · 8 channels"
in property <string> server-stats;
// Our nickname on the current server, and the channel we are in.
// The server's host banner, empty without one (the server card shows its
// painted art then); mode as TreeItem.banner-mode.
in property <image> server-icon;
in property <image> server-banner;
in property <int> server-banner-mode;
// Our nickname on the current server, our avatar there (empty without
// one), and the channel we are in.
in property <string> nickname;
in property <image> own-avatar;
in property <string> own-channel;
// Its topic, and how many people it takes (-1: no limit).
in property <string> own-channel-topic;
in property <int> own-channel-limit: -1;
// Its banner picture (TeamSpeak 6), as TreeItem.banner.
in property <image> own-channel-banner;
in property <int> own-channel-banner-mode;
in property <bool> voice-connected;
in property <bool> voice-connecting;
in property <bool> observing;
@@ -0,0 +1,25 @@
import { Theme } from "../theme.slint";
// Banners decorate their owning row/header; they never add layout height.
// Cover keeps artwork undistorted while cropping its centre to the surface.
export component BannerPicture inherits Rectangle {
in property <image> source;
clip: true;
accessible-role: AccessibleRole.none;
Image {
width: 100%;
height: 100%;
source: root.source;
image-fit: cover;
horizontal-alignment: center;
vertical-alignment: center;
accessible-role: AccessibleRole.none;
}
// Even a white picture behind dark-theme text (or black behind light
// text) retains >4.5:1 contrast for Theme.text at the weakest stop.
Rectangle {
background: @linear-gradient(90deg,
Theme.surface.transparentize(0.26) 0%,
Theme.surface.transparentize(0.34) 100%);
}
}
@@ -9,6 +9,7 @@ export { Toggle, ToggleRow, RadioRow } from "toggle.slint";
export { Slider } from "slider.slint";
export { SegmentedTabs, TabItem } from "tabs.slint";
export { Status, Avatar } from "avatar.slint";
export { BannerPicture } from "banner-picture.slint";
export { CountBadge, LiveBadge, Chip, Dot } from "badge.slint";
export { SectionHeader, Card, Divider, Banner } from "card.slint";
export { Meter, SpeakingBars } from "meter.slint";
+130 -74
View File
@@ -5,78 +5,78 @@ import { Theme } from "../theme.slint";
import { Icons } from "../icons.slint";
import { Bridge, TreeItem } from "../bridge.slint";
import { Nav } from "../nav.slint";
import { Icon, Button, ButtonKind, IconButton, Avatar, LiveBadge, Chip, SectionHeader, SpeakingBars, PopupMenu, MenuEntry, ListView } from "../components/index.slint";
import { Icon, Button, ButtonKind, IconButton, Avatar, LiveBadge, Chip, SectionHeader, SpeakingBars, PopupMenu, MenuEntry, ListView, BannerPicture } from "../components/index.slint";
// The banner at the top of the sidebar: server name, counts, a menu.
export component ServerHeader inherits Rectangle {
height: 132px;
height: 76px * Theme.font-scale;
border-radius: Theme.radius-lg;
clip: true;
background: Theme.surface-2;
accessible-role: AccessibleRole.groupbox;
accessible-label: Bridge.server-title;
// Painted banner: a night sky gradient with a horizon glow.
Rectangle {
height: 72px;
y: 0;
background: @linear-gradient(180deg, #1a2d7a 0%, #3a2a8f 45%, #0b1330 100%);
Rectangle {
y: parent.height - 30px;
height: 30px;
background: @linear-gradient(180deg, transparent 0%, Theme.surface-2 100%);
}
for star[i] in [
{ x: 0.12, y: 0.2 }, { x: 0.3, y: 0.45 }, { x: 0.52, y: 0.15 }, { x: 0.7, y: 0.35 },
{ x: 0.86, y: 0.18 }, { x: 0.42, y: 0.62 }, { x: 0.93, y: 0.55 }, { x: 0.2, y: 0.7 },
]: Rectangle {
x: parent.width * star.x;
y: parent.height * star.y;
width: mod(i, 3) == 0 ? 3px : 2px;
height: self.width;
border-radius: self.width / 2;
background: #ffffffb0;
}
if Bridge.server-banner.width > 0: BannerPicture {
source: Bridge.server-banner;
}
VerticalLayout {
padding: Theme.space-4;
padding-top: 64px;
spacing: 2px;
HorizontalLayout {
spacing: Theme.space-2;
HorizontalLayout {
padding: Theme.space-3;
spacing: Theme.space-3;
Rectangle {
width: 42px;
height: 42px;
y: (parent.height - self.height) / 2;
if Bridge.server-icon.width > 0: Image {
width: 100%;
height: 100%;
source: Bridge.server-icon;
image-fit: contain;
accessible-role: AccessibleRole.none;
}
if Bridge.server-icon.width == 0: Icon {
source: Icons.server;
size: 32px;
tint: Theme.text-secondary;
x: (parent.width - self.width) / 2;
y: (parent.height - self.height) / 2;
}
}
VerticalLayout {
alignment: center;
horizontal-stretch: 1;
spacing: 3px;
Text {
text: Bridge.server-title;
font-size: Theme.font-lg;
font-size: Theme.font-md;
font-weight: Theme.weight-semibold;
color: Theme.text;
vertical-alignment: center;
horizontal-stretch: 1;
overflow: elide;
}
if Bridge.current-server >= 0: IconButton {
icon: Icons.chevron-down;
label: @tr("Server menu");
size: 28px;
icon-size: Theme.icon-sm;
clicked => { menu.show(self.x + self.width - 220px, self.y + self.height + 4px); }
HorizontalLayout {
spacing: Theme.space-2;
Rectangle {
width: 7px;
height: 7px;
y: (parent.height - self.height) / 2;
border-radius: 4px;
background: Bridge.voice-connected ? Theme.success : Bridge.observing ? Theme.info : Bridge.voice-connecting ? Theme.warning : Theme.offline;
}
Text {
text: Bridge.server-stats != "" ? Bridge.server-stats
: Bridge.voice-connecting ? @tr("Connecting…")
: Bridge.current-server >= 0 ? @tr("Not connected") : @tr("Add a server to start");
font-size: Theme.font-xs;
color: Bridge.server-banner.width > 0 ? Theme.text : Theme.text-secondary;
overflow: elide;
}
}
}
HorizontalLayout {
spacing: Theme.space-2;
Rectangle {
width: 8px;
height: 8px;
y: (parent.height - self.height) / 2;
border-radius: 4px;
background: Bridge.voice-connected ? Theme.success : Bridge.observing ? Theme.info : Bridge.voice-connecting ? Theme.warning : Theme.offline;
}
Text {
text: Bridge.server-stats != "" ? Bridge.server-stats
: Bridge.voice-connecting ? @tr("Connecting…")
: Bridge.current-server >= 0 ? @tr("Not connected") : @tr("Add a server to start");
font-size: Theme.font-sm;
color: Theme.text-secondary;
overflow: elide;
}
if Bridge.current-server >= 0: IconButton {
icon: Icons.chevron-down;
label: @tr("Server menu");
size: 24px;
icon-size: Theme.icon-sm;
y: (parent.height - self.height) / 2;
clicked => { menu.show(self.x + self.width - 220px, self.y + self.height + 4px); }
}
}
menu := PopupMenu {
@@ -117,12 +117,26 @@ export component ConnectActions inherits HorizontalLayout {
}
}
// A server-provided icon in its own colours.
component RowIcon inherits VerticalLayout {
in property <image> source;
alignment: center;
Image {
width: 16px;
height: 16px;
source: root.source;
image-fit: contain;
accessible-role: AccessibleRole.none;
}
}
// One row of the tree: a channel or a client.
component TreeRow inherits Rectangle {
in property <TreeItem> item;
callback client-clicked(int);
property <length> indent: item.depth * 14px;
height: item.is-channel ? 34px * Theme.font-scale : 30px * Theme.font-scale;
clip: true;
border-radius: Theme.radius-md;
background: item.is-channel && item.own ? Theme.accent-soft : area.has-hover ? Theme.surface-3 : transparent;
border-width: item.is-channel && item.own ? 1px : 0px;
@@ -137,6 +151,21 @@ component TreeRow inherits Rectangle {
client-clicked(item.id);
}
}
// Artwork is clipped behind the same compact row as its title.
if item.is-channel && item.banner.width > 0: BannerPicture {
x: root.indent;
width: max(0px, root.width - root.indent);
y: 0;
source: item.banner;
}
// The artwork covers the row's own background: tint it as that would
// be for our channel and on hover, translucent so the picture shows.
if item.is-channel && item.banner.width > 0 && (item.own || area.has-hover): Rectangle {
x: root.indent;
width: max(0px, root.width - root.indent);
border-radius: root.border-radius;
background: item.own ? Theme.accent-soft.transparentize(0.35) : Theme.surface-3.transparentize(0.5);
}
area := TouchArea {
mouse-cursor: MouseCursor.pointer;
double-clicked => {
@@ -153,38 +182,39 @@ component TreeRow inherits Rectangle {
}
}
if item.is-channel: HorizontalLayout {
height: 34px * Theme.font-scale;
padding-left: Theme.space-2 + root.indent;
padding-right: Theme.space-3;
spacing: Theme.space-2;
Rectangle {
width: 18px;
accessible-role: AccessibleRole.button;
accessible-label: item.collapsed ? @tr("Expand") : @tr("Collapse");
accessible-action-default => { Bridge.toggle-collapse(item.id); }
Icon {
source: item.collapsed ? Icons.chevron-right : Icons.chevron-down;
size: 14px;
tint: Theme.text-muted;
}
TouchArea {
clicked => { Bridge.toggle-collapse(item.id); }
}
if item.centered-spacer: Rectangle { width: 18px; }
if !item.centered-spacer && item.icon.width > 0: RowIcon {
source: item.icon;
}
Icon {
if !item.centered-spacer && item.icon.width == 0: Icon {
source: item.locked ? Icons.lock : Icons.volume-2;
size: 18px;
tint: item.own ? Theme.text : Theme.icon;
tint: item.banner.width > 0 || item.own ? Theme.text : Theme.icon;
y: (parent.height - self.height) / 2;
}
Text {
text: item.name;
color: item.own ? Theme.text : Theme.text-secondary;
font-weight: item.own ? Theme.weight-semibold : Theme.weight-medium;
horizontal-alignment: item.centered-spacer ? center : left;
// Full contrast over a banner.
color: item.own || item.banner.width > 0 ? Theme.text : Theme.text-secondary;
font-weight: item.own || item.banner.width > 0 ? Theme.weight-semibold : Theme.weight-medium;
vertical-alignment: center;
horizontal-stretch: 1;
overflow: elide;
}
if item.members > 0 || item.max-members >= 0: HorizontalLayout {
// At the end where the start shows the channel's icon, or nothing
// (a centred spacer).
if item.locked && (item.icon.width > 0 || item.centered-spacer): Icon {
source: Icons.lock;
size: 14px;
tint: item.banner.width > 0 ? Theme.text : Theme.icon;
y: (parent.height - self.height) / 2;
}
if !item.centered-spacer && (item.members > 0 || item.max-members >= 0): HorizontalLayout {
spacing: 3px;
if item.own: Icon {
source: Icons.users;
@@ -194,11 +224,26 @@ component TreeRow inherits Rectangle {
}
Text {
text: item.max-members >= 0 ? item.members + "/" + item.max-members : item.members;
color: item.own ? Theme.text : Theme.text-muted;
color: item.own || item.banner.width > 0 ? Theme.text : Theme.text-muted;
font-size: Theme.font-sm;
vertical-alignment: center;
}
}
Rectangle {
width: 18px;
accessible-role: AccessibleRole.button;
accessible-label: item.collapsed ? @tr("Expand") : @tr("Collapse");
accessible-action-default => { Bridge.toggle-collapse(item.id); }
Icon {
source: item.collapsed ? Icons.chevron-right : Icons.chevron-down;
size: 14px;
tint: item.banner.width > 0 ? Theme.text : Theme.text-muted;
y: (parent.height - self.height) / 2;
}
TouchArea {
clicked => { Bridge.toggle-collapse(item.id); }
}
}
}
if !item.is-channel: HorizontalLayout {
padding-left: Theme.space-2 + root.indent + 12px;
@@ -210,6 +255,7 @@ component TreeRow inherits Rectangle {
size: 22px;
initials: item.initials;
tint: item.tint;
image: item.avatar;
speaking: item.talking;
label: item.name;
}
@@ -283,6 +329,16 @@ component TreeRow inherits Rectangle {
font-size: Theme.font-xs;
vertical-alignment: center;
}
// Group and client icons.
if item.icon.width > 0: RowIcon {
source: item.icon;
}
if item.icon-2.width > 0: RowIcon {
source: item.icon-2;
}
if item.icon-3.width > 0: RowIcon {
source: item.icon-3;
}
}
}
+8 -4
View File
@@ -6,16 +6,18 @@ import { Theme } from "../theme.slint";
import { Icons } from "../icons.slint";
import { Bridge, ChatLine, ReactionItem, FileItem, Images } from "../bridge.slint";
import { Nav } from "../nav.slint";
import { Icon, IconButton, Avatar, Chip, TabItem, TextField, RichText, Banner, Button, ButtonKind, Spinner, Tooltip, ListView } from "../components/index.slint";
import { Icon, IconButton, Avatar, Chip, TabItem, TextField, RichText, Banner, Button, ButtonKind, Spinner, Tooltip, ListView, BannerPicture } from "../components/index.slint";
// The header of the main area: an icon, a title and a description, and
// actions (@children) at the right.
// A compact title and actions over the optional channel background.
export component PageHeader inherits Rectangle {
in property <image> icon: Icons.hash;
in property <image> banner;
in property <string> title;
in property <string> description;
min-height: 60px;
border-width: 0px;
clip: true;
if root.banner.width > 0: BannerPicture { source: root.banner; }
HorizontalLayout {
padding-left: Theme.space-6;
padding-right: Theme.space-4;
@@ -44,7 +46,7 @@ export component PageHeader inherits Rectangle {
Text {
text: root.description;
font-size: Theme.font-sm;
color: Theme.text-muted;
color: root.banner.width > 0 ? Theme.text : Theme.text-muted;
vertical-alignment: center;
horizontal-stretch: 1;
overflow: elide;
@@ -583,8 +585,10 @@ export component ChatView inherits VerticalLayout {
property <string> tab-name: Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length ? Bridge.tabs[Bridge.current-tab].name : "";
property <int> tab-kind: Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length ? Bridge.tabs[Bridge.current-tab].kind : 0;
property <string> tab-topic: Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length ? Bridge.tabs[Bridge.current-tab].topic : "";
property <image> tab-banner: Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length ? Bridge.tabs[Bridge.current-tab].banner : @image-url("");
if root.header: PageHeader {
banner: root.tab-banner;
icon: root.tab-kind == 1 ? Icons.hash : root.tab-kind == 2 ? Icons.at-sign : Icons.message-square;
title: root.tab-name;
description: root.tab-topic != "" ? root.tab-topic : Bridge.server-title;
@@ -290,11 +290,13 @@ component ShareCard inherits Modal {
Avatar {
size: 32px;
initials: "";
image: viewer.avatar;
status: viewer.state == "connected" ? Status.online : viewer.state == "requested" ? Status.idle : Status.offline;
Icon {
source: Icons.user;
size: 16px;
tint: #ffffff;
visible: viewer.avatar.width == 0;
}
}
}
+1
View File
@@ -291,6 +291,7 @@ component HomeBanner inherits Rectangle {
size: root.compact ? 44px : 56px;
square: true;
initials: root.server.initials;
image: root.server.icon;
tint: root.server.tint;
label: root.server.name;
status: root.server.status == "connected" ? Status.online : root.server.status == "observing" ? Status.info : root.server.status == "connecting" ? Status.idle : Status.none;
+51 -43
View File
@@ -7,7 +7,7 @@ import { Theme } from "../theme.slint";
import { Icons } from "../icons.slint";
import { Bridge, MemberItem, StreamItem } from "../bridge.slint";
import { Nav, MobileTab } from "../nav.slint";
import { Icon, IconButton, Button, ButtonKind, Avatar, LiveBadge, Select, Slider, SpeakingBars, ScrollView } from "../components/index.slint";
import { Icon, IconButton, Button, ButtonKind, Avatar, LiveBadge, Select, Slider, SpeakingBars, ScrollView, BannerPicture } from "../components/index.slint";
import { MessageList, Composer } from "chat.slint";
import { StudioBridge } from "../studio-bridge.slint";
@@ -21,52 +21,60 @@ export global PhoneVoice {
}
}
// The channel's name and topic, back, and Leave.
component ChannelBar inherits HorizontalLayout {
padding-left: Theme.space-3;
padding-right: Theme.space-3;
spacing: Theme.space-3;
// Channel background behind its name, topic, Back and Leave.
component ChannelBar inherits Rectangle {
height: 56px;
IconButton {
icon: Icons.arrow-left;
label: @tr("Back");
round: true;
filled: true;
size: 40px;
y: (parent.height - self.height) / 2;
clicked => { PhoneVoice.close(); }
clip: true;
if Bridge.own-channel-banner.width > 0: BannerPicture {
y: 0;
source: Bridge.own-channel-banner;
}
Icon {
source: Icons.volume-2;
size: 28px;
tint: Theme.text-secondary;
y: (parent.height - self.height) / 2;
}
VerticalLayout {
alignment: center;
horizontal-stretch: 1;
Text {
text: Bridge.own-channel;
color: Theme.text;
font-size: Theme.font-lg;
font-weight: Theme.weight-semibold;
overflow: elide;
HorizontalLayout {
height: 56px;
padding-left: Theme.space-3;
padding-right: Theme.space-3;
spacing: Theme.space-3;
IconButton {
icon: Icons.arrow-left;
label: @tr("Back");
round: true;
filled: true;
size: 40px;
y: (parent.height - self.height) / 2;
clicked => { PhoneVoice.close(); }
}
if Bridge.own-channel-topic != "": Text {
text: Bridge.own-channel-topic;
color: Theme.text-secondary;
font-size: Theme.font-sm;
overflow: elide;
Icon {
source: Icons.volume-2;
size: 28px;
tint: Theme.text-secondary;
y: (parent.height - self.height) / 2;
}
}
Button {
kind: ButtonKind.danger;
icon: Icons.log-out;
text: @tr("Leave");
y: (parent.height - self.height) / 2;
clicked => {
PhoneVoice.close();
Bridge.disconnect-voice();
VerticalLayout {
alignment: center;
horizontal-stretch: 1;
Text {
text: Bridge.own-channel;
color: Theme.text;
font-size: Theme.font-lg;
font-weight: Theme.weight-semibold;
overflow: elide;
}
if Bridge.own-channel-topic != "": Text {
text: Bridge.own-channel-topic;
color: Bridge.own-channel-banner.width > 0 ? Theme.text : Theme.text-secondary;
font-size: Theme.font-sm;
overflow: elide;
}
}
Button {
kind: ButtonKind.danger;
icon: Icons.log-out;
text: @tr("Leave");
y: (parent.height - self.height) / 2;
clicked => {
PhoneVoice.close();
Bridge.disconnect-voice();
}
}
}
}
+3
View File
@@ -44,6 +44,7 @@ export component MobileServers inherits VerticalLayout {
size: 46px;
square: true;
initials: server.initials;
image: server.icon;
tint: server.tint;
status: server.status == "connected" ? Status.online : server.status == "observing" ? Status.info : Status.none;
}
@@ -129,12 +130,14 @@ export component YouPage inherits ScrollView {
Avatar {
size: 56px;
initials: "";
image: Bridge.own-avatar;
tint: Theme.accent;
status: Bridge.voice-connected ? Status.online : Bridge.observing ? Status.info : Status.offline;
Icon {
source: Icons.user;
size: 28px;
tint: #ffffff;
visible: Bridge.own-avatar.width == 0;
}
}
VerticalLayout {
@@ -454,6 +454,7 @@ export component StreamViewer inherits Rectangle {
}
if !root.alone: VerticalLayout {
PageHeader {
banner: Bridge.own-channel-banner;
icon: Icons.volume-2;
title: Bridge.own-channel != "" ? Bridge.own-channel : Bridge.viewer-title;
description: Bridge.own-channel-topic;
@@ -930,6 +930,7 @@ component ChatRow inherits Rectangle {
if !line.continued: Avatar {
size: 34px;
initials: line.initials;
image: line.avatar;
tint: line.tint;
label: line.author;
}
+2 -1
View File
@@ -17,6 +17,7 @@ component StudioUser inherits HorizontalLayout {
Avatar {
size: 38px;
initials: Bridge.nickname != "" ? "" : "?";
image: Bridge.own-avatar;
tint: Theme.accent;
label: Bridge.nickname;
crown: StudioBridge.status.live;
@@ -25,7 +26,7 @@ component StudioUser inherits HorizontalLayout {
source: Icons.user;
size: 20px;
tint: #ffffff;
visible: Bridge.nickname != "";
visible: Bridge.nickname != "" && Bridge.own-avatar.width == 0;
}
}
}
+74 -69
View File
@@ -5,7 +5,7 @@ import { Theme } from "../theme.slint";
import { Icons } from "../icons.slint";
import { Bridge, MemberItem, StreamItem } from "../bridge.slint";
import { Nav, SettingsSection } from "../nav.slint";
import { Icon, IconButton, Button, ButtonKind, Avatar, LiveBadge, Chip, SpeakingBars } from "../components/index.slint";
import { Icon, IconButton, Button, ButtonKind, Avatar, LiveBadge, Chip, SpeakingBars, BannerPicture } from "../components/index.slint";
import { MessageList, Composer } from "chat.slint";
// One person: a large avatar with a ring (green while talking, blue while
@@ -212,78 +212,83 @@ component StreamCard inherits Rectangle {
// The voice channel view (desktop): header, people, streams, chat.
export component VoiceView inherits VerticalLayout {
// The title with the buttons beside it; the topic and the count below
// take the whole width.
HorizontalLayout {
padding-left: Theme.space-7;
padding-right: Theme.space-5;
padding-top: Theme.space-5;
padding-bottom: Theme.space-3;
spacing: Theme.space-5;
Icon {
source: Icons.volume-2;
size: 40px;
tint: Theme.text-secondary;
y: Theme.space-1;
// Banner shares the header; it does not push people and streams down.
Rectangle {
clip: true;
if Bridge.own-channel-banner.width > 0: BannerPicture {
source: Bridge.own-channel-banner;
}
VerticalLayout {
horizontal-stretch: 1;
spacing: Theme.space-1;
HorizontalLayout {
spacing: Theme.space-3;
Text {
text: Bridge.own-channel;
color: Theme.text;
font-size: Theme.font-3xl;
font-weight: Theme.weight-semibold;
vertical-alignment: center;
horizontal-stretch: 1;
overflow: elide;
}
IconButton {
icon: Icons.message-square;
label: @tr("Chat only");
y: (parent.height - self.height) / 2;
clicked => { Nav.show-voice(false); }
}
Button {
icon: Icons.settings;
text: @tr("Voice Settings");
y: (parent.height - self.height) / 2;
clicked => { Nav.open-settings(SettingsSection.voice); }
}
Button {
kind: ButtonKind.danger;
icon: Icons.phone-off;
text: @tr("Leave");
y: (parent.height - self.height) / 2;
clicked => {
Nav.show-voice(false);
Bridge.disconnect-voice();
HorizontalLayout {
padding-left: Theme.space-7;
padding-right: Theme.space-5;
padding-top: Theme.space-5;
padding-bottom: Theme.space-3;
spacing: Theme.space-5;
Icon {
source: Icons.volume-2;
size: 40px;
tint: Theme.text-secondary;
y: Theme.space-1;
}
VerticalLayout {
horizontal-stretch: 1;
spacing: Theme.space-1;
HorizontalLayout {
spacing: Theme.space-3;
Text {
text: Bridge.own-channel;
color: Theme.text;
font-size: Theme.font-3xl;
font-weight: Theme.weight-semibold;
vertical-alignment: center;
horizontal-stretch: 1;
overflow: elide;
}
IconButton {
icon: Icons.message-square;
label: @tr("Chat only");
y: (parent.height - self.height) / 2;
clicked => { Nav.show-voice(false); }
}
Button {
icon: Icons.settings;
text: @tr("Voice Settings");
y: (parent.height - self.height) / 2;
clicked => { Nav.open-settings(SettingsSection.voice); }
}
Button {
kind: ButtonKind.danger;
icon: Icons.phone-off;
text: @tr("Leave");
y: (parent.height - self.height) / 2;
clicked => {
Nav.show-voice(false);
Bridge.disconnect-voice();
}
}
}
}
if Bridge.own-channel-topic != "": Text {
text: Bridge.own-channel-topic;
color: Theme.text-secondary;
font-size: Theme.font-md;
overflow: elide;
}
HorizontalLayout {
spacing: Theme.space-2;
alignment: start;
Icon {
source: Icons.users;
size: 16px;
tint: Theme.text-secondary;
y: (parent.height - self.height) / 2;
if Bridge.own-channel-topic != "": Text {
text: Bridge.own-channel-topic;
color: Bridge.own-channel-banner.width > 0 ? Theme.text : Theme.text-secondary;
font-size: Theme.font-md;
overflow: elide;
}
Text {
text: Bridge.own-channel-limit >= 0
? @tr("{} in voice / {} total", Bridge.members.length, Bridge.own-channel-limit)
: @tr("{} in voice", Bridge.members.length);
color: Theme.text-secondary;
font-size: Theme.font-body;
HorizontalLayout {
spacing: Theme.space-2;
alignment: start;
Icon {
source: Icons.users;
size: 16px;
tint: Theme.text-secondary;
y: (parent.height - self.height) / 2;
}
Text {
text: Bridge.own-channel-limit >= 0
? @tr("{} in voice / {} total", Bridge.members.length, Bridge.own-channel-limit)
: @tr("{} in voice", Bridge.members.length);
color: Bridge.own-channel-banner.width > 0 ? Theme.text : Theme.text-secondary;
font-size: Theme.font-body;
}
}
}
}
+2 -1
View File
@@ -180,6 +180,7 @@ export component UserCard inherits Rectangle {
Avatar {
size: 38px;
initials: Bridge.nickname != "" ? "" : "?";
image: Bridge.own-avatar;
tint: Theme.accent;
label: Bridge.nickname;
// Green ring while our voice goes out.
@@ -189,7 +190,7 @@ export component UserCard inherits Rectangle {
source: Icons.user;
size: 20px;
tint: #ffffff;
visible: Bridge.nickname != "";
visible: Bridge.nickname != "" && Bridge.own-avatar.width == 0;
}
}
}
+1
View File
@@ -46,6 +46,7 @@ component RailServer inherits Rectangle {
size: 46px;
square: true;
initials: server.initials;
image: server.icon;
tint: server.tint;
label: server.name;
status: server.status == "connected" ? Status.online : server.status == "observing" ? Status.info : server.status == "connecting" ? Status.idle : Status.none;
+5 -2
View File
@@ -6,7 +6,7 @@ import { Theme } from "../theme.slint";
import { Icons } from "../icons.slint";
import { Bridge } from "../bridge.slint";
import { Nav, Page, MobileTab, SettingsSection } from "../nav.slint";
import { Icon, IconButton, CountBadge, PopupMenu, MenuEntry } from "../components/index.slint";
import { Icon, IconButton, CountBadge, PopupMenu, MenuEntry, BannerPicture } from "../components/index.slint";
import { PhoneVoice } from "../screens/mobile-voice.slint";
// One entry of the bottom navigation.
@@ -106,6 +106,7 @@ component PeoplePill inherits Rectangle {
export component MobileShell inherits Rectangle {
in property <string> title;
in property <string> subtitle;
in property <image> banner;
// Total unread messages (the Chat tab's badge).
in property <int> unread;
// Show a back arrow (sub-pages such as the settings).
@@ -123,6 +124,8 @@ export component MobileShell inherits Rectangle {
Rectangle {
height: 60px;
accessible-role: AccessibleRole.banner;
clip: true;
if root.banner.width > 0: BannerPicture { source: root.banner; }
HorizontalLayout {
padding-left: Theme.space-4;
padding-right: Theme.space-3;
@@ -153,7 +156,7 @@ export component MobileShell inherits Rectangle {
}
if root.subtitle != "": Text {
text: root.subtitle;
color: Theme.accent-text;
color: root.banner.width > 0 ? Theme.text : Theme.accent-text;
font-size: Theme.font-sm;
overflow: elide;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 260 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 254 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 283 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

+92
View File
@@ -422,6 +422,98 @@ the window's size so the pointer is not over the window, and passes
| ![friends](screenshots/mobile-friends.png) | ![messages](screenshots/mobile-messages.png) | ![events](screenshots/mobile-events.png) | ![the bell](screenshots/mobile-notifications.png) | ![streaming settings](screenshots/mobile-settings-streaming.png) |
| ![add server](screenshots/mobile-add-server.png) | | | | |
## Server and channel pictures
The compact server card shows its icon over the host banner. TeamSpeak 6
channel banners sit behind their titles in fixed-height tree rows (34 pixels),
and behind desktop and phone chat/voice headers. Artwork uses centred cover
cropping without distortion; it never adds height to navigation. Custom channel
icons lead the title, and recognized `[cspacerN]` labels are centred without
showing the prefix. A theme-aware surface gradient (74% to 66% opacity) keeps
primary text above 4.5:1 contrast even on all-white or all-black artwork, while
leaving the image visible. Missing pictures retain the normal background.
Bookmarks remember the server icon ID and the address that supplied it. The
server list, search results and server header load its cached bytes before
connecting, including after restarting the app. Editing a server address
invalidates the association; queued details from the old address cannot replace
it. A missing or evicted image falls back to initials. This requires no
ServerQuery configuration and starts no background voice connection.
First-visit icon downloads before login remain unverified. On a private TS6
6.0.0-beta13.1 fixture, the native encrypted handshake completed without
`clientinit`, but pre-login `serverinfo`, `getserverinfo`, `servergetvariables`,
`ftinitdownload` and `ftgetchannelfilehttptoken scid=icons` probes each received
no response within three seconds. The installed official client's UI code
populates its bookmark icon cache from connected server properties. Its clean
profile requires account setup before the server list, so no fresh-profile
network capture was obtained. These observations do not establish that every
server or client version lacks a pre-login mechanism.
The engine downloads banners only while `cache.fetch_images` is enabled.
Banners on the web (`http`, `https`) come from their host; banners in the
server's own files, linked as `ts3image://` (TeamSpeak 5 and 6:
`ts3image://<host>?port=…&channel=…&path=…&filename=…`, the file browser's
`ts3file://` link with its scheme changed; TeamSpeak 3:
`ts3image://<name>?channel=…&path=…`), come through the voice connection's
file transfer, so they need voice and the server's file permissions. Their
cache entry is named by the server too, as the same address names another
file elsewhere. Up to eight distinct web banners download concurrently;
duplicate URLs share a request. A picture may be up to 64 MiB, avatars and
icons too, and goes to disk as it arrives. Web downloads have a 10-second
connection timeout and fail after 20 seconds without data or when, after
their first 30 seconds, they average less than 32 KiB/s; there is no
fixed overall deadline, so large banners on slow hosts still arrive. Failed
avatars, icons and banners receive up to three automatic retries after
1, 4 and 16 seconds,
without waiting for a presence update. Avatar/icon/banner file-transfer
negotiation expires after 15 seconds, and the download after 30 seconds
plus its size at 32 KiB/s. User file transfers retain their existing
timing. Replaced images and closed sessions discard
obsolete results. A host banner's reload interval is at least 60 seconds;
failed refreshes preserve the previous cached picture. Closing the session
stops its reload timer. `PictureReady` invalidates the decoded image before
refreshing the visible models, including when the URL and cache path stay
the same.
PNG, JPEG, GIF, WebP and SVG are decoded by content, since cached files have
no extension. Raster pictures larger than 16,384 pixels on either axis or
64 MiB of decoded RGBA are refused before pixel allocation on the UI
thread. SVG uses Slint's vector loader and the existing vector-cache cost.
Avatars and server, channel, client and group icons use the same image cache.
The focused checks are the `voelin-core`, `voelin-model`, `voelin-observer`,
`voelin-store` and `voelin-ui` library tests. They cover offline icon restoration,
bookmark compatibility, cache misses and old-address event rejection. The live
`ts6_banners` test checks disabled
fetching, recovery from HTTP 503 without another presence update, all three
modes, channel URL replacement and removal, and a fresh host download after
the 60-second interval. `ts6_avatars` uploads an avatar with one client and
verifies its bytes and MD5 after another client downloads it into an independent
cache. Both use
the development TS6 server by default; a private fixture can override its
endpoints without changing the other live tests:
```sh
VOELIN_LIVE=1 \
VOELIN_BANNER_VOICE_ADDR=127.0.0.1:19988 \
VOELIN_BANNER_QUERY_ADDR=127.0.0.1:20022 \
cargo test --locked -p voelin-core --test live ts6_banners -- --exact
```
The 2026-10-04 follow-up passed all 200 focused library tests. The download
checks passed both live scenarios against a private
TS6 6.0.0-beta13.1 instance, including its real reload interval. The compact
layout passed seven headless screenshot scenarios. These screenshots use
sample data on Xvfb with Slint's software
renderer; the phone layouts are desktop renders, not Android device tests.
| Desktop | Phone layout |
|---|---|
| ![Dark chat and channel banners](screenshots/banners-desktop-dark.png) | ![Channel banner in the mobile chat header](screenshots/banners-mobile-chat.png) |
| ![Light chat and channel banners](screenshots/banners-desktop-light.png) | ![Light server list](screenshots/banners-mobile-servers.png) |
| ![Banner in the desktop voice header](screenshots/banners-desktop-voice.png) | ![Banner in the mobile voice header](screenshots/banners-mobile-voice.png) |
## Limits
- No drop shadows or blur (the software renderer draws none): glows are
+4
View File
@@ -476,6 +476,10 @@ impl Runner<'_> {
println!("icon {icon} {}", path.display());
return Ok(self.expected(&format!("icon {icon}")));
}
Event::PictureReady { url, path, .. } => {
println!("picture {url} {}", path.display());
return Ok(self.expected(&format!("picture {url}")));
}
Event::OfflineMessages { result, .. } => {
let list = result.map_err(|e| anyhow::anyhow!("messagelist: {e}"))?;
println!("offline inbox n={}", list.len());