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

Generated
+1
View File
@@ -9480,6 +9480,7 @@ dependencies = [
"futures",
"hickory-resolver",
"md5",
"reqwest",
"rusqlite",
"serde",
"serde_json",
+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"] }
+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();
}
}
+16 -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;
@@ -646,6 +649,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,
+70 -1
View File
@@ -38,6 +38,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 +109,8 @@ 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,
}
/// Our live stream, for the gateway's directory.
@@ -168,6 +171,11 @@ 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>,
/// 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 +202,8 @@ impl Session {
contacts_rx,
avatars: HashMap::new(),
icons: HashSet::new(),
pictures: HashSet::new(),
banner_reload: None,
contact_audio: HashMap::new(),
stream_friends: BTreeSet::new(),
details: None,
@@ -741,6 +751,7 @@ impl Session {
fn forget_images(&mut self) {
self.avatars.clear();
self.icons.clear();
self.pictures.clear();
self.contact_audio.clear();
self.stream_friends.clear();
self.details = None;
@@ -799,10 +810,60 @@ impl Session {
self.fetch_image(cache::icon_key(icon), Some(files::icon_path(icon)), waiter);
}
/// 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 reload = Some((&p.server.banner_gfx_url, p.server.banner_gfx_interval_s))
.filter(|(url, every)| !url.is_empty() && *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();
// Ends with the session (nobody receives).
let timer = tokio::spawn(async move {
let start = tokio::time::Instant::now() + every;
let mut tick = tokio::time::interval_at(start, every);
loop {
tick.tick().await;
if tx.send(SourceEvent::ReloadBanner).is_err() {
break;
}
}
});
self.banner_reload = Some((url.clone(), every_s, timer.abort_handle()));
}
}
if !self.settings.current().get(&CACHE_FETCH_IMAGES) {
return;
}
let urls = std::iter::once(&p.server.banner_gfx_url)
.chain(p.channels.values().filter_map(|c| c.banner_gfx_url.as_ref()));
for url in urls.filter(|u| !u.is_empty()) {
if self.pictures.insert(url.clone()) {
self.fetch_picture(url, false);
}
}
}
/// Get the picture at `url` into the cache (again with `fresh`).
fn fetch_picture(&self, url: &str, fresh: bool) {
let (session, events, address) = (self.id, self.events.clone(), url.to_owned());
let waiter: Waiter = Box::new(move |result| match result {
Ok(path) => {
let _ = events.send(Event::PictureReady { session, url: address, path });
}
Err(e) => debug!(url = %address, "no picture: {e}"),
});
web::fetch(self.cache.current(), url, fresh, max_cache_bytes(&self.settings), waiter);
}
/// Get `key` from the cache, downloading `path` of channel 0 once.
fn fetch_image(&self, key: String, path: Option<String>, waiter: Waiter) {
let cache = self.cache.current();
let Fetch::Download(temp) = cache.fetch(&key, waiter) else { return };
let Fetch::Download(temp) = cache.fetch(&key, false, 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));
@@ -1302,6 +1363,13 @@ impl Session {
self.emit(Event::RequestDone { session: self.id, request, result });
}
},
SourceEvent::ReloadBanner => {
if let Some((url, ..)) = &self.banner_reload
&& self.settings.current().get(&CACHE_FETCH_IMAGES)
{
self.fetch_picture(url, true);
}
}
_ => debug!("event from a replaced source ignored"),
}
}
@@ -1613,6 +1681,7 @@ 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 });
+215
View File
@@ -0,0 +1,215 @@
//! 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 [`MAX_BYTES`], arrives
//! within [`TIMEOUT`] (connected within [`CONNECT_TIMEOUT`]) and 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.
use std::path::Path;
use std::sync::LazyLock;
use std::time::Duration;
use crate::cache::{self, Cache, Fetch, Waiter};
/// Larger pictures are refused; banners are rarely above a few hundred KiB.
pub(crate) const MAX_BYTES: u64 = 4 << 20;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const TIMEOUT: Duration = Duration::from_secs(30);
/// 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)
.timeout(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 result = download(&url, &temp, MAX_BYTES).await;
cache.finish(&key, &temp, result, max_cache_bytes);
});
}
/// Download the picture at `url` into `to`: at most `max_bytes`, and only
/// if it is a picture.
async fn download(url: &str, to: &Path, max_bytes: u64) -> Result<(), String> {
let client = CLIENT.as_ref().map_err(Clone::clone)?;
let too_big = || format!("larger than {} KiB", max_bytes >> 10);
let mut response = client
.get(url)
.send()
.await
.and_then(reqwest::Response::error_for_status)
.map_err(|e| e.to_string())?;
if response.content_length().is_some_and(|n| n > max_bytes) {
return Err(too_big());
}
let mut data = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? {
if (data.len() + chunk.len()) as u64 > max_bytes {
return Err(too_big());
}
data.extend_from_slice(&chunk);
}
if !is_picture(&data) {
return Err("not a picture".into());
}
if let Some(dir) = to.parent() {
tokio::fs::create_dir_all(dir).await.map_err(|e| e.to_string())?;
}
tokio::fs::write(to, &data).await.map_err(|e| e.to_string())
}
/// 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]; 6] =
[b"\x89PNG\r\n\x1a\n", b"\xff\xd8\xff", b"GIF87a", b"GIF89a", b"<?xml", b"<svg"];
STARTS.iter().any(|s| data.starts_with(s))
|| (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())
}
// 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()),
_ => ("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;
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");
download(&format!("{base}/banner"), &to, 1000).await.unwrap();
assert_eq!(std::fs::read(&to).unwrap(), PNG);
download(&format!("{base}/svg"), &to, 1000).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, 1000).await.unwrap_err();
assert!(e.contains(error), "{path}: {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, 1000).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();
}
#[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"<!DOCTYPE html>"));
assert!(!is_picture(b"RIFF\x24\0\0\0WAVEfmt "));
assert!(!is_picture(b""));
}
}
+124
View File
@@ -122,3 +122,127 @@ 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 on 127.0.0.1 that answers every request with `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 {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
while let Ok((mut socket, _)) = listener.accept().await {
let body = body.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]),
}
}
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}")
}
/// The host banner and a channel banner set through ServerQuery reach the
/// engine's cache (`Event::PictureReady`); the server is put back after.
#[tokio::test(flavor = "multi_thread")]
async fn ts6_banners() {
use base64::Engine as _;
use voelin_model::BannerMode;
use voelin_query::{Command as Query, QueryClient};
if !live() {
return;
}
let png = base64::prelude::BASE64_STANDARD.decode(PNG).unwrap();
let base = 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, "127.0.0.1:10022"))
.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 (old_url, old_mode) =
(before("virtualserver_hostbanner_gfx_url"), before("virtualserver_hostbanner_mode"));
let edit = Query::new("serveredit")
.arg("virtualserver_hostbanner_gfx_url", &host_url)
.arg("virtualserver_hostbanner_mode", 2);
admin.send(&edit).await.unwrap();
let created = admin
.send(
&Query::new("channelcreate")
.arg("channel_name", format!("banner-{}", std::process::id()))
.arg("channel_banner_gfx_url", &channel_url)
.arg("channel_banner_mode", 1),
)
.await;
let check = {
let (host_url, channel_url) = (host_url.clone(), channel_url.clone());
tokio::spawn(async move {
let engine = Engine::start();
let dir =
std::env::temp_dir().join(format!("voelin-live-banners-{}", std::process::id()));
engine.send(Command::AttachCache(dir.clone()));
let mut events = engine.subscribe();
engine.send(Command::ConnectVoice {
session: 1,
options: Box::new(VoiceOptions::new("127.0.0.1:9988", "banner-check")),
});
let mut seen = std::collections::HashMap::new();
let mut channel_mode = None;
wait_for(&mut events, "both banners", |e| {
match e {
Event::PictureReady { url, path, .. } => {
seen.insert(url.clone(), std::fs::read(path).unwrap());
}
Event::Presence { presence, .. } => {
channel_mode = presence
.channels
.values()
.find(|c| c.banner_gfx_url.as_deref() == Some(channel_url.as_str()))
.map(|c| c.banner_mode);
assert_eq!(presence.server.banner_mode, BannerMode::KeepAspect);
}
_ => {}
}
seen.contains_key(&host_url) && seen.contains_key(&channel_url)
})
.await;
assert_eq!(channel_mode, Some(BannerMode::IgnoreAspect));
assert!(seen.values().all(|bytes| *bytes == png));
engine.send(Command::CloseSession { session: 1 });
tokio::time::sleep(Duration::from_millis(500)).await;
let _ = std::fs::remove_dir_all(dir);
})
};
let result = check.await;
if let Ok(rows) = &created
&& let Some(cid) = rows.first().and_then(|r| r.get("cid"))
{
let delete = Query::new("channeldelete").arg("cid", cid).arg("force", 1);
admin.send(&delete).await.unwrap();
}
let restore = Query::new("serveredit")
.arg("virtualserver_hostbanner_gfx_url", old_url)
.arg("virtualserver_hostbanner_mode", old_mode);
admin.send(&restore).await.unwrap();
created.unwrap();
if let Err(e) = result {
std::panic::resume_unwind(e.into_panic());
}
}
+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());