Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

29.7 KB
Raw Blame
//! Image downloads for egui (avatars, emoji, attachments).
//!
//! egui_extras' HTTP loader opens a new connection per image with no limit,
//! which with hundreds of custom emoji floods the network and starves the
//! Discord connection. This loader shares one pooled HTTP/2 client and runs at
//! most a few downloads at a time; failures are retried after a short pause.

use eframe::egui::{
    self,
    load::{
        Bytes, BytesLoadResult, BytesLoader, BytesPoll, ImageLoadResult, ImageLoader, ImagePoll, LoadError, SizeHint,
        SizedTexture, TextureLoadResult, TextureLoader, TexturePoll,
    },
};
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

const MAX_CONCURRENT: usize = 12;
const RETRY_AFTER: Duration = Duration::from_secs(30);
/// Downloaded (still compressed) image files kept in memory.
const BYTES_BUDGET: usize = 48 * 1024 * 1024;
/// With a disk cache, a downloaded file is only needed until it's decoded
/// (the texture then holds the picture); one not asked for in this long is
/// dropped from memory and re-read from disk if it's ever needed again.
/// (30 s: a channel's worth of pictures and clips is ~40 MB of files.)
const BYTES_TTL: Duration = Duration::from_secs(30);
/// Textures not drawn for this long are freed.
const TEXTURE_TTL: Duration = Duration::from_secs(45);
const EMOJI_TTL: Duration = Duration::from_secs(600);

/// Windows-rendered or Discord custom emoji.
fn is_emoji(uri: &str) -> bool {
    uri.starts_with("winemoji://") || uri.contains("/emojis/") || uri.contains("twemoji")
}

enum Entry {
    Pending,
    Ready(Arc<[u8]>, Option<String>, Instant),
    Failed(String, Instant),
}

/// RustCord's own URI tweaks live in the fragment (`#.gif`, `#still`): the server
/// never sees it, so cache and fetch by the URL without it.
fn without_fragment(uri: &str) -> &str {
    uri.split('#').next().unwrap_or(uri)
}

/// Per-frame URIs of animations → the animation: `x.gif#12` → `x.gif`
/// (egui's GIF frames), `x.mp4#vframe=3` → `x.mp4` (RustCord's GIF videos).
fn gif_base(uri: &str) -> Option<&str> {
    if let Some((base, _)) = crate::video::split_frame_uri(uri) {
        return Some(base);
    }
    let (base, frame) = uri.rsplit_once('#')?;
    frame.parse::<usize>().ok()?;
    base.contains(".gif").then_some(base)
}

/// Decodes downloaded images (PNG / JPEG / WebP, and the first frame of a
/// GIF) on background threads. egui_extras decodes on the UI thread, which
/// stutters when a channel's avatars, emoji and pictures arrive at once.
///
/// GIFs only ever play through the shared player (`video`, see
/// `video::clip_key`). A GIF's own address given to egui ("x.gif") arrives
/// here as "x.gif#<frame>", egui's way of playing GIFs itself; left to
/// egui_extras that decodes the whole file on the UI thread, keeps every
/// frame, and redraws at the GIF's own pace. Here it is simply the GIF's
/// first frame: a still.
pub struct FastImages {
    cache: Arc<Mutex<HashMap<String, Decoded>>>,
    jobs: Mutex<std::sync::mpsc::Sender<(String, Arc<[u8]>)>>,
}

enum Decoded {
    Pending,
    /// The pixels, and when they were last asked for.
    Ready(Arc<egui::ColorImage>, Instant),
    Failed(String),
}

/// A decoded picture is handed to the GPU the first time it is drawn and
/// dropped here right then. One that is never drawn (it scrolled out of view
/// while it was still decoding: a channel settling at its bottom leaves
/// dozens, 13 MB apiece for big attachments) used to stay for good; now it
/// goes after this long unasked-for, and is decoded again if it comes back.
const DECODED_TTL: Duration = Duration::from_secs(12);

/// The decoded-pictures cache, for [`drop_stale_decoded`].
static DECODED: std::sync::OnceLock<Arc<Mutex<HashMap<String, Decoded>>>> = std::sync::OnceLock::new();

