Download champion splashes and cache their banner focus (#83)
CI / core (pull_request) Successful in 1m31s

This commit is contained in:
nessar committed 2026-11-21 14:16:58 +01:00
1 parent 3de8fd527c
commit e440d155fc
11 files changed
+488 -99

No files matched your search

+61 -26
View File
@@ -1,4 +1,5 @@
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use image::codecs::jpeg::JpegEncoder;
@@ -35,6 +36,8 @@ pub trait ChampionSource: Send + Sync {
fn portrait(&self, version: &str, key: &str) -> Result<Vec<u8>, SourceError>;
/// JPEG bytes of the tall loading-screen art (308 x 560 px), used on the cards.
fn card_portrait(&self, key: &str) -> Result<Vec<u8>, SourceError>;
/// Original landscape splash JPEG (1215 x 717 px).
fn splash(&self, key: &str) -> Result<Vec<u8>, SourceError>;
}
const HOST: &str = "https://ddragon.leagueoflegends.com";
@@ -84,6 +87,11 @@ impl ChampionSource for DataDragon {
let url = format!("{HOST}/cdn/img/champion/loading/{}_0.jpg", encode(key));
get(&self.agent, &url, None, |b| b.read_to_vec())
}
fn splash(&self, key: &str) -> Result<Vec<u8>, SourceError> {
let url = format!("{HOST}/cdn/img/champion/splash/{}_0.jpg", encode(key));
get(&self.agent, &url, None, |b| b.read_to_vec())
}
}
/// Width of a stored card portrait: the loading art's own width, about the largest card
@@ -100,6 +108,11 @@ const CARD_FOCUS_X: f64 = 0.5;
const CARD_FOCUS_Y: f64 = 0.24;
const CARD_JPEG_QUALITY: u8 = 85;
/// Data Dragon keys become local file names.
pub(crate) fn valid_art_key(key: &str) -> bool {
!key.is_empty() && key.bytes().all(|c| c.is_ascii_alphanumeric())
}
/// The folder of the card portraits, in the portraits folder.
pub(crate) fn cards_dir(portraits_dir: &Path) -> PathBuf {
portraits_dir.join("cards")
@@ -132,10 +145,7 @@ fn card_crop(width: u32, height: u32) -> (u32, u32, u32, u32) {
/// Crops the loading art to the card's shape, shrinks it to the stored size when larger
/// (never upscales) and encodes it as JPEG.
fn process_card_portrait(jpeg: &[u8]) -> Result<Vec<u8>, String> {
let art = image::load_from_memory_with_format(jpeg, ImageFormat::Jpeg)
.map_err(|e| format!("Portrait illisible : {e}"))?
.into_rgb8();
fn process_card_portrait(art: RgbImage) -> Result<Vec<u8>, String> {
let (x, y, w, h) = card_crop(art.width(), art.height());
let mut card: RgbImage = imageops::crop_imm(&art, x, y, w, h).to_image();
drop(art);
@@ -159,6 +169,25 @@ fn process_card_portrait(jpeg: &[u8]) -> Result<Vec<u8>, String> {
Ok(out)
}
/// The names of the files in `dir`; none when it is missing or unreadable.
pub(crate) fn file_names(dir: &Path) -> impl Iterator<Item = OsString> {
std::fs::read_dir(dir)
.into_iter()
.flatten()
.filter_map(Result::ok)
.filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_file()))
.map(|entry| entry.file_name())
}
pub(crate) fn save_image(path: &Path, bytes: &[u8]) -> bool {
let partial = path.with_extension("part");
let saved = std::fs::write(&partial, bytes).is_ok() && std::fs::rename(&partial, path).is_ok();
if !saved {
let _ = std::fs::remove_file(partial);
}
saved
}
fn decode_latest_version(body: &str) -> Result<String, SourceError> {
let versions: Vec<String> = serde_json::from_str(body)
.map_err(|e| SourceError::Other(format!("Versions illisibles : {e}")))?;
@@ -233,16 +262,11 @@ impl Tracker {
.map_err(|e| Error::Storage(format!("{} : {e}", portraits_dir.display())))?;
for champion in self.cached_champions()? {
let path = portraits_dir.join(format!("{}.png", champion.key));
// The key becomes a file name: only trust plain names.
if path.exists() || !champion.key.chars().all(|c| c.is_ascii_alphanumeric()) {
if !valid_art_key(&champion.key) || path.exists() {
continue;
}
if let Ok(png) = source.portrait(&version, &champion.key) {
// Written under another name first so a cut download is never taken for a portrait.
let partial = path.with_extension("part");
if std::fs::write(&partial, png).is_ok() {
let _ = std::fs::rename(&partial, &path);
}
save_image(&path, &png);
}
}
Ok(())
@@ -253,45 +277,50 @@ impl Tracker {
/// download of one champion (not found, an unreadable image) is skipped and retried by the
/// next pass; a network error stops the pass, as every other request would fail as well.
/// `on_attempt` is called after each download attempt, with whether a portrait was saved.
/// Meant to run after `refresh_champions`.
pub fn refresh_card_portraits(&self, on_attempt: &mut dyn FnMut(bool)) -> Result<(), Error> {
self.download_cards(on_attempt, |_, _| {}).map(|_| ())
}
/// Shares the uncropped loading art with the splash pass. False means the network went away.
pub(crate) fn download_cards(
&self,
on_attempt: &mut dyn FnMut(bool),
mut on_loading: impl FnMut(&str, &image::DynamicImage),
) -> Result<bool, Error> {
let Some((source, portraits_dir)) = &self.champions else {
return Ok(());
return Ok(true);
};
let cards_dir = cards_dir(portraits_dir);
std::fs::create_dir_all(&cards_dir)
.map_err(|e| Error::Storage(format!("{} : {e}", cards_dir.display())))?;
for champion in self.cached_champions()? {
let path = card_portrait_path(portraits_dir, &champion.key);
// The key becomes a file name: only trust plain names.
if path.exists() || !champion.key.chars().all(|c| c.is_ascii_alphanumeric()) {
if !valid_art_key(&champion.key) || path.exists() {
continue;
}
let art = match source.card_portrait(&champion.key) {
Ok(art) => art,
Err(SourceError::Network(_)) => {
on_attempt(false);
break;
return Ok(false);
}
Err(_) => {
on_attempt(false);
continue;
}
};
let Ok(card) = process_card_portrait(&art) else {
let Ok(art) = image::load_from_memory_with_format(&art, ImageFormat::Jpeg) else {
on_attempt(false);
continue;
};
// Written under another name first so a cut write is never taken for a portrait.
let partial = path.with_extension("part");
let saved =
std::fs::write(&partial, card).is_ok() && std::fs::rename(&partial, &path).is_ok();
if !saved {
let _ = std::fs::remove_file(&partial);
}
on_attempt(saved);
on_loading(&champion.key, &art);
let Ok(card) = process_card_portrait(art.into_rgb8()) else {
on_attempt(false);
continue;
};
on_attempt(save_image(&path, &card));
}
Ok(())
Ok(true)
}
pub(crate) fn cached_champions(&self) -> Result<Vec<Champion>, Error> {
@@ -386,6 +415,12 @@ mod tests {
out
}
fn process_card_portrait(jpeg: &[u8]) -> Result<Vec<u8>, String> {
let art = image::load_from_memory_with_format(jpeg, ImageFormat::Jpeg)
.map_err(|e| e.to_string())?;
super::process_card_portrait(art.into_rgb8())
}
fn decoded(jpeg: &[u8]) -> RgbImage {
image::load_from_memory_with_format(jpeg, ImageFormat::Jpeg)
.unwrap()