Import, statistics page and game client following (#4 to #12, #15) #25

Merged
nessar merged 5 commits from feat/import-statistics-client-following into main 2026-11-16 23:48:31 +01:00
46 changed files with 11298 additions and 17 deletions

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
# Only the core crate is checked: the app crate (GPUI) only builds on Windows (ADR-0003).
name: CI
on:
pull_request:
push:
branches:
- main
jobs:
core:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust stable (rustfmt, clippy)
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --component rustfmt,clippy
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Format
run: cargo fmt -p arena-tracker-core --check
- name: Clippy
run: cargo clippy -p arena-tracker-core --all-targets --locked -- -D warnings
- name: Tests
run: cargo test -p arena-tracker-core --locked
Generated
+173
View File
@@ -213,6 +213,17 @@ dependencies = [
[[package]]
name = "arena-tracker-core"
version = "0.1.0"
dependencies = [
"base64 0.23.1",
"rusqlite",
"rustls",
"serde",
"serde_json",
"tempfile",
"toml 1.2.1+spec-1.1.0",
"tungstenite",
"ureq",
]
[[package]]
name = "arg_enum_proc_macro"
@@ -1167,6 +1178,12 @@ dependencies = [
"linktime-proc-macro",
]
[[package]]
name = "data-encoding"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
[[package]]
name = "data-url"
version = "0.3.2"
@@ -1533,6 +1550,18 @@ dependencies = [
"zune-inflate",
]
[[package]]
name = "fallible-iterator"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
[[package]]
name = "fallible-streaming-iterator"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
[[package]]
name = "fastrand"
version = "2.5.0"
@@ -2709,6 +2738,15 @@ dependencies = [
"foldhash",
]
[[package]]
name = "hashlink"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb"
dependencies = [
"hashbrown 0.17.1",
]
[[package]]
name = "heapless"
version = "0.9.3"
@@ -3416,6 +3454,17 @@ dependencies = [
"libc",
]
[[package]]
name = "libsqlite3-sys"
version = "0.40.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b06e69070b7e12262b0cd90832f0a7396f142a2b330181255562decf9f0c6215"
dependencies = [
"cc",
"pkg-config",
"vcpkg",
]
[[package]]
name = "linebender_resource_handle"
version = "0.1.1"
@@ -5292,6 +5341,30 @@ dependencies = [
"memchr",
]
[[package]]
name = "rsqlite-vfs"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "rusqlite"
version = "0.43.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f172c4812a19b26d1c23cdb0070e69db335503dfa378b910eb857386e5b8beba"
dependencies = [
"bitflags 2.13.2",
"fallible-iterator",
"fallible-streaming-iterator",
"hashlink",
"libsqlite3-sys",
"smallvec",
"sqlite-wasm-rs",
]
[[package]]
name = "rust-embed"
version = "8.14.0"
@@ -5423,6 +5496,7 @@ version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"log",
"once_cell",
"ring",
"rustls-pki-types",
@@ -5751,6 +5825,17 @@ dependencies = [
"serde",
]
[[package]]
name = "sha1"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"digest 0.11.3",
]
[[package]]
name = "sha1_smol"
version = "1.0.1"
@@ -5954,6 +6039,16 @@ dependencies = [
"bitflags 2.13.2",
]
[[package]]
name = "sqlite-wasm-rs"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cd504cecbfe7eef649988840f9a6cb768d11085efec138f8e99f160632d867"
dependencies = [
"cc",
"rsqlite-vfs",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
@@ -6581,6 +6676,25 @@ dependencies = [
"core_maths",
]
[[package]]
name = "tungstenite"
version = "0.30.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22"
dependencies = [
"bytes",
"data-encoding",
"http",
"httparse",
"log",
"rand 0.10.4",
"rustls",
"rustls-pki-types",
"sha1",
"thiserror 2.0.21",
"webpki-roots 0.26.11",
]
[[package]]
name = "typenum"
version = "1.20.1"
@@ -6676,6 +6790,35 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "ureq"
version = "3.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d"
dependencies = [
"base64 0.23.1",
"flate2",
"log",
"percent-encoding",
"rustls",
"rustls-pki-types",
"ureq-proto",
"utf8-zero",
"webpki-roots 1.0.12",
]
[[package]]
name = "ureq-proto"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3"
dependencies = [
"base64 0.23.1",
"http",
"httparse",
"log",
]
[[package]]
name = "url"
version = "2.5.8"
@@ -6748,6 +6891,12 @@ version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
[[package]]
name = "utf8-zero"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
[[package]]
name = "utf8_iter"
version = "1.1.0"
@@ -6787,6 +6936,12 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "version_check"
version = "0.9.5"
@@ -7052,6 +7207,24 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "webpki-roots"
version = "0.26.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
dependencies = [
"webpki-roots 1.0.12",
]
[[package]]
name = "webpki-roots"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "weezl"
version = "0.1.12"
+20
View File
@@ -17,6 +17,20 @@ Depuis WSL, à la racine du dépôt :
La première compilation de GPUI prend plusieurs minutes.
## Configuration
L'application lit `%APPDATA%\arena-tracker\config.toml`, en dehors du dépôt. Le fichier est facultatif : au premier lancement, l'application demande la clé API Riot (à demander sur le portail développeur Riot), l'enregistre dans ce fichier et la prend en compte sans redémarrage. La clé se change ensuite dans `Paramètres`. Exemple de fichier, avec des valeurs fictives :
```toml
riot_api_key = "RGAPI-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" # clé du portail développeur Riot
riot_id = "NomDeJeu#TAG" # facultatif
region = "europe" # facultatif, "europe" par défaut
```
Le Compte connecté au client de League of Legends est suivi automatiquement. `riot_id` ne sert que de repli, quand le client est fermé au premier lancement.
La base des Parties, `arena-tracker.db`, est créée dans le même dossier, ainsi que `seasons.toml`, la table des Saisons : elle peut être modifiée, et les changements sont pris en compte au lancement suivant. La clé API ne doit jamais être commitée.
## Tests
Les tests du coeur (`arena-tracker-core`, sans dépendance graphique) s'exécutent nativement dans WSL :
@@ -24,3 +38,9 @@ Les tests du coeur (`arena-tracker-core`, sans dépendance graphique) s'exécute
```
cargo test
```
## Intégration continue
- À chaque pull request et à chaque push sur `main`, un workflow Gitea Actions (`.gitea/workflows/ci.yml`) vérifie le formatage (`cargo fmt --check`), lance le linter (`cargo clippy`, avertissements traités comme des erreurs) et exécute les tests (`cargo test`) du coeur `arena-tracker-core`, avec `--locked` : un `Cargo.lock` non à jour fait échouer la CI.
- La crate applicative (GPUI) n'est pas compilée en CI, car elle ne se compile que sous Windows (ADR-0003). La CI ne compile ni ne publie l'exécutable Windows.
- Le workflow nécessite un runner Linux (`act_runner`) enregistré sur l'instance Gitea.
+254
View File
@@ -0,0 +1,254 @@
//! The champion table: one row per champion, virtualised by the component.
use arena_tracker_core::{ChampionRow, Column as SortKey, Date, sort_rows};
use gpui_kit::component::table::{Column, ColumnSort, TableDelegate, TableState};
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::*;
use crate::text::{decimal, state_label};
struct Spec {
title: &'static str,
key: SortKey,
width: f32,
numeric: bool,
}
const fn spec(title: &'static str, key: SortKey, width: f32, numeric: bool) -> Spec {
Spec {
title,
key,
width,
numeric,
}
}
const SPECS: [Spec; 9] = [
spec("Champion", SortKey::Champion, 220., false),
spec("État", SortKey::State, 110., false),
spec("Parties", SortKey::Matches, 90., true),
spec("Meilleur Placement", SortKey::BestPlacement, 160., true),
spec("Top 1", SortKey::Top1, 80., true),
spec("Victoires", SortKey::Wins, 100., true),
spec("Placement moyen", SortKey::AveragePlacement, 150., true),
spec("Tentatives", SortKey::Attempts, 110., true),
spec("Dernière Partie", SortKey::LastMatch, 150., true),
];
/// Hidden outside a Season, where there is no Challenge.
const ATTEMPTS: usize = 7;
const PORTRAIT: f32 = 24.;
pub struct ChampionTable {
rows: Vec<ChampionRow>,
in_season: bool,
/// The user's choice; `None` means the default for the view.
sort: Option<(SortKey, bool)>,
}
impl ChampionTable {
pub fn new() -> ChampionTable {
ChampionTable {
rows: Vec::new(),
in_season: false,
sort: None,
}
}
/// Replaces the rows (already filtered) and keeps them sorted.
pub fn set_rows(&mut self, rows: Vec<ChampionRow>, in_season: bool) {
self.rows = rows;
self.in_season = in_season;
self.resort();
}
/// Column and `descending`.
fn sorted_by(&self) -> (SortKey, bool) {
self.sort
.filter(|(key, _)| self.in_season || *key != SortKey::Attempts)
.unwrap_or(if self.in_season {
(SortKey::Attempts, true)
} else {
(SortKey::Matches, true)
})
}
fn resort(&mut self) {
let (key, descending) = self.sorted_by();
sort_rows(&mut self.rows, key, descending);
}
fn spec(&self, col_ix: usize) -> &'static Spec {
&SPECS[col_ix + usize::from(!self.in_season && col_ix >= ATTEMPTS)]
}
}
fn or_dash<T: ToString>(value: Option<T>) -> String {
value.map_or_else(|| "-".into(), |v| v.to_string())
}
fn cell_text(row: &ChampionRow, key: SortKey) -> String {
match key {
SortKey::State => state_label(row.state).into(),
SortKey::Champion => row.champion.name.clone(),
SortKey::Matches => row.matches.to_string(),
SortKey::BestPlacement => or_dash(row.best_placement),
SortKey::Top1 => row.top1.to_string(),
SortKey::Wins => row.wins.to_string(),
SortKey::AveragePlacement => row.average_placement.map_or("-".into(), |a| decimal(a, 1)),
SortKey::Attempts => or_dash(row.attempts),
SortKey::LastMatch => or_dash(row.last_match_ms.map(Date::from_ms)),
}
}
impl TableDelegate for ChampionTable {
fn columns_count(&self, _: &App) -> usize {
SPECS.len() - usize::from(!self.in_season)
}
fn rows_count(&self, _: &App) -> usize {
self.rows.len()
}
fn column(&self, col_ix: usize, _: &App) -> Column {
let spec = self.spec(col_ix);
let column = Column::new(spec.title, spec.title).width(px(spec.width));
let column = if spec.numeric {
column.text_right()
} else {
column
};
let (sorted_key, descending) = self.sorted_by();
match spec.key {
key if key == sorted_key && descending => column.descending(),
key if key == sorted_key => column.ascending(),
_ => column.sortable(),
}
}
// The table cycles a header descending, ascending, then back to `Default`: the view's
// default order.
fn perform_sort(
&mut self,
col_ix: usize,
sort: ColumnSort,
_: &mut Window,
cx: &mut Context<TableState<Self>>,
) {
let key = self.spec(col_ix).key;
self.sort = match sort {
ColumnSort::Default => None,
ColumnSort::Ascending => Some((key, false)),
ColumnSort::Descending => Some((key, true)),
};
self.resort();
cx.notify();
}
fn render_td(
&mut self,
row_ix: usize,
col_ix: usize,
_: &mut Window,
cx: &mut Context<TableState<Self>>,
) -> impl IntoElement {
let row = &self.rows[row_ix];
let key = self.spec(col_ix).key;
if key != SortKey::Champion {
return cell_text(row, key).into_any_element();
}
let portrait = match &row.portrait {
Some(path) => img(path.clone()).size(px(PORTRAIT)).into_any_element(),
None => div()
.size(px(PORTRAIT))
.bg(cx.theme().border)
.into_any_element(),
};
div()
.h_flex()
.items_center()
.gap_2()
.child(portrait)
.child(row.champion.name.clone())
.into_any_element()
}
fn render_empty(
&mut self,
_: &mut Window,
cx: &mut Context<TableState<Self>>,
) -> impl IntoElement {
div()
.size_full()
.flex()
.items_center()
.justify_center()
.text_color(cx.theme().muted_foreground)
.child("Aucun champion à afficher")
}
}
#[cfg(test)]
mod tests {
use arena_tracker_core::{Champion, ChampionRow, ChampionState};
// Explicit imports: a glob of `gpui_kit` would shadow the built-in `#[test]`.
use super::{ATTEMPTS, ChampionTable, SortKey, cell_text};
fn row(name: &str) -> ChampionRow {
ChampionRow {
champion: Champion {
id: 1,
key: name.into(),
name: name.into(),
},
portrait: None,
matches: 0,
best_placement: None,
top1: 0,
wins: 0,
average_placement: None,
last_match_ms: None,
attempts: None,
state: None,
}
}
#[test]
fn missing_values_show_a_dash() {
let row = row("Ahri");
for key in [
SortKey::BestPlacement,
SortKey::AveragePlacement,
SortKey::Attempts,
SortKey::LastMatch,
] {
assert_eq!(cell_text(&row, key), "-");
}
assert_eq!(cell_text(&row, SortKey::State), "");
}
#[test]
fn values_are_formatted_in_french() {
let row = ChampionRow {
matches: 3,
best_placement: Some(1),
average_placement: Some(2.5),
last_match_ms: Some(1_700_000_000_000),
attempts: Some(2),
state: Some(ChampionState::Completed),
..row("Ahri")
};
assert_eq!(cell_text(&row, SortKey::AveragePlacement), "2,5");
assert_eq!(cell_text(&row, SortKey::LastMatch), "14/11/2023");
assert_eq!(cell_text(&row, SortKey::Attempts), "2");
assert_eq!(cell_text(&row, SortKey::State), "Validé");
}
#[test]
fn attempts_column_is_hidden_outside_a_season() {
let mut table = ChampionTable::new();
assert_eq!(table.spec(ATTEMPTS).key, SortKey::LastMatch);
table.set_rows(vec![], true);
assert_eq!(table.spec(ATTEMPTS).key, SortKey::Attempts);
}
}
+175 -4
View File
@@ -1,21 +1,179 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod champion_table;
mod settings;
mod stats_page;
mod text;
mod worker;
use std::sync::Arc;
use std::sync::mpsc::{self, Sender};
use arena_tracker_core::{
Config, DataDragon, LeagueClient, RiotApi, Tracker, data_dir, default_seasons, load_seasons,
};
use gpui_kit::component::*;
use gpui_kit::*;
struct RootView;
use settings::{KeyEvent, KeyForm, KeyStore};
use stats_page::{PageEvent, StatsPage};
use worker::{Msg, spawn_follower};
#[derive(Clone, Copy, PartialEq)]
enum Screen {
/// True first launch: the key form stands in for the page until a key is saved.
Prompt,
Page,
Settings,
}
struct RootView {
page: Entity<StatsPage>,
form: Entity<KeyForm>,
screen: Screen,
tracker: Arc<Tracker>,
/// The configured Riot ID, used when the game client is closed on first launch.
fallback_riot_id: String,
tx: Sender<Msg>,
_subscriptions: Vec<Subscription>,
}
impl RootView {
fn new(setup: Setup, window: &mut Window, cx: &mut Context<Self>) -> Self {
let Setup {
tracker,
riot_id,
notice,
store,
} = setup;
// Without a key the page still shows what is stored; only a true first launch (no key
// and nothing stored) has nothing to show, so the key form stands in for the page.
let first_launch = !store.has_key() && tracker.accounts().unwrap_or_default().is_empty();
let (tx, rx) = mpsc::channel();
let page = cx.new(|cx| {
StatsPage::new(
tracker.clone(),
notice,
!first_launch,
rx,
tx.clone(),
window,
cx,
)
});
let form = cx.new(|cx| KeyForm::new(store, first_launch, window, cx));
let subscriptions = vec![
cx.subscribe_in(
&page,
window,
|this, _, event: &PageEvent, window, cx| match event {
PageEvent::OpenSettings => {
this.form.update(cx, |form, cx| form.reset(window, cx));
this.screen = Screen::Settings;
cx.notify();
}
},
),
cx.subscribe_in(&form, window, |this, _, event: &KeyEvent, _, cx| {
match event {
KeyEvent::Saved if this.screen == Screen::Prompt => {
// Nothing is imported before a key exists: the follower starts now.
let (tracker, riot_id) =
(this.tracker.clone(), this.fallback_riot_id.clone());
spawn_follower(tracker, riot_id, this.tx.clone());
this.page.update(cx, |page, cx| page.following(cx));
}
KeyEvent::Saved => this.page.update(cx, |page, cx| page.begin_refresh(cx)),
KeyEvent::Back => {}
}
this.screen = Screen::Page;
cx.notify();
}),
];
let screen = if first_launch {
Screen::Prompt
} else {
spawn_follower(tracker.clone(), riot_id.clone(), tx.clone());
Screen::Page
};
RootView {
page,
form,
screen,
tracker,
fallback_riot_id: riot_id,
tx,
_subscriptions: subscriptions,
}
}
}
impl Render for RootView {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
let content = match self.screen {
Screen::Page => self.page.clone().into_any_element(),
Screen::Prompt | Screen::Settings => self.form.clone().into_any_element(),
};
div().size_full().child(content)
}
}
/// Shown instead of the app when the configuration or the database cannot be loaded.
struct Unavailable(Vec<String>);
impl Render for Unavailable {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.v_flex()
.size_full()
.items_center()
.justify_center()
.child(arena_tracker_core::startup_message())
.children(self.0.clone())
}
}
struct Setup {
tracker: Arc<Tracker>,
riot_id: String,
notice: Option<String>,
store: KeyStore,
}
/// Loads the configuration and opens the database, or gives the lines to show instead. A
/// missing config file is fine: the app then asks for the key.
fn startup() -> Result<Setup, Vec<String>> {
let bad_config = |error: String| {
vec![
format!("Configuration introuvable ou invalide : {error}"),
"Corrigez ou supprimez %APPDATA%\\arena-tracker\\config.toml.".into(),
]
};
let dir =
data_dir().ok_or_else(|| bad_config("la variable APPDATA n'est pas définie.".into()))?;
std::fs::create_dir_all(&dir).map_err(|e| bad_config(e.to_string()))?;
let path = dir.join("config.toml");
let config = Config::load_or_default(&path).map_err(|e| bad_config(e.to_string()))?;
let (seasons, notice) = match load_seasons(&dir.join("seasons.toml")) {
Ok(seasons) => (seasons, None),
Err(e) => (
default_seasons(),
Some(format!("Table des Saisons invalide : {e}")),
),
};
let api = Arc::new(RiotApi::new(config.riot_api_key.clone(), &config.region));
let tracker = Tracker::open(&dir.join("arena-tracker.db"), Box::new(api.clone()))
.map_err(|e| vec![e.to_string()])?
.with_seasons(seasons)
.with_champions(Box::new(DataDragon::new()), dir.join("portraits"))
.with_client(Box::new(LeagueClient::new()));
Ok(Setup {
tracker: Arc::new(tracker),
riot_id: config.riot_id.clone(),
notice,
store: KeyStore::new(path, config, api),
})
}
fn main() {
gpui_kit::application().run(move |cx| {
gpui_kit::init(cx);
@@ -24,9 +182,22 @@ fn main() {
title: Some("Arena Tracker".into()),
..Default::default()
}),
window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
None,
size(px(1280.), px(860.)),
cx,
))),
..Default::default()
};
gpui_kit::open_window(options, cx, |_, cx| cx.new(|_| RootView))
.expect("Failed to open window");
match startup() {
Ok(setup) => gpui_kit::open_window(options, cx, |window, cx| {
cx.new(|cx| RootView::new(setup, window, cx))
})
.map(drop),
Err(lines) => {
gpui_kit::open_window(options, cx, |_, cx| cx.new(|_| Unavailable(lines))).map(drop)
}
}
.expect("Failed to open window");
});
}
+184
View File
@@ -0,0 +1,184 @@
//! The Riot API key form: the first-launch prompt and the settings view.
use std::path::PathBuf;
use std::sync::Arc;
use arena_tracker_core::{Config, Error, RiotApi};
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::*;
const PLACEHOLDER_SAVED: &str = "Clé enregistrée";
const PLACEHOLDER_EMPTY: &str = "Clé API Riot";
/// Where the key lives: the config file, and the running Riot client that uses it.
pub struct KeyStore {
path: PathBuf,
config: Config,
api: Arc<RiotApi>,
}
impl KeyStore {
pub fn new(path: PathBuf, config: Config, api: Arc<RiotApi>) -> KeyStore {
KeyStore { path, config, api }
}
pub fn has_key(&self) -> bool {
!self.config.riot_api_key.is_empty()
}
/// Writes the key to the config file and hands it to the Riot client, no restart needed.
fn save(&mut self, key: &str) -> Result<(), Error> {
let previous = std::mem::replace(&mut self.config.riot_api_key, key.to_string());
if let Err(e) = self.config.save(&self.path) {
self.config.riot_api_key = previous;
return Err(e);
}
self.api.set_key(key.to_string());
Ok(())
}
}
pub enum KeyEvent {
Saved,
Back,
}
pub struct KeyForm {
store: KeyStore,
input: Entity<InputState>,
/// The first-launch prompt (no key and nothing stored yet) has no way back.
first_launch: bool,
error: Option<String>,
_subscription: Subscription,
}
impl EventEmitter<KeyEvent> for KeyForm {}
impl KeyForm {
pub fn new(
store: KeyStore,
first_launch: bool,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let placeholder = if store.has_key() {
PLACEHOLDER_SAVED
} else {
PLACEHOLDER_EMPTY
};
let input = cx.new(|cx| {
InputState::new(window, cx)
.masked(true)
.placeholder(placeholder)
});
let subscription =
cx.subscribe_in(&input, window, |this, _, event: &InputEvent, window, cx| {
if matches!(event, InputEvent::PressEnter { .. }) {
this.save(window, cx);
}
});
KeyForm {
first_launch,
store,
input,
error: None,
_subscription: subscription,
}
}
/// Back to an empty field, as when the form is opened again.
pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.error = None;
self.clear(window, cx);
cx.notify();
}
fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let placeholder = if self.store.has_key() {
PLACEHOLDER_SAVED
} else {
PLACEHOLDER_EMPTY
};
self.input.update(cx, |input, cx| {
input.set_value("", window, cx);
input.set_placeholder(placeholder, window, cx);
});
}
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let key = self.input.read(cx).value();
let key = key.trim();
if key.is_empty() {
self.error = Some("Saisissez une clé API.".into());
} else {
match self.store.save(key) {
Ok(()) => {
self.error = None;
self.first_launch = false;
self.clear(window, cx);
cx.emit(KeyEvent::Saved);
}
Err(e) => self.error = Some(format!("Enregistrement impossible : {e}")),
}
}
cx.notify();
}
}
impl Render for KeyForm {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (title, explanation) = if self.first_launch {
(
"Clé API Riot",
"Une clé API Riot est nécessaire pour importer vos Parties : demandez-en une sur le portail développeur Riot (developer.riotgames.com). Elle reste enregistrée sur cet ordinateur.",
)
} else {
(
"Paramètres",
"Saisissez une nouvelle clé API Riot pour remplacer celle qui est enregistrée. Elle reste enregistrée sur cet ordinateur.",
)
};
let (muted, danger) = (cx.theme().muted_foreground, cx.theme().danger);
let buttons = div()
.h_flex()
.gap_2()
.child(
Button::new("save")
.primary()
.label("Enregistrer")
.on_click(cx.listener(|this, _, window, cx| this.save(window, cx))),
)
.children((!self.first_launch).then(|| {
Button::new("back")
.label("Retour")
.on_click(cx.listener(|_, _, _, cx| cx.emit(KeyEvent::Back)))
}));
div()
.size_full()
.flex()
.items_center()
.justify_center()
.child(
div()
.v_flex()
.w(px(520.))
.gap_3()
.child(
div()
.text_xl()
.font_weight(FontWeight::SEMIBOLD)
.child(title),
)
.child(div().text_color(muted).child(explanation))
.child(Input::new(&self.input).mask_toggle())
.children(
self.error
.clone()
.map(|error| div().text_color(danger).child(error)),
)
.child(buttons),
)
}
}
+776
View File
@@ -0,0 +1,776 @@
//! The statistics page: banners, Challenge header, charts and champion table for one Account.
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender, TryRecvError};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arena_tracker_core::{
Account, ChallengeSummary, Charts, Format, ProgressCheck, Scope, SeasonScope, StateFilter,
Statistics, Status, SyncProgress, Tracker, UpdateProblem,
};
use gpui_kit::component::StyledExt as _;
use gpui_kit::component::alert::Alert;
use gpui_kit::component::button::Button;
use gpui_kit::component::chart::{AreaChart, BarChart};
use gpui_kit::component::select::{Select, SelectEvent, SelectItem, SelectState};
use gpui_kit::component::tab::{Tab, TabBar};
use gpui_kit::component::table::{DataTable, TableState};
use gpui_kit::component::{ActiveTheme as _, Disableable as _, IndexPath, Sizable as _};
use gpui_kit::*;
use crate::champion_table::ChampionTable;
use crate::text::{CLIENT_ABSENT, decimal, official_differs, official_note, riot_id, sync_line};
use crate::worker::{Msg, RefreshGate, spawn_refresh};
const ALL_SEASONS: &str = "Toutes les Saisons";
const ALL_FORMATS: &str = "Tous les Formats";
const NO_MATCH: &str = "Aucune Partie";
const CHART_HEIGHT: f32 = 150.;
/// While an import runs, the page is recomputed at most this often.
const RELOAD_EVERY: Duration = Duration::from_secs(1);
pub enum PageEvent {
OpenSettings,
}
/// One Account in the selector; its value is the puuid.
#[derive(Clone, PartialEq)]
struct AccountItem {
puuid: String,
title: SharedString,
}
impl SelectItem for AccountItem {
type Value = String;
fn title(&self) -> SharedString {
self.title.clone()
}
fn value(&self) -> &String {
&self.puuid
}
}
pub struct StatsPage {
tracker: Arc<Tracker>,
tx: Sender<Msg>,
notice: Option<String>,
/// As of the last follower round or refresh.
status: Status,
accounts: Vec<Account>,
last_active: Option<Account>,
/// The Account the user picked instead of following the one being updated.
pinned: Option<String>,
/// The Account whose statistics are in `stats`.
shown: Option<String>,
progress: Option<SyncProgress>,
refresh: RefreshGate,
/// Until the follower's first round ends.
pending_round: bool,
crashed: bool,
last_reload: Instant,
current_season: Option<String>,
season: SeasonScope,
format: Option<Format>,
filter: StateFilter,
stats: Option<Statistics>,
stats_error: Option<String>,
stored: Option<usize>,
account_select: Entity<SelectState<Vec<AccountItem>>>,
account_items: Vec<AccountItem>,
season_select: Entity<SelectState<Vec<SharedString>>>,
format_select: Entity<SelectState<Vec<SharedString>>>,
format_names: Vec<SharedString>,
table: Entity<TableState<ChampionTable>>,
table_in_season: bool,
_subscriptions: Vec<Subscription>,
}
impl EventEmitter<PageEvent> for StatsPage {}
/// The state filters on offer: the Challenge ones only make sense in a Season.
fn filters(in_season: bool) -> &'static [(&'static str, StateFilter)] {
const SEASON: [(&str, StateFilter); 4] = [
("Tous", StateFilter::All),
("Validés", StateFilter::Completed),
("Restants", StateFilter::Remaining),
("Jamais joués", StateFilter::NeverPlayed),
];
if in_season {
&SEASON
} else {
&[SEASON[0], SEASON[3]]
}
}
impl StatsPage {
/// `following`: a follower thread is already running, its first round is pending.
pub fn new(
tracker: Arc<Tracker>,
notice: Option<String>,
following: bool,
rx: Receiver<Msg>,
tx: Sender<Msg>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let seasons: Vec<SharedString> = tracker
.seasons()
.into_iter()
.rev()
.map(|s| s.name.into())
.chain([ALL_SEASONS.into()])
.collect();
let now_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64);
let current_season = tracker.current_season(now_ms).map(|s| s.name);
let season = current_season
.clone()
.map_or(SeasonScope::AllSeasons, SeasonScope::Season);
let selected = match &season {
SeasonScope::Season(name) => seasons.iter().position(|s| s.as_ref() == name.as_str()),
SeasonScope::AllSeasons => Some(seasons.len() - 1),
};
let account_select =
cx.new(|cx| SelectState::new(Vec::<AccountItem>::new(), None, window, cx));
let season_select =
cx.new(|cx| SelectState::new(seasons, selected.map(IndexPath::new), window, cx));
let format_names = vec![SharedString::from(ALL_FORMATS)];
let format_select = cx
.new(|cx| SelectState::new(format_names.clone(), Some(IndexPath::new(0)), window, cx));
let table =
cx.new(|cx| TableState::new(ChampionTable::new(), window, cx).col_movable(false));
let subscriptions = vec![
cx.subscribe_in(
&account_select,
window,
|this, _, event: &SelectEvent<Vec<AccountItem>>, window, cx| {
let SelectEvent::Confirm(Some(puuid)) = event else {
return;
};
// Picking the Account being updated is following it again.
let following = this
.status
.updating
.as_ref()
.is_some_and(|a| a.puuid == *puuid);
this.pinned = (!following).then(|| puuid.clone());
this.reload(window, cx);
},
),
cx.subscribe_in(
&season_select,
window,
|this, _, event: &SelectEvent<Vec<SharedString>>, window, cx| {
let SelectEvent::Confirm(Some(name)) = event else {
return;
};
this.season = if name.as_ref() == ALL_SEASONS {
SeasonScope::AllSeasons
} else {
SeasonScope::Season(name.to_string())
};
this.recompute(window, cx);
},
),
cx.subscribe_in(
&format_select,
window,
|this, _, event: &SelectEvent<Vec<SharedString>>, window, cx| {
let SelectEvent::Confirm(Some(name)) = event else {
return;
};
let formats = this.stats.iter().flat_map(|s| s.formats.iter());
this.format = formats.copied().find(|f| f.name() == name.as_ref());
this.recompute(window, cx);
},
),
];
// The workers' messages arrive on a plain channel; polling it keeps the UI free of
// any extra dependency.
cx.spawn_in(window, async move |this, cx| {
loop {
cx.background_executor()
.timer(Duration::from_millis(100))
.await;
loop {
match rx.try_recv() {
Ok(msg) => {
let applied = cx.update(|window, app| {
this.update(app, |page, cx| page.apply(msg, window, cx))
});
// The window or the page is gone: nothing left to update.
if !matches!(applied, Ok(Ok(()))) {
return;
}
}
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => return,
}
}
}
})
.detach();
let mut page = StatsPage {
status: tracker.status(),
tracker,
tx,
notice,
accounts: Vec::new(),
last_active: None,
pinned: None,
shown: None,
progress: None,
refresh: RefreshGate::default(),
pending_round: following,
crashed: false,
last_reload: Instant::now(),
current_season,
season,
format: None,
filter: StateFilter::All,
stats: None,
stats_error: None,
stored: None,
account_select,
account_items: Vec::new(),
season_select,
format_select,
format_names,
table,
table_in_season: false,
_subscriptions: subscriptions,
};
page.reload(window, cx);
page
}
/// The follower thread was just started.
pub fn following(&mut self, cx: &mut Context<Self>) {
self.pending_round = true;
cx.notify();
}
/// Starts a refresh, or queues one behind the refresh already running.
pub fn begin_refresh(&mut self, cx: &mut Context<Self>) {
if self.refresh.request() {
spawn_refresh(self.tracker.clone(), self.tx.clone());
}
cx.notify();
}
fn busy(&self) -> bool {
self.progress.is_some() || self.refresh.running() || self.pending_round
}
/// The Account shown: the pinned one, else the one being updated.
fn viewed(&self) -> Option<&Account> {
self.pinned
.as_ref()
.and_then(|puuid| self.accounts.iter().find(|a| a.puuid == *puuid))
.or(self.status.updating.as_ref())
.or(self.last_active.as_ref())
.or(self.accounts.first())
}
/// Whether the Account shown is not the one being updated (or none is), so only stored
/// data is shown. Unknown until the follower's first round has reported.
fn stale(&self) -> bool {
!self.pending_round
&& self.viewed().is_some_and(|viewed| {
self.status
.updating
.as_ref()
.is_none_or(|updating| updating.puuid != viewed.puuid)
})
}
/// The game's own count, only meaningful for the Account being updated in the current Season.
fn official(&self) -> Option<&ProgressCheck> {
let updated = matches!((self.viewed(), &self.status.updating), (Some(v), Some(u)) if v.puuid == u.puuid);
let current = matches!((&self.season, &self.current_season), (SeasonScope::Season(s), Some(c)) if s == c);
(updated && current).then_some(&self.status.official_progress)
}
fn apply(&mut self, msg: Msg, window: &mut Window, cx: &mut Context<Self>) {
match msg {
Msg::Progress(progress) => {
self.progress = Some(progress);
if self.last_reload.elapsed() >= RELOAD_EVERY {
self.reload(window, cx);
}
}
Msg::Champions => self.reload(window, cx),
Msg::Round { status, reload } => {
self.status = status;
self.pending_round = false;
self.progress = None;
self.crashed = false;
if reload {
self.reload(window, cx);
}
}
Msg::Refreshed(status) => {
self.status = status;
self.progress = None;
self.crashed = false;
self.reload(window, cx);
// A request made while this one ran (a key saved meanwhile) is served now.
if self.refresh.finished() {
spawn_refresh(self.tracker.clone(), self.tx.clone());
}
}
Msg::Crashed => {
self.refresh.reset();
self.pending_round = false;
self.progress = None;
self.crashed = true;
}
}
cx.notify();
}
/// Re-reads the Accounts, then the statistics of the one shown.
fn reload(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.accounts = self.tracker.accounts().unwrap_or_default();
self.last_active = self.tracker.last_active_account().ok().flatten();
if self.pinned.as_ref() == self.status.updating.as_ref().map(|a| &a.puuid) {
self.pinned = None;
}
let items: Vec<AccountItem> = self
.accounts
.iter()
.map(|a| AccountItem {
puuid: a.puuid.clone(),
title: riot_id(a).into(),
})
.collect();
let changed = items != self.account_items;
self.account_items = items.clone();
let viewed = self.viewed().map(|a| a.puuid.clone());
self.account_select.update(cx, |select, cx| {
if changed {
select.set_items(items, window, cx);
}
if let Some(puuid) = &viewed
&& select.selected_value() != Some(puuid)
{
select.set_selected_value(puuid, window, cx);
}
});
self.recompute(window, cx);
}
/// Recomputes the statistics for the current scope; never called while rendering.
fn recompute(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.last_reload = Instant::now();
if matches!(self.season, SeasonScope::AllSeasons)
&& !matches!(self.filter, StateFilter::All | StateFilter::NeverPlayed)
{
self.filter = StateFilter::All;
}
let viewed = self.viewed().map(|a| a.puuid.clone());
if viewed != self.shown {
// Another Account may not have played the selected Format.
self.shown = viewed.clone();
if self.format.take().is_some() {
self.format_select.update(cx, |select, cx| {
select.set_selected_index(Some(IndexPath::new(0)), window, cx)
});
}
}
self.stats = None;
self.stats_error = None;
self.stored = None;
if let Some(puuid) = &viewed {
let scope = Scope {
season: self.season.clone(),
format: self.format,
};
match self.tracker.statistics(puuid, &scope) {
Ok(stats) => self.stats = Some(stats),
Err(e) => self.stats_error = Some(format!("Statistiques indisponibles : {e}")),
}
self.stored = self.tracker.match_count(puuid).ok();
}
let mut names = vec![SharedString::from(ALL_FORMATS)];
names.extend(
self.stats
.iter()
.flat_map(|s| s.formats.iter().map(|f| SharedString::from(f.name()))),
);
if names != self.format_names {
self.format_names = names.clone();
self.format_select
.update(cx, |select, cx| select.set_items(names, window, cx));
}
self.refresh_table(cx);
cx.notify();
}
fn refresh_table(&mut self, cx: &mut Context<Self>) {
let rows = self.stats.iter().flat_map(|s| &s.rows);
let rows = rows.filter(|row| self.filter.keeps(row)).cloned().collect();
let in_season = matches!(self.season, SeasonScope::Season(_));
// Only a change of columns needs `refresh`, which also resets the column widths.
let columns_changed = in_season != self.table_in_season;
self.table_in_season = in_season;
self.table.update(cx, |table, cx| {
table.delegate_mut().set_rows(rows, in_season);
if columns_changed {
table.refresh(cx);
}
cx.notify();
});
}
/// One line each, the most important first; the stored data stays visible under all.
fn banners(&self) -> Vec<AnyElement> {
let mut banners = Vec::new();
if let Some(problem) = &self.status.problem {
let message = problem.message();
banners.push(match problem {
UpdateProblem::MatchPending
| UpdateProblem::RateLimited
| UpdateProblem::NoAccount => Alert::warning("problem", message),
_ => Alert::error("problem", message),
});
}
if let Some(ProgressCheck::Differs { app, official }) = self.official() {
banners.push(Alert::warning(
"official",
official_differs(*app, *official),
));
}
if !self.pending_round && !self.status.client_running {
banners.push(Alert::info("client", CLIENT_ABSENT));
}
if let Some(notice) = &self.notice {
banners.push(Alert::warning("notice", notice.clone()));
}
if let Some(error) = &self.stats_error {
banners.push(Alert::error("stats", error.clone()));
}
banners
.into_iter()
.map(|alert| alert.small().into_any_element())
.collect()
}
}
fn tile(
label: &'static str,
value: String,
note: Option<String>,
border: Hsla,
muted: Hsla,
) -> impl IntoElement {
div()
.v_flex()
.flex_1()
.gap_1()
.p_3()
.border_1()
.border_color(border)
.rounded_md()
.child(div().text_sm().text_color(muted).child(label))
.child(
div()
.text_xl()
.font_weight(FontWeight::SEMIBOLD)
.child(value),
)
.children(note.map(|note| div().text_xs().text_color(muted).child(note)))
}
fn challenge_tiles(
c: &ChallengeSummary,
official: Option<&ProgressCheck>,
border: Hsla,
muted: Hsla,
) -> impl IntoElement {
let average = c.average_attempts.map_or("-".into(), |a| decimal(a, 2));
// Next to the count whether the app agrees or not; the banner covers the difference.
let note = match official {
Some(ProgressCheck::Agrees(n)) | Some(ProgressCheck::Differs { official: n, .. }) => {
Some(official_note(*n))
}
_ => None,
};
div()
.h_flex()
.gap_3()
.child(tile(
"Champions validés",
format!("{} / {}", c.completed, c.total),
note,
border,
muted,
))
.child(tile(
"Tentatives",
c.attempts.to_string(),
None,
border,
muted,
))
.child(tile(
"Tentatives par champion validé",
average,
None,
border,
muted,
))
.child(tile(
"Du premier coup",
c.first_tries.to_string(),
None,
border,
muted,
))
}
/// A titled card holding a chart, or `empty` in its place.
fn card(
title: &'static str,
chart: Option<AnyElement>,
empty: &'static str,
border: Hsla,
muted: Hsla,
) -> impl IntoElement {
let body = chart.unwrap_or_else(|| {
div()
.size_full()
.flex()
.items_center()
.justify_center()
.text_color(muted)
.child(empty)
.into_any_element()
});
div()
.v_flex()
.flex_1()
.min_w_0()
.gap_2()
.p_3()
.border_1()
.border_color(border)
.rounded_md()
.child(
div()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
.child(title),
)
.child(div().h(px(CHART_HEIGHT)).w_full().children(Some(body)))
}
fn placements_chart(charts: &Charts) -> Option<AnyElement> {
(!charts.placements.is_empty()).then(|| {
BarChart::new(charts.placements.clone())
.id("placements")
.band(|(placement, _)| placement.to_string())
.value(|(_, count)| *count as f64)
.label(|(_, count)| count.to_string())
.name("Parties")
.into_any_element()
})
}
fn completed_chart(charts: &Charts) -> Option<AnyElement> {
let points: Vec<(String, f64)> = charts
.completed_over_time
.iter()
.map(|(day, count)| (day.to_string(), *count as f64))
.collect();
// The counts only grow, so the last one is the highest. The y axis runs from 0 to a
// multiple of 4 in four steps with no padding: every tick is then a whole number.
let top = charts.completed_over_time.last().map_or(0, |(_, n)| *n);
let top = top.div_ceil(4).max(1) * 4;
(!points.is_empty()).then(|| {
AreaChart::new(points)
.id("completed")
.x(|(day, _)| day.clone())
.y(|(_, count)| *count)
.linear()
.x_tick_count(3)
.y_axis(true)
.y_domain(0., top as f64)
.y_padding(0., 0.)
.y_tick_count(5)
.name("Champions validés")
.into_any_element()
})
}
fn attempts_chart(charts: &Charts) -> Option<AnyElement> {
const LABELS: [&str; 5] = ["1", "2", "3", "4", "5+"];
let bars: Vec<(&str, usize)> = LABELS
.into_iter()
.zip(charts.attempts_to_complete)
.collect();
bars.iter().any(|(_, count)| *count > 0).then(|| {
BarChart::new(bars)
.id("attempts")
.band(|(label, _)| *label)
.value(|(_, count)| *count as f64)
.label(|(_, count)| count.to_string())
.name("Champions")
.into_any_element()
})
}
impl Render for StatsPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (border, muted) = {
let theme = cx.theme();
(theme.border, theme.muted_foreground)
};
let in_season = matches!(self.season, SeasonScope::Season(_));
let options = filters(in_season);
let selected = options.iter().position(|(_, f)| *f == self.filter);
let empty = Charts {
placements: vec![],
completed_over_time: vec![],
attempts_to_complete: [0; 5],
};
let charts = self.stats.as_ref().map_or(&empty, |s| &s.charts);
let challenge = self.stats.as_ref().and_then(|s| s.challenge.as_ref());
let mut cards = vec![
card(
"Répartition des Placements",
placements_chart(charts),
NO_MATCH,
border,
muted,
)
.into_any_element(),
];
if in_season {
cards.push(
card(
"Champions validés au fil de la Saison",
completed_chart(charts),
"Aucun champion validé",
border,
muted,
)
.into_any_element(),
);
cards.push(
card(
"Tentatives pour valider",
attempts_chart(charts),
"Aucun champion validé",
border,
muted,
)
.into_any_element(),
);
}
let busy = self.busy();
let status_line = sync_line(busy, self.progress, self.crashed, self.stored);
div()
.v_flex()
.size_full()
.gap_3()
.p_3()
.child(
// The selectors give way first (down to their minimum width), then the buttons
// wrap onto a second line: nothing is ever clipped.
div()
.h_flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_x_3()
.gap_y_2()
.child(
div()
.h_flex()
.items_center()
.gap_3()
.min_w_0()
.child(
Select::new(&self.account_select)
.id("account")
.placeholder("Aucun Compte")
.w(px(260.))
.min_w(px(150.)),
)
.children(self.stale().then(|| {
div()
.text_sm()
.whitespace_nowrap()
.text_color(muted)
.child("Non mis à jour")
}))
.child(
Select::new(&self.season_select)
.id("season")
.w(px(220.))
.min_w(px(130.)),
)
.child(
Select::new(&self.format_select)
.id("format")
.w(px(220.))
.min_w(px(130.)),
),
)
.child(
div()
.h_flex()
.items_center()
.gap_3()
.flex_shrink_0()
.child(
div()
.text_sm()
.whitespace_nowrap()
.text_color(muted)
.child(status_line),
)
.child(
Button::new("refresh")
.label("Actualiser")
.disabled(busy)
.on_click(cx.listener(|this, _, _, cx| this.begin_refresh(cx))),
)
.child(Button::new("settings").label("Paramètres").on_click(
cx.listener(|_, _, _, cx| cx.emit(PageEvent::OpenSettings)),
)),
),
)
.child(div().v_flex().gap_1().children(self.banners()))
.children(challenge.map(|c| challenge_tiles(c, self.official(), border, muted)))
.child(div().h_flex().gap_3().children(cards))
.child(
TabBar::new("state-filter")
.segmented()
.selected_index(selected.unwrap_or(0))
.children(options.iter().map(|(label, _)| Tab::new().label(*label)))
.on_click(cx.listener(|this, ix: &usize, _, cx| {
let in_season = matches!(this.season, SeasonScope::Season(_));
if let Some((_, filter)) = filters(in_season).get(*ix) {
this.filter = *filter;
this.refresh_table(cx);
cx.notify();
}
})),
)
.child(
div()
.flex_1()
.min_h(px(240.))
.child(DataTable::new(&self.table).stripe(true)),
)
}
}
+145
View File
@@ -0,0 +1,145 @@
//! French display helpers shared by the page and the table.
use arena_tracker_core::{Account, ChampionState, SyncProgress};
/// Fixed decimals with a decimal comma: `1,96`.
pub fn decimal(value: f64, digits: usize) -> String {
format!("{value:.digits$}").replace('.', ",")
}
/// How many Matches are stored, with the singular and the empty case.
pub fn stored(count: usize) -> String {
match count {
0 => "Aucune Partie enregistrée".into(),
1 => "1 Partie enregistrée".into(),
n => format!("{n} Parties enregistrées"),
}
}
pub fn state_label(state: Option<ChampionState>) -> &'static str {
match state {
Some(ChampionState::Completed) => "Validé",
Some(ChampionState::InProgress) => "En cours",
Some(ChampionState::NeverPlayed) => "Jamais joué",
None => "",
}
}
pub const CLIENT_ABSENT: &str =
"Client League of Legends non détecté : affichage des données enregistrées.";
const INTERNAL_ERROR: &str = "Mise à jour impossible : erreur interne.";
pub fn riot_id(account: &Account) -> String {
format!("{}#{}", account.game_name, account.tag_line)
}
/// The discreet line under the Challenge tile.
pub fn official_note(official: u32) -> String {
format!("Progression officielle : {official}")
}
pub fn official_differs(app: usize, official: u32) -> String {
format!(
"La Progression officielle du jeu indique {official} champions validés, l'application en compte {app} : des Parties manquent peut-être."
)
}
/// The sync status line: what is running, else the last failure, else the stored count.
pub fn sync_line(
busy: bool,
progress: Option<SyncProgress>,
crashed: bool,
stored_count: Option<usize>,
) -> String {
match progress {
// A report with nothing to fetch is still the listing.
Some(p) if busy && p.to_fetch > 0 => {
format!("Import en cours : {} / {} Parties", p.fetched, p.to_fetch)
}
_ if busy => "Synchronisation en cours…".into(),
_ if crashed => INTERNAL_ERROR.into(),
_ => stored_count.map(stored).unwrap_or_default(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decimals_use_a_comma() {
assert_eq!(decimal(1.96, 2), "1,96");
assert_eq!(decimal(3.0, 1), "3,0");
assert_eq!(decimal(2.0 / 3.0, 1), "0,7");
}
#[test]
fn stored_matches_are_pluralised() {
assert_eq!(stored(0), "Aucune Partie enregistrée");
assert_eq!(stored(1), "1 Partie enregistrée");
assert_eq!(stored(42), "42 Parties enregistrées");
}
#[test]
fn states_have_a_french_label() {
assert_eq!(state_label(Some(ChampionState::Completed)), "Validé");
assert_eq!(state_label(Some(ChampionState::InProgress)), "En cours");
assert_eq!(state_label(Some(ChampionState::NeverPlayed)), "Jamais joué");
assert_eq!(state_label(None), "");
}
fn account(name: &str, tag: &str) -> Account {
Account {
puuid: "p".into(),
game_name: name.into(),
tag_line: tag.into(),
}
}
#[test]
fn riot_ids_join_name_and_tag() {
assert_eq!(riot_id(&account("Joueur", "EUW")), "Joueur#EUW");
}
#[test]
fn official_progress_texts() {
assert_eq!(official_note(52), "Progression officielle : 52");
assert_eq!(
official_differs(50, 52),
"La Progression officielle du jeu indique 52 champions validés, l'application en compte 50 : des Parties manquent peut-être."
);
}
#[test]
fn the_sync_line_follows_what_is_running() {
let progress = SyncProgress {
fetched: 3,
to_fetch: 10,
};
assert_eq!(
sync_line(true, Some(progress), false, Some(5)),
"Import en cours : 3 / 10 Parties"
);
assert_eq!(
sync_line(true, None, false, Some(5)),
"Synchronisation en cours…"
);
let nothing = SyncProgress {
fetched: 0,
to_fetch: 0,
};
assert_eq!(
sync_line(true, Some(nothing), false, Some(5)),
"Synchronisation en cours…"
);
assert_eq!(
sync_line(false, None, true, Some(5)),
"Mise à jour impossible : erreur interne."
);
assert_eq!(
sync_line(false, None, false, Some(1)),
"1 Partie enregistrée"
);
assert_eq!(sync_line(false, None, false, None), "");
}
}
+142
View File
@@ -0,0 +1,142 @@
//! Background threads: following the game client, and the refresh button.
//! Both talk to the page through `Msg`.
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::sync::mpsc::Sender;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
use arena_tracker_core::{Status, SyncProgress, Tracker};
pub enum Msg {
/// A sync is fetching Matches.
Progress(SyncProgress),
/// The champion catalog and portraits were refreshed.
Champions,
/// A follower round ended; `reload` when the stored data may have changed.
Round { status: Status, reload: bool },
/// A refresh ended.
Refreshed(Status),
/// A worker thread panicked.
Crashed,
}
/// At most one refresh thread at a time. A request made while one runs is served once, when it
/// reports back: the sync it was waiting for may have started before the reason for it.
#[derive(Default)]
pub struct RefreshGate {
running: bool,
queued: bool,
}
impl RefreshGate {
pub fn running(&self) -> bool {
self.running
}
/// True when a refresh thread must start now.
pub fn request(&mut self) -> bool {
if self.running {
self.queued = true;
return false;
}
self.running = true;
true
}
/// The running refresh reported back; true when the queued one must start now.
pub fn finished(&mut self) -> bool {
self.running = std::mem::take(&mut self.queued);
self.running
}
/// A thread panicked: nothing is known to run any more.
pub fn reset(&mut self) {
*self = RefreshGate::default();
}
}
fn now_ms() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64)
}
/// Runs `body` on its own thread; a panic is reported instead of leaving the page waiting.
fn spawn_guarded(tx: Sender<Msg>, body: impl FnOnce(&Sender<Msg>) + Send + 'static) {
thread::spawn(move || {
if catch_unwind(AssertUnwindSafe(|| body(&tx))).is_err() {
let _ = tx.send(Msg::Crashed);
}
});
}
/// Keeps the active Account up to date for as long as the app runs: one thread, rounds of
/// `follow_client` separated by `wait_for_client`. `fallback_riot_id` is the configured Riot ID.
/// The champion catalog and portraits are fetched on another thread, so a first launch's
/// import never waits for them.
pub fn spawn_follower(tracker: Arc<Tracker>, fallback_riot_id: String, tx: Sender<Msg>) {
let champions = tracker.clone();
spawn_guarded(tx.clone(), move |tx| {
let _ = champions.refresh_champions();
let _ = tx.send(Msg::Champions);
});
spawn_guarded(tx, move |tx| {
let fallback = Some(fallback_riot_id.as_str()).filter(|id| !id.trim().is_empty());
let mut first = true;
loop {
let changed = tracker.follow_client(now_ms(), fallback, &mut |progress| {
let _ = tx.send(Msg::Progress(progress));
});
let status = tracker.status();
let _ = tx.send(Msg::Round {
status,
reload: changed || first,
});
first = false;
tracker.wait_for_client();
}
});
}
/// The refresh button: one sync of the Account being kept up to date.
pub fn spawn_refresh(tracker: Arc<Tracker>, tx: Sender<Msg>) {
spawn_guarded(tx, move |tx| {
// A failure is recorded in the status, which the page shows as a banner.
let _ = tracker.refresh(&mut |progress| {
let _ = tx.send(Msg::Progress(progress));
});
let _ = tx.send(Msg::Refreshed(tracker.status()));
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_request_while_a_refresh_runs_waits_for_it_and_is_served_once() {
let mut gate = RefreshGate::default();
assert!(gate.request());
assert!(gate.running());
assert!(!gate.request());
assert!(!gate.request());
// The running one ends: one queued refresh starts, however many were asked.
assert!(gate.finished());
assert!(gate.running());
assert!(!gate.finished());
assert!(!gate.running());
assert!(gate.request());
}
#[test]
fn a_crash_forgets_the_queue() {
let mut gate = RefreshGate::default();
assert!(gate.request());
assert!(!gate.request());
gate.reset();
assert!(!gate.running());
assert!(!gate.finished());
}
}
+11
View File
@@ -5,3 +5,14 @@ rust-version.workspace = true
version.workspace = true
[dependencies]
base64 = { version = "0.23.1", default-features = false, features = ["std"] }
rusqlite = { version = "0.43.0", features = ["bundled"] }
rustls = { version = "0.23.46", default-features = false, features = ["ring", "std", "tls12"] }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
toml = "1.2.1"
tungstenite = { version = "0.30.0", default-features = false, features = ["handshake", "rustls-tls-webpki-roots"] }
ureq = "3.5.2"
[dev-dependencies]
tempfile = "3.27.0"
+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);
}
}
+25
View File
@@ -0,0 +1,25 @@
-----BEGIN CERTIFICATE-----
MIIEIDCCAwgCCQDJC+QAdVx4UDANBgkqhkiG9w0BAQUFADCB0TELMAkGA1UEBhMC
VVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFTATBgNVBAcTDFNhbnRhIE1vbmljYTET
MBEGA1UEChMKUmlvdCBHYW1lczEdMBsGA1UECxMUTG9MIEdhbWUgRW5naW5lZXJp
bmcxMzAxBgNVBAMTKkxvTCBHYW1lIEVuZ2luZWVyaW5nIENlcnRpZmljYXRlIEF1
dGhvcml0eTEtMCsGCSqGSIb3DQEJARYeZ2FtZXRlY2hub2xvZ2llc0ByaW90Z2Ft
ZXMuY29tMB4XDTEzMTIwNDAwNDgzOVoXDTQzMTEyNzAwNDgzOVowgdExCzAJBgNV
BAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRUwEwYDVQQHEwxTYW50YSBNb25p
Y2ExEzARBgNVBAoTClJpb3QgR2FtZXMxHTAbBgNVBAsTFExvTCBHYW1lIEVuZ2lu
ZWVyaW5nMTMwMQYDVQQDEypMb0wgR2FtZSBFbmdpbmVlcmluZyBDZXJ0aWZpY2F0
ZSBBdXRob3JpdHkxLTArBgkqhkiG9w0BCQEWHmdhbWV0ZWNobm9sb2dpZXNAcmlv
dGdhbWVzLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKoJemF/
6PNG3GRJGbjzImTdOo1OJRDI7noRwJgDqkaJFkwv0X8aPUGbZSUzUO23cQcCgpYj
21ygzKu5dtCN2EcQVVpNtyPuM2V4eEGr1woodzALtufL3Nlyh6g5jKKuDIfeUBHv
JNyQf2h3Uha16lnrXmz9o9wsX/jf+jUAljBJqsMeACOpXfuZy+YKUCxSPOZaYTLC
y+0GQfiT431pJHBQlrXAUwzOmaJPQ7M6mLfsnpHibSkxUfMfHROaYCZ/sbWKl3lr
ZA9DbwaKKfS1Iw0ucAeDudyuqb4JntGU/W0aboKA0c3YB02mxAM4oDnqseuKV/CX
8SQAiaXnYotuNXMCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAf3KPmddqEqqC8iLs
lcd0euC4F5+USp9YsrZ3WuOzHqVxTtX3hR1scdlDXNvrsebQZUqwGdZGMS16ln3k
WObw7BbhU89tDNCN7Lt/IjT4MGRYRE+TmRc5EeIXxHkQ78bQqbmAI3GsW+7kJsoO
q3DdeE+M+BUJrhWorsAQCgUyZO166SAtKXKLIcxa+ddC49NvMQPJyzm3V+2b1roP
SvD2WV8gRYUnGmy/N0+u6ANq5EsbhZ548zZc+BI4upsWChTLyxt2RxR7+uGlS1+5
EcGfKZ+g024k/J32XP4hdho7WYAS2xMiV83CfLR/MNi8oSMaVQTdKD8cpgiWJk3L
XWehWA==
-----END CERTIFICATE-----
+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);
}
}
+248
View File
@@ -0,0 +1,248 @@
mod common;
use std::sync::atomic::Ordering;
use arena_tracker_core::{
ChampionState, Error, Scope, SeasonScope, Statistics, Tracker, default_seasons, load_seasons,
};
use common::{
CATALOG, FakeChampions, FakeHistory, SELF_PUUID, jan_2026, open_tracker, played_match,
recorded_account,
};
fn statistics(tracker: &Tracker) -> Statistics {
let scope = Scope {
season: SeasonScope::Season(common::S1.into()),
format: None,
};
tracker.statistics(SELF_PUUID, &scope).unwrap()
}
fn row_names(stats: &Statistics) -> Vec<&str> {
stats
.rows
.iter()
.map(|r| r.champion.name.as_str())
.collect()
}
/// A tracker on the same database file as `open_tracker`, whose history is empty.
fn reopen(dir: &std::path::Path, champions: FakeChampions) -> Tracker {
Tracker::open(
&dir.join("arena.db"),
Box::new(FakeHistory::new(recorded_account(), vec![])),
)
.unwrap()
.with_seasons(common::seasons())
.with_champions(Box::new(champions), dir.join("portraits"))
}
#[test]
fn the_catalog_is_fetched_once_while_the_game_version_is_unchanged() {
let dir = tempfile::tempdir().unwrap();
let first = FakeChampions::new("1.0", &CATALOG);
let first_calls = first.catalog_counter();
let tracker = reopen(dir.path(), first);
tracker.refresh_champions().unwrap();
tracker.refresh_champions().unwrap();
assert_eq!(first_calls.load(Ordering::SeqCst), 1);
assert_eq!(statistics(&tracker).challenge.unwrap().total, 6);
drop(tracker);
let same_version = FakeChampions::new("1.0", &CATALOG);
let same_calls = same_version.catalog_counter();
reopen(dir.path(), same_version)
.refresh_champions()
.unwrap();
assert_eq!(same_calls.load(Ordering::SeqCst), 0);
let mut grown = CATALOG.to_vec();
grown.push((777, "Newcomer", "Nouveau"));
let new_version = FakeChampions::new("2.0", &grown);
let new_calls = new_version.catalog_counter();
let tracker = reopen(dir.path(), new_version);
tracker.refresh_champions().unwrap();
assert_eq!(new_calls.load(Ordering::SeqCst), 1);
assert_eq!(statistics(&tracker).challenge.unwrap().total, 7);
}
#[test]
fn a_failing_source_leaves_the_cached_catalog_usable() {
let dir = tempfile::tempdir().unwrap();
reopen(dir.path(), FakeChampions::new("1.0", &CATALOG))
.refresh_champions()
.unwrap();
let offline = reopen(dir.path(), FakeChampions::new("2.0", &CATALOG).failing());
assert!(matches!(offline.refresh_champions(), Err(Error::Source(_))));
assert_eq!(statistics(&offline).challenge.unwrap().total, 6);
}
#[test]
fn without_any_catalog_the_page_shows_the_champions_played() {
let dir = tempfile::tempdir().unwrap();
let tracker = open_tracker(dir.path(), &[played_match(1, 3, jan_2026(2, 0))]).with_champions(
Box::new(FakeChampions::new("1.0", &CATALOG).failing()),
dir.path().join("portraits"),
);
assert!(tracker.refresh_champions().is_err());
tracker.sync(common::RIOT_ID, &mut |_| {}).unwrap();
let stats = statistics(&tracker);
assert_eq!(row_names(&stats), ["Annie"]);
assert_eq!(stats.challenge.unwrap().total, 1);
}
#[test]
fn a_champion_played_but_absent_from_the_catalog_still_gets_a_row() {
let dir = tempfile::tempdir().unwrap();
let tracker = open_tracker(dir.path(), &[played_match(1, 3, jan_2026(2, 0))]).with_champions(
Box::new(FakeChampions::new("1.0", &CATALOG[1..])),
dir.path().join("portraits"),
);
tracker.refresh_champions().unwrap();
tracker.sync(common::RIOT_ID, &mut |_| {}).unwrap();
let stats = statistics(&tracker);
assert_eq!(stats.rows.len(), 6);
let annie = stats.rows.iter().find(|r| r.champion.id == 1).unwrap();
assert_eq!(
(annie.champion.key.as_str(), annie.champion.name.as_str()),
("Annie", "Annie")
);
assert_eq!(annie.state, Some(ChampionState::InProgress));
assert_eq!(stats.challenge.unwrap().total, 6);
}
#[test]
fn rows_are_ordered_by_champion_name_in_french_order() {
let dir = tempfile::tempdir().unwrap();
let champions = [
(1, "Zoe", "Zoé"),
(2, "Zed", "Zed"),
(11, "MasterYi", "Maître Yi"),
(3, "Nami", "Nami"),
];
let tracker = reopen(dir.path(), FakeChampions::new("1.0", &champions));
tracker.refresh_champions().unwrap();
assert_eq!(
row_names(&statistics(&tracker)),
["Maître Yi", "Nami", "Zed", "Zoé"]
);
}
#[test]
fn portraits_are_downloaded_and_exposed_and_a_failed_one_is_left_out() {
let dir = tempfile::tempdir().unwrap();
let tracker = reopen(
dir.path(),
FakeChampions::new("1.0", &CATALOG).without_portrait("Jinx"),
);
assert!(
statistics(&tracker)
.rows
.iter()
.all(|r| r.portrait.is_none())
);
tracker.refresh_champions().unwrap();
let stats = statistics(&tracker);
let portraits = dir.path().join("portraits");
for row in &stats.rows {
if row.champion.key == "Jinx" {
assert_eq!(row.portrait, None);
} else {
let path = portraits.join(format!("{}.png", row.champion.key));
assert_eq!(row.portrait.as_ref(), Some(&path));
assert_eq!(
std::fs::read(&path).unwrap(),
format!("png of {}", row.champion.key).into_bytes()
);
}
}
assert!(!portraits.join("Jinx.part").exists());
}
#[test]
fn refreshing_without_a_champion_source_does_nothing() {
let dir = tempfile::tempdir().unwrap();
let tracker = open_tracker(dir.path(), &[]);
tracker.refresh_champions().unwrap();
assert!(!dir.path().join("portraits").exists());
}
#[test]
fn load_seasons_writes_the_shipped_table_when_the_file_is_missing() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("sub").join("seasons.toml");
let seasons = load_seasons(&path).unwrap();
assert_eq!(seasons, default_seasons());
assert!(
std::fs::read_to_string(&path)
.unwrap()
.contains("[[season]]")
);
assert_eq!(load_seasons(&path).unwrap(), seasons);
}
#[test]
fn load_seasons_reads_the_edited_file_sorted_by_start() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("seasons.toml");
std::fs::write(
&path,
"[[season]]\nname = \"Plus tard\"\nstart = 2027-02-01\nofficial_track = \"Piste X\"\n\n[[season]]\nname = \"Avant\"\nstart = 2026-12-31\n",
)
.unwrap();
let seasons = load_seasons(&path).unwrap();
let summary: Vec<_> = seasons
.iter()
.map(|s| (s.name.as_str(), s.start.to_string()))
.collect();
assert_eq!(
summary,
[
("Avant", "31/12/2026".to_string()),
("Plus tard", "01/02/2027".to_string())
]
);
let tracks: Vec<_> = seasons
.iter()
.map(|s| s.official_track.as_deref())
.collect();
assert_eq!(tracks, [None, Some("Piste X")]);
}
#[test]
fn load_seasons_rejects_invalid_files() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("seasons.toml");
for bad in [
"pas du toml",
"",
"[[season]]\nname = \"X\"\nstart = 2026-01-01T10:00:00\n",
"[[season]]\nname = \"X\"\nstart = 2026-01-01T10:00:00Z\n",
"[[season]]\nname = \"X\"\nstart = \"2026-01-01\"\n",
"[[season]]\nname = \"X\"\n",
"[[season]]\nstart = 2026-01-01\n",
] {
std::fs::write(&path, bad).unwrap();
assert!(
matches!(load_seasons(&path), Err(Error::Config(_))),
"{bad:?}"
);
}
}
+671
View File
@@ -0,0 +1,671 @@
//! Test doubles and payload builders shared by the integration tests.
// Each test binary uses its own subset of these helpers.
#![allow(dead_code)]
use std::collections::HashMap;
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use arena_tracker_core::{
Account, Champion, ChampionCatalog, ChampionSource, ClientError, Date, GameClientSource,
GamePhase, Gameflow, MatchHistorySource, Season, SourceError, Tracker,
};
use serde_json::Value;
pub const SELF_PUUID: &str = "fixture-puuid-self";
const BASE: &str = include_str!("../fixtures/riot/match_1750_EUW1_9000000006.json");
/// The six recorded Riot payloads.
pub fn recorded_matches() -> Vec<String> {
[
include_str!("../fixtures/riot/match_1700_EUW1_9000000001.json"),
include_str!("../fixtures/riot/match_1700_EUW1_9000000002.json"),
include_str!("../fixtures/riot/match_1740_EUW1_9000000004.json"),
include_str!("../fixtures/riot/match_1740_EUW1_9000000005.json"),
include_str!("../fixtures/riot/match_1750_EUW1_9000000003.json"),
include_str!("../fixtures/riot/match_1750_EUW1_9000000006.json"),
]
.map(String::from)
.to_vec()
}
pub fn recorded_account() -> Account {
serde_json::from_str(include_str!("../fixtures/riot/account.json")).unwrap()
}
/// A payload cloned from a recorded one, with the self participant patched.
pub fn payload(
match_id: &str,
queue_id: u32,
champion_id: u32,
champion_name: &str,
placement: u8,
win: bool,
started_at_ms: i64,
) -> String {
let mut v: Value = serde_json::from_str(BASE).unwrap();
v["metadata"]["matchId"] = match_id.into();
v["info"]["queueId"] = queue_id.into();
v["info"]["gameStartTimestamp"] = started_at_ms.into();
let me = v["info"]["participants"]
.as_array_mut()
.unwrap()
.iter_mut()
.find(|p| p["puuid"] == SELF_PUUID)
.unwrap();
me["championId"] = champion_id.into();
me["championName"] = champion_name.into();
me["placement"] = placement.into();
me["win"] = win.into();
v.to_string()
}
pub fn with_game_mode(payload: &str, game_mode: &str) -> String {
let mut v: Value = serde_json::from_str(payload).unwrap();
v["info"]["gameMode"] = game_mode.into();
v.to_string()
}
/// The payload with these fields missing from every participant but the Account.
pub fn without_fields_for_others(payload: &str, fields: &[&str]) -> String {
let mut v: Value = serde_json::from_str(payload).unwrap();
for p in v["info"]["participants"].as_array_mut().unwrap() {
if p["puuid"] != SELF_PUUID {
for field in fields {
p.as_object_mut().unwrap().remove(*field);
}
}
}
v.to_string()
}
pub fn played_by(payload: &str, puuid: &str) -> String {
payload.replace(SELF_PUUID, puuid)
}
fn queue_and_start(raw: &str) -> (u32, i64) {
let v: Value = serde_json::from_str(raw).unwrap();
(
v["info"]["queueId"].as_u64().unwrap() as u32,
v["info"]["gameStartTimestamp"].as_i64().unwrap(),
)
}
fn match_id(raw: &str) -> String {
let v: Value = serde_json::from_str(raw).unwrap();
v["metadata"]["matchId"].as_str().unwrap().to_string()
}
struct Listing {
owner: String,
/// The queue the id is listed under.
queue_id: u32,
match_id: String,
started_ms: i64,
/// `None`: Riot lists the id but answers "not found" when asked for it.
raw: Option<String>,
/// Unlisted Matches can only be fetched by their id.
listed: bool,
}
impl Listing {
fn of(owner: &str, raw: String) -> Listing {
let (queue_id, started_ms) = queue_and_start(&raw);
Listing {
owner: owner.into(),
queue_id,
match_id: match_id(&raw),
started_ms,
raw: Some(raw),
listed: true,
}
}
}
/// In-memory Match history that behaves like Riot's (newest first, paged, filtered by queue).
pub struct FakeHistory {
accounts: Vec<Account>,
listings: Mutex<Vec<Listing>>,
/// Every call fails with this until it is cleared.
failure: Mutex<Option<SourceError>>,
fail_after: Option<usize>,
rate_limit_once: AtomicBool,
/// Lists in the order the Matches were added instead of newest first.
as_given: bool,
/// Called at the start of every fetch: announces it, then waits to be released.
gate: Option<(Sender<()>, Mutex<Receiver<()>>)>,
fetches: Arc<AtomicUsize>,
listed: Arc<AtomicUsize>,
calls: Arc<AtomicUsize>,
}
impl FakeHistory {
pub fn new(account: Account, payloads: Vec<String>) -> FakeHistory {
FakeHistory {
accounts: Vec::new(),
listings: Mutex::default(),
failure: Mutex::default(),
fail_after: None,
rate_limit_once: AtomicBool::new(false),
as_given: false,
gate: None,
fetches: Arc::default(),
listed: Arc::default(),
calls: Arc::default(),
}
.with_account(account, payloads)
}
/// Another Account Riot can resolve; its payloads must have been built for its puuid.
pub fn with_account(mut self, account: Account, payloads: Vec<String>) -> FakeHistory {
for raw in payloads {
self.add_for(&account.puuid, raw);
}
self.accounts.push(account);
self
}
/// Lists a payload under a queue other than its own: a sync only asks for Arena queues.
pub fn listed_under(self, queue_id: u32, payload: String) -> FakeHistory {
let owner = self.accounts[0].puuid.clone();
self.listings.lock().unwrap().push(Listing {
queue_id,
..Listing::of(&owner, payload)
});
self
}
/// A Match that appears for the first Account (e.g. one that has just been played).
pub fn add(&self, payload: String) {
self.add_for(&self.accounts[0].puuid, payload);
}
pub fn add_for(&self, puuid: &str, raw: String) {
self.listings.lock().unwrap().push(Listing::of(puuid, raw));
}
/// A Match Riot has but does not list, like one of a queue the app does not know.
pub fn add_unlisted(&self, payload: String) {
let owner = self.accounts[0].puuid.clone();
self.listings.lock().unwrap().push(Listing {
listed: false,
..Listing::of(&owner, payload)
});
}
/// An id Riot lists (Arena 3x6) but cannot deliver.
pub fn add_missing(&self, match_id: &str, started_ms: i64) {
self.add_broken(match_id, started_ms, None);
}
/// An id Riot lists (Arena 3x6) whose payload is not a readable Match.
pub fn add_unreadable(&self, match_id: &str, started_ms: i64, text: &str) {
self.add_broken(match_id, started_ms, Some(text.into()));
}
fn add_broken(&self, match_id: &str, started_ms: i64, raw: Option<String>) {
let owner = self.accounts[0].puuid.clone();
self.listings.lock().unwrap().push(Listing {
owner,
queue_id: 1750,
match_id: match_id.into(),
started_ms,
raw,
listed: true,
});
}
/// Lists Matches in the order they were added, however old they are.
pub fn delivered_as_given(mut self) -> FakeHistory {
self.as_given = true;
self
}
/// Every call fails with this error until `None` is set.
pub fn fail_with(&self, error: Option<SourceError>) {
*self.failure.lock().unwrap() = error;
}
/// Every fetch after the first `n` fails with a network error.
pub fn failing_after(mut self, n: usize) -> FakeHistory {
self.fail_after = Some(n);
self
}
/// The first fetch answers "rate limited" once.
pub fn rate_limited_once(mut self) -> FakeHistory {
self.rate_limit_once = AtomicBool::new(true);
self
}
/// Each fetch sends on `entered`, then blocks until `release` delivers.
pub fn gated(mut self, entered: Sender<()>, release: Receiver<()>) -> FakeHistory {
self.gate = Some((entered, Mutex::new(release)));
self
}
/// Payloads delivered by `fetch_match`, still readable after the fake is boxed.
pub fn fetch_counter(&self) -> Arc<AtomicUsize> {
self.fetches.clone()
}
/// Match ids returned by `match_ids`.
pub fn listed_counter(&self) -> Arc<AtomicUsize> {
self.listed.clone()
}
/// Calls of any kind made to the source.
pub fn call_counter(&self) -> Arc<AtomicUsize> {
self.calls.clone()
}
fn enter(&self) -> Result<(), SourceError> {
self.calls.fetch_add(1, Ordering::SeqCst);
match &*self.failure.lock().unwrap() {
Some(error) => Err(error.clone()),
None => Ok(()),
}
}
}
impl MatchHistorySource for FakeHistory {
fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result<Account, SourceError> {
self.enter()?;
// Riot IDs are case-insensitive for Riot, too.
self.accounts
.iter()
.find(|a| {
a.game_name.eq_ignore_ascii_case(game_name)
&& a.tag_line.eq_ignore_ascii_case(tag_line)
})
.cloned()
.ok_or(SourceError::NotFound)
}
fn match_ids(
&self,
puuid: &str,
queue_id: u32,
start: usize,
count: usize,
start_time_s: Option<i64>,
) -> Result<Vec<String>, SourceError> {
self.enter()?;
let mut found: Vec<_> = self
.listings
.lock()
.unwrap()
.iter()
.filter(|l| l.listed && l.owner == puuid && l.queue_id == queue_id)
.filter(|l| start_time_s.is_none_or(|t| l.started_ms / 1000 >= t))
.map(|l| (l.started_ms, l.match_id.clone()))
.collect();
if !self.as_given {
found.sort_by_key(|(started_ms, _)| std::cmp::Reverse(*started_ms));
}
let page: Vec<String> = found
.into_iter()
.skip(start)
.take(count)
.map(|(_, id)| id)
.collect();
self.listed.fetch_add(page.len(), Ordering::SeqCst);
Ok(page)
}
fn fetch_match(&self, id: &str) -> Result<String, SourceError> {
self.enter()?;
if let Some((entered, release)) = &self.gate {
entered.send(()).unwrap();
release.lock().unwrap().recv().unwrap();
}
if self.rate_limit_once.swap(false, Ordering::SeqCst) {
return Err(SourceError::RateLimited {
retry_after: Duration::ZERO,
});
}
if self
.fail_after
.is_some_and(|n| self.fetches.load(Ordering::SeqCst) >= n)
{
return Err(SourceError::Network("connexion perdue".into()));
}
let raw = self
.listings
.lock()
.unwrap()
.iter()
.find(|l| l.match_id == id)
.and_then(|l| l.raw.clone())
.ok_or(SourceError::NotFound)?;
self.fetches.fetch_add(1, Ordering::SeqCst);
Ok(raw)
}
}
/// Champion reference data served from memory.
pub struct FakeChampions {
version: String,
champions: Vec<Champion>,
failing: bool,
no_portrait: Vec<String>,
catalog_calls: Arc<AtomicUsize>,
}
impl FakeChampions {
/// `champions`: (id, key, display name).
pub fn new(version: &str, champions: &[(u32, &str, &str)]) -> FakeChampions {
FakeChampions {
version: version.into(),
champions: champions
.iter()
.map(|&(id, key, name)| Champion {
id,
key: key.into(),
name: name.into(),
})
.collect(),
failing: false,
no_portrait: Vec::new(),
catalog_calls: Arc::default(),
}
}
/// Every call fails with a network error.
pub fn failing(mut self) -> FakeChampions {
self.failing = true;
self
}
/// The portrait download of this champion key fails.
pub fn without_portrait(mut self, key: &str) -> FakeChampions {
self.no_portrait.push(key.into());
self
}
pub fn catalog_counter(&self) -> Arc<AtomicUsize> {
self.catalog_calls.clone()
}
fn check(&self) -> Result<(), SourceError> {
if self.failing {
Err(SourceError::Network("hors ligne".into()))
} else {
Ok(())
}
}
}
impl ChampionSource for FakeChampions {
fn latest_version(&self) -> Result<String, SourceError> {
self.check()?;
Ok(self.version.clone())
}
fn catalog(&self, version: &str) -> Result<ChampionCatalog, SourceError> {
self.catalog_calls.fetch_add(1, Ordering::SeqCst);
self.check()?;
Ok(ChampionCatalog {
version: version.into(),
champions: self.champions.clone(),
})
}
fn portrait(&self, _version: &str, key: &str) -> Result<Vec<u8>, SourceError> {
self.check()?;
if self.no_portrait.iter().any(|k| k == key) {
return Err(SourceError::NotFound);
}
Ok(format!("png of {key}").into_bytes())
}
}
// Statistics scenarios: a small catalog, two Seasons and Matches described by champion and Placement.
pub const RIOT_ID: &str = "Joueur#EUW";
pub const HOUR_MS: i64 = 3_600_000;
pub const S1: &str = "Saison A";
pub const S2: &str = "Saison B";
/// The name of the progression track recorded from the real client for the Season 2 2026.
pub const S2_TRACK: &str = "2026 Season 2 Champs Completed Track";
/// (id, key, French name)
pub const CATALOG: [(u32, &str, &str); 6] = [
(1, "Annie", "Annie"),
(8, "Vladimir", "Vladimir"),
(11, "MasterYi", "Maître Yi"),
(19, "Warwick", "Warwick"),
(103, "Ahri", "Ahri"),
(222, "Jinx", "Jinx"),
];
pub fn date(year: i32, month: u8, day: u8) -> Date {
Date { year, month, day }
}
/// `hours` after 00:00 UTC of `date`.
pub fn at(date: Date, hours: i64) -> i64 {
date.start_ms() + hours * HOUR_MS
}
/// `hours` after 00:00 UTC on a day of January 2026 (inside S1).
pub fn jan_2026(day: u8, hours: i64) -> i64 {
at(date(2026, 1, day), hours)
}
/// S1 starts on 2026-01-01 and S2 on 2026-04-01; only S2 has an official track.
pub fn seasons() -> Vec<Season> {
vec![
Season {
name: S1.into(),
start: date(2026, 1, 1),
official_track: None,
},
Season {
name: S2.into(),
start: date(2026, 4, 1),
official_track: Some(S2_TRACK.into()),
},
]
}
#[derive(Clone)]
pub struct PlayedMatch {
pub champion: u32,
pub placement: u8,
pub queue_id: u32,
pub started_at_ms: i64,
}
/// An Arena 3x6 Match.
pub fn played_match(champion: u32, placement: u8, started_at_ms: i64) -> PlayedMatch {
PlayedMatch {
champion,
placement,
queue_id: 1750,
started_at_ms,
}
}
impl PlayedMatch {
pub fn in_format(mut self, queue_id: u32) -> PlayedMatch {
self.queue_id = queue_id;
self
}
}
/// One Match per Placement, an hour apart from `from_ms`.
pub fn run(champion: u32, placements: &[u8], from_ms: i64) -> Vec<PlayedMatch> {
(0..)
.zip(placements)
.map(|(i, &p)| played_match(champion, p, from_ms + i * HOUR_MS))
.collect()
}
/// The payloads of the Matches, as the Riot API would serve them (win = top 3).
pub fn payloads(matches: &[PlayedMatch]) -> Vec<String> {
(0..)
.zip(matches)
.map(|(i, m)| {
let key = CATALOG
.iter()
.find(|(id, _, _)| *id == m.champion)
.map_or("Unknown", |(_, key, _)| key);
payload(
&format!("EUW1_{i}"),
m.queue_id,
m.champion,
key,
m.placement,
m.placement <= 3,
m.started_at_ms,
)
})
.collect()
}
pub fn open_tracker(dir: &Path, matches: &[PlayedMatch]) -> Tracker {
Tracker::open(
&dir.join("arena.db"),
Box::new(FakeHistory::new(recorded_account(), payloads(matches))),
)
.unwrap()
.with_seasons(seasons())
}
/// A tracker with the six-champion catalog cached and the Matches imported.
pub fn imported_tracker(dir: &Path, matches: &[PlayedMatch]) -> Tracker {
let tracker = open_tracker(dir, matches).with_champions(
Box::new(FakeChampions::new("1.0", &CATALOG)),
dir.join("portraits"),
);
tracker.refresh_champions().unwrap();
tracker.sync(RIOT_ID, &mut |_| {}).unwrap();
tracker
}
/// The id of the Arena game in the recorded in-game session of the client.
pub fn recorded_game_id() -> u64 {
let session: Value = serde_json::from_str(include_str!(
"../fixtures/client/gameflow_session_in_game.json"
))
.unwrap();
session["gameData"]["gameId"].as_u64().unwrap()
}
/// The game client, driven by the test between rounds.
#[derive(Clone, Default)]
pub struct FakeClient {
state: Arc<Mutex<ClientState>>,
}
#[derive(Default)]
struct ClientState {
signed_in: Option<(String, String)>,
gameflow: Gameflow,
tracks: HashMap<String, u32>,
waits: Vec<Duration>,
}
impl FakeClient {
/// A client that is not running.
pub fn absent() -> FakeClient {
FakeClient::default()
}
/// Signed in as the recorded Account, with what the real client answered.
pub fn recorded() -> FakeClient {
let client = FakeClient::default();
let summoner: Value =
serde_json::from_str(include_str!("../fixtures/client/current_summoner.json")).unwrap();
client.sign_in(
summoner["gameName"].as_str().unwrap(),
summoner["tagLine"].as_str().unwrap(),
);
let phase: String =
serde_json::from_str(include_str!("../fixtures/client/gameflow_phase_none.json"))
.unwrap();
client.set_phase(&phase, false);
let groups: Vec<Value> = serde_json::from_str(include_str!(
"../fixtures/client/progression_groups_configuration.json"
))
.unwrap();
let instance: Value = serde_json::from_str(include_str!(
"../fixtures/client/progression_instance_data.json"
))
.unwrap();
let group = groups
.iter()
.find(|g| g["id"] == instance["groupId"])
.unwrap();
client.set_track(
group["name"].as_str().unwrap(),
instance["counters"][0]["counterValue"].as_u64().unwrap() as u32,
);
client
}
pub fn sign_in(&self, game_name: &str, tag_line: &str) {
self.state.lock().unwrap().signed_in = Some((game_name.into(), tag_line.into()));
}
/// The client closes.
pub fn sign_out(&self) {
self.state.lock().unwrap().signed_in = None;
}
/// `phase` is the client's own name for it, e.g. "InProgress".
pub fn set_phase(&self, phase: &str, arena: bool) {
let mut state = self.state.lock().unwrap();
state.gameflow = Gameflow {
phase: GamePhase::from_client(phase),
arena,
..state.gameflow.clone()
};
}
/// The client's id of the game being played (kept across phases until changed).
pub fn set_game_id(&self, game_id: Option<u64>) {
self.state.lock().unwrap().gameflow.game_id = game_id;
}
pub fn set_track(&self, name: &str, value: u32) {
self.state.lock().unwrap().tracks.insert(name.into(), value);
}
pub fn remove_track(&self, name: &str) {
self.state.lock().unwrap().tracks.remove(name);
}
/// The timeouts the tracker asked to wait for.
pub fn waits(&self) -> Vec<Duration> {
self.state.lock().unwrap().waits.clone()
}
}
impl GameClientSource for FakeClient {
fn signed_in(&self) -> Result<(String, String), ClientError> {
let state = self.state.lock().unwrap();
state.signed_in.clone().ok_or(ClientError::Absent)
}
fn gameflow(&self) -> Result<Gameflow, ClientError> {
let state = self.state.lock().unwrap();
state.signed_in.as_ref().ok_or(ClientError::Absent)?;
Ok(state.gameflow.clone())
}
fn official_progress(&self, track_name: &str) -> Result<Option<u32>, ClientError> {
let state = self.state.lock().unwrap();
state.signed_in.as_ref().ok_or(ClientError::Absent)?;
Ok(state.tracks.get(track_name).copied())
}
fn wait_for_change(&self, timeout: Duration) {
self.state.lock().unwrap().waits.push(timeout);
}
}
@@ -0,0 +1,6 @@
{
"errorCode": "RPC_ERROR",
"httpStatus": 404,
"implementationDetails": {},
"message": "No active delegate"
}
+24
View File
@@ -0,0 +1,24 @@
{
"accountId": 1000001,
"displayName": "Joueur",
"gameName": "Joueur",
"internalName": "Joueur",
"nameChangeFlag": false,
"percentCompleteForNextLevel": 43,
"privacy": "PUBLIC",
"profileIconId": 1,
"puuid": "fixture-puuid-self",
"rerollPoints": {
"currentPoints": 0,
"maxRolls": 2,
"numberOfRolls": 0,
"pointsCostToRoll": 250,
"pointsToReroll": 250
},
"summonerId": 2000002,
"summonerLevel": 867,
"tagLine": "EUW",
"unnamed": false,
"xpSinceLastLevel": 1499,
"xpUntilNextLevel": 3456
}
@@ -0,0 +1 @@
"None"
@@ -0,0 +1,6 @@
{
"errorCode": "RPC_ERROR",
"httpStatus": 404,
"implementationDetails": {},
"message": "No gameflow session exists."
}
@@ -0,0 +1,27 @@
{
"phase": "InProgress",
"gameData": {
"gameId": 9000000099,
"isCustomGame": false,
"queue": {
"id": 1750,
"mapId": 30,
"name": "Arena 3x6",
"shortName": "Arena 3x6",
"type": "CHERRY",
"gameMode": "CHERRY",
"category": "PvP",
"isRanked": false,
"isCustom": false
}
},
"map": {
"id": 30,
"name": "Arena",
"mapStringId": "TGR",
"gameMode": "CHERRY",
"gameModeName": "Arena",
"gameModeShortName": "Arena",
"isRGM": false
}
}
@@ -0,0 +1,94 @@
[
{
"counters": [
{
"direction": "INCREASING",
"groupId": "",
"id": "d453b6dd-9cfd-5be5-9279-bdaf01235756",
"name": "Opal_SilverShields",
"startValue": 0
}
],
"id": "337e6110-69cf-4a19-bfbc-e6e86acdedca",
"milestones": [],
"name": "Opal_Progression",
"productId": "",
"repeat": {
"count": 0,
"milestones": [],
"multiplier": 1.0,
"repeatTriggers": [],
"scope": 0
},
"schemaVersion": "1.0"
},
{
"counters": [
{
"direction": "INCREASING",
"groupId": "",
"id": "d64a3f04-2ba0-475a-9a33-782cb12e6467",
"name": "2026 Season 2 Cherry Champs Completed Counter",
"startValue": 0
}
],
"id": "01030e0d-e3e3-4034-93dc-44a88bcb8401",
"milestones": [],
"name": "2026 Season 2 Champs Completed Track",
"productId": "",
"repeat": {
"count": 0,
"milestones": [],
"multiplier": 0.0,
"repeatTriggers": [],
"scope": 0
},
"schemaVersion": "2.0"
},
{
"counters": [
{
"direction": "INCREASING",
"groupId": "",
"id": "be96f5dc-d65c-4ea4-9a23-0b2c1bb6880f",
"name": "2026 Season 1 Cherry Champs Completed Counter",
"startValue": 0
}
],
"id": "7d0ef399-dd59-4005-bf1d-e0b98cda8acb",
"milestones": [],
"name": "2026 Season 1 Champs Completed Track",
"productId": "",
"repeat": {
"count": 0,
"milestones": [],
"multiplier": 1.0,
"repeatTriggers": [],
"scope": 0
},
"schemaVersion": "1.0"
},
{
"counters": [
{
"direction": "INCREASING",
"groupId": "",
"id": "ae1d0604-8841-4640-987e-29696c18caca",
"name": "Cherry 2025 Champs Completed Counter",
"startValue": 0
}
],
"id": "e5d45c5c-a035-4e0a-9c9d-c02a3604a3b9",
"milestones": [],
"name": "Cherry 2025 Champs Completed Track",
"productId": "",
"repeat": {
"count": 0,
"milestones": [],
"multiplier": 1.0,
"repeatTriggers": [],
"scope": 0
},
"schemaVersion": "1.0"
}
]
@@ -0,0 +1,14 @@
{
"counters": [
{
"counterId": "d64a3f04-2ba0-475a-9a33-782cb12e6467",
"counterValue": 52,
"groupId": "",
"ownerId": "",
"productId": ""
}
],
"groupId": "01030e0d-e3e3-4034-93dc-44a88bcb8401",
"milestones": [],
"schemaVersion": "2.0"
}
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
["16.22.1", "16.21.1", "16.20.1"]
+5
View File
@@ -0,0 +1,5 @@
{
"puuid": "fixture-puuid-self",
"gameName": "Joueur",
"tagLine": "EUW"
}
@@ -0,0 +1,234 @@
{
"metadata": {
"dataVersion": "2",
"matchId": "EUW1_9000000001",
"participants": [
"fixture-puuid-01",
"fixture-puuid-02",
"fixture-puuid-03",
"fixture-puuid-04",
"fixture-puuid-05",
"fixture-puuid-06",
"fixture-puuid-07",
"fixture-puuid-08",
"fixture-puuid-09",
"fixture-puuid-10",
"fixture-puuid-11",
"fixture-puuid-12",
"fixture-puuid-13",
"fixture-puuid-14",
"fixture-puuid-15",
"fixture-puuid-self"
]
},
"info": {
"endOfGameResult": "GameComplete",
"gameCreation": 1765540183371,
"gameDuration": 1286,
"gameEndTimestamp": 1765541564635,
"gameId": 9000000001,
"gameMode": "CHERRY",
"gameName": "teambuilder-match-9000000001",
"gameStartTimestamp": 1765540278065,
"gameType": "MATCHED_GAME",
"gameVersion": "15.24.732.64",
"mapId": 30,
"platformId": "EUW1",
"queueId": 1700,
"tournamentCode": "",
"participants": [
{
"puuid": "fixture-puuid-01",
"riotIdGameName": "Autre01",
"riotIdTagline": "FIX",
"championId": 77,
"championName": "Udyr",
"placement": 8,
"subteamPlacement": 8,
"playerSubteamId": 8,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-02",
"riotIdGameName": "Autre02",
"riotIdTagline": "FIX",
"championId": 103,
"championName": "Ahri",
"placement": 3,
"subteamPlacement": 3,
"playerSubteamId": 3,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-03",
"riotIdGameName": "Autre03",
"riotIdTagline": "FIX",
"championId": 901,
"championName": "Smolder",
"placement": 1,
"subteamPlacement": 1,
"playerSubteamId": 4,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-04",
"riotIdGameName": "Autre04",
"riotIdTagline": "FIX",
"championId": 350,
"championName": "Yuumi",
"placement": 8,
"subteamPlacement": 8,
"playerSubteamId": 8,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-05",
"riotIdGameName": "Autre05",
"riotIdTagline": "FIX",
"championId": 48,
"championName": "Trundle",
"placement": 7,
"subteamPlacement": 7,
"playerSubteamId": 2,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-06",
"riotIdGameName": "Autre06",
"riotIdTagline": "FIX",
"championId": 18,
"championName": "Tristana",
"placement": 7,
"subteamPlacement": 7,
"playerSubteamId": 2,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-07",
"riotIdGameName": "Autre07",
"riotIdTagline": "FIX",
"championId": 72,
"championName": "Skarner",
"placement": 4,
"subteamPlacement": 4,
"playerSubteamId": 7,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-08",
"riotIdGameName": "Autre08",
"riotIdTagline": "FIX",
"championId": 106,
"championName": "Volibear",
"placement": 6,
"subteamPlacement": 6,
"playerSubteamId": 6,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-09",
"riotIdGameName": "Autre09",
"riotIdTagline": "FIX",
"championId": 51,
"championName": "Caitlyn",
"placement": 2,
"subteamPlacement": 2,
"playerSubteamId": 5,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-10",
"riotIdGameName": "Autre10",
"riotIdTagline": "FIX",
"championId": 360,
"championName": "Samira",
"placement": 2,
"subteamPlacement": 2,
"playerSubteamId": 5,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-11",
"riotIdGameName": "Autre11",
"riotIdTagline": "FIX",
"championId": 202,
"championName": "Jhin",
"placement": 3,
"subteamPlacement": 3,
"playerSubteamId": 3,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-12",
"riotIdGameName": "Autre12",
"riotIdTagline": "FIX",
"championId": 268,
"championName": "Azir",
"placement": 6,
"subteamPlacement": 6,
"playerSubteamId": 6,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-13",
"riotIdGameName": "Autre13",
"riotIdTagline": "FIX",
"championId": 80,
"championName": "Pantheon",
"placement": 5,
"subteamPlacement": 5,
"playerSubteamId": 1,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-14",
"riotIdGameName": "Autre14",
"riotIdTagline": "FIX",
"championId": 50,
"championName": "Swain",
"placement": 5,
"subteamPlacement": 5,
"playerSubteamId": 1,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-15",
"riotIdGameName": "Autre15",
"riotIdTagline": "FIX",
"championId": 145,
"championName": "Kaisa",
"placement": 1,
"subteamPlacement": 1,
"playerSubteamId": 4,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-self",
"riotIdGameName": "Joueur",
"riotIdTagline": "EUW",
"championId": 222,
"championName": "Jinx",
"placement": 4,
"subteamPlacement": 4,
"playerSubteamId": 7,
"win": true,
"teamId": 100
}
]
}
}
@@ -0,0 +1,234 @@
{
"metadata": {
"dataVersion": "2",
"matchId": "EUW1_9000000002",
"participants": [
"fixture-puuid-01",
"fixture-puuid-02",
"fixture-puuid-03",
"fixture-puuid-04",
"fixture-puuid-05",
"fixture-puuid-06",
"fixture-puuid-07",
"fixture-puuid-08",
"fixture-puuid-09",
"fixture-puuid-10",
"fixture-puuid-11",
"fixture-puuid-12",
"fixture-puuid-13",
"fixture-puuid-14",
"fixture-puuid-15",
"fixture-puuid-self"
]
},
"info": {
"endOfGameResult": "GameComplete",
"gameCreation": 1778621899569,
"gameDuration": 1559,
"gameEndTimestamp": 1778623484903,
"gameId": 9000000002,
"gameMode": "CHERRY",
"gameName": "teambuilder-match-9000000002",
"gameStartTimestamp": 1778621925732,
"gameType": "MATCHED_GAME",
"gameVersion": "16.9.772.8292",
"mapId": 30,
"platformId": "EUW1",
"queueId": 1700,
"tournamentCode": "",
"participants": [
{
"puuid": "fixture-puuid-01",
"riotIdGameName": "Autre01",
"riotIdTagline": "FIX",
"championId": 90,
"championName": "Malzahar",
"placement": 3,
"subteamPlacement": 3,
"playerSubteamId": 2,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-02",
"riotIdGameName": "Autre02",
"riotIdTagline": "FIX",
"championId": 1,
"championName": "Annie",
"placement": 3,
"subteamPlacement": 3,
"playerSubteamId": 2,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-03",
"riotIdGameName": "Autre03",
"riotIdTagline": "FIX",
"championId": 32,
"championName": "Amumu",
"placement": 4,
"subteamPlacement": 4,
"playerSubteamId": 7,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-04",
"riotIdGameName": "Autre04",
"riotIdTagline": "FIX",
"championId": 17,
"championName": "Teemo",
"placement": 8,
"subteamPlacement": 8,
"playerSubteamId": 3,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-05",
"riotIdGameName": "Autre05",
"riotIdTagline": "FIX",
"championId": 86,
"championName": "Garen",
"placement": 8,
"subteamPlacement": 8,
"playerSubteamId": 3,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-06",
"riotIdGameName": "Autre06",
"riotIdTagline": "FIX",
"championId": 56,
"championName": "Nocturne",
"placement": 2,
"subteamPlacement": 2,
"playerSubteamId": 5,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-07",
"riotIdGameName": "Autre07",
"riotIdTagline": "FIX",
"championId": 45,
"championName": "Veigar",
"placement": 4,
"subteamPlacement": 4,
"playerSubteamId": 7,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-08",
"riotIdGameName": "Autre08",
"riotIdTagline": "FIX",
"championId": 98,
"championName": "Shen",
"placement": 5,
"subteamPlacement": 5,
"playerSubteamId": 8,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-09",
"riotIdGameName": "Autre09",
"riotIdTagline": "FIX",
"championId": 40,
"championName": "Janna",
"placement": 6,
"subteamPlacement": 6,
"playerSubteamId": 4,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-10",
"riotIdGameName": "Autre10",
"riotIdTagline": "FIX",
"championId": 518,
"championName": "Neeko",
"placement": 6,
"subteamPlacement": 6,
"playerSubteamId": 4,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-11",
"riotIdGameName": "Autre11",
"riotIdTagline": "FIX",
"championId": 83,
"championName": "Yorick",
"placement": 7,
"subteamPlacement": 7,
"playerSubteamId": 1,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-12",
"riotIdGameName": "Autre12",
"riotIdTagline": "FIX",
"championId": 17,
"championName": "Teemo",
"placement": 7,
"subteamPlacement": 7,
"playerSubteamId": 1,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-13",
"riotIdGameName": "Autre13",
"riotIdTagline": "FIX",
"championId": 777,
"championName": "Yone",
"placement": 5,
"subteamPlacement": 5,
"playerSubteamId": 8,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-14",
"riotIdGameName": "Autre14",
"riotIdTagline": "FIX",
"championId": 50,
"championName": "Swain",
"placement": 1,
"subteamPlacement": 1,
"playerSubteamId": 6,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-15",
"riotIdGameName": "Autre15",
"riotIdTagline": "FIX",
"championId": 77,
"championName": "Udyr",
"placement": 1,
"subteamPlacement": 1,
"playerSubteamId": 6,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-self",
"riotIdGameName": "Joueur",
"riotIdTagline": "EUW",
"championId": 11,
"championName": "MasterYi",
"placement": 2,
"subteamPlacement": 2,
"playerSubteamId": 5,
"win": true,
"teamId": 100
}
]
}
}
@@ -0,0 +1,260 @@
{
"metadata": {
"dataVersion": "2",
"matchId": "EUW1_9000000004",
"participants": [
"fixture-puuid-01",
"fixture-puuid-self",
"fixture-puuid-03",
"fixture-puuid-04",
"fixture-puuid-05",
"fixture-puuid-06",
"fixture-puuid-07",
"fixture-puuid-08",
"fixture-puuid-09",
"fixture-puuid-10",
"fixture-puuid-11",
"fixture-puuid-12",
"fixture-puuid-13",
"fixture-puuid-14",
"fixture-puuid-15",
"fixture-puuid-16",
"fixture-puuid-17",
"fixture-puuid-18"
]
},
"info": {
"endOfGameResult": "GameComplete",
"gameCreation": 1784407849858,
"gameDuration": 1466,
"gameEndTimestamp": 1784409359696,
"gameId": 9000000004,
"gameMode": "CHERRY",
"gameName": "teambuilder-match-9000000004",
"gameStartTimestamp": 1784407893073,
"gameType": "MATCHED_GAME",
"gameVersion": "16.14.794.5912",
"mapId": 30,
"platformId": "EUW1",
"queueId": 1740,
"tournamentCode": "",
"participants": [
{
"puuid": "fixture-puuid-01",
"riotIdGameName": "Autre01",
"riotIdTagline": "FIX",
"championId": 150,
"championName": "Gnar",
"placement": 2,
"subteamPlacement": 2,
"playerSubteamId": 5,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-self",
"riotIdGameName": "Joueur",
"riotIdTagline": "EUW",
"championId": 8,
"championName": "Vladimir",
"placement": 2,
"subteamPlacement": 2,
"playerSubteamId": 5,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-03",
"riotIdGameName": "Autre03",
"riotIdTagline": "FIX",
"championId": 235,
"championName": "Senna",
"placement": 1,
"subteamPlacement": 1,
"playerSubteamId": 6,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-04",
"riotIdGameName": "Autre04",
"riotIdTagline": "FIX",
"championId": 69,
"championName": "Cassiopeia",
"placement": 3,
"subteamPlacement": 3,
"playerSubteamId": 3,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-05",
"riotIdGameName": "Autre05",
"riotIdTagline": "FIX",
"championId": 85,
"championName": "Kennen",
"placement": 3,
"subteamPlacement": 3,
"playerSubteamId": 3,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-06",
"riotIdGameName": "Autre06",
"riotIdTagline": "FIX",
"championId": 235,
"championName": "Senna",
"placement": 3,
"subteamPlacement": 3,
"playerSubteamId": 3,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-07",
"riotIdGameName": "Autre07",
"riotIdTagline": "FIX",
"championId": 223,
"championName": "TahmKench",
"placement": 1,
"subteamPlacement": 1,
"playerSubteamId": 6,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-08",
"riotIdGameName": "Autre08",
"riotIdTagline": "FIX",
"championId": 30,
"championName": "Karthus",
"placement": 5,
"subteamPlacement": 5,
"playerSubteamId": 4,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-09",
"riotIdGameName": "Autre09",
"riotIdTagline": "FIX",
"championId": 266,
"championName": "Aatrox",
"placement": 1,
"subteamPlacement": 1,
"playerSubteamId": 6,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-10",
"riotIdGameName": "Autre10",
"riotIdTagline": "FIX",
"championId": 91,
"championName": "Talon",
"placement": 6,
"subteamPlacement": 6,
"playerSubteamId": 1,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-11",
"riotIdGameName": "Autre11",
"riotIdTagline": "FIX",
"championId": 72,
"championName": "Skarner",
"placement": 6,
"subteamPlacement": 6,
"playerSubteamId": 1,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-12",
"riotIdGameName": "Autre12",
"riotIdTagline": "FIX",
"championId": 711,
"championName": "Vex",
"placement": 4,
"subteamPlacement": 4,
"playerSubteamId": 2,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-13",
"riotIdGameName": "Autre13",
"riotIdTagline": "FIX",
"championId": 202,
"championName": "Jhin",
"placement": 5,
"subteamPlacement": 5,
"playerSubteamId": 4,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-14",
"riotIdGameName": "Autre14",
"riotIdTagline": "FIX",
"championId": 44,
"championName": "Taric",
"placement": 6,
"subteamPlacement": 6,
"playerSubteamId": 1,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-15",
"riotIdGameName": "Autre15",
"riotIdTagline": "FIX",
"championId": 141,
"championName": "Kayn",
"placement": 4,
"subteamPlacement": 4,
"playerSubteamId": 2,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-16",
"riotIdGameName": "Autre16",
"riotIdTagline": "FIX",
"championId": 427,
"championName": "Ivern",
"placement": 4,
"subteamPlacement": 4,
"playerSubteamId": 2,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-17",
"riotIdGameName": "Autre17",
"riotIdTagline": "FIX",
"championId": 9,
"championName": "FiddleSticks",
"placement": 5,
"subteamPlacement": 5,
"playerSubteamId": 4,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-18",
"riotIdGameName": "Autre18",
"riotIdTagline": "FIX",
"championId": 105,
"championName": "Fizz",
"placement": 2,
"subteamPlacement": 2,
"playerSubteamId": 5,
"win": true,
"teamId": 100
}
]
}
}
@@ -0,0 +1,260 @@
{
"metadata": {
"dataVersion": "2",
"matchId": "EUW1_9000000005",
"participants": [
"fixture-puuid-01",
"fixture-puuid-02",
"fixture-puuid-03",
"fixture-puuid-04",
"fixture-puuid-05",
"fixture-puuid-self",
"fixture-puuid-07",
"fixture-puuid-08",
"fixture-puuid-09",
"fixture-puuid-10",
"fixture-puuid-11",
"fixture-puuid-12",
"fixture-puuid-13",
"fixture-puuid-14",
"fixture-puuid-15",
"fixture-puuid-16",
"fixture-puuid-17",
"fixture-puuid-18"
]
},
"info": {
"endOfGameResult": "GameComplete",
"gameCreation": 1794423967882,
"gameDuration": 1772,
"gameEndTimestamp": 1794425852692,
"gameId": 9000000005,
"gameMode": "CHERRY",
"gameName": "teambuilder-match-9000000005",
"gameStartTimestamp": 1794424080842,
"gameType": "MATCHED_GAME",
"gameVersion": "16.22.834.8910",
"mapId": 30,
"platformId": "EUW1",
"queueId": 1740,
"tournamentCode": "",
"participants": [
{
"puuid": "fixture-puuid-01",
"riotIdGameName": "Autre01",
"riotIdTagline": "FIX",
"championId": 518,
"championName": "Neeko",
"placement": 4,
"subteamPlacement": 4,
"playerSubteamId": 1,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-02",
"riotIdGameName": "Autre02",
"riotIdTagline": "FIX",
"championId": 74,
"championName": "Heimerdinger",
"placement": 4,
"subteamPlacement": 4,
"playerSubteamId": 1,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-03",
"riotIdGameName": "Autre03",
"riotIdTagline": "FIX",
"championId": 18,
"championName": "Tristana",
"placement": 4,
"subteamPlacement": 4,
"playerSubteamId": 1,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-04",
"riotIdGameName": "Autre04",
"riotIdTagline": "FIX",
"championId": 267,
"championName": "Nami",
"placement": 3,
"subteamPlacement": 3,
"playerSubteamId": 3,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-05",
"riotIdGameName": "Autre05",
"riotIdTagline": "FIX",
"championId": 14,
"championName": "Sion",
"placement": 3,
"subteamPlacement": 3,
"playerSubteamId": 3,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-self",
"riotIdGameName": "Joueur",
"riotIdTagline": "EUW",
"championId": 19,
"championName": "Warwick",
"placement": 5,
"subteamPlacement": 5,
"playerSubteamId": 5,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-07",
"riotIdGameName": "Autre07",
"riotIdTagline": "FIX",
"championId": 145,
"championName": "Kaisa",
"placement": 3,
"subteamPlacement": 3,
"playerSubteamId": 3,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-08",
"riotIdGameName": "Autre08",
"riotIdTagline": "FIX",
"championId": 63,
"championName": "Brand",
"placement": 2,
"subteamPlacement": 2,
"playerSubteamId": 4,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-09",
"riotIdGameName": "Autre09",
"riotIdTagline": "FIX",
"championId": 202,
"championName": "Jhin",
"placement": 1,
"subteamPlacement": 1,
"playerSubteamId": 6,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-10",
"riotIdGameName": "Autre10",
"riotIdTagline": "FIX",
"championId": 111,
"championName": "Nautilus",
"placement": 1,
"subteamPlacement": 1,
"playerSubteamId": 6,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-11",
"riotIdGameName": "Autre11",
"riotIdTagline": "FIX",
"championId": 45,
"championName": "Veigar",
"placement": 6,
"subteamPlacement": 6,
"playerSubteamId": 2,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-12",
"riotIdGameName": "Autre12",
"riotIdTagline": "FIX",
"championId": 68,
"championName": "Rumble",
"placement": 6,
"subteamPlacement": 6,
"playerSubteamId": 2,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-13",
"riotIdGameName": "Autre13",
"riotIdTagline": "FIX",
"championId": 555,
"championName": "Pyke",
"placement": 6,
"subteamPlacement": 6,
"playerSubteamId": 2,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-14",
"riotIdGameName": "Autre14",
"riotIdTagline": "FIX",
"championId": 133,
"championName": "Quinn",
"placement": 5,
"subteamPlacement": 5,
"playerSubteamId": 5,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-15",
"riotIdGameName": "Autre15",
"riotIdTagline": "FIX",
"championId": 30,
"championName": "Karthus",
"placement": 1,
"subteamPlacement": 1,
"playerSubteamId": 6,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-16",
"riotIdGameName": "Autre16",
"riotIdTagline": "FIX",
"championId": 112,
"championName": "Viktor",
"placement": 2,
"subteamPlacement": 2,
"playerSubteamId": 4,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-17",
"riotIdGameName": "Autre17",
"riotIdTagline": "FIX",
"championId": 893,
"championName": "Aurora",
"placement": 2,
"subteamPlacement": 2,
"playerSubteamId": 4,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-18",
"riotIdGameName": "Autre18",
"riotIdTagline": "FIX",
"championId": 54,
"championName": "Malphite",
"placement": 5,
"subteamPlacement": 5,
"playerSubteamId": 5,
"win": false,
"teamId": 200
}
]
}
}
@@ -0,0 +1,260 @@
{
"metadata": {
"dataVersion": "2",
"matchId": "EUW1_9000000003",
"participants": [
"fixture-puuid-01",
"fixture-puuid-02",
"fixture-puuid-03",
"fixture-puuid-04",
"fixture-puuid-05",
"fixture-puuid-self",
"fixture-puuid-07",
"fixture-puuid-08",
"fixture-puuid-09",
"fixture-puuid-10",
"fixture-puuid-11",
"fixture-puuid-12",
"fixture-puuid-13",
"fixture-puuid-14",
"fixture-puuid-15",
"fixture-puuid-16",
"fixture-puuid-17",
"fixture-puuid-18"
]
},
"info": {
"endOfGameResult": "GameComplete",
"gameCreation": 1778669937095,
"gameDuration": 1452,
"gameEndTimestamp": 1778671482103,
"gameId": 9000000003,
"gameMode": "CHERRY",
"gameName": "teambuilder-match-9000000003",
"gameStartTimestamp": 1778670030168,
"gameType": "MATCHED_GAME",
"gameVersion": "16.10.775.1511",
"mapId": 30,
"platformId": "EUW1",
"queueId": 1750,
"tournamentCode": "",
"participants": [
{
"puuid": "fixture-puuid-01",
"riotIdGameName": "Autre01",
"riotIdTagline": "FIX",
"championId": 127,
"championName": "Lissandra",
"placement": 1,
"subteamPlacement": 1,
"playerSubteamId": 3,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-02",
"riotIdGameName": "Autre02",
"riotIdTagline": "FIX",
"championId": 875,
"championName": "Sett",
"placement": 1,
"subteamPlacement": 1,
"playerSubteamId": 3,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-03",
"riotIdGameName": "Autre03",
"riotIdTagline": "FIX",
"championId": 11,
"championName": "MasterYi",
"placement": 6,
"subteamPlacement": 6,
"playerSubteamId": 4,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-04",
"riotIdGameName": "Autre04",
"riotIdTagline": "FIX",
"championId": 412,
"championName": "Thresh",
"placement": 6,
"subteamPlacement": 6,
"playerSubteamId": 4,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-05",
"riotIdGameName": "Autre05",
"riotIdTagline": "FIX",
"championId": 429,
"championName": "Kalista",
"placement": 5,
"subteamPlacement": 5,
"playerSubteamId": 6,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-self",
"riotIdGameName": "Joueur",
"riotIdTagline": "EUW",
"championId": 117,
"championName": "Lulu",
"placement": 6,
"subteamPlacement": 6,
"playerSubteamId": 4,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-07",
"riotIdGameName": "Autre07",
"riotIdTagline": "FIX",
"championId": 429,
"championName": "Kalista",
"placement": 4,
"subteamPlacement": 4,
"playerSubteamId": 1,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-08",
"riotIdGameName": "Autre08",
"riotIdTagline": "FIX",
"championId": 83,
"championName": "Yorick",
"placement": 4,
"subteamPlacement": 4,
"playerSubteamId": 1,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-09",
"riotIdGameName": "Autre09",
"riotIdTagline": "FIX",
"championId": 22,
"championName": "Ashe",
"placement": 4,
"subteamPlacement": 4,
"playerSubteamId": 1,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-10",
"riotIdGameName": "Autre10",
"riotIdTagline": "FIX",
"championId": 45,
"championName": "Veigar",
"placement": 5,
"subteamPlacement": 5,
"playerSubteamId": 6,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-11",
"riotIdGameName": "Autre11",
"riotIdTagline": "FIX",
"championId": 4,
"championName": "TwistedFate",
"placement": 1,
"subteamPlacement": 1,
"playerSubteamId": 3,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-12",
"riotIdGameName": "Autre12",
"riotIdTagline": "FIX",
"championId": 876,
"championName": "Lillia",
"placement": 2,
"subteamPlacement": 2,
"playerSubteamId": 5,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-13",
"riotIdGameName": "Autre13",
"riotIdTagline": "FIX",
"championId": 432,
"championName": "Bard",
"placement": 2,
"subteamPlacement": 2,
"playerSubteamId": 5,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-14",
"riotIdGameName": "Autre14",
"riotIdTagline": "FIX",
"championId": 3,
"championName": "Galio",
"placement": 5,
"subteamPlacement": 5,
"playerSubteamId": 6,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-15",
"riotIdGameName": "Autre15",
"riotIdTagline": "FIX",
"championId": 11,
"championName": "MasterYi",
"placement": 3,
"subteamPlacement": 3,
"playerSubteamId": 2,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-16",
"riotIdGameName": "Autre16",
"riotIdTagline": "FIX",
"championId": 154,
"championName": "Zac",
"placement": 3,
"subteamPlacement": 3,
"playerSubteamId": 2,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-17",
"riotIdGameName": "Autre17",
"riotIdTagline": "FIX",
"championId": 105,
"championName": "Fizz",
"placement": 3,
"subteamPlacement": 3,
"playerSubteamId": 2,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-18",
"riotIdGameName": "Autre18",
"riotIdTagline": "FIX",
"championId": 115,
"championName": "Ziggs",
"placement": 2,
"subteamPlacement": 2,
"playerSubteamId": 5,
"win": true,
"teamId": 100
}
]
}
}
@@ -0,0 +1,260 @@
{
"metadata": {
"dataVersion": "2",
"matchId": "EUW1_9000000006",
"participants": [
"fixture-puuid-01",
"fixture-puuid-02",
"fixture-puuid-03",
"fixture-puuid-04",
"fixture-puuid-05",
"fixture-puuid-06",
"fixture-puuid-07",
"fixture-puuid-08",
"fixture-puuid-09",
"fixture-puuid-10",
"fixture-puuid-11",
"fixture-puuid-12",
"fixture-puuid-13",
"fixture-puuid-14",
"fixture-puuid-15",
"fixture-puuid-16",
"fixture-puuid-self",
"fixture-puuid-18"
]
},
"info": {
"endOfGameResult": "GameComplete",
"gameCreation": 1794763725811,
"gameDuration": 1874,
"gameEndTimestamp": 1794765626749,
"gameId": 9000000006,
"gameMode": "CHERRY",
"gameName": "teambuilder-match-9000000006",
"gameStartTimestamp": 1794763752767,
"gameType": "MATCHED_GAME",
"gameVersion": "16.22.834.8910",
"mapId": 30,
"platformId": "EUW1",
"queueId": 1750,
"tournamentCode": "",
"participants": [
{
"puuid": "fixture-puuid-01",
"riotIdGameName": "Autre01",
"riotIdTagline": "FIX",
"championId": 24,
"championName": "Jax",
"placement": 5,
"subteamPlacement": 5,
"playerSubteamId": 1,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-02",
"riotIdGameName": "Autre02",
"riotIdTagline": "FIX",
"championId": 117,
"championName": "Lulu",
"placement": 5,
"subteamPlacement": 5,
"playerSubteamId": 1,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-03",
"riotIdGameName": "Autre03",
"riotIdTagline": "FIX",
"championId": 21,
"championName": "MissFortune",
"placement": 5,
"subteamPlacement": 5,
"playerSubteamId": 1,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-04",
"riotIdGameName": "Autre04",
"riotIdTagline": "FIX",
"championId": 24,
"championName": "Jax",
"placement": 4,
"subteamPlacement": 4,
"playerSubteamId": 2,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-05",
"riotIdGameName": "Autre05",
"riotIdTagline": "FIX",
"championId": 222,
"championName": "Jinx",
"placement": 2,
"subteamPlacement": 2,
"playerSubteamId": 6,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-06",
"riotIdGameName": "Autre06",
"riotIdTagline": "FIX",
"championId": 112,
"championName": "Viktor",
"placement": 4,
"subteamPlacement": 4,
"playerSubteamId": 2,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-07",
"riotIdGameName": "Autre07",
"riotIdTagline": "FIX",
"championId": 56,
"championName": "Nocturne",
"placement": 4,
"subteamPlacement": 4,
"playerSubteamId": 2,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-08",
"riotIdGameName": "Autre08",
"riotIdTagline": "FIX",
"championId": 74,
"championName": "Heimerdinger",
"placement": 6,
"subteamPlacement": 6,
"playerSubteamId": 3,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-09",
"riotIdGameName": "Autre09",
"riotIdTagline": "FIX",
"championId": 526,
"championName": "Rell",
"placement": 1,
"subteamPlacement": 1,
"playerSubteamId": 4,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-10",
"riotIdGameName": "Autre10",
"riotIdTagline": "FIX",
"championId": 81,
"championName": "Ezreal",
"placement": 3,
"subteamPlacement": 3,
"playerSubteamId": 5,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-11",
"riotIdGameName": "Autre11",
"riotIdTagline": "FIX",
"championId": 516,
"championName": "Ornn",
"placement": 6,
"subteamPlacement": 6,
"playerSubteamId": 3,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-12",
"riotIdGameName": "Autre12",
"riotIdTagline": "FIX",
"championId": 4,
"championName": "TwistedFate",
"placement": 6,
"subteamPlacement": 6,
"playerSubteamId": 3,
"win": false,
"teamId": 200
},
{
"puuid": "fixture-puuid-13",
"riotIdGameName": "Autre13",
"riotIdTagline": "FIX",
"championId": 112,
"championName": "Viktor",
"placement": 1,
"subteamPlacement": 1,
"playerSubteamId": 4,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-14",
"riotIdGameName": "Autre14",
"riotIdTagline": "FIX",
"championId": 120,
"championName": "Hecarim",
"placement": 1,
"subteamPlacement": 1,
"playerSubteamId": 4,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-15",
"riotIdGameName": "Autre15",
"riotIdTagline": "FIX",
"championId": 69,
"championName": "Cassiopeia",
"placement": 3,
"subteamPlacement": 3,
"playerSubteamId": 5,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-16",
"riotIdGameName": "Autre16",
"riotIdTagline": "FIX",
"championId": 111,
"championName": "Nautilus",
"placement": 3,
"subteamPlacement": 3,
"playerSubteamId": 5,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-self",
"riotIdGameName": "Joueur",
"riotIdTagline": "EUW",
"championId": 39,
"championName": "Irelia",
"placement": 2,
"subteamPlacement": 2,
"playerSubteamId": 6,
"win": true,
"teamId": 100
},
{
"puuid": "fixture-puuid-18",
"riotIdGameName": "Autre18",
"riotIdTagline": "FIX",
"championId": 114,
"championName": "Fiora",
"placement": 2,
"subteamPlacement": 2,
"playerSubteamId": 6,
"win": true,
"teamId": 100
}
]
}
}
File diff suppressed because it is too large. Load diff
+624
View File
@@ -0,0 +1,624 @@
mod common;
use std::path::Path;
use std::sync::atomic::Ordering;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use arena_tracker_core::{
Account, Error, Format, Match, SourceError, SyncProgress, SyncReport, Tracker,
};
use common::{
FakeHistory, SELF_PUUID, payload, played_by, recorded_account, recorded_matches, with_game_mode,
};
use serde_json::Value;
const RIOT_ID: &str = "Joueur#EUW";
fn open(db: &Path, history: FakeHistory) -> Tracker {
Tracker::open(db, Box::new(history)).unwrap()
}
fn sync(tracker: &Tracker) -> SyncReport {
tracker.sync(RIOT_ID, &mut |_| {}).unwrap()
}
/// The expectation for a recorded payload, read from the payload itself.
fn expected(raw: &str) -> Match {
let v: Value = serde_json::from_str(raw).unwrap();
let me = v["info"]["participants"]
.as_array()
.unwrap()
.iter()
.find(|p| p["puuid"] == SELF_PUUID)
.unwrap();
let format = match v["info"]["queueId"].as_u64().unwrap() {
1700 => Format::Arena16,
1740 => Format::BraveryArena,
1750 => Format::Arena3x6,
queue => panic!("unexpected queue {queue}"),
};
Match {
match_id: v["metadata"]["matchId"].as_str().unwrap().into(),
format,
champion_id: me["championId"].as_u64().unwrap() as u32,
champion_name: me["championName"].as_str().unwrap().into(),
placement: me["placement"].as_u64().unwrap() as u8,
win: me["win"].as_bool().unwrap(),
started_at_ms: v["info"]["gameStartTimestamp"].as_i64().unwrap(),
}
}
/// Five Arena 3x6 Matches, one every 1000 s starting at `from_s`.
fn five_matches(from_s: i64) -> Vec<String> {
five_matches_every(from_s, 1000)
}
/// Five Arena 3x6 Matches, one every `step_s` seconds starting at `from_s`.
fn five_matches_every(from_s: i64, step_s: i64) -> Vec<String> {
(0..5)
.map(|i| {
payload(
&format!("EUW1_{i}"),
1750,
10 + i as u32,
"Champion",
(i % 8 + 1) as u8,
i % 2 == 0,
(from_s + i * step_s) * 1000,
)
})
.collect()
}
fn started_at(matches: &[Match]) -> Vec<i64> {
matches.iter().map(|m| m.started_at_ms).collect()
}
#[test]
fn tracker_can_be_shared_between_threads() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Tracker>();
}
#[test]
fn imports_the_recorded_matches() {
let dir = tempfile::tempdir().unwrap();
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), recorded_matches()),
);
let report = sync(&tracker);
assert_eq!(report.account, recorded_account());
assert_eq!((report.added, report.stored), (6, 6));
let mut want: Vec<Match> = recorded_matches().iter().map(|raw| expected(raw)).collect();
want.sort_by_key(|m| m.started_at_ms);
assert_eq!(tracker.matches(SELF_PUUID).unwrap(), want);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 6);
assert_eq!(tracker.accounts().unwrap(), [recorded_account()]);
}
#[test]
fn importing_twice_changes_nothing_and_fetches_nothing() {
let dir = tempfile::tempdir().unwrap();
let fake = FakeHistory::new(recorded_account(), recorded_matches());
let fetches = fake.fetch_counter();
let tracker = open(&dir.path().join("arena.db"), fake);
sync(&tracker);
let first = tracker.matches(SELF_PUUID).unwrap();
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (0, 6));
assert_eq!(fetches.load(Ordering::SeqCst), 6);
assert_eq!(tracker.matches(SELF_PUUID).unwrap(), first);
}
#[test]
fn interrupted_import_keeps_what_was_stored_and_resumes_with_the_rest() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let flaky = open(
&db,
FakeHistory::new(recorded_account(), five_matches(1_000_000)).failing_after(2),
);
let err = flaky.sync(RIOT_ID, &mut |_| {}).unwrap_err();
assert!(matches!(err, Error::Source(SourceError::Network(_))));
assert_eq!(flaky.match_count(SELF_PUUID).unwrap(), 2);
drop(flaky);
let healthy = FakeHistory::new(recorded_account(), five_matches(1_000_000));
let fetches = healthy.fetch_counter();
let tracker = open(&db, healthy);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
let report = sync(&tracker);
// The two stored are the newest ones: the missing older ones are still found.
assert_eq!((report.added, report.stored), (3, 5));
assert_eq!(fetches.load(Ordering::SeqCst), 3);
assert_eq!(tracker.matches(SELF_PUUID).unwrap().len(), 5);
}
#[test]
fn later_sync_fetches_only_newer_matches() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let days_apart = |from_s| five_matches_every(from_s, 10 * 24 * 3600);
sync(&open(
&db,
FakeHistory::new(recorded_account(), days_apart(1_000_000)),
));
let mut now_on_riot = days_apart(1_000_000);
now_on_riot.push(payload(
"EUW1_new1",
1750,
1,
"Annie",
1,
true,
4_500_000_000,
));
now_on_riot.push(payload(
"EUW1_new2",
1740,
2,
"Olaf",
3,
true,
4_501_000_000,
));
let fake = FakeHistory::new(recorded_account(), now_on_riot);
let (fetches, listed) = (fake.fetch_counter(), fake.listed_counter());
let tracker = open(&db, fake);
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (2, 7));
assert_eq!(fetches.load(Ordering::SeqCst), 2);
// Riot is only asked for recent Matches: the newest stored one (listed again) and the new ones.
assert_eq!(listed.load(Ordering::SeqCst), 3);
}
#[test]
fn matches_are_returned_oldest_first_whatever_the_delivery_order() {
let dir = tempfile::tempdir().unwrap();
let mut payloads = five_matches(1_000_000);
payloads.swap(0, 3);
payloads.swap(1, 4);
let delivered: Vec<i64> = payloads.iter().map(|p| started_ms(p)).collect();
assert!(!delivered.is_sorted() && !delivered.iter().rev().is_sorted());
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), payloads).delivered_as_given(),
);
sync(&tracker);
let started = started_at(&tracker.matches(SELF_PUUID).unwrap());
assert_eq!(started.len(), 5);
assert!(started.is_sorted());
}
fn started_ms(payload: &str) -> i64 {
let v: Value = serde_json::from_str(payload).unwrap();
v["info"]["gameStartTimestamp"].as_i64().unwrap()
}
#[test]
fn a_catch_up_cut_short_fetches_the_older_matches_next_time() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let at = |hours: i64| (1_000_000 + hours * 3600) * 1000;
let known = payload("EUW1_1", 1750, 1, "A", 4, false, at(0));
sync(&open(
&db,
FakeHistory::new(recorded_account(), vec![known.clone()]),
));
// Three Matches played while the app was closed.
let mut on_riot = vec![known];
for i in 2..=4 {
let id = format!("EUW1_{i}");
on_riot.push(payload(&id, 1750, i, "B", 4, false, at(i64::from(i))));
}
// The catch-up stores the newest one, then dies.
let cut = open(
&db,
FakeHistory::new(recorded_account(), on_riot.clone()).failing_after(1),
);
assert!(cut.sync(RIOT_ID, &mut |_| {}).is_err());
assert_eq!(cut.match_count(SELF_PUUID).unwrap(), 2);
drop(cut);
let report = sync(&open(&db, FakeHistory::new(recorded_account(), on_riot)));
assert_eq!((report.added, report.stored), (2, 4));
}
#[test]
fn a_match_that_started_earlier_but_was_published_later_is_still_imported() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let at = |hours: i64| (1_000_000 + hours * 3600) * 1000;
let first = payload("EUW1_1", 1750, 1, "A", 4, false, at(0));
let newest = payload("EUW1_2", 1750, 2, "B", 4, false, at(30));
let fake = FakeHistory::new(recorded_account(), vec![first, newest]);
let tracker = open(&db, fake);
sync(&tracker);
// A game that began before the newest stored one ends only now.
let late = FakeHistory::new(
recorded_account(),
vec![
payload("EUW1_1", 1750, 1, "A", 4, false, at(0)),
payload("EUW1_2", 1750, 2, "B", 4, false, at(30)),
payload("EUW1_3", 1750, 3, "C", 1, true, at(10)),
],
);
drop(tracker);
let report = sync(&open(&db, late));
assert_eq!((report.added, report.stored), (1, 3));
}
#[test]
fn a_match_that_cannot_be_delivered_or_read_does_not_block_the_others() {
let dir = tempfile::tempdir().unwrap();
let at = |hours: i64| (1_000_000 + hours * 3600) * 1000;
let fake = FakeHistory::new(
recorded_account(),
vec![
payload("EUW1_1", 1750, 1, "A", 4, false, at(1)),
payload("EUW1_2", 1750, 2, "B", 2, true, at(3)),
],
);
fake.add_missing("EUW1_gone", at(4));
fake.add_unreadable("EUW1_garbled", at(2), "<html>pas du JSON</html>");
fake.add_unreadable("EUW1_empty_object", at(0), "{}");
let tracker = open(&dir.path().join("arena.db"), fake);
let mut progress = Vec::new();
let report = tracker.sync(RIOT_ID, &mut |p| progress.push(p)).unwrap();
assert_eq!((report.added, report.stored), (2, 2));
assert_eq!(
progress.last(),
Some(&SyncProgress {
fetched: 5,
to_fetch: 5
})
);
let again = sync(&tracker);
assert_eq!((again.added, again.stored), (0, 2));
}
#[test]
fn other_participants_may_lack_any_field() {
let dir = tempfile::tempdir().unwrap();
let thin = common::without_fields_for_others(
&payload("EUW1_1", 1750, 7, "Zed", 2, true, 1_000_000_000),
&["placement", "win", "championId", "championName", "teamId"],
);
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), vec![thin]),
);
let report = sync(&tracker);
assert_eq!(report.added, 1);
let stored = tracker.matches(SELF_PUUID).unwrap();
assert_eq!((stored[0].champion_id, stored[0].placement), (7, 2));
}
#[test]
fn an_account_resolved_to_another_puuid_is_a_second_account() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let at = |hours: i64| (1_000_000 + hours * 3600) * 1000;
let build = |puuid: &str, ids: &[u32]| -> Vec<String> {
ids.iter()
.map(|&i| {
let raw = payload(
&format!("EUW1_{i}"),
1750,
i,
"A",
1,
true,
at(i64::from(i)),
);
played_by(&raw, puuid)
})
.collect()
};
// Under the development key, Joueur#EUW is P1.
let account = |puuid: &str| Account {
puuid: puuid.into(),
..recorded_account()
};
let first = open(&db, FakeHistory::new(account("P1"), build("P1", &[1, 2])));
sync(&first);
let before = first.matches("P1").unwrap();
drop(first);
// Under the personal key it is P2: nothing proves it is the same Account.
let tracker = open(
&db,
FakeHistory::new(account("P2"), build("P2", &[1, 2, 3])),
);
let report = sync(&tracker);
assert_eq!(report.account.puuid, "P2");
assert_eq!((report.added, report.stored), (3, 3));
assert_eq!(tracker.matches("P1").unwrap(), before);
let mut puuids: Vec<String> = tracker
.accounts()
.unwrap()
.into_iter()
.map(|a| a.puuid)
.collect();
puuids.sort();
assert_eq!(puuids, ["P1", "P2"]);
}
const LEGACY_SCHEMA: &str = "
CREATE TABLE accounts (
puuid TEXT PRIMARY KEY, game_name TEXT NOT NULL, tag_line TEXT NOT NULL,
full_import_done INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE 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)
);
INSERT INTO accounts VALUES ('fixture-puuid-self', 'Joueur', 'EUW', 1);
INSERT INTO matches VALUES ('fixture-puuid-self', 'EUW1_1', 1750, 1, 'A', 4, 0, 1000000000, '{}');";
#[test]
fn a_database_written_before_the_sync_mark_keeps_working() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
rusqlite::Connection::open(&db)
.unwrap()
.execute_batch(LEGACY_SCHEMA)
.unwrap();
let other = Account {
puuid: "fixture-puuid-other".into(),
game_name: "Autre".into(),
tag_line: "FIX".into(),
};
let theirs = vec![played_by(
&payload("EUW1_9", 1750, 9, "I", 1, true, 1_000_005_000),
&other.puuid,
)];
let tracker = open(
&db,
FakeHistory::new(
recorded_account(),
vec![
payload("EUW1_1", 1750, 1, "A", 4, false, 1_000_000_000),
payload("EUW1_2", 1750, 2, "B", 1, true, 1_000_003_000),
],
)
.with_account(other.clone(), theirs),
);
// No mark yet: everything is listed, what is stored is not fetched again.
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (1, 2));
// A new Account can be added to the old table.
let report = tracker.sync("Autre#FIX", &mut |_| {}).unwrap();
assert_eq!((report.added, report.stored), (1, 1));
assert_eq!(tracker.accounts().unwrap().len(), 2);
}
#[test]
fn queues_map_to_formats_and_non_matches_are_skipped() {
let dir = tempfile::tempdir().unwrap();
let at = |i: i64| (1_000_000 + i) * 1000;
let fake = FakeHistory::new(
recorded_account(),
vec![
payload("EUW1_1", 1750, 1, "A", 1, true, at(1)),
payload("EUW1_2", 1740, 2, "B", 2, true, at(2)),
payload("EUW1_3", 1700, 3, "C", 3, true, at(3)),
payload("EUW1_4", 1710, 4, "D", 4, true, at(4)),
],
)
.listed_under(1700, payload("EUW1_5", 1704, 5, "E", 1, true, at(5)))
.listed_under(1700, payload("EUW1_6", 9999, 6, "F", 5, false, at(6)))
.listed_under(
1700,
with_game_mode(&payload("EUW1_7", 1700, 7, "G", 1, true, at(7)), "ARAM"),
);
let tracker = open(&dir.path().join("arena.db"), fake);
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (5, 5));
let formats: Vec<_> = tracker
.matches(SELF_PUUID)
.unwrap()
.into_iter()
.map(|m| (m.match_id, m.format))
.collect();
assert_eq!(
formats,
[
("EUW1_1".into(), Format::Arena3x6),
("EUW1_2".into(), Format::BraveryArena),
("EUW1_3".into(), Format::Arena16),
("EUW1_4".into(), Format::Arena16),
("EUW1_6".into(), Format::Other(9999)),
]
);
}
#[test]
fn a_rate_limit_is_waited_out_and_the_import_completes() {
let dir = tempfile::tempdir().unwrap();
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), recorded_matches()).rate_limited_once(),
);
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (6, 6));
}
#[test]
fn progress_goes_from_nothing_fetched_to_everything_fetched() {
let dir = tempfile::tempdir().unwrap();
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), recorded_matches()),
);
let mut progress = Vec::new();
tracker.sync(RIOT_ID, &mut |p| progress.push(p)).unwrap();
let want: Vec<_> = (0..=6)
.map(|fetched| SyncProgress {
fetched,
to_fetch: 6,
})
.collect();
assert_eq!(progress, want);
progress.clear();
tracker.sync(RIOT_ID, &mut |p| progress.push(p)).unwrap();
assert_eq!(
progress,
[SyncProgress {
fetched: 0,
to_fetch: 0
}]
);
}
#[test]
fn two_accounts_keep_separate_matches() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
sync(&open(
&db,
FakeHistory::new(recorded_account(), five_matches(1_000_000)),
));
let other = Account {
puuid: "fixture-puuid-other".into(),
game_name: "Autre".into(),
tag_line: "FIX".into(),
};
let theirs: Vec<String> = five_matches(5_000_000)[..2]
.iter()
.map(|raw| played_by(raw, &other.puuid))
.collect();
let tracker = open(&db, FakeHistory::new(other.clone(), theirs));
let report = tracker.sync("Autre#FIX", &mut |_| {}).unwrap();
assert_eq!((report.added, report.stored), (2, 2));
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 5);
assert_eq!(tracker.match_count(&other.puuid).unwrap(), 2);
assert!(
tracker
.matches(&other.puuid)
.unwrap()
.iter()
.all(|m| m.started_at_ms >= 5_000_000_000)
);
assert_eq!(tracker.accounts().unwrap().len(), 2);
}
#[test]
fn matches_without_the_account_are_skipped() {
let dir = tempfile::tempdir().unwrap();
let stranger = Account {
puuid: "fixture-puuid-stranger".into(),
game_name: "Joueur".into(),
tag_line: "EUW".into(),
};
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(stranger, recorded_matches()),
);
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (0, 0));
}
#[test]
fn riot_ids_are_validated_and_must_exist() {
let dir = tempfile::tempdir().unwrap();
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), recorded_matches()),
);
for bad in ["Joueur", "#EUW", "Joueur#"] {
let err = tracker.sync(bad, &mut |_| {}).unwrap_err();
assert!(matches!(err, Error::InvalidRiotId(_)), "{bad}");
}
let err = tracker.sync("Inconnu#EUW", &mut |_| {}).unwrap_err();
assert!(matches!(err, Error::Source(SourceError::NotFound)));
}
#[test]
fn readers_are_not_blocked_while_a_fetch_is_in_flight() {
let dir = tempfile::tempdir().unwrap();
let (entered_tx, entered_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
let fake = FakeHistory::new(recorded_account(), recorded_matches()[..1].to_vec())
.gated(entered_tx, release_rx);
let tracker = open(&dir.path().join("arena.db"), fake);
thread::scope(|scope| {
let import = scope.spawn(|| sync(&tracker));
entered_rx.recv().unwrap();
// The import is now waiting on the source; the UI thread must still get answers.
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 0);
assert_eq!(tracker.accounts().unwrap().len(), 1);
release_tx.send(()).unwrap();
assert_eq!(import.join().unwrap().added, 1);
});
}
#[test]
fn concurrent_syncs_run_one_after_the_other_and_fetch_each_match_once() {
let dir = tempfile::tempdir().unwrap();
let (entered_tx, entered_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
let fake = FakeHistory::new(recorded_account(), recorded_matches()[..1].to_vec())
.gated(entered_tx, release_rx);
let fetches = fake.fetch_counter();
let tracker = open(&dir.path().join("arena.db"), fake);
let (overlapped, added) = thread::scope(|scope| {
let first = scope.spawn(|| sync(&tracker));
entered_rx.recv().unwrap();
let second = scope.spawn(|| sync(&tracker));
// Without the lock, the second sync would reach the source while the first waits there.
let overlapped = entered_rx.recv_timeout(Duration::from_millis(300)).is_ok();
release_tx.send(()).unwrap();
release_tx.send(()).unwrap();
let added = (first.join().unwrap().added, second.join().unwrap().added);
(overlapped, added)
});
assert!(!overlapped);
assert_eq!(added, (1, 0));
assert_eq!(fetches.load(Ordering::SeqCst), 1);
}
+595
View File
@@ -0,0 +1,595 @@
mod common;
use arena_tracker_core::{
Champion, ChampionRow, ChampionState, Column, Error, Format, Scope, Season, SeasonScope,
StateFilter, Statistics, Tracker, sort_rows,
};
use common::jan_2026 as jan;
use common::{
CATALOG, FakeHistory, RIOT_ID, S1, S2, SELF_PUUID, at, date, imported_tracker, payloads,
played_match, recorded_account, run, seasons,
};
use std::sync::atomic::Ordering;
fn stats(tracker: &Tracker, season: &str, format: Option<Format>) -> Statistics {
let scope = Scope {
season: SeasonScope::Season(season.into()),
format,
};
tracker.statistics(SELF_PUUID, &scope).unwrap()
}
fn all_seasons(tracker: &Tracker) -> Statistics {
let scope = Scope {
season: SeasonScope::AllSeasons,
format: None,
};
tracker.statistics(SELF_PUUID, &scope).unwrap()
}
fn row(stats: &Statistics, champion_id: u32) -> &ChampionRow {
stats
.rows
.iter()
.find(|r| r.champion.id == champion_id)
.unwrap()
}
#[test]
fn attempts_run_up_to_the_first_top_1_and_no_further() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &run(11, &[5, 4, 1, 3], jan(2, 0)));
let stats = stats(&tracker, S1, None);
let yi = row(&stats, 11);
assert_eq!(yi.state, Some(ChampionState::Completed));
assert_eq!(yi.attempts, Some(3));
assert_eq!(yi.matches, 4);
let challenge = stats.challenge.unwrap();
assert_eq!((challenge.completed, challenge.first_tries), (1, 0));
assert_eq!(challenge.attempts, 3);
}
#[test]
fn champion_states() {
let dir = tempfile::tempdir().unwrap();
let matches = [run(222, &[1], jan(2, 0)), run(103, &[3, 5], jan(2, 0))].concat();
let tracker = imported_tracker(dir.path(), &matches);
let stats = stats(&tracker, S1, None);
let first_try = row(&stats, 222);
assert_eq!(first_try.state, Some(ChampionState::Completed));
assert_eq!(first_try.attempts, Some(1));
let in_progress = row(&stats, 103);
assert_eq!(in_progress.state, Some(ChampionState::InProgress));
assert_eq!(in_progress.attempts, Some(2));
let never_played = row(&stats, 8);
assert_eq!(never_played.state, Some(ChampionState::NeverPlayed));
assert_eq!(never_played.attempts, Some(0));
assert_eq!(stats.challenge.unwrap().first_tries, 1);
}
#[test]
fn challenge_totals_count_every_attempt_but_average_only_completed_champions() {
let dir = tempfile::tempdir().unwrap();
let matches = [
run(11, &[5, 4, 1, 3], jan(2, 0)), // Completed in 3
run(222, &[1], jan(3, 0)), // First Try
run(103, &[3, 5], jan(4, 0)), // in progress, 2 Attempts so far
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let challenge = stats(&tracker, S1, None).challenge.unwrap();
assert_eq!(challenge.completed, 2);
assert_eq!(challenge.total, CATALOG.len());
assert_eq!(challenge.attempts, 3 + 1 + 2);
assert_eq!(challenge.average_attempts, Some(2.0));
assert_eq!(challenge.first_tries, 1);
}
#[test]
fn average_attempts_is_none_when_nothing_is_completed() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &run(103, &[3, 5], jan(2, 0)));
let challenge = stats(&tracker, S1, None).challenge.unwrap();
assert_eq!(challenge.completed, 0);
assert_eq!(challenge.average_attempts, None);
assert_eq!(challenge.attempts, 2);
}
#[test]
fn a_top_1_in_any_format_completes_the_champion() {
let dir = tempfile::tempdir().unwrap();
let matches = [
played_match(11, 5, jan(2, 0)).in_format(1740),
played_match(11, 1, jan(2, 1)).in_format(1700),
]
.to_vec();
let tracker = imported_tracker(dir.path(), &matches);
let stats = stats(&tracker, S1, Some(Format::BraveryArena));
// Only the Bravery Arena Match is in scope, yet the Challenge still sees both.
assert_eq!(row(&stats, 11).matches, 1);
assert_eq!(row(&stats, 11).state, Some(ChampionState::Completed));
assert_eq!(row(&stats, 11).attempts, Some(2));
assert_eq!(stats.challenge.unwrap().completed, 1);
}
#[test]
fn the_format_filter_changes_statistics_and_never_the_challenge() {
let dir = tempfile::tempdir().unwrap();
let matches = vec![
played_match(11, 5, jan(2, 0)),
played_match(11, 1, jan(2, 1)).in_format(1740),
played_match(11, 3, jan(2, 2)),
played_match(11, 6, jan(2, 4)).in_format(1740),
played_match(222, 2, jan(3, 0)).in_format(1740),
];
let tracker = imported_tracker(dir.path(), &matches);
let everything = stats(&tracker, S1, None);
let filtered = stats(&tracker, S1, Some(Format::Arena3x6));
let (all, only) = (row(&everything, 11), row(&filtered, 11));
assert_eq!(
(all.matches, all.top1, all.wins, all.best_placement),
(4, 1, 2, Some(1))
);
assert_eq!(all.average_placement, Some(3.75));
assert_eq!(all.last_match_ms, Some(jan(2, 4)));
assert_eq!(
(only.matches, only.top1, only.wins, only.best_placement),
(2, 0, 1, Some(3))
);
assert_eq!(only.average_placement, Some(4.0));
assert_eq!(only.last_match_ms, Some(jan(2, 2)));
assert_eq!(row(&filtered, 222).matches, 0);
assert_eq!(row(&filtered, 222).last_match_ms, None);
assert_eq!(
everything.charts.placements,
[(1, 1), (2, 1), (3, 1), (4, 0), (5, 1), (6, 1)]
);
assert_eq!(
filtered.charts.placements,
[(1, 0), (2, 0), (3, 1), (4, 0), (5, 1)]
);
// Unchanged: the Challenge, every state and Attempts count, the two Challenge charts.
assert_eq!(everything.challenge, filtered.challenge);
for (a, b) in everything.rows.iter().zip(&filtered.rows) {
assert_eq!(
(a.state, a.attempts),
(b.state, b.attempts),
"{}",
a.champion.name
);
}
assert_eq!(
everything.charts.completed_over_time,
filtered.charts.completed_over_time
);
assert_eq!(
everything.charts.attempts_to_complete,
filtered.charts.attempts_to_complete
);
assert_eq!(everything.formats, [Format::Arena3x6, Format::BraveryArena]);
assert_eq!(filtered.formats, everything.formats);
}
#[test]
fn a_season_starts_at_its_first_millisecond() {
let dir = tempfile::tempdir().unwrap();
let s1_start = date(2026, 1, 1).start_ms();
let s2_start = date(2026, 4, 1).start_ms();
let matches = vec![
played_match(1, 4, s1_start - 1), // before the first Season
played_match(8, 4, s1_start), // first instant of S1
played_match(11, 4, s2_start - 1), // last millisecond of S1
played_match(19, 4, s2_start), // first instant of S2
];
let tracker = imported_tracker(dir.path(), &matches);
let in_season = |name| -> Vec<u32> {
let stats = stats(&tracker, name, None);
let mut ids: Vec<u32> = stats
.rows
.iter()
.filter(|r| r.matches > 0)
.map(|r| r.champion.id)
.collect();
ids.sort();
ids
};
assert_eq!(in_season(S1), [8, 11]);
assert_eq!(in_season(S2), [19]);
let everything = all_seasons(&tracker);
assert_eq!(everything.rows.iter().filter(|r| r.matches > 0).count(), 4);
assert_eq!(row(&everything, 1).matches, 1);
}
#[test]
fn each_season_has_its_own_challenge_and_the_current_one_is_found_by_date() {
let dir = tempfile::tempdir().unwrap();
let matches = [
run(11, &[1], jan(2, 0)),
run(11, &[4], at(date(2026, 4, 2), 0)),
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let past = stats(&tracker, S1, None);
let current = stats(&tracker, S2, None);
assert_eq!(past.challenge.unwrap().completed, 1);
let challenge = current.challenge.clone().unwrap();
assert_eq!((challenge.completed, challenge.attempts), (0, 1));
assert_eq!(row(&current, 11).state, Some(ChampionState::InProgress));
let name = |ms| tracker.current_season(ms).map(|s| s.name);
assert_eq!(name(date(2026, 1, 1).start_ms() - 1), None);
assert_eq!(name(date(2026, 1, 1).start_ms()), Some(S1.into()));
assert_eq!(name(date(2026, 4, 1).start_ms() - 1), Some(S1.into()));
assert_eq!(name(date(2026, 4, 1).start_ms()), Some(S2.into()));
assert_eq!(name(date(2100, 1, 1).start_ms()), Some(S2.into()));
assert_eq!(tracker.seasons(), seasons());
}
#[test]
fn the_all_seasons_view_has_no_challenge() {
let dir = tempfile::tempdir().unwrap();
let matches = [
run(11, &[1], jan(2, 0)),
run(11, &[4], at(date(2026, 4, 2), 0)),
run(222, &[3], at(date(2025, 6, 1), 0)),
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let stats = all_seasons(&tracker);
assert_eq!(stats.challenge, None);
let yi = row(&stats, 11);
assert_eq!((yi.matches, yi.top1, yi.best_placement), (2, 1, Some(1)));
assert_eq!(yi.average_placement, Some(2.5));
assert_eq!((yi.attempts, yi.state), (None, None));
assert_eq!(
(row(&stats, 222).attempts, row(&stats, 222).state),
(None, None)
);
assert_eq!(row(&stats, 8).state, Some(ChampionState::NeverPlayed));
assert_eq!(row(&stats, 8).attempts, None);
assert!(stats.charts.completed_over_time.is_empty());
assert_eq!(stats.charts.attempts_to_complete, [0; 5]);
assert_eq!(stats.charts.placements, [(1, 1), (2, 0), (3, 1), (4, 1)]);
}
#[test]
fn an_unknown_season_is_an_error() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &[]);
let scope = Scope {
season: SeasonScope::Season("Saison Z".into()),
format: None,
};
let err = tracker.statistics(SELF_PUUID, &scope).unwrap_err();
assert!(matches!(err, Error::UnknownSeason(name) if name == "Saison Z"));
}
#[test]
fn an_edited_season_table_reassigns_stored_matches_without_importing_again() {
let dir = tempfile::tempdir().unwrap();
let matches = [run(11, &[4], jan(1, 1)), run(19, &[4], jan(3, 1))].concat();
drop(imported_tracker(dir.path(), &matches));
let history = FakeHistory::new(recorded_account(), payloads(&matches));
let fetches = history.fetch_counter();
let tracker = Tracker::open(&dir.path().join("arena.db"), Box::new(history))
.unwrap()
.with_seasons(vec![
Season {
name: "Début".into(),
start: date(2026, 1, 1),
official_track: None,
},
Season {
name: "Suite".into(),
start: date(2026, 1, 2),
official_track: None,
},
]);
let report = tracker.sync(RIOT_ID, &mut |_| {}).unwrap();
assert_eq!((report.added, fetches.load(Ordering::SeqCst)), (0, 0));
let played = |name| -> Vec<u32> {
stats(&tracker, name, None)
.rows
.iter()
.filter(|r| r.matches > 0)
.map(|r| r.champion.id)
.collect()
};
assert_eq!(played("Début"), [11]);
assert_eq!(played("Suite"), [19]);
assert!(
tracker
.statistics(
SELF_PUUID,
&Scope {
season: SeasonScope::Season(S1.into()),
format: None
}
)
.is_err()
);
}
#[test]
fn row_values_for_one_champion() {
let dir = tempfile::tempdir().unwrap();
let matches = vec![
played_match(11, 4, jan(2, 1)),
played_match(11, 1, jan(2, 2)).in_format(1740),
played_match(11, 2, jan(2, 3)).in_format(1700),
];
let tracker = imported_tracker(dir.path(), &matches);
let stats = stats(&tracker, S1, None);
let yi = row(&stats, 11);
assert_eq!(
yi.champion,
Champion {
id: 11,
key: "MasterYi".into(),
name: "Maître Yi".into()
}
);
assert_eq!(yi.matches, 3);
assert_eq!(yi.best_placement, Some(1));
assert_eq!(yi.top1, 1);
assert_eq!(yi.wins, 2);
assert_eq!(yi.average_placement, Some(7.0 / 3.0));
assert_eq!(yi.last_match_ms, Some(jan(2, 3)));
let unplayed = row(&stats, 8);
assert_eq!(unplayed.matches, 0);
assert_eq!(
(
unplayed.best_placement,
unplayed.average_placement,
unplayed.last_match_ms
),
(None, None, None)
);
}
#[test]
fn the_chart_series_are_empty_without_matches() {
let dir = tempfile::tempdir().unwrap();
let tracker = imported_tracker(dir.path(), &[]);
let charts = stats(&tracker, S1, None).charts;
assert!(charts.placements.is_empty());
assert!(charts.completed_over_time.is_empty());
assert_eq!(charts.attempts_to_complete, [0; 5]);
}
#[test]
fn the_chart_series_follow_the_completions() {
let dir = tempfile::tempdir().unwrap();
let matches = [
run(1, &[1], jan(2, 1)),
run(8, &[1], jan(2, 5)),
run(11, &[4, 1], jan(5, 0)),
run(19, &[3, 3, 3, 3, 1], jan(6, 0)),
run(103, &[6, 6, 6, 6, 6, 6, 1], jan(6, 8)),
run(222, &[2, 2, 1], jan(10, 0)),
]
.concat();
let tracker = imported_tracker(dir.path(), &matches);
let charts = stats(&tracker, S1, None).charts;
assert_eq!(
charts.completed_over_time,
[
(date(2026, 1, 2), 2),
(date(2026, 1, 5), 3),
(date(2026, 1, 6), 5),
(date(2026, 1, 10), 6),
]
);
// 1 Attempt: Annie and Vladimir; 2: Maître Yi; 3: Jinx; 5 or more: Warwick and Ahri.
assert_eq!(charts.attempts_to_complete, [2, 1, 1, 0, 2]);
}
fn bare_row(name: &str, id: u32) -> ChampionRow {
ChampionRow {
champion: Champion {
id,
key: name.into(),
name: name.into(),
},
portrait: None,
matches: 0,
best_placement: None,
top1: 0,
wins: 0,
average_placement: None,
last_match_ms: None,
attempts: None,
state: None,
}
}
fn names(rows: &[ChampionRow]) -> Vec<&str> {
rows.iter().map(|r| r.champion.name.as_str()).collect()
}
#[test]
fn rows_sort_by_column_with_missing_values_last_and_ties_by_name() {
let with_attempts = |name, id, attempts| ChampionRow {
attempts,
..bare_row(name, id)
};
let mut rows = vec![
with_attempts("Bard", 3, Some(3)),
with_attempts("Zed", 4, None),
with_attempts("Annie", 1, Some(3)),
with_attempts("Ahri", 2, Some(1)),
with_attempts("Jinx", 5, Some(0)),
];
sort_rows(&mut rows, Column::Attempts, true);
assert_eq!(names(&rows), ["Annie", "Bard", "Ahri", "Jinx", "Zed"]);
sort_rows(&mut rows, Column::Attempts, false);
assert_eq!(names(&rows), ["Jinx", "Ahri", "Annie", "Bard", "Zed"]);
}
#[test]
fn rows_sort_by_name_ignoring_case_and_accents() {
let mut rows: Vec<_> = ["Zoé", "Zed", "Maître Yi", "Nami", "ahri"]
.iter()
.zip(1..)
.map(|(name, id)| bare_row(name, id))
.collect();
sort_rows(&mut rows, Column::Champion, false);
assert_eq!(names(&rows), ["ahri", "Maître Yi", "Nami", "Zed", "Zoé"]);
sort_rows(&mut rows, Column::Champion, true);
assert_eq!(names(&rows), ["Zoé", "Zed", "Nami", "Maître Yi", "ahri"]);
}
#[test]
fn rows_sort_by_numbers_and_dates() {
let rows = vec![
ChampionRow {
average_placement: Some(2.5),
last_match_ms: Some(10),
matches: 1,
..bare_row("A", 1)
},
ChampionRow {
average_placement: Some(1.5),
last_match_ms: Some(30),
matches: 3,
..bare_row("B", 2)
},
bare_row("C", 3),
];
let order = |column, descending| {
let mut sorted = rows.clone();
sort_rows(&mut sorted, column, descending);
sorted
.iter()
.map(|r| r.champion.name.clone())
.collect::<Vec<_>>()
.concat()
};
assert_eq!(order(Column::AveragePlacement, false), "BAC");
assert_eq!(order(Column::AveragePlacement, true), "ABC");
assert_eq!(order(Column::LastMatch, true), "BAC");
assert_eq!(order(Column::Matches, true), "BAC");
assert_eq!(order(Column::Wins, false), "ABC"); // all zero: by name
}
#[test]
fn state_filters_keep_the_expected_rows() {
let with_state = |state| ChampionRow {
state,
..bare_row("A", 1)
};
let completed = with_state(Some(ChampionState::Completed));
let in_progress = with_state(Some(ChampionState::InProgress));
let never = with_state(Some(ChampionState::NeverPlayed));
let unknown = with_state(None);
let kept = |filter: StateFilter| -> Vec<bool> {
[&completed, &in_progress, &never, &unknown]
.iter()
.map(|r| filter.keeps(r))
.collect()
};
assert_eq!(kept(StateFilter::All), [true, true, true, true]);
assert_eq!(kept(StateFilter::Completed), [true, false, false, false]);
assert_eq!(kept(StateFilter::Remaining), [false, true, true, false]);
assert_eq!(kept(StateFilter::NeverPlayed), [false, false, true, false]);
}
#[test]
fn open_tracker_alone_uses_the_shipped_seasons() {
let dir = tempfile::tempdir().unwrap();
let tracker = Tracker::open(
&dir.path().join("arena.db"),
Box::new(FakeHistory::new(recorded_account(), vec![])),
)
.unwrap();
assert_eq!(tracker.seasons(), arena_tracker_core::default_seasons());
}
#[test]
fn rows_sort_by_state_with_unknown_states_last() {
let with_state = |name, id, state| ChampionRow {
state,
..bare_row(name, id)
};
let mut rows = vec![
with_state("Zed", 1, Some(ChampionState::NeverPlayed)),
with_state("Bard", 2, None),
with_state("Nami", 3, Some(ChampionState::InProgress)),
with_state("Jinx", 4, Some(ChampionState::Completed)),
with_state("Ahri", 5, Some(ChampionState::NeverPlayed)),
with_state("Annie", 6, Some(ChampionState::Completed)),
];
sort_rows(&mut rows, Column::State, false);
assert_eq!(
names(&rows),
["Annie", "Jinx", "Nami", "Ahri", "Zed", "Bard"]
);
sort_rows(&mut rows, Column::State, true);
assert_eq!(
names(&rows),
["Ahri", "Zed", "Nami", "Annie", "Jinx", "Bard"]
);
}
#[test]
fn attempts_follow_start_times_not_the_order_matches_were_stored_in() {
let dir = tempfile::tempdir().unwrap();
// Riot hands the newest Match over first: the top 1 is stored before the two failures.
let matches = [
played_match(11, 1, jan(5, 0)),
played_match(11, 4, jan(3, 0)),
played_match(11, 6, jan(2, 0)),
];
let tracker = Tracker::open(
&dir.path().join("arena.db"),
Box::new(FakeHistory::new(recorded_account(), payloads(&matches)).delivered_as_given()),
)
.unwrap()
.with_seasons(seasons());
tracker.sync(RIOT_ID, &mut |_| {}).unwrap();
let stats = stats(&tracker, S1, None);
let yi = row(&stats, 11);
assert_eq!(
(yi.state, yi.attempts),
(Some(ChampionState::Completed), Some(3))
);
assert_eq!(stats.challenge.unwrap().average_attempts, Some(3.0));
}