/// Drop decoded pictures nobody has drawn or asked for lately.
pub fn drop_stale_decoded() {
    let Some(cache) = DECODED.get() else { return };
    if let Ok(mut c) = cache.lock() {
        c.retain(|_, d| match d {
            Decoded::Ready(_, asked) => asked.elapsed() < DECODED_TTL,
            _ => true,
        });
    }
}

/// Decode a downloaded picture, refusing anything absurdly large: a small
/// file can claim a huge size ("decompression bomb") and take gigabytes.
pub fn decode_limited(bytes: &[u8]) -> image::ImageResult<image::DynamicImage> {
    let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()?;
    let mut limits = image::Limits::default();
    limits.max_image_width = Some(16_384);
    limits.max_image_height = Some(16_384);
    limits.max_alloc = Some(256 * 1024 * 1024);
    reader.limits(limits);
    reader.decode()
}

impl FastImages {
    pub fn install(ctx: &egui::Context) {
        let cache: Arc<Mutex<HashMap<String, Decoded>>> = Default::default();
        let _ = DECODED.set(cache.clone());
        let (tx, rx) = std::sync::mpsc::channel::<(String, Arc<[u8]>)>();
        let rx = Arc::new(Mutex::new(rx));
        for i in 0..2 {
            let (rx, cache, ctx) = (rx.clone(), cache.clone(), ctx.clone());
            let _ = std::thread::Builder::new().name(format!("rustcord-decode-{i}")).spawn(move || loop {
                let job = rx.lock().ok().and_then(|r| r.recv().ok());
                let Some((uri, bytes)) = job else { return };
                let decoded = match decode_limited(&bytes) {
                    Ok(img) => {
                        let rgba = img.to_rgba8();
                        let size = [rgba.width() as usize, rgba.height() as usize];
                        // An avatar: its dominant colour, for profiles without a banner.
                        if crate::palette::wants(&uri) {
                            if let Some(c) = crate::palette::dominant(rgba.as_raw(), size[0], size[1]) {
                                crate::palette::remember(&uri, c);
                            }
                        }
                        Decoded::Ready(Arc::new(egui::ColorImage::from_rgba_unmultiplied(size, rgba.as_raw())), Instant::now())
                    }
                    Err(e) => Decoded::Failed(e.to_string()),
                };
                if let Ok(mut c) = cache.lock() {
                    if matches!(c.get(&uri), Some(Decoded::Pending)) {
                        c.insert(uri, decoded);
                    }
                }
                drop(bytes);
                crate::diagnostics::release_this_threads_memory();
                ctx.request_repaint();
            });
        }
        ctx.add_image_loader(Arc::new(Self { cache, jobs: Mutex::new(tx) }));
    }
}

impl ImageLoader for FastImages {
    fn id(&self) -> &str {
        egui::generate_loader_id!(FastImages)
    }

    fn load(&self, ctx: &egui::Context, uri: &str, _: SizeHint) -> ImageLoadResult {
        let web = uri.starts_with("https://");
        // The player's frames and SVGs aren't this loader's. (A GIF is: its first frame.)
        let path = without_fragment(uri).split('?').next().unwrap_or(uri);
        let video_frame = crate::video::split_frame_uri(uri).is_some();
        if !web || video_frame || path.ends_with(".svg") {
            return Err(LoadError::NotSupported);
        }
        match self.cache.lock().expect("decoded").get_mut(uri) {
            Some(Decoded::Ready(img, asked)) => {
                *asked = Instant::now();
                return Ok(ImagePoll::Ready { image: img.clone() });
            }
            Some(Decoded::Pending) => return Ok(ImagePoll::Pending { size: None }),
            Some(Decoded::Failed(e)) => return Err(LoadError::Loading(e.clone())),
            None => {}
        }
        match ctx.try_load_bytes(uri)? {
            BytesPoll::Pending { size } => Ok(ImagePoll::Pending { size }),
            BytesPoll::Ready { bytes, .. } => {
                self.cache.lock().expect("decoded").insert(uri.to_string(), Decoded::Pending);
                let _ = self.jobs.lock().expect("jobs").send((uri.to_string(), Arc::from(&bytes[..])));
                Ok(ImagePoll::Pending { size: None })
            }
        }
    }

    fn forget(&self, uri: &str) {
        if let Ok(mut c) = self.cache.lock() {
            c.remove(uri);
        }
    }

