Author SHA1 Message Date
nessar 2622b11028 Document EUW community Arena statistics for v2 (#46)
CI / core (pull_request) Successful in 1m10s
2026-11-18 23:47:57 +01:00
44 changed files with 276 additions and 5780 deletions

No files matched your search

-3
View File
@@ -1,3 +0,0 @@
# Link the MSVC C runtime into the executable: the installer ships no vcruntime140.dll (ADR-0005).
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
-9
View File
@@ -1,5 +1,4 @@
# Only the core crate is checked: the app crate (GPUI) only builds on Windows (ADR-0003).
# Betas of develop are published from the build PC once these checks pass (docs/publication.md).
name: CI
on:
@@ -7,11 +6,6 @@ on:
push:
branches:
- main
- develop
# CI never publishes: a read-only job token is enough.
permissions:
contents: read
jobs:
core:
@@ -32,6 +26,3 @@ jobs:
- name: Tests
run: cargo test -p arena-tracker-core --locked
- name: Beta publication tests
run: python3 scripts/test_publish_beta.py
-1
View File
@@ -1,4 +1,3 @@
/target
*.local.toml
.env
__pycache__/
+9 -29
View File
@@ -6,12 +6,9 @@ Personal tracking of League of Legends Arena matches, centred on progress throug
**Match**:
A finished Arena game played by an Account with one champion, in one Format.
In community statistics, each participant contributes one Match for their champion. Each distinct item in that participant's final inventory and each distinct selected Augment counts once in that Match.
_Avoid_: Game, session
**Match Recap**:
The available statistics for a Match and its participants.
_Avoid_: Match report
**Format**:
A variant of Arena with its own team structure and rules, such as Arena 3x6 or Bravery Arena; it filters statistics but does not split the Challenge.
_Avoid_: Mode, type, queue
@@ -32,13 +29,6 @@ _Avoid_: Victory
The goal of getting a top 1 with every champion in the game in as few Attempts as possible, scoped to one Account and one Season across all Formats, mirroring how the game client counts it.
_Avoid_: Checklist, goal, Arena God
**Mark**:
One of three milestones for a champion within a Challenge, earned for the first Match, the first Win, and the first top 1 respectively. A first Match ending in a top 1 earns all three Marks at once.
_Avoid_: Point, Fame
**Mastery Points**:
The champion mastery score that League of Legends gives an Account for a particular champion.
**Completed**:
The state of a champion that has at least one top 1 within a given Challenge.
_Avoid_: Done, validated, won
@@ -59,22 +49,16 @@ _Avoid_: Split, run
A League of Legends account; the active Account is the one signed in to the game client.
_Avoid_: Player, profile, summoner
**Champ select**:
The draft before an Arena Match, where each player bans and picks a champion; only an Arena champ select opens the champ select view.
_Avoid_: Draft, selection
**Anvil champions**:
The five champions the game favours in the current Arena patch and shows during champ select; the game client calls them crowd favorites.
_Avoid_: Crowd favorites, favorites
**Pickable**:
A champion the local player can still pick in the current Arena champ select: offered by the client, not disabled, and neither banned nor taken by another player.
_Avoid_: Available, owned
**Official Progress**:
The game's own per-Season count of champions it considers completed, used only to cross-check a Challenge.
_Avoid_: Riot challenge, tracker
**Augment**:
An Arena effect the player selects during play that changes how their champion plays.
**Tier**:
A grade for an Arena item or Augment on a given champion. When enough Matches are available, the main criterion is its observed top 1 rate relative to the champion's overall top 1 rate on the same patch and in the same Format. S is the highest grade.
## Interface terms
The interface is in French. Each glossary term has one French word in user-facing text; the _Avoid_ lists above govern English naming in code and documents, not these words.
@@ -82,18 +66,14 @@ The interface is in French. Each glossary term has one French word in user-facin
| Term | In the interface |
| --- | --- |
| Match | Partie |
| Match Recap | Récapitulatif de partie |
| Challenge | Défi |
| Mark | Marque |
| Mastery Points | Points de maîtrise |
| Attempt | Tentative |
| First Try | du premier coup |
| Completed | validé |
| Win | Victoire |
| Season | Saison |
| Account | Compte |
| Champ select | Sélection des champions |
| Anvil champions | Champions de l'Enclume |
| Pickable | Disponible |
| Official Progress | Progression officielle |
| Augment | Amélioration |
| Tier | Tier |
| Placement, Format, Top N | unchanged |
Generated
+2 -4
View File
@@ -219,10 +219,9 @@ dependencies = [
[[package]]
name = "arena-tracker"
version = "1.0.0"
version = "0.1.0"
dependencies = [
"arena-tracker-core",
"base64 0.23.1",
"embed-resource",
"gpui-kit",
"gpui-pre",
@@ -232,10 +231,9 @@ dependencies = [
[[package]]
name = "arena-tracker-core"
version = "1.0.0"
version = "0.1.0"
dependencies = [
"base64 0.23.1",
"ring",
"rusqlite",
"rustls",
"serde",
+1 -1
View File
@@ -6,4 +6,4 @@ default-members = ["crates/core"]
[workspace.package]
edition = "2024"
rust-version = "1.98"
version = "1.0.0"
version = "0.1.0"
-4
View File
@@ -4,8 +4,6 @@ Application de bureau Windows qui suit les Parties d'Arena de League of Legends.
Règle n°1 : l'application reste fluide et légère, sans jamais donner l'impression de ralentir ni l'application ni l'ordinateur. Ses budgets mesurables (temps par image, CPU au repos, mémoire, travail de fond) et la façon de les mesurer sont dans `docs/performance.md`.
L’installateur par utilisateur et la commande de construction des paquets Stable et Bêta sont décrits dans le [guide des paquets Windows](docs/paquets-windows.md). Les branches main et develop, la cible du cycle et la publication des bêtas sont décrites dans [Publication](docs/publication.md).
## Prérequis
- Windows avec la chaîne d'outils Rust (rustup), version 1.98 ou plus récente, accessible depuis WSL sous le nom `cargo.exe`.
@@ -44,8 +42,6 @@ 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.
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
-3
View File
@@ -9,15 +9,12 @@ profile = ["gpui-kit/profiler"]
[dependencies]
arena-tracker-core = { path = "../core" }
base64 = { version = "0.23.1", default-features = false, features = ["std"] }
gpui-kit = "=0.9.1"
[target.'cfg(windows)'.dependencies]
raw-window-handle = "0.6"
windows = { version = "0.62", features = [
"Win32_Security",
"Win32_System_LibraryLoader",
"Win32_System_Threading",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
] }
-92
View File
@@ -1,92 +0,0 @@
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION AND CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
-22
View File
@@ -1,24 +1,2 @@
// GPUI loads icon resource 1 for the window and its taskbar entry; File Explorer shows it too.
1 ICON "icon.ico"
#ifdef ARENA_RELEASE
#include "release-version.h"
1 VERSIONINFO
FILEVERSION ARENA_VERSION_NUMBERS
PRODUCTVERSION ARENA_VERSION_NUMBERS
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904B0"
BEGIN
VALUE "ProductName", "Arena Tracker"
VALUE "FileVersion", ARENA_VERSION_TEXT
VALUE "ProductVersion", ARENA_VERSION_TEXT
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x0409, 1200
END
END
#endif
-13
View File
@@ -194,19 +194,6 @@ impl ChampionTable {
}
}
/// Prepared on pick/statistics changes so a redraw only lays out the labels.
pub fn pick_labels(row: &ChampionRow) -> Vec<SharedString> {
SPECS
.iter()
.map(|spec| {
if spec.key == SortKey::Champion {
return row.champion.name.clone().into();
}
format!("{} · {}", spec.title, cell_text(row, spec.key)).into()
})
.collect()
}
/// A cell of `spec`'s column, header or body: fixed width, shrinking with the window.
// Text past it is clipped: an ellipsis (`text_ellipsis`) cost 0.2 ms per frame (#31).
fn cell(spec: &Spec) -> Div {
+40 -285
View File
@@ -3,16 +3,13 @@
mod champion_table;
#[cfg(feature = "profile")]
mod profile;
mod release;
mod settings;
mod single_instance;
mod stats_page;
mod text;
mod title_bar;
mod tray;
mod worker;
use std::{borrow::Cow, ops::ControlFlow, rc::Rc, sync::Arc};
use std::{rc::Rc, sync::Arc};
use arena_tracker_core::{
Config, DataDragon, LeagueClient, Preferences, RiotApi, Tracker, data_dir, default_seasons,
@@ -23,8 +20,7 @@ use gpui_kit::component::*;
use gpui_kit::*;
use settings::{KeyEvent, KeyForm, KeyStore, apply_theme};
use stats_page::StatsPage;
use title_bar::{MIN_WINDOW_SIZE, refresh_button, settings_button, title_bar, update_button};
use stats_page::{PageEvent, StatsPage};
use worker::{Msg, spawn_follower};
#[derive(Clone, Copy, PartialEq)]
@@ -38,14 +34,12 @@ enum Screen {
struct RootView {
page: Entity<StatsPage>,
form: Entity<KeyForm>,
focus: FocusHandle,
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>,
_form_events: Subscription,
_champ_select: Subscription,
_subscriptions: Vec<Subscription>,
}
impl RootView {
@@ -72,8 +66,19 @@ impl RootView {
)
});
let form = cx.new(|cx| KeyForm::new(store, first_launch, window, cx));
let form_events =
cx.subscribe_in(&form, window, |this, _, event: &KeyEvent, 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.
@@ -82,30 +87,13 @@ impl RootView {
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.request_refresh(cx)),
KeyEvent::Saved => this.page.update(cx, |page, cx| page.begin_refresh(cx)),
KeyEvent::Back => {}
// Only the title bar changes.
KeyEvent::UpdateReady => return cx.notify(),
}
this.show_page(window, cx);
});
let champ_select = cx.subscribe_in(
&page,
window,
|this, _, transition: &stats_page::ChampSelectTransition, window, cx| {
// Only on entry: the window stays open after the champ select.
if transition.entered
&& let Some(hwnd) = tray::window_hwnd(window)
{
// Outside this update: the native calls resize the window through GPUI.
cx.spawn(async move |_, _| tray::reveal(hwnd)).detach();
}
if this.screen == Screen::Settings {
// Champ select takes the window away: do not bring back half-typed edits.
this.show_page(window, cx);
}
},
);
this.screen = Screen::Page;
cx.notify();
}),
];
let screen = if first_launch {
Screen::Prompt
} else {
@@ -115,105 +103,39 @@ impl RootView {
RootView {
page,
form,
focus: initial_focus(window, cx),
screen,
tracker,
fallback_riot_id: riot_id,
tx,
_form_events: form_events,
_champ_select: champ_select,
_subscriptions: subscriptions,
}
}
fn can_refresh(&self, cx: &App) -> bool {
self.screen != Screen::Prompt && self.form.read(cx).has_key() && !self.page.read(cx).busy()
}
fn open_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.screen == Screen::Page {
self.screen = Screen::Settings;
self.focus.focus(window, cx);
cx.notify();
}
}
/// Leaves the key form for the page, discarding half-typed edits.
fn show_page(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.form.update(cx, |form, cx| form.reset(window, cx));
self.screen = Screen::Page;
self.focus.focus(window, cx);
cx.notify();
}
}
impl Render for RootView {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let refresh =
refresh_button(self.can_refresh(cx), cx).on_click(cx.listener(|this, _, _, cx| {
if this.can_refresh(cx) {
this.page.update(cx, |page, cx| page.request_refresh(cx));
}
}));
let on_page = self.screen == Screen::Page;
let settings = settings_button(on_page, cx)
.on_click(cx.listener(|this, _, window, cx| this.open_settings(window, cx)));
// The settings show the ready version next to « Redémarrer ».
let update = self.form.read(cx).update_ready().then(|| {
update_button(on_page, cx)
.on_click(cx.listener(|this, _, window, cx| this.open_settings(window, cx)))
});
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()
.id("arena-tracker")
.track_focus(&self.focus)
.v_flex()
.size_full()
.child(title_bar(refresh, settings, update, window, cx))
.child(div().flex_1().min_h_0().child(content))
div().size_full().child(content)
}
}
/// Shown instead of the app when the configuration or the database cannot be loaded.
struct Unavailable {
lines: Vec<String>,
focus: FocusHandle,
}
struct Unavailable(Vec<String>);
impl Render for Unavailable {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.id("unavailable")
.track_focus(&self.focus)
.v_flex()
.size_full()
.child(title_bar(
refresh_button(false, cx),
settings_button(false, cx),
None,
window,
cx,
))
.child(
div()
.v_flex()
.flex_1()
.items_center()
.justify_center()
.children(self.lines.clone()),
)
.items_center()
.justify_center()
.children(self.0.clone())
}
}
fn initial_focus(window: &mut Window, cx: &mut App) -> FocusHandle {
// Tab dispatch needs a focused element inside gpui-kit's root key context.
let focus = cx.focus_handle();
focus.focus(window, cx);
focus
}
struct Setup {
tracker: Arc<Tracker>,
riot_id: String,
@@ -259,211 +181,44 @@ fn startup() -> Result<Setup, (Vec<String>, Preferences)> {
})
}
/// DirectWrite exposes the variable font's text optical size as its own family.
const INTER: &str = "Inter Variable Text";
/// Sets Inter as the interface font and adjusts the theme colours. Needs `gpui_kit::init` first.
fn init_theme(cx: &mut App) {
let text = cx.text_system();
let ttf = include_bytes!("../assets/InterVariable.ttf");
if let Err(error) = text.add_fonts(vec![Cow::Borrowed(ttf)]) {
eprintln!("Failed to load Inter: {error}");
}
// A family that falls back costs a font lookup on every text run: keep the system font then.
let inter = font(INTER);
if text.get_font_for_id(text.resolve_font(&inter)) == Some(inter) {
Theme::update(cx, |theme| theme.font_family = INTER.into());
}
// The default dark table header text has low contrast against its background.
let dark = Rc::make_mut(&mut Theme::global_mut(cx).dark_theme);
dark.colors.table_head_foreground = dark.colors.muted_foreground.clone();
}
fn main() {
release::handle_command();
let Some(single_instance::Primary {
instance: _instance,
starting,
}) = single_instance::launch()
else {
return;
};
// Only the single instance gets here: a launch relayed to a running one installs nothing.
let ControlFlow::Continue(update_notice) = release::update_at_launch() else {
return;
};
let app = gpui_kit::application().with_assets(gpui_kit::assets::Assets);
app.run(move |cx| {
gpui_kit::init(cx);
init_theme(cx);
// The default dark table header text has low contrast against its background.
let dark = Rc::make_mut(&mut Theme::global_mut(cx).dark_theme);
dark.colors.table_head_foreground = dark.colors.muted_foreground.clone();
#[cfg(feature = "profile")]
profile::start(cx);
let options = WindowOptions {
titlebar: Some(TitlebarOptions {
title: Some("Arena Tracker".into()),
..TitleBar::title_bar_options()
..Default::default()
}),
window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
None,
size(px(1280.), px(860.)),
cx,
))),
window_min_size: Some(MIN_WINDOW_SIZE),
..Default::default()
};
match startup() {
Ok(mut setup) => {
setup.notice = (update_notice.into_iter().chain(setup.notice))
.reduce(|update, seasons| format!("{update}\n{seasons}"));
gpui_kit::open_window(options, cx, |window, cx| {
single_instance::accept_relaunches(window);
cx.new(|cx| RootView::new(setup, window, cx))
})
.map(drop)
}
Err((mut lines, preferences)) => gpui_kit::open_window(options, cx, |window, cx| {
lines.extend(update_notice);
single_instance::accept_relaunches(window);
Ok(setup) => gpui_kit::open_window(options, cx, |window, cx| {
cx.new(|cx| RootView::new(setup, window, cx))
})
.map(drop),
Err((lines, preferences)) => gpui_kit::open_window(options, cx, |window, cx| {
apply_theme(preferences.theme, window, cx);
window
.observe_window_appearance(move |window, cx| {
apply_theme(preferences.theme, window, cx);
})
.detach();
// Without a readable configuration the one-time notice could not be recorded.
tray::Tray::install_saved(window, preferences.close_to_tray, None, cx);
cx.new(|cx| Unavailable {
lines,
focus: initial_focus(window, cx),
})
tray::Tray::install_saved(window, preferences.close_to_tray, cx);
cx.new(|_| Unavailable(lines))
})
.map(drop),
}
.expect("Failed to open window");
drop(starting);
});
}
#[cfg(test)]
mod tests {
use std::path::Path;
use std::sync::Arc;
use arena_tracker_core::{Config, RiotApi, Tracker, UpdateChannel};
use gpui_kit::component::{Theme, ThemeMode};
use gpui_kit::{
AppContext as _, Entity, FontWeight, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers,
TestAppContext, VisualTestContext, WindowOptions, font, point, px,
};
use super::{INTER, KeyStore, RootView, Screen, Setup};
use crate::title_bar::{BAR_HEIGHT, BUTTON_WIDTH};
use crate::worker::UpdateChecked;
// Not #[gpui::test]: its text system is a no-op, and this checks DirectWrite's real one.
#[test]
fn inter_is_used_in_both_themes() {
let platform = gpui_kit::platform::current_platform(false);
let cx = TestAppContext::build_with_text_system(
gpui::TestDispatcher::new(0),
None,
platform.text_system(),
);
cx.update(|cx| {
gpui_kit::init(cx);
super::init_theme(cx);
for mode in [ThemeMode::Light, ThemeMode::Dark] {
Theme::change(mode, None, cx);
assert_eq!(Theme::global(cx).font_family.as_str(), INTER);
}
// DirectWrite returns the nearest weight, so only a wider glyph proves a semibold face.
let text = cx.text_system();
let [regular, semibold] = [FontWeight::NORMAL, FontWeight::SEMIBOLD].map(|weight| {
let mut requested = font(INTER);
requested.weight = weight;
let id = text.resolve_font(&requested);
assert_eq!(text.get_font_for_id(id), Some(requested));
text.advance(id, px(14.), 'm').unwrap().width
});
assert!(semibold > regular, "{semibold:?} <= {regular:?}");
});
}
/// A first launch: no key and nothing stored.
fn first_launch(cx: &mut TestAppContext) -> (VisualTestContext, Entity<RootView>) {
cx.update(gpui_kit::init);
let (window, root) = cx.update(|cx| {
let config = Config::load_or_default(Path::new(":memory:")).unwrap();
let api = Arc::new(RiotApi::new(String::new(), &config.region));
let setup = Setup {
tracker: Arc::new(
Tracker::open(Path::new(":memory:"), Box::new(api.clone())).unwrap(),
),
riot_id: String::new(),
notice: None,
store: KeyStore::new("unused.toml".into(), config, api),
};
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| RootView::new(setup, window, cx))
})
.unwrap()
});
(VisualTestContext::from_window(window, cx), root)
}
#[gpui::test]
fn a_ready_update_adds_a_title_bar_button_that_opens_the_settings(cx: &mut TestAppContext) {
let (mut cx, root) = first_launch(cx);
let cx = &mut cx;
root.update(cx, |root, cx| {
root.screen = Screen::Page;
cx.notify();
});
// Centre of the third action button, title-bar drag area until an update is ready.
let update = point(BUTTON_WIDTH * 2.5, BAR_HEIGHT / 2.);
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.simulate_click(update, Modifiers::none());
assert!(root.read_with(cx, |root, _| root.screen == Screen::Page));
let form = root.read_with(cx, |root, _| root.form.clone());
form.update(cx, |form, cx| {
let checked = UpdateChecked {
channel: UpdateChannel::Stable,
ready: Some("1.0.1".into()),
};
form.update_checked(checked, cx);
});
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.simulate_click(update, Modifiers::none());
assert!(root.read_with(cx, |root, _| root.screen == Screen::Settings));
}
#[gpui::test]
fn settings_in_the_title_bar_respects_the_initial_key_prompt(cx: &mut TestAppContext) {
let (mut cx, root) = first_launch(cx);
let cx = &mut cx;
// Centre of the second action button.
let settings = point(BUTTON_WIDTH * 1.5, BAR_HEIGHT / 2.);
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.simulate_click(settings, Modifiers::none());
assert!(root.read_with(cx, |root, _| root.screen == Screen::Prompt));
// Model a keyless launch with stored data, where Settings is available.
root.update(cx, |root, cx| {
root.screen = Screen::Page;
cx.notify();
});
assert!(!root.read_with(cx, |root, cx| root.can_refresh(cx)));
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.simulate_keystrokes("tab");
let enter =
cx.update(|_, cx| Keystroke::parse_with_os("enter", cx.platform_info().os).unwrap());
cx.simulate_event(KeyDownEvent {
keystroke: enter.clone(),
is_held: false,
prefer_character_input: false,
});
cx.simulate_event(KeyUpEvent { keystroke: enter });
assert!(root.read_with(cx, |root, _| root.screen == Screen::Settings));
}
}
-212
View File
@@ -1,212 +0,0 @@
use std::io;
use std::ops::ControlFlow;
use std::os::windows::io::AsRawHandle;
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use arena_tracker_core::{Config, Preferences, UpdateChannel, data_dir};
use base64::prelude::{BASE64_STANDARD, Engine};
use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0};
use windows::Win32::System::Threading::{
CREATE_NO_WINDOW, GetExitCodeProcess, OpenProcess, PROCESS_NAME_WIN32,
PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, QueryFullProcessImageNameW,
WaitForSingleObject,
};
use windows::core::PWSTR;
use crate::single_instance::owned;
/// This executable's release version; `None` for a development build, which never updates.
pub const VERSION: Option<&str> = option_env!("ARENA_RELEASE_VERSION");
const CHANNEL: Option<&str> = option_env!("ARENA_RELEASE_CHANNEL");
const PUBLIC_KEY: Option<&str> = option_env!("ARENA_RELEASE_PUBLIC_KEY");
/// Public: read without a Gitea account or token.
const RELEASES: &str = "https://gitea.nessar.fr/api/v1/repos/nessar/arena-tracker/releases";
/// Velopack 1.2.161 waits up to 60 s for the app to exit, 15 s for each hook and about 40 s
/// for the folder swap: an installer still running after this counts as failed.
const INSTALLER_WAIT_MS: u32 = 180_000;
/// The Windows installer invokes these fast callbacks and waits for the process to exit.
/// The SDK's ordinary startup path opens cached packages even with auto-apply disabled.
pub fn handle_command() {
let mut args = std::env::args_os().skip(1);
let Some(command) = args.next() else { return };
match command.to_str() {
Some(
"--veloapp-install"
| "--veloapp-updated"
| "--veloapp-obsolete"
| "--veloapp-uninstall",
) => {
std::process::exit(0);
}
Some("--verify-release") => {
let ok = args.next().is_some_and(|dir| {
verify_release(Path::new(&dir))
.inspect_err(|err| eprintln!("{err}"))
.is_ok()
});
std::process::exit(if ok { 0 } else { 1 });
}
_ => {}
}
}
/// Checks a release folder with the identity this executable was built with.
fn verify_release(dir: &Path) -> Result<(), String> {
let (Some(channel), Some(version), Some(key), Some(commit)) = (
CHANNEL,
VERSION,
PUBLIC_KEY,
option_env!("ARENA_RELEASE_COMMIT"),
) else {
return Err("Exécutable construit sans identité de version.".into());
};
let key = BASE64_STANDARD.decode(key).map_err(|e| e.to_string())?;
let signed_commit = arena_tracker_core::verify_release(dir, &key, channel, version)
.map_err(|e| e.to_string())?;
if signed_commit != commit {
return Err("Commit de la version inattendu.".into());
}
Ok(())
}
/// The saved choice, or until the player chooses, the installed version's channel: Stable for a
/// development build.
pub fn channel(preferences: Preferences) -> UpdateChannel {
(preferences.update_channel).unwrap_or(if CHANNEL == Some("beta") {
UpdateChannel::Beta
} else {
UpdateChannel::Stable
})
}
/// What every update step needs: the folder of kept updates,
/// `%LOCALAPPDATA%\arena-tracker\updates`, outside the installation and Velopack's cache; the
/// public key; the installed version. `None` for a development build.
fn update_context() -> Option<(PathBuf, Vec<u8>, &'static str)> {
let dir = PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join("arena-tracker/updates");
Some((dir, BASE64_STANDARD.decode(PUBLIC_KEY?).ok()?, VERSION?))
}
/// Keeps the newest release of `channel` downloaded and authenticated in the updates folder and
/// returns its version. A failed check only means no update is ready; the next launch checks
/// again.
pub fn download_update(channel: UpdateChannel) -> Option<String> {
let (dir, key, version) = update_context()?;
arena_tracker_core::download_update(RELEASES, &dir, &key, channel, version)
.ok()
.flatten()
}
/// Before the app loads, in the single instance only: hands the kept update of the chosen
/// channel to Update.exe once. `Break`: Update.exe replaces this version and opens the app.
/// `Continue`: load the app, with the notice to show if there is one.
pub fn update_at_launch() -> ControlFlow<(), Option<String>> {
let Some((dir, key, version)) = update_context() else {
return ControlFlow::Continue(None);
};
// Without a readable configuration the chosen channel is unknown; the app then says why.
// shortcut: startup() reads config.toml again, a few hundred bytes; pass it along if that
// file ever grows.
let config =
data_dir().and_then(|data| Config::load_or_default(&data.join("config.toml")).ok());
let Some(config) = config else {
return ControlFlow::Continue(None);
};
let channel = channel(config.preferences);
arena_tracker_core::update_at_launch(
&dir,
&key,
channel,
version,
start_installer,
installer_exit,
)
.map_continue(|error| error.map(|error| error.to_string()))
}
/// « Redémarrer »: hands the kept update of `channel` to Update.exe; the app must then quit.
/// Hashes the package on the calling thread: a few tens of milliseconds for a full package.
pub fn restart_to_update(channel: UpdateChannel) -> Result<(), String> {
let (dir, key, version) = update_context().ok_or("Cette version ne se met pas à jour.")?;
arena_tracker_core::restart_to_update(&dir, &key, channel, version, start_installer)
.map_err(|e| e.to_string())
}
/// Update.exe at the installation's root, next to `current\arena-tracker.exe`.
fn installer() -> io::Result<PathBuf> {
let exe = std::env::current_exe()?;
let root = exe.parent().and_then(Path::parent);
Ok(root.ok_or(io::ErrorKind::NotFound)?.join("Update.exe"))
}
/// Starts Velopack's installer on an authenticated package, which it reads in place: it waits
/// for this process to exit, replaces `current\` and opens the app once, this version again if
/// it fails (ADR-0005, `docs/paquets-windows.md`).
fn start_installer(package: &Path) -> io::Result<u32> {
let child = Command::new(installer()?)
.args([
"apply",
"--waitPid",
&std::process::id().to_string(),
"--package",
])
.arg(package)
.creation_flags(CREATE_NO_WINDOW.0)
.spawn()?;
Ok(child.id())
}
/// The exit code of the installer an earlier launch started as `pid`, once it ends. A launch
/// waiting here runs from the installation, so Velopack stops it before replacing `current\`.
fn installer_exit(pid: u32) -> Option<u32> {
process_exit(pid, &installer().ok()?)
}
/// Waits for process `pid` and returns its exit code; `None` when no such process runs from
/// `image` (the id may belong to another program by now), or when it still runs after the wait.
// shortcut: compares path spellings, as current_exe() gives them to both launches; compare file
// identities if an 8.3 or `\\?\` spelling ever shows up there.
fn process_exit(pid: u32, image: &Path) -> Option<u32> {
let access = PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE;
let process = owned(unsafe { OpenProcess(access, false, pid) }.ok()?);
let handle = HANDLE(process.as_raw_handle());
let mut name = [0u16; 1024];
let mut len = name.len() as u32;
let name_ptr = PWSTR(name.as_mut_ptr());
unsafe { QueryFullProcessImageNameW(handle, PROCESS_NAME_WIN32, name_ptr, &mut len) }.ok()?;
let name = String::from_utf16_lossy(&name[..len as usize]);
if !name.eq_ignore_ascii_case(&image.to_string_lossy())
|| unsafe { WaitForSingleObject(handle, INSTALLER_WAIT_MS) } != WAIT_OBJECT_0
{
return None;
}
let mut code = 0;
unsafe { GetExitCodeProcess(handle, &mut code) }.ok()?;
Some(code)
}
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use std::process::Command;
use super::process_exit;
#[test]
fn the_installers_exit_code_is_read_only_from_its_own_image() {
let windows = PathBuf::from(std::env::var_os("SystemRoot").unwrap());
let cmd = windows.join("System32").join("cmd.exe");
// Kept until the end: its open handle stops the id from going to another process.
let child = Command::new(&cmd).args(["/c", "exit 3"]).spawn().unwrap();
assert_eq!(
process_exit(child.id(), Path::new("C:\\Other\\Update.exe")),
None
);
// SystemRoot and the process image differ in case.
assert_eq!(process_exit(child.id(), &cmd), Some(3));
drop(child);
}
}
+11 -260
View File
@@ -4,8 +4,7 @@ use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
use arena_tracker_core::{Config, Error, Preferences, RiotApi, ThemePreference, UpdateChannel};
use gpui_kit::base::async_util::{Sender, unbounded};
use arena_tracker_core::{Config, Error, Preferences, RiotApi, ThemePreference};
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::component::radio::RadioGroup;
@@ -13,9 +12,7 @@ use gpui_kit::component::switch::Switch;
use gpui_kit::component::{ActiveTheme as _, StyledExt as _, Theme, ThemeMode};
use gpui_kit::*;
use crate::release::{self, channel};
use crate::tray::{Tray, UNAVAILABLE};
use crate::worker::{RefreshGate, UpdateChecked, spawn_update_check};
const PLACEHOLDER_SAVED: &str = "Clé enregistrée";
const PLACEHOLDER_EMPTY: &str = "Clé API Riot";
@@ -24,12 +21,6 @@ const THEMES: [(ThemePreference, &str); 3] = [
(ThemePreference::Light, "Clair"),
(ThemePreference::Dark, "Sombre"),
];
const CHANNELS: [(UpdateChannel, &str); 2] = [
(UpdateChannel::Stable, "Stable"),
(UpdateChannel::Beta, "Bêta"),
];
const STABLE_AFTER_BETA: &str =
"La bêta installée reste en place jusqu’à une version stable plus récente.";
fn theme_mode(preference: ThemePreference, system: ThemeMode) -> ThemeMode {
match preference {
@@ -73,12 +64,6 @@ impl KeyStore {
Ok(())
}
/// A failed write only means the notice is shown again at the next launch.
fn record_tray_notice(&mut self) {
self.config.tray_notice_shown = true;
let _ = self.config.save(&self.path);
}
fn save_preferences(&mut self, preferences: Preferences) -> Result<(), Error> {
let previous = std::mem::replace(&mut self.config.preferences, preferences);
if let Err(error) = self.config.save(&self.path) {
@@ -92,8 +77,6 @@ impl KeyStore {
pub enum KeyEvent {
Saved,
Back,
/// An update became ready or stopped being ready: the title bar shows it.
UpdateReady,
}
pub struct KeyForm {
@@ -102,27 +85,14 @@ pub struct KeyForm {
/// The first-launch prompt (no key and nothing stored yet) has no way back.
first_launch: bool,
error: Option<String>,
preference_error: Option<SharedString>,
preference_error: Option<&'static str>,
tray: Option<Rc<Tray>>,
/// The tray reports here that it showed its one-time notice.
notice_shown: Sender<()>,
/// « Mise à jour prête » with the version downloaded and authenticated for the chosen channel.
ready: Option<SharedString>,
/// One update check at a time: once per launch, then once per channel change.
update_checks: RefreshGate,
updates: Sender<UpdateChecked>,
_subscriptions: [Subscription; 2],
_notice_listener: Task<()>,
_update_listener: Task<()>,
}
impl EventEmitter<KeyEvent> for KeyForm {}
impl KeyForm {
pub fn has_key(&self) -> bool {
self.store.has_key()
}
pub fn new(
store: KeyStore,
first_launch: bool,
@@ -131,30 +101,7 @@ impl KeyForm {
) -> Self {
let preferences = store.config.preferences;
apply_theme(preferences.theme, window, cx);
let (notice_shown, notices) = unbounded();
let notice_listener = cx.spawn(async move |this, cx| {
while notices.recv().await.is_ok() {
if this
.update(cx, |form, _| form.store.record_tray_notice())
.is_err()
{
return;
}
}
});
let (updates, results) = unbounded();
let update_listener = cx.spawn(async move |this, cx| {
while let Ok(checked) = results.recv().await {
if this
.update(cx, |form, cx| form.update_checked(checked, cx))
.is_err()
{
return;
}
}
});
let notice = (!store.config.tray_notice_shown).then(|| notice_shown.clone());
let tray = Tray::install_saved(window, preferences.close_to_tray, notice, cx);
let tray = Tray::install_saved(window, preferences.close_to_tray, cx);
let appearance = cx.observe_window_appearance(window, |this, window, cx| {
apply_theme(this.store.config.preferences.theme, window, cx);
});
@@ -174,72 +121,17 @@ impl KeyForm {
this.save(window, cx);
}
});
let mut form = KeyForm {
KeyForm {
first_launch,
store,
input,
error: None,
preference_error: None,
tray,
notice_shown,
ready: None,
update_checks: RefreshGate::default(),
updates,
_subscriptions: [subscription, appearance],
_notice_listener: notice_listener,
_update_listener: update_listener,
};
form.check_updates();
form
}
pub fn update_ready(&self) -> bool {
self.ready.is_some()
}
/// Not while a check runs: it may replace the folder of the package being handed over.
fn can_restart(&self) -> bool {
self.update_ready() && !self.update_checks.running()
}
/// Checks the chosen channel in the background, after the running check if there is one.
fn check_updates(&mut self) {
if release::VERSION.is_some() && self.update_checks.request() {
let channel = channel(self.store.config.preferences);
spawn_update_check(channel, self.updates.clone());
}
}
/// Only a check of the channel chosen now can make an update ready.
pub(crate) fn update_checked(&mut self, checked: UpdateChecked, cx: &mut Context<Self>) {
if self.update_checks.finished() {
let channel = channel(self.store.config.preferences);
spawn_update_check(channel, self.updates.clone());
}
if checked.channel == channel(self.store.config.preferences) {
let ready = (checked.ready)
.map(|version| format!("Mise à jour prête : version {version}").into());
self.set_ready(ready, cx);
}
// « Redémarrer » waits for the end of the check.
cx.notify();
}
fn set_ready(&mut self, ready: Option<SharedString>, cx: &mut Context<Self>) {
if self.ready != ready {
self.ready = ready;
cx.emit(KeyEvent::UpdateReady);
cx.notify();
}
}
/// « Mise à jour prête », or why an installed beta stays on the stable channel.
fn update_status(&self) -> Option<SharedString> {
let beta = release::VERSION.is_some_and(|version| version.contains("-beta."));
let stable = channel(self.store.config.preferences) == UpdateChannel::Stable;
(self.ready.clone()).or_else(|| (beta && stable).then_some(STABLE_AFTER_BETA.into()))
}
/// 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;
@@ -259,23 +151,17 @@ impl KeyForm {
return;
}
if preferences.close_to_tray && !previous.close_to_tray {
let notice = (!self.store.config.tray_notice_shown).then(|| self.notice_shown.clone());
self.tray = Tray::install(window, notice, cx);
self.tray = Tray::install(window, cx);
if self.tray.is_none() {
self.preference_error = Some(UNAVAILABLE.into());
self.preference_error = Some(UNAVAILABLE);
cx.notify();
return;
}
}
self.preference_error = if self.store.save_preferences(preferences).is_err() {
Some("Impossible d’enregistrer les préférences.".into())
Some("Impossible d’enregistrer les préférences.")
} else {
apply_theme(preferences.theme, window, cx);
if channel(preferences) != channel(previous) {
// The other channel's update must not show as ready, even if its check ends late.
self.set_ready(None, cx);
self.check_updates();
}
None
};
if !self.store.config.preferences.close_to_tray
@@ -288,7 +174,7 @@ impl KeyForm {
fn preferences(&self, cx: &mut Context<Self>) -> impl IntoElement {
let preferences = self.store.config.preferences;
let (muted, danger) = (cx.theme().muted_foreground, cx.theme().danger);
let danger = cx.theme().danger;
div()
.v_flex()
.gap_3()
@@ -328,69 +214,12 @@ impl KeyForm {
})),
),
)
.child(
div()
.v_flex()
.gap_1()
.child("Mises à jour")
.child(
RadioGroup::horizontal("update-channel")
.children(CHANNELS.map(|(_, label)| label))
.selected_index(
CHANNELS
.iter()
.position(|(choice, _)| *choice == channel(preferences)),
)
.on_change(cx.listener(|this, index: &usize, window, cx| {
this.set_preferences(
Preferences {
update_channel: Some(CHANNELS[*index].0),
..this.store.config.preferences
},
window,
cx,
);
})),
)
.children(
self.update_status()
.map(|status| div().text_color(muted).child(status)),
)
.children(self.can_restart().then(|| {
div().h_flex().child(
Button::new("restart")
.label("Redémarrer")
.on_click(cx.listener(|this, _, _, cx| this.restart(cx))),
)
})),
)
.children(
(self.preference_error.clone()).map(|error| div().text_color(danger).child(error)),
self.preference_error
.map(|error| div().text_color(danger).child(error)),
)
}
/// Hands the ready update to the installer, then quits as « Quitter » does: never hidden in
/// the notification area, the single instance is free when the new version opens.
fn restart(&mut self, cx: &mut Context<Self>) {
// A second click queued before the quit must not start a second installer.
if !self.can_restart() {
return;
}
match release::restart_to_update(channel(self.store.config.preferences)) {
Ok(()) => {
self.set_ready(None, cx);
cx.quit();
}
Err(error) => {
self.preference_error = Some(error.into());
// Checked again, and downloaded again if the kept package was altered.
self.set_ready(None, cx);
self.check_updates();
cx.notify();
}
}
}
fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let placeholder = if self.store.has_key() {
PLACEHOLDER_SAVED
@@ -488,85 +317,7 @@ impl Render for KeyForm {
#[cfg(test)]
mod tests {
use std::sync::Arc;
use arena_tracker_core::{Config, Preferences, RiotApi, UpdateChannel};
use gpui_kit::{AppContext as _, TestAppContext, VisualTestContext, WindowOptions};
use super::{KeyForm, KeyStore, ThemeMode, ThemePreference, theme_mode};
use crate::worker::UpdateChecked;
#[gpui::test]
fn the_chosen_channel_is_saved_and_only_its_check_offers_a_restart(cx: &mut TestAppContext) {
cx.update(gpui_kit::init);
let dir = std::env::temp_dir().join(format!("arena-channel-{}", std::process::id()));
let path = dir.join("config.toml");
let _ = std::fs::remove_dir_all(&dir);
let (window, form) = cx.update(|cx| {
let config = Config::load_or_default(&path).unwrap();
let api = Arc::new(RiotApi::new(String::new(), &config.region));
let store = KeyStore::new(path.clone(), config, api);
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| KeyForm::new(store, false, window, cx))
})
.unwrap()
});
let cx = &mut VisualTestContext::from_window(window, cx);
let choose = |channel, cx: &mut VisualTestContext| {
cx.update(|window, cx| {
form.update(cx, |form, cx| {
let preferences = Preferences {
update_channel: Some(channel),
..form.store.config.preferences
};
form.set_preferences(preferences, window, cx);
})
})
};
let saved = |channel| Preferences {
update_channel: Some(channel),
..Preferences::default()
};
choose(UpdateChannel::Beta, cx);
let loaded = Config::load(&path).unwrap().preferences;
assert_eq!(loaded, saved(UpdateChannel::Beta));
form.update(cx, |form, cx| {
// A stable check that ends after the change to Bêta stays out of sight.
let late = UpdateChecked {
channel: UpdateChannel::Stable,
ready: Some("1.0.1".into()),
};
form.update_checked(late, cx);
assert!(!form.update_ready());
assert_eq!(form.update_status(), None);
let checked = UpdateChecked {
channel: UpdateChannel::Beta,
ready: Some("1.1.0-beta.3".into()),
};
form.update_checked(checked, cx);
assert!(form.update_ready());
assert_eq!(
form.update_status().as_deref(),
Some("Mise à jour prête : version 1.1.0-beta.3")
);
});
cx.update(|window, cx| window.draw(cx).clear(cx));
form.update(cx, |form, cx| {
// A development build has no installer: « Redémarrer » says so and the app stays.
form.restart(cx);
assert!(!form.update_ready());
let error = form.preference_error.as_deref();
assert_eq!(error, Some("Cette version ne se met pas à jour."));
});
choose(UpdateChannel::Stable, cx);
assert!(!form.read_with(cx, |form, _| form.update_ready()));
let loaded = Config::load(&path).unwrap().preferences;
assert_eq!(loaded, saved(UpdateChannel::Stable));
std::fs::remove_dir_all(&dir).unwrap();
}
use super::{ThemeMode, ThemePreference, theme_mode};
#[test]
fn system_tracks_the_current_appearance_and_manual_choices_override_it() {
-299
View File
@@ -1,299 +0,0 @@
//! Elects one primary process per Windows session and relays launches to its window.
use std::marker::PhantomData;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use gpui_kit::Window;
use windows::Win32::{
Foundation::{
HANDLE, HWND, LPARAM, LRESULT, WAIT_ABANDONED, WAIT_EVENT, WAIT_OBJECT_0, WAIT_TIMEOUT,
WPARAM,
},
System::Threading::{
CreateEventW, CreateMutexW, EVENT_MODIFY_STATE, OpenEventW, ReleaseMutex, SetEvent,
WaitForMultipleObjects, WaitForSingleObject,
},
UI::{
Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass},
WindowsAndMessaging::*,
},
};
use windows::core::{BOOL, Error, HSTRING, PCWSTR, Result, w};
const STARTING: PCWSTR = w!("Local\\nessar.arena-tracker.starting");
const INSTANCE: PCWSTR = w!("Local\\nessar.arena-tracker.instance");
const WINDOW_MARKER: PCWSTR = w!("nessar.arena-tracker.main-window");
// The marker is only a presence flag, its value is never read.
const MARKED: HANDLE = HANDLE(1 as _);
const REOPEN_SUBCLASS: usize = 0;
// Past this wait another instance is alive, so the launch gives up quietly.
const LAUNCH_TIMEOUT_MS: u32 = 5_000;
// Shares the window's WM_APP message space with the tray's message.
const REOPEN: u32 = crate::tray::TRAY_MESSAGE + 1;
// The acknowledgement event is the second object in the wait list.
const REOPENED: WAIT_EVENT = WAIT_EVENT(WAIT_OBJECT_0.0 + 1);
// Windows requires a mutex to be released on the thread that acquired it.
pub struct HeldMutex(OwnedHandle, PhantomData<*mut ()>);
impl HeldMutex {
/// `None` when the wait timed out. An abandoned mutex (crashed owner) counts as acquired.
fn from_wait(handle: OwnedHandle, status: WAIT_EVENT) -> Result<Option<Self>> {
match status {
WAIT_OBJECT_0 | WAIT_ABANDONED => Ok(Some(Self(handle, PhantomData))),
WAIT_TIMEOUT => Ok(None),
_ => Err(Error::from_thread()),
}
}
}
impl Drop for HeldMutex {
fn drop(&mut self) {
let _ = unsafe { ReleaseMutex(HANDLE(self.0.as_raw_handle())) };
}
}
pub struct Primary {
/// Held for the whole life of the app.
pub instance: HeldMutex,
/// Held until the first window is open, so that relaunches find it.
pub starting: HeldMutex,
}
pub(crate) fn owned(handle: HANDLE) -> OwnedHandle {
unsafe { OwnedHandle::from_raw_handle(handle.0) }
}
fn marked(hwnd: HWND) -> bool {
!unsafe { GetPropW(hwnd, WINDOW_MARKER) }.is_invalid()
}
/// `None` means exit without starting: the launch was relayed, or another instance is alive.
pub fn launch() -> Option<Primary> {
claim(STARTING, INSTANCE, relay).unwrap_or_else(|error| {
eprintln!("Failed to check for a running instance: {error}");
None
})
}
fn claim(
starting_name: PCWSTR,
instance_name: PCWSTR,
relay: impl FnOnce() -> Result<Option<OwnedHandle>>,
) -> Result<Option<Primary>> {
// Serialize launches until the winner has a window. Keep its other lock through app teardown.
let gate = owned(unsafe { CreateMutexW(None, false, starting_name)? });
let status = unsafe { WaitForSingleObject(HANDLE(gate.as_raw_handle()), LAUNCH_TIMEOUT_MS) };
let Some(starting) = HeldMutex::from_wait(gate, status)? else {
return Ok(None);
};
let mutex = owned(unsafe { CreateMutexW(None, false, instance_name)? });
let handle = HANDLE(mutex.as_raw_handle());
let status = match unsafe { WaitForSingleObject(handle, 0) } {
WAIT_TIMEOUT => match relay()? {
// If the window closes before acknowledging, take over when the owner exits.
Some(event) => unsafe {
WaitForMultipleObjects(
&[handle, HANDLE(event.as_raw_handle())],
false,
LAUNCH_TIMEOUT_MS,
)
},
None => unsafe { WaitForSingleObject(handle, LAUNCH_TIMEOUT_MS) },
},
status => status,
};
if status == REOPENED {
return Ok(None);
}
Ok(HeldMutex::from_wait(mutex, status)?.map(|instance| Primary { instance, starting }))
}
fn reply_name(pid: u32) -> HSTRING {
HSTRING::from(format!("Local\\nessar.arena-tracker.reopened.{pid}"))
}
fn relay() -> Result<Option<OwnedHandle>> {
unsafe extern "system" fn find(hwnd: HWND, output: LPARAM) -> BOOL {
if !marked(hwnd) {
return true.into();
}
unsafe { *(output.0 as *mut HWND) = hwnd };
false.into()
}
let mut hwnd = HWND::default();
let _ = unsafe { EnumWindows(Some(find), LPARAM((&mut hwnd as *mut HWND) as isize)) };
if hwnd.is_invalid() {
return Ok(None);
}
let mut pid = 0;
if unsafe { GetWindowThreadProcessId(hwnd, Some(&mut pid)) } == 0 {
return Ok(None);
}
let sender = std::process::id();
let event = owned(unsafe { CreateEventW(None, false, false, &reply_name(sender))? });
let posted = unsafe {
let _ = AllowSetForegroundWindow(pid);
// A posted reopen runs after any close already in the window's message queue.
PostMessageW(Some(hwnd), REOPEN, WPARAM(sender as usize), LPARAM(0))
};
Ok(posted.is_ok().then_some(event))
}
pub fn accept_relaunches(window: &Window) {
let Some(hwnd) = crate::tray::window_hwnd(window) else {
eprintln!("Failed to get the window handle for relaunches");
return;
};
unsafe {
if !SetWindowSubclass(hwnd, Some(window_proc), REOPEN_SUBCLASS, 0).as_bool() {
eprintln!("Failed to install the window reopen handler");
return;
}
if let Err(error) = SetPropW(hwnd, WINDOW_MARKER, Some(MARKED)) {
eprintln!("Failed to publish the window: {error}");
}
}
}
unsafe extern "system" fn window_proc(
hwnd: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
id: usize,
_: usize,
) -> LRESULT {
match message {
REOPEN => {
if marked(hwnd) {
crate::tray::reopen(hwnd);
// The relaunching process may have timed out and exited, taking its event along.
if marked(hwnd)
&& let Ok(event) = unsafe {
OpenEventW(EVENT_MODIFY_STATE, false, &reply_name(wparam.0 as u32))
}
{
let _event = owned(event);
let _ = unsafe { SetEvent(event) };
}
}
return LRESULT(0);
}
WM_DESTROY => {
let _ = unsafe { RemovePropW(hwnd, WINDOW_MARKER) };
}
WM_NCDESTROY => {
let _ = unsafe { RemoveWindowSubclass(hwnd, Some(window_proc), id) };
}
_ => {}
}
unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }
}
#[cfg(test)]
mod tests {
use std::{mem, sync::mpsc, thread, time::Duration};
use super::*;
/// Per-pid mutex names, so that tests never meet a real instance or each other.
fn names(test: &str) -> (HSTRING, HSTRING) {
let pid = std::process::id();
(
HSTRING::from(format!("Local\\arena-tracker.test.{test}.starting.{pid}")),
HSTRING::from(format!("Local\\arena-tracker.test.{test}.instance.{pid}")),
)
}
fn claim_with(
(starting, instance): &(HSTRING, HSTRING),
relay: impl FnOnce() -> Result<Option<OwnedHandle>>,
) -> Result<Option<Primary>> {
claim(PCWSTR(starting.as_ptr()), PCWSTR(instance.as_ptr()), relay)
}
fn event(signaled: bool) -> Result<Option<OwnedHandle>> {
let event = unsafe { CreateEventW(None, false, signaled, PCWSTR::null())? };
Ok(Some(owned(event)))
}
#[test]
fn launch_relays_to_a_running_instance_and_takes_over_after_shutdown() {
let names = names("relay");
let Primary {
instance: primary,
starting: initializing,
} = claim_with(&names, || panic!("First launch has no window to relay to"))
.unwrap()
.unwrap();
let names = &names;
thread::scope(|scope| {
let secondary = scope.spawn(|| {
assert!(claim_with(names, || event(true)).unwrap().is_none());
});
drop(initializing);
secondary.join().unwrap();
let (relaying, attempted) = mpsc::channel();
let successor = scope.spawn(move || {
let result = claim_with(names, || {
relaying.send(()).unwrap();
event(false)
});
assert!(result.unwrap().is_some());
});
let result = attempted.recv_timeout(Duration::from_secs(5));
drop(primary);
result.unwrap();
successor.join().unwrap();
});
}
#[test]
fn launch_takes_over_from_a_crashed_primary() {
let names = names("crashed");
thread::scope(|scope| {
scope
.spawn(|| {
let primary = claim_with(&names, || panic!("No window yet"))
.unwrap()
.unwrap();
// Exiting while owning both mutexes abandons them, as a crash would.
mem::forget(primary);
})
.join()
.unwrap();
});
let result = claim_with(&names, || panic!("The crashed primary left no window"));
assert!(result.unwrap().is_some());
}
#[test]
fn launch_without_a_window_takes_over_once_the_owner_exits() {
let names = names("no-window");
let Primary { instance, starting } = claim_with(&names, || panic!("No window yet"))
.unwrap()
.unwrap();
drop(starting);
let names = &names;
thread::scope(|scope| {
let (relaying, attempted) = mpsc::channel();
let successor = scope.spawn(move || {
let result = claim_with(names, || {
relaying.send(()).unwrap();
Ok(None)
});
assert!(result.unwrap().is_some());
});
let result = attempted.recv_timeout(Duration::from_secs(5));
drop(instance);
result.unwrap();
successor.join().unwrap();
});
}
}
+68 -489
View File
@@ -4,24 +4,24 @@ use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arena_tracker_core::{
Account, ChallengeSummary, ChampSelect, ChampionRow, ChampionSearch, Charts, Format,
ProgressCheck, Scope, SeasonScope, StateFilter, Statistics, Status, SyncProgress, Tracker,
UpdateProblem, account_riot_id, same_riot_id,
Account, ChallengeSummary, ChampionSearch, Charts, Format, ProgressCheck, Scope, SeasonScope,
StateFilter, Statistics, Status, SyncProgress, Tracker, UpdateProblem,
};
use gpui_kit::base::async_util::{Receiver, Sender};
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::input::{Input, InputEvent, InputState};
use gpui_kit::component::select::{Select, SelectEvent, SelectItem, SelectState};
use gpui_kit::component::tab::{Tab, TabBar};
use gpui_kit::component::{ActiveTheme as _, IndexPath, Sizable as _};
use gpui_kit::component::{ActiveTheme as _, Disableable as _, IndexPath, Sizable as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use crate::champion_table::ChampionTable;
use crate::text::{CLIENT_ABSENT, decimal, official_differs, official_note, sync_line};
use crate::worker::{LiveChampSelect, Msg, RefreshGate, spawn_refresh, spawn_statistics};
use crate::text::{CLIENT_ABSENT, decimal, official_differs, official_note, riot_id, sync_line};
use crate::worker::{Msg, RefreshGate, spawn_refresh, spawn_statistics};
const ALL_SEASONS: &str = "Toutes les Saisons";
const ALL_FORMATS: &str = "Tous les Formats";
@@ -32,12 +32,6 @@ const CHARTS_HEIGHT: f32 = 206.;
/// While an import runs, the page is recomputed at most this often.
const RELOAD_EVERY: Duration = Duration::from_secs(1);
fn now_ms() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64)
}
/// Hides page parts for issue #27 measurements only with `--features profile`.
#[inline]
pub fn shown(part: &str) -> bool {
@@ -64,6 +58,10 @@ pub fn shown(part: &str) -> bool {
}
}
pub enum PageEvent {
OpenSettings,
}
/// One Account in the selector; its value is the puuid.
#[derive(Clone, PartialEq)]
struct AccountItem {
@@ -83,30 +81,12 @@ impl SelectItem for AccountItem {
}
}
/// The page entered or left an Arena champ select.
pub struct ChampSelectTransition {
pub entered: bool,
}
impl EventEmitter<ChampSelectTransition> for StatsPage {}
pub struct StatsPage {
tracker: Arc<Tracker>,
tx: Sender<Msg>,
notice: Option<String>,
/// As of the last follower round or refresh.
status: Status,
champ_select: LiveChampSelect,
/// The Account of `champ_select`, resolved when its Riot ID changes.
champ_select_account: Option<String>,
/// The Riot ID `champ_select_account` was resolved for.
champ_select_riot_id: Option<String>,
/// The current champion's cells, prepared when the pick or the statistics change.
current_labels: Vec<SharedString>,
/// What the panel says when the current champion has no statistics row.
current_fallback: SharedString,
/// What the panel says while the statistics are missing.
champ_select_notice: SharedString,
anvil_labels: Vec<SharedString>,
accounts: Vec<Account>,
last_active: Option<Account>,
/// The Account the user picked instead of following the one being updated.
@@ -142,6 +122,8 @@ pub struct StatsPage {
_listener: Task<()>,
}
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] = [
@@ -175,7 +157,10 @@ impl StatsPage {
.map(|s| s.name.into())
.chain([ALL_SEASONS.into()])
.collect();
let current_season = tracker.current_season(now_ms()).map(|s| s.name);
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);
@@ -190,7 +175,8 @@ impl StatsPage {
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 search_input = cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher"));
let search_input =
cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher un champion"));
let charts = cx.new(|_| ChartsRow::new());
let table = cx.new(|_| ChampionTable::new());
@@ -264,13 +250,6 @@ impl StatsPage {
tracker,
tx,
notice,
champ_select: None,
champ_select_account: None,
champ_select_riot_id: None,
current_labels: Vec::new(),
current_fallback: SharedString::default(),
champ_select_notice: SharedString::default(),
anvil_labels: Vec::new(),
accounts: Vec::new(),
last_active: None,
pinned: None,
@@ -312,14 +291,14 @@ impl StatsPage {
}
/// Starts a refresh, or queues one behind the refresh already running.
pub fn request_refresh(&mut self, cx: &mut Context<Self>) {
pub fn begin_refresh(&mut self, cx: &mut Context<Self>) {
if self.refresh.request() {
spawn_refresh(self.tracker.clone(), self.tx.clone());
}
cx.notify();
}
pub fn busy(&self) -> bool {
fn busy(&self) -> bool {
self.progress.is_some() || self.refresh.running() || self.pending_round
}
@@ -366,50 +345,14 @@ impl StatsPage {
}
}
Msg::Champions => self.reload_in_background(window, cx),
Msg::ChampSelect(champ_select) => {
if self.champ_select == champ_select {
return;
}
let previous = self.champ_select.as_ref();
let next = champ_select.as_ref();
let changed_page = previous.is_some() != next.is_some();
let switch = changed_page || previous.map(|(id, _)| id) != next.map(|(id, _)| id);
let pool_changed = match (previous, next) {
(Some((_, before)), Some((_, after))) => !before.same_pickable(after),
(None, None) => false,
_ => true,
};
self.champ_select = champ_select;
if switch {
// The Account belongs to the signed-in Riot ID: resolve it once, not on every
// statistics preparation.
self.champ_select_riot_id = None;
self.stats_generation += 1;
self.stats = None;
self.stats_error = None;
self.stored = None;
self.reload_in_background(window, cx);
}
if changed_page {
cx.emit(ChampSelectTransition {
entered: self.in_champ_select(),
});
}
self.update_picks();
if pool_changed || switch {
self.refresh_table(cx);
}
// A hover or lock-in changes neither the Account nor the pool: the page is
// redrawn by the notification at the end of this message.
}
Msg::Round { status, reload } => {
// A follower round that changes nothing shown must not rebuild the page (they keep coming).
if status == self.status
let unchanged = status == self.status
&& !reload
&& !self.pending_round
&& self.progress.is_none()
&& !self.crashed
{
&& !self.crashed;
if unchanged {
return;
}
self.status = status;
@@ -419,9 +362,6 @@ impl StatsPage {
if reload {
self.reload_in_background(window, cx);
}
if self.in_champ_select() {
self.update_picks();
}
}
Msg::Refreshed(status) => {
self.status = status;
@@ -448,21 +388,16 @@ impl StatsPage {
self.recompute_in_background(true, window, cx);
}
}
Msg::Crashed => self.mark_crashed(),
Msg::RefreshCrashed => {
Msg::Crashed => {
self.refresh.reset();
self.mark_crashed();
self.pending_round = false;
self.progress = None;
self.crashed = true;
}
}
cx.notify();
}
fn mark_crashed(&mut self) {
self.pending_round = false;
self.progress = None;
self.crashed = true;
}
/// A worker's reload: the Accounts now, the statistics on a below-normal worker, so neither a
/// visible nor a hidden window waits for them (rule #1).
fn reload_in_background(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -489,15 +424,11 @@ impl StatsPage {
.iter()
.map(|a| AccountItem {
puuid: a.puuid.clone(),
title: account_riot_id(a).into(),
title: riot_id(a).into(),
})
.collect();
let changed = items != self.account_items;
self.account_items = items.clone();
if changed {
// The live champ select's Account may now be in the list: resolve it again.
self.champ_select_riot_id = None;
}
let viewed = self.viewed().map(|a| a.puuid.clone());
self.account_select.update(cx, |select, cx| {
if changed {
@@ -521,14 +452,6 @@ impl StatsPage {
cx: &mut Context<Self>,
) -> Option<String> {
self.last_reload = Instant::now();
if self.in_champ_select() {
if computing {
self.stats_generation += 1;
}
self.current_season = self.tracker.current_season(now_ms()).map(|s| s.name);
let puuid = self.champ_select_account()?;
return self.current_season.is_some().then_some(puuid);
}
if matches!(self.season, SeasonScope::AllSeasons)
&& !matches!(self.filter, StateFilter::All | StateFilter::NeverPlayed)
{
@@ -550,36 +473,6 @@ impl StatsPage {
viewed
}
/// The Account of the live champ select. Resolved when the signed-in Riot ID changes (or the
/// Accounts do), so preparing statistics builds no Riot ID per Account every time.
fn champ_select_account(&mut self) -> Option<String> {
let id = self.champ_select.as_ref().map(|(id, _)| id.as_str())?;
if self.champ_select_riot_id.as_deref() != Some(id) {
self.champ_select_riot_id = Some(id.into());
self.champ_select_account = self
.accounts
.iter()
.find(|a| same_riot_id(&account_riot_id(a), id))
.map(|a| a.puuid.clone());
}
self.champ_select_account.clone()
}
fn statistics_scope(&self) -> Scope {
if self.in_champ_select()
&& let Some(season) = &self.current_season
{
return Scope {
season: SeasonScope::Season(season.clone()),
format: None,
};
}
Scope {
season: self.season.clone(),
format: self.format,
}
}
/// Requests the statistics from a worker (`start_job`: none is running), or shows none when no
/// Account is viewed.
fn recompute_in_background(
@@ -591,7 +484,10 @@ impl StatsPage {
let viewed = self.prepare_statistics(start_job, window, cx);
if let Some(puuid) = viewed {
if start_job {
let scope = self.statistics_scope();
let scope = Scope {
season: self.season.clone(),
format: self.format,
};
// A below-normal worker keeps hidden and visible windows responsive (rule #1).
spawn_statistics(
self.tracker.clone(),
@@ -619,7 +515,10 @@ impl StatsPage {
self.stats_error = None;
self.stored = None;
if let Some(puuid) = &viewed {
let scope = self.statistics_scope();
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}")),
@@ -631,12 +530,6 @@ impl StatsPage {
/// Shows `stats`: the Format choices, the charts and the table.
fn show_statistics(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.in_champ_select() {
self.update_picks();
self.refresh_table(cx);
cx.notify();
return;
}
let charts = self.stats.as_ref().map(|s| &s.charts);
let in_season = self.in_season();
self.charts
@@ -656,155 +549,19 @@ impl StatsPage {
cx.notify();
}
fn in_champ_select(&self) -> bool {
self.champ_select.is_some()
}
fn live_champ_select(&self) -> Option<&ChampSelect> {
self.champ_select.as_ref().map(|(_, pick)| pick)
}
fn update_picks(&mut self) {
let rows = self.stats.as_ref().map_or(&[][..], |s| s.rows.as_slice());
let pick = self.live_champ_select();
let current_labels = pick
.and_then(|s| s.current_row(rows))
.map(crate::champion_table::pick_labels)
.unwrap_or_default();
let mut anvil_labels: Vec<SharedString> = pick
.map(|s| {
s.anvil_champions
.iter()
.map(|id| {
let row = rows.iter().find(|r| r.champion.id == *id);
let mut label = champion_label(row, *id);
if let Some(state) = row.and_then(|r| r.state) {
label.push_str(" · ");
label.push_str(crate::text::state_label(Some(state)));
}
if !s.can_pick(*id) {
label.push_str(" · Indisponible");
}
SharedString::from(label)
})
.collect()
})
.unwrap_or_default();
anvil_labels.sort();
// Statistics are missing rather than absent when they are still on their way.
let loading = self.stats.is_none()
&& self.stats_error.is_none()
&& self.current_season.is_some()
&& self.status.updating.is_some();
let current_fallback = pick.map_or_else(SharedString::default, |s| match s.current {
Some(id) if current_labels.is_empty() => {
let row = rows.iter().find(|r| r.champion.id == id);
let note = if loading {
"Chargement des statistiques…"
} else {
"Statistiques indisponibles"
};
format!("{} · {note}", champion_label(row, id)).into()
}
Some(_) => SharedString::default(),
None => "Aucun champion sélectionné".into(),
});
let champ_select_notice = match (&self.stats_error, self.stats.is_some()) {
(Some(error), _) => error.clone().into(),
(None, true) => SharedString::default(),
(None, false) if self.current_season.is_none() => "Aucune Saison en cours".into(),
(None, false) if self.status.updating.is_none() => "Compte indisponible".into(),
(None, false) => "Chargement des statistiques…".into(),
};
self.current_labels = current_labels;
self.anvil_labels = anvil_labels;
self.current_fallback = current_fallback;
self.champ_select_notice = champ_select_notice;
}
fn refresh_table(&mut self, cx: &mut Context<Self>) {
let rows = self.stats.iter().flat_map(|s| &s.rows);
let rows = rows
.filter(|row| match &self.champ_select {
Some((_, pick)) => pick.remaining(row),
None => self.filter.keeps(row) && self.search.matches(&row.champion),
})
.filter(|row| self.filter.keeps(row) && self.search.matches(&row.champion))
.cloned()
.collect();
let in_season = self.in_champ_select() || self.in_season();
let in_season = self.in_season();
self.table.update(cx, |table, cx| {
table.set_rows(rows, in_season);
cx.notify();
});
}
fn champ_select_view(&self, cx: &App) -> Div {
let border = cx.theme().border;
let page = div().v_flex().size_full().p_3().gap_3().child(
div()
.text_xl()
.font_weight(FontWeight::SEMIBOLD)
.child("Sélection des champions · Arena"),
);
page.child(match self.current_labels.split_first() {
Some((name, labels)) => div()
.h_flex()
.items_center()
.flex_wrap()
.gap_x_4()
.gap_y_1()
.child(div().font_weight(FontWeight::SEMIBOLD).child(name.clone()))
.children(
labels
.iter()
.cloned()
.map(|label| div().text_sm().child(label)),
),
None => div().child(self.current_fallback.clone()),
})
.child(
div()
.v_flex()
.gap_2()
.p_3()
.border_1()
.border_color(border)
.rounded_md()
.child(
div()
.font_weight(FontWeight::SEMIBOLD)
.child("Champions de l'Enclume"),
)
.child(
div()
.h_flex()
.flex_wrap()
.gap_x_4()
.gap_y_1()
.children(
self.anvil_labels
.iter()
.cloned()
.map(|name| div().child(name)),
)
.when(self.anvil_labels.is_empty(), |row| {
row.child("Aucun champion de l'Enclume communiqué par le client")
}),
),
)
.child(
div()
.font_weight(FontWeight::SEMIBOLD)
.child("Champions disponibles à valider"),
)
.when(self.stats.is_none(), |page| {
page.child(self.champ_select_notice.clone())
})
.when(self.stats.is_some(), |page| {
page.child(div().flex_1().min_h_0().child(self.table.clone()))
})
}
/// One line each, the most important first; the stored data stays visible under all.
fn banners(&self) -> Vec<AnyElement> {
let mut banners = Vec::new();
@@ -839,11 +596,6 @@ impl StatsPage {
}
}
/// The champion's name, or the client's id when the catalog does not know it.
fn champion_label(row: Option<&ChampionRow>, id: u32) -> String {
row.map_or_else(|| format!("Champion {id}"), |row| row.champion.name.clone())
}
fn tile(
label: &'static str,
value: String,
@@ -1110,9 +862,6 @@ impl Render for StatsPage {
let theme = cx.theme();
(theme.border, theme.muted_foreground)
};
if self.in_champ_select() {
return self.champ_select_view(cx);
}
let options = filters(self.in_season());
let selected = options.iter().position(|(_, f)| *f == self.filter);
let challenge = self.stats.as_ref().and_then(|s| s.challenge.as_ref());
@@ -1126,8 +875,8 @@ impl Render for StatsPage {
.p_3()
.when(shown("header"), |page| {
page.child(
// The selectors give way first (down to their minimum width), then the status
// wraps onto a second line: nothing is ever clipped.
// 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()
@@ -1169,13 +918,29 @@ impl Render for StatsPage {
),
)
.child(
div().h_flex().items_center().gap_3().flex_shrink_0().child(
div()
.text_sm()
.whitespace_nowrap()
.text_color(muted)
.child(status_line),
),
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)),
)),
),
)
})
@@ -1226,14 +991,13 @@ impl Render for StatsPage {
#[cfg(test)]
mod tests {
use std::cell::{Cell, RefCell};
use std::cell::Cell;
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use arena_tracker_core::{
Account, Champion, ChampionRow, ChampionState, Charts, Format, MatchHistorySource, RiotApi,
SourceError, StateFilter, Statistics, Tracker,
Champion, ChampionRow, ChampionState, Charts, RiotApi, StateFilter, Statistics, Tracker,
};
use gpui_kit::base::async_util::unbounded;
use gpui_kit::{
@@ -1245,23 +1009,15 @@ mod tests {
use crate::champion_table::tests::row;
fn open_page(cx: &mut TestAppContext) -> (Entity<StatsPage>, VisualTestContext) {
open_page_with_tracker(
cx,
cx.update(gpui_kit::init);
let tracker = Arc::new(
Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(Vec::new()),
)
}
fn open_page_with_tracker(
cx: &mut TestAppContext,
tracker: Tracker,
) -> (Entity<StatsPage>, VisualTestContext) {
cx.update(gpui_kit::init);
let tracker = Arc::new(tracker);
);
let (window, page) = cx.update(|cx| {
let (tx, rx) = unbounded();
let bounds = Bounds {
@@ -1280,183 +1036,6 @@ mod tests {
(page, VisualTestContext::from_window(window, cx))
}
struct RefreshHistory;
impl MatchHistorySource for RefreshHistory {
fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result<Account, SourceError> {
Ok(Account {
puuid: game_name.into(),
game_name: game_name.into(),
tag_line: tag_line.into(),
})
}
fn match_ids(
&self,
puuid: &str,
queue_id: u32,
start: usize,
_: usize,
_: Option<i64>,
) -> Result<Vec<String>, SourceError> {
Ok(if puuid == "Alice" && queue_id == 1750 && start == 0 {
vec!["EUW1_9000000006".into()]
} else {
Vec::new()
})
}
fn fetch_match(&self, _: &str) -> Result<String, SourceError> {
Ok(
include_str!("../../core/tests/fixtures/riot/match_1750_EUW1_9000000006.json")
.replace("fixture-puuid-self", "Alice"),
)
}
}
/// A page on Alice's 3x6 statistics with the Format filter set, whose refresh worker meets Bob
/// (the client adopted another Account) before the UI does.
async fn refresh_towards_bob(cx: &mut TestAppContext, pin_alice: bool) -> Entity<StatsPage> {
cx.executor().allow_parking();
let tracker = Tracker::open(Path::new(":memory:"), Box::new(RefreshHistory))
.unwrap()
.with_seasons(Vec::new());
tracker.sync("Alice#EUW", &mut |_| {}).unwrap();
let (page, mut window) = open_page_with_tracker(cx, tracker);
window.update(|window, cx| {
page.update(cx, |page, cx| {
assert_eq!(page.viewed().unwrap().puuid, "Alice");
assert_eq!(page.stats.as_ref().unwrap().formats, [Format::Arena3x6]);
if pin_alice {
page.pinned = Some("Alice".into());
}
page.format = Some(Format::Arena3x6);
page.recompute(window, cx);
page.tracker.follow_client(0, Some("Bob#EUW"), &mut |_| {});
page.request_refresh(cx);
});
});
cx.condition(&page, |page, _| !page.busy()).await;
page
}
#[gpui::test]
async fn a_refresh_keeps_following_the_account_being_updated(cx: &mut TestAppContext) {
let page = refresh_towards_bob(cx, false).await;
page.read_with(cx, |page, _| {
assert_eq!(page.status.updating.as_ref().unwrap().puuid, "Bob");
assert_eq!(page.pinned, None);
assert_eq!(page.viewed().unwrap().puuid, "Bob");
// Another Account may not have played the Format: the filter is dropped
// (`prepare_statistics`), whatever the refresh.
assert_eq!(page.format, None);
});
}
#[gpui::test]
async fn a_refresh_keeps_a_pinned_account_and_format(cx: &mut TestAppContext) {
let page = refresh_towards_bob(cx, true).await;
page.read_with(cx, |page, _| {
assert_eq!(page.status.updating.as_ref().unwrap().puuid, "Bob");
assert_eq!(page.pinned.as_deref(), Some("Alice"));
assert_eq!(page.viewed().unwrap().puuid, "Alice");
assert_eq!(page.format, Some(Format::Arena3x6));
});
}
#[gpui::test]
async fn champ_select_uses_the_signed_in_accounts_challenge_and_restores_the_pinned_page(
cx: &mut TestAppContext,
) {
use crate::worker::Msg;
use arena_tracker_core::{ChampSelect, SeasonScope};
cx.executor().allow_parking();
let tracker = Tracker::open(Path::new(":memory:"), Box::new(RefreshHistory)).unwrap();
tracker.sync("Bob#EUW", &mut |_| {}).unwrap();
tracker.follow_client(0, Some("Alice#EUW"), &mut |_| {});
let (page, mut window) = open_page_with_tracker(cx, tracker);
let pick = ChampSelect::new(Some(39), [39].into(), vec![39]);
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.pinned = Some("Bob".into());
p.season = SeasonScope::AllSeasons;
p.filter = StateFilter::NeverPlayed;
p.reload(w, cx);
assert!(p.stats.as_ref().unwrap().rows.is_empty());
p.apply(Msg::ChampSelect(Some(("Alice#EUW".into(), pick))), w, cx);
})
});
cx.condition(&page, |p, _| !p.current_labels.is_empty())
.await;
page.read_with(cx, |p, cx| {
assert_eq!(p.current_labels[0].as_ref(), "Irelia");
assert!(
p.current_labels
.iter()
.any(|l| l.starts_with("Tentatives · 1"))
);
assert_eq!(p.anvil_labels.len(), 1);
assert!(p.anvil_labels[0].starts_with("Irelia · "));
assert_eq!(p.table.read(cx).names(), ["Irelia"]);
});
// A hover change touches neither the Account nor the pool: the panel must still update.
let next = ChampSelect::new(None, [39].into(), vec![39]);
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(Msg::ChampSelect(Some(("Alice#EUW".into(), next))), w, cx);
})
});
page.read_with(cx, |p, _| {
assert!(p.current_labels.is_empty());
assert_eq!(p.current_fallback.as_ref(), "Aucun champion sélectionné");
});
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(Msg::ChampSelect(None), w, cx);
})
});
cx.condition(&page, |p, _| p.stats.is_some()).await;
page.read_with(cx, |p, cx| {
assert_eq!(p.viewed().unwrap().puuid, "Bob");
assert_eq!(p.season, SeasonScope::AllSeasons);
assert_eq!(p.filter, StateFilter::NeverPlayed);
assert!(p.table.read(cx).names().is_empty());
});
}
#[gpui::test]
fn only_entering_a_champ_select_is_reported_as_an_entry(cx: &mut TestAppContext) {
use crate::worker::Msg;
use arena_tracker_core::ChampSelect;
let tracker = Tracker::open(Path::new(":memory:"), Box::new(RefreshHistory)).unwrap();
let (page, mut window) = open_page_with_tracker(cx, tracker);
let entered = Rc::new(RefCell::new(Vec::new()));
let _events = window.update(|_, cx| {
let entered = entered.clone();
cx.subscribe(
&page,
move |_, transition: &super::ChampSelectTransition, _| {
entered.borrow_mut().push(transition.entered)
},
)
});
let hovered = |current| ChampSelect::new(current, [39].into(), vec![39]);
for champ_select in [
None,
Some(("Alice#EUW".into(), hovered(Some(39)))),
Some(("Alice#EUW".into(), hovered(None))),
None,
None,
] {
window.update(|w, cx| {
page.update(cx, |p, cx| p.apply(Msg::ChampSelect(champ_select), w, cx))
});
}
assert_eq!(*entered.borrow(), [true, false]);
}
#[gpui::test]
fn typing_in_the_search_field_filters_the_table(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
+18 -1
View File
@@ -1,6 +1,6 @@
//! French display helpers shared by the page and the table.
use arena_tracker_core::{ChampionState, SyncProgress};
use arena_tracker_core::{Account, ChampionState, SyncProgress};
/// Fixed decimals with a decimal comma: `1,96`.
pub fn decimal(value: f64, digits: usize) -> String {
@@ -29,6 +29,10 @@ 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}")
@@ -84,6 +88,19 @@ mod tests {
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");
-174
View File
@@ -1,174 +0,0 @@
use gpui_kit::base::Button as BaseButton;
use gpui_kit::component::tooltip::Tooltip;
use gpui_kit::component::{ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use windows::Win32::{
Foundation::{LPARAM, WPARAM},
UI::WindowsAndMessaging::{PostMessageW, SC_CLOSE, SC_MAXIMIZE, SC_RESTORE, WM_SYSCOMMAND},
};
// Windows 11 caption metrics.
pub(crate) const BUTTON_WIDTH: Pixels = px(46.);
pub(crate) const BAR_HEIGHT: Pixels = px(32.);
// Six button widths plus room for the centered title, in narrow Windows Snap zones. A ready
// update adds a seventh in place of the title's left padding.
pub const MIN_WINDOW_SIZE: Size<Pixels> = size(px(380.), px(216.));
/// A flat button filling the bar's height, so that when the window is maximized the screen
/// edge (and for Fermer, the top-right corner) still hits it. Only hover and press show.
fn bar_button(id: &'static str, icon: IconName, label: &'static str, cx: &App) -> BaseButton {
BaseButton::new(id)
.w(BUTTON_WIDTH)
.h_full()
.flex_shrink_0()
// Always bordered, so the focus ring does not shift the icon.
.border_1()
.border_color(transparent_black())
.focus_visible(|style| style.border_color(cx.theme().ring))
.child(Icon::new(icon).small())
.accessibility_label(label)
.tooltip(move |window, cx| Tooltip::new(label).build(window, cx))
}
fn neutral(button: BaseButton, cx: &App) -> BaseButton {
let theme = cx.theme();
button
.hover(|style| style.bg(theme.accent).text_color(theme.accent_foreground))
.active(|style| style.bg(theme.secondary_active))
}
fn action_button(
id: &'static str,
icon: IconName,
label: &'static str,
enabled: bool,
cx: &App,
) -> BaseButton {
let button = bar_button(id, icon, label, cx).disabled(!enabled);
if enabled {
neutral(button, cx)
} else {
button.text_color(cx.theme().muted_foreground)
}
}
pub fn refresh_button(enabled: bool, cx: &App) -> BaseButton {
action_button("refresh", IconName::RefreshCw, "Actualiser", enabled, cx)
}
pub fn settings_button(enabled: bool, cx: &App) -> BaseButton {
action_button("settings", IconName::Settings, "Paramètres", enabled, cx)
}
/// Shown only while an update is ready, in green so it is noticed.
pub fn update_button(enabled: bool, cx: &App) -> BaseButton {
let button = action_button(
"update",
IconName::ArrowUp,
"Mise à jour prête",
enabled,
cx,
);
if enabled {
button.text_color(cx.theme().success)
} else {
button
}
}
/// `update` is the update button, while one is ready.
pub fn title_bar(
refresh: BaseButton,
settings: BaseButton,
update: Option<BaseButton>,
window: &Window,
cx: &App,
) -> impl IntoElement {
let theme = cx.theme();
let balanced = update.is_some();
let (icon, label) = if window.is_maximized() {
(IconName::WindowRestore, "Restaurer")
} else {
(IconName::WindowMaximize, "Agrandir")
};
div()
.h_flex()
.w_full()
.h(BAR_HEIGHT)
.flex_shrink_0()
.bg(theme.title_bar)
.border_b_1()
.border_color(theme.title_bar_border)
.child(refresh)
.child(settings)
.children(update)
.child(
div()
.h_flex()
.h_full()
.flex_1()
.min_w_0()
// Without the update button, this padding balances the third button on the right.
.when(!balanced, |title| title.pl(BUTTON_WIDTH))
.justify_center()
.text_xs()
.window_control_area(WindowControlArea::Drag)
.child(Text::new("window-title".into(), "Arena Tracker".into())),
)
.child(
neutral(
bar_button("minimize", IconName::WindowMinimize, "Réduire", cx),
cx,
)
.on_click(|_, window, _| window.minimize_window()),
)
.child(
neutral(bar_button("maximize", icon, label, cx), cx)
.window_control_area(WindowControlArea::Max)
.on_click(|event, window, _| {
// GPUI's native hit target handles mouse clicks and Snap Layouts.
if !matches!(event, ClickEvent::Mouse(_)) {
toggle_maximize(window);
}
})
.on_a11y_action(AccessibleAction::Click, |_, window, _| {
toggle_maximize(window);
}),
)
.child(
// No window_control_area: the click stays in Rust and SC_CLOSE keeps Alt+F4
// semantics. Enter, Space and the accessibility Click (a synthesized mouse
// click) all reach on_click.
bar_button("close", IconName::WindowClose, "Fermer", cx)
// Windows' own close colours: the theme's danger pair is meant for text and
// gives a red-on-red icon in the dark theme.
.hover(|style| style.bg(rgb(0xC42B1C)).text_color(white()))
.active(|style| style.bg(rgba(0xC42B1CE6)).text_color(white()))
.on_click(|_, window, _| window_command(window, SC_CLOSE)),
)
}
fn toggle_maximize(window: &Window) {
let command = if window.is_maximized() {
SC_RESTORE
} else {
SC_MAXIMIZE
};
window_command(window, command);
}
fn window_command(window: &Window, command: u32) {
if let Some(hwnd) = crate::tray::window_hwnd(window) {
// Post so the native command runs after GPUI finishes dispatching this click.
let _ = unsafe {
PostMessageW(
Some(hwnd),
WM_SYSCOMMAND,
WPARAM(command as usize),
LPARAM(0),
)
};
}
}
+33 -127
View File
@@ -5,7 +5,6 @@ use std::{
rc::{Rc, Weak},
};
use gpui_kit::base::async_util::Sender;
use gpui_kit::{App, PromptLevel, Subscription, Window};
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
use windows::Win32::{
@@ -13,57 +12,38 @@ use windows::Win32::{
System::LibraryLoader::GetModuleHandleW,
UI::{
Shell::{
DefSubclassProc, GetWindowSubclass, NIF_ICON, NIF_INFO, NIF_MESSAGE, NIF_SHOWTIP,
NIF_TIP, NIIF_INFO, NIM_ADD, NIM_DELETE, NIM_MODIFY, NIM_SETFOCUS, NIM_SETVERSION,
NIN_SELECT, NOTIFYICON_VERSION_4, NOTIFYICONDATAW, NOTIFYICONIDENTIFIER,
RemoveWindowSubclass, SetWindowSubclass, Shell_NotifyIconGetRect, Shell_NotifyIconW,
DefSubclassProc, NIF_ICON, NIF_MESSAGE, NIF_SHOWTIP, NIF_TIP, NIM_ADD, NIM_DELETE,
NIM_SETFOCUS, NIM_SETVERSION, NIN_SELECT, NOTIFYICON_VERSION_4, NOTIFYICONDATAW,
NOTIFYICONIDENTIFIER, RemoveWindowSubclass, SetWindowSubclass, Shell_NotifyIconGetRect,
Shell_NotifyIconW,
},
WindowsAndMessaging::*,
},
};
use windows::core::{PCWSTR, w};
const TRAY_SUBCLASS: usize = 0;
pub(crate) const TRAY_MESSAGE: u32 = WM_APP + 1;
const TRAY_MESSAGE: u32 = WM_APP + 1;
const ICON_ID: u32 = 1;
const OPEN: u32 = 1;
const QUIT: u32 = 2;
const NIN_KEYSELECT: u32 = NIN_SELECT | 1;
pub const UNAVAILABLE: &str =
"La zone de notification est indisponible. La fenêtre reste accessible.";
const NOTICE_TITLE: &str = "Arena Tracker reste ouvert";
const NOTICE_TEXT: &str = "L’application continue dans la zone de notification. Cliquez sur \
son icône pour la rouvrir, ou faites un clic droit pour la quitter.";
pub(crate) fn window_hwnd(window: &Window) -> Option<HWND> {
let RawWindowHandle::Win32(handle) = HasWindowHandle::window_handle(window).ok()?.as_raw()
else {
return None;
};
Some(HWND(handle.hwnd.get() as _))
}
pub struct Tray {
hwnd: HWND,
taskbar_created: u32,
enabled: Cell<bool>,
hidden: Cell<bool>,
/// Until the one-time notice is shown: told when it is, so that it can be recorded.
notice: Cell<Option<Sender<()>>>,
_quit: Subscription,
}
impl Tray {
pub fn install_saved(
window: &mut Window,
enabled: bool,
notice: Option<Sender<()>>,
cx: &mut App,
) -> Option<Rc<Self>> {
pub fn install_saved(window: &mut Window, enabled: bool, cx: &mut App) -> Option<Rc<Self>> {
if !enabled {
return None;
}
let tray = Self::install(window, notice, cx);
let tray = Self::install(window, cx);
if tray.is_none() {
window.defer(cx, |window, cx| {
drop(window.prompt(PromptLevel::Warning, UNAVAILABLE, None, &["OK"], cx));
@@ -72,8 +52,12 @@ impl Tray {
tray
}
pub fn install(window: &Window, notice: Option<Sender<()>>, cx: &App) -> Option<Rc<Self>> {
let hwnd = window_hwnd(window)?;
pub fn install(window: &Window, cx: &App) -> Option<Rc<Self>> {
let RawWindowHandle::Win32(handle) = HasWindowHandle::window_handle(window).ok()?.as_raw()
else {
return None;
};
let hwnd = HWND(handle.hwnd.get() as _);
let taskbar_created = unsafe { RegisterWindowMessageW(w!("TaskbarCreated")) };
if taskbar_created == 0 {
return None;
@@ -91,13 +75,12 @@ impl Tray {
taskbar_created,
enabled: Cell::new(true),
hidden: Cell::new(false),
notice: Cell::new(notice),
_quit: quit,
}
});
// The subclass owns one reference until WM_NCDESTROY. This window belongs to the UI thread.
let data = Rc::into_raw(tray.clone());
if !unsafe { SetWindowSubclass(hwnd, Some(window_proc), TRAY_SUBCLASS, data as usize) }
if !unsafe { SetWindowSubclass(hwnd, Some(window_proc), data as usize, data as usize) }
.as_bool()
{
drop(unsafe { Rc::from_raw(data) });
@@ -109,7 +92,7 @@ impl Tray {
pub fn uninstall(self: Rc<Self>) {
self.enabled.set(false);
let data = Rc::as_ptr(&self);
if unsafe { RemoveWindowSubclass(self.hwnd, Some(window_proc), TRAY_SUBCLASS) }.as_bool() {
if unsafe { RemoveWindowSubclass(self.hwnd, Some(window_proc), data as usize) }.as_bool() {
drop(unsafe { Rc::from_raw(data) });
}
}
@@ -135,7 +118,11 @@ impl Tray {
hIcon: icon,
..self.icon_data()
};
fill(&mut data.szTip, "Arena Tracker");
let mut tip = [0; 128];
for (unit, letter) in tip.iter_mut().zip("Arena Tracker".encode_utf16()) {
*unit = letter;
}
data.szTip = tip;
if !Shell_NotifyIconW(NIM_ADD, &data).as_bool() {
return false;
}
@@ -148,26 +135,6 @@ impl Tray {
}
}
/// Says once, as a Windows notification, that closing kept the app running here.
fn show_notice(&self) {
let Some(shown) = self.notice.take() else {
return;
};
let mut data = NOTIFYICONDATAW {
uFlags: NIF_INFO,
dwInfoFlags: NIIF_INFO,
..self.icon_data()
};
fill(&mut data.szInfoTitle, NOTICE_TITLE);
fill(&mut data.szInfo, NOTICE_TEXT);
if unsafe { Shell_NotifyIconW(NIM_MODIFY, &data) }.as_bool() {
// Recorded by the settings form, outside this window procedure.
let _ = shown.try_send(());
} else {
self.notice.set(Some(shown));
}
}
fn remove_icon(&self) {
if self.hidden.replace(false) {
let _ = unsafe { Shell_NotifyIconW(NIM_DELETE, &self.icon_data()) };
@@ -176,7 +143,15 @@ impl Tray {
fn open(&self) {
self.remove_icon();
foreground(self.hwnd);
unsafe {
let command = if IsIconic(self.hwnd).as_bool() {
SW_RESTORE
} else {
SW_SHOW
};
let _ = ShowWindow(self.hwnd, command);
let _ = SetForegroundWindow(self.hwnd);
}
}
fn report_unavailable(&self) {
@@ -245,77 +220,6 @@ impl Tray {
}
}
/// Copies `text` into a fixed Win32 string field, truncated, always ending with a NUL.
fn fill(field: &mut [u16], text: &str) {
let room = field.len() - 1;
for (unit, letter) in field[..room].iter_mut().zip(text.encode_utf16()) {
*unit = letter;
}
}
/// The window's tray, while it is installed.
fn installed_tray(hwnd: HWND) -> Option<Rc<Tray>> {
let mut data = 0;
unsafe { GetWindowSubclass(hwnd, Some(window_proc), TRAY_SUBCLASS, Some(&mut data)) }
.as_bool()
.then(|| unsafe { retain(data as *const Tray) })
}
pub fn reopen(hwnd: HWND) {
match installed_tray(hwnd) {
Some(tray) => tray.open(),
None => foreground(hwnd),
}
}
/// Brings a minimized window, or one hidden in the notification area, back above the other
/// windows while the foreground app keeps the keyboard. A window already shown is left alone.
pub fn reveal(hwnd: HWND) {
unsafe {
let iconic = IsIconic(hwnd).as_bool();
if IsWindowVisible(hwnd).as_bool() && !iconic {
return;
}
if let Some(tray) = installed_tray(hwnd) {
tray.remove_icon();
}
if iconic {
// shortcut: a window minimized from maximized may come back at its normal size, as no
// show command maximizes without activating; revisit if the Windows check shows it.
let _ = ShowWindow(hwnd, SW_SHOWNOACTIVATE);
}
let _ = SetWindowPos(
hwnd,
Some(HWND_TOP),
0,
0,
0,
0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW,
);
}
}
/// A native call can destroy the window and release the subclass's reference, so take our own.
unsafe fn retain(data: *const Tray) -> Rc<Tray> {
unsafe {
Rc::increment_strong_count(data);
Rc::from_raw(data)
}
}
fn foreground(hwnd: HWND) {
unsafe {
let command = if IsIconic(hwnd).as_bool() {
SW_RESTORE
} else {
SW_SHOW
};
let _ = ShowWindow(hwnd, command);
let _ = SetForegroundWindow(hwnd);
}
}
unsafe extern "system" fn window_proc(
hwnd: HWND,
message: u32,
@@ -335,7 +239,10 @@ unsafe extern "system" fn window_proc(
{
return unsafe { DefSubclassProc(hwnd, message, wparam, lparam) };
}
let tray = unsafe { retain(data) };
let tray = unsafe {
Rc::increment_strong_count(data);
Rc::from_raw(data)
};
match message {
WM_CLOSE if tray.enabled.get() => {
@@ -343,7 +250,6 @@ unsafe extern "system" fn window_proc(
if tray.add_icon() {
tray.hidden.set(true);
let _ = unsafe { ShowWindow(hwnd, SW_HIDE) };
tray.show_notice();
} else {
tray.report_unavailable();
}
+25 -114
View File
@@ -1,31 +1,21 @@
//! Background threads: following the game client, refreshing, computing statistics and
//! downloading updates. They talk to the page through `Msg`, and to the settings through
//! `UpdateChecked`.
//! Background threads: following the game client, refreshing and computing statistics.
//! They talk to the page through `Msg`.
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
use arena_tracker_core::{
ChampSelect, ClientEvent, Scope, Statistics, Status, SyncProgress, Tracker, UpdateChannel,
};
use arena_tracker_core::{Scope, Statistics, Status, SyncProgress, Tracker};
use gpui_kit::base::async_util::Sender;
/// The signed-in Riot ID and its pick, or none outside an Arena champ select.
pub type LiveChampSelect = Option<(String, ChampSelect)>;
pub enum Msg {
ChampSelect(LiveChampSelect),
/// 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,
},
Round { status: Status, reload: bool },
/// A refresh ended.
Refreshed(Status),
/// Statistics for a requested scope were computed.
@@ -36,8 +26,6 @@ pub enum Msg {
},
/// A worker thread panicked.
Crashed,
/// The refresh worker panicked.
RefreshCrashed,
}
/// At most one job at a time. A request made while one runs is served once, when it reports back.
@@ -104,120 +92,46 @@ fn lower_priority() {
}
/// Runs `body` on its own thread; a panic is reported instead of leaving the page waiting.
fn spawn_guarded<T: Send + 'static>(
tx: Sender<T>,
on_panic: T,
body: impl FnOnce(&Sender<T>) + Send + 'static,
) {
fn spawn_guarded(tx: Sender<Msg>, body: impl FnOnce(&Sender<Msg>) + Send + 'static) {
thread::spawn(move || {
lower_priority();
if catch_unwind(AssertUnwindSafe(|| body(&tx))).is_err() {
let _ = tx.try_send(on_panic);
let _ = tx.try_send(Msg::Crashed);
}
});
}
/// Keeps the active Account up to date for as long as the app runs: event-driven follower rounds
/// and a live champ select subscription. Each wake reads the client once and shares that read with
/// both. `fallback_riot_id` is the configured Riot ID.
/// 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(), Msg::Crashed, move |tx| {
spawn_guarded(tx.clone(), move |tx| {
let _ = champions.refresh_champions();
let _ = tx.try_send(Msg::Champions);
});
// Coalesce history updates while Riot is busy; the WebSocket keeps delivering live picks.
let (wake, rounds) = std::sync::mpsc::sync_channel(1);
let latest = Arc::new(std::sync::Mutex::new(None));
let history = tracker.clone();
let history_latest = latest.clone();
spawn_guarded(tx.clone(), Msg::Crashed, move |tx| {
spawn_guarded(tx, move |tx| {
let fallback = Some(fallback_riot_id.as_str()).filter(|id| !id.trim().is_empty());
let mut first = true;
for () in rounds {
// Another wake landed while this one's round ran: its read is newer and already
// queued, so this round has nothing of its own to do.
let Some(snapshot) = history_latest.lock().unwrap().take() else {
continue;
};
let mut progress = |progress| {
loop {
let changed = tracker.follow_client(now_ms(), fallback, &mut |progress| {
let _ = tx.try_send(Msg::Progress(progress));
};
let changed = history.follow_client_with(now_ms(), fallback, &snapshot, &mut progress);
if tx
.try_send(Msg::Round {
status: history.status(),
reload: changed || first,
})
.is_err()
{
break;
}
});
let status = tracker.status();
let _ = tx.try_send(Msg::Round {
status,
reload: changed || first,
});
first = false;
tracker.wait_for_client();
}
});
spawn_guarded(tx, Msg::Crashed, move |tx| {
let mut previous = None;
let mut snapshot = tracker.client_snapshot();
let mut needs_snapshot = true;
while !tx.is_closed() {
// The follower round uses the same read as the live champ select: one gameflow
// request per wake, and none for a champ select event.
if needs_snapshot {
*latest.lock().unwrap() = Some(snapshot.clone());
if matches!(
wake.try_send(()),
Err(std::sync::mpsc::TrySendError::Disconnected(()))
) {
break;
}
}
match tracker.champ_select_with(&snapshot) {
Ok(champ_select) if champ_select != previous => {
if tx.try_send(Msg::ChampSelect(champ_select.clone())).is_err() {
break;
}
previous = champ_select;
}
Ok(_) => {}
// A failed read is not the champ select ending: keep what the page shows.
Err(_) => {}
}
// A champ select event costs no request once a read has answered: only a gameflow
// event, or a read that failed, needs a fresh one. The gameflow event that starts
// the champ select is that event.
needs_snapshot =
tracker.wait_for_client() == ClientEvent::Other || snapshot.gameflow.is_err();
if needs_snapshot {
snapshot = tracker.client_snapshot();
}
}
});
}
/// What an update check for `channel` kept ready: the version, if any.
pub struct UpdateChecked {
pub channel: UpdateChannel,
pub ready: Option<String>,
}
/// Downloads and authenticates the newest release of `channel`, as one below-normal thread.
pub fn spawn_update_check(channel: UpdateChannel, tx: Sender<UpdateChecked>) {
let crashed = UpdateChecked {
channel,
ready: None,
};
spawn_guarded(tx, crashed, move |tx| {
let ready = crate::release::download_update(channel);
let _ = tx.try_send(UpdateChecked { channel, ready });
});
}
/// 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, Msg::RefreshCrashed, move |tx| {
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.try_send(Msg::Progress(progress));
@@ -234,7 +148,7 @@ pub fn spawn_statistics(
generation: u64,
tx: Sender<Msg>,
) {
spawn_guarded(tx, Msg::Crashed, move |tx| {
spawn_guarded(tx, move |tx| {
// A panic is reported as this job's result, not as `Crashed`: the page's statistics job
// must end with a result whatever happens, and a crash banner is for the other workers.
let (stats, stored) = catch_unwind(AssertUnwindSafe(|| {
@@ -269,16 +183,13 @@ mod tests {
#[test]
fn guarded_workers_deliver_messages_and_report_panics() {
let (tx, rx) = unbounded();
spawn_guarded(tx.clone(), Msg::Crashed, |tx| {
spawn_guarded(tx.clone(), |tx| {
let _ = tx.try_send(Msg::Champions);
});
assert!(matches!(gpui_kit::block_on(rx.recv()), Ok(Msg::Champions)));
spawn_guarded(tx, Msg::RefreshCrashed, |_| panic!("worker panic"));
assert!(matches!(
gpui_kit::block_on(rx.recv()),
Ok(Msg::RefreshCrashed)
));
spawn_guarded(tx, |_| panic!("worker panic"));
assert!(matches!(gpui_kit::block_on(rx.recv()), Ok(Msg::Crashed)));
assert!(gpui_kit::block_on(rx.recv()).is_err());
}
@@ -362,7 +273,7 @@ mod tests {
fn guarded_threads_run_below_normal_priority() {
let (tx, _rx) = unbounded();
let (priority_tx, priority_rx) = std::sync::mpsc::channel();
spawn_guarded(tx, Msg::Crashed, move |_| {
spawn_guarded(tx, move |_| {
let priority = unsafe { GetThreadPriority(GetCurrentThread()) };
priority_tx.send(priority).unwrap();
});
-1
View File
@@ -6,7 +6,6 @@ version.workspace = true
[dependencies]
base64 = { version = "0.23.1", default-features = false, features = ["std"] }
ring = "0.17.14"
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"] }
-372
View File
@@ -1,372 +0,0 @@
//! The local player's pick and the champions offered during an Arena champ select.
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use serde_json::Value;
use crate::client::Gameflow;
use crate::league_client::{lock, parse};
use crate::{ChampionRow, ChampionState, ClientError};
pub(crate) const PICKABLE_EVENT: &str = "OnJsonApiEvent_lol-champ-select_v1_pickable-champion-ids";
pub(crate) const DISABLED_EVENT: &str = "OnJsonApiEvent_lol-champ-select_v1_disabled-champion-ids";
pub(crate) const ANVIL_EVENT: &str =
"OnJsonApiEvent_lol-lobby-team-builder_champ-select_v1_crowd-favorite-champion-list";
/// The local player's live pick and the champions they can still pick.
#[derive(Clone, Debug)]
pub struct ChampSelect {
pub current: Option<u32>,
/// The five anvil champions; empty when the client reports none. The client calls them
/// crowd favorites.
pub anvil_champions: Vec<u32>,
/// The champions the champ select offers, before its bans and the other players' picks.
/// Shared with the client's cache instead of cloned on every session event.
pickable: Arc<HashSet<u32>>,
/// Banned or taken by another player in this champ select.
excluded: HashSet<u32>,
}
impl PartialEq for ChampSelect {
fn eq(&self, other: &Self) -> bool {
self.current == other.current
&& self.anvil_champions == other.anvil_champions
&& self.same_pickable(other)
}
}
fn champion_id(value: &Value) -> Option<u32> {
u32::try_from(value.as_u64()?).ok().filter(|id| *id != 0)
}
fn array(value: &Value) -> Result<&[Value], ClientError> {
value
.as_array()
.map(Vec::as_slice)
.ok_or_else(|| ClientError::Other("Liste de champions illisible".into()))
}
fn ids(body: &str) -> Result<HashSet<u32>, ClientError> {
let value = parse(body)?;
let ids =
ids_in(&value).ok_or_else(|| ClientError::Other("Liste de champions illisible".into()))?;
Ok(ids.into_iter().collect())
}
/// The champion ids of a list, from a body or from an event's data.
fn ids_in(value: &Value) -> Option<Vec<u32>> {
value
.as_array()
.map(|ids| ids.iter().filter_map(champion_id).collect())
}
impl ChampSelect {
/// A champ select with nothing banned or taken, for callers with a ready pool.
pub fn new(current: Option<u32>, pickable: HashSet<u32>, anvil_champions: Vec<u32>) -> Self {
Self {
current,
anvil_champions,
pickable: Arc::new(pickable),
excluded: HashSet::new(),
}
}
fn from_session(
session: &Value,
pickable: Arc<HashSet<u32>>,
anvil_champions: Vec<u32>,
) -> Result<Self, ClientError> {
let local = session["localPlayerCellId"]
.as_i64()
.ok_or(ClientError::Absent)?;
let team = array(&session["myTeam"])?;
let me = team
.iter()
.find(|p| p["cellId"] == local)
.ok_or(ClientError::Absent)?;
let current =
champion_id(&me["championId"]).or_else(|| champion_id(&me["championPickIntent"]));
let mut excluded = HashSet::new();
for player in team
.iter()
.filter(|p| p["cellId"] != local && p["team"] == me["team"])
{
if let Some(id) = champion_id(&player["championId"]) {
excluded.insert(id);
}
}
// In Arena the confirmed bans were in actions while both team ban lists were empty.
for turn in array(&session["actions"])? {
for action in array(turn)? {
if action["type"] == "ban"
&& action["completed"] == true
&& let Some(id) = champion_id(&action["championId"])
{
excluded.insert(id);
}
}
}
for key in ["myTeamBans", "theirTeamBans"] {
if let Some(bans) = session["bans"][key].as_array() {
excluded.extend(bans.iter().filter_map(champion_id));
}
}
Ok(Self {
current,
anvil_champions,
pickable,
excluded,
})
}
pub fn current_row<'a>(&self, rows: &'a [ChampionRow]) -> Option<&'a ChampionRow> {
let id = self.current?;
rows.iter().find(|r| r.champion.id == id)
}
/// Whether the local player can still pick this champion. Their own pick always stays
/// pickable.
pub fn can_pick(&self, id: u32) -> bool {
self.current == Some(id) || (self.pickable.contains(&id) && !self.excluded.contains(&id))
}
/// Whether both champ selects offer the same champions, whatever the current pick. The
/// shared set makes the common case a pointer comparison.
pub fn same_pickable(&self, other: &Self) -> bool {
(Arc::ptr_eq(&self.pickable, &other.pickable) || self.pickable == other.pickable)
&& self.excluded == other.excluded
}
/// A champion still to complete in the Challenge and pickable in this champ select. The
/// player's own hovered or locked champion stays in the list while not Completed: they can
/// pick it.
pub fn remaining(&self, row: &ChampionRow) -> bool {
row.state.is_some_and(|s| s != ChampionState::Completed) && self.can_pick(row.champion.id)
}
}
/// The live champ select, read the one way both the real client and the tests read it: the
/// session the client sent as an event, else its answer to a session request, and the champion
/// lists read once per champ select.
#[derive(Default)]
pub struct ChampSelectReader {
lists: Mutex<Option<ChampSelectLists>>,
/// The latest session the client sent as an event, taken by the next read.
session: Mutex<Option<Value>>,
}
impl ChampSelectReader {
/// Forgets the champ select: the next read belongs to a new one.
pub(crate) fn reset(&self) {
*lock(&self.lists) = None;
*lock(&self.session) = None;
}
/// Follows a gameflow read: anything but an Arena champ select ends the cached one, whose
/// lists must not leak into the next.
pub fn reset_unless_arena_champ_select(&self, flow: &Gameflow) {
if !flow.is_arena_champ_select() {
self.reset();
}
}
/// Keeps the session the client sent as an event for the next read, which then needs no
/// session request.
pub fn set_session(&self, session: Value) {
if session.is_object() {
*lock(&self.session) = Some(session);
}
}
/// Reads the live champ select. `session` and `lists` make the requests; they run only when
/// the event session or the champion lists are missing, and never under a lock.
pub fn read(
&self,
session: impl FnOnce() -> Result<String, ClientError>,
lists: impl FnOnce() -> Result<(String, String, Option<String>), ClientError>,
) -> Result<ChampSelect, ClientError> {
let session = match lock(&self.session).take() {
Some(session) => session,
None => parse(&session()?)?,
};
if lock(&self.lists).is_none() {
let (pickable, disabled, anvil) = lists()?;
let lists = ChampSelectLists::from_bodies(&pickable, &disabled, anvil.as_deref())?;
*lock(&self.lists) = Some(lists);
}
let lists = lock(&self.lists);
let lists = lists.as_ref().expect("set just above");
ChampSelect::from_session(&session, lists.pickable(), lists.anvil().to_vec())
}
/// Applies the client's pickable list event.
pub(crate) fn set_pickable(&self, data: &Value) {
if let Some(lists) = lock(&self.lists).as_mut() {
lists.set_pickable(data);
}
}
/// Applies the client's disabled list event.
pub(crate) fn set_disabled(&self, data: &Value) {
if let Some(lists) = lock(&self.lists).as_mut() {
lists.set_disabled(data);
}
}
/// Applies the client's anvil champions event.
pub(crate) fn set_anvil(&self, data: &Value) {
if let Some(lists) = lock(&self.lists).as_mut() {
lists.set_anvil(data);
}
}
}
/// The champion lists of a champ select: read once, then updated from the client's events.
#[derive(Debug, Default)]
pub(crate) struct ChampSelectLists {
/// The client's pickable list, before the disabled champions are removed.
offered: HashSet<u32>,
disabled: HashSet<u32>,
anvil: Vec<u32>,
/// `offered` minus `disabled`, rebuilt only when either list changes.
pickable: Arc<HashSet<u32>>,
}
impl ChampSelectLists {
pub(crate) fn from_bodies(
pickable: &str,
disabled: &str,
anvil: Option<&str>,
) -> Result<Self, ClientError> {
let mut lists = Self {
offered: ids(pickable)?,
disabled: ids(disabled)?,
..Self::default()
};
if let Some(body) = anvil
&& let Ok(value) = parse(body)
&& let Some(ids) = ids_in(&value)
{
lists.anvil = ids;
}
lists.rebuild();
Ok(lists)
}
fn rebuild(&mut self) {
self.pickable = Arc::new(self.offered.difference(&self.disabled).copied().collect());
}
pub(crate) fn pickable(&self) -> Arc<HashSet<u32>> {
self.pickable.clone()
}
pub(crate) fn anvil(&self) -> &[u32] {
&self.anvil
}
fn set_pickable(&mut self, data: &Value) {
if let Some(ids) = ids_in(data) {
self.offered = ids.into_iter().collect();
self.rebuild();
}
}
fn set_disabled(&mut self, data: &Value) {
if let Some(ids) = ids_in(data) {
self.disabled = ids.into_iter().collect();
self.rebuild();
}
}
fn set_anvil(&mut self, data: &Value) {
if let Some(ids) = ids_in(data) {
self.anvil = ids;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn the_lists_change_only_for_the_events_that_concern_them() {
let mut lists = ChampSelectLists::from_bodies("[1,2,3]", "[3]", Some("[9,8]")).unwrap();
assert_eq!(&*lists.pickable(), &HashSet::from([1, 2]));
assert_eq!(lists.anvil(), [9, 8]);
// A Delete carries no data: it changes nothing.
lists.set_pickable(&Value::Null);
lists.set_anvil(&Value::Null);
assert_eq!(&*lists.pickable(), &HashSet::from([1, 2]));
assert_eq!(lists.anvil(), [9, 8]);
lists.set_pickable(&json!([1, 4]));
assert_eq!(&*lists.pickable(), &HashSet::from([1, 4]));
assert_eq!(lists.anvil(), [9, 8]);
lists.set_disabled(&json!([1]));
assert_eq!(&*lists.pickable(), &HashSet::from([4]));
lists.set_anvil(&json!([5, 6]));
assert_eq!(lists.anvil(), [5, 6]);
}
#[test]
fn the_anvil_champions_are_read_once_when_the_champ_select_starts() {
assert!(
ChampSelectLists::from_bodies("[]", "[]", None)
.unwrap()
.anvil()
.is_empty()
);
assert_eq!(
ChampSelectLists::from_bodies("[]", "[]", Some("[1,2]"))
.unwrap()
.anvil(),
[1, 2]
);
// A malformed anvil answer only loses the anvil list, not the pickable one.
let lists = ChampSelectLists::from_bodies("[7]", "[]", Some("not json")).unwrap();
assert_eq!(&*lists.pickable(), &HashSet::from([7]));
assert!(lists.anvil().is_empty());
}
#[test]
fn a_read_uses_the_session_of_an_event_and_reads_the_lists_once() {
let reader = ChampSelectReader::default();
let session = || {
Ok(
r#"{"localPlayerCellId":16,"myTeam":[{"cellId":16,"championId":0,
"championPickIntent":0}],"actions":[],
"bans":{"myTeamBans":[],"theirTeamBans":[]}}"#
.to_string(),
)
};
let lists = || {
Ok((
"[1,2]".to_string(),
"[]".to_string(),
Some("[9]".to_string()),
))
};
reader.read(session, lists).unwrap();
// A session event replaces the request; the lists stay cached.
reader.set_session(json!({
"localPlayerCellId": 16,
"myTeam": [{"cellId": 16, "championId": 2, "championPickIntent": 0}],
"actions": [],
"bans": {"myTeamBans": [], "theirTeamBans": []}
}));
let pick = reader
.read(
|| panic!("the event session must be used"),
|| panic!("the lists must stay cached"),
)
.unwrap();
assert_eq!(pick.current, Some(2));
}
}
+2 -115
View File
@@ -8,51 +8,8 @@ pub trait GameClientSource: Send + Sync {
/// 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>;
/// Reads the live Arena champ select after gameflow enters champ select.
fn champ_select(&self) -> Result<crate::ChampSelect, ClientError>;
/// Blocks until the client reports an event or `timeout` elapses, and says which kind it was.
fn wait_for_event(&self, timeout: Duration) -> ClientEvent;
}
/// What a wait saw: a champ select change, or anything else (gameflow, summoner, a timeout).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ClientEvent {
/// The champ select session or one of its champion lists changed.
ChampSelect,
/// Anything else.
#[default]
Other,
}
/// One read of the client, shared by the follower round and the live champ select: a wake makes
/// one gameflow request, not one per reader.
#[derive(Clone, Debug)]
pub struct ClientSnapshot {
pub signed_in: Result<(String, String), ClientError>,
pub gameflow: Result<Gameflow, ClientError>,
}
impl ClientSnapshot {
pub fn read(source: &dyn GameClientSource) -> Self {
let signed_in = source.signed_in();
// Nobody signed in means the login screen: no gameflow request. Carrying the error keeps
// `Absent` meaning "no champ select" and a transient failure keeping the one shown.
let gameflow = match &signed_in {
Ok(_) => source.gameflow(),
Err(error) => Err(error.clone()),
};
Self {
signed_in,
gameflow,
}
}
pub fn absent() -> Self {
Self {
signed_in: Err(ClientError::Absent),
gameflow: Err(ClientError::Absent),
}
}
/// Blocks until the client reports a change or `timeout` elapses.
fn wait_for_change(&self, timeout: Duration);
}
#[derive(Debug, Clone, PartialEq)]
@@ -92,68 +49,10 @@ pub struct Gameflow {
pub game_id: Option<u64>,
}
impl Gameflow {
/// The only time the live pick is shown.
pub fn is_arena_champ_select(&self) -> bool {
self.arena && self.phase == GamePhase::ChampSelect
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
/// A client whose sign-in and gameflow answers are fixed; counts the gameflow requests.
struct Source {
signed_in: Result<(String, String), ClientError>,
gameflow_calls: AtomicUsize,
}
impl GameClientSource for Source {
fn signed_in(&self) -> Result<(String, String), ClientError> {
self.signed_in.clone()
}
fn gameflow(&self) -> Result<Gameflow, ClientError> {
self.gameflow_calls.fetch_add(1, Ordering::SeqCst);
Ok(Gameflow::default())
}
fn official_progress(&self, _: &str) -> Result<Option<u32>, ClientError> {
Ok(None)
}
fn champ_select(&self) -> Result<crate::ChampSelect, ClientError> {
Err(ClientError::Absent)
}
fn wait_for_event(&self, _: Duration) -> ClientEvent {
ClientEvent::Other
}
}
#[test]
fn a_login_screen_makes_no_gameflow_request() {
let source = Source {
signed_in: Err(ClientError::Absent),
gameflow_calls: AtomicUsize::new(0),
};
let snapshot = ClientSnapshot::read(&source);
assert_eq!(snapshot.gameflow, Err(ClientError::Absent));
assert_eq!(source.gameflow_calls.load(Ordering::SeqCst), 0);
// A transient failure is carried, so a shown champ select stays.
let source = Source {
signed_in: Err(ClientError::Other("panne".into())),
gameflow_calls: AtomicUsize::new(0),
};
let snapshot = ClientSnapshot::read(&source);
assert_eq!(snapshot.gameflow, Err(ClientError::Other("panne".into())));
assert_eq!(source.gameflow_calls.load(Ordering::SeqCst), 0);
}
#[test]
fn client_phases_map_to_game_phases() {
for (name, phase) in [
@@ -176,16 +75,4 @@ mod tests {
assert_eq!(GamePhase::from_client(name), phase, "{name}");
}
}
#[test]
fn only_an_arena_champ_select_shows_the_live_pick() {
let flow = |phase, arena| Gameflow {
phase,
arena,
game_id: None,
};
assert!(flow(GamePhase::ChampSelect, true).is_arena_champ_select());
assert!(!flow(GamePhase::ChampSelect, false).is_arena_champ_select());
assert!(!flow(GamePhase::InGame, true).is_arena_champ_select());
}
}
-56
View File
@@ -13,9 +13,6 @@ pub struct Config {
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)]
@@ -27,9 +24,6 @@ pub struct Config {
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>,
}
impl Default for Preferences {
@@ -37,7 +31,6 @@ impl Default for Preferences {
Self {
close_to_tray: true,
theme: ThemePreference::System,
update_channel: None,
}
}
}
@@ -51,25 +44,6 @@ pub enum ThemePreference {
Dark,
}
/// 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()
}
@@ -92,7 +66,6 @@ impl Config {
riot_api_key: String::new(),
riot_id: String::new(),
region: default_region(),
tray_notice_shown: false,
preferences: Preferences::default(),
other: toml::Table::new(),
})
@@ -134,28 +107,8 @@ mod tests {
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);
}
#[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]
@@ -206,22 +159,14 @@ mod tests {
)
.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),
};
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!(
@@ -239,7 +184,6 @@ mod tests {
riot_api_key: "RGAPI-secret".into(),
riot_id: String::new(),
region: "europe".into(),
tray_notice_shown: false,
preferences: Preferences::default(),
other: toml::Table::new(),
};
-8
View File
@@ -40,9 +40,6 @@ pub enum Error {
InvalidRiotId(String),
Config(String),
UnknownSeason(String),
InvalidUpdate(String),
/// The version whose installation did not happen.
UpdateFailed(String),
}
impl fmt::Display for Error {
@@ -55,11 +52,6 @@ impl fmt::Display for Error {
}
Error::Config(msg) => write!(f, "Configuration invalide : {msg}"),
Error::UnknownSeason(name) => write!(f, "Saison inconnue : « {name} »."),
Error::InvalidUpdate(why) => write!(f, "Mise à jour refusée : {why}."),
Error::UpdateFailed(version) => write!(
f,
"La mise à jour vers la version {version} n’a pas pu être installée ; la version actuelle reste en place."
),
}
}
}
+25 -96
View File
@@ -5,7 +5,7 @@ use std::time::Duration;
use rusqlite::OptionalExtension;
use crate::client::{ClientEvent, ClientSnapshot, GameClientSource, GamePhase, Gameflow};
use crate::client::{GameClientSource, GamePhase, Gameflow};
use crate::error::{Error, SourceError};
use crate::model::{Account, SyncProgress, SyncReport};
use crate::seasons::Season;
@@ -129,21 +129,14 @@ pub(crate) struct Follow {
official_progress: ProgressCheck,
}
/// `gameName#tagLine`, the one place a Riot ID is built.
pub fn riot_id(game_name: &str, tag_line: &str) -> String {
format!("{game_name}#{tag_line}")
fn riot_id(account: &Account) -> String {
format!("{}#{}", account.game_name, account.tag_line)
}
/// Riot IDs differ in case only when they name the same Account.
pub fn same_riot_id(a: &str, b: &str) -> bool {
fn same_riot_id(a: &str, b: &str) -> bool {
a.to_lowercase() == b.to_lowercase()
}
/// `gameName#tagLine` of an Account, the one place an Account's Riot ID is built.
pub fn account_riot_id(account: &Account) -> String {
riot_id(&account.game_name, &account.tag_line)
}
impl Tracker {
/// Without a client, it is always absent.
pub fn with_client(mut self, client: Box<dyn GameClientSource>) -> Tracker {
@@ -198,40 +191,16 @@ impl Tracker {
now_ms: i64,
fallback_riot_id: Option<&str>,
on_progress: &mut dyn FnMut(SyncProgress),
) -> bool {
self.follow_client_with(
now_ms,
fallback_riot_id,
&self.client_snapshot(),
on_progress,
)
}
/// One read of the client for this wake; the follower round and the live champ select share
/// it.
pub fn client_snapshot(&self) -> ClientSnapshot {
match &self.client {
Some(client) => ClientSnapshot::read(client.as_ref()),
None => ClientSnapshot::absent(),
}
}
/// A follower round on a client read already made for this wake.
pub fn follow_client_with(
&self,
now_ms: i64,
fallback_riot_id: Option<&str>,
snapshot: &ClientSnapshot,
on_progress: &mut dyn FnMut(SyncProgress),
) -> bool {
let before = self.status();
let mut added = 0;
let signed_in = snapshot
.signed_in
.as_ref()
.ok()
.map(|(name, tag)| riot_id(name, tag));
let gameflow = snapshot.gameflow.as_ref().ok().cloned();
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()) {
@@ -318,7 +287,7 @@ impl Tracker {
.follow()
.updating
.as_ref()
.is_some_and(|a| same_riot_id(&account_riot_id(a), signed_in)) =>
.is_some_and(|a| same_riot_id(&riot_id(a), signed_in)) =>
{
client
.official_progress(&track)
@@ -334,47 +303,17 @@ impl Tracker {
self.status() != before || added > 0
}
/// The signed-in Riot ID and its live pick, from a client read already made for this wake.
/// `Err` means the read failed: keep what is shown. `Ok(None)` means no Arena champ select
/// is running.
pub fn champ_select_with(
&self,
snapshot: &ClientSnapshot,
) -> Result<Option<(String, crate::ChampSelect)>, crate::ClientError> {
let flow = match &snapshot.gameflow {
Ok(flow) => flow,
Err(crate::ClientError::Absent) => return Ok(None),
Err(error) => return Err(error.clone()),
};
if !flow.is_arena_champ_select() {
return Ok(None);
}
let (name, tag) = match &snapshot.signed_in {
Ok(id) => id,
Err(crate::ClientError::Absent) => return Ok(None),
Err(error) => return Err(error.clone()),
};
let Some(client) = &self.client else {
return Ok(None);
};
Ok(Some((riot_id(name, tag), client.champ_select()?)))
}
/// 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. The event says whether only the live
/// champ select needs another read.
pub fn wait_for_client(&self) -> ClientEvent {
/// 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_event(timeout),
None => {
thread::sleep(timeout);
ClientEvent::Other
}
Some(client) => client.wait_for_change(timeout),
None => thread::sleep(timeout),
}
}
@@ -390,7 +329,7 @@ impl Tracker {
};
let result = match (signed_in, updating) {
(Some(id), _) => self.adopt(&id, on_progress),
(None, Some(account)) => self.update(&account_riot_id(&account), 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)),
@@ -403,7 +342,7 @@ impl Tracker {
/// 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| account_riot_id(&a))
last.map(|a| riot_id(&a))
.or_else(|| self.follow().fallback.clone())
}
@@ -416,10 +355,10 @@ impl Tracker {
/// adds a Match ends the waits for the games the client gave no id for.
fn update(
&self,
account_id: &str,
riot_id: &str,
on_progress: &mut dyn FnMut(SyncProgress),
) -> Result<SyncReport, UpdateProblem> {
match self.sync(account_id, on_progress) {
match self.sync(riot_id, on_progress) {
Ok(report) => {
if report.added > 0 {
self.follow().pending.retain(|p| p.game_id.is_some());
@@ -434,15 +373,15 @@ impl Tracker {
/// active one is the stored Account with that Riot ID, if any: never the previous Account.
fn adopt(
&self,
account_id: &str,
riot_id: &str,
on_progress: &mut dyn FnMut(SyncProgress),
) -> Result<SyncReport, UpdateProblem> {
let result = self.update(account_id, on_progress);
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(&account_riot_id(a), account_id))
.find(|a| same_riot_id(&self::riot_id(a), riot_id))
}),
};
if let Some(account) = &account
@@ -452,7 +391,7 @@ impl Tracker {
}
let mut follow = self.follow();
follow.updating = account;
follow.adopted = result.is_ok().then(|| account_id.into());
follow.adopted = result.is_ok().then(|| riot_id.into());
follow.adopt_retry_after_ms = follow.adopt_retry_after_ms.filter(|_| result.is_err());
result
}
@@ -469,7 +408,7 @@ impl Tracker {
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(&account_riot_id(account), on_progress);
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) {
@@ -529,16 +468,6 @@ mod tests {
use std::collections::HashSet;
use std::time::Duration;
#[test]
fn account_riot_ids_join_name_and_tag() {
let account = Account {
puuid: "p".into(),
game_name: "Joueur".into(),
tag_line: "EUW".into(),
};
assert_eq!(account_riot_id(&account), "Joueur#EUW");
}
#[test]
fn every_problem_has_its_own_message() {
let messages: HashSet<String> = [
+13 -257
View File
@@ -17,8 +17,7 @@ use tungstenite::{Connector, Message, WebSocket, client_tls_with_config};
use ureq::Agent;
use ureq::tls::{Certificate, RootCerts, TlsConfig};
use crate::champ_select::{ANVIL_EVENT, ChampSelectReader, DISABLED_EVENT, PICKABLE_EVENT};
use crate::client::{ClientError, ClientEvent, GameClientSource, GamePhase, Gameflow};
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
@@ -28,19 +27,10 @@ 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 SESSION: &str = "/lol-champ-select/v1/session";
const PICKABLE: &str = "/lol-champ-select/v1/pickable-champion-ids";
const DISABLED: &str = "/lol-champ-select/v1/disabled-champion-ids";
/// The client calls the five anvil champions "crowd favorites" and spells it "favorte" here.
const ANVIL_CHAMPIONS: &str = "/lol-lobby-team-builder/champ-select/v1/crowd-favorte-champion-list";
const SESSION_EVENT: &str = "OnJsonApiEvent_lol-champ-select_v1_session";
const TOPICS: &[&str] = &[
const TOPICS: [&str; 3] = [
"OnJsonApiEvent_lol-gameflow_v1_session",
"OnJsonApiEvent_lol-summoner_v1_current-summoner",
SESSION_EVENT,
PICKABLE_EVENT,
DISABLED_EVENT,
ANVIL_EVENT,
"OnJsonApiEvent_lol-champ-select_v1_session",
];
/// The local League client's API (unofficial, read-only). Deliberately no `Debug`: it handles
@@ -52,7 +42,6 @@ pub struct LeagueClient {
/// configuration is downloaded once per track.
tracks: Mutex<HashMap<String, (String, Option<String>)>>,
events: Mutex<Option<Events>>,
champ_select_reader: ChampSelectReader,
}
struct Events(WebSocket<MaybeTlsStream<TcpStream>>);
@@ -93,7 +82,6 @@ impl LeagueClient {
agent,
tracks: Mutex::default(),
events: Mutex::default(),
champ_select_reader: ChampSelectReader::default(),
}
}
@@ -167,24 +155,7 @@ impl GameClientSource for LeagueClient {
fn gameflow(&self) -> Result<Gameflow, ClientError> {
let (status, body) = self.get("/lol-gameflow/v1/session")?;
let flow = decode_gameflow(status, &body)?;
self.champ_select_reader
.reset_unless_arena_champ_select(&flow);
Ok(flow)
}
fn champ_select(&self) -> Result<crate::ChampSelect, ClientError> {
self.champ_select_reader.read(
|| self.get_ok(SESSION),
|| {
let pickable = self.get_ok(PICKABLE)?;
let disabled = self.get_ok(DISABLED)?;
// The anvil list is a bonus: a failed read leaves it empty until an event
// delivers it.
let anvil = self.get_ok(ANVIL_CHAMPIONS).ok();
Ok((pickable, disabled, anvil))
},
)
decode_gameflow(status, &body)
}
fn official_progress(&self, track_name: &str) -> Result<Option<u32>, ClientError> {
@@ -211,21 +182,15 @@ impl GameClientSource for LeagueClient {
decode_counter(&body, counter_id.as_deref())
}
fn wait_for_event(&self, timeout: Duration) -> ClientEvent {
fn wait_for_change(&self, timeout: Duration) {
let started = Instant::now();
let mut events = lock(&self.events);
if events.is_none() {
// A reconnection may follow a client restart: the lists belong to the previous one.
self.champ_select_reader.reset();
*events = self.connect();
// Re-read the snapshot after subscribing.
if events.is_some() {
return ClientEvent::Other;
}
}
let Some(connection) = events.as_mut() else {
thread::sleep(timeout.min(TIMEOUT));
return ClientEvent::Other;
return;
};
// Right after subscribing, the client sends one empty text frame per subscription
// (observed on patch 16.22): they and pings are not changes.
@@ -238,58 +203,19 @@ impl GameClientSource for LeagueClient {
.map_err(tungstenite::Error::Io)
.and_then(|()| connection.0.read());
match read {
Ok(Message::Text(text)) if !text.is_empty() => {
let Some((topic, data)) = decode_event(&text) else {
continue;
};
match self.apply_event(&topic, data) {
// A deleted session carries nothing to show: keep waiting, the gameflow
// event that follows ends the champ select view.
None => continue,
Some(event) => return event,
}
}
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 ClientEvent::Other;
return;
}
}
}
impl LeagueClient {
/// Applies one event, touching only the list it concerns. `None` when the event carries
/// nothing to show: a deleted champ select session, which must cost no request.
fn apply_event(&self, topic: &str, data: Value) -> Option<ClientEvent> {
match topic {
SESSION_EVENT => {
if data.is_null() {
return None;
}
self.champ_select_reader.set_session(data);
Some(ClientEvent::ChampSelect)
}
PICKABLE_EVENT => {
self.champ_select_reader.set_pickable(&data);
Some(ClientEvent::ChampSelect)
}
DISABLED_EVENT => {
self.champ_select_reader.set_disabled(&data);
Some(ClientEvent::ChampSelect)
}
ANVIL_EVENT => {
self.champ_select_reader.set_anvil(&data);
Some(ClientEvent::ChampSelect)
}
_ => Some(ClientEvent::Other),
}
}
}
pub(crate) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
@@ -310,18 +236,12 @@ fn tls_config() -> Result<ClientConfig, rustls::Error> {
)
}
/// A rejected certificate, a timeout or a dropped connection is worth telling apart from a
/// client that is simply not there (nothing listens): the first ones say nothing about the champ
/// select.
/// 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}"))
}
ureq::Error::Timeout(_) => ClientError::Other(format!("Le client ne répond pas : {e}")),
ureq::Error::Io(ref io) if io.kind() != ErrorKind::ConnectionRefused => {
ClientError::Other(format!("Échange avec le client interrompu : {e}"))
}
_ => ClientError::Absent,
}
}
@@ -351,21 +271,11 @@ fn install_dir_from_settings(yaml: &str) -> Option<PathBuf> {
(!path.is_empty()).then(|| path.into())
}
pub(crate) fn parse(body: &str) -> Result<Value, ClientError> {
fn parse(body: &str) -> Result<Value, ClientError> {
serde_json::from_str(body)
.map_err(|e| ClientError::Other(format!("Réponse du client illisible : {e}")))
}
/// Topic and resource of a WebSocket event frame,
/// `[8, "topic", {"data": resource, "eventType": ..., "uri": ...}]`; the resource is null on a
/// `Delete`.
fn decode_event(text: &str) -> Option<(String, Value)> {
let frame = parse(text).ok()?;
let topic = frame.get(1)?.as_str()?.to_owned();
let data = frame.pointer("/2/data").cloned().unwrap_or(Value::Null);
Some((topic, data))
}
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());
@@ -377,7 +287,7 @@ fn decode_signed_in(body: &str) -> Result<(String, String), ClientError> {
/// No session (404) means no game. The other fields are read leniently: the API is
/// unofficial and changes with patches.
pub fn decode_gameflow(status: u16, body: &str) -> Result<Gameflow, ClientError> {
fn decode_gameflow(status: u16, body: &str) -> Result<Gameflow, ClientError> {
match status {
404 => Ok(Gameflow::default()),
200 => {
@@ -633,157 +543,6 @@ mod tests {
assert_eq!(decode_counter("{}", Some(counter)), Ok(None));
}
#[test]
fn reads_the_topic_and_data_of_an_event_frame() {
let (topic, data) = decode_event(&frame(
SESSION_EVENT,
"Update",
r#"{"localPlayerCellId":16}"#,
))
.unwrap();
assert_eq!(topic, SESSION_EVENT);
assert_eq!(data["localPlayerCellId"], 16);
let (_, data) = decode_event(&frame(SESSION_EVENT, "Delete", "null")).unwrap();
assert!(data.is_null());
assert!(decode_event("not json").is_none());
assert!(decode_event("[]").is_none());
}
/// A frame as the client sends it: the resource sits in the envelope's `data`.
fn frame(topic: &str, event_type: &str, data: &str) -> String {
format!(r#"[8,"{topic}",{{"data":{data},"eventType":"{event_type}","uri":"/x"}}]"#)
}
/// A session body the reader can assemble, with this local pick.
fn session(current: u32) -> String {
format!(
r#"{{"localPlayerCellId":16,"myTeam":[{{"cellId":16,"championId":{current},
"championPickIntent":0}},{{"cellId":17,"championId":0,
"championPickIntent":0}}],"actions":[],
"bans":{{"myTeamBans":[],"theirTeamBans":[]}}}}"#
)
}
#[test]
fn a_raw_event_frame_updates_the_cached_session_and_lists() {
let client = LeagueClient::in_dir(PathBuf::new());
client
.champ_select_reader
.read(
|| Ok(session(0)),
|| Ok(("[1,2]".into(), "[]".into(), Some("[]".into()))),
)
.unwrap();
let apply = |topic, event_type, data: &str| {
let (topic, data) = decode_event(&frame(topic, event_type, data)).unwrap();
client.apply_event(&topic, data)
};
assert_eq!(
apply(SESSION_EVENT, "Update", &session(16)),
Some(ClientEvent::ChampSelect)
);
assert_eq!(
apply(ANVIL_EVENT, "Update", "[9,8]"),
Some(ClientEvent::ChampSelect)
);
assert_eq!(
apply(PICKABLE_EVENT, "Update", "[2]"),
Some(ClientEvent::ChampSelect)
);
// A deleted session carries nothing: it costs no request. Other Deletes change nothing
// either, but still wake the follower.
assert_eq!(apply(SESSION_EVENT, "Delete", "null"), None);
assert_eq!(
apply(ANVIL_EVENT, "Delete", "null"),
Some(ClientEvent::ChampSelect)
);
assert_eq!(
apply(PICKABLE_EVENT, "Delete", "null"),
Some(ClientEvent::ChampSelect)
);
// The event session replaces the request and the updated lists are used.
let pick = client
.champ_select_reader
.read(
|| panic!("the event session must be used"),
|| panic!("the lists must stay cached"),
)
.unwrap();
assert_eq!(pick.current, Some(16));
assert_eq!(pick.anvil_champions, [9, 8]);
assert!(!pick.can_pick(1));
assert!(pick.can_pick(2));
}
#[test]
fn only_a_client_that_is_gone_is_absent() {
let io = |kind| ureq::Error::Io(std::io::Error::from(kind));
assert_eq!(
transport_error(io(ErrorKind::ConnectionRefused)),
ClientError::Absent
);
for transient in [
ureq::Error::Timeout(ureq::Timeout::Global),
io(ErrorKind::TimedOut),
io(ErrorKind::ConnectionReset),
] {
assert!(matches!(transport_error(transient), ClientError::Other(_)));
}
}
#[test]
fn events_update_only_the_list_they_concern() {
use serde_json::json;
let client = LeagueClient::in_dir(PathBuf::new());
client
.champ_select_reader
.read(
|| Ok(session(0)),
|| Ok(("[1,2]".into(), "[2]".into(), Some("[9]".into()))),
)
.unwrap();
// A gameflow event leaves the champion lists alone; the old code cleared them all.
assert_eq!(
client.apply_event("OnJsonApiEvent_lol-gameflow_v1_session", json!({})),
Some(ClientEvent::Other)
);
let read = || {
client
.champ_select_reader
.read(|| Ok(session(0)), || panic!("the lists must stay cached"))
.unwrap()
};
let pick = read();
assert_eq!(pick.anvil_champions, [9]);
assert!(pick.can_pick(1));
assert!(!pick.can_pick(2));
assert_eq!(
client.apply_event(PICKABLE_EVENT, json!([1, 3])),
Some(ClientEvent::ChampSelect)
);
let pick = read();
assert!(pick.can_pick(1));
assert!(pick.can_pick(3));
assert!(!pick.can_pick(2));
// A session event is kept for the next read instead of a request.
assert_eq!(
client.apply_event(SESSION_EVENT, serde_json::from_str(&session(16)).unwrap()),
Some(ClientEvent::ChampSelect)
);
assert!(
client
.champ_select_reader
.read(
|| panic!("the event session must be used"),
|| panic!("the lists must stay cached"),
)
.is_ok()
);
}
#[test]
fn without_a_lockfile_the_client_is_absent() {
let dir = tempfile::tempdir().unwrap();
@@ -792,10 +551,7 @@ mod tests {
assert_eq!(client.gameflow(), Err(ClientError::Absent));
assert_eq!(client.official_progress(SEASON_2), Err(ClientError::Absent));
let started = Instant::now();
assert_eq!(
client.wait_for_event(Duration::from_millis(50)),
ClientEvent::Other
);
client.wait_for_change(Duration::from_millis(50));
assert!(started.elapsed() >= Duration::from_millis(50));
assert!(started.elapsed() < TIMEOUT);
}
+4 -11
View File
@@ -1,4 +1,3 @@
mod champ_select;
mod champion_search;
mod champions;
mod client;
@@ -12,20 +11,15 @@ mod riot;
mod seasons;
mod statistics;
mod tracker;
mod update_package;
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 client::{ClientError, GameClientSource, GamePhase, Gameflow};
pub use config::{Config, Preferences, ThemePreference, data_dir};
pub use date::Date;
pub use error::{Error, SourceError};
pub use follow::{
MATCH_RETRIES, ProgressCheck, RETRY_EVERY_MS, Status, UpdateProblem, account_riot_id, riot_id,
same_riot_id,
};
pub use league_client::{LeagueClient, decode_gameflow};
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};
@@ -34,4 +28,3 @@ pub use statistics::{
Statistics, sort_rows,
};
pub use tracker::{MatchHistorySource, Tracker};
pub use update_package::{download_update, restart_to_update, update_at_launch, verify_release};
-358
View File
@@ -1,358 +0,0 @@
use std::fs::{self, File};
use std::io::{self, Read};
use std::ops::ControlFlow;
use std::path::{Path, PathBuf};
use std::time::Duration;
use base64::prelude::{BASE64_STANDARD, Engine};
use ring::{digest, signature};
use serde::Deserialize;
use ureq::Agent;
use crate::{Error, SourceError, UpdateChannel};
/// Bounds what a source can write to disk: a full package is a few tens of MiB.
const MAX_DOWNLOAD: u64 = 256 << 20;
/// A connection or a read that stalls this long fails; a slow download does not.
const STALL: Duration = Duration::from_secs(30);
/// Suffix of the file `<channel>-<version>.attempt`, written next to a kept package's folder when
/// the package is handed to the installer. It holds the installer's process id, `REPORTED` once
/// a failure was shown, or anything else when the launch stopped before knowing the process.
/// It outlives a new download of the same version (Velopack deletes a package it cannot open):
/// no launch retries that version on its own, only « Redémarrer » does.
const ATTEMPT: &str = ".attempt";
const REPORTED: &str = "reported";
#[derive(Deserialize)]
struct Manifest {
app: String,
target: String,
channel: String,
version: String,
commit: String,
package: String,
sha256: String,
}
/// Verifies a release folder: the signed manifest, then the digest of the package read as a plain
/// byte stream, never as an archive. Returns the authenticated source commit.
/// Callers must keep these bytes isolated until success, then apply exactly these bytes.
pub fn verify_release(
dir: &Path,
public_key: &[u8],
channel: &str,
version: &str,
) -> Result<String, Error> {
let rejected = |why: String| Error::InvalidUpdate(why);
let open = |name: &str| {
File::open(dir.join(name)).map_err(|e| rejected(format!("{name} illisible ({e})")))
};
let read = |name: &str, limit: u64| {
let mut bytes = Vec::new();
open(name)?
.take(limit + 1)
.read_to_end(&mut bytes)
.map_err(|e| rejected(format!("{name} illisible ({e})")))?;
if bytes.len() as u64 > limit {
return Err(rejected(format!("{name} trop volumineux")));
}
Ok(bytes)
};
let manifest = read(&format!("release-{channel}.json"), 4096)?;
let signed = read(&format!("release-{channel}.sig"), 64)?;
signature::UnparsedPublicKey::new(&signature::ED25519, public_key)
.verify(&manifest, &signed)
.map_err(|_| rejected("signature invalide".into()))?;
let release: Manifest = serde_json::from_slice(&manifest)
.map_err(|e| rejected(format!("manifeste illisible ({e})")))?;
let package = format!("ArenaTracker-{version}-{channel}-full.nupkg");
if release.app != "ArenaTracker"
|| release.target != "win-x64"
|| release.channel != channel
|| release.version != version
|| release.package != package
{
return Err(rejected("identité inattendue".into()));
}
let mut file = open(&package)?;
let mut hash = digest::Context::new(&digest::SHA256);
let mut buffer = [0; 64 * 1024];
loop {
let n = file
.read(&mut buffer)
.map_err(|e| rejected(format!("{package} illisible ({e})")))?;
if n == 0 {
break;
}
hash.update(&buffer[..n]);
}
if release.sha256 != BASE64_STANDARD.encode(hash.finish().as_ref()) {
return Err(rejected("condensat du paquet différent".into()));
}
Ok(release.commit)
}
#[derive(Deserialize)]
struct Release {
assets: Vec<Asset>,
}
#[derive(Deserialize)]
struct Asset {
name: String,
browser_download_url: String,
}
/// Orders `X.Y.Z` after its betas and `beta.2` before `beta.10`; `None` for any other form.
fn version_order(version: &str) -> Option<[u64; 4]> {
let number = |text: &str| text.parse::<u64>().ok().filter(|n| n.to_string() == text);
let (core, beta) = match version.split_once("-beta.") {
Some((core, n)) => (core, number(n).filter(|n| (1..u64::MAX).contains(n))?),
None => (version, u64::MAX),
};
let mut parts = core.split('.').map(number);
let order = [parts.next()??, parts.next()??, parts.next()??, beta];
parts.next().is_none().then_some(order)
}
/// The order of `version` when `channel` takes it over `installed`: above it, and of its kind.
fn newer(version: &str, installed: [u64; 4], channel: UpdateChannel) -> Option<[u64; 4]> {
let order = version_order(version)?;
// Betas end below u64::MAX, stables at it: a channel only takes its own versions.
let beta = channel == UpdateChannel::Beta;
(order > installed && (order[3] < u64::MAX) == beta).then_some(order)
}
/// The newest package folder of `channel` kept in `dir` above `installed`, with its version.
/// Another channel's folder, which a check may not have removed yet, never counts.
fn kept_update(dir: &Path, channel: UpdateChannel, installed: &str) -> Option<(String, PathBuf)> {
let installed = version_order(installed)?;
let prefix = format!("{}-", channel.name());
fs::read_dir(dir)
.ok()?
.flatten()
.filter_map(|entry| {
let name = entry.file_name().into_string().ok()?;
let version = name.strip_prefix(&prefix)?;
Some((
newer(version, installed, channel)?,
version.to_owned(),
entry.path(),
))
})
.max_by_key(|(order, ..)| *order)
.map(|(_, version, folder)| (version, folder))
}
/// The attempt record of the kept package folder `folder` (see `ATTEMPT`).
fn attempt_file(folder: &Path) -> PathBuf {
let mut path = folder.as_os_str().to_owned();
path.push(ATTEMPT);
path.into()
}
/// Authenticates the kept package in `folder` again, then hands exactly that file to `start`,
/// which starts the installer on it and returns the installer's process id.
fn hand_over(
folder: &Path,
public_key: &[u8],
channel: UpdateChannel,
version: &str,
start: impl FnOnce(&Path) -> io::Result<u32>,
) -> Result<(), Error> {
let name = channel.name();
verify_release(folder, public_key, name, version)?;
let attempt = attempt_file(folder);
// Written first: whatever happens next, no launch retries this package on its own.
fs::write(&attempt, "").map_err(storage)?;
let package = folder.join(format!("ArenaTracker-{version}-{name}-full.nupkg"));
let installer = start(&package).map_err(|_| {
let _ = fs::write(&attempt, REPORTED);
Error::UpdateFailed(version.into())
})?;
// Lets a launch during the installation wait for it rather than report a failure.
let _ = fs::write(&attempt, installer.to_string());
Ok(())
}
/// Runs before the app loads, by the single instance only. Hands the kept package of `channel`
/// above `installed` to the installer once, through `start` (see `hand_over`). `outcome` waits
/// for the installer process with the given id and returns its exit code, or `None` when no such
/// installer runs any more. `Break`: the installer replaces this version and opens the app.
/// `Continue`: load the app, showing the error if there is one. A failed attempt is reported
/// once and never retried from here, so a failing update cannot keep the app from opening.
pub fn update_at_launch(
dir: &Path,
public_key: &[u8],
channel: UpdateChannel,
installed: &str,
start: impl FnOnce(&Path) -> io::Result<u32>,
outcome: impl FnOnce(u32) -> Option<u32>,
) -> ControlFlow<(), Option<Error>> {
let Some((version, folder)) = kept_update(dir, channel, installed) else {
return ControlFlow::Continue(None);
};
let attempt = attempt_file(&folder);
let text = match fs::read_to_string(&attempt) {
Err(error) if error.kind() == io::ErrorKind::NotFound => {
return match hand_over(&folder, public_key, channel, &version, start) {
Ok(()) => ControlFlow::Break(()),
Err(error) => ControlFlow::Continue(Some(error)),
};
}
// Unreadable: never retried from here, and nothing more is known.
Err(_) => return ControlFlow::Continue(None),
Ok(text) => text,
};
if text == REPORTED {
return ControlFlow::Continue(None);
}
// Launched during the installation, or by the installer itself once it is over.
if let Ok(installer) = text.parse()
&& outcome(installer) == Some(0)
{
return ControlFlow::Break(());
}
let _ = fs::write(&attempt, REPORTED);
ControlFlow::Continue(Some(Error::UpdateFailed(version)))
}
/// « Redémarrer »: hands the kept package of `channel` above `installed` to the installer like
/// `update_at_launch`, even after a failed attempt. The app must then quit for the installer.
pub fn restart_to_update(
dir: &Path,
public_key: &[u8],
channel: UpdateChannel,
installed: &str,
start: impl FnOnce(&Path) -> io::Result<u32>,
) -> Result<(), Error> {
let (version, folder) = kept_update(dir, channel, installed)
.ok_or_else(|| Error::InvalidUpdate("paquet introuvable".into()))?;
hand_over(&folder, public_key, channel, &version, start)
}
/// Removes the entries of `dir` whose name `matches`, as far as it can: an entry another program
/// holds open stays until a later check, and must not hide an authenticated package.
fn remove_entries(dir: &Path, matches: impl Fn(&str) -> bool) {
for entry in fs::read_dir(dir).into_iter().flatten().flatten() {
if matches(&entry.file_name().to_string_lossy()) {
let _ = if entry.file_type().is_ok_and(|kind| kind.is_dir()) {
fs::remove_dir_all(entry.path())
} else {
fs::remove_file(entry.path())
};
}
}
}
/// Keeps the newest release of `channel` above `installed` downloaded and authenticated in
/// `dir/<channel>-<version>` and returns its version, or `None` when there is none. Anything
/// else in `dir` but that version's attempt record is removed; another channel's package goes
/// before any network access, so it can
/// never be taken for this channel's. Bytes are downloaded into `dir/partial` and renamed only
/// once `verify_release` accepts them. A kept package is verified again instead of downloaded.
/// `releases_url` is a Gitea releases API endpoint, where betas are pre-releases.
/// One call at a time per `dir`.
pub fn download_update(
releases_url: &str,
dir: &Path,
public_key: &[u8],
channel: UpdateChannel,
installed: &str,
) -> Result<Option<String>, Error> {
let installed = version_order(installed)
.ok_or_else(|| Error::InvalidUpdate("version installée illisible".into()))?;
let name = channel.name();
fs::create_dir_all(dir).map_err(storage)?;
remove_entries(dir, |entry| !entry.starts_with(&format!("{name}-")));
let agent: Agent = Agent::config_builder()
.http_status_as_error(false)
.user_agent("arena-tracker")
.timeout_connect(Some(STALL))
.timeout_per_read(Some(STALL))
.build()
.into();
let get = |url: &str| {
let response = agent.get(url).call().map_err(network)?;
match response.status().as_u16() {
200..=299 => Ok(response),
status => Err(network(format!("HTTP {status}"))),
}
};
let beta = channel == UpdateChannel::Beta;
let list = get(&format!(
"{releases_url}?draft=false&pre-release={beta}&limit=10"
))?
.into_body()
.read_to_string()
.map_err(network)?;
let releases: Vec<Release> = serde_json::from_str(&list)
.map_err(|e| Error::InvalidUpdate(format!("liste des versions illisible ({e})")))?;
let manifest_files = [
format!("release-{name}.json"),
format!("release-{name}.sig"),
];
let newest = releases
.iter()
.filter_map(|release| {
let has = |file: &str| release.assets.iter().any(|asset| asset.name == file);
let version = release.assets.iter().find_map(|asset| {
let rest = asset.name.strip_prefix("ArenaTracker-")?;
rest.strip_suffix(&format!("-{name}-full.nupkg"))
})?;
let order = newer(version, installed, channel)?;
let complete = manifest_files.iter().all(|file| has(file));
complete.then_some((order, version, release))
})
.max_by_key(|(order, ..)| *order);
let Some((_, version, release)) = newest else {
remove_entries(dir, |_| true);
return Ok(None);
};
let kept = format!("{name}-{version}");
let attempt = format!("{kept}{ATTEMPT}");
let others = |entry: &str| entry != kept && entry != attempt;
if verify_release(&dir.join(&kept), public_key, name, version).is_ok() {
remove_entries(dir, others);
return Ok(Some(version.into()));
}
// An older package of this channel stays until the newer one is ready.
remove_entries(dir, |entry| entry == kept);
let partial = dir.join("partial");
fs::create_dir(&partial).map_err(storage)?;
let package = format!("ArenaTracker-{version}-{name}-full.nupkg");
let downloaded = manifest_files
.iter()
.chain([&package])
.try_for_each(|file| {
let asset = release.assets.iter().find(|asset| &asset.name == file);
let asset = asset.ok_or_else(|| Error::InvalidUpdate(format!("{file} absent")))?;
// verify_release reads at most 4 KiB of manifest and 64 bytes of signature.
let limit = if file == &package { MAX_DOWNLOAD } else { 4096 };
let mut body = get(&asset.browser_download_url)?.into_body();
let mut reader = body.with_config().limit(limit).reader();
let mut target = File::create(partial.join(file)).map_err(storage)?;
std::io::copy(&mut reader, &mut target)
.map_err(|e| Error::InvalidUpdate(format!("{file} incomplet ({e})")))?;
Ok(())
});
if let Err(error) =
downloaded.and_then(|()| verify_release(&partial, public_key, name, version))
{
let _ = fs::remove_dir_all(&partial);
return Err(error);
}
fs::rename(&partial, dir.join(&kept)).map_err(storage)?;
remove_entries(dir, others);
Ok(Some(version.into()))
}
fn network(error: impl ToString) -> Error {
Error::Source(SourceError::Network(error.to_string()))
}
fn storage(error: std::io::Error) -> Error {
Error::Storage(error.to_string())
}
+6 -105
View File
@@ -2,7 +2,7 @@
// Each test binary uses its own subset of these helpers.
#![allow(dead_code)]
use std::collections::{HashMap, VecDeque};
use std::collections::HashMap;
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc::{Receiver, Sender};
@@ -10,9 +10,8 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
use arena_tracker_core::{
Account, ChampSelect, ChampSelectReader, Champion, ChampionCatalog, ChampionSource,
ClientError, ClientEvent, Date, GameClientSource, GamePhase, Gameflow, MatchHistorySource,
Season, SourceError, Tracker, decode_gameflow,
Account, Champion, ChampionCatalog, ChampionSource, ClientError, Date, GameClientSource,
GamePhase, Gameflow, MatchHistorySource, Season, SourceError, Tracker,
};
use serde_json::Value;
@@ -562,9 +561,6 @@ pub fn recorded_game_id() -> u64 {
#[derive(Clone, Default)]
pub struct FakeClient {
state: Arc<Mutex<ClientState>>,
/// Session and champion-list bodies the fake's champ select reader asked for.
session_reads: Arc<AtomicUsize>,
list_reads: Arc<AtomicUsize>,
}
#[derive(Default)]
@@ -573,26 +569,6 @@ struct ClientState {
gameflow: Gameflow,
tracks: HashMap<String, u32>,
waits: Vec<Duration>,
/// The raw bodies the client answers for the current champ select.
champ_select: Option<RawChampSelect>,
/// Reads the champ select the one way the live client does.
champ_select_reader: ChampSelectReader,
/// Session bodies the client reports as events, applied before `wait_for_event` returns.
events: VecDeque<Value>,
/// A raw gameflow body, replayed through the same parser as the live client.
raw_gameflow: Option<String>,
gameflow_error: Option<ClientError>,
champ_select_error: Option<ClientError>,
}
/// The raw client responses of a champ select, replayed through the same reader as the live
/// client.
#[derive(Clone)]
pub struct RawChampSelect {
pub pickable: String,
pub disabled: String,
pub anvil: String,
pub session: String,
}
impl FakeClient {
@@ -645,7 +621,6 @@ impl FakeClient {
/// `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.raw_gameflow = None;
state.gameflow = Gameflow {
phase: GamePhase::from_client(phase),
arena,
@@ -653,43 +628,11 @@ impl FakeClient {
};
}
/// Replays a captured gameflow body through the live client's parser.
pub fn set_gameflow(&self, body: &str) {
self.state.lock().unwrap().raw_gameflow = Some(body.into());
}
/// 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_champ_select(&self, raw: RawChampSelect) {
self.state.lock().unwrap().champ_select = Some(raw);
}
/// Reports one of the captured session bodies as the client's champ select event.
pub fn send_champ_select_event(&self, session: &str) {
let session = serde_json::from_str(session).unwrap_or(Value::Null);
self.state.lock().unwrap().events.push_back(session);
}
/// How many session and champion-list bodies the champ select reader asked the client for.
pub fn champ_select_reads(&self) -> (usize, usize) {
(
self.session_reads.load(Ordering::SeqCst),
self.list_reads.load(Ordering::SeqCst),
)
}
/// The next gameflow or champ select read fails with this, until cleared.
pub fn fail_gameflow(&self, error: Option<ClientError>) {
self.state.lock().unwrap().gameflow_error = error;
}
pub fn fail_champ_select(&self, error: Option<ClientError>) {
self.state.lock().unwrap().champ_select_error = error;
}
pub fn set_track(&self, name: &str, value: u32) {
self.state.lock().unwrap().tracks.insert(name.into(), value);
}
@@ -713,41 +656,7 @@ impl GameClientSource for FakeClient {
fn gameflow(&self) -> Result<Gameflow, ClientError> {
let state = self.state.lock().unwrap();
state.signed_in.as_ref().ok_or(ClientError::Absent)?;
if let Some(error) = &state.gameflow_error {
return Err(error.clone());
}
let flow = match &state.raw_gameflow {
Some(body) => decode_gameflow(200, body)?,
None => state.gameflow.clone(),
};
state
.champ_select_reader
.reset_unless_arena_champ_select(&flow);
Ok(flow)
}
fn champ_select(&self) -> Result<ChampSelect, ClientError> {
let state = self.state.lock().unwrap();
if let Some(error) = &state.champ_select_error {
return Err(error.clone());
}
let raw = state.champ_select.as_ref().ok_or(ClientError::Absent)?;
let sessions = self.session_reads.clone();
let lists = self.list_reads.clone();
state.champ_select_reader.read(
|| {
sessions.fetch_add(1, Ordering::SeqCst);
Ok(raw.session.clone())
},
|| {
lists.fetch_add(1, Ordering::SeqCst);
Ok((
raw.pickable.clone(),
raw.disabled.clone(),
Some(raw.anvil.clone()),
))
},
)
Ok(state.gameflow.clone())
}
fn official_progress(&self, track_name: &str) -> Result<Option<u32>, ClientError> {
@@ -756,15 +665,7 @@ impl GameClientSource for FakeClient {
Ok(state.tracks.get(track_name).copied())
}
fn wait_for_event(&self, timeout: Duration) -> ClientEvent {
let mut state = self.state.lock().unwrap();
state.waits.push(timeout);
match state.events.pop_front() {
Some(session) => {
state.champ_select_reader.set_session(session);
ClientEvent::ChampSelect
}
None => ClientEvent::Other,
}
fn wait_for_change(&self, timeout: Duration) {
self.state.lock().unwrap().waits.push(timeout);
}
}
@@ -1,223 +0,0 @@
{
"gameflow": {
"phase": "ChampSelect",
"map": {
"id": 30,
"gameMode": "CHERRY"
},
"gameData": {
"queue": {
"id": 1750,
"gameMode": "CHERRY"
}
}
},
"pickableChampionIds": [
103,
12,
16,
233,
25,
50
],
"disabledChampionIds": [],
"ownedChampionsMinimal": [
{
"id": 12,
"ownership": {
"owned": true
}
},
{
"id": 16,
"ownership": {
"owned": true
}
},
{
"id": 25,
"ownership": {
"owned": true
}
},
{
"id": 50,
"ownership": {
"owned": true
}
},
{
"id": 103,
"ownership": {
"owned": true
}
},
{
"id": 233,
"ownership": {
"owned": true
}
}
],
"sessions": [
{
"localPlayerCellId": 16,
"myTeam": [
{
"cellId": 16,
"championId": 0,
"championPickIntent": 0
},
{
"cellId": 17,
"championId": 0,
"championPickIntent": 0
}
],
"actions": [],
"bans": {
"myTeamBans": [],
"theirTeamBans": []
}
},
{
"localPlayerCellId": 16,
"myTeam": [
{
"cellId": 16,
"championId": 0,
"championPickIntent": 0
},
{
"cellId": 17,
"championId": 0,
"championPickIntent": 25
}
],
"actions": [
[
{
"type": "ban",
"championId": 12,
"completed": true
},
{
"type": "ban",
"championId": 50,
"completed": false
}
]
],
"bans": {
"myTeamBans": [],
"theirTeamBans": []
}
},
{
"localPlayerCellId": 16,
"myTeam": [
{
"cellId": 16,
"championId": 0,
"championPickIntent": 233
},
{
"cellId": 17,
"championId": 0,
"championPickIntent": 25
}
],
"actions": [
[
{
"type": "ban",
"championId": 12,
"completed": true
},
{
"type": "ban",
"championId": 50,
"completed": true
}
]
],
"bans": {
"myTeamBans": [],
"theirTeamBans": []
}
},
{
"localPlayerCellId": 16,
"myTeam": [
{
"cellId": 16,
"championId": 0,
"championPickIntent": 16
},
{
"cellId": 17,
"championId": 25,
"championPickIntent": 25
}
],
"actions": [
[
{
"type": "ban",
"championId": 12,
"completed": true
},
{
"type": "ban",
"championId": 50,
"completed": true
}
]
],
"bans": {
"myTeamBans": [],
"theirTeamBans": []
}
},
{
"localPlayerCellId": 16,
"myTeam": [
{
"cellId": 16,
"championId": 16,
"championPickIntent": 0
},
{
"cellId": 17,
"championId": 25,
"championPickIntent": 25
}
],
"actions": [
[
{
"type": "ban",
"championId": 12,
"completed": true
},
{
"type": "ban",
"championId": 50,
"completed": true
}
]
],
"bans": {
"myTeamBans": [],
"theirTeamBans": []
}
}
],
"crowdFavoriteChampionIds": [
233,
64,
5,
16,
68
]
}
+4 -140
View File
@@ -7,13 +7,12 @@ use std::thread;
use std::time::{Duration, Instant};
use arena_tracker_core::{
Account, ChampSelect, ChampionRow, ChampionState, ClientError, ClientEvent, Format,
MATCH_RETRIES, ProgressCheck, RETRY_EVERY_MS, Scope, SeasonScope, SourceError, Tracker,
UpdateProblem,
Account, Format, MATCH_RETRIES, ProgressCheck, RETRY_EVERY_MS, Scope, SeasonScope, SourceError,
Tracker, UpdateProblem,
};
use common::{
FakeClient, FakeHistory, PlayedMatch, RawChampSelect, S2, S2_TRACK, SELF_PUUID, at, date,
payload, payloads, played_by, played_match, recorded_account, run, seasons,
FakeClient, FakeHistory, PlayedMatch, S2, S2_TRACK, SELF_PUUID, at, date, payload, payloads,
played_by, played_match, recorded_account, run, seasons,
};
const OTHER_PUUID: &str = "fixture-puuid-other";
@@ -93,11 +92,6 @@ fn round(tracker: &Tracker) -> bool {
round_after(tracker, RETRY_EVERY_MS)
}
/// The live champ select the page would show, read once at this instant.
fn shown(tracker: &Tracker) -> Result<Option<(String, ChampSelect)>, ClientError> {
tracker.champ_select_with(&tracker.client_snapshot())
}
fn completed(tracker: &Tracker, puuid: &str) -> usize {
let scope = Scope {
season: SeasonScope::Season(S2.into()),
@@ -1029,133 +1023,3 @@ fn banners_point_to_the_parametres_screen_and_never_to_a_missing_field() {
assert!(!text(problem).contains("réglages"));
}
}
#[test]
fn arena_champ_select_replays_bans_hovers_and_lock_in_for_the_current_challenge() {
use serde_json::Value;
fn assert_pick(
pick: &ChampSelect,
rows: &[ChampionRow],
current: Option<(u32, ChampionState)>,
remaining: &[u32],
) {
assert_eq!(pick.anvil_champions, [233, 64, 5, 16, 68]);
assert_eq!(
pick.current_row(rows)
.map(|r| (r.champion.id, r.attempts, r.state)),
current.map(|(id, state)| (id, Some(1), Some(state)))
);
let mut ids: Vec<_> = rows
.iter()
.filter(|r| pick.remaining(r))
.map(|r| r.champion.id)
.collect();
ids.sort_unstable();
assert_eq!(ids, remaining);
}
let capture: Value =
serde_json::from_str(include_str!("fixtures/client/arena_champ_select.json")).unwrap();
let world = World::new(
&[12, 16, 25, 50, 103, 233].map(|id| played_match(id, if id == 16 { 1 } else { 4 }, now())),
);
let tracker = world.tracker();
// The fake replays the captured raw responses through the same reader as the live client.
let set_frame = |frame: usize| {
world.client.set_champ_select(RawChampSelect {
pickable: capture["pickableChampionIds"].to_string(),
disabled: capture["disabledChampionIds"].to_string(),
anvil: capture["crowdFavoriteChampionIds"].to_string(),
session: capture["sessions"][frame].to_string(),
});
};
set_frame(0);
world.client.set_phase("ChampSelect", false);
round(&tracker);
assert_eq!(shown(&tracker), Ok(None));
// The captured gameflow body goes through the live client's parser too.
world.client.set_gameflow(&capture["gameflow"].to_string());
let rows = tracker
.statistics(
SELF_PUUID,
&Scope {
season: SeasonScope::Season(S2.into()),
format: None,
},
)
.unwrap()
.rows;
// The first read fetches the session and the champion lists once.
let (account, pick) = shown(&tracker).unwrap().unwrap();
assert_eq!(account, "Joueur#EUW");
assert_pick(&pick, &rows, None, &[12, 25, 50, 103, 233]);
assert_eq!(world.client.champ_select_reads(), (1, 1));
// Every later change arrives as the client's session event: neither the session nor the
// lists are read again.
for (frame, current, remaining) in [
(1, None, vec![25, 50, 103, 233]),
(
2,
Some((233, ChampionState::InProgress)),
vec![25, 103, 233],
),
(3, Some((16, ChampionState::Completed)), vec![103, 233]),
(4, Some((16, ChampionState::Completed)), vec![103, 233]),
] {
world
.client
.send_champ_select_event(&capture["sessions"][frame].to_string());
assert_eq!(tracker.wait_for_client(), ClientEvent::ChampSelect);
let (_, pick) = shown(&tracker).unwrap().unwrap();
assert_pick(&pick, &rows, current, &remaining);
assert_eq!(world.client.champ_select_reads(), (1, 1));
}
// Leaving the champ select ends it and drops its lists; the next one reads them again.
world.client.set_phase("InProgress", true);
assert_eq!(shown(&tracker), Ok(None));
set_frame(0);
world.client.set_gameflow(&capture["gameflow"].to_string());
assert!(shown(&tracker).unwrap().is_some());
assert_eq!(world.client.champ_select_reads(), (2, 2));
}
#[test]
fn a_failed_champ_select_read_keeps_the_pick_until_the_champ_select_really_ends() {
use serde_json::Value;
let capture: Value =
serde_json::from_str(include_str!("fixtures/client/arena_champ_select.json")).unwrap();
let world = World::new(&[]);
let tracker = world.tracker();
world.client.set_champ_select(RawChampSelect {
pickable: capture["pickableChampionIds"].to_string(),
disabled: capture["disabledChampionIds"].to_string(),
anvil: capture["crowdFavoriteChampionIds"].to_string(),
session: capture["sessions"][0].to_string(),
});
world.client.set_gameflow(&capture["gameflow"].to_string());
let live = shown(&tracker).unwrap();
assert!(live.is_some());
// A failed gameflow or session request is not an answer that the champ select is over.
world
.client
.fail_gameflow(Some(ClientError::Other("HTTP 500".into())));
assert_eq!(shown(&tracker), Err(ClientError::Other("HTTP 500".into())));
world.client.fail_gameflow(None);
world
.client
.fail_champ_select(Some(ClientError::Other("HTTP 500".into())));
assert_eq!(shown(&tracker), Err(ClientError::Other("HTTP 500".into())));
world.client.fail_champ_select(None);
assert_eq!(shown(&tracker).unwrap(), live);
// Leaving champ select, or the client going away, does end it.
world.client.set_phase("InProgress", true);
assert_eq!(shown(&tracker), Ok(None));
world.client.sign_out();
assert_eq!(shown(&tracker), Ok(None));
}
-568
View File
@@ -1,568 +0,0 @@
use std::fs;
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::ops::ControlFlow;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
use arena_tracker_core::{
Error, UpdateChannel, download_update, restart_to_update, update_at_launch, verify_release,
};
use base64::prelude::{BASE64_STANDARD, Engine};
use ring::digest;
use ring::signature::{Ed25519KeyPair, KeyPair};
use serde_json::{Value, json};
use tempfile::TempDir;
const PACKAGE: &str = "ArenaTracker-1.0.0-stable-full.nupkg";
/// A stable 1.0.0 release folder; `signature` None leaves the signature file out.
fn release(manifest: &[u8], signature: Option<&[u8]>, package: &[u8]) -> TempDir {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join("release-stable.json"), manifest).unwrap();
if let Some(signature) = signature {
fs::write(dir.path().join("release-stable.sig"), signature).unwrap();
}
fs::write(dir.path().join(PACKAGE), package).unwrap();
dir
}
#[test]
fn only_the_signed_full_package_for_the_expected_release_is_accepted() {
let key = Ed25519KeyPair::from_seed_unchecked(&[7; 32]).unwrap();
let manifest = json!({
"app": "ArenaTracker", "target": "win-x64", "channel": "stable", "version": "1.0.0",
"commit": "c".repeat(40), "package": PACKAGE,
"sha256": "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0="
});
let check = |dir: &TempDir, channel: &str, version: &str| {
verify_release(dir.path(), key.public_key().as_ref(), channel, version)
};
let refused =
|dir: TempDir| matches!(check(&dir, "stable", "1.0.0"), Err(Error::InvalidUpdate(_)));
let doc = serde_json::to_vec(&manifest).unwrap();
let sig = key.sign(&doc);
let good = release(&doc, Some(sig.as_ref()), b"abc");
assert_eq!(check(&good, "stable", "1.0.0").unwrap(), "c".repeat(40));
assert!(check(&good, "beta", "1.0.0").is_err());
assert!(check(&good, "stable", "1.1.0").is_err());
assert!(refused(release(&doc, Some(sig.as_ref()), b"abd")));
assert!(refused(release(&doc, None, b"abc")));
assert!(refused(release(&doc, Some(&[]), b"abc")));
assert!(refused(release(&doc, Some(&[0; 64]), b"abc")));
let missing_package = release(&doc, Some(sig.as_ref()), b"abc");
fs::remove_file(missing_package.path().join(PACKAGE)).unwrap();
assert!(refused(missing_package));
let mut padded = doc.clone();
padded.resize(4097, b' ');
assert!(refused(release(
&padded,
Some(key.sign(&padded).as_ref()),
b"abc"
)));
for (field, wrong) in [
("app", "Other"),
("target", "win-arm64"),
("channel", "beta"),
("version", "1.1.0"),
("package", "different.nupkg"),
("sha256", ""),
] {
let mut other: Value = manifest.clone();
other[field] = wrong.into();
let other = serde_json::to_vec(&other).unwrap();
assert!(
refused(release(&other, Some(sig.as_ref()), b"abc")),
"{field}"
);
assert!(
refused(release(&other, Some(key.sign(&other).as_ref()), b"abc")),
"{field}"
);
}
}
/// The files of one Release: (name, bytes). Betas are published as pre-releases.
struct Published {
prerelease: bool,
files: Vec<(String, Vec<u8>)>,
}
/// A release of `version` signed by `key`, following the package contract of #57.
fn publish(key: &Ed25519KeyPair, channel: &str, version: &str) -> Published {
let package = format!("ArenaTracker-{version}-{channel}-full.nupkg");
let bytes = format!("package {version}").into_bytes();
let manifest = serde_json::to_vec(&json!({
"app": "ArenaTracker", "target": "win-x64", "channel": channel, "version": version,
"commit": "c".repeat(40), "package": package,
"sha256": BASE64_STANDARD.encode(digest::digest(&digest::SHA256, &bytes)),
}))
.unwrap();
Published {
prerelease: channel == "beta",
files: vec![
(
format!("release-{channel}.sig"),
key.sign(&manifest).as_ref().to_vec(),
),
(format!("release-{channel}.json"), manifest),
(package, bytes),
],
}
}
/// Serves `releases` like Gitea's API and returns its releases URL and a count of package
/// downloads. With `cut`, a package response stops halfway through its announced length.
fn serve(releases: Vec<Published>, cut: bool) -> (String, Arc<AtomicUsize>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let downloads = Arc::new(AtomicUsize::new(0));
let (url, count) = (base.clone(), downloads.clone());
thread::spawn(move || {
for stream in listener.incoming() {
let mut stream = stream.unwrap();
let mut reader = BufReader::new(&stream);
let mut line = String::new();
reader.read_line(&mut line).unwrap();
let path = line.split(' ').nth(1).unwrap().to_string();
// The headers end with an empty line.
while !matches!(reader.read_line(&mut String::new()), Ok(0..=2)) {}
let (body, cut) = if let Some(query) = path.strip_prefix("/releases?") {
let prerelease = query.contains("pre-release=true");
let list: Vec<Value> = releases
.iter()
.enumerate()
.filter(|(_, release)| release.prerelease == prerelease)
.map(|(i, release)| {
let assets: Vec<Value> = release
.files
.iter()
.map(|(name, _)| {
let link = format!("{url}/files/{i}/{name}");
json!({ "name": name, "browser_download_url": link })
})
.collect();
json!({ "tag_name": format!("t{i}"), "prerelease": prerelease, "assets": assets })
})
.collect();
(serde_json::to_vec(&list).unwrap(), false)
} else {
let (i, name) = path["/files/".len()..].split_once('/').unwrap();
let files = &releases[i.parse::<usize>().unwrap()].files;
let (_, bytes) = files.iter().find(|(file, _)| file == name).unwrap();
let package = name.ends_with(".nupkg");
if package {
count.fetch_add(1, Ordering::SeqCst);
}
(bytes.clone(), cut && package)
};
let sent = if cut { &body[..body.len() / 2] } else { &body };
let head = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
let _ = stream
.write_all(head.as_bytes())
.and_then(|()| stream.write_all(sent));
}
});
(format!("{base}/releases"), downloads)
}
/// A releases URL nothing listens on.
fn unreachable() -> String {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
format!("http://{}/releases", listener.local_addr().unwrap())
}
fn key() -> Ed25519KeyPair {
Ed25519KeyPair::from_seed_unchecked(&[7; 32]).unwrap()
}
/// The names left in the updates folder.
fn kept(dir: &Path) -> Vec<String> {
let mut names: Vec<String> = fs::read_dir(dir)
.unwrap()
.map(|entry| entry.unwrap().file_name().into_string().unwrap())
.collect();
names.sort();
names
}
#[test]
fn each_channel_gets_its_newest_release_above_the_installed_version() {
let key = key();
let (url, _) = serve(
vec![
publish(&key, "stable", "1.0.0"),
publish(&key, "beta", "1.2.0-beta.10"),
publish(&key, "stable", "1.1.0"),
publish(&key, "beta", "1.2.0-beta.2"),
publish(&key, "stable", "1.0.1"),
publish(&key, "stable", "2.0"),
],
false,
);
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check =
|channel, installed| download_update(&url, dir.path(), public, channel, installed).unwrap();
assert_eq!(
check(UpdateChannel::Stable, "1.0.0").as_deref(),
Some("1.1.0")
);
assert_eq!(kept(dir.path()), ["stable-1.1.0"]);
let ready = dir.path().join("stable-1.1.0");
assert!(verify_release(&ready, public, "stable", "1.1.0").is_ok());
// The same version or an older one is ignored, and nothing stays pending.
assert_eq!(check(UpdateChannel::Stable, "1.1.0"), None);
assert_eq!(check(UpdateChannel::Stable, "1.2.0"), None);
assert!(kept(dir.path()).is_empty());
// beta.10 comes after beta.2, and the beta channel never takes a stable.
assert_eq!(
check(UpdateChannel::Beta, "1.1.0-beta.1").as_deref(),
Some("1.2.0-beta.10")
);
assert_eq!(
check(UpdateChannel::Beta, "1.0.0").as_deref(),
Some("1.2.0-beta.10")
);
assert_eq!(kept(dir.path()), ["beta-1.2.0-beta.10"]);
assert_eq!(check(UpdateChannel::Beta, "1.2.0-beta.10"), None);
assert!(kept(dir.path()).is_empty());
}
#[test]
fn back_to_stable_from_a_newer_beta_waits_for_a_newer_stable() {
let key = key();
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check = |url: &str| {
download_update(
url,
dir.path(),
public,
UpdateChannel::Stable,
"1.2.0-beta.3",
)
.unwrap()
};
let older = vec![
publish(&key, "stable", "1.1.0"),
publish(&key, "beta", "1.2.0-beta.4"),
];
assert_eq!(check(&serve(older, false).0), None);
let newer = vec![
publish(&key, "stable", "1.1.0"),
publish(&key, "stable", "1.2.0"),
];
assert_eq!(check(&serve(newer, false).0).as_deref(), Some("1.2.0"));
}
#[test]
fn a_kept_package_is_verified_again_and_downloaded_again_once_altered() {
let key = key();
let (url, downloads) = serve(vec![publish(&key, "stable", "1.1.0")], false);
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check = || download_update(&url, dir.path(), public, UpdateChannel::Stable, "1.0.0");
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
assert_eq!(downloads.load(Ordering::SeqCst), 1);
let package = dir
.path()
.join("stable-1.1.0/ArenaTracker-1.1.0-stable-full.nupkg");
fs::write(&package, b"altered").unwrap();
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
assert_eq!(downloads.load(Ordering::SeqCst), 2);
assert_eq!(fs::read(&package).unwrap(), b"package 1.1.0");
}
#[test]
fn a_channel_change_discards_the_other_channels_package_even_offline() {
let key = key();
let (url, _) = serve(
vec![
publish(&key, "stable", "1.1.0"),
publish(&key, "beta", "1.2.0-beta.1"),
],
false,
);
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check = |url: &str, channel| download_update(url, dir.path(), public, channel, "1.0.0");
assert!(check(&url, UpdateChannel::Stable).unwrap().is_some());
// A late stable package goes as soon as a beta check starts, before any network access.
let offline = unreachable();
assert!(matches!(
check(&offline, UpdateChannel::Beta),
Err(Error::Source(_))
));
assert!(kept(dir.path()).is_empty());
assert_eq!(
check(&url, UpdateChannel::Beta).unwrap().as_deref(),
Some("1.2.0-beta.1")
);
// Offline, the channel's own pending package stays for a later launch.
assert!(check(&offline, UpdateChannel::Beta).is_err());
assert_eq!(kept(dir.path()), ["beta-1.2.0-beta.1"]);
}
#[test]
fn a_failed_newer_download_keeps_the_older_pending_package() {
let key = key();
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check = |url: &str| download_update(url, dir.path(), public, UpdateChannel::Beta, "1.0.0");
let first = vec![publish(&key, "beta", "1.1.0-beta.1")];
assert!(check(&serve(first, false).0).is_ok());
let newer = || {
vec![
publish(&key, "beta", "1.1.0-beta.1"),
publish(&key, "beta", "1.1.0-beta.2"),
]
};
assert!(check(&serve(newer(), true).0).is_err());
assert_eq!(kept(dir.path()), ["beta-1.1.0-beta.1"]);
let ready = check(&serve(newer(), false).0).unwrap();
assert_eq!(ready.as_deref(), Some("1.1.0-beta.2"));
assert_eq!(kept(dir.path()), ["beta-1.1.0-beta.2"]);
}
#[test]
fn network_and_signature_failures_leave_no_update_ready() {
let key = key();
let other = Ed25519KeyPair::from_seed_unchecked(&[8; 32]).unwrap();
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check =
|url: &str| download_update(url, dir.path(), public, UpdateChannel::Stable, "1.0.0");
assert!(matches!(check(&unreachable()), Err(Error::Source(_))));
let (cut, _) = serve(vec![publish(&key, "stable", "1.1.0")], true);
assert!(check(&cut).is_err());
assert!(kept(dir.path()).is_empty());
let (forged, _) = serve(vec![publish(&other, "stable", "1.1.0")], false);
assert!(matches!(check(&forged), Err(Error::InvalidUpdate(_))));
assert!(kept(dir.path()).is_empty());
let mut altered = publish(&key, "stable", "1.1.0");
altered.files[2].1 = b"package 6.6.6".to_vec();
assert!(matches!(
check(&serve(vec![altered], false).0),
Err(Error::InvalidUpdate(_))
));
assert!(kept(dir.path()).is_empty());
// A release without its signature is not offered at all.
let mut unsigned = publish(&key, "stable", "1.1.0");
unsigned.files.remove(0);
assert_eq!(check(&serve(vec![unsigned], false).0).unwrap(), None);
}
/// Keeps `version` of `channel` in `dir` as a finished download would, and returns its package.
fn keep(dir: &Path, key: &Ed25519KeyPair, channel: &str, version: &str) -> PathBuf {
let folder = dir.join(format!("{channel}-{version}"));
fs::create_dir(&folder).unwrap();
for (name, bytes) in publish(key, channel, version).files {
fs::write(folder.join(name), bytes).unwrap();
}
folder.join(format!("ArenaTracker-{version}-{channel}-full.nupkg"))
}
type Start<'a> = &'a mut dyn FnMut(&Path) -> std::io::Result<u32>;
type Outcome<'a> = &'a mut dyn FnMut(u32) -> Option<u32>;
fn never_started(_: &Path) -> std::io::Result<u32> {
panic!("the installer must not start")
}
fn no_installer(_: u32) -> Option<u32> {
panic!("no installer was started")
}
/// Records each package handed to the installer, which gets process id `pid`.
fn recording(started: &mut Vec<PathBuf>, pid: u32) -> impl FnMut(&Path) -> std::io::Result<u32> {
move |package| {
started.push(package.to_owned());
Ok(pid)
}
}
type Launch = ControlFlow<(), Option<Error>>;
/// The installer replaces this version and opens the app.
fn applying(launch: &Launch) -> bool {
matches!(launch, ControlFlow::Break(()))
}
fn loads_quietly(launch: &Launch) -> bool {
matches!(launch, ControlFlow::Continue(None))
}
fn reports_failed(launch: &Launch, version: &str) -> bool {
matches!(launch, ControlFlow::Continue(Some(Error::UpdateFailed(failed))) if failed == version)
}
#[test]
fn a_launch_hands_the_chosen_channels_package_to_the_installer_once() {
let key = key();
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let stable = keep(dir.path(), &key, "stable", "1.1.0");
keep(dir.path(), &key, "stable", "1.0.1");
// Left from before a change to Stable, until the next check removes it.
let beta = keep(dir.path(), &key, "beta", "1.2.0-beta.1");
let launch = |channel, installed, start: Start, outcome: Outcome| {
update_at_launch(dir.path(), public, channel, installed, start, outcome)
};
let stable_launch =
|start: Start, outcome: Outcome| launch(UpdateChannel::Stable, "1.0.0", start, outcome);
let mut started = Vec::new();
let first = stable_launch(&mut recording(&mut started, 42), &mut no_installer);
assert!(applying(&first), "{first:?}");
assert_eq!(started, [stable]);
// A launch while the installer runs waits for it and leaves the app to the version it opens.
let succeeded = stable_launch(&mut never_started, &mut |pid| (pid == 42).then_some(0));
assert!(applying(&succeeded), "{succeeded:?}");
// After a failure the version in place loads and says so once, then never retries on its own.
let failed = stable_launch(&mut never_started, &mut |_| Some(1));
assert!(reports_failed(&failed, "1.1.0"), "{failed:?}");
let next = stable_launch(&mut never_started, &mut no_installer);
assert!(loads_quietly(&next), "{next:?}");
// « Redémarrer » retries it; an installer that is gone counts as failed.
let restart = restart_to_update(dir.path(), public, UpdateChannel::Stable, "1.0.0", |_| {
Ok(43)
});
assert!(restart.is_ok());
let gone = stable_launch(&mut never_started, &mut |pid| (pid != 43).then_some(0));
assert!(reports_failed(&gone, "1.1.0"), "{gone:?}");
// Once the new version is installed, nothing is left to apply.
let installed = launch(
UpdateChannel::Stable,
"1.1.0",
&mut never_started,
&mut no_installer,
);
assert!(loads_quietly(&installed), "{installed:?}");
// The Bêta channel takes only its own package.
let mut started = Vec::new();
let beta_launch = launch(
UpdateChannel::Beta,
"1.1.0",
&mut recording(&mut started, 44),
&mut no_installer,
);
assert!(applying(&beta_launch), "{beta_launch:?}");
assert_eq!(started, [beta]);
}
#[test]
fn an_altered_package_or_an_installer_that_cannot_start_leaves_the_installed_version() {
let key = key();
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let package = keep(dir.path(), &key, "stable", "1.1.0");
let launch = |start: Start| {
update_at_launch(
dir.path(),
public,
UpdateChannel::Stable,
"1.0.0",
start,
no_installer,
)
};
// Altered between the download and this launch: refused before the installer sees it.
fs::write(&package, b"altered").unwrap();
let refused = launch(&mut never_started);
assert!(
matches!(
refused,
ControlFlow::Continue(Some(Error::InvalidUpdate(_)))
),
"{refused:?}"
);
let restart = restart_to_update(
dir.path(),
public,
UpdateChannel::Stable,
"1.0.0",
never_started,
);
assert!(matches!(restart, Err(Error::InvalidUpdate(_))));
// Downloaded again, then the installer cannot start: reported, and no launch loops on it.
fs::write(&package, b"package 1.1.0").unwrap();
let failed = launch(&mut |_| Err(std::io::ErrorKind::NotFound.into()));
assert!(reports_failed(&failed, "1.1.0"), "{failed:?}");
let next = launch(&mut never_started);
assert!(loads_quietly(&next), "{next:?}");
}
#[test]
fn a_failed_version_is_not_retried_at_launch_but_a_newer_release_is() {
let key = key();
let (url, downloads) = serve(vec![publish(&key, "stable", "1.1.0")], false);
let dir = tempfile::tempdir().unwrap();
let public = key.public_key().as_ref();
let check = || download_update(&url, dir.path(), public, UpdateChannel::Stable, "1.0.0");
let launch = |start: Start, outcome: Outcome| {
update_at_launch(
dir.path(),
public,
UpdateChannel::Stable,
"1.0.0",
start,
outcome,
)
};
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
assert!(applying(&launch(&mut |_| Ok(42), &mut no_installer)));
// Velopack deletes a package it cannot open, then reopens the version in place.
let package = dir
.path()
.join("stable-1.1.0/ArenaTracker-1.1.0-stable-full.nupkg");
fs::remove_file(&package).unwrap();
let failed = launch(&mut never_started, &mut |_| Some(1));
assert!(reports_failed(&failed, "1.1.0"), "{failed:?}");
assert_eq!(check().unwrap().as_deref(), Some("1.1.0"));
assert_eq!(downloads.load(Ordering::SeqCst), 2);
let next = launch(&mut never_started, &mut no_installer);
assert!(loads_quietly(&next), "{next:?}");
// The next release gets its own attempt: the app never stays on the version in place.
let newer = vec![
publish(&key, "stable", "1.1.0"),
publish(&key, "stable", "1.2.0"),
publish(&key, "stable", "1.3.0"),
];
let (url, _) = serve(newer, false);
let ready = download_update(&url, dir.path(), public, UpdateChannel::Stable, "1.0.0");
assert_eq!(ready.unwrap().as_deref(), Some("1.3.0"));
assert_eq!(kept(dir.path()), ["stable-1.3.0"]);
let mut started = Vec::new();
let newest = launch(&mut recording(&mut started, 43), &mut no_installer);
assert!(applying(&newest), "{newest:?}");
let package = dir
.path()
.join("stable-1.3.0/ArenaTracker-1.3.0-stable-full.nupkg");
assert_eq!(started, [package]);
}
@@ -1,26 +0,0 @@
---
status: accepted
---
# Package with Velopack's packer and authenticate updates with our own signed manifest
Arena Tracker installs per user with Velopack 1.2.161 (`scripts/package`), but only its packer is used: the app never calls the Velopack SDK. In that version the SDK's startup path opens cached packages to read their manifests even with auto-apply disabled, and nothing in Velopack checks a package against a project key. Each release therefore carries a manifest signed with the project's Ed25519 key, binding the app, the Windows target, the version, the channel and the source commit to the SHA-256 of one full package. The core's `verify_release` checks it before anything opens the package as an archive. Releases contain full packages only.
Velopack also installs a root launcher, `Arena Tracker.exe`, which runs `Update.exe start`. If the installed manifest is unreadable, that command opens the latest `packages\*.nupkg` to read its manifest, and if an `app-*` folder exists it applies that package without any signature check. Our Start Menu shortcut targets `current\arena-tracker.exe` and never runs the launcher. Both paths need a file written into `%LOCALAPPDATA%\ArenaTracker` by the same Windows account, which could equally replace the app's executable. We accept this residual path (decided on 2026-11-20, as #57 required before adopting Velopack).
The MSVC C runtime is linked statically (`.cargo/config.toml`), so a package ships no `vcruntime140.dll` that would vary with the build machine's Visual Studio redistributable.
## Considered Options
- **Velopack SDK at startup**: automatic updates for free, but it opens unauthenticated local packages before the app can check them.
- **Delete the installer's package copy after each install or update**: leaves the launcher nothing to open, at the cost of altering files Velopack manages; it protects only against a writer who can already replace the app.
- **Our own installer and updater**: no residual path, but a much larger amount of code to write and maintain.
- **Packer only, own signed manifest, accepted launcher path** (chosen).
## Consequences
- The updater must download into a folder outside the installation and Velopack's cache, call `verify_release` there, and hand exactly those verified bytes to Velopack; unverified bytes never enter `%LOCALAPPDATA%\ArenaTracker`, even after an interrupted download.
- Applying runs `Update.exe apply --waitPid <pid> --package <file>` on the file just verified again, which Velopack reads in place. Its folder swap has no rollback: a power cut between its two renames leaves no `current` folder until a reinstall (accepted; `docs/paquets-windows.md`, « Application de la mise à jour »).
- Delta packages stay off (`--delta None`) until their preparation path can be authenticated too.
- Upgrading Velopack means re-reading its startup, locator and install code for new paths that open local packages.
- The private key never enters the repository, the app or the artefacts; only its public key is built into the executable.
@@ -0,0 +1,15 @@
---
status: accepted
---
# Serve community Arena statistics from a backend in v2
The second-screen lists need statistics for the current patch and Format even when the active Account has never played the champion. In v2, a backend will collect a community sample of finished Arena games independently of the desktop app and compute item and Augment statistics from their participants' results. Once the champion is known, the app requests the lists for that champion, patch and Format. We accept the cost of running the service to keep collection off the player's machine and apply the same counting rules to every Match in the sample.
The server continuously discovers finished EUW Arena games through the Riot web API and updates aggregates independently of client requests. Discovery must work without the user's Account. Clients can use aggregates that are several hours old as long as the patch and Format match. Only the desktop app reads live session state from the local League client.
Each option's rates use the observed Matches with that option, and the champion's reference rate uses all observed Matches with that champion on the same patch and in the same Format.
The item list includes every distinct item in the final inventory, including boots, components and prismatic items. The desktop app shows **Objets** on the left and **Améliorations** on the right so both are readable during play. Each list opens **Par tier** and can independently switch to **Les plus joués**.
For v2, trial discovery from periodically renewed groups of EUW ranked accounts across tiers and divisions. Read their Arena histories, expand through participants, and count each game ID once. This can underrepresent groups who play Arena exclusively. Before relying on the sample, measure distinct games per Format and compare champion top 1 rates across independent starting groups. [League-V4](https://developer.riotgames.com/apis#league-v4/GET_getLeagueEntries) · [Match-V5](https://developer.riotgames.com/apis#match-v5/GET_getMatchIdsByPUUID)
-71
View File
@@ -1,71 +0,0 @@
# Spécification de la refonte d’Arena Tracker
## Problème et résultat attendu
Entre deux Parties, le joueur veut repérer les champions avec lesquels il lui manque un top 1. Pendant une sélection Arena, il veut répondre à une question plus précise : « Parmi les champions marqués d’une enclume, lesquels me reste-t-il à valider et lesquels puis-je encore choisir ? » L’écran actuel demande de lire un tableau parmi des compteurs, des filtres et des graphiques.
L’accueil et la sélection doivent donner la réponse avec les mêmes cartes de champion. Une page « Statistiques » accueille l’analyse détaillée. La référence visuelle est la maquette validée, avec ses portraits verticaux allongés, son compteur discret et son trait de progression fin. L’interface reste en français et garde sa propre identité visuelle. [Ouvrir la maquette interactive](prototype-interface.html)
## Critères d’acceptation
### Accueil et tri
1. À chaque ouverture, « Tous » est sélectionné. La grille présente tous les champions, y compris ceux jamais joués et ceux déjà validés. La recherche par nom et les filtres « Restants » et « Validés » permettent de réduire la grille.
2. À côté du titre, une seule ligne de texte indique le nombre de champions validés sur le total du Défi de la saison. Un trait fin sous le compteur matérialise la progression. Le total reste celui du Défi quand on recherche un champion, filtre la grille ou passe en sélection.
3. Lorsqu’aucune préférence de tri n’a encore été enregistrée, les champions sont classés par points de maîtrise décroissants. Le joueur peut choisir A–Z. Le même choix s’applique aux deux écrans et à leurs différentes sections, puis à la prochaine ouverture.
### Carte de champion
Les trois marques portent sur le Défi d’un Compte pour une Saison, tous Formats Arena confondus. Deux coches en bas du portrait, « Joué » et « Victoire », montrent les deux premières marques. Le premier top 1 valide le champion. Hors indisponibilité en sélection, la carte se lit ainsi :
| Historique du champion sur la saison | Joué | Victoire | Portrait |
| --- | --- | --- | --- |
| Aucune Partie | Non | Non | En couleur |
| A joué, aucune Victoire | Oui | Non | En couleur |
| A remporté une Victoire, meilleur Placement de 2ᵉ par exemple | Oui | Oui | En couleur |
| A terminé premier au moins une fois | Oui | Oui | Grisé, « Validé » |
Une seule Partie peut donner les trois marques. Une 2ᵉ place en Arena 3×6 donne la coche « Victoire » et laisse le champion dans « Restants ».
Au survol ou au focus clavier, la fiche du champion affiche ses Parties, ses Victoires, son meilleur Placement, ses Tentatives et ses points de maîtrise. Pour un champion validé, elle affiche aussi **la date du premier top 1 de la saison**. Un top 1 ultérieur conserve cette date. Les Tentatives s’arrêtent à la Partie de validation incluse.
### Pendant la sélection Arena
1. La détection d’une sélection Arena affiche automatiquement la rangée de cartes dans la fenêtre existante, sous la progression de saison. Le joueur garde le focus dans League : une fenêtre réduite ou cachée dans la zone de notification se rouvre à l’entrée en sélection, sans prendre le focus, et reste ouverte à la fin de la sélection. Ce comportement n’a pas de réglage.
2. La rangée « Champions de l’Enclume » contient **tous** les champions marqués d’une enclume dans la sélection en cours, dans le tri choisi. Au-dessous, « Autres champions » est replié par défaut. L’ouvrir affiche tous les champions sans enclume, avec le même tri et les mêmes cartes. Sa recherche par nom filtre uniquement cette section.
3. Dans les deux sections, les cartes gardent leur place lorsqu’un champion est validé, banni ou pris par un allié. Son portrait est grisé et la carte indique les raisons applicables : « Validé », « Banni », « Pris par un allié ». Un champion validé et banni porte les deux indications.
4. Une présélection alliée laisse la carte dans son état courant. « Pris par un allié » apparaît à la confirmation du choix. Les bans et les choix alliés expirent avec la sélection : ils n’affectent ni les coches personnelles, ni le compteur du Défi, ni la sélection suivante.
### Page « Statistiques »
Pour une Saison, présenter d’abord la courbe cumulée des champions validés, puis la répartition des Placements et les Tentatives nécessaires pour valider un champion. Réutiliser les statistiques existantes et conserver la consultation par Compte, Saison et Format. Dans « Toutes les Saisons », seules les statistiques qui ont un sens sur cette période s’appliquent. Le Défi reste propre à une Saison.
## Décisions d’implémentation
- L’application cible reste l’application Windows native en GPUI via gpui-kit. L’accueil et la sélection réutilisent une seule représentation de carte. La logique de progression provient des Parties enregistrées, y compris pour les données antérieures à la refonte. La Progression officielle sert au contrôle du total.
- Le calcul du Défi détermine déjà la première Partie de Placement 1 par ordre chronologique. Exposer sa date à la fiche du champion et employer la même convention de date que la courbe de progression. Les marques saisonnières restent indépendantes du filtre de Format des statistiques.
- Conserver le comportement existant de la recherche de champions, des préférences et du suivi de Compte. Le client League reste une source en lecture seule. Les données de sélection sont temporaires : leur disparition laisse l’historique enregistré consultable.
- Réutiliser le suivi de sélection Arena livré avec le ticket #13. Il lit déjà les Champions de l’Enclume, les bans et les choix alliés, puis regroupe les champions exclus pour déterminer lesquels sont disponibles. Transmettre à la carte le motif précis du grisé et actualiser son libellé lorsque ce motif change.
- Respecter les budgets existants : réagir aux événements du client, limiter le travail aux portraits affichés, garder les chargements en arrière-plan à basse priorité. Le survol d’une carte doit pouvoir afficher ses données sans relire l’historique ni recalculer les graphiques. Le benchmark complet relève du contrôle de version majeure. [Budgets et méthode de mesure](performance.md)
## Données à confirmer et propositions de repli
| Dépendance | Ce qu’il reste à établir | Proposition si la donnée manque |
| --- | --- | --- |
| Liste des Champions de l’Enclume indisponible | Le suivi actuel accepte une liste absente ou vide. Déterminer si le client permet de distinguer ces deux situations dans les données reçues. | Garder la collection consultable et signaler sobrement l’information indisponible. Une liste inconnue ne suffit pas pour classer tous les champions « sans enclume ». |
| Points de maîtrise | Le tracker ne les récupère pas encore. Vérifier la source par Compte et la disponibilité hors ligne. | Utiliser les dernières valeurs connues. À défaut, proposer A–Z temporairement en conservant la préférence du joueur. Une valeur inconnue reste distincte de zéro. |
Ces replis sont des propositions de développement. La maquette illustre les états connus avec douze champions fictivement suivis.
## Vérification
| Comportement à vérifier | Scénario et point d’appui existant |
| --- | --- |
| Marques, date et compteur | Étendre les tests de statistiques sur Parties enregistrées. Importer deux top 1 dans le désordre avec une Victoire antérieure. Vérifier la première date, les Tentatives et une seule validation. Changer de Format, de Saison puis de Compte pour vérifier la portée du Défi. |
| Grille et tri | Prolonger les tests d’interface qui saisissent une recherche et vérifient les champions affichés. Combiner alias, filtres, tri et passage en sélection. Rouvrir avec les mêmes préférences : « Tous » revient et le tri choisi persiste. |
| Sélection en direct | Rejouer la capture Arena 3×6 déjà utilisée pour tester les enclumes, les bans, la présélection et la confirmation. Vérifier les deux sections, les motifs de grisé et l’ordre stable. Sortir puis entrer dans une autre sélection pour vérifier le nettoyage des états temporaires. Une sélection hors Arena garde le comportement existant. |
| Interaction et résilience | Dans les tests GPUI, déplier « Autres champions » et rechercher un nom : la rangée des enclumes reste intacte. Vérifier la présence de la date sur la fiche d’un champion validé et son absence sur celle d’un champion restant, au clavier comme au survol. Reprendre les tests d’isolation du rendu des graphiques et les cas de client absent ou de portrait manquant. Sous Windows, vérifier la bascule avec League au premier plan puis avec le tracker réduit. |
## Hors périmètre
Les nouveaux indicateurs statistiques feront l’objet d’un autre ticket. La Renommée, les actions de sélection ou de ban dans League et le bouton « Simuler la sélection » de la maquette sont exclus de la version native.
-66
View File
@@ -1,66 +0,0 @@
# Installateur et paquets de mise à jour Windows x64
Pour installer Arena Tracker, ouvrir `ArenaTracker-stable-Setup.exe` ou `ArenaTracker-beta-Setup.exe` puis utiliser **Arena Tracker** dans le menu Démarrer. Les deux canaux utilisent la même installation par utilisateur, dans `%LOCALAPPDATA%\ArenaTracker`. Windows peut la supprimer depuis **Applications installées**. La configuration, la clé Riot, les Parties et les Saisons restent dans `%APPDATA%\arena-tracker` pour le prochain lancement, y compris après réinstallation.
## Construire une version
Sur le poste de build, installer les prérequis de `scripts/prod` (Rust MSVC x64 et Visual Studio), le runtime .NET 10 pour Windows, et disposer de Python 3.11+, Git, tar et OpenSSL 3 côté WSL. Télécharger une fois l’archive officielle de vpk 1.2.161. La commande vérifie son SHA-256 avant de l’exécuter. [Archive vpk 1.2.161](https://github.com/velopack/velopack/releases/download/1.2.161/vpk.1.2.161.nupkg)
Depuis la racine du dépôt, utiliser la version du script correspondant au commit souhaité. Les deux variables contiennent des **chemins WSL**. Conserver la même clé privée Ed25519 pour les publications successives des deux canaux. Provisionner ce fichier hors dépôt, accessible uniquement au compte de signature. Une clé de test se crée par exemple avec `(umask 077 && openssl genpkey -algorithm ED25519 -out ~/arena-test-only.pem)`.
```bash
export VPK_NUPKG=~/outils/vpk.1.2.161.nupkg
export ARENA_SIGNING_KEY=~/cles/arena-release.pem
scripts/package "$(git rev-parse HEAD)" 1.1.0-beta.2 beta ../sorties/1.1.0-beta.2
```
Pour la stable, remplacer les trois derniers arguments par `1.1.0 stable ../sorties/1.1.0`. Le script exporte les sources du commit, compile via `scripts/prod build` et prépare le dossier de sortie à neuf. La version complète figure dans les propriétés de l’exécutable Windows. Seules la clé publique et l’identité de la version entrent dans l’application. Le dossier demandé apparaît après vérification par l’exécutable construit. `scripts/publish-beta` s’en sert pour publier les bêtas ([publication](publication.md)).
## Contrat pour le client de mise à jour
Chaque Release contient quatre fichiers. Pour la stable de l’exemple :
| Fichier | Utilisation |
| --- | --- |
| `ArenaTracker-stable-Setup.exe` | Première installation |
| `release-stable.json` | Manifeste UTF-8, 4 Kio maximum |
| `release-stable.sig` | Signature Ed25519 brute de 64 octets sur le fichier JSON exact, retour à la ligne compris |
| `ArenaTracker-1.1.0-stable-full.nupkg` | Paquet complet dont le SHA-256 est signé via le manifeste |
Le manifeste lie `app` (`ArenaTracker`), `target` (`win-x64`), `version`, `channel`, `commit`, `package` et `sha256` (Base64 standard du condensat binaire). Le canal vaut `stable` pour `X.Y.Z`, ou `beta` pour `X.Y.Z-beta.N`, avec N positif. Les noms des fichiers bêta suivent la même règle, par exemple `ArenaTracker-1.1.0-beta.2-beta-full.nupkg`.
Télécharger les octets dans un dossier isolé hors de l’installation et du cache Velopack. Vérifier la signature avec la clé publique embarquée, l’identité attendue, puis le condensat du paquet entier avant de l’ouvrir comme archive. Conserver ces mêmes octets jusqu’à l’application et revérifier un paquet conservé entre deux lancements. Le cœur fournit `verify_release(dossier, clé, canal, version)`, qui applique aussi les tailles maximales et les noms de fichiers ci-dessus. Pour contrôler un jeu d’artefacts avec le binaire de **cette** version, exécuter `arena-tracker.exe --verify-release <dossier>` et vérifier le code de sortie (0 pour la réussite). Les tests du contrat utilisent une clé jetable avec `cargo test --locked -p arena-tracker-core --test update_package`, nativement sous WSL.
## Recherche et téléchargement dans l’application
Le joueur choisit **Stable** ou **Bêta** dans les **Paramètres** (`update_channel` dans `config.toml`). Tant qu’aucun choix n’est enregistré, le canal de la version installée s’applique : Bêta après l’installateur bêta, Stable sinon. Ni une installation ni une mise à jour ne modifie un choix enregistré. Une version de production vérifie son canal une fois par démarrage effectif, puis après chaque changement de canal, sur un seul fil de priorité inférieure à la normale. Elle interroge sans authentification `https://gitea.nessar.fr/api/v1/repos/nessar/arena-tracker/releases?draft=false&pre-release=<bêta>&limit=10`. Une bêta doit donc être publiée comme préversion. Le dépôt est public depuis le 2026-11-20 : aucun compte ni jeton n’est nécessaire. Les versions de développement ne recherchent rien.
Une Release compte seulement si elle contient les trois fichiers du canal. La plus haute version strictement supérieure à la version installée l’emporte (`1.1.0-beta.2` < `1.1.0-beta.10` < `1.1.0`). Le canal Stable ne reçoit jamais de bêta et le canal Bêta jamais de stable. Revenir à Stable depuis une bêta plus récente attend donc une stable plus récente, ce que les Paramètres expliquent.
Les fichiers sont téléchargés dans `%LOCALAPPDATA%\arena-tracker\updates\partial` : 256 Mio au plus par fichier, échec après 30 s sans données. `verify_release` les contrôle, puis le dossier est renommé `<canal>-<version>`. Seulement alors, un bouton « Mise à jour prête » apparaît dans la barre de titre ; il ouvre les Paramètres, qui indiquent la version et proposent « Redémarrer ». Le dossier `updates` ne conserve ensuite que ce paquet ; un paquet plus ancien du même canal reste en place jusque-là. Dès le début de la vérification suivante, avant tout accès réseau, il supprime le paquet de l’autre canal. Sans réseau, il conserve celui du canal choisi. Un paquet conservé est revérifié, et non téléchargé à nouveau. Un paquet de l’autre canal, téléchargé tardivement ou verrouillé, peut rester jusqu’à cette vérification ; l’application ne le prend jamais.
## Application de la mise à jour
« Redémarrer », dans les Paramètres, et le lancement qui suit « Quitter » appliquent le même paquet : le dossier du canal choisi dont la version dépasse la version installée, vérifié de nouveau par `verify_release`. L’application lance alors, depuis la racine de l’installation, `Update.exe apply --waitPid <pid> --package <paquet>` sur le fichier qui vient d’être vérifié dans `%LOCALAPPDATA%\arena-tracker\updates`, puis se ferme comme avec « Quitter », sans passer par la zone de notification. Velopack 1.2.161 lit ce fichier sur place, sans le copier dans `packages`. Il attend la fin du processus (60 s au plus, puis il arrête tout programme lancé depuis l’installation), extrait le paquet, remplace `current` et ouvre une seule fois la nouvelle version, ou de nouveau l’ancienne en cas d’échec. Il affiche sa fenêtre de progression et journalise dans `%LOCALAPPDATA%\velopack\velopack_ArenaTracker.log`. [Commande apply](https://github.com/velopack/velopack/blob/1.2.161/src/bins/src/commands/apply.rs) · [Remplacement sous Windows](https://github.com/velopack/velopack/blob/1.2.161/src/bins/src/commands/apply_windows_impl.rs)
Au lancement, cette décision suit l’élection de l’instance unique et précède toute fenêtre. Un raccourci lancé pendant qu’Arena Tracker tourne, visible, réduit ou caché dans la zone de notification, ramène seulement sa fenêtre (#50) : ni second suivi, ni recherche, ni installation. Avant de lancer `Update.exe`, l’application crée `<canal>-<version>.attempt` à côté du dossier du paquet, puis y inscrit l’identifiant du processus. Ce fichier survit à un nouveau téléchargement de la même version. Un lancement qui le trouve ne relance jamais l’installation lui-même ; seule une version plus récente repart de zéro. Si ce processus `Update.exe` tourne encore (lancement rapproché, ou ancienne version rouverte par Velopack après un échec), il attend sa fin, 3 min au plus. Un code de sortie 0 laisse la place à la version que Velopack ouvre ; sinon l’application s’ouvre dans sa version actuelle et signale l’échec une fois, dans un bandeau. « Redémarrer » permet de réessayer. Un paquet altéré depuis son téléchargement est refusé et signalé ; la vérification suivante le télécharge de nouveau. Si la configuration est illisible, le canal choisi est inconnu et rien n’est appliqué.
Les Parties sont écrites une à une dans SQLite en mode WAL, et la configuration est écrite à côté puis renommée. Un arrêt pendant un import ne laisse donc ni Partie corrompue ni configuration partielle ; l’import suivant reprend les Parties manquantes.
Limites acceptées de Velopack 1.2.161 : son remplacement n’a pas de retour arrière. `current` est renommé, puis le dossier extrait prend sa place. Une coupure entre ces deux renommages, ou un fichier extrait verrouillé plus de 30 s, laisse l’installation sans `current` ; une réinstallation la répare et les données de `%APPDATA%\arena-tracker` restent intactes. Un fichier verrouillé dans `current` fait au contraire échouer le premier renommage, et l’ancienne version reste en place. Velopack supprime aussi le paquet qu’il ne parvient pas à ouvrir ; la vérification suivante le télécharge de nouveau. Entre la vérification et la lecture par `Update.exe`, seul un programme du même compte Windows peut remplacer le paquet, et ce compte peut tout aussi bien remplacer l’exécutable ([ADR-0005](adr/0005-package-with-velopack-and-our-own-signed-manifest.md)).
## Validation du chemin de démarrage
L’essai Windows de vpk 1.2.161 a installé une application témoin sous un jeton non élevé. Le raccourci créé par le packer ciblait directement `current\Trial.exe` et a ouvert cette application même avec le paquet local verrouillé en accès exclusif. La désinstallation a ensuite supprimé le raccourci.
Dans le SDK Rust de cette version, `set_auto_apply_on_startup(false)` laisse actif `find_local_full_packages`, qui ouvre les archives locales pour lire leurs manifestes. Arena Tracker utilise seulement le packer. Ses quatre callbacks d’installation, de remplacement et de désinstallation sortent avant GPUI. Son démarrage normal n’appelle aucun gestionnaire de paquets. Le raccourci du menu Démarrer cible directement `current\arena-tracker.exe`. Le lanceur `Arena Tracker.exe` placé à la racine de l’installation lance `Update.exe start` : si le manifeste installé est illisible, celui-ci ouvre le dernier `packages\*.nupkg` pour lire son manifeste, et si un dossier `app-*` existe, il applique ce paquet sans vérification. L’installateur copie son propre paquet dans `packages`. Ces deux chemins demandent une écriture dans le dossier d’installation par le même compte Windows ; ce risque est accepté et motivé dans l’[ADR-0005](adr/0005-package-with-velopack-and-our-own-signed-manifest.md). [Démarrage par le stub](https://github.com/velopack/velopack/blob/1.2.161/src/bins/src/commands/start_windows_impl.rs) Pour appliquer une mise à jour, fournir explicitement le paquet authentifié et garder tout téléchargement hors du cache, y compris après interruption. Les publications contiennent exclusivement des paquets complets (`--delta None`). [Démarrage du SDK](https://github.com/velopack/velopack/blob/1.2.161/src/lib-rust/src/app.rs) · [Lecture des paquets locaux](https://github.com/velopack/velopack/blob/1.2.161/src/lib-rust/src/locator.rs) · [Raccourcis Windows](https://github.com/velopack/velopack/blob/1.2.161/src/bins/src/windows/shortcuts.rs)
La recette avec les exécutables de production a enchaîné installation de la stable 1.0.0, ouverture, désinstallation puis installation de la 1.1.0-beta.2 sous le même compte non élevé. Les deux fenêtres ont affiché le Compte de test, sa Saison personnalisée et sa Victoire avec Ahri. Le contenu de la configuration (clé Riot fictive incluse) et de la table des Saisons était identique après chaque désinstallation.
Le runtime C de Visual C++ est lié statiquement dans l’exécutable (`.cargo/config.toml`) : le paquet ne contient aucune DLL et l’application ne dépend que des bibliothèques de Windows.
Le 2026-11-20, la 1.0.0 stable construite par `scripts/package` (commit `611a19c`, clé de test) a été installée en mode silencieux sous un jeton non élevé (niveau Medium). Le raccourci **Arena Tracker** du menu Démarrer a ouvert `current\arena-tracker.exe`, qui affichait le Compte, la Saison et les Parties existants. Après désinstallation, puis réinstallation et nouvelle ouverture par le raccourci, puis nouvelle désinstallation, `config.toml` et `seasons.toml` étaient identiques octet pour octet et la base passait `integrity_check` avec les mêmes Parties. La désinstallation a retiré le dossier d’installation, le raccourci et l’entrée **Applications installées**. L’exécutable n’importe que des bibliothèques de Windows (aucune `VCRUNTIME140.dll` ni `api-ms-win-crt-*`). Faute de Windows Sandbox, aucun poste sans Visual Studio n’a été essayé. `arena-tracker.exe --verify-release` accepte le dossier produit et refuse une copie dont un bit du paquet est inversé (« Mise à jour refusée : condensat du paquet différent. »).
## Signature reconnue par Windows
Sur le poste de validation, le magasin personnel du compte ne contenait aucun certificat de signature de code avec clé privée. `Get-AuthenticodeSignature` a renvoyé `NotSigned` sur l’installateur. Une distribution avec éditeur vérifié demande un certificat approuvé ou un compte Microsoft Artifact Signing et un horodatage. Le comportement de SmartScreen sur un installateur téléchargé n’a pas été observé ; un installateur non signé peut déclencher un avertissement. La signature Ed25519 des mises à jour est vérifiée par Arena Tracker. [Options de signature Windows](https://learn.microsoft.com/en-us/windows/apps/package-and-deploy/code-signing-options)
-339
View File
@@ -1,339 +0,0 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Arena Tracker · Maquette interactive</title>
<!-- Maquette autonome : comparer la lisibilité de la même carte sur les deux écrans. -->
<style>
:root {
color-scheme: dark;
font: 15px/1.45 Inter, "Segoe UI Variable Text", "Segoe UI", system-ui, sans-serif;
--bg: #121318; --surface: #1a1b22; --line: #32343f; --text: #f3f2f8;
--soft: #b4b4c3; --accent: #c1afff; --ink: #201732;
}
* { box-sizing: border-box }
body { margin: 0; background: var(--bg); color: var(--text) }
button, input, select { font: inherit }
button, select, summary { cursor: pointer }
button, input, select { color: inherit }
button { background: none; border: 0 }
:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px }
[hidden] { display: none !important }
.wrap { width: min(1264px, 100%); margin-inline: auto; padding-inline: clamp(16px,4.6vw,66px) }
header { background: #17181e; border-bottom: 1px solid var(--line) }
.topbar, .brand, nav, .mode, .progress-meta, .collection-head, .tools, .search,
.sort, .marks, .mark, .reason, .detail-line, footer .wrap { display: flex; align-items: center }
.topbar { gap: 40px; min-height: 64px }
.brand { gap: 10px; white-space: nowrap; font-weight: 740; font-size: 18px; letter-spacing: -.7px }
.brand img { width: 27px; height: 27px }
nav { gap: 4px }
nav button { border-radius: 7px; padding: 8px 14px; color: var(--soft); font-size: 13px; font-weight: 600 }
nav button[aria-current=page] { color: #eee9ff; background: #34303f }
nav button:hover, .mode:hover { color: white; background: #30313a }
.mode { margin-left: auto; gap: 8px; justify-content: center; padding: 8px 12px; border: 1px solid #454551; border-radius: 7px; font-size: 12px; font-weight: 600 }
.mode[aria-pressed=true] { color: var(--accent); border-color: #76678f }
.icon { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; flex: none }
main { min-height: calc(100vh - 130px); padding-block: 35px 22px }
.season { color: var(--soft); font-size: 12px }
.progress-meta { justify-content: space-between; gap: 14px; flex-wrap: wrap; margin-top: 3px }
h1,h2,h3,p { margin: 0 }
h1 { font-size: clamp(25px,2.5vw,32px); font-weight: 650; line-height: 1.15; letter-spacing: -.045em }
h2 { font-size: 23px; font-weight: 650; line-height: 1.25; letter-spacing: -.045em }
.total { color: var(--soft); font-size: 12px; white-space: nowrap; font-variant-numeric: tabular-nums }
.total strong { color: var(--text); font-weight: 600 }
progress { display: block; appearance: none; width: 100%; height: 2px; margin-top: 5px; border: none; border-radius: 2px; background: #3b3a46; overflow: hidden }
progress::-webkit-progress-bar { background: #3b3a46 }
progress::-webkit-progress-value { background: var(--accent); border-radius: 10px }
progress::-moz-progress-bar { background: var(--accent); border-radius: 10px }
.collection-head { margin-block: 28px 16px; justify-content: space-between; flex-wrap: wrap; gap: 12px }
h2 .count { vertical-align: middle; display: inline-block; margin-left: 5px; padding: 2px 7px; border: 1px solid var(--line); border-radius: 6px; color: var(--soft); font-size: 12px; font-weight: 550; letter-spacing: normal }
.tools { gap: 8px; flex-wrap: wrap }
.search, .sort, .tabs { min-height: 34px; background: var(--surface); border: 1px solid var(--line); border-radius: 7px }
.search,.sort { gap: 7px; padding-inline: 10px; color: var(--soft) }
.search:focus-within,.sort:focus-within { border-color: var(--accent) }
input, select { background: transparent; outline: none; border: 0; font-size: 12px }
input { width: 140px; padding: 7px 0; color: var(--text) }
input::placeholder { color: var(--soft) }
select { cursor: pointer; color: var(--text); padding-block: 6px }
option { background: var(--surface) }
.tabs { display: flex; align-items: stretch; padding: 2px }
.tabs button { font-size: 12px; border-radius: 4px; padding: 3px 9px; color: var(--soft) }
.tabs button[aria-pressed=true] { background: #373640; color: white }
.grid { display: grid; grid-template-columns: repeat(6,minmax(0,1fr)); gap: 14px }
.card { position: relative; isolation: isolate; display: block; text-align: left; padding: 0; width: 100%; aspect-ratio: .68; background: #252631; border: 1px solid #393a43; border-radius: 10px; overflow: hidden }
.card:hover,.card:focus-visible,.card.pinned { border-color: var(--accent) }
.card img,.shade,.card-info { position: absolute; inset: 0; width: 100%; height: 100% }
.card img { object-fit: cover; object-position: 50% 24%; z-index: -2 }
.card.dim img { filter: grayscale(1) brightness(.72) }
.shade { z-index: -1; background: linear-gradient(to bottom,rgba(12,13,21,.04) 35%,rgba(10,11,18,.3) 55%,rgba(10,11,18,.95) 90%) }
.reason-stack { position: absolute; top: 9px; left: 8px; right: 8px; display: flex; align-items: flex-start; flex-wrap: wrap; gap: 3px }
.reason { width: fit-content; max-width: 100%; gap: 4px; padding: 3px 6px; border-radius: 4px; background: #202027ee; color: #f0eff3; font-size: 10px; font-weight: 650 }
.reason .icon { width: 12px; height: 12px }
.caption { position: absolute; left: 12px; right: 8px; bottom: 12px }
.name { display: block; color: #fff; font-size: clamp(16px,1.5vw,21px); font-weight: 670; letter-spacing: -.035em; line-height: 1.18 }
.marks { margin-top: 7px; flex-wrap: wrap; gap: 4px 10px }
.mark { gap: 4px; font-size: 10px; font-weight: 600; color: #cdccd4 }
.mark.on { color: #dfd4ff }
.mark .dot { display: inline-grid; place-items: center; width: 11px; height: 11px; border-radius: 50%; border: 1px solid #acaab7 }
.mark.on .dot { background: #c4b3fc; border-color: #c4b3fc; color: var(--ink) }
.dot .icon { width: 8px; height: 8px; stroke-width: 3 }
.card-info { display: none; padding: 12px; flex-direction: column; justify-content: center; background: #16161ef5; font-size: 12px; pointer-events: none }
.card-info strong { font-size: 17px; margin-bottom: 10px; letter-spacing: -.035em }
.detail-line { justify-content: space-between; gap: 4px; padding-block: 2px; color: var(--soft) }
.detail-line b { color: white; font-weight: 600 }
.card.pinned .card-info,.card:focus-visible:not(.dismissed) .card-info { display: flex }
@media (hover:hover) { .card:hover:not(.dismissed) .card-info { display: flex } }
details { margin-top: 22px; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line) }
summary { display: flex; align-items: center; gap: 9px; min-height: 51px; font-weight: 600; list-style: none }
summary::-webkit-details-marker { display: none }
summary .icon { color: var(--soft) }
details[open] summary .icon { transform: rotate(90deg) }
details .search { width: fit-content; margin-block: 2px 14px }
details .grid { margin-bottom: 18px }
.empty { color: var(--soft); grid-column: 1/-1; padding: 30px 0 }
#stats { padding-top: 27px }
.chart-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; margin-top: 14px }
.chart { border: 1px solid var(--line); border-radius: 12px; background: var(--surface); padding: 20px }
.chart h2 { font-size: 18px }
.chart svg { display: block; width: 100%; height: 120px; margin-top: 18px }
.chart svg text { font: 12px system-ui; fill: var(--soft) }
.bars { display: flex; align-items: end; gap: 12px; margin-top: 18px }
.bar-col { flex: 1; display: grid; justify-items: center; gap: 4px; font-size: 12px; color: var(--soft) }
.bar { width: min(36px,75%); height: var(--height); background: #ae9acb; border-radius: 3px 3px 0 0 }
footer .wrap { justify-content: space-between; padding-block: 14px 22px; color: #a5a5b5; font-size: 11px; gap: 12px }
@media(max-width:1000px) { .grid { grid-template-columns: repeat(4,minmax(0,1fr)) } .topbar { gap: 22px } }
@media(max-width:720px) { .grid { grid-template-columns: repeat(3,minmax(0,1fr)); gap: 10px } .chart-grid { grid-template-columns: 1fr } .topbar { flex-wrap:wrap; gap: 4px 12px; padding-block: 10px } nav { order: 2; width: 100% } main { padding-top: 18px } .progress-meta { align-items:flex-start; flex-direction:column; gap:6px } }
@media(max-width:480px) { .grid { grid-template-columns: repeat(2,minmax(0,1fr)) } .tools { width:100% } .caption { left:9px } .topbar .mode { font-size:11px; padding:7px 9px } }
</style>
</head>
<body>
<header><div class="wrap topbar">
<span class="brand"><img alt="" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTYgMjU2IiB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiI+CiAgPCEtLSBUaGUgQXJlbmEgc2VlbiBmcm9tIGFib3ZlOiBhIHJpbmcuIFRoZSBnb2xkIHJpbSBrZWVwcyB0aGUgZGlzYyB2aXNpYmxlIG9uIGRhcmsgYmFja2dyb3VuZHMuIC0tPgogIDxjaXJjbGUgY3g9IjEyOCIgY3k9IjEyOCIgcj0iMTI0IiBmaWxsPSIjZjViODNkIi8+CiAgPGNpcmNsZSBjeD0iMTI4IiBjeT0iMTI4IiByPSIxMDAiIGZpbGw9IiMxNjFiMmUiLz4KICA8IS0tIEEgdG9wIDE6IGEgY3Jvd24sIGluIG9uZSBzb2xpZCBzaGFwZSBzbyB0aGF0IGl0IHN1cnZpdmVzIGF0IDE2IHBpeGVscy4gLS0+CiAgPHBhdGggZmlsbD0iI2Y1YjgzZCIgZD0iTTY4IDE4NiBMNTIgODYgTDk4IDEyNiBMMTI4IDY2IEwxNTggMTI2IEwyMDQgODYgTDE4OCAxODYgWiIvPgo8L3N2Zz4K">Arena Tracker</span>
<nav aria-label="Navigation principale"><button id="homeTab" aria-current="page">Défi</button><button id="statsTab">Statistiques</button></nav>
<button class="mode" id="simulate" aria-pressed="false"><span aria-hidden="true">⇄</span> <span id="modeLabel">Simuler la sélection</span></button>
</div></header>
<main class="wrap">
<section aria-labelledby="title">
<div class="season">Saison 2 · 2026</div>
<div class="progress-meta"><h1 id="title">Défi de saison</h1>
<div class="total"><strong id="fraction"></strong> champions validés
<progress id="progress" aria-label="Champions validés cette saison"></progress>
</div>
</div>
</section>
<section id="collection" aria-labelledby="collectionTitle">
<div class="collection-head">
<h2 id="collectionTitle"><span id="heading">Mes champions</span> <span class="count" id="visibleCount"></span></h2>
<div class="tools">
<label class="search" id="homeSearchBox"><span data-icon="search"></span><input id="homeSearch" type="search" aria-label="Rechercher dans mes champions" placeholder="Rechercher…"></label>
<div class="tabs" id="filters" role="group" aria-label="État du Défi"><button data-filter="Tous" aria-pressed="true">Tous</button><button data-filter="Restants" aria-pressed="false">Restants</button><button data-filter="Validés" aria-pressed="false">Validés</button></div>
<label class="sort"><span data-icon="sort"></span><select id="sort" aria-label="Trier les champions"><option value="mastery">Maîtrise</option><option value="name">A–Z</option></select></label>
</div>
</div>
<div class="grid" id="primary"></div>
<details id="others" hidden>
<summary><span data-icon="chevron"></span>Autres champions</summary>
<label class="search"><span data-icon="search"></span><input id="otherSearch" type="search" aria-label="Rechercher dans les autres champions" placeholder="Rechercher…"></label>
<div class="grid" id="secondary"></div>
</details>
</section>
<section id="stats" hidden aria-label="Statistiques de la saison">
<article class="chart"><h2>Champions validés au fil de la saison</h2><div id="trend"></div></article>
<div class="chart-grid"><article class="chart"><h2>Répartition des placements</h2><div class="bars" id="placements"></div></article><article class="chart"><h2>Tentatives pour valider</h2><div class="bars" id="attempts"></div></article></div>
</section>
</main>
<footer><div class="wrap"><span>Maquette interactive · Données fictives</span><span>Illustrations Riot Games</span></div></footer>
<script>
// Ressources embarquées pour ouvrir la maquette hors ligne.
const portraits = {
"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+VaZezV/4BbkEuoc0aipq6wtOyB3BOSKzuMS7EEpQuoi28cUE+wcwvchIBajRnajUmQYfuKFpY1lje0bjOf1jmr+aZwzoiQw6F4dHFd12NQPN+5i1gbukErIuiPrEegfcMIWe7PuydJfoYtlZQK8Bj4aHmOvqcse9fXgdZuS3FBt3hvK6BK39fnzhsF6Zmo22qO1S9WrWzPDhx/z5DY0W+psF3jcA3oiaU8TWOzK95x/J5malvm7en8B3XeJtTciSCHMbcVyvS8ypK2L7XgxgpaZBlC8mY/txelnMMgOYAB7JoTnVA/hrp8Q+QARPZ9KFCV1DyWv30C1LZ3js94Y20r5ZC9TjFFKNcql9qtabaiLDh9qFEhuzq4wA5PJNFQAeaYatzA5RtQe3FrRCiYzU5mFVAfxH2AbbjeuBm1x6937mul6+gV1zxvZsWC6QsGanXienHrIiQzIT+k1fpF/YqhmHwtvLibbfPdLine truncated
};
const paths = {
search: '<circle cx="10.5" cy="10.5" r="6.5"/><path d="m16 16 5 5"/>',
sort: '<path d="M4 6h16M4 12h11M4 18h6"/>',
chevron: '<path d="m9 5 7 7-7 7"/>',
check: '<path d="m4 12 5 5L20 6"/>',
ban: '<circle cx="12" cy="12" r="9"/><path d="m6 6 12 12"/>',
ally: '<circle cx="12" cy="8" r="3"/><path d="M5 20v-2c0-6 14-6 14 0v2"/>'
};
function icon(key) { return '<svg class="icon" aria-hidden="true" viewBox="0 0 24 24">' + paths[key] + '</svg>'; }
document.querySelectorAll('[data-icon]').forEach(el => el.replaceWith(document.createRange().createContextualFragment(icon(el.dataset.icon))));
// Parties fictives en Arena 3×6. Les nombres sont les placements, du plus ancien au plus récent.
const matchDates = ['14 nov. 2026', '15 nov. 2026', '16 nov. 2026', '17 nov. 2026'];
const champions = [
{name:'Ahri', mastery:280400, matches:[5,3,2], anvil:true},
{name:'Ekko', mastery:248100, matches:[2,1,5], anvil:true},
{name:'Leona', mastery:205000, matches:[4,6], anvil:true, unavailable:'Banni'},
{name:"Kog’Maw", key:'KogMaw', mastery:180300, matches:[3,2,4], anvil:true},
{name:'Akali', mastery:144600, matches:[], anvil:true, unavailable:'Pris par un allié'},
{name:'Jhin', mastery:121800, matches:[5], anvil:true},
{name:'Ashe', mastery:115200, matches:[1,3]},
{name:'Diana', mastery:108900, matches:[5,2]},
{name:'Miss Fortune', key:'MissFortune', mastery:84000, matches:[4,3,1]},
{name:'Senna', mastery:71200, matches:[], unavailable:'Banni'},
{name:'Yasuo', mastery:60000, matches:[6,4,2,1], unavailable:'Pris par un allié'},
{name:'Zyra', mastery:55800, matches:[4,5]}
];
const $ = id => document.getElementById(id);
const complete = c => c.matches.includes(1);
const completed = champions.filter(complete);
$('fraction').textContent = completed.length + ' / ' + champions.length;
$('progress').max = champions.length;
$('progress').value = completed.length;
let selection = false;
let statistics = false;
let filter = 'Tous';
try { if (localStorage.getItem('arena-prototype-sort') === 'name') $('sort').value = 'name'; } catch { /* Stockage facultatif pour les fichiers locaux. */ }
function mark(label, on) {
return '<span class="mark' + (on ? ' on' : '') + '"><span class="dot" aria-hidden="true">' + (on ? icon('check') : '') + '</span>' + label + '</span>';
}
function card(c) {
const wins = c.matches.filter(p => p <= 3).length;
const firstTop1 = c.matches.indexOf(1);
const reasons = [];
if (complete(c)) reasons.push(['Validé','check']);
if (selection && c.unavailable) reasons.push([c.unavailable, c.unavailable === 'Banni' ? 'ban' : 'ally']);
const labels = reasons.map(([label, symbol]) => '<span class="reason">' + icon(symbol) + label + '</span>').join('');
const best = c.matches.length ? Math.min(...c.matches) : 0;
const details = [
['Parties', c.matches.length], ['Victoires', wins],
['Meilleur placement', best ? (best === 1 ? '1ᵉʳ' : best + 'ᵉ') : '—'],
['Tentatives', firstTop1 >= 0 ? firstTop1 + 1 : c.matches.length],
['Maîtrise', c.mastery.toLocaleString('fr-FR')]
];
if (firstTop1 >= 0) details.push(['Premier top 1', matchDates[firstTop1]]);
const summary = [c.name, ...reasons.map(r => r[0]), ...details.map(([k,v]) => k + ' ' + v)].join(', ');
return '<button type="button" class="card' + (reasons.length ? ' dim' : '') + '" aria-label="' + summary + '">' +
'<img alt="" draggable="false" src="' + portraits[c.key || c.name] + '"><span class="shade"></span><span class="reason-stack">' + labels + '</span>' +
'<span class="caption"><span class="name">' + c.name + '</span><span class="marks">' + mark('Joué', c.matches.length > 0) + mark('Victoire', wins > 0) + '</span></span>' +
'<span class="card-info" aria-hidden="true"><strong>' + c.name + '</strong>' + details.map(([k,v]) => '<span class="detail-line">' + k + '<b>' + v + '</b></span>').join('') + '</span></button>';
}
function normalise(name) { return name.toLocaleLowerCase('fr').normalize('NFD').replace(/\p{M}|[^a-z0-9]/gu, ''); }
function ordered(list) {
const byName = (a,b) => a.name.localeCompare(b.name, 'fr');
return list.sort($('sort').value === 'name' ? byName : (a,b) => b.mastery - a.mastery || byName(a,b));
}
function showCards(container, list) {
$(container).innerHTML = list.map(card).join('') || '<p class="empty">Aucun champion trouvé.</p>';
}
function renderPrimary() {
const query = normalise($('homeSearch').value);
const list = champions.filter(c => {
if (selection) return c.anvil;
const matchesFilter = filter === 'Tous' || (filter === 'Validés' ? complete(c) : !complete(c));
return matchesFilter && normalise(c.name).includes(query);
});
showCards('primary', ordered(list));
$('visibleCount').textContent = list.length;
}
function renderOthers() {
if (!selection || !$('others').open) return;
const query = normalise($('otherSearch').value);
showCards('secondary', ordered(champions.filter(c => !c.anvil && normalise(c.name).includes(query))));
}
function showScreen() {
$('stats').hidden = !statistics;
$('collection').hidden = statistics;
$('homeTab').setAttribute('aria-current', statistics ? 'false' : 'page');
$('statsTab').setAttribute('aria-current', statistics ? 'page' : 'false');
$('simulate').setAttribute('aria-pressed', selection);
$('modeLabel').textContent = selection ? 'Terminer la sélection' : 'Simuler la sélection';
$('title').textContent = statistics ? 'Statistiques' : selection ? 'Sélection des champions' : 'Défi de saison';
$('heading').textContent = selection ? 'Champions de l’Enclume' : 'Mes champions';
$('homeSearchBox').hidden = $('filters').hidden = selection;
$('others').hidden = !selection;
if (!statistics) { renderPrimary(); renderOthers(); }
}
$('simulate').onclick = () => {
selection = !selection;
statistics = false;
$('others').open = false;
$('otherSearch').value = '';
showScreen();
};
$('homeTab').onclick = () => { statistics = false; showScreen(); };
$('statsTab').onclick = () => { statistics = true; showScreen(); };
$('sort').onchange = () => {
try { localStorage.setItem('arena-prototype-sort', $('sort').value); } catch { /* Stockage indisponible. */ }
renderPrimary(); renderOthers();
};
$('filters').onclick = event => {
const button = event.target.closest('[data-filter]');
if (!button) return;
filter = button.dataset.filter;
for (const item of $('filters').children) item.setAttribute('aria-pressed', item === button);
renderPrimary();
};
$('homeSearch').oninput = renderPrimary;
$('otherSearch').oninput = renderOthers;
$('others').ontoggle = renderOthers;
function dismissDetails(button) {
button.classList.remove('pinned');
button.classList.add('dismissed');
}
document.addEventListener('click', event => {
const card = event.target.closest('.card');
const old = document.querySelector('.card.pinned');
if (old) dismissDetails(old);
if (card && card !== old) { card.classList.remove('dismissed'); card.classList.add('pinned'); }
});
document.addEventListener('keydown', event => {
if (event.key === 'Escape') {
document.querySelectorAll('.card:hover,.card:focus,.card.pinned').forEach(dismissDetails);
}
});
for (const eventName of ['pointerover','focusin']) {
$('collection').addEventListener(eventName, event => {
const card = event.target.closest('.card.dismissed');
if (card && !card.contains(event.relatedTarget)) card.classList.remove('dismissed');
});
}
// Le même petit historique alimente les trois graphiques de démonstration.
function renderCharts() {
const placements = [0,0,0,0,0,0];
const attempts = [0,0,0,0,0];
const days = [0];
let count = 0;
const rounds = Math.max(...champions.map(c => c.matches.length));
for (let round = 0; round < rounds; round++) {
for (const c of champions) {
if (c.matches[round]) placements[c.matches[round] - 1]++;
if (c.matches.indexOf(1) === round) { count++; attempts[Math.min(round,4)]++; }
}
days.push(count);
}
const x = i => 35 + 610 * i / rounds;
const y = v => 90 - 70 * v / Math.max(count,1);
const path = days.map((v,i) => (i ? 'L' : 'M') + x(i) + ' ' + y(v)).join(' ');
const ticks = days.map((v,i) => '<text x="' + x(i) + '" y="110" text-anchor="middle">J' + (i+1) + '</text>').join('');
$('trend').innerHTML = '<svg viewBox="0 0 680 118" role="img" aria-label="Champions validés par jour : ' + days.join(', ') + '">' +
'<path d="M35 20H645 M35 55H645 M35 90H645" stroke="#3b3945"/><text x="15" y="24">' + count + '</text><text x="15" y="94">0</text>' +
'<path d="' + path + ' L645 90 H35 Z" fill="#b39aee" opacity=".13"/><path d="' + path + '" fill="none" stroke="#c1afff" stroke-width="3"/>' + ticks + '</svg>';
function bars(id, values, labels) {
$(id).innerHTML = values.map((v,i) => '<div class="bar-col" aria-label="' + labels[i] + ' : ' + v + '"><b>' + v + '</b><span class="bar" style="--height:' + 65 * v / Math.max(...values,1) + 'px"></span><span>' + labels[i] + '</span></div>').join('');
}
bars('placements', placements, ['1ᵉʳ','2ᵉ','3ᵉ','4ᵉ','5ᵉ','6ᵉ']);
bars('attempts', attempts, ['1','2','3','4','5+']);
}
renderCharts();
showScreen();
</script>
</body>
</html>
-68
View File
@@ -1,68 +0,0 @@
# Publication des bêtas
Les bêtas sont publiées dans les Releases du dépôt Gitea, avec les fichiers du [contrat des paquets](paquets-windows.md#contrat-pour-le-client-de-mise-à-jour). Le mainteneur les publie depuis le poste de build, par une commande. La CI ne publie rien : elle n’a pas la chaîne Windows (ADR-0003), et un runner sur le poste de build exécuterait sans isolation le code des pull requests, là où se trouve la clé de signature.
## Branches
- **develop** reçoit le travail du cycle. Chaque push exécute les contrôles CI ; une bêta se publie à partir d’un commit de develop dont les contrôles ont réussi.
- **main** porte les versions stables (#61). Un push sur main exécute les contrôles et ne publie rien.
- Les pull requests exécutent les contrôles, avec un jeton en lecture seule.
Le travail arrive sur develop en fast-forward, par pull request ou par push direct. Squasher avant de pousser est facultatif. develop n’est jamais réécrit : dans Gitea, **Paramètres → Branches**, protéger `develop` contre le push forcé. La numérotation compare les commits publiés à celui qu’on publie.
Pour établir develop la première fois : `git push origin origin/main:refs/heads/develop`.
## Cible du cycle
La version stable visée est la `version` de `[workspace.package]` dans `Cargo.toml`. En début de cycle, sur develop, le mainteneur la remplace par la stable suivante, rafraîchit `Cargo.lock` avec `cargo update -w` et pousse les deux fichiers. La commande refuse de publier une bêta pour une cible dont le tag stable `vX.Y.Z` existe déjà : après une stable, les bêtas reprennent avec la nouvelle cible.
## Publier une bêta
Sur le poste de build, avec les [prérequis de `scripts/package`](paquets-windows.md#construire-une-version) et sa clé de publication, depuis la racine du dépôt :
```bash
export VPK_NUPKG=~/outils/vpk.1.2.161.nupkg
export ARENA_SIGNING_KEY=~/cles/arena-release.pem
read -rs GITEA_TOKEN && export GITEA_TOKEN # Jeton personnel Gitea, droit d’écriture sur le dépôt
scripts/publish-beta
```
Sans argument, la commande publie le dernier commit de develop sur Gitea. On peut passer un autre commit de develop. Elle récupère develop et les tags de Gitea. Elle refuse un commit absent de develop sur Gitea, ou dont les contrôles CI n’ont pas réussi. Elle construit la version avec `scripts/package` à partir du commit lui-même, quel que soit l’état de la copie de travail, puis la publie. Le jeton se crée dans **Paramètres → Applications** de Gitea, avec l’accès en écriture aux dépôts ; il est retiré de l’environnement avant la compilation. La clé reste dans son fichier, hors du dépôt, comme pour `scripts/package`.
## Numérotation
Pour une cible 1.1.0, les bêtas reçoivent les versions 1.1.0-beta.1, 1.1.0-beta.2, etc. Chaque bêta publiée porte le tag `v1.1.0-beta.N` sur son commit. Ces tags sont le compteur du cycle : ne jamais les supprimer ni les déplacer. Une nouvelle cible commence à beta.1.
- Le numéro vaut le plus grand numéro existant de la cible, plus un. Le tag est créé par l’API Gitea après la compilation, et Gitea refuse un tag existant : deux publications ne partagent jamais un numéro. Un refus ou une compilation en échec ne publie rien et laisse le numéro libre.
- Un commit déjà contenu dans la dernière bêta numérotée ne donne pas de nouvelle bêta : la commande l’indique et ne publie rien.
`python3 scripts/test_publish_beta.py` vérifie la numérotation, les refus et les relances ; la CI l’exécute avec les contrôles.
## Release
La commande construit la version, crée le tag, puis une Release en brouillon. Elle y téléverse l’installateur `ArenaTracker-beta-Setup.exe`, le paquet complet, `release-beta.json` et `release-beta.sig`, vérifie la liste des fichiers et seulement ensuite publie la Release comme préversion. Les clients ne lisent que les Releases publiées (`draft=false`) : un brouillon incomplet ne leur est jamais annoncé. Le canal Stable ne lit pas les préversions, et les noms de fichiers bêta ne recouvrent pas ceux de la stable.
## Reprise d’une publication interrompue
Relancer la même commande, avec le même commit. Elle reprend selon ce qu’elle trouve :
| État trouvé | Relance |
| --- | --- |
| Aucun tag pour ce commit | Compile et publie avec le numéro suivant ; ne publie rien si la dernière bêta numérotée contient déjà le commit |
| Tag sans Release, ou brouillon incomplet | Recompile au même numéro, remplace tous les fichiers du brouillon et le publie |
| Release publiée et complète | Vérifie la signature, le manifeste, le commit et le condensat du paquet, puis la réutilise sans compiler |
| Release publiée incomplète ou différente | Échoue sans rien remplacer ; la bêta suivante prend le numéro suivant |
La compilation partage le dossier de build de `scripts/win`. Une version lancée depuis `target\release` verrouille l’exécutable et fait échouer la compilation : la fermer, puis relancer.
## Validation
Le 2026-11-20, la logique de publication de cette commande a été exercée sur un dépôt de test privé (Gitea 28.1.0, clé de test). Elle était alors lancée par un runner CI à chaque push de develop, ce qui a été abandonné ensuite au profit de la commande locale.
- Un push sur main n’a rien publié. La création de develop a publié 1.0.0-beta.1. Un push de deux commits a publié une seule bêta, beta.2, au second commit.
- Deux pushs rapprochés : le plus récent a reçu beta.3, et le plus ancien, traité après, n’a rien publié.
- Un commit dont le contrôle de format échouait n’a rien publié. Le correctif a reçu beta.4.
- Relancer beta.4 a réutilisé sa Release sans compiler. Remise en brouillon sans son paquet, elle a été recompilée et republiée au même numéro. Une publication interrompue en pleine compilation n’a laissé ni tag, ni Release, ni fichier de clé ; la relance a publié beta.5.
- Une pull request n’a pas pu créer de tag avec son jeton (HTTP 403).
Les cinq Releases étaient des préversions publiées de quatre fichiers. Le commit de chaque manifeste correspondait à son tag, et le SHA-256 signé correspondait au paquet téléchargé. L’`arena-tracker.exe` de chaque paquet a accepté sa propre Release avec `--verify-release`. Les deux refus propres à la commande locale (commit absent de develop, contrôles non réussis) sont couverts par les tests. Ils ont aussi été vérifiés contre l’état réel des commits sur Gitea : `success` quand tous les contrôles ont réussi, `pending` sans contrôle.
-224
View File
@@ -1,224 +0,0 @@
# Recherche des champions : noms et alias vérifiés
Recherche effectuée le **16 novembre 2026** pour préparer un ticket ; aucune fonctionnalité n'est implémentée ici.
Ticket créé : [#18 — Search the champion table by name and known aliases](https://gitea.nessar.fr/nessar/arena-tracker/issues/18).
## Périmètre et résultat
Le catalogue Riot Data Dragon **16.22.1** contient **173 champions**, avec leurs noms français et anglais. Les 173 ont été vérifiés contre les deux listes d'alias ci-dessous. Le tableau présente tous ces champions, y compris ceux pour lesquels aucune des sources n'ajoute de diminutif. Sources : [catalogue Riot français](https://ddragon.leagueoflegends.com/cdn/16.22.1/data/fr_FR/champion.json) et [catalogue Riot anglais](https://ddragon.leagueoflegends.com/cdn/16.22.1/data/en_US/champion.json).
Le [fichier de surnoms de production U.GG](https://static.bigbrain.gg/assets/lol/riot_patch_update/prod/champion-nicknames.json) contient **234 entrées** : les 173 champions du catalogue, 60 identifiants `Jade_…` et `Bob`. Ces 61 identifiants hors catalogue sont exclus de cette recherche. Pour les champions du catalogue, **49 champions ont une liste non vide, pour 56 entrées brutes**. Le [module ChampionNames de Liquipedia](https://liquipedia.net/leagueoflegends/index.php?title=Module:ChampionNames&action=raw) contient **373 correspondances concernant les 173 champions**, plus deux valeurs techniques (`none`, `transparent`) exclues.
Après suppression des variantes équivalentes à un nom canonique français, anglais ou à l'identifiant Data Dragon, l'union des deux sources donne **185 alias distincts après normalisation**, concernant **134 champions**. Aucun de ces 185 alias normalisés ne pointe vers deux champions dans les données relevées. Ce constat ne garantit pas qu'une recherche partielle ne produise qu'un seul résultat.
Cette liste est exhaustive **pour les deux jeux de données consultés et ce catalogue**, pas pour tous les surnoms inventés par les joueurs ou toutes les langues. Certains alias de Liquipedia sont des codes de contribution au wiki ; leur présence prouve leur prise en charge par ce module, pas leur popularité dans la communauté. Les données distantes peuvent changer après cette date.
## Ce qui a été vérifié chez U.GG
La [FAQ U.GG](https://u.gg/faq/) annonce la recherche par surnom et donne `TF` pour Twisted Fate comme exemple. La page interactive a répondu HTTP 403 dans cet environnement, mais ses ressources publiques sont accessibles. Le [bundle JavaScript U.GG](https://static.bigbrain.gg/lol/static/js/main.d207db790ed2d04395c0.js) construit les entrées de recherche en réunissant l'identifiant Data Dragon, le nom localisé et les valeurs du fichier `champion-nicknames.json`. Il transmet ensuite les entrées à un moteur de recherche sur le champ `key`, avec classement et score ; il ne s'agit donc pas d'une preuve d'égalité stricte sur les alias.
Le fichier de surnoms a été téléchargé directement avec HTTP 200. Le comportement visuel, les scores exacts, la tolérance aux fautes et le classement des résultats U.GG n'ont pas été testés dans un navigateur. Le ticket peut reprendre les alias vérifiés sans promettre de reproduire le moteur U.GG.
## Diminutifs et variantes d'écriture
Les noms complets français et anglais et l'identifiant Data Dragon constituent les noms de base. La règle de normalisation utilisée **pour cette comparaison documentaire** est : casse ignorée, décomposition Unicode, retrait des marques d'accent et des caractères non alphanumériques. Elle couvre notamment les espaces, apostrophes droites ou typographiques, points et esperluettes. C'est une règle proposée pour Arena Tracker, pas une affirmation sur les règles exactes d'U.GG.
- `K'Santé`, `K’Sante`, `K Sante` et `ksante` donnent `ksante` : pas besoin d'un diminutif spécifique pour cet exemple.
- `Cho'Gath` / `chogath`, `Kai'Sa` / `kaisa`, `Kha'Zix` / `khazix`, `Kog'Maw` / `kogmaw`, `Rek'Sai` / `reksai`, `Vel'Koz` / `velkoz`, `Bel'Veth` / `belveth` et `Dr. Mundo` / `drmundo` relèvent de la même normalisation.
- `Séraphine` / `seraphine`, `Zoé` / `zoe` et `Maître Yi` / `maitreyi` relèvent des accents. `MasterYi` reste un nom de base grâce à l'identifiant Data Dragon et au nom anglais.
- `tf` pour Twisted Fate et `asol` pour **Aurelion Sol** sont de vrais alias supplémentaires, présents dans les deux sources. `a sol` se normalise en `asol`. L'orthographe `aurelon sol` n'est pas un alias relevé dans ces sources.
- Une recherche par sous-chaîne du nom trouve déjà de nombreux raccourcis (`cait`, `morg`, `voli`). Les conserver dans le relevé permet de documenter ce que les sources acceptent ; leur stockage séparé n'est pas nécessaire s'ils sont couverts par la règle de recherche.
## Relevé complet par champion
Les colonnes U.GG et Liquipedia reproduisent leurs **alias supplémentaires** : les formes équivalentes après normalisation aux noms français, anglais ou à l'identifiant de la ligne sont omises. Les variantes brutes restantes sont conservées (par exemple `a sol` et `asol`), même si elles se normalisent de la même façon. `—` signifie qu'aucun alias supplémentaire n'est fourni par cette source, pas que le champion ne doit pas être trouvable.
Toutes les valeurs U.GG proviennent de son [JSON de production](https://static.bigbrain.gg/assets/lol/riot_patch_update/prod/champion-nicknames.json) ; toutes les valeurs Liquipedia proviennent du [module ChampionNames](https://liquipedia.net/leagueoflegends/index.php?title=Module:ChampionNames&action=raw). Les noms et identifiants proviennent des catalogues Riot ci-dessus.
| Champion (nom français) | Identifiant Data Dragon | U.GG | Liquipedia |
| --- | --- | --- | --- |
| Aatrox | `Aatrox` | — | `aa`, `aat` |
| Ahri | `Ahri` | — | — |
| Akali | `Akali` | — | `aka` |
| Akshan | `Akshan` | — | `ak` |
| Alistar | `Alistar` | `Cow`, `Ali` | `ali` |
| Ambessa | `Ambessa` | — | — |
| Amumu | `Amumu` | `Mummy` | `amu` |
| Anivia | `Anivia` | — | `aniv` |
| Annie | `Annie` | — | `ann` |
| Aphelios | `Aphelios` | — | `aph` |
| Ashe | `Ashe` | — | — |
| Aurelion Sol | `AurelionSol` | `ASol`, `Sol` | `a sol`, `asol` |
| Aurora | `Aurora` | — | — |
| Azir | `Azir` | — | — |
| Bard | `Bard` | `Brad` | — |
| Bel'Veth | `Belveth` | — | `bel` |
| Blitzcrank | `Blitzcrank` | `Blitz` | `blit`, `blitz` |
| Brand | `Brand` | — | — |
| Braum | `Braum` | — | `brm` |
| Briar | `Briar` | — | `bri` |
| Caitlyn | `Caitlyn` | `Cait` | `cait` |
| Camille | `Camille` | — | `cam`, `cami` |
| Cassiopeia | `Cassiopeia` | `Cass` | `cass` |
| Cho'Gath | `Chogath` | `Cho` | `cho` |
| Corki | `Corki` | — | `cor` |
| Darius | `Darius` | — | `dar` |
| Diana | `Diana` | — | `dia` |
| Draven | `Draven` | — | `dra`, `drav` |
| Dr. Mundo | `DrMundo` | `Dr`, `Mundo` | `dm`, `mun`, `mundo` |
| Ekko | `Ekko` | — | `ek` |
| Elise | `Elise` | — | `eli` |
| Evelynn | `Evelynn` | `Eve` | `eve` |
| Ezreal | `Ezreal` | `Ez` | `ez` |
| Fiddlesticks | `Fiddlesticks` | `Fid`, `Fiddle` | `fid`, `fids`, `fiddle` |
| Fiora | `Fiora` | — | `fio` |
| Fizz | `Fizz` | — | — |
| Galio | `Galio` | — | `gal`, `gali` |
| Gangplank | `Gangplank` | `Gp` | `gp` |
| Garen | `Garen` | — | `gar` |
| Gnar | `Gnar` | — | — |
| Gragas | `Gragas` | — | `grag` |
| Graves | `Graves` | — | `grav` |
| Gwen | `Gwen` | — | — |
| Hecarim | `Hecarim` | `Hec` | `hec`, `heca` |
| Heimerdinger | `Heimerdinger` | `Heimer`, `Donger` | `heim`, `heime`, `heimer` |
| Hwei | `Hwei` | — | — |
| Illaoi | `Illaoi` | — | `ill` |
| Irelia | `Irelia` | — | `ire` |
| Ivern | `Ivern` | — | `ive` |
| Janna | `Janna` | — | `jan` |
| Jarvan IV | `JarvanIV` | `J4` | `j4`, `jarvan`, `jarvan 4` |
| Jax | `Jax` | — | — |
| Jayce | `Jayce` | — | `jc` |
| Jhin | `Jhin` | — | — |
| Jinx | `Jinx` | — | `jnx` |
| Kai'Sa | `Kaisa` | — | `ks`, `kai` |
| Kalista | `Kalista` | — | `kali` |
| Karma | `Karma` | — | `karm` |
| Karthus | `Karthus` | — | `kart`, `karth` |
| Kassadin | `Kassadin` | `Kass` | `kass`, `kassa` |
| Katarina | `Katarina` | `Kat` | `kat`, `kata` |
| Kayle | `Kayle` | — | `kayl` |
| Kayn | `Kayn` | — | — |
| Kennen | `Kennen` | — | `ken` |
| Kha'Zix | `Khazix` | — | `k6`, `kha` |
| Kindred | `Kindred` | — | `kin`, `kind` |
| Kled | `Kled` | — | — |
| Kog'Maw | `KogMaw` | `Kog` | `kog` |
| K'Santé | `KSante` | — | `ksa` |
| LeBlanc | `Leblanc` | `LB` | `lb` |
| Lee Sin | `LeeSin` | `Lee` | `lee` |
| Leona | `Leona` | — | `leo` |
| Lillia | `Lillia` | — | `lil` |
| Lissandra | `Lissandra` | `Liss` | `liss` |
| Locke | `Locke` | — | — |
| Lucian | `Lucian` | — | `luc` |
| Lulu | `Lulu` | — | — |
| Lux | `Lux` | — | — |
| Maître Yi | `MasterYi` | `Yi` | `yi` |
| Malphite | `Malphite` | `Malph` | `malp`, `malph` |
| Malzahar | `Malzahar` | `Malz` | `malz`, `malza` |
| Maokai | `Maokai` | `Tree` | `mao` |
| Mel | `Mel` | — | — |
| Milio | `Milio` | — | `mil` |
| Miss Fortune | `MissFortune` | `MF` | `mf` |
| Mordekaiser | `Mordekaiser` | `Mord` | `mord`, `morde` |
| Morgana | `Morgana` | `Morg` | `morg` |
| Naafiri | `Naafiri` | — | `naa` |
| Nami | `Nami` | — | — |
| Nasus | `Nasus` | `Susan` | — |
| Nautilus | `Nautilus` | `Naut` | `naut` |
| Neeko | `Neeko` | — | `nee` |
| Nidalee | `Nidalee` | `Nid` | `nid`, `nida` |
| Nilah | `Nilah` | — | `nil` |
| Nocturne | `Nocturne` | `Noct` | `noc`, `noct` |
| Nunu et Willump | `Nunu` | — | — |
| Olaf | `Olaf` | — | — |
| Orianna | `Orianna` | `Ori` | `ori`, `oriana` |
| Ornn | `Ornn` | — | — |
| Pantheon | `Pantheon` | `Panth` | `panth` |
| Poppy | `Poppy` | — | `pop` |
| Pyke | `Pyke` | — | — |
| Qiyana | `Qiyana` | — | `qiy` |
| Quinn | `Quinn` | — | `quin` |
| Rakan | `Rakan` | — | `rak` |
| Rammus | `Rammus` | — | `ram` |
| Rek'Sai | `RekSai` | — | `rek` |
| Rell | `Rell` | — | — |
| Renata Glasc | `Renata` | — | `rg` |
| Renekton | `Renekton` | `Gator` | `rene`, `renek` |
| Rengar | `Rengar` | — | `ren`, `reng` |
| Riven | `Riven` | — | `riv` |
| Rumble | `Rumble` | — | `rum` |
| Ryze | `Ryze` | — | — |
| Samira | `Samira` | — | `sam`, `sami` |
| Sejuani | `Sejuani` | `Sej` | `sej`, `seju` |
| Senna | `Senna` | — | `sen` |
| Séraphine | `Seraphine` | — | `ser`, `sera` |
| Sett | `Sett` | — | — |
| Shaco | `Shaco` | — | — |
| Shen | `Shen` | — | — |
| Shyvana | `Shyvana` | `Shyv` | `shyv` |
| Singed | `Singed` | — | `sin` |
| Sion | `Sion` | — | — |
| Sivir | `Sivir` | — | `siv` |
| Skarner | `Skarner` | — | `skar` |
| Smolder | `Smolder` | — | `smo`, `sml` |
| Sona | `Sona` | — | — |
| Soraka | `Soraka` | — | `srk`, `raka` |
| Swain | `Swain` | — | `swa` |
| Sylas | `Sylas` | — | `syl` |
| Syndra | `Syndra` | — | `syn` |
| Tahm Kench | `TahmKench` | `TK` | `tk`, `tahm`, `kench` |
| Taliyah | `Taliyah` | — | `tali` |
| Talon | `Talon` | — | `tal` |
| Taric | `Taric` | — | `tar` |
| Teemo | `Teemo` | — | `tee` |
| Thresh | `Thresh` | — | `thr` |
| Tristana | `Tristana` | `Trist` | `tris`, `trist` |
| Trundle | `Trundle` | `Troll` | `trun` |
| Tryndamere | `Tryndamere` | `Trynd` | `tryn`, `trynd`, `trynda` |
| Twisted Fate | `TwistedFate` | `TF` | `tf` |
| Twitch | `Twitch` | — | `twi` |
| Udyr | `Udyr` | — | — |
| Urgot | `Urgot` | — | `ur`, `urg` |
| Varus | `Varus` | — | `var` |
| Vayne | `Vayne` | — | `vn`, `vay` |
| Veigar | `Veigar` | — | `vei`, `veig` |
| Vel'Koz | `Velkoz` | — | `vel` |
| Vex | `Vex` | — | — |
| Vi | `Vi` | — | — |
| Viego | `Viego` | — | `vie` |
| Viktor | `Viktor` | — | `vik` |
| Vladimir | `Vladimir` | `Vlad` | `vlad` |
| Volibear | `Volibear` | `Voli` | `voli` |
| Warwick | `Warwick` | `WW` | `ww` |
| Wukong | `MonkeyKing` | — | `wu`, `wuk` |
| Xayah | `Xayah` | — | `xay` |
| Xerath | `Xerath` | — | `xer` |
| Xin Zhao | `XinZhao` | `Xin` | `xz`, `xin` |
| Yasuo | `Yasuo` | `Yas` | `yas` |
| Yone | `Yone` | — | `y1` |
| Yorick | `Yorick` | — | `yor` |
| Yunara | `Yunara` | — | — |
| Yuumi | `Yuumi` | — | `yuu` |
| Zaahen | `Zaahen` | — | `zaa` |
| Zac | `Zac` | — | — |
| Zed | `Zed` | — | — |
| Zeri | `Zeri` | — | — |
| Ziggs | `Ziggs` | — | `zig` |
| Zilean | `Zilean` | `Zil` | `zil` |
| Zoé | `Zoe` | — | — |
| Zyra | `Zyra` | — | — |
## Cas à préciser dans le ticket
- La recherche partielle peut produire plusieurs champions : `mal` couvre Malphite et Malzahar ; `ren` couvre notamment Renata Glasc et Renekton. Une table filtrée peut simplement conserver tous les résultats correspondants.
- Les alias très courts ne doivent pas devenir des sous-chaînes à chercher dans tous les autres alias : par exemple `ks` est un alias de Kai'Sa dans Liquipedia, tandis que `ksa` désigne K'Santé. Comparer les alias complets normalisés évite de transformer cette relation en recherche floue implicite.
- Les surnoms descriptifs de U.GG sont vérifiés mais distincts des abréviations : `cow` (Alistar), `mummy` (Amumu), `donger` (Heimerdinger), `tree` (Maokai), `susan` (Nasus), `gator` (Renekton), `troll` (Trundle), notamment.
- La liste est une référence datée. Les noms canoniques doivent continuer à fonctionner pour les nouveaux champions même avant l'ajout éventuel de leurs surnoms ; chaque ajout d'alias peut être vérifié contre l'identifiant du champion.
## Vérifications du relevé
La jointure par identifiant couvre les **173/173** champions, sans identifiant inconnu dans les lignes finales. Les alias techniques et les champions hors catalogue sont exclus. Le total des alias supplémentaires normalisés a été recalculé et leurs cibles vérifiées ; aucun conflit entre alias exacts n'a été trouvé. Aucun test de l'application n'a été exécuté : seul ce document de recherche est ajouté.
-145
View File
@@ -1,145 +0,0 @@
#!/usr/bin/env python3
"""Build a signed Windows release from a Git snapshot. Run from the repository root."""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import zipfile
VPK_VERSION = "1.2.161"
VPK_SHA256 = "2b56ce117f803fc70c103cb423bd040e395e40370f6ff6e10818e9ff9c26a323"
def output(*args, **kw):
return subprocess.check_output(args, **kw)
def windows_path(path):
return output("wslpath", "-w", path.resolve()).decode().strip()
def digest(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256")
def wsl_path(win_path):
return Path(output("wslpath", "-u", win_path).decode().strip())
def build(args):
number = r"(0|[1-9][0-9]*)"
suffix = r"-beta\.([1-9][0-9]*)" if args.channel == "beta" else ""
match = re.fullmatch(r"\.".join([number] * 3) + suffix, args.version)
if not match or any(int(n) > 65535 for n in match.groups()[:3]):
raise ValueError("Version attendue : X.Y.Z (stable) ou X.Y.Z-beta.N (beta), composantes ≤ 65535")
root = Path(output("git", "rev-parse", "--show-toplevel").decode().strip()).resolve()
commit = output("git", "rev-parse", "--verify", "--end-of-options", args.commit + "^{commit}").decode().strip()
if output("git", "show", f"{commit}:scripts/package") != Path(__file__).read_bytes():
raise ValueError("Lancer le script de packaging du commit choisi")
dest = args.output.resolve()
if dest.exists():
raise ValueError("Le dossier de sortie existe déjà")
key = Path(os.environ["ARENA_SIGNING_KEY"]).resolve(strict=True)
if key.is_relative_to(root):
raise ValueError("La clé de signature doit rester hors du dépôt")
spki = output("openssl", "pkey", "-in", key, "-pubout", "-outform", "DER")
if len(spki) != 44 or not spki.startswith(bytes.fromhex("302a300506032b6570032100")):
raise ValueError("Une clé de signature Ed25519 est requise")
tool = Path(os.environ["VPK_NUPKG"])
dest.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory() as work, tempfile.TemporaryDirectory(dir=dest.parent) as staging:
tmp = Path(work)
local_tool = tmp / "vpk.nupkg"
shutil.copyfile(tool, local_tool)
if digest(local_tool).hexdigest() != VPK_SHA256:
raise ValueError(f"Archive NuGet officielle de vpk {VPK_VERSION} attendue")
src = tmp / "src"
src.mkdir()
archive = tmp / "source.tar"
subprocess.run(["git", "archive", "--output", archive, commit], check=True)
# -m: fresh mtimes, so Cargo never reuses a workspace crate built from other sources in the shared target.
subprocess.run(["tar", "-xmf", archive, "-C", src], check=True)
assets = src / "crates/app/assets"
(assets / "release-version.h").write_text(
f'#define ARENA_VERSION_TEXT "{args.version}"\n'
f'#define ARENA_VERSION_NUMBERS {",".join(match.groups()[:3])},0\n'
)
rc = assets / "app.rc"
rc.write_text("#define ARENA_RELEASE\n" + rc.read_text())
identity = {
"ARENA_RELEASE_VERSION": args.version, "ARENA_RELEASE_CHANNEL": args.channel,
"ARENA_RELEASE_COMMIT": commit, "ARENA_RELEASE_PUBLIC_KEY": base64.b64encode(spki[-32:]).decode(),
}
env = os.environ.copy()
del env["ARENA_SIGNING_KEY"]
env.update(identity)
env["WSLENV"] = ":".join(filter(None, [env.get("WSLENV", ""), *identity]))
messages = output(src / "scripts/prod", "build", "--message-format=json-render-diagnostics", env=env)
executables = []
for line in messages.splitlines():
artifact = json.loads(line)
if artifact.get("executable") and artifact["target"]["name"] == "arena-tracker":
executables.append(artifact["executable"])
if len(executables) != 1:
raise ValueError("Cargo devait construire un seul exécutable arena-tracker")
package_dir = tmp / "app"
package_dir.mkdir()
app = package_dir / "arena-tracker.exe"
shutil.copyfile(wsl_path(executables[0]), app)
app.chmod(0o755)
# The pinned packer labels its input with --runtime. Check the actual PE machine first.
with app.open("rb") as pe:
pe.seek(0x3C)
pe.seek(int.from_bytes(pe.read(4), "little"))
if pe.read(6) != b"PE\0\0\x64\x86":
raise ValueError("Exécutable Windows x64 attendu")
with zipfile.ZipFile(local_tool) as archive:
for member in archive.namelist():
if member.startswith(("tools/net10.0/any/", "vendor/")):
archive.extract(member, tmp / "vpk")
packed = tmp / "packed"
subprocess.run(["dotnet.exe", windows_path(tmp / "vpk/tools/net10.0/any/vpk.dll"), "pack",
"--skip-updates", "--runtime", "win-x64", "--packId", "ArenaTracker",
"--packTitle", "Arena Tracker", "--packAuthors", "Arena Tracker",
"--packVersion", args.version, "--channel", args.channel,
"--packDir", windows_path(package_dir), "--mainExe", app.name,
"--icon", windows_path(assets / "icon.ico"), "--outputDir", windows_path(packed),
"--shortcuts", "StartMenuRoot", "--delta", "None", "--noPortable"], check=True)
stage = Path(staging) / "release"
stage.mkdir()
package = stage / f"ArenaTracker-{args.version}-{args.channel}-full.nupkg"
shutil.move(packed / package.name, package)
installer = f"ArenaTracker-{args.channel}-Setup.exe"
shutil.move(packed / installer, stage / installer)
manifest = stage / f"release-{args.channel}.json"
manifest.write_text(json.dumps({
"app": "ArenaTracker", "target": "win-x64", "channel": args.channel,
"version": args.version, "commit": commit, "package": package.name,
"sha256": base64.b64encode(digest(package).digest()).decode(),
}) + "\n")
subprocess.run(["openssl", "pkeyutl", "-sign", "-rawin", "-inkey", key,
"-in", manifest, "-out", manifest.with_suffix(".sig")], check=True)
subprocess.run([app, "--verify-release", windows_path(stage)], check=True)
stage.rename(dest)
print(dest)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("commit")
parser.add_argument("version")
parser.add_argument("channel", choices=("stable", "beta"))
parser.add_argument("output", type=Path)
try:
build(parser.parse_args())
except (ValueError, OSError, KeyError, subprocess.CalledProcessError) as err:
raise SystemExit(f"Erreur : {err}")
-188
View File
@@ -1,188 +0,0 @@
#!/usr/bin/env python3
"""Publish the beta of a develop commit to Gitea Releases, from the build PC. Run from the repository root."""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import tempfile
import tomllib
import urllib.error
import urllib.parse
import urllib.request
def git(*args, check=True):
result = subprocess.run(["git", *args], capture_output=True, text=True)
if check and result.returncode:
raise ValueError(f"git {args[0]} : {result.stderr.strip()}")
return result.stdout.strip() if result.returncode == 0 else None
def target(commit):
"""The stable version the cycle leads to: the workspace version in the commit's Cargo.toml."""
version = tomllib.loads(git("show", f"{commit}:Cargo.toml"))["workspace"]["package"]["version"]
if not re.fullmatch(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)", version):
raise ValueError(f"Cible de cycle X.Y.Z attendue dans Cargo.toml, pas {version}")
return version
def tagged_commit(tag):
return git("rev-parse", "-q", "--verify", f"refs/tags/{tag}^{{commit}}", check=False)
def number(commit, version):
"""(N, tag exists) for the commit's beta of version, or None when a newer beta tag contains it."""
if tagged_commit(f"v{version}"):
raise ValueError(f"La {version} est déjà publiée : fixer la cible du cycle suivant dans Cargo.toml")
betas = {}
for tag in git("tag", "--list", f"v{version}-beta.*").split():
if match := re.fullmatch(rf"v{re.escape(version)}-beta\.([1-9][0-9]*)", tag):
betas[int(match[1])] = tagged_commit(tag)
for n, sha in betas.items():
if sha == commit:
return n, True
# A commit older than the newest beta's is already in it, published or once its publication resumes.
if betas:
ancestor = subprocess.run(["git", "merge-base", "--is-ancestor", commit, betas[max(betas)]]).returncode
if ancestor not in (0, 1):
raise ValueError("git merge-base a échoué")
if ancestor == 0:
return None
return max(betas, default=0) + 1, False
def package_file(version):
return f"ArenaTracker-{version}-beta-full.nupkg"
def files(version):
return {"ArenaTracker-beta-Setup.exe", "release-beta.json", "release-beta.sig", package_file(version)}
def expect(reply, *statuses):
status, body = reply
if status not in statuses:
raise ValueError(f"Gitea a répondu HTTP {status} : {body}")
return body
def check(api, release, commit, version, key):
"""Accept a published Release only if it is the complete, signed beta of this commit."""
assets = {asset["name"]: asset for asset in release["assets"]}
if set(assets) != files(version) or not release["prerelease"]:
raise ValueError(f"La Release publiée {version} est incomplète ou n’est pas une préversion : rien n’est remplacé")
package = package_file(version)
with tempfile.TemporaryDirectory() as work:
for name in ("release-beta.json", "release-beta.sig", package):
(Path(work) / name).write_bytes(api.fetch(assets[name]["browser_download_url"]))
public = Path(work) / "public.pem"
subprocess.run(["openssl", "pkey", "-in", key, "-pubout", "-out", public], check=True)
manifest = Path(work) / "release-beta.json"
signed = subprocess.run(["openssl", "pkeyutl", "-verify", "-pubin", "-inkey", public, "-rawin",
"-in", manifest, "-sigfile", manifest.with_suffix(".sig")], capture_output=True)
digest = base64.b64encode(hashlib.sha256((Path(work) / package).read_bytes()).digest()).decode()
if signed.returncode or json.loads(manifest.read_bytes()) != {
"app": "ArenaTracker", "target": "win-x64", "channel": "beta", "version": version,
"commit": commit, "package": package, "sha256": digest,
}:
raise ValueError(f"La Release publiée {version} ne correspond pas au commit {commit} : rien n’est remplacé")
def publish(api, commit, version, tagged, build, key):
"""Publish version at commit as a complete prerelease, or reuse it if a previous run did."""
tag = f"v{version}"
status, release = api.call("GET", f"/releases/tags/{tag}") if tagged else (404, None)
if status == 404:
release = None
elif status != 200:
raise ValueError(f"Gitea a répondu HTTP {status} : {release}")
if release and not release["draft"]:
check(api, release, commit, version, key)
print(f"{version} est déjà publiée au commit {commit} : publication réutilisée")
return
with tempfile.TemporaryDirectory() as work:
out = Path(work) / "release"
build(commit, version, out, key)
if not tagged:
# Atomic: Gitea refuses an existing tag, so two publications never share a number.
expect(api.call("POST", "/tags", {"tag_name": tag, "target": commit}), 200, 201)
if not release:
release = expect(api.call("POST", "/releases", {
"tag_name": tag, "name": f"Arena Tracker {version}", "body": f"Commit {commit}",
"draft": True, "prerelease": True}), 201)
# A draft is invisible to clients: its files are replaced as one set, built together.
for asset in release["assets"]:
expect(api.call("DELETE", f"/releases/{release['id']}/assets/{asset['id']}"), 204)
for path in out.iterdir():
name = urllib.parse.quote(path.name)
expect(api.call("POST", f"/releases/{release['id']}/assets?name={name}", data=path.read_bytes()), 201)
draft = expect(api.call("GET", f"/releases/{release['id']}"), 200)
if {asset["name"] for asset in draft["assets"]} != files(version):
raise ValueError(f"Le brouillon {version} n’a pas les fichiers attendus : il reste invisible")
expect(api.call("PATCH", f"/releases/{release['id']}", {"draft": False, "prerelease": True}), 200)
print(f"{version} publiée au commit {commit}")
def release_beta(api, commit, build, key):
"""Publish the commit's beta, provided it is on develop and its CI checks passed."""
if subprocess.run(["git", "merge-base", "--is-ancestor", commit, "refs/remotes/origin/develop"]).returncode:
raise ValueError(f"Le commit {commit} n’est pas dans develop sur Gitea : le pousser d’abord")
state = expect(api.call("GET", f"/commits/{commit}/status"), 200)["state"]
if state != "success":
raise ValueError(f"Les contrôles CI du commit {commit} n’ont pas réussi (état : {state}) : rien n’est publié")
version = target(commit)
found = number(commit, version)
if found is None:
print(f"Le commit {commit} est déjà contenu dans la dernière bêta de {version} : aucune publication")
return
n, tagged = found
publish(api, commit, f"{version}-beta.{n}", tagged, build, key)
class Gitea:
def __init__(self, repo_url, token):
self.repo_url = repo_url
self.headers = {"Authorization": f"token {token}"}
def request(self, url, method="GET", headers=None, data=None):
request = urllib.request.Request(url, data, {**self.headers, **(headers or {})}, method=method)
with urllib.request.urlopen(request, timeout=600) as response:
return response.status, response.read()
def call(self, method, path, body=None, data=None):
kind = "application/octet-stream"
if body is not None:
data, kind = json.dumps(body).encode(), "application/json"
try:
status, reply = self.request(self.repo_url + path, method, {"Content-Type": kind}, data)
except urllib.error.HTTPError as err:
return err.code, err.read().decode(errors="replace")
return status, json.loads(reply) if reply else None
def fetch(self, url):
return self.request(url)[1]
def build(commit, version, out, key):
subprocess.run([Path(__file__).with_name("package"), commit, version, "beta", out],
env=dict(os.environ, ARENA_SIGNING_KEY=key), check=True)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("commit", nargs="?", default="origin/develop", help="dernier commit de develop par défaut")
args = parser.parse_args()
try:
key = str(Path(os.environ["ARENA_SIGNING_KEY"]).resolve(strict=True))
# Out of the environment before the build, which never sees it.
api = Gitea("https://gitea.nessar.fr/api/v1/repos/nessar/arena-tracker", os.environ.pop("GITEA_TOKEN"))
# Gitea's develop and beta tags, which the checks and the numbering read.
git("fetch", "--quiet", "--force", "--tags", "origin", "develop")
commit = git("rev-parse", "--verify", "--end-of-options", args.commit + "^{commit}")
release_beta(api, commit, build, key)
except (ValueError, OSError, KeyError, subprocess.CalledProcessError) as err:
raise SystemExit(f"Erreur : {err}")
-201
View File
@@ -1,201 +0,0 @@
"""Numbering and reruns of scripts/publish-beta, against a fake Gitea and a temporary Git repository.
Run: python3 scripts/test_publish_beta.py (Python 3.11+, git, OpenSSL 3).
"""
import base64
import copy
import hashlib
import importlib.machinery
import importlib.util
import itertools
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
loader = importlib.machinery.SourceFileLoader("publish_beta", str(Path(__file__).with_name("publish-beta")))
pb = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader))
loader.exec_module(pb)
class FakeGitea:
"""The Releases API as publish-beta uses it. Tags are created in the current repository."""
def __init__(self):
self.releases, self.blobs, self.ids = [], {}, itertools.count(1)
self.failing_upload, self.tag_conflict, self.checks = None, False, {}
def call(self, method, path, body=None, data=None):
parts = path.split("?")[0].split("/")[1:]
if method == "GET" and parts[0] == "commits":
return 200, {"state": self.checks.get(parts[1], "success")}
if method == "GET" and parts[:2] == ["releases", "tags"]:
found = [r for r in self.releases if r["tag_name"] == parts[2]]
return (200, copy.deepcopy(found[0])) if found else (404, "release not found")
if method == "POST" and parts == ["tags"]:
if self.tag_conflict or pb.tagged_commit(body["tag_name"]):
return 409, "tag already exists"
subprocess.run(["git", "tag", body["tag_name"], body["target"]], check=True)
return 201, {}
if method == "POST" and parts == ["releases"]:
release = {"id": next(self.ids), "tag_name": body["tag_name"], "draft": body["draft"],
"prerelease": body["prerelease"], "assets": []}
self.releases.append(release)
return 201, copy.deepcopy(release)
release = next(r for r in self.releases if r["id"] == int(parts[1]))
if method == "POST":
name = path.split("name=")[1]
if name == self.failing_upload:
return 500, "connection reset"
url = f"https://gitea.test/{release['tag_name']}/{name}"
self.blobs[url] = data
release["assets"].append({"id": next(self.ids), "name": name, "browser_download_url": url})
return 201, {}
if method == "DELETE":
release["assets"] = [a for a in release["assets"] if a["id"] != int(parts[3])]
return 204, None
if method == "PATCH":
release.update(body)
return 200, copy.deepcopy(release)
def fetch(self, url):
return self.blobs[url]
class PublishBeta(unittest.TestCase):
def setUp(self):
work = tempfile.TemporaryDirectory()
self.addCleanup(work.cleanup)
self.addCleanup(os.chdir, os.getcwd())
os.chdir(work.name)
self.key = Path(work.name) / "key.pem"
subprocess.run(["openssl", "genpkey", "-algorithm", "ED25519", "-out", self.key], check=True)
os.mkdir("repo")
os.chdir("repo")
subprocess.run(["git", "init", "-q"], check=True)
self.gitea, self.builds = FakeGitea(), []
def commit(self, target="1.1.0", pushed=True):
Path("Cargo.toml").write_text(f'[workspace.package]\nversion = "{target}"\n')
subprocess.run(["git", "add", "Cargo.toml"], check=True)
subprocess.run(["git", "-c", "user.name=CI", "-c", "user.email=ci@test", "commit", "-q",
"--allow-empty", "-m", "change"], check=True)
if pushed:
subprocess.run(["git", "update-ref", "refs/remotes/origin/develop", "HEAD"], check=True)
return pb.git("rev-parse", "HEAD")
def build(self, commit, version, out, key):
"""Sign a stand-in release the way scripts/package does."""
self.builds.append(version)
out.mkdir()
package = out / f"ArenaTracker-{version}-beta-full.nupkg"
package.write_bytes(f"{commit} {version}".encode())
(out / "ArenaTracker-beta-Setup.exe").write_bytes(b"setup")
manifest = out / "release-beta.json"
manifest.write_text(json.dumps({
"app": "ArenaTracker", "target": "win-x64", "channel": "beta", "version": version,
"commit": commit, "package": package.name,
"sha256": base64.b64encode(hashlib.sha256(package.read_bytes()).digest()).decode(),
}) + "\n")
subprocess.run(["openssl", "pkeyutl", "-sign", "-rawin", "-inkey", key, "-in", manifest,
"-out", manifest.with_suffix(".sig")], check=True)
def release(self, commit):
pb.release_beta(self.gitea, commit, self.build, self.key)
def published(self):
"""Tag → commit of each Release a client sees, each checked complete and signed."""
seen = {}
for release in self.gitea.releases:
if not release["draft"]:
commit = pb.tagged_commit(release["tag_name"])
pb.check(self.gitea, release, commit, release["tag_name"][1:], self.key)
seen[release["tag_name"]] = commit
return seen
def test_each_push_gets_the_next_number_and_a_rerun_reuses_it(self):
first = self.commit()
self.release(first)
self.release(first)
self.commit()
last = self.commit()
self.release(last) # One push bringing two commits.
self.assertEqual(self.published(), {"v1.1.0-beta.1": first, "v1.1.0-beta.2": last})
self.assertEqual(self.builds, ["1.1.0-beta.1", "1.1.0-beta.2"])
def test_a_commit_whose_checks_did_not_pass_publishes_nothing(self):
commit = self.commit()
self.gitea.checks[commit] = "pending"
with self.assertRaisesRegex(ValueError, "contrôles CI"):
self.release(commit)
self.assertEqual((self.builds, pb.git("tag")), ([], ""))
def test_a_commit_not_pushed_to_develop_publishes_nothing(self):
self.commit()
local = self.commit(pushed=False)
with self.assertRaisesRegex(ValueError, "pas dans develop"):
self.release(local)
self.assertEqual((self.builds, pb.git("tag")), ([], ""))
def test_an_older_commit_published_last_publishes_nothing(self):
older = self.commit()
newer = self.commit()
self.release(newer)
self.release(older)
self.assertEqual(self.published(), {"v1.1.0-beta.1": newer})
self.assertEqual(self.builds, ["1.1.0-beta.1"])
def test_a_rerun_completes_an_interrupted_publication_under_its_number(self):
interrupted = self.commit()
self.gitea.failing_upload = "release-beta.sig"
with self.assertRaisesRegex(ValueError, "500"):
self.release(interrupted)
self.assertEqual(self.published(), {})
self.gitea.failing_upload = None
later = self.commit()
self.release(later)
self.release(interrupted)
self.assertEqual(self.published(), {"v1.1.0-beta.1": interrupted, "v1.1.0-beta.2": later})
self.assertEqual(len(self.gitea.releases), 2)
def test_a_new_cycle_starts_its_own_series(self):
old = self.commit("1.1.0")
self.release(old)
new = self.commit("1.2.0")
self.release(new)
self.assertEqual(self.published(), {"v1.1.0-beta.1": old, "v1.2.0-beta.1": new})
def test_a_released_target_publishes_nothing(self):
commit = self.commit()
subprocess.run(["git", "tag", "v1.1.0", commit], check=True)
with self.assertRaisesRegex(ValueError, "déjà publiée"):
self.release(commit)
self.assertEqual((self.builds, self.gitea.releases), ([], []))
def test_a_failed_build_publishes_nothing(self):
def broken(*args):
raise subprocess.CalledProcessError(1, "scripts/package")
with self.assertRaises(subprocess.CalledProcessError):
pb.release_beta(self.gitea, self.commit(), broken, self.key)
self.assertEqual((pb.git("tag"), self.gitea.releases), ("", []))
def test_a_number_taken_meanwhile_is_not_shared(self):
self.gitea.tag_conflict = True
with self.assertRaisesRegex(ValueError, "409"):
self.release(self.commit())
self.assertEqual(self.gitea.releases, [])
def test_a_different_published_release_is_never_replaced(self):
commit = self.commit()
self.release(commit)
self.gitea.blobs["https://gitea.test/v1.1.0-beta.1/ArenaTracker-1.1.0-beta.1-beta-full.nupkg"] = b"other"
with self.assertRaisesRegex(ValueError, "rien n’est remplacé"):
self.release(commit)
self.assertEqual(self.builds, ["1.1.0-beta.1"])
if __name__ == "__main__":
unittest.main()