use std::collections::BTreeMap; use std::ffi::OsString; use std::path::{Path, PathBuf}; use image::codecs::jpeg::JpegEncoder; use image::imageops::{self, FilterType}; use image::{ExtendedColorType, ImageFormat, RgbImage}; use rusqlite::params; use serde::Deserialize; use ureq::Agent; use crate::error::{Error, SourceError}; use crate::riot::{agent, encode, get}; use crate::tracker::Tracker; #[derive(Clone, Debug, PartialEq, Eq)] pub struct Champion { pub id: u32, /// Data Dragon id, e.g. "MasterYi"; also the portrait's file name. pub key: String, /// French display name, e.g. "Maître Yi". pub name: String, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct ChampionCatalog { pub version: String, pub champions: Vec, } /// Port: champion reference data (Riot's public game data). Real adapter: `DataDragon`. pub trait ChampionSource: Send + Sync { fn latest_version(&self) -> Result; fn catalog(&self, version: &str) -> Result; /// PNG bytes. fn portrait(&self, version: &str, key: &str) -> Result, SourceError>; /// JPEG bytes of the tall loading-screen art (308 x 560 px), used on the cards. fn card_portrait(&self, key: &str) -> Result, SourceError>; /// Original landscape splash JPEG (1215 x 717 px). fn splash(&self, key: &str) -> Result, SourceError>; } const HOST: &str = "https://ddragon.leagueoflegends.com"; /// Data Dragon, Riot's public static game data (no API key, no rate limit). pub struct DataDragon { agent: Agent, } impl DataDragon { pub fn new() -> DataDragon { DataDragon { agent: agent() } } } impl Default for DataDragon { fn default() -> Self { DataDragon::new() } } impl ChampionSource for DataDragon { fn latest_version(&self) -> Result { let url = format!("{HOST}/api/versions.json"); decode_latest_version(&get(&self.agent, &url, None, |b| b.read_to_string())?) } fn catalog(&self, version: &str) -> Result { let url = format!("{HOST}/cdn/{}/data/fr_FR/champion.json", encode(version)); decode_catalog( version, &get(&self.agent, &url, None, |b| b.read_to_string())?, ) } fn portrait(&self, version: &str, key: &str) -> Result, SourceError> { let url = format!( "{HOST}/cdn/{}/img/champion/{}.png", encode(version), encode(key) ); get(&self.agent, &url, None, |b| b.read_to_vec()) } fn card_portrait(&self, key: &str) -> Result, SourceError> { // The loading art's path carries no game version. 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, 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 /// at 150 % display scale. Together with `CARD_PORTRAIT_HEIGHT` it keeps the card's /// aspect ratio (`CARD_ASPECT`), so the portraits stay at the cards' display size. const CARD_PORTRAIT_WIDTH: u32 = 308; /// Height of a stored card portrait: `CARD_PORTRAIT_WIDTH / CARD_ASPECT`, rounded. const CARD_PORTRAIT_HEIGHT: u32 = 453; /// A card's width over its height (the mockup's `.card { aspect-ratio: .68 }`): the ratio the /// stored card portraits are cropped to, and the one the app draws its cards at. pub const CARD_ASPECT: f64 = 0.68; /// Where the crop window sits in the overflow (the mockup's `object-position: 50% 24%`). 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") } /// Where a champion's card portrait is kept. pub(crate) fn card_portrait_path(portraits_dir: &Path, key: &str) -> PathBuf { cards_dir(portraits_dir).join(format!("{key}.jpg")) } /// The crop window (x, y, width, height) that `object-fit: cover` with the card's /// `object-position` shows of a `width` x `height` image. fn card_crop(width: u32, height: u32) -> (u32, u32, u32, u32) { let (w, h) = (f64::from(width), f64::from(height)); let (crop_w, crop_h) = if w / h < CARD_ASPECT { // Taller than the card: keep the full width. (width, ((w / CARD_ASPECT).round() as u32).clamp(1, height)) } else { (((h * CARD_ASPECT).round() as u32).clamp(1, width), height) }; let x = (CARD_FOCUS_X * f64::from(width - crop_w)).round() as u32; let y = (CARD_FOCUS_Y * f64::from(height - crop_h)).round() as u32; ( x.min(width - crop_w), y.min(height - crop_h), crop_w, crop_h, ) } /// 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(art: RgbImage) -> Result, 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); if w > CARD_PORTRAIT_WIDTH { card = imageops::resize( &card, CARD_PORTRAIT_WIDTH, CARD_PORTRAIT_HEIGHT, FilterType::Lanczos3, ); } let mut out = Vec::new(); JpegEncoder::new_with_quality(&mut out, CARD_JPEG_QUALITY) .encode( card.as_raw(), card.width(), card.height(), ExtendedColorType::Rgb8, ) .map_err(|e| format!("Portrait non encodable : {e}"))?; 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 { 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 { let versions: Vec = serde_json::from_str(body) .map_err(|e| SourceError::Other(format!("Versions illisibles : {e}")))?; versions .into_iter() .next() .ok_or_else(|| SourceError::Other("Aucune version de jeu publiée.".into())) } #[derive(Deserialize)] struct CatalogFile { data: BTreeMap, } #[derive(Deserialize)] struct CatalogEntry { id: String, /// The numeric champion id, as a string. key: String, name: String, } pub(crate) fn decode_catalog(version: &str, body: &str) -> Result { let file: CatalogFile = serde_json::from_str(body) .map_err(|e| SourceError::Other(format!("Champions illisibles : {e}")))?; let mut champions = file .data .into_values() .map(|entry| { let id = entry.key.parse().map_err(|_| { SourceError::Other(format!("Identifiant de champion invalide : {}", entry.key)) })?; Ok(Champion { id, key: entry.id, name: entry.name, }) }) .collect::, SourceError>>()?; champions.sort_by_key(|c| c.id); Ok(ChampionCatalog { version: version.into(), champions, }) } impl Tracker { /// Champion reference data comes from `source`; portraits are kept in `portraits_dir`. pub fn with_champions( mut self, source: Box, portraits_dir: PathBuf, ) -> Tracker { self.champions = Some((source, portraits_dir)); self } /// Refreshes the cached champion catalog when the game version changed, then downloads /// the portraits missing from the portraits dir. A failed portrait is skipped; a failed /// version or catalog call is returned and leaves the cached catalog untouched. pub fn refresh_champions(&self) -> Result<(), Error> { let Some((source, portraits_dir)) = &self.champions else { return Ok(()); }; let version = source.latest_version()?; if self.cached_version()?.as_deref() != Some(version.as_str()) { let catalog = source.catalog(&version)?; self.store_catalog(&version, &catalog.champions)?; } std::fs::create_dir_all(portraits_dir) .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)); if !valid_art_key(&champion.key) || path.exists() { continue; } if let Ok(png) = source.portrait(&version, &champion.key) { save_image(&path, &png); } } Ok(()) } /// Downloads the tall card portraits missing from the portraits dir's `cards` folder, /// cropped and shrunk to the card's size (see `process_card_portrait`). A failed /// 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. pub fn refresh_card_portraits(&self, on_attempt: &mut dyn FnMut(bool)) -> Result<(), Error> { self.download_cards(on_attempt, |_, _| {}).map(|_| ()) } /// Shares decoded loading art or a confirmed 404 with the splash pass. False stops both passes offline. pub(crate) fn download_cards( &self, on_attempt: &mut dyn FnMut(bool), mut on_loading: impl FnMut(&str, Option<&image::DynamicImage>), ) -> Result { let Some((source, portraits_dir)) = &self.champions else { 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); 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); return Ok(false); } Err(error) => { if error == SourceError::NotFound { on_loading(&champion.key, None); } on_attempt(false); continue; } }; let Ok(art) = image::load_from_memory_with_format(&art, ImageFormat::Jpeg) else { on_attempt(false); continue; }; on_loading(&champion.key, Some(&art)); let Ok(card) = process_card_portrait(art.into_rgb8()) else { on_attempt(false); continue; }; on_attempt(save_image(&path, &card)); } Ok(true) } pub(crate) fn cached_champions(&self) -> Result, Error> { let db = self.db(); let mut stmt = db.prepare("SELECT id, key, name FROM champions")?; let champions = stmt .query_map([], |row| { Ok(Champion { id: row.get(0)?, key: row.get(1)?, name: row.get(2)?, }) })? .collect::>()?; Ok(champions) } fn cached_version(&self) -> Result, Error> { let db = self.db(); let mut stmt = db.prepare("SELECT value FROM meta WHERE name = 'champion_version'")?; let versions = stmt .query_map([], |row| row.get(0))? .collect::, _>>()?; Ok(versions.into_iter().next()) } fn store_catalog(&self, version: &str, champions: &[Champion]) -> Result<(), Error> { let db = self.db(); let tx = db.unchecked_transaction()?; tx.execute("DELETE FROM champions", [])?; for c in champions { tx.execute( "INSERT OR REPLACE INTO champions (id, key, name) VALUES (?1, ?2, ?3)", params![c.id, c.key, c.name], )?; } tx.execute( "INSERT OR REPLACE INTO meta (name, value) VALUES ('champion_version', ?1)", [version], )?; tx.commit()?; Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn decodes_the_latest_game_version() { let body = include_str!("../tests/fixtures/ddragon/versions.json"); assert_eq!(decode_latest_version(body).unwrap(), "16.22.1"); assert!(decode_latest_version("[]").is_err()); } #[test] fn decodes_the_champion_catalog() { let body = include_str!("../tests/fixtures/ddragon/champion.json"); let catalog = decode_catalog("16.22.1", body).unwrap(); assert_eq!(catalog.version, "16.22.1"); assert_eq!(catalog.champions.len(), 173); let champion = |id| catalog.champions.iter().find(|c| c.id == id).unwrap(); assert_eq!( champion(11), &Champion { id: 11, key: "MasterYi".into(), name: "Maître Yi".into() } ); assert_eq!(champion(62).key, "MonkeyKing"); assert_eq!(champion(62).name, "Wukong"); } /// A 308 x 560-like JPEG: red above `red_to`, green from `green_from`, blue between. fn banded_jpeg(width: u32, height: u32, red_to: u32, green_from: u32) -> Vec { let img = RgbImage::from_fn(width, height, |_, y| { if y < red_to { image::Rgb([255, 0, 0]) } else if y >= green_from { image::Rgb([0, 255, 0]) } else { image::Rgb([0, 0, 255]) } }); let mut out = Vec::new(); JpegEncoder::new_with_quality(&mut out, 95) .encode(img.as_raw(), width, height, ExtendedColorType::Rgb8) .unwrap(); out } fn process_card_portrait(jpeg: &[u8]) -> Result, 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() .into_rgb8() } #[test] fn the_crop_keeps_the_full_width_and_the_mockups_focus() { assert_eq!(CARD_PORTRAIT_HEIGHT, (308.0 / CARD_ASPECT).round() as u32); // 24 % of the 107 px overflow. assert_eq!(card_crop(308, 560), (0, 26, 308, 453)); assert_eq!(card_crop(616, 1120), (0, 51, 616, 906)); // Wider than a card: the full height, centered. assert_eq!(card_crop(500, 400), (114, 0, 272, 400)); // Already the card's shape. assert_eq!(card_crop(68, 100), (0, 0, 68, 100)); } #[test] fn the_loading_art_is_cropped_to_the_card_at_the_focus() { // The window is rows 26..479: red above it, green below it. let card = process_card_portrait(&banded_jpeg(308, 560, 26, 479)).unwrap(); let card = decoded(&card); assert_eq!((card.width(), card.height()), (308, 453)); for y in [10, 226, 442] { let [r, g, b] = card.get_pixel(150, y).0; assert!(b > 200 && r < 60 && g < 60, "row {y}: {r} {g} {b}"); } } #[test] fn a_larger_art_is_shrunk_and_a_smaller_one_is_cropped_only() { let large = decoded(&process_card_portrait(&banded_jpeg(616, 1120, 51, 957)).unwrap()); assert_eq!((large.width(), large.height()), (308, 453)); let small = decoded(&process_card_portrait(&banded_jpeg(100, 200, 0, 200)).unwrap()); assert_eq!((small.width(), small.height()), (100, 147)); } #[test] fn an_undecodable_art_is_an_error() { assert!(process_card_portrait(b"pas une image").is_err()); assert!(process_card_portrait(&[]).is_err()); let mut cut = banded_jpeg(308, 560, 26, 479); cut.truncate(cut.len() / 2); let _ = process_card_portrait(&cut); // Must not panic; a cut file may still decode partly. } #[test] fn rejects_a_non_numeric_champion_key() { let body = r#"{"data":{"X":{"id":"X","key":"abc","name":"X"}}}"#; assert!(decode_catalog("1", body).is_err()); } }