Fetch banners from the web into the image cache

The host banner (virtualserver_hostbanner_gfx_url) and TeamSpeak 6
channel banners are http(s) addresses on any host, not files on the
server, so the voice file transfer that fetches avatars and icons cannot
get them. A new engine path (web.rs) downloads them with the workspace's
reqwest client (rustls, system proxies and certificate store) into the
same cache, keyed by the MD5 of the address (pictures/<md5>), only for
http and https, at most 4 MiB, with a 10 s connect and 30 s overall
timeout, and keeps a download only if its content is a picture the UI
decodes (PNG, JPEG, GIF, WebP, SVG), whatever the address or the server
say; an error page is not cached as a banner.

The session fetches the banners of the presence it shows, from any
source, when cache.fetch_images allows (it contacts hosts the server
chose, as the official client does), and reports each as PictureReady.
When the server sets virtualserver_hostbanner_gfx_interval, a timer asks
the session to fetch the host banner again (never more often than once a
minute, as TeamSpeak 3 and 6 servers enforce) and the new file replaces
the old one; Cache::fetch takes `fresh` for that.

Tests: a local HTTP server on 127.0.0.1 for the download, the size cap
(announced and unannounced), refused pages and the cache; the cache keys;
a live test that sets both banners on the TeamSpeak 6 dev server through
ServerQuery, sees them arrive and puts the server back. voelinctl engine
prints the pictures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-04 14:12:34 +03:00
1 parent 04a6d1f931
commit 1318a9db3b
8 files changed
+486 -16

No files matched your search

+54 -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,14 @@ pub(crate) fn icon_key(id: u32) -> String {
format!("icons/{id}")
}
/// 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)))
}
impl Cache {
/// A cache in `dir` (created when the first file arrives).
pub fn new(dir: impl Into<PathBuf>) -> Self {
@@ -131,9 +140,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 +248,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 +308,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 +326,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 +337,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 +358,20 @@ 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]
@@ -383,5 +404,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();
}
}