    fn forget_all(&self) {
        if let Ok(mut c) = self.cache.lock() {
            c.clear();
        }
    }

    fn byte_size(&self) -> usize {
        self.cache
            .lock()
            .map(|c| c.values().map(|d| if let Decoded::Ready(i, _) = d { i.pixels.len() * 4 } else { 0 }).sum())
            .unwrap_or(0)
    }
}

/// A cached texture: when it was last drawn, and for an animation (see
/// `video`), which frame of the clip it currently holds.
struct Texture {
    handle: egui::TextureHandle,
    used: Instant,
    frame: Option<usize>,
}

/// Textures for every image, freed when not drawn for [`TEXTURE_TTL`].
/// egui's default loader keeps every image ever shown, on the GPU and as
/// decoded pixels in RAM, for as long as the app runs.
///
/// An animation (`<url>#vframe=<n>`) is one texture per clip whose pixels
/// are replaced as it plays, not one texture per frame: a 150-frame clip
/// would otherwise allocate 150 GPU textures (70 MB at 400×300) that then
/// sit in this cache, and allocate a new one on every frame while playing.
pub struct LruTextures {
    cache: Mutex<HashMap<(String, egui::TextureOptions), Texture>>,
    last_sweep: Mutex<Instant>,
}

impl LruTextures {
    pub fn install(ctx: &egui::Context) {
        ctx.add_texture_loader(Arc::new(Self { cache: Default::default(), last_sweep: Mutex::new(Instant::now()) }));
    }

    fn forget_decoded(ctx: &egui::Context, uri: &str) {
        for l in ctx.loaders().image.lock().iter() {
            l.forget(uri);
        }
    }

    /// Free textures that haven't been drawn lately, and the decoded
    /// animations behind them.
    fn sweep(&self, ctx: &egui::Context) {
        {
            let mut last = self.last_sweep.lock().expect("sweep");
            if last.elapsed() < Duration::from_secs(5) {
                return;
            }
            *last = Instant::now();
        }
        drop_stale_decoded();
        crate::video::release_idle();
        let mut gone_clips = HashSet::new();
        let still_used: HashSet<String> = {
            let mut cache = self.cache.lock().expect("textures");
            cache.retain(|(uri, _), tex| {
                // Emoji are small and come back all the time (pickers,
                // reactions): keep them much longer so pickers open at once.
                let ttl = if is_emoji(uri) { EMOJI_TTL } else { TEXTURE_TTL };
                let keep = tex.used.elapsed() < ttl;
                if !keep {
                    if tex.frame.is_some() {
                        gone_clips.insert(uri.clone());
                    } else if let Some(b) = gif_base(uri) {
                        gone_clips.insert(b.to_string());
                    }
                }
                keep
            });
            cache.iter().filter_map(|((u, _), tex)| if tex.frame.is_some() { Some(u.clone()) } else { gif_base(u).map(String::from) }).collect()
        };
        for b in gone_clips.difference(&still_used) {
            Self::forget_decoded(ctx, b);
        }
    }
}

impl TextureLoader for LruTextures {
    fn id(&self) -> &str {
        egui::generate_loader_id!(LruTextures)
    }

