From f4a9e5e7a8ee9902e5ea4f2376ae1b134937b2e3 Mon Sep 17 00:00:00 2001 From: Nessar Date: Thu, 19 Nov 2026 18:31:21 +0100 Subject: [PATCH] Show live Arena champion picks and crowd favorites (#13) --- crates/app/src/champion_table.rs | 13 ++ crates/app/src/main.rs | 15 +- crates/app/src/stats_page.rs | 271 +++++++++++++++++++++++++++++-- crates/app/src/worker.rs | 61 +++++-- crates/core/src/champ_select.rs | 121 ++++++++++++++ crates/core/src/client.rs | 9 + crates/core/src/follow.rs | 19 ++- crates/core/src/league_client.rs | 75 ++++++++- crates/core/src/lib.rs | 2 + crates/core/tests/common/mod.rs | 14 ++ crates/core/tests/follow.rs | 75 +++++++++ 11 files changed, 636 insertions(+), 39 deletions(-) create mode 100644 crates/core/src/champ_select.rs diff --git a/crates/app/src/champion_table.rs b/crates/app/src/champion_table.rs index 3e831f1..1448f66 100644 --- a/crates/app/src/champion_table.rs +++ b/crates/app/src/champion_table.rs @@ -194,6 +194,19 @@ impl ChampionTable { } } +/// Prepared on pick/statistics changes so a redraw only lays out the labels. +pub fn pick_labels(row: &ChampionRow) -> Vec { + 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 { diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 060f1f9..bdf651a 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -43,6 +43,7 @@ struct RootView { fallback_riot_id: String, tx: Sender, _form_events: Subscription, + _champ_select: Subscription, } impl RootView { @@ -82,10 +83,22 @@ impl RootView { KeyEvent::Saved => this.page.update(cx, |page, cx| page.request_refresh(cx)), KeyEvent::Back => {} } + this.form.update(cx, |form, cx| form.reset(window, cx)); this.screen = Screen::Page; this.focus.focus(window, cx); cx.notify(); }); + let champ_select = cx.subscribe_in( + &page, + window, + |this, _, _: &stats_page::ChampSelectTransition, window, cx| { + if this.screen == Screen::Settings { + this.screen = Screen::Page; + this.focus.focus(window, cx); + cx.notify(); + } + }, + ); let screen = if first_launch { Screen::Prompt } else { @@ -101,6 +114,7 @@ impl RootView { fallback_riot_id: riot_id, tx, _form_events: form_events, + _champ_select: champ_select, } } @@ -120,7 +134,6 @@ impl Render for RootView { let settings = settings_button(self.screen == Screen::Page, cx).on_click(cx.listener( |this, _, window, cx| { if this.screen == Screen::Page { - this.form.update(cx, |form, cx| form.reset(window, cx)); this.screen = Screen::Settings; this.focus.focus(window, cx); cx.notify(); diff --git a/crates/app/src/stats_page.rs b/crates/app/src/stats_page.rs index 99bf697..6ff8ac9 100644 --- a/crates/app/src/stats_page.rs +++ b/crates/app/src/stats_page.rs @@ -4,8 +4,8 @@ use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use arena_tracker_core::{ - Account, ChallengeSummary, ChampionSearch, Charts, Format, ProgressCheck, Scope, SeasonScope, - StateFilter, Statistics, Status, SyncProgress, Tracker, UpdateProblem, + Account, ChallengeSummary, ChampSelect, 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 _; @@ -76,12 +76,18 @@ impl SelectItem for AccountItem { } } +pub struct ChampSelectTransition; +impl EventEmitter for StatsPage {} + pub struct StatsPage { tracker: Arc, tx: Sender, notice: Option, /// As of the last follower round or refresh. status: Status, + selection: crate::worker::Selection, + current_pick: Vec, + favorites: Vec, accounts: Vec, last_active: Option, /// The Account the user picked instead of following the one being updated. @@ -242,6 +248,9 @@ impl StatsPage { tracker, tx, notice, + selection: None, + current_pick: Vec::new(), + favorites: Vec::new(), accounts: Vec::new(), last_active: None, pinned: None, @@ -337,14 +346,39 @@ impl StatsPage { } } Msg::Champions => self.reload_in_background(window, cx), + Msg::Selection(selection) => { + if self.selection == selection { + return; + } + let next = selection.as_ref().and_then(|s| s.as_ref().ok()); + let changed_page = self.selection.is_some() != selection.is_some(); + let previous = self.selection.as_ref().and_then(|s| s.as_ref().ok()); + let switch = changed_page || previous.map(|(id, _)| id) != next.map(|(id, _)| id); + let pool_changed = + previous.map(|(_, s)| &s.pickable) != next.map(|(_, s)| &s.pickable); + self.selection = selection; + if switch { + 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); + } + self.update_picks(); + if pool_changed || switch { + self.refresh_table(cx); + } + } Msg::Round { status, reload } => { - // A follower round that changes nothing shown must not rebuild the page (they keep coming). - let unchanged = status == self.status + if status == self.status && !reload && !self.pending_round && self.progress.is_none() - && !self.crashed; - if unchanged { + && !self.crashed + { return; } self.status = status; @@ -449,6 +483,26 @@ impl StatsPage { cx: &mut Context, ) -> Option { self.last_reload = Instant::now(); + if self.selection.is_some() { + if computing { + self.stats_generation += 1; + } + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default(); + self.current_season = self + .tracker + .current_season(now.as_millis() as i64) + .map(|s| s.name); + let (id, _) = self.selection.as_ref()?.as_ref().ok()?; + let id = id.to_lowercase(); + return self + .accounts + .iter() + .find(|a| riot_id(a).to_lowercase() == id) + .filter(|_| self.current_season.is_some()) + .map(|a| a.puuid.clone()); + } if matches!(self.season, SeasonScope::AllSeasons) && !matches!(self.filter, StateFilter::All | StateFilter::NeverPlayed) { @@ -470,6 +524,21 @@ impl StatsPage { viewed } + fn statistics_scope(&self) -> Scope { + if self.selection.is_some() + && 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( @@ -481,10 +550,7 @@ impl StatsPage { let viewed = self.prepare_statistics(start_job, window, cx); if let Some(puuid) = viewed { if start_job { - let scope = Scope { - season: self.season.clone(), - format: self.format, - }; + let scope = self.statistics_scope(); // A below-normal worker keeps hidden and visible windows responsive (rule #1). spawn_statistics( self.tracker.clone(), @@ -512,10 +578,7 @@ impl StatsPage { self.stats_error = None; self.stored = None; if let Some(puuid) = &viewed { - let scope = Scope { - season: self.season.clone(), - format: self.format, - }; + let scope = self.statistics_scope(); match self.tracker.statistics(puuid, &scope) { Ok(stats) => self.stats = Some(stats), Err(e) => self.stats_error = Some(format!("Statistiques indisponibles : {e}")), @@ -527,6 +590,12 @@ impl StatsPage { /// Shows `stats`: the Format choices, the charts and the table. fn show_statistics(&mut self, window: &mut Window, cx: &mut Context) { + if self.selection.is_some() { + 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 @@ -546,19 +615,134 @@ impl StatsPage { cx.notify(); } + fn live_pick(&self) -> Option<&ChampSelect> { + self.selection.as_ref()?.as_ref().ok().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_pick(); + let current = pick + .and_then(|s| s.current_row(rows)) + .map(crate::champion_table::pick_labels) + .unwrap_or_default(); + self.favorites = pick + .into_iter() + .flat_map(|s| { + s.crowd_favorites.iter().flatten().map(|id| { + let row = rows.iter().find(|r| r.champion.id == *id); + let mut label = + row.map_or_else(|| format!("Champion {id}"), |r| r.champion.name.clone()); + if let Some(state) = row.and_then(|r| r.state) { + label.push_str(" · "); + label.push_str(crate::text::state_label(Some(state))); + } + if !s.pickable.contains(id) && s.current != Some(*id) { + label.push_str(" · Indisponible"); + } + SharedString::from(label) + }) + }) + .collect(); + self.favorites.sort(); + self.current_pick = current; + } + fn refresh_table(&mut self, cx: &mut Context) { let rows = self.stats.iter().flat_map(|s| &s.rows); let rows = rows - .filter(|row| self.filter.keeps(row) && self.search.matches(&row.champion)) + .filter(|row| match &self.selection { + Some(Ok((_, pick))) => pick.remaining(row), + Some(Err(_)) => false, + None => self.filter.keeps(row) && self.search.matches(&row.champion), + }) .cloned() .collect(); - let in_season = self.in_season(); + let in_season = self.selection.is_some() || 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 pick = self.live_pick(); + let border = cx.theme().border; + let mut page = div().v_flex().size_full().p_3().gap_3().child( + div() + .text_xl() + .font_weight(FontWeight::SEMIBOLD) + .child("Sélection des champions · Arena"), + ); + let Some(pick) = pick else { + return page.child("Sélection indisponible dans le client."); + }; + page = page.child(match self.current_pick.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(pick.current.map_or_else( + || "Aucun champion sélectionné".to_owned(), + |id| format!("Champion {id} · Statistiques indisponibles"), + )), + }); + page.child( + div() + .v_flex() + .gap_2() + .p_3() + .border_1() + .border_color(border) + .rounded_md() + .child( + div() + .font_weight(FontWeight::SEMIBOLD) + .child("Favoris du public · Enclume"), + ) + .child( + div() + .h_flex() + .flex_wrap() + .gap_x_4() + .gap_y_1() + .children(self.favorites.iter().cloned().map(|name| div().child(name))) + .when(self.favorites.is_empty(), |row| { + row.child("Aucun favori communiqué par le client") + }), + ), + ) + .child( + div() + .font_weight(FontWeight::SEMIBOLD) + .child("Champions disponibles à valider"), + ) + .when(self.stats.is_none(), |page| { + page.child(self.stats_error.clone().unwrap_or_else(|| { + if self.current_season.is_none() { + "Aucune Saison en cours" + } else if self.status.updating.is_none() { + "Compte indisponible" + } else { + "Chargement des statistiques…" + } + .into() + })) + }) + .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 { let mut banners = Vec::new(); @@ -859,6 +1043,9 @@ impl Render for StatsPage { let theme = cx.theme(); (theme.border, theme.muted_foreground) }; + if self.selection.is_some() { + 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()); @@ -1110,6 +1297,58 @@ mod tests { }); } + #[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 { + current: Some(39), + pickable: [39].into(), + crowd_favorites: Some(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::Selection(Some(Ok(("Alice#EUW".into(), pick)))), w, cx); + }) + }); + cx.condition(&page, |p, _| !p.current_pick.is_empty()).await; + page.read_with(cx, |p, cx| { + assert_eq!(p.current_pick[0].as_ref(), "Irelia"); + assert!( + p.current_pick + .iter() + .any(|l| l.starts_with("Tentatives · 1")) + ); + assert_eq!(p.favorites.len(), 1); + assert!(p.favorites[0].starts_with("Irelia · ")); + assert_eq!(p.table.read(cx).names(), ["Irelia"]); + }); + window.update(|w, cx| { + page.update(cx, |p, cx| { + p.apply(Msg::Selection(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 typing_in_the_search_field_filters_the_table(cx: &mut TestAppContext) { let (page, cx) = open_page(cx); diff --git a/crates/app/src/worker.rs b/crates/app/src/worker.rs index 807ba90..aae96ed 100644 --- a/crates/app/src/worker.rs +++ b/crates/app/src/worker.rs @@ -6,16 +6,24 @@ use std::sync::Arc; use std::thread; use std::time::{SystemTime, UNIX_EPOCH}; -use arena_tracker_core::{Scope, Statistics, Status, SyncProgress, Tracker}; +use arena_tracker_core::{ + ChampSelect, ClientError, Scope, Statistics, Status, SyncProgress, Tracker, +}; use gpui_kit::base::async_util::Sender; +pub type Selection = Option>; + pub enum Msg { + Selection(Selection), /// 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. @@ -103,8 +111,7 @@ fn spawn_guarded(tx: Sender, on_panic: Msg, body: impl FnOnce(&Sender) }); } -/// 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. +/// Keeps the active Account up to date for as long as the app runs: event-driven follower rounds and a live selection subscription. `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, fallback_riot_id: String, tx: Sender) { @@ -113,20 +120,48 @@ pub fn spawn_follower(tracker: Arc, fallback_riot_id: String, tx: Sende let _ = champions.refresh_champions(); let _ = tx.try_send(Msg::Champions); }); - spawn_guarded(tx, Msg::Crashed, move |tx| { + // Coalesce history updates while Riot is busy; the WebSocket keeps delivering live picks. + let (wake, rounds) = std::sync::mpsc::sync_channel(1); + let history = tracker.clone(); + spawn_guarded(tx.clone(), Msg::Crashed, move |tx| { let fallback = Some(fallback_riot_id.as_str()).filter(|id| !id.trim().is_empty()); let mut first = true; - loop { - let changed = tracker.follow_client(now_ms(), fallback, &mut |progress| { + for () in rounds { + let changed = history.follow_client(now_ms(), fallback, &mut |progress| { let _ = tx.try_send(Msg::Progress(progress)); }); - let status = tracker.status(); - let _ = tx.try_send(Msg::Round { - status, - reload: changed || first, - }); + if tx + .try_send(Msg::Round { + status: history.status(), + reload: changed || first, + }) + .is_err() + { + break; + } first = false; - tracker.wait_for_client(); + } + }); + spawn_guarded(tx, Msg::Crashed, move |tx| { + let mut previous = None; + let mut selection_only = false; + while !tx.is_closed() { + if !selection_only + && matches!( + wake.try_send(()), + Err(std::sync::mpsc::TrySendError::Disconnected(())) + ) + { + break; + } + let selection = tracker.champ_select(); + if selection != previous { + if tx.try_send(Msg::Selection(selection.clone())).is_err() { + break; + } + previous = selection; + } + selection_only = tracker.wait_for_client(); } }); } diff --git a/crates/core/src/champ_select.rs b/crates/core/src/champ_select.rs new file mode 100644 index 0000000..2c477c3 --- /dev/null +++ b/crates/core/src/champ_select.rs @@ -0,0 +1,121 @@ +//! The local player's pick and the champions offered during an Arena champ select. +use std::collections::HashSet; + +use serde_json::Value; + +use crate::league_client::parse; +use crate::{ChampionRow, ChampionState, ClientError}; + +#[derive(Clone, Debug, PartialEq)] +pub struct ChampSelect { + pub current: Option, + /// The five anvil champions. None when the client could not report the list. + pub crowd_favorites: Option>, + pub pickable: HashSet, +} + +fn champion_id(value: &Value) -> Option { + 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())) +} + +impl ChampSelect { + pub fn available_champions( + pickable: &str, + disabled: &str, + owned: &str, + ) -> Result, ClientError> { + let mut ids: HashSet<_> = array(&parse(owned)?)? + .iter() + .filter(|c| c["ownership"]["owned"] == true) + .filter_map(|c| champion_id(&c["id"])) + .collect(); + for id in array(&parse(disabled)?)?.iter().filter_map(champion_id) { + ids.remove(&id); + } + Ok(array(&parse(pickable)?)? + .iter() + .filter_map(champion_id) + .filter(|id| ids.contains(id)) + .collect()) + } + + pub fn from_session( + body: &str, + mut pickable: HashSet, + crowd_favorites: Option>, + ) -> Result { + let session = parse(body)?; + 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"])); + for player in team + .iter() + .filter(|p| p["cellId"] != local && p["team"] == me["team"]) + { + if let Some(id) = champion_id(&player["championId"]) { + pickable.remove(&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"]) + { + pickable.remove(&id); + } + } + } + for key in ["myTeamBans", "theirTeamBans"] { + if let Some(bans) = session["bans"][key].as_array() { + for id in bans.iter().filter_map(champion_id) { + pickable.remove(&id); + } + } + } + Ok(Self { + current, + pickable, + crowd_favorites, + }) + } + + pub fn current_row<'a>(&self, rows: &'a [ChampionRow]) -> Option<&'a ChampionRow> { + let id = self.current?; + rows.iter().find(|r| r.champion.id == id) + } + + pub fn remaining(&self, row: &ChampionRow) -> bool { + row.state.is_some_and(|s| s != ChampionState::Completed) + && self.pickable.contains(&row.champion.id) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pickable_excludes_disabled_unowned_and_unavailable_champions() { + let owned = r#"[{"id":1,"ownership":{"owned":true}},{"id":2,"ownership":{"owned":false}},{"id":3,"ownership":{"owned":true}},{"id":4,"ownership":{"owned":true}}]"#; + assert_eq!( + ChampSelect::available_champions("[1,2,3]", "[3]", owned).unwrap(), + HashSet::from([1]) + ); + } +} diff --git a/crates/core/src/client.rs b/crates/core/src/client.rs index d4feb08..afedbf4 100644 --- a/crates/core/src/client.rs +++ b/crates/core/src/client.rs @@ -8,8 +8,17 @@ 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, ClientError>; + /// Reads the live Arena selection after gameflow enters champ select. + fn champ_select(&self) -> Result { + Err(ClientError::Absent) + } /// Blocks until the client reports a change or `timeout` elapses. fn wait_for_change(&self, timeout: Duration); + /// True when only the live selection needs another read. + fn wait_for_selection_event(&self, timeout: Duration) -> bool { + self.wait_for_change(timeout); + false + } } #[derive(Debug, Clone, PartialEq)] diff --git a/crates/core/src/follow.rs b/crates/core/src/follow.rs index 6ad80d7..c60c55d 100644 --- a/crates/core/src/follow.rs +++ b/crates/core/src/follow.rs @@ -303,17 +303,30 @@ impl Tracker { self.status() != before || added > 0 } + /// The signed-in Riot ID and its live pick. Independent of slow Match history imports. + pub fn champ_select(&self) -> Option> { + let client = self.client.as_ref()?; + let flow = client.gameflow().ok()?; + (flow.arena && flow.phase == GamePhase::ChampSelect).then(|| { + let (name, tag) = client.signed_in()?; + Ok((format!("{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. - pub fn wait_for_client(&self) { + pub fn wait_for_client(&self) -> bool { let timeout = if self.follow().pending.is_empty() { WAIT_OTHERWISE } else { WAIT_WHILE_PENDING }; match &self.client { - Some(client) => client.wait_for_change(timeout), - None => thread::sleep(timeout), + Some(client) => client.wait_for_selection_event(timeout), + None => { + thread::sleep(timeout); + false + } } } diff --git a/crates/core/src/league_client.rs b/crates/core/src/league_client.rs index 1dedc2e..b762068 100644 --- a/crates/core/src/league_client.rs +++ b/crates/core/src/league_client.rs @@ -27,10 +27,15 @@ const SETTINGS: &str = "Riot Games/Metadata/league_of_legends.live/league_of_legends.live.product_settings.yaml"; const DEFAULT_INSTALL_DIR: &str = r"C:\Riot Games\League of Legends"; const TIMEOUT: Duration = Duration::from_secs(5); -const TOPICS: [&str; 3] = [ +const FAVORITES: &str = "/lol-lobby-team-builder/champ-select/v1/crowd-favorte-champion-list"; +const TOPICS: &[&str] = &[ "OnJsonApiEvent_lol-gameflow_v1_session", "OnJsonApiEvent_lol-summoner_v1_current-summoner", "OnJsonApiEvent_lol-champ-select_v1_session", + "OnJsonApiEvent_lol-champ-select_v1_pickable-champion-ids", + "OnJsonApiEvent_lol-champ-select_v1_disabled-champion-ids", + "OnJsonApiEvent_lol-champions_v1_owned-champions-minimal", + "OnJsonApiEvent_lol-lobby-team-builder_champ-select_v1_crowd-favorite-champion-list", ]; /// The local League client's API (unofficial, read-only). Deliberately no `Debug`: it handles @@ -42,6 +47,13 @@ pub struct LeagueClient { /// configuration is downloaded once per track. tracks: Mutex)>>, events: Mutex>, + pool: Mutex>, +} + +struct ChampionPool { + available: std::collections::HashSet, + favorites: Option>, + next_favorites_read: Instant, } struct Events(WebSocket>); @@ -82,6 +94,7 @@ impl LeagueClient { agent, tracks: Mutex::default(), events: Mutex::default(), + pool: Mutex::default(), } } @@ -155,7 +168,40 @@ impl GameClientSource for LeagueClient { fn gameflow(&self) -> Result { let (status, body) = self.get("/lol-gameflow/v1/session")?; - decode_gameflow(status, &body) + let flow = decode_gameflow(status, &body)?; + if !flow.arena || flow.phase != GamePhase::ChampSelect { + *lock(&self.pool) = None; + } + Ok(flow) + } + + fn champ_select(&self) -> Result { + let session = self.get_ok("/lol-champ-select/v1/session")?; + let mut pool = lock(&self.pool); + if pool.is_none() { + let available = crate::ChampSelect::available_champions( + &self.get_ok("/lol-champ-select/v1/pickable-champion-ids")?, + &self.get_ok("/lol-champ-select/v1/disabled-champion-ids")?, + &self.get_ok("/lol-champions/v1/owned-champions-minimal")?, + )?; + *pool = Some(ChampionPool { + available, + favorites: None, + next_favorites_read: Instant::now(), + }); + } + let pool = pool.as_mut().unwrap(); + if pool.favorites.as_ref().is_none_or(Vec::is_empty) + && Instant::now() >= pool.next_favorites_read + { + // The GET spells it "favorte"; the event spells it "favorite". + pool.favorites = self + .get_ok(FAVORITES) + .ok() + .and_then(|s| serde_json::from_str(&s).ok()); + pool.next_favorites_read = Instant::now() + Duration::from_secs(1); + } + crate::ChampSelect::from_session(&session, pool.available.clone(), pool.favorites.clone()) } fn official_progress(&self, track_name: &str) -> Result, ClientError> { @@ -183,14 +229,23 @@ impl GameClientSource for LeagueClient { } fn wait_for_change(&self, timeout: Duration) { + self.wait_for_selection_event(timeout); + } + + fn wait_for_selection_event(&self, timeout: Duration) -> bool { let started = Instant::now(); let mut events = lock(&self.events); if events.is_none() { + *lock(&self.pool) = None; *events = self.connect(); + // Re-read the snapshot after subscribing. + if events.is_some() { + return false; + } } let Some(connection) = events.as_mut() else { thread::sleep(timeout.min(TIMEOUT)); - return; + return false; }; // Right after subscribing, the client sends one empty text frame per subscription // (observed on patch 16.22): they and pings are not changes. @@ -203,14 +258,22 @@ impl GameClientSource for LeagueClient { .map_err(tungstenite::Error::Io) .and_then(|()| connection.0.read()); match read { - Ok(Message::Text(text)) if !text.is_empty() => return, + Ok(Message::Text(text)) if !text.is_empty() => { + let topic = text.split('"').nth(1).unwrap_or_default(); + let session = topic == "OnJsonApiEvent_lol-champ-select_v1_session"; + if !session { + *lock(&self.pool) = None; + } + return topic.starts_with("OnJsonApiEvent_lol-champ-select_") + || topic.ends_with("_crowd-favorite-champion-list"); + } Ok(Message::Close(_)) => *events = None, Ok(_) => continue, Err(tungstenite::Error::Io(e)) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {} Err(_) => *events = None, } - return; + return false; } } } @@ -271,7 +334,7 @@ fn install_dir_from_settings(yaml: &str) -> Option { (!path.is_empty()).then(|| path.into()) } -fn parse(body: &str) -> Result { +pub(crate) fn parse(body: &str) -> Result { serde_json::from_str(body) .map_err(|e| ClientError::Other(format!("Réponse du client illisible : {e}"))) } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 010a1df..df8f615 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -1,3 +1,4 @@ +mod champ_select; mod champion_search; mod champions; mod client; @@ -12,6 +13,7 @@ mod seasons; mod statistics; mod tracker; +pub use champ_select::ChampSelect; pub use champion_search::ChampionSearch; pub use champions::{Champion, ChampionCatalog, ChampionSource, DataDragon}; pub use client::{ClientError, GameClientSource, GamePhase, Gameflow}; diff --git a/crates/core/tests/common/mod.rs b/crates/core/tests/common/mod.rs index 3c9ccf5..a528df5 100644 --- a/crates/core/tests/common/mod.rs +++ b/crates/core/tests/common/mod.rs @@ -569,6 +569,7 @@ struct ClientState { gameflow: Gameflow, tracks: HashMap, waits: Vec, + selection: Option, } impl FakeClient { @@ -633,6 +634,10 @@ impl FakeClient { self.state.lock().unwrap().gameflow.game_id = game_id; } + pub fn set_selection(&self, value: arena_tracker_core::ChampSelect) { + self.state.lock().unwrap().selection = Some(value); + } + pub fn set_track(&self, name: &str, value: u32) { self.state.lock().unwrap().tracks.insert(name.into(), value); } @@ -659,6 +664,15 @@ impl GameClientSource for FakeClient { Ok(state.gameflow.clone()) } + fn champ_select(&self) -> Result { + self.state + .lock() + .unwrap() + .selection + .clone() + .ok_or(ClientError::Absent) + } + fn official_progress(&self, track_name: &str) -> Result, ClientError> { let state = self.state.lock().unwrap(); state.signed_in.as_ref().ok_or(ClientError::Absent)?; diff --git a/crates/core/tests/follow.rs b/crates/core/tests/follow.rs index 882172a..6af9682 100644 --- a/crates/core/tests/follow.rs +++ b/crates/core/tests/follow.rs @@ -1023,3 +1023,78 @@ 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 arena_tracker_core::{ChampSelect, ChampionState}; + use serde_json::Value; + 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(); + let read = |frame: usize| { + ChampSelect::from_session( + &capture["sessions"][frame].to_string(), + ChampSelect::available_champions( + &capture["pickableChampionIds"].to_string(), + &capture["disabledChampionIds"].to_string(), + &capture["ownedChampionsMinimal"].to_string(), + ) + .unwrap(), + Some(serde_json::from_value(capture["crowdFavoriteChampionIds"].clone()).unwrap()), + ) + .unwrap() + }; + world.client.set_selection(read(0)); + world.client.set_phase("ChampSelect", false); + round(&tracker); + assert!(tracker.champ_select().is_none()); + world.client.set_phase("ChampSelect", true); + let rows = tracker + .statistics( + SELF_PUUID, + &Scope { + season: SeasonScope::Season(S2.into()), + format: None, + }, + ) + .unwrap() + .rows; + for (frame, current, remaining) in [ + (0, None, vec![12, 25, 50, 103, 233]), + (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.set_selection(read(frame)); + round(&tracker); + let (account, pick) = tracker.champ_select().unwrap().unwrap(); + assert_eq!(account, "Joueur#EUW"); + assert_eq!( + pick.crowd_favorites.as_deref(), + Some([233, 64, 5, 16, 68].as_slice()) + ); + 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); + } + world.client.set_phase("InProgress", true); + round(&tracker); + assert!(tracker.champ_select().is_none()); +}