From 5ce8c777c4a1f931f389915e4d87a6afa59dc92b Mon Sep 17 00:00:00 2001
From: TO
Date: Fri, 20 Nov 2026 21:08:35 +0100
Subject: [PATCH] Fetch Mastery Points from the Riot API and add the champion
sort preference (#76)
The tracker asks Riot for each Account's champion mastery (platform host) right
after a successful sync, and after a Match fetched by id is added, so no new
polling. Lists are stored per Account in one transaction and read back with
Tracker::mastery (None = never fetched). A failed fetch keeps the last values
and records no problem. Preferences gain champion_sort (mastery or name).
Co-Authored-By: Claude Opus 5.5
---
README.md | 2 +-
crates/core/src/config.rs | 49 +++
crates/core/src/follow.rs | 5 +
crates/core/src/lib.rs | 2 +-
crates/core/src/riot.rs | 74 ++++-
crates/core/src/tracker.rs | 89 +++++-
crates/core/tests/common/mod.rs | 50 +++
.../tests/fixtures/riot/champion_mastery.json | 34 ++
crates/core/tests/mastery.rs | 292 ++++++++++++++++++
9 files changed, 593 insertions(+), 4 deletions(-)
create mode 100644 crates/core/tests/fixtures/riot/champion_mastery.json
create mode 100644 crates/core/tests/mastery.rs
diff --git a/README.md b/README.md
index 87e0093..893a52d 100644
--- a/README.md
+++ b/README.md
@@ -44,7 +44,7 @@ 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.
-L'application y écrit aussi ses préférences (`close_to_tray`, `theme`, `update_channel` : `stable` ou `beta`, absent tant que le canal de la version installée s'applique) et `tray_notice_shown`, qui passe à `true` une fois affichée la notification indiquant que la fenêtre fermée continue dans la zone de notification. Le remettre à `false` la fait réapparaître à la prochaine fermeture.
+L'application y écrit aussi ses préférences (`close_to_tray`, `theme`, `update_channel` : `stable` ou `beta`, absent tant que le canal de la version installée s'applique, `champion_sort` : `mastery` ou `name`, absent tant que le joueur n'a pas choisi, le tri se faisant alors par points de maîtrise) et `tray_notice_shown`, qui passe à `true` une fois affichée la notification indiquant que la fenêtre fermée continue dans la zone de notification. Le remettre à `false` la fait réapparaître à la prochaine fermeture.
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.
diff --git a/crates/core/src/config.rs b/crates/core/src/config.rs
index 922cc5f..59d538f 100644
--- a/crates/core/src/config.rs
+++ b/crates/core/src/config.rs
@@ -30,6 +30,9 @@ pub struct Preferences {
/// `None` until the player chooses: the installed version's channel applies.
#[serde(skip_serializing_if = "Option::is_none")]
pub update_channel: Option,
+ /// `None` until the player chooses: the cards are sorted by Mastery Points.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub champion_sort: Option,
}
impl Default for Preferences {
@@ -38,6 +41,7 @@ impl Default for Preferences {
close_to_tray: true,
theme: ThemePreference::System,
update_channel: None,
+ champion_sort: None,
}
}
}
@@ -51,6 +55,15 @@ pub enum ThemePreference {
Dark,
}
+/// How the champion cards are ordered. Saved only when chosen: without a choice the sort is by
+/// Mastery Points (`Mastery`), highest first; `Name` is A to Z.
+#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum ChampionSort {
+ Mastery,
+ Name,
+}
+
/// The releases an installation follows. Saved only when chosen in the settings: installing or
/// updating to a beta never changes a saved choice.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
@@ -138,6 +151,41 @@ mod tests {
assert!(config.preferences.close_to_tray);
assert_eq!(config.preferences.theme, ThemePreference::System);
assert_eq!(config.preferences.update_channel, None);
+ assert_eq!(config.preferences.champion_sort, None);
+ }
+
+ #[test]
+ fn the_champion_sort_is_saved_only_once_chosen() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("config.toml");
+ let mut config = Config::load_or_default(&path).unwrap();
+ config.preferences.theme = ThemePreference::Dark;
+ config.save(&path).unwrap();
+ assert!(
+ !std::fs::read_to_string(&path)
+ .unwrap()
+ .contains("champion_sort")
+ );
+ assert_eq!(Config::load(&path).unwrap().preferences.champion_sort, None);
+
+ config.preferences.champion_sort = Some(ChampionSort::Name);
+ config.save(&path).unwrap();
+ assert!(
+ std::fs::read_to_string(&path)
+ .unwrap()
+ .contains("champion_sort = \"name\"")
+ );
+ assert_eq!(
+ Config::load(&path).unwrap().preferences.champion_sort,
+ Some(ChampionSort::Name)
+ );
+ assert_eq!(
+ load("champion_sort = \"mastery\"\n")
+ .unwrap()
+ .preferences
+ .champion_sort,
+ Some(ChampionSort::Mastery)
+ );
}
#[test]
@@ -211,6 +259,7 @@ mod tests {
close_to_tray: false,
theme: ThemePreference::Dark,
update_channel: Some(UpdateChannel::Beta),
+ champion_sort: Some(ChampionSort::Name),
};
config.save(&path).unwrap();
assert!(
diff --git a/crates/core/src/follow.rs b/crates/core/src/follow.rs
index 6870462..23aa7b7 100644
--- a/crates/core/src/follow.rs
+++ b/crates/core/src/follow.rs
@@ -424,6 +424,8 @@ impl Tracker {
if report.added > 0 {
self.follow().pending.retain(|p| p.game_id.is_some());
}
+ // Riot has just answered for this Account: one more request for its points.
+ self.refresh_mastery(&report.account.puuid);
Ok(report)
}
Err(e) => Err(self.record(UpdateProblem::from(&e))),
@@ -476,6 +478,9 @@ impl Tracker {
Ok(fetched) => {
let added = usize::from(fetched == Fetched::Added);
self.clear_problem(added);
+ if added > 0 {
+ self.refresh_mastery(&account.puuid);
+ }
(added, fetched != Fetched::NotFound)
}
Err(e) => {
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index effa473..55fb112 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -18,7 +18,7 @@ pub use champ_select::{ChampSelect, ChampSelectReader};
pub use champion_search::ChampionSearch;
pub use champions::{Champion, ChampionCatalog, ChampionSource, DataDragon};
pub use client::{ClientError, ClientEvent, ClientSnapshot, GameClientSource, GamePhase, Gameflow};
-pub use config::{Config, Preferences, ThemePreference, UpdateChannel, data_dir};
+pub use config::{ChampionSort, Config, Preferences, ThemePreference, UpdateChannel, data_dir};
pub use date::Date;
pub use error::{Error, SourceError};
pub use follow::{
diff --git a/crates/core/src/riot.rs b/crates/core/src/riot.rs
index 9b22058..67fc6ba 100644
--- a/crates/core/src/riot.rs
+++ b/crates/core/src/riot.rs
@@ -3,6 +3,7 @@ use std::sync::{Mutex, PoisonError};
use std::thread;
use std::time::{Duration, Instant};
+use serde::Deserialize;
use ureq::{Agent, Body};
use crate::error::SourceError;
@@ -42,6 +43,10 @@ impl RiotApi {
}
fn get(&self, path_and_query: &str) -> Result {
+ self.get_on(&self.host, path_and_query)
+ }
+
+ fn get_on(&self, host: &str, path_and_query: &str) -> Result {
let key = self
.key
.lock()
@@ -55,7 +60,7 @@ impl RiotApi {
Instant::now(),
);
thread::sleep(wait);
- let url = format!("{}{path_and_query}", self.host);
+ let url = format!("{host}{path_and_query}");
get(&self.agent, &url, Some(&key), |body| body.read_to_string())
}
}
@@ -132,6 +137,29 @@ impl MatchHistorySource for RiotApi {
fn fetch_match(&self, match_id: &str) -> Result {
self.get(&format!("/lol/match/v5/matches/{}", encode(match_id)))
}
+
+ /// Mastery lives on the platform host (e.g. `euw1`), not on the regional one.
+ fn champion_mastery(
+ &self,
+ platform: &str,
+ puuid: &str,
+ ) -> Result, SourceError> {
+ // The platform becomes part of the host: nothing but letters and digits goes through.
+ if platform.is_empty() || !platform.bytes().all(|b| b.is_ascii_alphanumeric()) {
+ return Err(SourceError::Other(format!(
+ "Plateforme invalide : {platform}"
+ )));
+ }
+ let host = format!(
+ "https://{}.api.riotgames.com",
+ platform.to_ascii_lowercase()
+ );
+ let path = format!(
+ "/lol/champion-mastery/v4/champion-masteries/by-puuid/{}",
+ encode(puuid)
+ );
+ decode_mastery(&self.get_on(&host, &path)?)
+ }
}
fn decode_account(body: &str) -> Result {
@@ -143,6 +171,21 @@ fn decode_ids(body: &str) -> Result, SourceError> {
.map_err(|e| SourceError::Other(format!("Liste de Parties illisible : {e}")))
}
+fn decode_mastery(body: &str) -> Result, SourceError> {
+ #[derive(Deserialize)]
+ #[serde(rename_all = "camelCase")]
+ struct Entry {
+ champion_id: u32,
+ champion_points: u64,
+ }
+ let entries: Vec = serde_json::from_str(body)
+ .map_err(|e| SourceError::Other(format!("Maîtrise illisible : {e}")))?;
+ Ok(entries
+ .into_iter()
+ .map(|e| (e.champion_id, e.champion_points))
+ .collect())
+}
+
/// Percent-encodes everything but RFC 3986 unreserved characters.
pub(crate) fn encode(segment: &str) -> String {
let mut out = String::new();
@@ -194,6 +237,26 @@ mod tests {
Err(SourceError::MissingKey)
);
assert_eq!(api.fetch_match("EUW1_1"), Err(SourceError::MissingKey));
+ assert_eq!(
+ api.champion_mastery("EUW1", "p"),
+ Err(SourceError::MissingKey)
+ );
+ }
+
+ #[test]
+ fn an_invalid_platform_is_rejected_without_a_request() {
+ // With a key, a request would be attempted (and fail on the network, not as `Other`).
+ let api = RiotApi::new("RGAPI-test".into(), "europe");
+ for platform in ["", "euw1.evil.example/", "eu w1", "euw1@host", "é"] {
+ assert!(
+ matches!(
+ api.champion_mastery(platform, "p"),
+ Err(SourceError::Other(_))
+ ),
+ "{platform:?}"
+ );
+ }
+ assert!(api.sent.lock().unwrap().is_empty());
}
#[test]
@@ -218,6 +281,15 @@ mod tests {
);
}
+ #[test]
+ fn decodes_the_champion_mastery_response() {
+ let points =
+ decode_mastery(include_str!("../tests/fixtures/riot/champion_mastery.json")).unwrap();
+ assert_eq!(points, [(222, 154_320), (103, 27_500), (51, 0)]);
+ assert_eq!(decode_mastery("[]").unwrap(), []);
+ assert!(decode_mastery("{}").is_err());
+ }
+
#[test]
fn decodes_a_match_id_list() {
assert_eq!(
diff --git a/crates/core/src/tracker.rs b/crates/core/src/tracker.rs
index 5334f78..b244202 100644
--- a/crates/core/src/tracker.rs
+++ b/crates/core/src/tracker.rs
@@ -1,4 +1,4 @@
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::thread;
@@ -28,6 +28,16 @@ pub trait MatchHistorySource: Send + Sync {
) -> Result, SourceError>;
/// The raw Match payload (JSON text) exactly as the API returned it.
fn fetch_match(&self, match_id: &str) -> Result;
+ /// The Account's Mastery Points as (champion id, points), for the champions it has points
+ /// with only. `platform` is a platform id such as "EUW1" (not a routing region). Sources
+ /// that cannot tell answer an error.
+ fn champion_mastery(
+ &self,
+ _platform: &str,
+ _puuid: &str,
+ ) -> Result, SourceError> {
+ Err(SourceError::NotFound)
+ }
}
impl MatchHistorySource for Arc {
@@ -49,6 +59,14 @@ impl MatchHistorySource for Arc {
fn fetch_match(&self, match_id: &str) -> Result {
(**self).fetch_match(match_id)
}
+
+ fn champion_mastery(
+ &self,
+ platform: &str,
+ puuid: &str,
+ ) -> Result, SourceError> {
+ (**self).champion_mastery(platform, puuid)
+ }
}
const SCHEMA: &str = "
@@ -75,6 +93,12 @@ CREATE TABLE IF NOT EXISTS champions (
key TEXT NOT NULL,
name TEXT NOT NULL
);
+CREATE TABLE IF NOT EXISTS mastery (
+ puuid TEXT NOT NULL,
+ champion_id INTEGER NOT NULL,
+ points INTEGER NOT NULL,
+ PRIMARY KEY (puuid, champion_id)
+);
CREATE TABLE IF NOT EXISTS meta (
name TEXT PRIMARY KEY,
value TEXT NOT NULL
@@ -258,6 +282,65 @@ impl Tracker {
Ok(mark.and_then(|ms| ms.parse().ok()))
}
+ /// The Mastery Points Riot last returned for the Account, by champion id. `None`: never
+ /// fetched for this Account, so every value is unknown. `Some(map)`: the last list Riot
+ /// returned; it holds only the champions with points, so once a list is known a champion
+ /// missing from it has 0 points. Never touches the network.
+ pub fn mastery(&self, puuid: &str) -> Result