    fn load(&self, ctx: &egui::Context, uri: &str, options: egui::TextureOptions, hint: SizeHint) -> TextureLoadResult {
        self.sweep(ctx);
        // Animations are keyed by the clip, not the frame.
        let (base, frame) = match crate::video::split_frame_uri(uri) {
            Some((b, f)) => (b, Some(f)),
            None => (uri, None),
        };
        // Pictures are mostly drawn smaller than they are (a 72 px emoji at
        // 20 px, a 48 px one at 22 px): give every texture mipmaps, so
        // shrinking averages the pixels like a browser does. Plain linear
        // filtering skips most of them, which leaves jagged, speckled edges.
        // Not for playing clips, whose pixels are replaced on every frame.
        let mut options = options;
        if frame.is_none() && options.minification == egui::TextureFilter::Linear && options.mipmap_mode.is_none() {
            options.mipmap_mode = Some(egui::TextureFilter::Linear);
        }
        let key = (base.to_string(), options);
        let shown = {
            let mut cache = self.cache.lock().expect("textures");
            match cache.get_mut(&key) {
                Some(tex) => {
                    tex.used = Instant::now();
                    Some((SizedTexture::from_handle(&tex.handle), tex.frame))
                }
                None => None,
            }
        };
        if let Some((texture, current)) = shown {
            if frame.is_none() || frame == current {
                return Ok(TexturePoll::Ready { texture });
            }
            // The clip moved on: replace the pixels in the same texture.
            // Until the frame is decoded, keep showing the one RustCord has.
            return match ctx.try_load_image(uri, hint)? {
                ImagePoll::Pending { .. } => Ok(TexturePoll::Ready { texture }),
                ImagePoll::Ready { image } => {
                    let mut cache = self.cache.lock().expect("textures");
                    match cache.get_mut(&key) {
                        Some(tex) => {
                            // Same size (every frame of a clip is): write into
                            // the texture's memory instead of having the GPU
                            // allocate it anew ~30 times a second per clip.
                            if tex.handle.size() == image.size {
                                tex.handle.set_partial([0, 0], image, options);
                            } else {
                                tex.handle.set(image, options);
                            }
                            tex.frame = frame;
                            Ok(TexturePoll::Ready { texture: SizedTexture::from_handle(&tex.handle) })
                        }
                        // Forgotten meanwhile: start over next frame.
                        None => Ok(TexturePoll::Pending { size: None }),
                    }
                }
            };
        }
        match ctx.try_load_image(uri, hint)? {
            ImagePoll::Pending { size } => Ok(TexturePoll::Pending { size }),
            ImagePoll::Ready { image } => {
                let handle = ctx.load_texture(base, image, options);
                let texture = SizedTexture::from_handle(&handle);
                self.cache.lock().expect("textures").insert(key, Texture { handle, used: Instant::now(), frame });
                // The pixels are on the GPU now: drop the decoded copy. An
                // animation keeps its decoded frames until `sweep` frees it.
                if frame.is_none() && gif_base(uri).is_none() {
                    Self::forget_decoded(ctx, uri);
                }
                Ok(TexturePoll::Ready { texture })
            }
        }
    }

    fn forget(&self, uri: &str) {
        let base = crate::video::split_frame_uri(uri).map(|(b, _)| b).unwrap_or(uri);
        // (A clip's texture goes by its key.)
        let clip = crate::video::clip_key(base);
        self.cache.lock().expect("textures").retain(|(u, _), _| u != base && *u != clip);
    }

    fn forget_all(&self) {
        self.cache.lock().expect("textures").clear();
    }

    fn byte_size(&self) -> usize {
        self.cache.lock().map(|c| c.values().map(|t| t.handle.byte_size()).sum()).unwrap_or(0)
    }
}

pub struct NetImages {
    client: reqwest::Client,
    runtime: tokio::runtime::Runtime,
    permits: Arc<tokio::sync::Semaphore>,
    cache: Arc<Mutex<HashMap<String, Entry>>>,
    /// On-disk copies of downloaded images (avatars, icons, emoji…), so the
    /// next launch shows them without downloading.
    disk: Option<Arc<std::path::Path>>,
    last_sweep: Mutex<Instant>,
}

impl NetImages {
    /// Drop files nobody has asked for in [`BYTES_TTL`] (they're on disk).
    fn sweep(&self, cache: &mut HashMap<String, Entry>) {
        if self.disk.is_none() {
            return;
        }
        let mut last = self.last_sweep.lock().expect("sweep");
        if last.elapsed() < Duration::from_secs(20) {
            return;
        }
        *last = Instant::now();
        cache.retain(|_, e| match e {
            Entry::Ready(_, _, used) => used.elapsed() < BYTES_TTL,
            _ => true,
        });
    }
}

/// Disk cache size cap; the oldest files go first.
const DISK_BUDGET: u64 = 400 * 1024 * 1024;
/// (32 MB: animated banners, profile effects and nameplates run to 10-16 MB,
/// and a file that isn't on disk has to stay in memory or be downloaded again.)
const DISK_MAX_FILE: usize = 32 * 1024 * 1024;

/// A picture bigger than this isn't downloaded at all.
const MAX_DOWNLOAD: usize = 64 * 1024 * 1024;

/// Why a picture didn't arrive.
enum Fetch {
    Net(reqwest::Error),
    TooBig,
}

