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>
315 lines
10 KiB
Rust
315 lines
10 KiB
Rust
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,
|
|
/// Whether the one-time notice about closing to the notification area was shown.
|
|
#[serde(default)]
|
|
pub tray_notice_shown: bool,
|
|
#[serde(flatten)]
|
|
pub preferences: Preferences,
|
|
#[serde(flatten)]
|
|
other: toml::Table,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
|
#[serde(default)]
|
|
pub struct Preferences {
|
|
pub close_to_tray: bool,
|
|
pub theme: ThemePreference,
|
|
/// `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 {
|
|
fn default() -> Self {
|
|
Self {
|
|
close_to_tray: true,
|
|
theme: ThemePreference::System,
|
|
update_channel: None,
|
|
champion_sort: None,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
|
#[serde(rename_all = "lowercase")]
|
|
pub enum ThemePreference {
|
|
#[default]
|
|
System,
|
|
Light,
|
|
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)]
|
|
#[serde(rename_all = "lowercase")]
|
|
pub enum UpdateChannel {
|
|
Stable,
|
|
Beta,
|
|
}
|
|
|
|
impl UpdateChannel {
|
|
/// The channel's name in release files.
|
|
pub fn name(self) -> &'static str {
|
|
match self {
|
|
UpdateChannel::Stable => "stable",
|
|
UpdateChannel::Beta => "beta",
|
|
}
|
|
}
|
|
}
|
|
|
|
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(),
|
|
tray_notice_shown: false,
|
|
preferences: Preferences::default(),
|
|
other: toml::Table::new(),
|
|
})
|
|
}
|
|
|
|
/// 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");
|
|
assert!(!config.tray_notice_shown);
|
|
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]
|
|
fn saving_other_preferences_records_no_channel_choice() {
|
|
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("update_channel")
|
|
);
|
|
assert_eq!(
|
|
Config::load(&path).unwrap().preferences.update_channel,
|
|
None
|
|
);
|
|
}
|
|
|
|
#[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());
|
|
assert!(config.preferences.close_to_tray);
|
|
assert_eq!(config.preferences.theme, ThemePreference::System);
|
|
}
|
|
|
|
#[test]
|
|
fn saved_settings_load_back() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let path = dir.path().join("config.toml");
|
|
std::fs::write(
|
|
&path,
|
|
"riot_api_key = \"RGAPI-secret\"\nriot_id = \"Joueur#EUW\"\nregion = \"americas\"\n\n[other]\nvalue = 42\n",
|
|
)
|
|
.unwrap();
|
|
let mut config = Config::load(&path).unwrap();
|
|
config.tray_notice_shown = true;
|
|
config.preferences = Preferences {
|
|
close_to_tray: false,
|
|
theme: ThemePreference::Dark,
|
|
update_channel: Some(UpdateChannel::Beta),
|
|
champion_sort: Some(ChampionSort::Name),
|
|
};
|
|
config.save(&path).unwrap();
|
|
assert!(
|
|
std::fs::read_to_string(&path)
|
|
.unwrap()
|
|
.contains("update_channel = \"beta\"")
|
|
);
|
|
let loaded = Config::load_or_default(&path).unwrap();
|
|
|
|
assert_eq!(loaded.preferences, config.preferences);
|
|
assert!(loaded.tray_notice_shown);
|
|
assert_eq!(loaded.other["other"]["value"].as_integer(), Some(42));
|
|
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(),
|
|
tray_notice_shown: false,
|
|
preferences: Preferences::default(),
|
|
other: toml::Table::new(),
|
|
};
|
|
|
|
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(_))
|
|
));
|
|
}
|
|
}
|