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 <noreply@anthropic.com>
This commit is contained in:
nessarandClaude Opus 5.5 committed 2026-11-20 21:09:18 +01:00
1 parent 50c0427958
commit 5ce8c777c4
9 files changed
+593 -4

No files matched your search

+49
View File
@@ -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<UpdateChannel>,
/// `None` until the player chooses: the cards are sorted by Mastery Points.
#[serde(skip_serializing_if = "Option::is_none")]
pub champion_sort: Option<ChampionSort>,
}
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!(
+5
View File
@@ -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) => {
+1 -1
View File
@@ -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::{
+73 -1
View File
@@ -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<String, SourceError> {
self.get_on(&self.host, path_and_query)
}
fn get_on(&self, host: &str, path_and_query: &str) -> Result<String, SourceError> {
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<String, SourceError> {
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<Vec<(u32, u64)>, 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<Account, SourceError> {
@@ -143,6 +171,21 @@ fn decode_ids(body: &str) -> Result<Vec<String>, SourceError> {
.map_err(|e| SourceError::Other(format!("Liste de Parties illisible : {e}")))
}
fn decode_mastery(body: &str) -> Result<Vec<(u32, u64)>, SourceError> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Entry {
champion_id: u32,
champion_points: u64,
}
let entries: Vec<Entry> = 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!(
+88 -1
View File
@@ -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<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>;
/// 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<Vec<(u32, u64)>, SourceError> {
Err(SourceError::NotFound)
}
}
impl<T: MatchHistorySource + ?Sized> MatchHistorySource for Arc<T> {
@@ -49,6 +59,14 @@ impl<T: MatchHistorySource + ?Sized> MatchHistorySource for Arc<T> {
fn fetch_match(&self, match_id: &str) -> Result<String, SourceError> {
(**self).fetch_match(match_id)
}
fn champion_mastery(
&self,
platform: &str,
puuid: &str,
) -> Result<Vec<(u32, u64)>, 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<Option<HashMap<u32, u64>>, Error> {
let db = self.db();
let known: Option<String> = db
.query_row(
"SELECT value FROM meta WHERE name = ?1",
[mastery_key(puuid)],
|row| row.get(0),
)
.optional()?;
if known.is_none() {
return Ok(None);
}
let mut stmt = db.prepare("SELECT champion_id, points FROM mastery WHERE puuid = ?1")?;
let points = stmt
.query_map([puuid], |row| {
Ok((row.get(0)?, row.get::<_, i64>(1)? as u64))
})?
.collect::<Result<_, _>>()?;
Ok(Some(points))
}
/// One request for the Account's Mastery Points, on the platform of its latest stored
/// Match (none stored: no request). A success replaces the stored list in one transaction;
/// a failure changes nothing, so the last values stay. Called only when the tracker is
/// already talking to Riot about this Account; its errors are not reported anywhere.
pub(crate) fn refresh_mastery(&self, puuid: &str) {
let Ok(Some(platform)) = self.platform_of(puuid) else {
return;
};
let Ok(list) = self.history.champion_mastery(&platform, puuid) else {
return;
};
// Ignored like the fetch itself: the previous values stay.
let _ = self.store_mastery(puuid, &list);
}
fn store_mastery(&self, puuid: &str, list: &[(u32, u64)]) -> Result<(), Error> {
let mut db = self.db();
let tx = db.transaction()?;
tx.execute("DELETE FROM mastery WHERE puuid = ?1", [puuid])?;
{
let mut insert = tx.prepare(
"INSERT OR REPLACE INTO mastery (puuid, champion_id, points) VALUES (?1, ?2, ?3)",
)?;
for &(champion_id, points) in list {
insert.execute(params![puuid, champion_id, points as i64])?;
}
}
tx.execute(
"INSERT OR REPLACE INTO meta (name, value) VALUES (?1, '1')",
[mastery_key(puuid)],
)?;
Ok(tx.commit()?)
}
/// 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
@@ -321,6 +404,10 @@ fn synced_until_key(puuid: &str) -> String {
format!("synced_until_ms:{puuid}")
}
fn mastery_key(puuid: &str) -> String {
format!("mastery:{puuid}")
}
/// What became of one Match fetched by id.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Fetched {