Fix image download recovery and banner layout
Retry failed avatars, icons and banners automatically with bounded backoff, expire stalled image transfers, and preserve explicit avatar requests. Bound concurrent HTTP downloads, allow larger banners, and decode BOM SVGs. Separate artwork from channel titles and controls across desktop and mobile, using bounded aspect-aware areas and realistic demo fixtures. Validation: 176 library tests, explicit-fetch policy regression, independent TS6 avatar download and transient503/banner reload scenarios, strict Clippy, formatting, license notices, and eight reviewed headless captures.
No files matched your search
@@ -9,6 +9,9 @@
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::time::Instant;
|
||||
|
||||
use tokio::sync::{broadcast, mpsc, watch};
|
||||
use tracing::debug;
|
||||
@@ -111,8 +114,23 @@ enum SourceEvent {
|
||||
AvatarUploaded(u64, RequestId, Result<String, String>),
|
||||
/// Time to fetch the host banner again (`banner_gfx_interval_s`).
|
||||
ReloadBanner(String),
|
||||
/// A failed picture can be tried again on the next presence update.
|
||||
PictureFailed(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),
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -175,6 +193,9 @@ struct Session {
|
||||
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)>,
|
||||
@@ -205,6 +226,9 @@ impl Session {
|
||||
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(),
|
||||
@@ -262,6 +286,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 {
|
||||
@@ -270,6 +296,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();
|
||||
@@ -602,7 +629,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, .. } => {
|
||||
@@ -751,6 +778,8 @@ 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();
|
||||
@@ -769,7 +798,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());
|
||||
}
|
||||
@@ -781,6 +810,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);
|
||||
@@ -788,30 +818,143 @@ 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}"),
|
||||
});
|
||||
let waiter = self
|
||||
.image_waiter(ImageRequest::Avatar { uid: uid.into(), hash: hash.into() }, requested);
|
||||
self.fetch_image(key, files::avatar_path(uid), waiter);
|
||||
}
|
||||
|
||||
fn fetch_icon(&self, icon: u32) {
|
||||
let (session, events) = (self.id, self.events.clone());
|
||||
let waiter: Waiter = Box::new(move |result| match result {
|
||||
Ok(path) => {
|
||||
let _ = events.send(Event::IconReady { session, icon, path });
|
||||
}
|
||||
Err(e) => debug!(icon, "no icon: {e}"),
|
||||
});
|
||||
let waiter = self.image_waiter(ImageRequest::Icon(icon), false);
|
||||
self.fetch_image(cache::icon_key(icon), Some(files::icon_path(icon)), 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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
@@ -844,9 +987,13 @@ impl Session {
|
||||
if !enabled {
|
||||
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| cache::picture_key(u).is_some()) {
|
||||
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| cache::picture_key(u).is_some())
|
||||
.cloned()
|
||||
.collect();
|
||||
self.pictures.retain(|url| urls.contains(url));
|
||||
for url in &urls {
|
||||
if self.pictures.insert(url.clone()) {
|
||||
self.fetch_picture(url, false);
|
||||
}
|
||||
@@ -855,17 +1002,7 @@ impl Session {
|
||||
|
||||
/// 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 sources = self.sources_tx.clone();
|
||||
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}");
|
||||
let _ = sources.send(SourceEvent::PictureFailed(address));
|
||||
}
|
||||
});
|
||||
let waiter = self.image_waiter(ImageRequest::Picture(url.into()), false);
|
||||
web::fetch(self.cache.current(), url, fresh, max_cache_bytes(&self.settings), waiter);
|
||||
}
|
||||
|
||||
@@ -874,7 +1011,7 @@ impl Session {
|
||||
let cache = self.cache.current();
|
||||
let Fetch::Download(temp) = cache.fetch(&key, false, waiter) else { return };
|
||||
let settings = self.settings.clone();
|
||||
let (Some(path), Some(_)) = (path, &self.voice) else {
|
||||
let (Some(path), Some((_, voice))) = (path, &self.voice) else {
|
||||
cache.finish(&key, &temp, Err(NO_VOICE.into()), max_cache_bytes(&settings));
|
||||
return;
|
||||
};
|
||||
@@ -892,7 +1029,10 @@ impl Session {
|
||||
});
|
||||
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 failed = report.clone();
|
||||
if voice.send(VoiceCmd::Download { transfer: None, file, sink, report }).is_err() {
|
||||
failed(TransferState::Failed(NO_VOICE.into()));
|
||||
}
|
||||
}
|
||||
|
||||
// Contacts
|
||||
@@ -1297,6 +1437,7 @@ impl Session {
|
||||
}
|
||||
|
||||
fn stop_all(&mut self) {
|
||||
self.forget_images();
|
||||
if let Some((.., timer)) = self.banner_reload.take() {
|
||||
timer.abort();
|
||||
}
|
||||
@@ -1375,8 +1516,8 @@ impl Session {
|
||||
self.emit(Event::RequestDone { session: self.id, request, result });
|
||||
}
|
||||
},
|
||||
SourceEvent::PictureFailed(url) => {
|
||||
self.pictures.remove(&url);
|
||||
SourceEvent::ImageFinished(requested, epoch, request, result) => {
|
||||
self.image_finished(requested, epoch, request, result);
|
||||
}
|
||||
SourceEvent::ReloadBanner(address) => {
|
||||
if let Some((url, ..)) = &self.banner_reload
|
||||
@@ -1727,35 +1868,203 @@ mod banner_tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_picture_is_retried_on_next_presence() {
|
||||
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);
|
||||
assert!(session.pictures.contains(url));
|
||||
cache.finish(&key, &temp, Err("temporary failure".into()), 0);
|
||||
let failure = session.sources_rx.as_mut().unwrap().recv().await.unwrap();
|
||||
session.source_event(failure);
|
||||
assert!(!session.pictures.contains(url));
|
||||
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.fetch_pictures(&presence);
|
||||
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.pictures.contains(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();
|
||||
}
|
||||
|
||||
#[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();
|
||||
}
|
||||
|
||||
|
||||
@@ -255,8 +255,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 +284,18 @@ impl Job {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 +450,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 +492,27 @@ 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)
|
||||
{
|
||||
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 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(Duration::from_secs(30), receive).await.is_err() {
|
||||
task_report(TransferState::Failed("image download timed out".into()));
|
||||
}
|
||||
});
|
||||
self.running(transfer, task.abort_handle(), part, report);
|
||||
}
|
||||
}
|
||||
@@ -760,7 +793,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 +959,41 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -17,10 +17,14 @@ 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);
|
||||
/// Allow larger GIF/PNG banners while bounding each buffered response.
|
||||
pub(crate) const MAX_BYTES: u64 = 16 << 20;
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const READ_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const TIMEOUT: Duration = Duration::from_secs(30);
|
||||
/// 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);
|
||||
@@ -28,6 +32,7 @@ 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)
|
||||
.timeout(TIMEOUT)
|
||||
.user_agent(concat!("Voelin/", env!("CARGO_PKG_VERSION")))
|
||||
.build()
|
||||
@@ -45,6 +50,7 @@ pub(crate) fn fetch(cache: Cache, url: &str, fresh: bool, max_cache_bytes: u64,
|
||||
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, MAX_BYTES).await;
|
||||
cache.finish(&key, &temp, result, max_cache_bytes);
|
||||
});
|
||||
@@ -83,9 +89,11 @@ async fn download(url: &str, to: &Path, max_bytes: u64) -> Result<(), 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"];
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -126,6 +134,7 @@ mod tests {
|
||||
"/svg" => {
|
||||
("200 OK", true, b"<svg xmlns='http://www.w3.org/2000/svg'/>".to_vec())
|
||||
}
|
||||
"/large-banner" => ("200 OK", true, [PNG, &vec![0; 5 << 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()),
|
||||
@@ -201,6 +210,82 @@ mod tests {
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn banners_above_the_old_four_megabyte_limit_are_downloaded() {
|
||||
let base = server().await;
|
||||
let dir = temp_dir("large-banner");
|
||||
let path = dir.join("large");
|
||||
download(&format!("{base}/large-banner"), &path, MAX_BYTES).await.unwrap();
|
||||
assert!(std::fs::metadata(&path).unwrap().len() > 4 << 20);
|
||||
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));
|
||||
@@ -208,6 +293,8 @@ mod tests {
|
||||
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""));
|
||||
|
||||
@@ -126,7 +126,7 @@ async fn ts3_engine() {
|
||||
/// A 1×1 PNG.
|
||||
const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
|
||||
|
||||
/// An HTTP server on 127.0.0.1 that answers every request with `body`;
|
||||
/// 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>) {
|
||||
@@ -135,10 +135,12 @@ async fn serve(body: Vec<u8>) -> (String, std::sync::Arc<std::sync::atomic::Atom
|
||||
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];
|
||||
@@ -149,6 +151,13 @@ async fn serve(body: Vec<u8>) -> (String, std::sync::Arc<std::sync::atomic::Atom
|
||||
}
|
||||
}
|
||||
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()
|
||||
@@ -270,6 +279,11 @@ async fn ts6_banners() {
|
||||
})
|
||||
.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(
|
||||
@@ -342,3 +356,90 @@ async fn ts6_banners() {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -385,7 +385,7 @@ 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, banners behind two channels and an icon
|
||||
// The host banner, a server icon, banners above 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;
|
||||
@@ -400,6 +400,8 @@ fn demo_ui(app: &mut App) {
|
||||
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 [
|
||||
@@ -1001,6 +1003,7 @@ fn demo_social(app: &mut App) {
|
||||
/// 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;
|
||||
@@ -1027,9 +1030,10 @@ fn demo_pictures(app: &mut App) {
|
||||
}),
|
||||
}];
|
||||
for (url, picture) in [
|
||||
(DEMO_HOST_BANNER, demo_picture(560, 144, 3)),
|
||||
(DEMO_HOST_BANNER, demo_picture(256, 256, 3)),
|
||||
(DEMO_CHILL_BANNER, demo_picture(900, 120, 11)),
|
||||
(DEMO_RAID_BANNER, demo_picture(640, 160, 5)),
|
||||
(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 });
|
||||
|
||||
@@ -136,6 +136,7 @@ pub fn forget(path: &std::path::Path) {
|
||||
/// 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()?;
|
||||
@@ -157,7 +158,7 @@ fn decode(bytes: &[u8]) -> Option<(Image, usize)> {
|
||||
}
|
||||
// Intrinsic SVG dimensions describe coordinates, not an allocated
|
||||
// pixel buffer. Use the same vector cost as the emoji cache.
|
||||
svg_cost(bytes.len())
|
||||
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))
|
||||
}
|
||||
@@ -236,6 +237,12 @@ 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>"#;
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
import { Theme } from "../theme.slint";
|
||||
|
||||
// A server's banner picture (the host banner, a TeamSpeak 6 channel banner)
|
||||
// filling its area, behind other content. `mode` as the server sets it:
|
||||
// 0 as it is (centred), 1 stretched, 2 scaled to fit keeping its aspect
|
||||
// ratio. A wash of `scrim-color` at `scrim` opacity over it keeps text on
|
||||
// top readable.
|
||||
// Native artwork keeps its pixel size; resized artwork gets an aspect-aware
|
||||
// area. Bound unusually tall pictures so navigation remains usable.
|
||||
export global BannerLayout {
|
||||
public pure function artwork-height(source: image, width: length, mode: int, limit: length) -> length {
|
||||
return source.width <= 0 ? 0px : min(limit, max(32px,
|
||||
mode == 0 ? source.height * 1px : width * source.height / source.width));
|
||||
}
|
||||
}
|
||||
|
||||
// Artwork has its own area: titles and controls use the solid surface below.
|
||||
// Wire modes: 0 native (centred), 1 stretched, 2 aspect-preserving fit.
|
||||
export component BannerPicture inherits Rectangle {
|
||||
in property <image> source;
|
||||
in property <int> mode;
|
||||
in property <color> scrim-color: Theme.surface;
|
||||
// Keep small text readable over even a solid white/black banner in
|
||||
// both themes. Text-free artwork can explicitly turn this off.
|
||||
in property <float> scrim: 0.9;
|
||||
clip: true;
|
||||
background: Theme.surface-2;
|
||||
accessible-role: AccessibleRole.none;
|
||||
Image {
|
||||
width: 100%;
|
||||
@@ -23,7 +26,4 @@ export component BannerPicture inherits Rectangle {
|
||||
vertical-alignment: center;
|
||||
accessible-role: AccessibleRole.none;
|
||||
}
|
||||
if root.scrim > 0: Rectangle {
|
||||
background: root.scrim-color.transparentize(1 - root.scrim);
|
||||
}
|
||||
}
|
||||
@@ -9,7 +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 { BannerPicture, BannerLayout } 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";
|
||||
|
||||
@@ -5,30 +5,24 @@ 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, BannerPicture } from "../components/index.slint";
|
||||
import { Icon, Button, ButtonKind, IconButton, Avatar, LiveBadge, Chip, SectionHeader, SpeakingBars, PopupMenu, MenuEntry, ListView, BannerPicture, BannerLayout } from "../components/index.slint";
|
||||
|
||||
// The banner at the top of the sidebar: server name, counts, a menu.
|
||||
export component ServerHeader inherits Rectangle {
|
||||
height: 132px;
|
||||
property <length> artwork-height: Bridge.server-banner.width > 0
|
||||
? BannerLayout.artwork-height(Bridge.server-banner, root.width, Bridge.server-banner-mode, 180px) : 64px;
|
||||
height: root.artwork-height + 76px;
|
||||
border-radius: Theme.radius-lg;
|
||||
clip: true;
|
||||
background: Theme.surface-2;
|
||||
accessible-role: AccessibleRole.groupbox;
|
||||
accessible-label: Bridge.server-title;
|
||||
// The server's host banner, fading into the card.
|
||||
if Bridge.server-banner.width > 0: Rectangle {
|
||||
height: 72px;
|
||||
// Keep the full host artwork separate from the server title and actions.
|
||||
if Bridge.server-banner.width > 0: BannerPicture {
|
||||
y: 0;
|
||||
BannerPicture {
|
||||
source: Bridge.server-banner;
|
||||
mode: Bridge.server-banner-mode;
|
||||
scrim: 0;
|
||||
}
|
||||
Rectangle {
|
||||
y: parent.height - 30px;
|
||||
height: 30px;
|
||||
background: @linear-gradient(180deg, transparent 0%, Theme.surface-2 100%);
|
||||
}
|
||||
height: root.artwork-height;
|
||||
source: Bridge.server-banner;
|
||||
mode: Bridge.server-banner-mode;
|
||||
}
|
||||
// Without one, a painted banner: a night sky gradient with a horizon
|
||||
// glow.
|
||||
@@ -55,7 +49,7 @@ export component ServerHeader inherits Rectangle {
|
||||
}
|
||||
VerticalLayout {
|
||||
padding: Theme.space-4;
|
||||
padding-top: 64px;
|
||||
padding-top: root.artwork-height + Theme.space-2;
|
||||
spacing: 2px;
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
@@ -152,7 +146,10 @@ 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;
|
||||
property <length> artwork-height: item.is-channel
|
||||
? BannerLayout.artwork-height(item.banner, max(0px, root.width - root.indent), item.banner-mode, 112px) : 0px;
|
||||
height: (item.is-channel ? 34px * Theme.font-scale : 30px * Theme.font-scale) + root.artwork-height;
|
||||
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;
|
||||
@@ -167,13 +164,14 @@ component TreeRow inherits Rectangle {
|
||||
client-clicked(item.id);
|
||||
}
|
||||
}
|
||||
// The channel's banner behind its row, washed so the name stays
|
||||
// readable (the own channel's tint over it).
|
||||
// Artwork above the title stays visible without reducing text contrast.
|
||||
if item.is-channel && item.banner.width > 0: BannerPicture {
|
||||
border-radius: root.border-radius;
|
||||
x: root.indent;
|
||||
width: max(0px, root.width - root.indent);
|
||||
y: 0;
|
||||
height: root.artwork-height;
|
||||
source: item.banner;
|
||||
mode: item.banner-mode;
|
||||
scrim-color: item.own ? Theme.accent-soft : area.has-hover ? Theme.surface-3 : Theme.surface;
|
||||
}
|
||||
area := TouchArea {
|
||||
mouse-cursor: MouseCursor.pointer;
|
||||
@@ -191,6 +189,8 @@ component TreeRow inherits Rectangle {
|
||||
}
|
||||
}
|
||||
if item.is-channel: HorizontalLayout {
|
||||
y: root.artwork-height;
|
||||
height: 34px * Theme.font-scale;
|
||||
padding-left: Theme.space-2 + root.indent;
|
||||
padding-right: Theme.space-3;
|
||||
spacing: Theme.space-2;
|
||||
|
||||
@@ -6,23 +6,15 @@ 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, BannerPicture } from "../components/index.slint";
|
||||
import { Icon, IconButton, Avatar, Chip, TabItem, TextField, RichText, Banner, Button, ButtonKind, Spinner, Tooltip, ListView, BannerPicture, BannerLayout } from "../components/index.slint";
|
||||
|
||||
// The header of the main area: an icon, a title and a description, and
|
||||
// actions (@children) at the right; a channel's banner picture behind them
|
||||
// (`banner`, `banner-mode` as TreeItem's).
|
||||
// The title, description and actions below a separate channel artwork area.
|
||||
export component PageHeader inherits Rectangle {
|
||||
in property <image> icon: Icons.hash;
|
||||
in property <string> title;
|
||||
in property <string> description;
|
||||
in property <image> banner;
|
||||
in property <int> banner-mode;
|
||||
min-height: 60px;
|
||||
border-width: 0px;
|
||||
if root.banner.width > 0: BannerPicture {
|
||||
source: root.banner;
|
||||
mode: root.banner-mode;
|
||||
}
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-6;
|
||||
padding-right: Theme.space-4;
|
||||
@@ -51,7 +43,7 @@ export component PageHeader inherits Rectangle {
|
||||
Text {
|
||||
text: root.description;
|
||||
font-size: Theme.font-sm;
|
||||
color: root.banner.width > 0 ? Theme.text-secondary : Theme.text-muted;
|
||||
color: Theme.text-muted;
|
||||
vertical-alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
overflow: elide;
|
||||
@@ -593,12 +585,15 @@ export component ChatView inherits VerticalLayout {
|
||||
property <image> tab-banner: Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length ? Bridge.tabs[Bridge.current-tab].banner : @image-url("");
|
||||
property <int> tab-banner-mode: Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length ? Bridge.tabs[Bridge.current-tab].banner-mode : 0;
|
||||
|
||||
if root.header && root.tab-banner.width > 0: BannerPicture {
|
||||
height: BannerLayout.artwork-height(root.tab-banner, self.width, root.tab-banner-mode, 160px);
|
||||
source: root.tab-banner;
|
||||
mode: root.tab-banner-mode;
|
||||
}
|
||||
if root.header: PageHeader {
|
||||
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;
|
||||
banner: root.tab-banner;
|
||||
banner-mode: root.tab-banner-mode;
|
||||
// Only when the chat does not come through our voice connection
|
||||
// (an invisible observer or a relay).
|
||||
if Bridge.presence-source != "" && !Bridge.voice-connected: Chip {
|
||||
|
||||
@@ -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, BannerPicture } from "../components/index.slint";
|
||||
import { Icon, IconButton, Button, ButtonKind, Avatar, LiveBadge, Select, Slider, SpeakingBars, ScrollView, BannerPicture, BannerLayout } from "../components/index.slint";
|
||||
import { MessageList, Composer } from "chat.slint";
|
||||
import { StudioBridge } from "../studio-bridge.slint";
|
||||
|
||||
@@ -21,14 +21,19 @@ export global PhoneVoice {
|
||||
}
|
||||
}
|
||||
|
||||
// The channel's name and topic, back, and Leave; its banner behind them.
|
||||
// The channel artwork above its name, topic, Back and Leave.
|
||||
component ChannelBar inherits Rectangle {
|
||||
height: 56px;
|
||||
property <length> artwork-height: BannerLayout.artwork-height(Bridge.own-channel-banner, root.width, Bridge.own-channel-banner-mode, 120px);
|
||||
height: 56px + root.artwork-height;
|
||||
if Bridge.own-channel-banner.width > 0: BannerPicture {
|
||||
y: 0;
|
||||
height: root.artwork-height;
|
||||
source: Bridge.own-channel-banner;
|
||||
mode: Bridge.own-channel-banner-mode;
|
||||
}
|
||||
HorizontalLayout {
|
||||
y: root.artwork-height;
|
||||
height: 56px;
|
||||
padding-left: Theme.space-3;
|
||||
padding-right: Theme.space-3;
|
||||
spacing: Theme.space-3;
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Theme } from "../theme.slint";
|
||||
import { Icons } from "../icons.slint";
|
||||
import { Bridge, StreamItem, MemberItem } from "../bridge.slint";
|
||||
import { Nav } from "../nav.slint";
|
||||
import { Icon, Button, ButtonKind, IconButton, Avatar, Status, LiveBadge, Chip, Select, SectionHeader, SpeakingBars, Slider, Spinner, TextField, TabItem, ListView, ScrollView } from "../components/index.slint";
|
||||
import { Icon, Button, ButtonKind, IconButton, Avatar, Status, LiveBadge, Chip, Select, SectionHeader, SpeakingBars, Slider, Spinner, TextField, TabItem, ListView, ScrollView, BannerPicture, BannerLayout } from "../components/index.slint";
|
||||
import { MemberRow, GroupHeader } from "members.slint";
|
||||
import { PageHeader, MessageList, Composer } from "chat.slint";
|
||||
|
||||
@@ -453,12 +453,15 @@ export component StreamViewer inherits Rectangle {
|
||||
compact: true;
|
||||
}
|
||||
if !root.alone: VerticalLayout {
|
||||
if Bridge.own-channel-banner.width > 0: BannerPicture {
|
||||
height: BannerLayout.artwork-height(Bridge.own-channel-banner, self.width, Bridge.own-channel-banner-mode, 160px);
|
||||
source: Bridge.own-channel-banner;
|
||||
mode: Bridge.own-channel-banner-mode;
|
||||
}
|
||||
PageHeader {
|
||||
icon: Icons.volume-2;
|
||||
title: Bridge.own-channel != "" ? Bridge.own-channel : Bridge.viewer-title;
|
||||
description: Bridge.own-channel-topic;
|
||||
banner: Bridge.own-channel-banner;
|
||||
banner-mode: Bridge.own-channel-banner-mode;
|
||||
if Bridge.members.length > 0: Button {
|
||||
icon: Icons.users;
|
||||
text: @tr("{} in voice", Bridge.members.length);
|
||||
|
||||
@@ -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, BannerPicture } from "../components/index.slint";
|
||||
import { Icon, IconButton, Button, ButtonKind, Avatar, LiveBadge, Chip, SpeakingBars, BannerPicture, BannerLayout } from "../components/index.slint";
|
||||
import { MessageList, Composer } from "chat.slint";
|
||||
|
||||
// One person: a large avatar with a ring (green while talking, blue while
|
||||
@@ -213,12 +213,13 @@ 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. The channel's banner behind them.
|
||||
// take the whole width. Artwork sits above the title on its own surface.
|
||||
if Bridge.own-channel-banner.width > 0: BannerPicture {
|
||||
height: BannerLayout.artwork-height(Bridge.own-channel-banner, self.width, Bridge.own-channel-banner-mode, 160px);
|
||||
source: Bridge.own-channel-banner;
|
||||
mode: Bridge.own-channel-banner-mode;
|
||||
}
|
||||
Rectangle {
|
||||
if Bridge.own-channel-banner.width > 0: BannerPicture {
|
||||
source: Bridge.own-channel-banner;
|
||||
mode: Bridge.own-channel-banner-mode;
|
||||
}
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-7;
|
||||
padding-right: Theme.space-5;
|
||||
|
||||
@@ -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, BannerPicture } from "../components/index.slint";
|
||||
import { Icon, IconButton, CountBadge, PopupMenu, MenuEntry, BannerPicture, BannerLayout } from "../components/index.slint";
|
||||
import { PhoneVoice } from "../screens/mobile-voice.slint";
|
||||
|
||||
// One entry of the bottom navigation.
|
||||
@@ -121,14 +121,15 @@ export component MobileShell inherits Rectangle {
|
||||
callback go-back();
|
||||
background: Theme.backdrop;
|
||||
VerticalLayout {
|
||||
if root.banner.width > 0: BannerPicture {
|
||||
height: BannerLayout.artwork-height(root.banner, self.width, root.banner-mode, 120px);
|
||||
source: root.banner;
|
||||
mode: root.banner-mode;
|
||||
}
|
||||
// Top bar.
|
||||
Rectangle {
|
||||
height: 60px;
|
||||
accessible-role: AccessibleRole.banner;
|
||||
if root.banner.width > 0: BannerPicture {
|
||||
source: root.banner;
|
||||
mode: root.banner-mode;
|
||||
}
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-4;
|
||||
padding-right: Theme.space-3;
|
||||
|
||||
|
Before Width: | Height: | Size: 254 KiB After Width: | Height: | Size: 238 KiB |
|
Before Width: | Height: | Size: 246 KiB After Width: | Height: | Size: 230 KiB |
|
Before Width: | Height: | Size: 274 KiB After Width: | Height: | Size: 262 KiB |
|
Before Width: | Height: | Size: 98 KiB After Width: | Height: | Size: 93 KiB |
|
Before Width: | Height: | Size: 67 KiB After Width: | Height: | Size: 63 KiB |
|
Before Width: | Height: | Size: 109 KiB After Width: | Height: | Size: 106 KiB |
@@ -425,16 +425,25 @@ the window's size so the pointer is not over the window, and passes
|
||||
## Server and channel pictures
|
||||
|
||||
The server card shows the host banner. TeamSpeak 6 channel banners appear
|
||||
behind their tree rows, the desktop chat and voice headers, and the phone's
|
||||
chat and voice headers. The server's sizing mode is preserved: 0 centres
|
||||
the original picture, 1 stretches it, and 2 fits it while keeping its aspect
|
||||
ratio. A theme-coloured wash keeps the text readable over bright pictures.
|
||||
above their tree rows, the desktop chat and voice headers, and the phone's
|
||||
chat and voice headers. Artwork has a separate area from titles and controls,
|
||||
so bright pictures remain visible without reducing text contrast. Areas follow
|
||||
the picture's aspect ratio, capped at 180 pixels for the host, 112 for tree
|
||||
rows, 160 for desktop headers and 120 for phone headers. The server's sizing
|
||||
mode is preserved: 0 centres the original picture (clipped to the bounded
|
||||
area), 1 stretches it, and 2 fits it while keeping its aspect ratio.
|
||||
Missing or refused pictures leave the normal background in place.
|
||||
|
||||
The engine downloads HTTP(S) banners only while `cache.fetch_images` is
|
||||
enabled. Downloads have a 4 MiB limit, a 10-second connection timeout and
|
||||
a 30-second overall timeout. Failed downloads can retry on a later
|
||||
presence update. A host banner's reload interval is at least 60 seconds;
|
||||
enabled. Up to eight distinct banners download concurrently; duplicate URLs
|
||||
share a request. Downloads have a 16 MiB limit, a 5-second connection
|
||||
timeout, a 10-second read timeout and a 30-second overall timeout. 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 negotiation expires after
|
||||
15 seconds and their image download after 30 seconds. 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
|
||||
@@ -448,8 +457,11 @@ Avatars and server, channel, client and group icons use the same image cache.
|
||||
|
||||
The focused checks are the `voelin-core`, `voelin-model`, `voelin-observer`
|
||||
and `voelin-ui` library tests. The live `ts6_banners` test checks disabled
|
||||
fetching, initial downloads, all three modes, channel URL replacement and
|
||||
removal, and a fresh host download after the 60-second interval. It uses
|
||||
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:
|
||||
|
||||
@@ -460,7 +472,7 @@ VOELIN_BANNER_QUERY_ADDR=127.0.0.1:20022 \
|
||||
cargo test --locked -p voelin-core --test live ts6_banners -- --exact
|
||||
```
|
||||
|
||||
The 2026-10-04 check passed 168 focused library tests and the live scenario
|
||||
The 2026-10-04 check passed 176 focused library tests and both live scenarios
|
||||
against a private TS6 6.0.0-beta13.1 instance, including its real reload
|
||||
interval. These screenshots use sample data on Xvfb with Slint's software
|
||||
renderer; the phone layouts are desktop renders, not Android device tests.
|
||||
|
||||