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:
nessarandClaude Fable 5.2 committed 2026-11-16 19:06:52 +01:00
1 parent 1c5cbea9b9
commit c44cf52a6a
21 files changed
+6472 -13

No files matched your search

+246
View File
@@ -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());
}
}
+78
View File
@@ -0,0 +1,78 @@
use std::time::Duration;
/// Port: the local League client. Strictly read-only. Real adapter: `LeagueClient`.
pub trait GameClientSource: Send + Sync {
/// Riot ID (game name, tag line) of the Account signed in to the client.
fn signed_in(&self) -> Result<(String, String), ClientError>;
fn gameflow(&self) -> Result<Gameflow, ClientError>;
/// Value of the Champs Completed counter of the progression track with this exact name;
/// `None` when the client has no such track.
fn official_progress(&self, track_name: &str) -> Result<Option<u32>, ClientError>;
/// Blocks until the client reports a change or `timeout` elapses.
fn wait_for_change(&self, timeout: Duration);
}
#[derive(Debug, Clone, PartialEq)]
pub enum ClientError {
/// Not running, not reachable, or nobody signed in yet.
Absent,
Other(String),
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum GamePhase {
#[default]
Idle,
ChampSelect,
InGame,
Ended,
}
impl GamePhase {
/// From the client's gameflow phase name; unknown names are `Idle`.
pub fn from_client(phase: &str) -> GamePhase {
match phase {
"ChampSelect" => GamePhase::ChampSelect,
"GameStart" | "InProgress" | "Reconnect" => GamePhase::InGame,
"WaitingForStats" | "PreEndOfGame" | "EndOfGame" => GamePhase::Ended,
_ => GamePhase::Idle,
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Gameflow {
pub phase: GamePhase,
/// The current game's mode is Arena (CHERRY); false when there is no game.
pub arena: bool,
/// The client's id of the current game; `None` when there is no game.
pub game_id: Option<u64>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn client_phases_map_to_game_phases() {
for (name, phase) in [
("ChampSelect", GamePhase::ChampSelect),
("GameStart", GamePhase::InGame),
("InProgress", GamePhase::InGame),
("Reconnect", GamePhase::InGame),
("WaitingForStats", GamePhase::Ended),
("PreEndOfGame", GamePhase::Ended),
("EndOfGame", GamePhase::Ended),
("None", GamePhase::Idle),
("Lobby", GamePhase::Idle),
("Matchmaking", GamePhase::Idle),
("CheckedIntoTournament", GamePhase::Idle),
("ReadyCheck", GamePhase::Idle),
("FailedToLaunch", GamePhase::Idle),
("TerminatedInError", GamePhase::Idle),
("SomethingNew", GamePhase::Idle),
] {
assert_eq!(GamePhase::from_client(name), phase, "{name}");
}
}
}
+166
View File
@@ -0,0 +1,166 @@
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::error::Error;
/// User settings from a TOML file. Deliberately has no `Debug`: it holds the API key.
#[derive(Deserialize, Serialize)]
pub struct Config {
#[serde(default)]
pub riot_api_key: String,
#[serde(default)]
pub riot_id: String,
#[serde(default = "default_region")]
pub region: String,
}
fn default_region() -> String {
"europe".into()
}
impl Config {
pub fn load(path: &Path) -> Result<Config, Error> {
let text = std::fs::read_to_string(path)
.map_err(|e| Error::Config(format!("{} : {e}", path.display())))?;
// Only the message: toml's Display quotes the offending line, which may be the key.
toml::from_str(&text)
.map_err(|e| Error::Config(format!("{} : {}", path.display(), e.message())))
}
/// Like `load`, but a missing file gives an empty configuration.
pub fn load_or_default(path: &Path) -> Result<Config, Error> {
if path.exists() {
return Config::load(path);
}
Ok(Config {
riot_api_key: String::new(),
riot_id: String::new(),
region: default_region(),
})
}
/// Writes the file, creating its folder. It is the only place the key is ever stored.
pub fn save(&self, path: &Path) -> Result<(), Error> {
let io_error = |e: std::io::Error| Error::Config(format!("{} : {e}", path.display()));
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(io_error)?;
}
let text = toml::to_string(self)
.map_err(|e| Error::Config(format!("{} : {e}", path.display())))?;
// Written aside first so a crash cannot leave a half-written key file.
let partial = path.with_extension("part");
std::fs::write(&partial, text).map_err(io_error)?;
std::fs::rename(&partial, path).map_err(io_error)
}
}
/// Per-user data directory (`%APPDATA%\arena-tracker`); `None` when APPDATA is unset.
pub fn data_dir() -> Option<PathBuf> {
std::env::var_os("APPDATA").map(|dir| PathBuf::from(dir).join("arena-tracker"))
}
#[cfg(test)]
mod tests {
use super::*;
fn load(text: &str) -> Result<Config, Error> {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, text).unwrap();
Config::load(&path)
}
#[test]
fn region_defaults_to_europe() {
let config = load("riot_api_key = \"k\"\nriot_id = \"Joueur#EUW\"\n").unwrap();
assert_eq!(config.riot_id, "Joueur#EUW");
assert_eq!(config.region, "europe");
}
#[test]
fn region_can_be_set() {
let config =
load("riot_api_key = \"k\"\nriot_id = \"J#NA\"\nregion = \"americas\"\n").unwrap();
assert_eq!(config.region, "americas");
}
#[test]
fn a_partial_file_gets_empty_values_and_the_default_region() {
let config = load("riot_id = \"Joueur#EUW\"\n").unwrap();
assert_eq!(
(config.riot_api_key.as_str(), config.region.as_str()),
("", "europe")
);
let config = load("").unwrap();
assert_eq!(
(config.riot_api_key.as_str(), config.riot_id.as_str()),
("", "")
);
}
#[test]
fn a_missing_file_gives_an_empty_configuration() {
let dir = tempfile::tempdir().unwrap();
let config = Config::load_or_default(&dir.path().join("config.toml")).unwrap();
assert_eq!(
(
config.riot_api_key.as_str(),
config.riot_id.as_str(),
config.region.as_str()
),
("", "", "europe")
);
assert!(!dir.path().join("config.toml").exists());
}
#[test]
fn saved_settings_load_back() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("nested").join("config.toml");
let config = Config {
riot_api_key: "RGAPI-secret".into(),
riot_id: "Joueur#EUW".into(),
region: "americas".into(),
};
config.save(&path).unwrap();
let loaded = Config::load_or_default(&path).unwrap();
assert_eq!(loaded.riot_api_key, "RGAPI-secret");
assert_eq!(
(loaded.riot_id.as_str(), loaded.region.as_str()),
("Joueur#EUW", "americas")
);
}
#[test]
fn a_failed_save_does_not_echo_the_key() {
let dir = tempfile::tempdir().unwrap();
let blocker = dir.path().join("file");
std::fs::write(&blocker, "").unwrap();
let config = Config {
riot_api_key: "RGAPI-secret".into(),
riot_id: String::new(),
region: "europe".into(),
};
let Err(err) = config.save(&blocker.join("config.toml")) else {
panic!("saving under a file must fail");
};
assert!(!format!("{err} {err:?}").contains("RGAPI-secret"));
}
#[test]
fn invalid_files_are_config_errors_that_do_not_echo_the_key() {
let Err(Error::Config(msg)) = load("riot_api_key = RGAPI-secret\n") else {
panic!("expected a Config error");
};
assert!(!msg.contains("RGAPI-secret"));
assert!(matches!(
Config::load(Path::new("/nonexistent/config.toml")),
Err(Error::Config(_))
));
}
}
+97
View File
@@ -0,0 +1,97 @@
use std::fmt;
const MS_PER_DAY: i64 = 86_400_000;
/// Calendar date (UTC).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Date {
pub year: i32,
pub month: u8,
pub day: u8,
}
impl Date {
/// The UTC day containing that instant.
pub fn from_ms(epoch_ms: i64) -> Date {
let (year, month, day) = civil_from_days(epoch_ms.div_euclid(MS_PER_DAY));
Date { year, month, day }
}
/// 00:00 UTC of that day.
pub fn start_ms(&self) -> i64 {
days_from_civil(self.year, self.month, self.day) * MS_PER_DAY
}
}
impl fmt::Display for Date {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:02}/{:02}/{:04}", self.day, self.month, self.year)
}
}
// Howard Hinnant's civil-calendar algorithms (days since 1970-01-01).
fn days_from_civil(year: i32, month: u8, day: u8) -> i64 {
let (month, day) = (i64::from(month), i64::from(day));
let y = i64::from(year) - i64::from(month <= 2);
let era = y.div_euclid(400);
let year_of_era = y.rem_euclid(400);
let day_of_year = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
era * 146_097 + day_of_era - 719_468
}
fn civil_from_days(days: i64) -> (i32, u8, u8) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let day_of_era = z.rem_euclid(146_097);
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let mp = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = year_of_era + era * 400 + i64::from(month <= 2);
(year as i32, month as u8, day as u8)
}
#[cfg(test)]
mod tests {
use super::*;
const KNOWN: [(Date, i64); 7] = [
(date(1970, 1, 1), 0),
(date(1969, 12, 31), -86_400_000),
(date(1999, 12, 31), 946_598_400_000),
(date(2000, 2, 29), 951_782_400_000), // leap day of a year divisible by 400
(date(2024, 2, 29), 1_709_164_800_000),
(date(2025, 3, 5), 1_741_132_800_000),
(date(2100, 3, 1), 4_107_542_400_000), // 2100 is not a leap year
];
const fn date(year: i32, month: u8, day: u8) -> Date {
Date { year, month, day }
}
#[test]
fn dates_convert_to_and_from_epoch_milliseconds() {
for (date, ms) in KNOWN {
assert_eq!(date.start_ms(), ms, "{date}");
assert_eq!(Date::from_ms(ms), date);
assert_eq!(Date::from_ms(ms + MS_PER_DAY - 1), date);
}
assert_eq!(Date::from_ms(1_741_132_800_000 - 1), date(2025, 3, 4));
}
#[test]
fn every_day_round_trips() {
for days in -800_000..800_000i64 {
let (y, m, d) = civil_from_days(days);
assert_eq!(days_from_civil(y, m, d), days);
}
}
#[test]
fn dates_display_in_french_style() {
assert_eq!(date(2025, 3, 5).to_string(), "05/03/2025");
}
}
+18
View File
@@ -0,0 +1,18 @@
# Vous pouvez modifier ces Saisons ou en ajouter (une entrée [[season]] par Saison).
# Une Saison commence à 00:00 UTC à la date indiquée et dure jusqu'au début de la suivante.
# official_track (facultatif) : nom de la piste de progression du client du jeu pour cette Saison.
[[season]]
name = "Saison 2025"
start = 2025-03-05
official_track = "Cherry 2025 Champs Completed Track"
[[season]]
name = "Saison 1 2026"
start = 2026-01-08
official_track = "2026 Season 1 Champs Completed Track"
[[season]]
name = "Saison 2 2026"
start = 2026-04-29
official_track = "2026 Season 2 Champs Completed Track"
+71
View File
@@ -0,0 +1,71 @@
use std::fmt;
use std::time::Duration;
#[derive(Clone, Debug, PartialEq)]
pub enum SourceError {
/// No API key configured yet (as opposed to one Riot rejected).
MissingKey,
InvalidKey,
RateLimited {
retry_after: Duration,
},
Network(String),
NotFound,
Other(String),
}
impl fmt::Display for SourceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SourceError::MissingKey => write!(f, "Aucune clé API Riot n'est configurée."),
SourceError::InvalidKey => write!(f, "Clé API Riot refusée ou expirée."),
SourceError::RateLimited { retry_after } => write!(
f,
"Limite de requêtes Riot atteinte (nouvel essai dans {} s).",
retry_after.as_secs()
),
SourceError::Network(msg) => write!(f, "Erreur réseau : {msg}"),
SourceError::NotFound => write!(f, "Introuvable chez Riot."),
SourceError::Other(msg) => write!(f, "Erreur Riot : {msg}"),
}
}
}
impl std::error::Error for SourceError {}
#[derive(Debug)]
pub enum Error {
Source(SourceError),
Storage(String),
InvalidRiotId(String),
Config(String),
UnknownSeason(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Source(e) => e.fmt(f),
Error::Storage(msg) => write!(f, "Erreur de stockage : {msg}"),
Error::InvalidRiotId(id) => {
write!(f, "Riot ID invalide : « {id} » (attendu : Nom#TAG).")
}
Error::Config(msg) => write!(f, "Configuration invalide : {msg}"),
Error::UnknownSeason(name) => write!(f, "Saison inconnue : « {name} »."),
}
}
}
impl std::error::Error for Error {}
impl From<SourceError> for Error {
fn from(e: SourceError) -> Self {
Error::Source(e)
}
}
impl From<rusqlite::Error> for Error {
fn from(e: rusqlite::Error) -> Self {
Error::Storage(e.to_string())
}
}
+509
View File
@@ -0,0 +1,509 @@
//! Keeping the active Account up to date by following the game client.
use std::sync::{MutexGuard, PoisonError};
use std::thread;
use std::time::Duration;
use rusqlite::OptionalExtension;
use crate::client::{GameClientSource, GamePhase, Gameflow};
use crate::error::{Error, SourceError};
use crate::model::{Account, SyncProgress, SyncReport};
use crate::seasons::Season;
use crate::statistics::{Scope, SeasonScope};
use crate::tracker::{Fetched, Tracker, account_from_row};
/// Tries at the Match of an Arena game that just ended, one per `RETRY_EVERY_MS` (about 30
/// minutes: Riot publishes it only when the whole game is over, which a player eliminated early
/// does not wait for).
pub const MATCH_RETRIES: usize = 90;
pub const RETRY_EVERY_MS: i64 = 20_000;
/// Rounds try a failed adoption again at most this often (an expired key fails every time).
const ADOPT_RETRY_MS: i64 = 60_000;
const WAIT_WHILE_PENDING: Duration = Duration::from_millis(RETRY_EVERY_MS as u64);
const WAIT_OTHERWISE: Duration = Duration::from_secs(60);
/// Why the last update did not (fully) happen.
#[derive(Debug, Clone, PartialEq)]
pub enum UpdateProblem {
MissingKey,
InvalidKey,
Network,
RateLimited,
/// Client absent and no Account known yet.
NoAccount,
/// A finished Arena game is not available from the Riot API yet.
MatchPending,
Other(String),
}
impl UpdateProblem {
/// The French banner text.
pub fn message(&self) -> String {
match self {
UpdateProblem::MissingKey => {
"Aucune clé API Riot n'est configurée : ajoutez-la dans les Paramètres.".into()
}
UpdateProblem::InvalidKey => {
"La clé API Riot est refusée (invalide ou expirée) : renouvelez-la dans les Paramètres."
.into()
}
UpdateProblem::Network => {
"L'API Riot est injoignable : vérifiez votre connexion.".into()
}
UpdateProblem::RateLimited => {
"L'API Riot limite les requêtes : la mise à jour reprendra plus tard.".into()
}
UpdateProblem::NoAccount => {
"Aucun Compte connu : lancez le client de League of Legends et connectez-vous."
.into()
}
UpdateProblem::MatchPending => {
"La dernière Partie n'est pas encore disponible chez Riot : actualisez plus tard pour l'importer."
.into()
}
UpdateProblem::Other(reason) => format!("Mise à jour impossible : {reason}"),
}
}
}
impl From<&Error> for UpdateProblem {
fn from(error: &Error) -> Self {
match error {
Error::Source(SourceError::MissingKey) => UpdateProblem::MissingKey,
Error::Source(SourceError::InvalidKey) => UpdateProblem::InvalidKey,
Error::Source(SourceError::Network(_)) => UpdateProblem::Network,
Error::Source(SourceError::RateLimited { .. }) => UpdateProblem::RateLimited,
other => UpdateProblem::Other(other.to_string()),
}
}
}
/// The game's own count compared with the app's, for the current Season.
#[derive(Debug, Clone, Default, PartialEq)]
pub enum ProgressCheck {
#[default]
Absent,
Agrees(u32),
Differs {
app: usize,
official: u32,
},
}
/// What the interface needs to know besides statistics.
#[derive(Debug, Clone, PartialEq)]
pub struct Status {
/// As of the last `follow_client` round.
pub client_running: bool,
/// The signed-in Account while the client runs, otherwise the last active one.
pub updating: Option<Account>,
/// Outcome of the most recent update attempt; `None` after a success.
pub problem: Option<UpdateProblem>,
pub official_progress: ProgressCheck,
}
/// The Match of a finished Arena game, not stored yet.
struct Pending {
/// The client's id of that game, when it gave one.
game_id: Option<u64>,
tries: usize,
next_try_ms: i64,
}
#[derive(Default)]
pub(crate) struct Follow {
/// The Riot ID read from the client by the last round; `None` while it is absent.
signed_in: Option<String>,
/// The Riot ID of the last adoption, `None` when it failed.
adopted: Option<String>,
/// Set when a round's adoption failed: rounds do not try again before.
adopt_retry_after_ms: Option<i64>,
gameflow: Gameflow,
pending: Vec<Pending>,
/// The Riot ID the app last gave to fall back on when there is nothing else.
fallback: Option<String>,
updating: Option<Account>,
problem: Option<UpdateProblem>,
/// The client's reading for the current Season: (Season name, counter value).
official: Option<(String, u32)>,
official_progress: ProgressCheck,
}
fn riot_id(account: &Account) -> String {
format!("{}#{}", account.game_name, account.tag_line)
}
fn same_riot_id(a: &str, b: &str) -> bool {
a.to_lowercase() == b.to_lowercase()
}
impl Tracker {
/// Without a client, it is always absent.
pub fn with_client(mut self, client: Box<dyn GameClientSource>) -> Tracker {
self.client = Some(client);
self
}
pub(crate) fn follow(&self) -> MutexGuard<'_, Follow> {
self.follow.lock().unwrap_or_else(PoisonError::into_inner)
}
/// A successful update clears the problem, except that the Match of a finished game stays
/// missing until one is added.
pub(crate) fn clear_problem(&self, added: usize) {
let mut follow = self.follow();
if added > 0 || follow.problem != Some(UpdateProblem::MatchPending) {
follow.problem = None;
}
}
/// Cheap: never touches the client or the network.
pub fn status(&self) -> Status {
let follow = self.follow();
Status {
client_running: follow.signed_in.is_some(),
updating: follow.updating.clone(),
problem: follow.problem.clone(),
official_progress: follow.official_progress.clone(),
}
}
/// The Account shown at launch before any round ran.
pub fn last_active_account(&self) -> Result<Option<Account>, Error> {
Ok(self
.db()
.query_row(
"SELECT a.puuid, a.game_name, a.tag_line
FROM meta m JOIN accounts a ON a.puuid = m.value
WHERE m.name = 'last_active_puuid'",
[],
account_from_row,
)
.optional()?)
}
/// One round of following the game client: reads it once, adopts the signed-in Account (or,
/// without a client, the last known one) until that succeeds, then tries the Matches of
/// finished Arena games that are due. Failures never propagate: they end up in
/// `status().problem`. Returns true when something visible may have changed.
pub fn follow_client(
&self,
now_ms: i64,
fallback_riot_id: Option<&str>,
on_progress: &mut dyn FnMut(SyncProgress),
) -> bool {
let before = self.status();
let mut added = 0;
let (signed_in, gameflow) = match &self.client {
Some(client) => match client.signed_in() {
Ok((name, tag)) => (Some(format!("{name}#{tag}")), client.gameflow().ok()),
Err(_) => (None, None),
},
None => (None, None),
};
let adopt = {
let mut follow = self.follow();
if let Some(id) = fallback_riot_id.map(str::trim).filter(|id| !id.is_empty()) {
follow.fallback = Some(id.into());
}
let lower = |id: &Option<String>| id.as_deref().map(str::to_lowercase);
if lower(&follow.signed_in) != lower(&signed_in) {
follow.adopt_retry_after_ms = None;
}
follow.signed_in = signed_in.clone();
let due = follow.adopt_retry_after_ms.is_none_or(|t| now_ms >= t);
due && match &signed_in {
Some(_) => lower(&follow.adopted) != lower(&signed_in),
// No client and no Account yet: catch up on Matches played while the app was closed.
None => follow.updating.is_none(),
}
};
if adopt {
match signed_in.clone().or_else(|| self.known_riot_id()) {
Some(id) => match self.adopt(&id, on_progress) {
Ok(report) => added += report.added,
Err(_) => self.follow().adopt_retry_after_ms = Some(now_ms + ADOPT_RETRY_MS),
},
None => self.follow().problem = Some(UpdateProblem::NoAccount),
}
}
if let Some(gameflow) = gameflow {
let mut follow = self.follow();
let previous = std::mem::replace(&mut follow.gameflow, gameflow);
let ended = previous.phase == GamePhase::InGame
&& previous.arena
&& follow.gameflow.phase != GamePhase::InGame;
let known = previous.game_id.is_some()
&& follow.pending.iter().any(|p| p.game_id == previous.game_id);
if ended && !known {
follow.pending.push(Pending {
game_id: previous.game_id,
tries: 0,
next_try_ms: now_ms,
});
}
}
let account = self.follow().updating.clone();
let mut due: Vec<Option<u64>> = (self.follow().pending.iter())
.filter(|p| p.next_try_ms <= now_ms)
.map(|p| p.game_id)
.collect();
// The games without an id all wait for the same sync: one try for them all.
due.sort_unstable();
due.dedup();
for game_id in due {
let (found, over) = match &account {
Some(account) => self.look_for_match(account, game_id, on_progress),
None => (0, false),
};
added += found;
let mut follow = self.follow();
let mut expired = false;
follow.pending.retain_mut(|p| {
if p.game_id != game_id || p.next_try_ms > now_ms {
return true;
}
p.tries += 1;
p.next_try_ms = now_ms + RETRY_EVERY_MS;
expired |= !over && p.tries >= MATCH_RETRIES;
!over && p.tries < MATCH_RETRIES
});
if expired && follow.problem.is_none() {
follow.problem = Some(UpdateProblem::MatchPending);
}
}
let official = match (&self.client, &signed_in, self.current_season(now_ms)) {
(
Some(client),
Some(signed_in),
Some(Season {
name,
official_track: Some(track),
..
}),
) if self
.follow()
.updating
.as_ref()
.is_some_and(|a| same_riot_id(&riot_id(a), signed_in)) =>
{
client
.official_progress(&track)
.ok()
.flatten()
.map(|value| (name, value))
}
_ => None,
};
self.follow().official = official;
self.update_progress_check();
self.status() != before || added > 0
}
/// Blocks until a client event or a timeout, shorter while a Match is pending: the rounds
/// events cause try it only once its time has come.
pub fn wait_for_client(&self) {
let timeout = if self.follow().pending.is_empty() {
WAIT_OTHERWISE
} else {
WAIT_WHILE_PENDING
};
match &self.client {
Some(client) => client.wait_for_change(timeout),
None => thread::sleep(timeout),
}
}
/// The refresh button: adopts the Account signed in to the client, else syncs the one being
/// kept up to date, else adopts the last known one.
pub fn refresh(
&self,
on_progress: &mut dyn FnMut(SyncProgress),
) -> Result<SyncReport, UpdateProblem> {
let (signed_in, updating) = {
let follow = self.follow();
(follow.signed_in.clone(), follow.updating.clone())
};
let result = match (signed_in, updating) {
(Some(id), _) => self.adopt(&id, on_progress),
(None, Some(account)) => self.update(&riot_id(&account), on_progress),
(None, None) => match self.known_riot_id() {
Some(id) => self.adopt(&id, on_progress),
None => Err(self.record(UpdateProblem::NoAccount)),
},
};
self.update_progress_check();
result
}
/// Without a client: the last active Account, else the configured Riot ID.
fn known_riot_id(&self) -> Option<String> {
let last = self.last_active_account().ok().flatten();
last.map(|a| riot_id(&a))
.or_else(|| self.follow().fallback.clone())
}
fn record(&self, problem: UpdateProblem) -> UpdateProblem {
self.follow().problem = Some(problem.clone());
problem
}
/// A sync whose failure is recorded as the current problem (a success clears it). One that
/// adds a Match ends the waits for the games the client gave no id for.
fn update(
&self,
riot_id: &str,
on_progress: &mut dyn FnMut(SyncProgress),
) -> Result<SyncReport, UpdateProblem> {
match self.sync(riot_id, on_progress) {
Ok(report) => {
if report.added > 0 {
self.follow().pending.retain(|p| p.game_id.is_some());
}
Ok(report)
}
Err(e) => Err(self.record(UpdateProblem::from(&e))),
}
}
/// Syncs the Account with this Riot ID and makes it the active one. When that fails, the
/// active one is the stored Account with that Riot ID, if any: never the previous Account.
fn adopt(
&self,
riot_id: &str,
on_progress: &mut dyn FnMut(SyncProgress),
) -> Result<SyncReport, UpdateProblem> {
let result = self.update(riot_id, on_progress);
let account = match &result {
Ok(report) => Some(report.account.clone()),
Err(_) => self.accounts().ok().and_then(|all| {
all.into_iter()
.find(|a| same_riot_id(&self::riot_id(a), riot_id))
}),
};
if let Some(account) = &account
&& let Err(e) = self.remember_active(account)
{
self.record(UpdateProblem::from(&e));
}
let mut follow = self.follow();
follow.updating = account;
follow.adopted = result.is_ok().then(|| riot_id.into());
follow.adopt_retry_after_ms = follow.adopt_retry_after_ms.filter(|_| result.is_err());
result
}
/// One try at the Match of a finished Arena game: fetched by its id when the client gave it
/// and a stored Match gives the platform, else looked for by a normal sync. Returns the
/// number of Matches added and whether the wait for this one is over.
fn look_for_match(
&self,
account: &Account,
game_id: Option<u64>,
on_progress: &mut dyn FnMut(SyncProgress),
) -> (usize, bool) {
let platform = self.platform_of(&account.puuid).ok().flatten();
let Some(match_id) = game_id.zip(platform).map(|(id, p)| format!("{p}_{id}")) else {
// Not over: `update` ends the waits without an id, a fetch by id ends the others.
let added = self.update(&riot_id(account), on_progress);
return (added.map_or(0, |report| report.added), false);
};
match self.fetch_and_store(&account.puuid, &match_id) {
Ok(fetched) => {
let added = usize::from(fetched == Fetched::Added);
self.clear_problem(added);
(added, fetched != Fetched::NotFound)
}
Err(e) => {
self.record(UpdateProblem::from(&e));
(0, false)
}
}
}
fn remember_active(&self, account: &Account) -> Result<(), Error> {
self.db().execute(
"INSERT OR REPLACE INTO meta (name, value) VALUES ('last_active_puuid', ?1)",
[&account.puuid],
)?;
Ok(())
}
/// Compares the client's reading with the Challenge of the active Account.
fn update_progress_check(&self) {
let (official, account) = {
let follow = self.follow();
(follow.official.clone(), follow.updating.clone())
};
let check = match (official, account) {
(Some((season, official)), Some(account)) => {
let scope = Scope {
season: SeasonScope::Season(season),
format: None,
};
match self.statistics(&account.puuid, &scope) {
Ok(stats) => {
let app = stats.challenge.map_or(0, |c| c.completed);
if app == official as usize {
ProgressCheck::Agrees(official)
} else {
ProgressCheck::Differs { app, official }
}
}
Err(_) => ProgressCheck::Absent,
}
}
_ => ProgressCheck::Absent,
};
self.follow().official_progress = check;
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
use std::time::Duration;
#[test]
fn every_problem_has_its_own_message() {
let messages: HashSet<String> = [
UpdateProblem::MissingKey,
UpdateProblem::InvalidKey,
UpdateProblem::Network,
UpdateProblem::RateLimited,
UpdateProblem::NoAccount,
UpdateProblem::MatchPending,
UpdateProblem::Other("panne".into()),
]
.iter()
.map(UpdateProblem::message)
.collect();
assert_eq!(messages.len(), 7);
assert!(messages.iter().all(|m| !m.is_empty()));
}
#[test]
fn errors_map_to_problems() {
let source = |e| UpdateProblem::from(&Error::Source(e));
assert_eq!(source(SourceError::MissingKey), UpdateProblem::MissingKey);
assert_eq!(source(SourceError::InvalidKey), UpdateProblem::InvalidKey);
assert_eq!(
source(SourceError::Network("x".into())),
UpdateProblem::Network
);
let limited = SourceError::RateLimited {
retry_after: Duration::ZERO,
};
assert_eq!(source(limited), UpdateProblem::RateLimited);
assert!(matches!(
source(SourceError::NotFound),
UpdateProblem::Other(_)
));
let storage = UpdateProblem::from(&Error::Storage("disque plein".into()));
assert!(matches!(storage, UpdateProblem::Other(m) if m.contains("disque plein")));
}
}
+558
View File
@@ -0,0 +1,558 @@
use std::collections::HashMap;
use std::io::ErrorKind;
use std::net::{SocketAddr, TcpStream};
use std::path::PathBuf;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};
use std::{env, fs, thread};
use base64::prelude::{BASE64_STANDARD, Engine};
use rustls::pki_types::CertificateDer;
use rustls::{ClientConfig, RootCertStore};
use serde_json::Value;
use tungstenite::client::IntoClientRequest;
use tungstenite::http::HeaderValue;
use tungstenite::stream::MaybeTlsStream;
use tungstenite::{Connector, Message, WebSocket, client_tls_with_config};
use ureq::Agent;
use ureq::tls::{Certificate, RootCerts, TlsConfig};
use crate::client::{ClientError, GameClientSource, GamePhase, Gameflow};
use crate::riot::encode;
/// Riot's published root certificate: the client's certificate is signed by it, and it is
/// the only root this adapter trusts.
const RIOT_ROOT: &str = include_str!("riotgames.pem");
const SETTINGS: &str =
"Riot Games/Metadata/league_of_legends.live/league_of_legends.live.product_settings.yaml";
const DEFAULT_INSTALL_DIR: &str = r"C:\Riot Games\League of Legends";
const TIMEOUT: Duration = Duration::from_secs(5);
const TOPICS: [&str; 3] = [
"OnJsonApiEvent_lol-gameflow_v1_session",
"OnJsonApiEvent_lol-summoner_v1_current-summoner",
"OnJsonApiEvent_lol-champ-select_v1_session",
];
/// The local League client's API (unofficial, read-only). Deliberately no `Debug`: it handles
/// the lockfile password.
pub struct LeagueClient {
install_dir: PathBuf,
agent: Agent,
/// Track name -> (group id, id of the group's first counter), so the big progression
/// configuration is downloaded once per track.
tracks: Mutex<HashMap<String, (String, Option<String>)>>,
events: Mutex<Option<Events>>,
}
struct Events(WebSocket<MaybeTlsStream<TcpStream>>);
impl Events {
/// Set on the stream the TLS layer reads from: on Windows a timeout is per handle, so a
/// clone of the `TcpStream` would not do.
fn set_read_timeout(&self, timeout: Duration) -> std::io::Result<()> {
match self.0.get_ref() {
MaybeTlsStream::Rustls(stream) => stream.get_ref().set_read_timeout(Some(timeout)),
_ => Err(ErrorKind::Unsupported.into()),
}
}
}
impl LeagueClient {
pub fn new() -> LeagueClient {
let from_settings = env::var_os("PROGRAMDATA")
.and_then(|dir| fs::read_to_string(PathBuf::from(dir).join(SETTINGS)).ok())
.and_then(|yaml| install_dir_from_settings(&yaml));
LeagueClient::in_dir(from_settings.unwrap_or_else(|| DEFAULT_INSTALL_DIR.into()))
}
fn in_dir(install_dir: PathBuf) -> LeagueClient {
let agent = Agent::config_builder()
.http_status_as_error(false)
.proxy(None) // the client is on this machine
.tls_config(
TlsConfig::builder()
.root_certs(RootCerts::new_with_certs(&[root_cert()]))
.build(),
)
.timeout_global(Some(TIMEOUT))
.build()
.into();
LeagueClient {
install_dir,
agent,
tracks: Mutex::default(),
events: Mutex::default(),
}
}
/// Read on every call: the port and password change each time the client restarts.
fn lockfile(&self) -> Result<(u16, String), ClientError> {
fs::read_to_string(self.install_dir.join("lockfile"))
.ok()
.and_then(|content| parse_lockfile(&content))
.ok_or(ClientError::Absent)
}
/// Status and body of a GET; the client is the only thing this ever talks to.
fn get(&self, path: &str) -> Result<(u16, String), ClientError> {
let (port, password) = self.lockfile()?;
let mut response = self
.agent
.get(&format!("https://127.0.0.1:{port}{path}"))
.header("Authorization", authorization(&password))
.call()
.map_err(transport_error)?;
let body = response
.body_mut()
.read_to_string()
.map_err(transport_error)?;
Ok((response.status().as_u16(), body))
}
fn get_ok(&self, path: &str) -> Result<String, ClientError> {
match self.get(path)? {
(200, body) => Ok(body),
(status, _) => Err(ClientError::Other(format!("HTTP {status}"))),
}
}
fn connect(&self) -> Option<Events> {
let (port, password) = self.lockfile().ok()?;
let tcp =
TcpStream::connect_timeout(&SocketAddr::from(([127, 0, 0, 1], port)), TIMEOUT).ok()?;
// They bound the TLS and WebSocket handshakes.
tcp.set_read_timeout(Some(TIMEOUT)).ok()?;
tcp.set_write_timeout(Some(TIMEOUT)).ok()?;
let mut request = format!("wss://127.0.0.1:{port}/")
.into_client_request()
.ok()?;
let auth = HeaderValue::from_str(&authorization(&password)).ok()?;
request.headers_mut().insert("Authorization", auth);
let tls = Connector::Rustls(Arc::new(tls_config().ok()?));
let (mut socket, _) = client_tls_with_config(request, tcp, None, Some(tls)).ok()?;
for topic in TOPICS {
socket
.send(Message::text(format!(r#"[5, "{topic}"]"#)))
.ok()?;
}
Some(Events(socket))
}
}
impl Default for LeagueClient {
fn default() -> Self {
LeagueClient::new()
}
}
impl GameClientSource for LeagueClient {
fn signed_in(&self) -> Result<(String, String), ClientError> {
match self.get("/lol-summoner/v1/current-summoner")? {
(200, body) => decode_signed_in(&body),
_ => Err(ClientError::Absent),
}
}
fn gameflow(&self) -> Result<Gameflow, ClientError> {
let (status, body) = self.get("/lol-gameflow/v1/session")?;
decode_gameflow(status, &body)
}
fn official_progress(&self, track_name: &str) -> Result<Option<u32>, ClientError> {
let known = lock(&self.tracks).get(track_name).cloned();
let (group_id, counter_id) = match known {
Some(track) => track,
None => {
let body = self.get_ok("/lol-progression/v1/groups/configuration")?;
let Some(track) = find_track(&body, track_name)? else {
return Ok(None);
};
lock(&self.tracks).insert(track_name.into(), track.clone());
track
}
};
let path = format!(
"/lol-progression/v1/groups/{}/instanceData",
encode(&group_id)
);
// A refused group id may be stale after a patch: look the track up again next time.
let body = self.get_ok(&path).inspect_err(|_| {
lock(&self.tracks).remove(track_name);
})?;
decode_counter(&body, counter_id.as_deref())
}
fn wait_for_change(&self, timeout: Duration) {
let started = Instant::now();
let mut events = lock(&self.events);
if events.is_none() {
*events = self.connect();
}
let Some(connection) = events.as_mut() else {
thread::sleep(timeout.min(TIMEOUT));
return;
};
// Right after subscribing, the client sends one empty text frame per subscription
// (observed on patch 16.22): they and pings are not changes.
loop {
let left = timeout
.saturating_sub(started.elapsed())
.max(Duration::from_millis(1));
let read = connection
.set_read_timeout(left)
.map_err(tungstenite::Error::Io)
.and_then(|()| connection.0.read());
match read {
Ok(Message::Text(text)) if !text.is_empty() => return,
Ok(Message::Close(_)) => *events = None,
Ok(_) => continue,
Err(tungstenite::Error::Io(e))
if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {}
Err(_) => *events = None,
}
return;
}
}
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
fn root_cert() -> Certificate<'static> {
Certificate::from_pem(RIOT_ROOT.as_bytes()).expect("riotgames.pem holds a certificate")
}
/// For the WebSocket: the pinned root only, and `ring` chosen explicitly so that no process-wide
/// crypto provider is needed.
fn tls_config() -> Result<ClientConfig, rustls::Error> {
let mut roots = RootCertStore::empty();
roots.add(CertificateDer::from(root_cert().der().to_vec()))?;
Ok(
ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
.with_safe_default_protocol_versions()?
.with_root_certificates(roots)
.with_no_client_auth(),
)
}
/// A rejected certificate is worth telling apart from a client that is simply not there.
fn transport_error(e: ureq::Error) -> ClientError {
match e {
ureq::Error::Tls(_) | ureq::Error::Rustls(_) => {
ClientError::Other(format!("Connexion TLS au client refusée : {e}"))
}
_ => ClientError::Absent,
}
}
fn authorization(password: &str) -> String {
format!(
"Basic {}",
BASE64_STANDARD.encode(format!("riot:{password}"))
)
}
/// (port, password) from `LeagueClient:<pid>:<port>:<password>:https`.
fn parse_lockfile(content: &str) -> Option<(u16, String)> {
let parts: Vec<&str> = content.trim().split(':').collect();
let [_, _, port, password, "https"] = parts[..] else {
return None;
};
(!password.is_empty()).then_some((port.parse().ok()?, password.into()))
}
/// The value of the `product_install_full_path` line of the product settings.
fn install_dir_from_settings(yaml: &str) -> Option<PathBuf> {
let line = yaml
.lines()
.find_map(|l| l.trim().strip_prefix("product_install_full_path:"))?;
let path = line.trim().trim_matches('"');
(!path.is_empty()).then(|| path.into())
}
fn parse(body: &str) -> Result<Value, ClientError> {
serde_json::from_str(body)
.map_err(|e| ClientError::Other(format!("Réponse du client illisible : {e}")))
}
fn decode_signed_in(body: &str) -> Result<(String, String), ClientError> {
let summoner = parse(body)?;
let field = |name: &str| summoner[name].as_str().filter(|s| !s.is_empty());
match (field("gameName"), field("tagLine")) {
(Some(name), Some(tag)) => Ok((name.into(), tag.into())),
_ => Err(ClientError::Absent),
}
}
/// No session (404) means no game. The other fields are read leniently: the API is
/// unofficial and changes with patches.
fn decode_gameflow(status: u16, body: &str) -> Result<Gameflow, ClientError> {
match status {
404 => Ok(Gameflow::default()),
200 => {
let session = parse(body)?;
let arena = ["/gameData/queue/gameMode", "/map/gameMode"]
.iter()
.any(|path| session.pointer(path).and_then(Value::as_str) == Some("CHERRY"));
Ok(Gameflow {
phase: GamePhase::from_client(session["phase"].as_str().unwrap_or_default()),
arena,
game_id: session
.pointer("/gameData/gameId")
.and_then(Value::as_u64)
.filter(|&id| id != 0),
})
}
_ => Err(ClientError::Other(format!("HTTP {status}"))),
}
}
/// (group id, id of the group's first counter) of the group with exactly this name.
fn find_track(
body: &str,
track_name: &str,
) -> Result<Option<(String, Option<String>)>, ClientError> {
let groups = parse(body)?;
let group = groups
.as_array()
.into_iter()
.flatten()
.find(|g| g["name"] == track_name);
Ok(group.and_then(|g| {
let counter = g.pointer("/counters/0/id").and_then(Value::as_str);
Some((g["id"].as_str()?.into(), counter.map(String::from)))
}))
}
/// The value of the counter with this id, else of the first counter.
fn decode_counter(body: &str, counter_id: Option<&str>) -> Result<Option<u32>, ClientError> {
let data = parse(body)?;
let counters = data["counters"].as_array().map_or(&[][..], Vec::as_slice);
let counter = counter_id
.and_then(|id| counters.iter().find(|c| c["counterId"] == id))
.or(counters.first());
Ok(counter
.and_then(|c| c["counterValue"].as_u64())
.and_then(|v| u32::try_from(v).ok()))
}
#[cfg(test)]
mod tests {
use super::*;
const SUMMONER: &str = include_str!("../tests/fixtures/client/current_summoner.json");
const NO_SESSION: &str = include_str!("../tests/fixtures/client/gameflow_session_absent.json");
const GROUPS: &str =
include_str!("../tests/fixtures/client/progression_groups_configuration.json");
const INSTANCE: &str = include_str!("../tests/fixtures/client/progression_instance_data.json");
const SEASON_2: &str = "2026 Season 2 Champs Completed Track";
const ARENA_GAME: &str = include_str!("../tests/fixtures/client/gameflow_session_in_game.json");
#[test]
fn reads_the_port_and_password_of_a_lockfile() {
let sample = "LeagueClient:4242:51234:fake-password_1:https";
assert_eq!(
parse_lockfile(sample),
Some((51234, "fake-password_1".into()))
);
assert_eq!(
parse_lockfile(&format!("{sample}\r\n")),
Some((51234, "fake-password_1".into()))
);
}
#[test]
fn a_malformed_lockfile_is_ignored() {
for bad in [
"",
"LeagueClient",
"LeagueClient:4242:51234:fake-password",
"LeagueClient:4242:notaport:fake-password:https",
"LeagueClient:4242:99999:fake-password:https",
"LeagueClient:4242:51234::https",
"LeagueClient:4242:51234:fake-password:http",
"LeagueClient:4242:51234:fake:password:https",
] {
assert_eq!(parse_lockfile(bad), None, "{bad:?}");
}
}
#[test]
fn reads_the_install_directory_from_the_product_settings() {
let yaml = "auto_patching_enabled_by_player: false\n\
product_install_full_path: \"C:/Riot Games/League of Legends\"\n\
settings:\n locale: \"fr_FR\"\n";
assert_eq!(
install_dir_from_settings(yaml),
Some(PathBuf::from("C:/Riot Games/League of Legends"))
);
assert_eq!(install_dir_from_settings("settings:\n locale: x\n"), None);
assert_eq!(
install_dir_from_settings("product_install_full_path: \"\""),
None
);
}
#[test]
fn basic_authorization_uses_the_riot_user() {
// base64("riot:fake-password")
assert_eq!(
authorization("fake-password"),
"Basic cmlvdDpmYWtlLXBhc3N3b3Jk"
);
}
#[test]
fn the_embedded_root_certificate_builds_a_tls_config() {
assert!(tls_config().is_ok());
}
#[test]
fn reads_the_signed_in_riot_id() {
assert_eq!(
decode_signed_in(SUMMONER),
Ok(("Joueur".into(), "EUW".into()))
);
}
#[test]
fn nobody_signed_in_yet_is_absent() {
for body in [
r#"{"gameName": "Joueur"}"#,
r#"{"gameName": "", "tagLine": "EUW"}"#,
r#"{"gameName": "Joueur", "tagLine": ""}"#,
r#"{"gameName": null, "tagLine": null}"#,
"{}",
] {
assert_eq!(decode_signed_in(body), Err(ClientError::Absent), "{body}");
}
assert!(matches!(
decode_signed_in("<html>"),
Err(ClientError::Other(_))
));
}
#[test]
fn no_gameflow_session_means_idle() {
assert_eq!(
decode_gameflow(404, NO_SESSION),
Ok(Gameflow {
phase: GamePhase::Idle,
arena: false,
game_id: None
})
);
}
#[test]
fn an_arena_game_in_progress_is_in_game_and_arena() {
assert_eq!(
decode_gameflow(200, ARENA_GAME),
Ok(Gameflow {
phase: GamePhase::InGame,
arena: true,
game_id: Some(9000000099)
})
);
let classic = r#"{"phase": "InProgress", "gameData": {"queue": {"gameMode": "CLASSIC"}}}"#;
assert_eq!(
decode_gameflow(200, classic),
Ok(Gameflow {
phase: GamePhase::InGame,
arena: false,
game_id: None
})
);
}
#[test]
fn unknown_and_missing_gameflow_fields_are_not_errors() {
let extra = r#"{"phase": "ChampSelect", "somethingNew": {"a": [1, 2]}, "map": null,
"gameData": {"queue": null}}"#;
assert_eq!(
decode_gameflow(200, extra),
Ok(Gameflow {
phase: GamePhase::ChampSelect,
arena: false,
game_id: None
})
);
assert_eq!(decode_gameflow(200, "{}"), decode_gameflow(404, ""));
// The map alone says Arena when the queue is missing.
let map_only = r#"{"phase": "EndOfGame", "map": {"gameMode": "CHERRY"}}"#;
assert_eq!(
decode_gameflow(200, map_only),
Ok(Gameflow {
phase: GamePhase::Ended,
arena: true,
game_id: None
})
);
// An id of 0 means no game; one that is not a number is ignored.
for id in ["0", "\"x\"", "null", "-1"] {
let body = format!(r#"{{"phase": "InProgress", "gameData": {{"gameId": {id}}}}}"#);
assert_eq!(decode_gameflow(200, &body).unwrap().game_id, None, "{id}");
}
assert_eq!(
decode_gameflow(503, ""),
Err(ClientError::Other("HTTP 503".into()))
);
}
#[test]
fn finds_the_champs_completed_tracks_by_exact_name() {
for (name, group, counter) in [
(
SEASON_2,
"01030e0d-e3e3-4034-93dc-44a88bcb8401",
"d64a3f04-2ba0-475a-9a33-782cb12e6467",
),
(
"2026 Season 1 Champs Completed Track",
"7d0ef399-dd59-4005-bf1d-e0b98cda8acb",
"be96f5dc-d65c-4ea4-9a23-0b2c1bb6880f",
),
(
"Cherry 2025 Champs Completed Track",
"e5d45c5c-a035-4e0a-9c9d-c02a3604a3b9",
"ae1d0604-8841-4640-987e-29696c18caca",
),
] {
assert_eq!(
find_track(GROUPS, name),
Ok(Some((group.into(), Some(counter.into())))),
"{name}"
);
}
for unknown in ["2026 Season 3 Champs Completed Track", "2026 Season 2", ""] {
assert_eq!(find_track(GROUPS, unknown), Ok(None), "{unknown:?}");
}
assert_eq!(find_track("[]", SEASON_2), Ok(None));
}
#[test]
fn reads_the_counter_of_the_track() {
let counter = "d64a3f04-2ba0-475a-9a33-782cb12e6467";
assert_eq!(decode_counter(INSTANCE, Some(counter)), Ok(Some(52)));
// Without a usable counter id, the first counter is read.
assert_eq!(decode_counter(INSTANCE, None), Ok(Some(52)));
assert_eq!(decode_counter(INSTANCE, Some("other")), Ok(Some(52)));
assert_eq!(decode_counter(r#"{"counters": []}"#, None), Ok(None));
assert_eq!(decode_counter("{}", Some(counter)), Ok(None));
}
#[test]
fn without_a_lockfile_the_client_is_absent() {
let dir = tempfile::tempdir().unwrap();
let client = LeagueClient::in_dir(dir.path().into());
assert_eq!(client.signed_in(), Err(ClientError::Absent));
assert_eq!(client.gameflow(), Err(ClientError::Absent));
assert_eq!(client.official_progress(SEASON_2), Err(ClientError::Absent));
let started = Instant::now();
client.wait_for_change(Duration::from_millis(50));
assert!(started.elapsed() >= Duration::from_millis(50));
assert!(started.elapsed() < TIMEOUT);
}
}
+27 -13
View File
@@ -1,14 +1,28 @@
/// Text shown at startup while no Match has been imported yet.
pub fn startup_message() -> &'static str {
"Aucune Partie importée pour l'instant."
}
mod champions;
mod client;
mod config;
mod date;
mod error;
mod follow;
mod league_client;
mod model;
mod riot;
mod seasons;
mod statistics;
mod tracker;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn startup_message_announces_no_imported_match() {
assert_eq!(startup_message(), "Aucune Partie importée pour l'instant.");
}
}
pub use champions::{Champion, ChampionCatalog, ChampionSource, DataDragon};
pub use client::{ClientError, GameClientSource, GamePhase, Gameflow};
pub use config::{Config, data_dir};
pub use date::Date;
pub use error::{Error, SourceError};
pub use follow::{MATCH_RETRIES, ProgressCheck, RETRY_EVERY_MS, Status, UpdateProblem};
pub use league_client::LeagueClient;
pub use model::{Account, Format, Match, SyncProgress, SyncReport};
pub use riot::RiotApi;
pub use seasons::{Season, default_seasons, load_seasons};
pub use statistics::{
ChallengeSummary, ChampionRow, ChampionState, Charts, Column, Scope, SeasonScope, StateFilter,
Statistics, sort_rows,
};
pub use tracker::{MatchHistorySource, Tracker};
+90
View File
@@ -0,0 +1,90 @@
use serde::Deserialize;
/// One Arena variant, derived from the game queue.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Format {
Arena3x6,
BraveryArena,
Arena16,
Other(u32),
}
impl Format {
/// `None` for queues that are not real Matches (1704 is the PBE test queue).
pub fn from_queue(queue_id: u32) -> Option<Format> {
match queue_id {
1750 => Some(Format::Arena3x6),
1740 => Some(Format::BraveryArena),
1700 | 1710 => Some(Format::Arena16),
1704 => None,
other => Some(Format::Other(other)),
}
}
pub fn name(&self) -> String {
match self {
Format::Arena3x6 => "Arena 3x6".into(),
Format::BraveryArena => "Bravery Arena".into(),
Format::Arena16 => "Arena 16 joueurs".into(),
Format::Other(queue) => format!("Arena (file {queue})"),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Account {
pub puuid: String,
pub game_name: String,
pub tag_line: String,
}
/// A stored Match as the user sees it.
#[derive(Clone, Debug, PartialEq)]
pub struct Match {
pub match_id: String,
pub format: Format,
pub champion_id: u32,
pub champion_name: String,
pub placement: u8,
pub win: bool,
pub started_at_ms: i64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SyncProgress {
pub fetched: usize,
pub to_fetch: usize,
}
#[derive(Clone, Debug)]
pub struct SyncReport {
pub account: Account,
/// Matches newly stored by this sync.
pub added: usize,
/// All Matches stored for the Account once the sync is done.
pub stored: usize,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn queues_map_to_formats() {
assert_eq!(Format::from_queue(1750), Some(Format::Arena3x6));
assert_eq!(Format::from_queue(1740), Some(Format::BraveryArena));
assert_eq!(Format::from_queue(1700), Some(Format::Arena16));
assert_eq!(Format::from_queue(1710), Some(Format::Arena16));
assert_eq!(Format::from_queue(1704), None);
assert_eq!(Format::from_queue(1800), Some(Format::Other(1800)));
}
#[test]
fn formats_have_french_facing_names() {
assert_eq!(Format::Arena3x6.name(), "Arena 3x6");
assert_eq!(Format::BraveryArena.name(), "Bravery Arena");
assert_eq!(Format::Arena16.name(), "Arena 16 joueurs");
assert_eq!(Format::Other(1800).name(), "Arena (file 1800)");
}
}
+258
View File
@@ -0,0 +1,258 @@
use std::collections::VecDeque;
use std::sync::{Mutex, PoisonError};
use std::thread;
use std::time::{Duration, Instant};
use ureq::{Agent, Body};
use crate::error::SourceError;
use crate::model::Account;
use crate::tracker::MatchHistorySource;
/// Personal-key limits: (requests, window).
const LIMITS: [(usize, Duration); 2] = [
(20, Duration::from_secs(1)),
(100, Duration::from_secs(120)),
];
const DEFAULT_RETRY_AFTER: Duration = Duration::from_secs(10);
/// Riot web API adapter. Deliberately has no `Debug`: it holds the API key.
pub struct RiotApi {
key: Mutex<String>,
host: String,
agent: Agent,
/// Send times of recent requests, oldest first.
sent: Mutex<VecDeque<Instant>>,
}
impl RiotApi {
/// `region` is the routing value, e.g. "europe".
pub fn new(api_key: String, region: &str) -> RiotApi {
RiotApi {
key: Mutex::new(api_key),
host: format!("https://{region}.api.riotgames.com"),
agent: agent(),
sent: Mutex::new(VecDeque::new()),
}
}
/// Replaces the key used by all later requests.
pub fn set_key(&self, api_key: String) {
*self.key.lock().unwrap_or_else(PoisonError::into_inner) = api_key;
}
fn get(&self, path_and_query: &str) -> Result<String, SourceError> {
let key = self
.key
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone();
if key.is_empty() {
return Err(SourceError::MissingKey);
}
let wait = reserve_slot(
&mut self.sent.lock().unwrap_or_else(PoisonError::into_inner),
Instant::now(),
);
thread::sleep(wait);
let url = format!("{}{path_and_query}", self.host);
get(&self.agent, &url, Some(&key), |body| body.read_to_string())
}
}
/// The HTTP client shared by the adapters.
pub(crate) fn agent() -> Agent {
Agent::config_builder()
.http_status_as_error(false)
.user_agent("arena-tracker") // the default UA is blocked by Cloudflare on some clients
.timeout_global(Some(Duration::from_secs(30)))
.build()
.into()
}
/// GETs `url` (sending the Riot token when given) and reads a successful body with `read`;
/// other statuses become `SourceError`s.
pub(crate) fn get<T>(
agent: &Agent,
url: &str,
riot_token: Option<&str>,
read: impl FnOnce(&mut Body) -> Result<T, ureq::Error>,
) -> Result<T, SourceError> {
let mut request = agent.get(url);
if let Some(token) = riot_token {
request = request.header("X-Riot-Token", token);
}
let mut response = request
.call()
.map_err(|e| SourceError::Network(e.to_string()))?;
match response.status().as_u16() {
200..=299 => read(response.body_mut()).map_err(|e| SourceError::Network(e.to_string())),
401 | 403 => Err(SourceError::InvalidKey),
404 => Err(SourceError::NotFound),
429 => Err(SourceError::RateLimited {
retry_after: response
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.trim().parse().ok())
.map_or(DEFAULT_RETRY_AFTER, Duration::from_secs),
}),
status => Err(SourceError::Other(format!("HTTP {status}"))),
}
}
impl MatchHistorySource for RiotApi {
fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result<Account, SourceError> {
let path = format!(
"/riot/account/v1/accounts/by-riot-id/{}/{}",
encode(game_name),
encode(tag_line)
);
decode_account(&self.get(&path)?)
}
fn match_ids(
&self,
puuid: &str,
queue_id: u32,
start: usize,
count: usize,
start_time_s: Option<i64>,
) -> Result<Vec<String>, SourceError> {
let mut path = format!(
"/lol/match/v5/matches/by-puuid/{}/ids?queue={queue_id}&start={start}&count={count}",
encode(puuid)
);
if let Some(t) = start_time_s {
path.push_str(&format!("&startTime={t}"));
}
decode_ids(&self.get(&path)?)
}
fn fetch_match(&self, match_id: &str) -> Result<String, SourceError> {
self.get(&format!("/lol/match/v5/matches/{}", encode(match_id)))
}
}
fn decode_account(body: &str) -> Result<Account, SourceError> {
serde_json::from_str(body).map_err(|e| SourceError::Other(format!("Compte illisible : {e}")))
}
fn decode_ids(body: &str) -> Result<Vec<String>, SourceError> {
serde_json::from_str(body)
.map_err(|e| SourceError::Other(format!("Liste de Parties illisible : {e}")))
}
/// Percent-encodes everything but RFC 3986 unreserved characters.
pub(crate) fn encode(segment: &str) -> String {
let mut out = String::new();
for byte in segment.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
out.push(byte as char)
}
_ => out.push_str(&format!("%{byte:02X}")),
}
}
out
}
/// Books the next request in the sliding windows and returns how long to wait before sending it.
fn reserve_slot(sent: &mut VecDeque<Instant>, now: Instant) -> Duration {
let longest = LIMITS[1].1;
while sent
.front()
.is_some_and(|&t| now.saturating_duration_since(t) >= longest)
{
sent.pop_front();
}
// A window of `max` requests is full when `max` requests are booked inside it; the new
// one may go once the oldest of them leaves.
let wait = LIMITS
.iter()
.filter(|&&(max, _)| sent.len() >= max)
.map(|&(max, window)| (sent[sent.len() - max] + window).saturating_duration_since(now))
.max()
.unwrap_or_default();
sent.push_back(now + wait);
wait
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn without_a_key_no_request_is_sent() {
let api = RiotApi::new(String::new(), "europe");
assert_eq!(
api.resolve_account("Joueur", "EUW"),
Err(SourceError::MissingKey)
);
assert_eq!(
api.match_ids("p", 1700, 0, 100, None),
Err(SourceError::MissingKey)
);
assert_eq!(api.fetch_match("EUW1_1"), Err(SourceError::MissingKey));
}
#[test]
fn the_key_can_be_replaced_without_rebuilding_the_adapter() {
let api = RiotApi::new(String::new(), "europe");
api.set_key("RGAPI-new".into());
assert_eq!(*api.key.lock().unwrap(), "RGAPI-new");
api.set_key(String::new());
assert_eq!(api.fetch_match("EUW1_1"), Err(SourceError::MissingKey));
}
#[test]
fn decodes_the_account_response() {
let account = decode_account(include_str!("../tests/fixtures/riot/account.json")).unwrap();
assert_eq!(
account,
Account {
puuid: "fixture-puuid-self".into(),
game_name: "Joueur".into(),
tag_line: "EUW".into(),
}
);
}
#[test]
fn decodes_a_match_id_list() {
assert_eq!(
decode_ids(r#"["EUW1_1","EUW1_2"]"#).unwrap(),
["EUW1_1", "EUW1_2"]
);
assert!(decode_ids("{}").is_err());
}
#[test]
fn path_segments_are_percent_encoded() {
assert_eq!(encode("Joueur"), "Joueur");
assert_eq!(encode("Été #1/é"), "%C3%89t%C3%A9%20%231%2F%C3%A9");
}
#[test]
fn throttle_spaces_requests_under_both_limits() {
let t0 = Instant::now();
let mut sent = VecDeque::new();
for _ in 0..20 {
assert_eq!(reserve_slot(&mut sent, t0), Duration::ZERO);
}
// 21st request waits for the 1 s window.
assert_eq!(reserve_slot(&mut sent, t0), Duration::from_secs(1));
// 100 requests fit in 120 s: spread over time so only the long window is full.
let mut sent = VecDeque::new();
for i in 0..100u64 {
let now = t0 + Duration::from_secs(i);
assert_eq!(reserve_slot(&mut sent, now), Duration::ZERO);
}
let now = t0 + Duration::from_secs(100);
assert_eq!(reserve_slot(&mut sent, now), Duration::from_secs(20));
// Once the oldest request left the window, no wait is needed.
let later = t0 + Duration::from_secs(121);
assert_eq!(reserve_slot(&mut sent, later), Duration::ZERO);
}
}
+135
View File
@@ -0,0 +1,135 @@
use std::ops::Range;
use std::path::Path;
use serde::Deserialize;
use crate::date::Date;
use crate::error::Error;
const DEFAULT_TABLE: &str = include_str!("default_seasons.toml");
#[derive(Clone, Debug, PartialEq)]
pub struct Season {
pub name: String,
pub start: Date,
/// Name of the game client's progression track holding this Season's Official Progress.
pub official_track: Option<String>,
}
#[derive(Deserialize)]
struct Table {
season: Vec<Entry>,
}
#[derive(Deserialize)]
struct Entry {
name: String,
start: toml::value::Datetime,
official_track: Option<String>,
}
/// The table shipped with the app, oldest first.
pub fn default_seasons() -> Vec<Season> {
parse(DEFAULT_TABLE).expect("the shipped Season table is valid")
}
/// Reads the user's Season table at `path`, first writing the shipped one if the file does
/// not exist so the user can edit it. Returns the Seasons sorted by start.
pub fn load_seasons(path: &Path) -> Result<Vec<Season>, Error> {
let io_error = |e: std::io::Error| Error::Config(format!("{} : {e}", path.display()));
if !path.exists() {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(io_error)?;
}
std::fs::write(path, DEFAULT_TABLE).map_err(io_error)?;
}
let text = std::fs::read_to_string(path).map_err(io_error)?;
parse(&text).map_err(|e| Error::Config(format!("{} : {e}", path.display())))
}
fn parse(text: &str) -> Result<Vec<Season>, String> {
let table: Table = toml::from_str(text).map_err(|e| e.to_string())?;
let mut seasons = Vec::new();
for entry in table.season {
let start = match entry.start {
toml::value::Datetime {
date: Some(d),
time: None,
offset: None,
} => Date {
year: i32::from(d.year),
month: d.month,
day: d.day,
},
_ => {
return Err(format!(
"« {} » : `start` doit être une date (AAAA-MM-JJ)",
entry.name
));
}
};
seasons.push(Season {
name: entry.name,
start,
official_track: entry.official_track,
});
}
seasons.sort_by_key(|s| s.start);
Ok(seasons)
}
/// The period of a Season in epoch ms: from its start up to the next Season's start
/// (exclusive); the last one is open-ended. `seasons` must be sorted by start.
pub(crate) fn period(seasons: &[Season], name: &str) -> Option<Range<i64>> {
let i = seasons.iter().position(|s| s.name == name)?;
let end = seasons
.get(i + 1)
.map_or(i64::MAX, |next| next.start.start_ms());
Some(seasons[i].start.start_ms()..end)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_shipped_table_lists_the_known_seasons() {
let seasons: Vec<_> = default_seasons()
.into_iter()
.map(|s| (s.name, s.start.to_string()))
.collect();
assert_eq!(
seasons,
[
("Saison 2025".into(), "05/03/2025".into()),
("Saison 1 2026".into(), "08/01/2026".into()),
("Saison 2 2026".into(), "29/04/2026".into()),
]
);
}
#[test]
fn the_shipped_table_carries_the_official_track_names() {
let tracks: Vec<_> = default_seasons()
.into_iter()
.map(|s| s.official_track)
.collect();
assert_eq!(
tracks,
[
Some("Cherry 2025 Champs Completed Track".into()),
Some("2026 Season 1 Champs Completed Track".into()),
Some("2026 Season 2 Champs Completed Track".into()),
]
);
}
#[test]
fn periods_run_to_the_next_start_and_the_last_is_open() {
let seasons = default_seasons();
let first = period(&seasons, "Saison 2025").unwrap();
assert_eq!(first.end, seasons[1].start.start_ms());
assert_eq!(period(&seasons, "Saison 2 2026").unwrap().end, i64::MAX);
assert!(period(&seasons, "Inconnue").is_none());
}
}
+380
View File
@@ -0,0 +1,380 @@
//! Challenge figures and champion statistics, computed on demand from stored Matches.
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::ops::Range;
use std::path::PathBuf;
use crate::champions::Champion;
use crate::date::Date;
use crate::error::Error;
use crate::model::{Format, Match};
use crate::seasons::{Season, period};
use crate::tracker::Tracker;
#[derive(Clone, Debug, PartialEq)]
pub enum SeasonScope {
/// By Season name.
Season(String),
AllSeasons,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Scope {
pub season: SeasonScope,
/// `None` = all Formats. Filters statistics only, never the Challenge.
pub format: Option<Format>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Statistics {
/// `None` in the all-Seasons view.
pub challenge: Option<ChallengeSummary>,
/// One per champion in the game, ordered by champion name.
pub rows: Vec<ChampionRow>,
pub charts: Charts,
/// Distinct Formats among all stored Matches of the Account, for the filter.
pub formats: Vec<Format>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ChallengeSummary {
pub completed: usize,
pub total: usize,
/// All Attempts, including those on champions not yet Completed.
pub attempts: usize,
/// Over Completed champions only.
pub average_attempts: Option<f64>,
pub first_tries: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChampionState {
Completed,
InProgress,
NeverPlayed,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ChampionRow {
pub champion: Champion,
/// Only when the file exists in the portraits dir.
pub portrait: Option<PathBuf>,
// In scope (Season and Format filter):
pub matches: usize,
pub best_placement: Option<u8>,
pub top1: usize,
pub wins: usize,
pub average_placement: Option<f64>,
pub last_match_ms: Option<i64>,
/// Season scope only, and not affected by the Format filter.
pub attempts: Option<usize>,
/// Season scope: always `Some`, not affected by the Format filter. All Seasons:
/// `Some(NeverPlayed)` for a champion with no stored Match, otherwise `None`.
pub state: Option<ChampionState>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Charts {
/// In scope: one entry per Placement from 1 to the highest seen, zero counts included.
pub placements: Vec<(u8, usize)>,
/// Season scope: the cumulative Completed count on each day a champion became Completed.
pub completed_over_time: Vec<(Date, usize)>,
/// Season scope: Completed champions that took 1, 2, 3, 4 and 5-or-more Attempts.
pub attempts_to_complete: [usize; 5],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Column {
Champion,
Matches,
BestPlacement,
Top1,
Wins,
AveragePlacement,
Attempts,
LastMatch,
State,
}
/// Sorts rows by a column. Rows with no value in it go last whatever the direction; ties
/// are broken by champion name.
pub fn sort_rows(rows: &mut [ChampionRow], column: Column, descending: bool) {
rows.sort_by(|a, b| {
let by_name = || {
collate(&a.champion.name)
.cmp(&collate(&b.champion.name))
.then(a.champion.id.cmp(&b.champion.id))
};
if column == Column::Champion {
return if descending {
by_name().reverse()
} else {
by_name()
};
}
match (value(a, column), value(b, column)) {
(Some(x), Some(y)) if descending => y.total_cmp(&x),
(Some(x), Some(y)) => x.total_cmp(&y),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => Ordering::Equal,
}
.then_with(by_name)
});
}
fn value(row: &ChampionRow, column: Column) -> Option<f64> {
match column {
Column::Champion => None,
Column::Matches => Some(row.matches as f64),
Column::BestPlacement => row.best_placement.map(f64::from),
Column::Top1 => Some(row.top1 as f64),
Column::Wins => Some(row.wins as f64),
Column::AveragePlacement => row.average_placement,
Column::Attempts => row.attempts.map(|n| n as f64),
Column::LastMatch => row.last_match_ms.map(|ms| ms as f64),
Column::State => row.state.map(|state| match state {
ChampionState::Completed => 0.0,
ChampionState::InProgress => 1.0,
ChampionState::NeverPlayed => 2.0,
}),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StateFilter {
All,
Completed,
/// In progress or never played.
Remaining,
NeverPlayed,
}
impl StateFilter {
/// A row with no state is only kept by `All`.
pub fn keeps(&self, row: &ChampionRow) -> bool {
match self {
StateFilter::All => true,
StateFilter::Completed => row.state == Some(ChampionState::Completed),
StateFilter::Remaining => matches!(
row.state,
Some(ChampionState::InProgress | ChampionState::NeverPlayed)
),
StateFilter::NeverPlayed => row.state == Some(ChampionState::NeverPlayed),
}
}
}
/// Alphabetical order for French names: case and accents do not count.
fn collate(name: &str) -> String {
name.to_lowercase()
.chars()
.map(|c| match c {
'à' | 'â' | 'ä' => 'a',
'é' | 'è' | 'ê' | 'ë' => 'e',
'î' | 'ï' => 'i',
'ô' | 'ö' => 'o',
'ù' | 'û' | 'ü' => 'u',
'ç' => 'c',
other => other,
})
.collect()
}
#[derive(Default)]
struct Progress {
attempts: usize,
completed_at_ms: Option<i64>,
}
/// Attempts per champion from Matches in chronological order: a champion's Matches count
/// up to and including its first top 1.
fn progress_by_champion(matches: &[&Match]) -> HashMap<u32, Progress> {
let mut progress: HashMap<u32, Progress> = HashMap::new();
for m in matches {
let p = progress.entry(m.champion_id).or_default();
if p.completed_at_ms.is_none() {
p.attempts += 1;
if m.placement == 1 {
p.completed_at_ms = Some(m.started_at_ms);
}
}
}
progress
}
/// `matches` are all the Account's stored Matches, oldest first. `period` is the Season's
/// period (`None` = all Seasons). The Challenge only ever looks at the Season, never at `format`.
pub(crate) fn compute(
catalog: Vec<Champion>,
matches: &[Match],
period: Option<Range<i64>>,
format: Option<Format>,
) -> Statistics {
// A champion played but missing from the catalog still counts.
let mut champions = catalog;
let mut known: HashSet<u32> = champions.iter().map(|c| c.id).collect();
for m in matches {
if known.insert(m.champion_id) {
champions.push(Champion {
id: m.champion_id,
key: m.champion_name.clone(),
name: m.champion_name.clone(),
});
}
}
champions.sort_by_cached_key(|c| (collate(&c.name), c.id));
let in_period: Vec<&Match> = matches
.iter()
.filter(|m| period.as_ref().is_none_or(|p| p.contains(&m.started_at_ms)))
.collect();
let in_scope: Vec<&Match> = in_period
.iter()
.copied()
.filter(|m| format.is_none_or(|f| m.format == f))
.collect();
let mut by_champion: HashMap<u32, Vec<&Match>> = HashMap::new();
for m in &in_scope {
by_champion.entry(m.champion_id).or_default().push(m);
}
let progress = period.is_some().then(|| progress_by_champion(&in_period));
let ever_played: HashSet<u32> = matches.iter().map(|m| m.champion_id).collect();
let rows: Vec<ChampionRow> = champions
.into_iter()
.map(|champion| {
let mine = by_champion.get(&champion.id).map_or(&[][..], Vec::as_slice);
let (attempts, state) = match &progress {
Some(progress) => {
let p = progress.get(&champion.id);
let state = match p {
Some(Progress {
completed_at_ms: Some(_),
..
}) => ChampionState::Completed,
Some(_) => ChampionState::InProgress,
None => ChampionState::NeverPlayed,
};
(Some(p.map_or(0, |p| p.attempts)), Some(state))
}
None => (
None,
(!ever_played.contains(&champion.id)).then_some(ChampionState::NeverPlayed),
),
};
ChampionRow {
portrait: None,
matches: mine.len(),
best_placement: mine.iter().map(|m| m.placement).min(),
top1: mine.iter().filter(|m| m.placement == 1).count(),
wins: mine.iter().filter(|m| m.win).count(),
average_placement: (!mine.is_empty()).then(|| {
mine.iter().map(|m| f64::from(m.placement)).sum::<f64>() / mine.len() as f64
}),
last_match_ms: mine.iter().map(|m| m.started_at_ms).max(),
attempts,
state,
champion,
}
})
.collect();
let highest = in_scope.iter().map(|m| m.placement).max().unwrap_or(0);
let placements = (1..=highest)
.map(|p| (p, in_scope.iter().filter(|m| m.placement == p).count()))
.collect();
let mut challenge = None;
let mut completed_over_time = Vec::new();
let mut attempts_to_complete = [0; 5];
if let Some(progress) = &progress {
let completed: Vec<(usize, i64)> = progress
.values()
.filter_map(|p| Some((p.attempts, p.completed_at_ms?)))
.collect();
challenge = Some(ChallengeSummary {
completed: completed.len(),
total: rows.len(),
attempts: progress.values().map(|p| p.attempts).sum(),
average_attempts: (!completed.is_empty()).then(|| {
completed.iter().map(|(n, _)| n).sum::<usize>() as f64 / completed.len() as f64
}),
first_tries: completed.iter().filter(|(n, _)| *n == 1).count(),
});
let mut per_day: BTreeMap<Date, usize> = BTreeMap::new();
for &(attempts, ms) in &completed {
*per_day.entry(Date::from_ms(ms)).or_default() += 1;
attempts_to_complete[attempts.min(5) - 1] += 1;
}
let mut cumulative = 0;
completed_over_time = per_day
.into_iter()
.map(|(day, n)| {
cumulative += n;
(day, cumulative)
})
.collect();
}
let mut formats: Vec<Format> = matches.iter().map(|m| m.format).collect();
formats.sort();
formats.dedup();
Statistics {
challenge,
rows,
charts: Charts {
placements,
completed_over_time,
attempts_to_complete,
},
formats,
}
}
impl Tracker {
/// Replaces the Season table; Matches are assigned to Seasons on demand, so already
/// stored Matches move accordingly.
pub fn with_seasons(mut self, mut seasons: Vec<Season>) -> Tracker {
seasons.sort_by_key(|s| s.start);
self.seasons = seasons;
self
}
/// Oldest first.
pub fn seasons(&self) -> Vec<Season> {
self.seasons.clone()
}
/// The Season containing `now_ms`.
pub fn current_season(&self, now_ms: i64) -> Option<Season> {
self.seasons
.iter()
.rev()
.find(|s| s.start.start_ms() <= now_ms)
.cloned()
}
pub fn statistics(&self, puuid: &str, scope: &Scope) -> Result<Statistics, Error> {
let season_period = match &scope.season {
SeasonScope::AllSeasons => None,
SeasonScope::Season(name) => Some(
period(&self.seasons, name).ok_or_else(|| Error::UnknownSeason(name.clone()))?,
),
};
let mut stats = compute(
self.cached_champions()?,
&self.matches(puuid)?,
season_period,
scope.format,
);
if let Some((_, dir)) = &self.champions {
for row in &mut stats.rows {
let path = dir.join(format!("{}.png", row.champion.key));
row.portrait = path.is_file().then_some(path);
}
}
Ok(stats)
}
}
+492
View File
@@ -0,0 +1,492 @@
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::thread;
use rusqlite::{Connection, OptionalExtension, Row, params};
use serde::Deserialize;
use crate::champions::ChampionSource;
use crate::client::GameClientSource;
use crate::error::{Error, SourceError};
use crate::follow::Follow;
use crate::model::{Account, Format, Match, SyncProgress, SyncReport};
use crate::seasons::{Season, default_seasons};
/// Port: where Match history comes from. Real adapter: `RiotApi`.
pub trait MatchHistorySource: Send + Sync {
fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result<Account, SourceError>;
/// One page of Match ids for one queue, newest first. `start_time_s`: only Matches
/// started at or after this epoch second.
fn match_ids(
&self,
puuid: &str,
queue_id: u32,
start: usize,
count: usize,
start_time_s: Option<i64>,
) -> Result<Vec<String>, SourceError>;
/// The raw Match payload (JSON text) exactly as the API returned it.
fn fetch_match(&self, match_id: &str) -> Result<String, SourceError>;
}
impl<T: MatchHistorySource + ?Sized> MatchHistorySource for Arc<T> {
fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result<Account, SourceError> {
(**self).resolve_account(game_name, tag_line)
}
fn match_ids(
&self,
puuid: &str,
queue_id: u32,
start: usize,
count: usize,
start_time_s: Option<i64>,
) -> Result<Vec<String>, SourceError> {
(**self).match_ids(puuid, queue_id, start, count, start_time_s)
}
fn fetch_match(&self, match_id: &str) -> Result<String, SourceError> {
(**self).fetch_match(match_id)
}
}
const SCHEMA: &str = "
PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS accounts (
puuid TEXT PRIMARY KEY,
game_name TEXT NOT NULL,
tag_line TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS matches (
puuid TEXT NOT NULL,
match_id TEXT NOT NULL,
queue_id INTEGER NOT NULL,
champion_id INTEGER NOT NULL,
champion_name TEXT NOT NULL,
placement INTEGER NOT NULL,
win INTEGER NOT NULL,
started_at_ms INTEGER NOT NULL,
raw TEXT NOT NULL,
PRIMARY KEY (puuid, match_id)
);
CREATE TABLE IF NOT EXISTS champions (
id INTEGER PRIMARY KEY,
key TEXT NOT NULL,
name TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS meta (
name TEXT PRIMARY KEY,
value TEXT NOT NULL
);";
/// Arena queues Riot lists Matches under (the PBE queue 1704 is left out on purpose).
const QUEUES: [u32; 4] = [1700, 1710, 1740, 1750];
const PAGE_SIZE: usize = 100;
const RATE_LIMIT_RETRIES: usize = 5;
/// A Match is published when the whole game ends, so one that started before the newest
/// stored Match (a player eliminated early who queued again) can show up later.
const OVERLAP_S: i64 = 48 * 3600;
pub struct Tracker {
db: Mutex<Connection>,
history: Box<dyn MatchHistorySource>,
pub(crate) seasons: Vec<Season>,
pub(crate) champions: Option<(Box<dyn ChampionSource>, PathBuf)>,
pub(crate) client: Option<Box<dyn GameClientSource>>,
pub(crate) follow: Mutex<Follow>,
/// Held for a whole `sync`: a second one waits for the first instead of importing in parallel.
sync_lock: Mutex<()>,
}
impl Tracker {
pub fn open(db_path: &Path, history: Box<dyn MatchHistorySource>) -> Result<Tracker, Error> {
let db = Connection::open(db_path)?;
db.execute_batch(SCHEMA)?;
Ok(Tracker {
db: Mutex::new(db),
history,
seasons: default_seasons(),
champions: None,
client: None,
follow: Mutex::default(),
sync_lock: Mutex::new(()),
})
}
/// Imports every Arena Match the source holds for the Account with this Riot ID
/// (`GameName#TAG`, split on the last `#`).
pub fn sync(
&self,
riot_id: &str,
on_progress: &mut dyn FnMut(SyncProgress),
) -> Result<SyncReport, Error> {
let _serial = self
.sync_lock
.lock()
.unwrap_or_else(PoisonError::into_inner);
let (game_name, tag_line) = riot_id
.trim()
.rsplit_once('#')
.filter(|(name, tag)| !name.is_empty() && !tag.is_empty())
.ok_or_else(|| Error::InvalidRiotId(riot_id.into()))?;
let account = with_retry(|| self.history.resolve_account(game_name, tag_line))?;
// shortcut: Riot API puuids are scoped to the API key's application, so the same Riot ID under another key becomes a second Account; merging them safely needs proof of identity.
self.db().execute(
"INSERT INTO accounts (puuid, game_name, tag_line) VALUES (?1, ?2, ?3)
ON CONFLICT (puuid) DO UPDATE SET game_name = excluded.game_name, tag_line = excluded.tag_line",
params![account.puuid, account.game_name, account.tag_line],
)?;
// Only the Matches since the last complete sync can be missing. The mark moves when a
// sync completes, never as Matches get stored, so a cut sync lists the same ones again.
let since_s = self
.synced_until_ms(&account.puuid)?
.map(|ms| ms / 1000 - OVERLAP_S);
let mut known = self.match_ids_stored(&account.puuid)?;
let mut to_fetch = self.list_match_ids(&account.puuid, since_s)?;
to_fetch.retain(|id| known.insert(id.clone()));
let total = to_fetch.len();
on_progress(SyncProgress {
fetched: 0,
to_fetch: total,
});
let mut added = 0;
for (i, match_id) in to_fetch.iter().enumerate() {
// Stored at once, so an interrupted import loses nothing.
if self.fetch_and_store(&account.puuid, match_id)? == Fetched::Added {
added += 1;
}
on_progress(SyncProgress {
fetched: i + 1,
to_fetch: total,
});
}
if let Some(newest_ms) = self.latest_start_ms(&account.puuid)? {
self.db().execute(
"INSERT OR REPLACE INTO meta (name, value) VALUES (?1, ?2)",
params![synced_until_key(&account.puuid), newest_ms.to_string()],
)?;
}
let stored = self.match_count(&account.puuid)?;
self.clear_problem(added);
Ok(SyncReport {
account,
added,
stored,
})
}
/// Fetches one Match by id and stores it. A Match Riot does not have or that cannot be
/// read is skipped rather than failing the caller: one bad id must not block the rest.
pub(crate) fn fetch_and_store(&self, puuid: &str, match_id: &str) -> Result<Fetched, Error> {
let raw = match with_retry(|| self.history.fetch_match(match_id)) {
Ok(raw) => raw,
Err(SourceError::NotFound) => return Ok(Fetched::NotFound),
Err(e) => return Err(e.into()),
};
let Ok(Some((m, queue_id))) = decode_match(&raw, puuid) else {
return Ok(Fetched::Ignored);
};
let inserted = insert_match(&self.db(), puuid, &m, queue_id, &raw)?;
Ok(if inserted {
Fetched::Added
} else {
Fetched::Known
})
}
pub fn accounts(&self) -> Result<Vec<Account>, Error> {
let db = self.db();
let mut stmt = db.prepare(
"SELECT puuid, game_name, tag_line FROM accounts ORDER BY game_name, tag_line",
)?;
let accounts = stmt
.query_map([], account_from_row)?
.collect::<Result<_, _>>()?;
Ok(accounts)
}
/// Stored Matches of the Account, oldest first.
pub fn matches(&self, puuid: &str) -> Result<Vec<Match>, Error> {
let db = self.db();
let mut stmt = db.prepare(
"SELECT match_id, queue_id, champion_id, champion_name, placement, win, started_at_ms
FROM matches WHERE puuid = ?1 ORDER BY started_at_ms, match_id",
)?;
let matches = stmt
.query_map([puuid], |row| {
let queue_id: u32 = row.get(1)?;
Ok(Match {
match_id: row.get(0)?,
format: Format::from_queue(queue_id).unwrap_or(Format::Other(queue_id)),
champion_id: row.get(2)?,
champion_name: row.get(3)?,
placement: row.get(4)?,
win: row.get(5)?,
started_at_ms: row.get(6)?,
})
})?
.collect::<Result<_, _>>()?;
Ok(matches)
}
pub fn match_count(&self, puuid: &str) -> Result<usize, Error> {
Ok(self.db().query_row(
"SELECT COUNT(*) FROM matches WHERE puuid = ?1",
[puuid],
|row| row.get::<_, i64>(0),
)? as usize)
}
/// The lock is only ever held around one short DB operation, never across a source call.
pub(crate) fn db(&self) -> MutexGuard<'_, Connection> {
self.db.lock().unwrap_or_else(PoisonError::into_inner)
}
fn synced_until_ms(&self, puuid: &str) -> Result<Option<i64>, Error> {
let mark: Option<String> = self
.db()
.query_row(
"SELECT value FROM meta WHERE name = ?1",
[synced_until_key(puuid)],
|row| row.get(0),
)
.optional()?;
Ok(mark.and_then(|ms| ms.parse().ok()))
}
/// The platform prefix of this Account's Match ids (e.g. "EUW1"), from its latest Match.
pub(crate) fn platform_of(&self, puuid: &str) -> Result<Option<String>, Error> {
let id: Option<String> = self
.db()
.query_row(
"SELECT match_id FROM matches WHERE puuid = ?1 ORDER BY started_at_ms DESC LIMIT 1",
[puuid],
|row| row.get(0),
)
.optional()?;
Ok(id.and_then(|id| id.split_once('_').map(|(platform, _)| platform.into())))
}
fn latest_start_ms(&self, puuid: &str) -> Result<Option<i64>, Error> {
Ok(self.db().query_row(
"SELECT MAX(started_at_ms) FROM matches WHERE puuid = ?1",
[puuid],
|row| row.get(0),
)?)
}
fn match_ids_stored(&self, puuid: &str) -> Result<HashSet<String>, Error> {
let db = self.db();
let mut stmt = db.prepare("SELECT match_id FROM matches WHERE puuid = ?1")?;
let ids = stmt
.query_map([puuid], |row| row.get(0))?
.collect::<Result<_, _>>()?;
Ok(ids)
}
fn list_match_ids(&self, puuid: &str, since_s: Option<i64>) -> Result<Vec<String>, Error> {
let mut ids = Vec::new();
for queue_id in QUEUES {
let mut start = 0;
loop {
let page = with_retry(|| {
self.history
.match_ids(puuid, queue_id, start, PAGE_SIZE, since_s)
})?;
let full_page = page.len() == PAGE_SIZE;
ids.extend(page);
if !full_page {
break;
}
start += PAGE_SIZE;
}
}
Ok(ids)
}
}
pub(crate) fn account_from_row(row: &Row) -> rusqlite::Result<Account> {
Ok(Account {
puuid: row.get(0)?,
game_name: row.get(1)?,
tag_line: row.get(2)?,
})
}
fn synced_until_key(puuid: &str) -> String {
format!("synced_until_ms:{puuid}")
}
/// What became of one Match fetched by id.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Fetched {
Added,
/// Already stored.
Known,
/// Not an Arena Match of this Account, or unreadable.
Ignored,
/// Riot does not have it (yet).
NotFound,
}
/// Waits out `RateLimited` and retries the same call, giving up after a few attempts.
fn with_retry<T>(mut call: impl FnMut() -> Result<T, SourceError>) -> Result<T, SourceError> {
for _ in 0..RATE_LIMIT_RETRIES {
match call() {
Err(SourceError::RateLimited { retry_after }) => thread::sleep(retry_after),
result => return result,
}
}
call()
}
/// Returns whether the Match was new.
fn insert_match(
db: &Connection,
puuid: &str,
m: &Match,
queue_id: u32,
raw: &str,
) -> rusqlite::Result<bool> {
let inserted = db.execute(
"INSERT OR IGNORE INTO matches
(puuid, match_id, queue_id, champion_id, champion_name, placement, win, started_at_ms, raw)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
params![
puuid,
m.match_id,
queue_id,
m.champion_id,
m.champion_name,
m.placement,
m.win,
m.started_at_ms,
raw
],
)?;
Ok(inserted == 1)
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Payload {
metadata: PayloadMetadata,
info: PayloadInfo,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PayloadMetadata {
match_id: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PayloadInfo {
queue_id: u32,
game_mode: String,
game_start_timestamp: i64,
/// Read one by one: only the Account's own entry has to be complete.
participants: Vec<serde_json::Value>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Participant {
champion_id: u32,
champion_name: String,
placement: u8,
win: bool,
}
/// The Match (with its raw queue id) the Account played in a Riot match-v5 payload, or
/// `None` when the payload is not an Arena Match of this Account.
fn decode_match(raw: &str, puuid: &str) -> Result<Option<(Match, u32)>, serde_json::Error> {
let payload: Payload = serde_json::from_str(raw)?;
let info = payload.info;
if info.game_mode != "CHERRY" {
return Ok(None);
}
let Some(format) = Format::from_queue(info.queue_id) else {
return Ok(None);
};
let Some(me) = info.participants.into_iter().find(|p| p["puuid"] == puuid) else {
return Ok(None);
};
let me: Participant = serde_json::from_value(me)?;
let m = Match {
match_id: payload.metadata.match_id,
format,
champion_id: me.champion_id,
champion_name: me.champion_name,
placement: me.placement,
win: me.win,
started_at_ms: info.game_start_timestamp,
};
Ok(Some((m, info.queue_id)))
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
const FIXTURE: &str = include_str!("../tests/fixtures/riot/match_1740_EUW1_9000000005.json");
#[test]
fn decodes_the_accounts_participant() {
let (m, queue_id) = decode_match(FIXTURE, "fixture-puuid-self")
.unwrap()
.unwrap();
assert_eq!(queue_id, 1740);
assert_eq!(
m,
Match {
match_id: "EUW1_9000000005".into(),
format: Format::BraveryArena,
champion_id: 19,
champion_name: "Warwick".into(),
placement: 5,
win: false,
started_at_ms: 1794424080842,
}
);
}
#[test]
fn ignores_payloads_without_the_account() {
assert!(decode_match(FIXTURE, "someone-else").unwrap().is_none());
}
#[test]
fn raw_payload_is_stored_unmodified_and_only_once() {
let db = Connection::open_in_memory().unwrap();
db.execute_batch(SCHEMA).unwrap();
let (m, queue_id) = decode_match(FIXTURE, "fixture-puuid-self")
.unwrap()
.unwrap();
assert!(insert_match(&db, "p", &m, queue_id, FIXTURE).unwrap());
assert!(!insert_match(&db, "p", &m, queue_id, FIXTURE).unwrap());
let raw: String = db
.query_row("SELECT raw FROM matches", [], |row| row.get(0))
.unwrap();
assert_eq!(raw, FIXTURE);
}
#[test]
fn rate_limit_is_retried_a_few_times_then_reported() {
let mut calls = 0;
let result: Result<(), _> = with_retry(|| {
calls += 1;
Err(SourceError::RateLimited {
retry_after: Duration::ZERO,
})
});
assert!(matches!(result, Err(SourceError::RateLimited { .. })));
assert_eq!(calls, RATE_LIMIT_RETRIES + 1);
}
}