/// The disk cache's folder (under RustCord's cache folder).
const DISK_DIR: &str = "img-v2";

/// May this picture be kept on disk? Avatars, icons, emoji, banners and
/// Discord's own artwork, yes. Attachments (what people send, DMs included)
/// and pictures from links (embeds, through Discord's proxy) only ever stay
/// in memory: they'd otherwise sit on disk unencrypted, readable by anything
/// that runs as you.
fn keep_on_disk(url: &str) -> bool {
    let private = ["/attachments/", "/ephemeral-attachments/", "/external/"];
    !(private.iter().any(|p| url.contains(p)) || url.contains("://images-ext-"))
}

/// The downloaded-files cache, for the two functions below.
static FILES: std::sync::OnceLock<Arc<Mutex<HashMap<String, Entry>>>> = std::sync::OnceLock::new();

/// Drop downloaded files nobody has asked for lately. The cache used to be
/// swept only when another image was requested, so an idle window kept
/// tens of MB of already-decoded files for as long as it stayed idle.
pub fn drop_stale_files() {
    let Some(cache) = FILES.get() else { return };
    if let Ok(mut c) = cache.lock() {
        c.retain(|_, e| match e {
            Entry::Ready(_, _, used) => used.elapsed() < BYTES_TTL,
            _ => true,
        });
    }
}

/// An address as it may be logged: without its query string or fragment
/// (attachment links are signed, and the signature is in the query).
pub fn log_url(url: &str) -> &str {
    url.split(['?', '#']).next().unwrap_or(url)
}

/// Forget every picture kept on disk (logging out: they belong to the account
/// that left). The folder itself stays, the running loader writes into it.
pub fn clear_disk() {
    let Some(dir) = directories::ProjectDirs::from("dev", "RustCord", "RustCord").map(|d| d.cache_dir().join(DISK_DIR)) else { return };
    let Ok(rd) = std::fs::read_dir(dir) else { return };
    for e in rd.flatten() {
        let _ = std::fs::remove_file(e.path());
    }
}

/// Drop one downloaded file: it has been decoded and its bytes aren't
/// needed again unless it is decoded anew (then it comes back from disk).
pub fn forget_file(url: &str) {
    let Some(cache) = FILES.get() else { return };
    if let Ok(mut c) = cache.lock() {
        if matches!(c.get(without_fragment(url)), Some(Entry::Ready(..))) {
            c.remove(without_fragment(url));
        }
    }
}

/// File name for a URL (FNV-1a hash + length; collisions are harmless
/// enough here: at worst a wrong picture until the cache is cleared).
fn disk_name(url: &str) -> String {
    let mut h: u64 = 0xcbf29ce484222325;
    for b in url.bytes() {
        h ^= b as u64;
        h = h.wrapping_mul(0x100000001b3);
    }
    format!("{h:016x}{:04x}", url.len() & 0xffff)
}

/// Keep the disk cache under budget (runs once, in the background).
fn prune_disk(dir: &std::path::Path) {
    let Ok(rd) = std::fs::read_dir(dir) else { return };
    let mut files: Vec<(std::time::SystemTime, u64, std::path::PathBuf)> = rd
        .flatten()
        .filter_map(|e| {
            let m = e.metadata().ok()?;
            Some((m.modified().or_else(|_| m.accessed()).ok()?, m.len(), e.path()))
        })
        .collect();
    let mut total: u64 = files.iter().map(|f| f.1).sum();
    if total <= DISK_BUDGET {
        return;
    }
    files.sort_by_key(|f| f.0);
    for (_, len, path) in files {
        if total <= DISK_BUDGET * 3 / 4 {
            break;
        }
        if std::fs::remove_file(&path).is_ok() {
            total -= len;
        }
    }
}

