Add core: Match import, statistics and game client following
Core half of tickets #4 to #12, behind one public interface tested with fake sources and a real SQLite database: - import of Arena Match history from the Riot API, idempotent and resumable, with a sync mark written only when a sync completes - Season table, champion catalog, Challenge summary, champion rows, chart series, Season and Format scopes - game client port and adapter: signed-in Account, end of an Arena game fetched by its id, Official Progress cross-check - update problems reported for banners while stored data stays readable The app crate is adapted in the next commit. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
1c5cbea9b9
commit
c44cf52a6a
21 files changed
+6472
-13
No files matched your search
@@ -0,0 +1,246 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
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<Champion>,
|
||||
}
|
||||
|
||||
/// Port: champion reference data (Riot's public game data). Real adapter: `DataDragon`.
|
||||
pub trait ChampionSource: Send + Sync {
|
||||
fn latest_version(&self) -> Result<String, SourceError>;
|
||||
fn catalog(&self, version: &str) -> Result<ChampionCatalog, SourceError>;
|
||||
/// PNG bytes.
|
||||
fn portrait(&self, version: &str, key: &str) -> Result<Vec<u8>, 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<String, SourceError> {
|
||||
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<ChampionCatalog, SourceError> {
|
||||
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<Vec<u8>, SourceError> {
|
||||
let url = format!(
|
||||
"{HOST}/cdn/{}/img/champion/{}.png",
|
||||
encode(version),
|
||||
encode(key)
|
||||
);
|
||||
get(&self.agent, &url, None, |b| b.read_to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
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}")))?;
|
||||
versions
|
||||
.into_iter()
|
||||
.next()
|
||||
.ok_or_else(|| SourceError::Other("Aucune version de jeu publiée.".into()))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CatalogFile {
|
||||
data: BTreeMap<String, CatalogEntry>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CatalogEntry {
|
||||
id: String,
|
||||
/// The numeric champion id, as a string.
|
||||
key: String,
|
||||
name: String,
|
||||
}
|
||||
|
||||
fn decode_catalog(version: &str, body: &str) -> Result<ChampionCatalog, SourceError> {
|
||||
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::<Result<Vec<_>, 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<dyn ChampionSource>,
|
||||
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));
|
||||
// The key becomes a file name: only trust plain names.
|
||||
if path.exists() || !champion.key.chars().all(|c| c.is_ascii_alphanumeric()) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn cached_champions(&self) -> Result<Vec<Champion>, 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::<Result<_, _>>()?;
|
||||
Ok(champions)
|
||||
}
|
||||
|
||||
fn cached_version(&self) -> Result<Option<String>, 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::<Result<Vec<_>, _>>()?;
|
||||
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");
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user