//! Champion portraits, fetched from Data Dragon and cached on disk. //! //! Rune decodes images but has no HTTP client on native, so the bytes come down here first. A //! portrait is drawn as soon as it is on disk, and the app redraws when a download lands. use std::collections::{HashMap, HashSet}; use std::io::Read; use std::path::PathBuf; use std::sync::mpsc::{Receiver, Sender, channel}; use std::sync::{Arc, Mutex}; use std::time::Duration; /// Riot's public asset CDN. const HOST: &str = "https://ddragon.leagueoflegends.com"; /// The champion list: Data Dragon ids ("Kaisa") by display name ("Kai'Sa"), for one patch. #[derive(Clone, serde::Deserialize, serde::Serialize)] struct Catalog { version: String, ids: HashMap, } /// Where the portraits and the champion list are cached. fn cache_dir() -> PathBuf { directories::ProjectDirs::from("com", "leaguerecorder", "leaguerecorder") .map(|dirs| dirs.cache_dir().join("portraits")) .unwrap_or_else(|| PathBuf::from("./portraits")) } /// Champion portraits drawn from the cache, with the missing ones fetched in the background. pub struct Portraits { dir: PathBuf, images: rune::ImageCache, catalog: Arc>>, asked: Mutex>, tx: Sender, } impl Portraits { pub fn new(waker: rune::Waker) -> Self { let dir = cache_dir(); let _ = std::fs::create_dir_all(&dir); let catalog = Arc::new(Mutex::new(read_catalog(&dir))); let (tx, rx) = channel(); let worker = Worker { dir: dir.clone(), catalog: catalog.clone(), wake: waker.clone(), }; let spawned = std::thread::Builder::new() .name("portraits".into()) .spawn(move || worker.run(rx)); if spawned.is_err() { eprintln!("portrait downloads are unavailable"); } Self { dir, images: rune::ImageCache::new(waker), catalog, asked: Mutex::new(HashSet::new()), tx, } } /// The portrait for a champion's display name at `size` points, once it is on disk. A /// missing one is queued and the app redraws when it arrives. pub fn image(&self, champion: &str, size: f32, scale: f32) -> Option { let champion = champion.trim(); if champion.is_empty() { return None; } let path = { let catalog = self.catalog.lock().unwrap(); let Some(catalog) = catalog.as_ref() else { drop(catalog); self.ask(champion); return None; }; let id = catalog.ids.get(champion)?; self.dir.join(format!("{id}.png")) }; if !path.is_file() { self.ask(champion); return None; } Some(self.images.file(&path, size, scale)) } fn ask(&self, champion: &str) { if self.asked.lock().unwrap().insert(champion.to_string()) { let _ = self.tx.send(champion.to_string()); } } } /// The cache's background thread: the champion list first, then one portrait at a time. struct Worker { dir: PathBuf, catalog: Arc>>, wake: rune::Waker, } impl Worker { fn run(self, rx: Receiver) { if self.catalog.lock().unwrap().is_none() { match self.ensure_catalog() { Some(catalog) => { *self.catalog.lock().unwrap() = Some(catalog); (self.wake)(); } None => eprintln!("champion list unavailable; drawing initials instead"), } } while let Ok(name) = rx.recv() { self.download(&name); } } /// The cached champion list, or a fresh one written next to the portraits. fn ensure_catalog(&self) -> Option { if let Some(catalog) = read_catalog(&self.dir) { return Some(catalog); } let catalog = fetch_catalog()?; let text = serde_json::to_vec(&catalog).ok()?; let path = self.dir.join("catalog.json"); let _ = std::fs::write(path.with_extension("part"), text); let _ = std::fs::rename(path.with_extension("part"), &path); Some(catalog) } fn download(&self, champion: &str) { let (id, version) = { let catalog = self.catalog.lock().unwrap(); let Some(catalog) = catalog.as_ref() else { return; }; let Some(id) = catalog.ids.get(champion).cloned() else { return; }; (id, catalog.version.clone()) }; let path = self.dir.join(format!("{id}.png")); if path.is_file() { return; } let url = format!("{HOST}/cdn/{version}/img/champion/{id}.png"); let Some(bytes) = get(&url) else { return; }; if bytes.is_empty() { return; } let part = path.with_extension("part"); if std::fs::write(&part, bytes).is_ok() && std::fs::rename(&part, &path).is_ok() { (self.wake)(); } } } fn read_catalog(dir: &std::path::Path) -> Option { let bytes = std::fs::read(dir.join("catalog.json")).ok()?; serde_json::from_slice(&bytes).ok() } /// The champion list of the latest patch: display names to Data Dragon ids. fn fetch_catalog() -> Option { let versions: Vec = serde_json::from_slice(&get(&format!("{HOST}/api/versions.json"))?).ok()?; let version = versions.into_iter().next()?; let url = format!("{HOST}/cdn/{version}/data/en_US/champion.json"); let data: serde_json::Value = serde_json::from_slice(&get(&url)?).ok()?; let mut ids = HashMap::new(); for (id, champion) in data.get("data")?.as_object()? { if let Some(name) = champion.get("name").and_then(|name| name.as_str()) { ids.insert(name.to_string(), id.clone()); } } (!ids.is_empty()).then_some(Catalog { version, ids }) } fn get(url: &str) -> Option> { let mut response = ureq::get(url) .config() .timeout_global(Some(Duration::from_secs(20))) .build() .call() .ok()?; let mut bytes = Vec::new(); response .body_mut() .as_reader() .read_to_end(&mut bytes) .ok()?; Some(bytes) }