impl NetImages {
    pub fn install(ctx: &egui::Context) {
        // Cached images are read from disk on tokio's blocking pool, which by
        // default grows to 512 threads: a start-up with a few hundred cached
        // avatars, icons and emoji spun up ~100 of them, and the allocator
        // keeps pages for every thread that ever allocated (measured
        // 2026-11-17: 25 threads / ~380 MB private in one run, 100 threads /
        // ~540 MB in the next). A few readers are as fast: the disk is the limit.
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(2)
            .max_blocking_threads(3)
            .thread_keep_alive(Duration::from_secs(2))
            .on_thread_park(crate::diagnostics::release_this_threads_memory)
            .thread_name("rustcord-images")
            .enable_all()
            .build()
            .expect("image runtime");
        let client = reqwest::Client::builder()
            .user_agent(concat!("RustCord/", env!("CARGO_PKG_VERSION")))
            .timeout(Duration::from_secs(30))
            .pool_max_idle_per_host(MAX_CONCURRENT)
            // Only https addresses are fetched; a redirect can't lead to http.
            .redirect(discord::http::https_only_redirects())
            .build()
            .expect("image client");
        let root = directories::ProjectDirs::from("dev", "RustCord", "RustCord").map(|d| d.cache_dir().to_path_buf());
        let disk = root.as_ref().map(|r| r.join(DISK_DIR)).filter(|d| std::fs::create_dir_all(d).is_ok());
        if let Some(d) = disk.clone() {
            let old = root.map(|r| r.join("img-v1"));
            let _ = std::thread::Builder::new().name("rustcord-cache-prune".into()).spawn(move || {
                // The cache before 0.4.7 also held attachments (DM pictures):
                // it goes, once.
                if let Some(old) = old.filter(|o| o.is_dir()) {
                    crate::cache::remove_tree(&old);
                }
                prune_disk(&d)
            });
        }
        let cache: Arc<Mutex<HashMap<String, Entry>>> = Default::default();
        let _ = FILES.set(cache.clone());
        ctx.add_bytes_loader(Arc::new(Self {
            client,
            runtime,
            permits: Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT)),
            cache,
            disk: disk.map(Arc::from),
            last_sweep: Mutex::new(Instant::now()),
        }));
    }
}

impl BytesLoader for NetImages {
    fn id(&self) -> &str {
        egui::generate_loader_id!(NetImages)
    }

    fn load(&self, ctx: &egui::Context, uri: &str) -> BytesLoadResult {
        // (Never plain http: anyone on the network could read or swap the picture.)
        if !uri.starts_with("https://") {
            return Err(LoadError::NotSupported);
        }
        let uri = without_fragment(uri);
        let mut cache = self.cache.lock().expect("image cache");
        self.sweep(&mut cache);
        match cache.get_mut(uri) {
            Some(Entry::Ready(bytes, mime, used)) => {
                *used = Instant::now();
                return Ok(BytesPoll::Ready { size: None, bytes: Bytes::Shared(bytes.clone()), mime: mime.clone() });
            }
            Some(Entry::Pending) => return Ok(BytesPoll::Pending { size: None }),
            Some(Entry::Failed(e, at)) if at.elapsed() < RETRY_AFTER => return Err(LoadError::Loading(e.clone())),
            _ => {}
        }
        cache.insert(uri.to_string(), Entry::Pending);
        drop(cache);

        let (client, permits, cache, ctx, url) =
            (self.client.clone(), self.permits.clone(), self.cache.clone(), ctx.clone(), uri.to_string());
        let disk = self.disk.clone();
        self.runtime.spawn(async move {
            // On disk from an earlier run? Then no download at all.
            let file = disk.as_ref().filter(|_| keep_on_disk(&url)).map(|d| d.join(disk_name(&url)));
            if let Some(f) = file.clone() {
                let read = tokio::task::spawn_blocking(move || std::fs::read(f).ok()).await.ok().flatten();
                if let Some(bytes) = read.filter(|b| !b.is_empty()) {
                    if let Ok(mut c) = cache.lock() {
                        if matches!(c.get(&url), Some(Entry::Pending)) {
                            c.insert(url, Entry::Ready(Arc::from(bytes), None, Instant::now()));
                        }
                    }
                    ctx.request_repaint();
                    return;
                }
            }
            let _permit = permits.acquire_owned().await;
            let sent = std::time::Instant::now();
            let result = async {
                let mut resp = client.get(&url).send().await.map_err(Fetch::Net)?.error_for_status().map_err(Fetch::Net)?;
                let mime = resp
                    .headers()
                    .get(reqwest::header::CONTENT_TYPE)
                    .and_then(|v| v.to_str().ok())
                    .map(String::from);
                if resp.content_length().is_some_and(|n| n > MAX_DOWNLOAD as u64) {
                    return Err(Fetch::TooBig);
                }
                // Read in pieces, so a file that is bigger than it said stops at the cap.
                let mut body = Vec::new();
                while let Some(chunk) = resp.chunk().await.map_err(Fetch::Net)? {
                    body.extend_from_slice(&chunk);
                    if body.len() > MAX_DOWNLOAD {
                        return Err(Fetch::TooBig);
                    }
                }
                Ok((body, mime))
            }
            .await;
            match &result {
                Ok((bytes, _)) => discord::reqlog::record_media("GET", &url, sent, Some(200), bytes.len() as u64, None),
                Err(Fetch::TooBig) => discord::reqlog::record_media("GET", &url, sent, Some(200), 0, Some("too big; not loaded".into())),
                // (Not the error's text: it carries the signed link.)
                Err(Fetch::Net(e)) => {
                    let why = if e.status().is_some() { None } else if e.is_timeout() { Some("timed out") } else { Some("couldn't connect") };
                    discord::reqlog::record_media("GET", &url, sent, e.status().map(|s| s.as_u16()), 0, why.map(String::from));
                }
            }
            let entry = match result {
                Ok((bytes, mime)) => {
                    if bytes.len() >= 4 * 1024 * 1024 {
                        log::info!("images: a {:.1} MB file ({})", bytes.len() as f64 / 1048576.0, log_url(&url));
                    }
                    let bytes: Arc<[u8]> = Arc::from(bytes);
                    if let (Some(f), true) = (file, bytes.len() <= DISK_MAX_FILE) {
                        let b = bytes.clone();
                        tokio::task::spawn_blocking(move || {
                            // Write then rename, so a half-written file is never read.
                            let tmp = f.with_extension("part");
                            if std::fs::write(&tmp, &b).is_ok() {
                                let _ = std::fs::rename(&tmp, &f);
                            }
                        });
                    }
                    Entry::Ready(bytes, mime, Instant::now())
                }
                Err(Fetch::TooBig) => {
                    log::info!("images: over {} MB, not loaded ({})", MAX_DOWNLOAD / (1024 * 1024), log_url(&url));
                    Entry::Failed("the file is too big to show".into(), Instant::now())
                }
                Err(Fetch::Net(e)) => {
                    // (Without the query string: attachment links are signed.)
                    let e = e.without_url();
                    log::debug!("image failed: {}: {e}", log_url(&url));
                    if e.status() == Some(reqwest::StatusCode::NOT_FOUND) {
                        crate::emoji::mark_missing(&url);
                    }
                    Entry::Failed(e.to_string(), Instant::now())
                }
            };
            if let Ok(mut c) = cache.lock() {
                // Only store if nobody called forget() in the meantime.
                if matches!(c.get(&url), Some(Entry::Pending)) {
                    c.insert(url, entry);
                }
                // Keep within budget: drop the least recently used files.
                let size = |e: &Entry| if let Entry::Ready(b, _, _) = e { b.len() } else { 0 };
                let mut total: usize = c.values().map(size).sum();
                if total > BYTES_BUDGET {
                    let mut by_age: Vec<(Instant, String, usize)> = c
                        .iter()
                        .filter_map(|(k, e)| if let Entry::Ready(b, _, t) = e { Some((*t, k.clone(), b.len())) } else { None })
                        .collect();
                    by_age.sort_by_key(|(t, _, _)| *t);
                    for (_, k, n) in by_age {
                        if total <= BYTES_BUDGET * 3 / 4 {
                            break;
                        }
                        c.remove(&k);
                        total -= n;
                    }
                }
            }
            ctx.request_repaint();
        });
        Ok(BytesPoll::Pending { size: None })
    }

    fn forget(&self, uri: &str) {
        if let Ok(mut c) = self.cache.lock() {
            c.remove(without_fragment(uri));
        }
    }

    fn forget_all(&self) {
        if let Ok(mut c) = self.cache.lock() {
            c.clear();
        }
    }

    fn byte_size(&self) -> usize {
        self.cache
            .lock()
            .map(|c| c.values().map(|e| if let Entry::Ready(b, _, _) = e { b.len() } else { 0 }).sum())
            .unwrap_or(0)
    }
}