Fix champ select review findings (#13)

- redraw the page on hover and lock-in changes, and reset the settings form
  when champ select takes the window away
- keep the current pick when a client read fails; only a real answer that
  the draft is over ends it
- read the client once per wake and share it between the follower and the
  live selection, reuse session event payloads, and touch only the cached
  champion list an event concerns
- replay the captured raw client responses in the fake and cover the list
  cache, event updates and the anvil-champion read
- name the five champions anvil champions and the set pickable, document
  them, and prepare redraw strings ahead of render
This commit is contained in:
nessar authored and nessar committed 2026-11-19 22:17:14 +01:00
1 parent f4a9e5e7a8
commit 5ba3251875
12 files changed
+799 -271

No files matched your search

+206 -36
View File
@@ -1,17 +1,37 @@
//! The local player's pick and the champions offered during an Arena champ select.
use std::collections::HashSet;
use std::sync::Arc;
use serde_json::Value;
use crate::league_client::parse;
use crate::{ChampionRow, ChampionState, ClientError};
#[derive(Clone, Debug, PartialEq)]
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. None when the client could not report the list.
pub crowd_favorites: Option<Vec<u32>>,
pub pickable: HashSet<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 draft 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 session.
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> {
@@ -25,33 +45,51 @@ fn array(value: &Value) -> Result<&[Value], ClientError> {
.ok_or_else(|| ClientError::Other("Liste de champions illisible".into()))
}
fn ids(body: &str) -> Result<HashSet<u32>, ClientError> {
Ok(array(&parse(body)?)?
.iter()
.filter_map(champion_id)
.collect())
}
fn ids_from_event(data: &Value) -> Option<HashSet<u32>> {
data.as_array()
.map(|ids| ids.iter().filter_map(champion_id).collect())
}
fn ordered_ids(data: &Value) -> Option<Vec<u32>> {
data.as_array()
.map(|ids| ids.iter().filter_map(champion_id).collect())
}
impl ChampSelect {
pub fn available_champions(
/// A selection with nothing banned or taken, for tests and 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(),
}
}
/// The champions the client offers, minus those disabled for this draft. The pickable list
/// is the client's answer to what the player can pick: it already includes free-rotation and
/// rented champions, so ownership is not consulted.
pub fn pickable_champions(
pickable: &str,
disabled: &str,
owned: &str,
) -> Result<HashSet<u32>, 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())
) -> Result<Arc<HashSet<u32>>, ClientError> {
let pickable = ids(pickable)?;
let disabled = ids(disabled)?;
Ok(Arc::new(pickable.difference(&disabled).copied().collect()))
}
pub fn from_session(
body: &str,
mut pickable: HashSet<u32>,
crowd_favorites: Option<Vec<u32>>,
session: &Value,
pickable: Arc<HashSet<u32>>,
anvil_champions: Vec<u32>,
) -> Result<Self, ClientError> {
let session = parse(body)?;
let local = session["localPlayerCellId"]
.as_i64()
.ok_or(ClientError::Absent)?;
@@ -62,12 +100,13 @@ impl ChampSelect {
.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"]) {
pickable.remove(&id);
excluded.insert(id);
}
}
// In Arena the confirmed bans were in actions while both team ban lists were empty.
@@ -77,21 +116,20 @@ impl ChampSelect {
&& action["completed"] == true
&& let Some(id) = champion_id(&action["championId"])
{
pickable.remove(&id);
excluded.insert(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);
}
excluded.extend(bans.iter().filter_map(champion_id));
}
}
Ok(Self {
current,
anvil_champions,
pickable,
crowd_favorites,
excluded,
})
}
@@ -100,22 +138,154 @@ impl ChampSelect {
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 selections 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 draft. 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.pickable.contains(&row.champion.id)
row.state.is_some_and(|s| s != ChampionState::Completed) && self.can_pick(row.champion.id)
}
}
/// The champion lists of a draft: fetched 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 fetch(
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) = ordered_ids(&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
}
/// Applies one client event. Returns false when the topic concerns something else; the lists
/// it does not concern are left untouched.
pub(crate) fn apply_event(&mut self, topic: &str, data: &Value) -> bool {
match topic {
PICKABLE_EVENT => {
if let Some(ids) = ids_from_event(data) {
self.offered = ids;
self.rebuild();
}
true
}
DISABLED_EVENT => {
if let Some(ids) = ids_from_event(data) {
self.disabled = ids;
self.rebuild();
}
true
}
ANVIL_EVENT => {
if let Some(ids) = ordered_ids(data) {
self.anvil = ids;
}
true
}
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[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}}]"#;
fn pickable_excludes_disabled_champions() {
assert_eq!(
ChampSelect::available_champions("[1,2,3]", "[3]", owned).unwrap(),
HashSet::from([1])
&*ChampSelect::pickable_champions("[1,2,3]", "[3]").unwrap(),
&HashSet::from([1, 2])
);
}
#[test]
fn the_lists_change_only_for_the_events_that_concern_them() {
let mut lists = ChampSelectLists::fetch("[1,2,3]", "[3]", Some("[9,8]")).unwrap();
assert_eq!(&*lists.pickable(), &HashSet::from([1, 2]));
assert_eq!(lists.anvil(), [9, 8]);
// A gameflow event used to clear the whole cache, costing three requests again.
assert!(!lists.apply_event(
"OnJsonApiEvent_lol-gameflow_v1_session",
&json!({"phase": "ChampSelect"})
));
assert_eq!(&*lists.pickable(), &HashSet::from([1, 2]));
assert_eq!(lists.anvil(), [9, 8]);
assert!(lists.apply_event(PICKABLE_EVENT, &json!([1, 4])));
assert_eq!(&*lists.pickable(), &HashSet::from([1, 4]));
assert_eq!(lists.anvil(), [9, 8]);
assert!(lists.apply_event(DISABLED_EVENT, &json!([1])));
assert_eq!(&*lists.pickable(), &HashSet::from([4]));
assert!(lists.apply_event(ANVIL_EVENT, &json!([5, 6])));
assert_eq!(lists.anvil(), [5, 6]);
}
#[test]
fn the_anvil_champions_are_read_once_when_the_draft_starts() {
assert!(
ChampSelectLists::fetch("[]", "[]", None)
.unwrap()
.anvil()
.is_empty()
);
assert_eq!(
ChampSelectLists::fetch("[]", "[]", Some("[1,2]"))
.unwrap()
.anvil(),
[1, 2]
);
// A malformed anvil answer only loses the anvil list, not the pickable one.
let lists = ChampSelectLists::fetch("[7]", "[]", Some("not json")).unwrap();
assert_eq!(&*lists.pickable(), &HashSet::from([7]));
assert!(lists.anvil().is_empty());
}
}
+54 -6
View File
@@ -12,12 +12,41 @@ pub trait GameClientSource: Send + Sync {
fn champ_select(&self) -> Result<crate::ChampSelect, ClientError> {
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
/// 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.
Selection,
/// Anything else.
#[default]
Other,
}
/// One read of the client, shared by the follower round and the live selection: 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 {
Self {
signed_in: source.signed_in(),
gameflow: source.gameflow(),
}
}
pub fn absent() -> Self {
Self {
signed_in: Err(ClientError::Absent),
gameflow: Err(ClientError::Absent),
}
}
}
@@ -58,6 +87,13 @@ 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 super::*;
@@ -84,4 +120,16 @@ 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());
}
}
+84 -33
View File
@@ -5,7 +5,7 @@ use std::time::Duration;
use rusqlite::OptionalExtension;
use crate::client::{GameClientSource, GamePhase, Gameflow};
use crate::client::{ClientEvent, ClientSnapshot, GameClientSource, GamePhase, Gameflow};
use crate::error::{Error, SourceError};
use crate::model::{Account, SyncProgress, SyncReport};
use crate::seasons::Season;
@@ -129,14 +129,20 @@ pub(crate) struct Follow {
official_progress: ProgressCheck,
}
fn riot_id(account: &Account) -> String {
format!("{}#{}", account.game_name, account.tag_line)
/// `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 same_riot_id(a: &str, b: &str) -> bool {
/// Riot IDs differ in case only when they name the same Account.
pub fn same_riot_id(a: &str, b: &str) -> bool {
a.to_lowercase() == b.to_lowercase()
}
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 {
@@ -191,16 +197,39 @@ 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 selection 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, 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 signed_in = snapshot
.signed_in
.as_ref()
.ok()
.map(|(name, tag)| riot_id(name, tag));
let gameflow = snapshot.gameflow.as_ref().ok().cloned();
let adopt = {
let mut follow = self.follow();
if let Some(id) = fallback_riot_id.map(str::trim).filter(|id| !id.is_empty()) {
@@ -287,7 +316,7 @@ impl Tracker {
.follow()
.updating
.as_ref()
.is_some_and(|a| same_riot_id(&riot_id(a), signed_in)) =>
.is_some_and(|a| same_riot_id(&account_riot_id(a), signed_in)) =>
{
client
.official_progress(&track)
@@ -303,29 +332,51 @@ 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<Result<(String, crate::ChampSelect), crate::ClientError>> {
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()?))
})
/// The signed-in Riot ID and its live pick, independent of slow Match history imports.
/// `Err` means the read failed: keep what is shown. `Ok(None)` means no Arena champ select
/// is running.
pub fn champ_select(&self) -> Result<Option<(String, crate::ChampSelect)>, crate::ClientError> {
self.champ_select_with(&self.client_snapshot())
}
/// The live pick from a client read already made for this wake.
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.
pub fn wait_for_client(&self) -> bool {
/// events cause try it only once its time has come. The event says whether only the live
/// selection needs another read.
pub fn wait_for_client(&self) -> ClientEvent {
let timeout = if self.follow().pending.is_empty() {
WAIT_OTHERWISE
} else {
WAIT_WHILE_PENDING
};
match &self.client {
Some(client) => client.wait_for_selection_event(timeout),
Some(client) => client.wait_for_event(timeout),
None => {
thread::sleep(timeout);
false
ClientEvent::Other
}
}
}
@@ -342,7 +393,7 @@ impl Tracker {
};
let result = match (signed_in, updating) {
(Some(id), _) => self.adopt(&id, on_progress),
(None, Some(account)) => self.update(&riot_id(&account), on_progress),
(None, Some(account)) => self.update(&account_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)),
@@ -355,7 +406,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| riot_id(&a))
last.map(|a| account_riot_id(&a))
.or_else(|| self.follow().fallback.clone())
}
@@ -368,10 +419,10 @@ impl Tracker {
/// adds a Match ends the waits for the games the client gave no id for.
fn update(
&self,
riot_id: &str,
account_id: &str,
on_progress: &mut dyn FnMut(SyncProgress),
) -> Result<SyncReport, UpdateProblem> {
match self.sync(riot_id, on_progress) {
match self.sync(account_id, on_progress) {
Ok(report) => {
if report.added > 0 {
self.follow().pending.retain(|p| p.game_id.is_some());
@@ -386,15 +437,15 @@ impl Tracker {
/// active one is the stored Account with that Riot ID, if any: never the previous Account.
fn adopt(
&self,
riot_id: &str,
account_id: &str,
on_progress: &mut dyn FnMut(SyncProgress),
) -> Result<SyncReport, UpdateProblem> {
let result = self.update(riot_id, on_progress);
let result = self.update(account_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(&self::riot_id(a), riot_id))
.find(|a| same_riot_id(&account_riot_id(a), account_id))
}),
};
if let Some(account) = &account
@@ -404,7 +455,7 @@ impl Tracker {
}
let mut follow = self.follow();
follow.updating = account;
follow.adopted = result.is_ok().then(|| riot_id.into());
follow.adopted = result.is_ok().then(|| account_id.into());
follow.adopt_retry_after_ms = follow.adopt_retry_after_ms.filter(|_| result.is_err());
result
}
@@ -421,7 +472,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(&riot_id(account), on_progress);
let added = self.update(&account_riot_id(account), on_progress);
return (added.map_or(0, |report| report.added), false);
};
match self.fetch_and_store(&account.puuid, &match_id) {
+141 -58
View File
@@ -17,7 +17,8 @@ use tungstenite::{Connector, Message, WebSocket, client_tls_with_config};
use ureq::Agent;
use ureq::tls::{Certificate, RootCerts, TlsConfig};
use crate::client::{ClientError, GameClientSource, GamePhase, Gameflow};
use crate::champ_select::{ANVIL_EVENT, ChampSelectLists, DISABLED_EVENT, PICKABLE_EVENT};
use crate::client::{ClientError, ClientEvent, GameClientSource, GamePhase, Gameflow};
use crate::riot::encode;
/// Riot's published root certificate: the client's certificate is signed by it, and it is
@@ -27,15 +28,19 @@ 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 FAVORITES: &str = "/lol-lobby-team-builder/champ-select/v1/crowd-favorte-champion-list";
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] = &[
"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",
SESSION_EVENT,
PICKABLE_EVENT,
DISABLED_EVENT,
ANVIL_EVENT,
];
/// The local League client's API (unofficial, read-only). Deliberately no `Debug`: it handles
@@ -47,13 +52,14 @@ pub struct LeagueClient {
/// configuration is downloaded once per track.
tracks: Mutex<HashMap<String, (String, Option<String>)>>,
events: Mutex<Option<Events>>,
pool: Mutex<Option<ChampionPool>>,
champion_lists: Mutex<ChampSelectCache>,
}
struct ChampionPool {
available: std::collections::HashSet<u32>,
favorites: Option<Vec<u32>>,
next_favorites_read: Instant,
/// The champion lists of the current draft and the latest session the client sent as an event.
#[derive(Default)]
struct ChampSelectCache {
lists: Option<ChampSelectLists>,
session: Option<Value>,
}
struct Events(WebSocket<MaybeTlsStream<TcpStream>>);
@@ -94,7 +100,7 @@ impl LeagueClient {
agent,
tracks: Mutex::default(),
events: Mutex::default(),
pool: Mutex::default(),
champion_lists: Mutex::default(),
}
}
@@ -169,39 +175,35 @@ 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)?;
if !flow.arena || flow.phase != GamePhase::ChampSelect {
*lock(&self.pool) = None;
if !flow.is_arena_champ_select() {
*lock(&self.champion_lists) = ChampSelectCache::default();
}
Ok(flow)
}
fn champ_select(&self) -> Result<crate::ChampSelect, ClientError> {
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 session = {
let mut cache = lock(&self.champion_lists);
cache.session.take()
};
let session = match session {
Some(session) => session,
None => parse(&self.get_ok(SESSION)?)?,
};
let mut cache = lock(&self.champion_lists);
if cache.lists.is_none() {
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();
cache.lists = Some(ChampSelectLists::fetch(
&pickable,
&disabled,
anvil.as_deref(),
)?);
}
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())
let lists = cache.lists.as_ref().expect("set just above");
crate::ChampSelect::from_session(&session, lists.pickable(), lists.anvil().to_vec())
}
fn official_progress(&self, track_name: &str) -> Result<Option<u32>, ClientError> {
@@ -228,24 +230,21 @@ impl GameClientSource for LeagueClient {
decode_counter(&body, counter_id.as_deref())
}
fn wait_for_change(&self, timeout: Duration) {
self.wait_for_selection_event(timeout);
}
fn wait_for_selection_event(&self, timeout: Duration) -> bool {
fn wait_for_event(&self, timeout: Duration) -> ClientEvent {
let started = Instant::now();
let mut events = lock(&self.events);
if events.is_none() {
*lock(&self.pool) = None;
// A reconnection may follow a client restart: the lists belong to the previous one.
*lock(&self.champion_lists) = ChampSelectCache::default();
*events = self.connect();
// Re-read the snapshot after subscribing.
if events.is_some() {
return false;
return ClientEvent::Other;
}
}
let Some(connection) = events.as_mut() else {
thread::sleep(timeout.min(TIMEOUT));
return false;
return ClientEvent::Other;
};
// Right after subscribing, the client sends one empty text frame per subscription
// (observed on patch 16.22): they and pings are not changes.
@@ -259,13 +258,10 @@ impl GameClientSource for LeagueClient {
.and_then(|()| connection.0.read());
match read {
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");
let Some((topic, data)) = decode_event(&text) else {
continue;
};
return self.apply_event(&topic, data);
}
Ok(Message::Close(_)) => *events = None,
Ok(_) => continue,
@@ -273,7 +269,30 @@ impl GameClientSource for LeagueClient {
if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {}
Err(_) => *events = None,
}
return false;
return ClientEvent::Other;
}
}
}
impl LeagueClient {
/// Applies one event to the cache, touching only the list it concerns.
fn apply_event(&self, topic: &str, data: Value) -> ClientEvent {
match topic {
SESSION_EVENT => {
let mut cache = lock(&self.champion_lists);
if data.is_object() {
cache.session = Some(data);
}
ClientEvent::Selection
}
PICKABLE_EVENT | DISABLED_EVENT | ANVIL_EVENT => {
let mut cache = lock(&self.champion_lists);
if let Some(lists) = cache.lists.as_mut() {
lists.apply_event(topic, &data);
}
ClientEvent::Selection
}
_ => ClientEvent::Other,
}
}
}
@@ -339,6 +358,13 @@ pub(crate) fn parse(body: &str) -> Result<Value, ClientError> {
.map_err(|e| ClientError::Other(format!("Réponse du client illisible : {e}")))
}
/// Topic and data of a WebSocket event frame, `[8, "topic", data]`.
fn decode_event(text: &str) -> Option<(String, Value)> {
let frame = parse(text).ok()?;
let topic = frame.get(1)?.as_str()?.to_owned();
Some((topic, frame.get(2).cloned().unwrap_or(Value::Null)))
}
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());
@@ -350,7 +376,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.
fn decode_gameflow(status: u16, body: &str) -> Result<Gameflow, ClientError> {
pub fn decode_gameflow(status: u16, body: &str) -> Result<Gameflow, ClientError> {
match status {
404 => Ok(Gameflow::default()),
200 => {
@@ -606,6 +632,60 @@ mod tests {
assert_eq!(decode_counter("{}", Some(counter)), Ok(None));
}
#[test]
fn reads_the_topic_and_data_of_an_event_frame() {
let frame = r#"[8,"OnJsonApiEvent_lol-champ-select_v1_session",{"localPlayerCellId":16}]"#;
let (topic, data) = decode_event(frame).unwrap();
assert_eq!(topic, SESSION_EVENT);
assert_eq!(data["localPlayerCellId"], 16);
assert!(decode_event("not json").is_none());
assert!(decode_event("[]").is_none());
}
#[test]
fn events_update_only_the_list_they_concern() {
use serde_json::json;
use std::collections::HashSet;
let client = LeagueClient::in_dir(PathBuf::new());
*lock(&client.champion_lists) = ChampSelectCache {
lists: Some(ChampSelectLists::fetch("[1,2]", "[2]", Some("[9]")).unwrap()),
session: None,
};
// 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!({})),
ClientEvent::Other
);
{
let cache = lock(&client.champion_lists);
let lists = cache.lists.as_ref().unwrap();
assert_eq!(&*lists.pickable(), &HashSet::from([1]));
assert_eq!(lists.anvil(), [9]);
}
assert_eq!(
client.apply_event(PICKABLE_EVENT, json!([1, 3])),
ClientEvent::Selection
);
assert_eq!(
&*lock(&client.champion_lists)
.lists
.as_ref()
.unwrap()
.pickable(),
&HashSet::from([1, 3])
);
// A session event is kept for the next read instead of a GET.
assert_eq!(
client.apply_event(SESSION_EVENT, json!({"localPlayerCellId": 16})),
ClientEvent::Selection
);
assert_eq!(
lock(&client.champion_lists).session,
Some(json!({"localPlayerCellId": 16}))
);
}
#[test]
fn without_a_lockfile_the_client_is_absent() {
let dir = tempfile::tempdir().unwrap();
@@ -614,7 +694,10 @@ mod tests {
assert_eq!(client.gameflow(), Err(ClientError::Absent));
assert_eq!(client.official_progress(SEASON_2), Err(ClientError::Absent));
let started = Instant::now();
client.wait_for_change(Duration::from_millis(50));
assert_eq!(
client.wait_for_event(Duration::from_millis(50)),
ClientEvent::Other
);
assert!(started.elapsed() >= Duration::from_millis(50));
assert!(started.elapsed() < TIMEOUT);
}
+5 -3
View File
@@ -16,12 +16,14 @@ 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};
pub use client::{ClientError, ClientEvent, ClientSnapshot, 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};
pub use league_client::LeagueClient;
pub use follow::{
MATCH_RETRIES, ProgressCheck, RETRY_EVERY_MS, Status, UpdateProblem, riot_id, same_riot_id,
};
pub use league_client::{LeagueClient, decode_gameflow};
pub use model::{Account, Format, Match, SyncProgress, SyncReport};
pub use riot::RiotApi;
pub use seasons::{Season, default_seasons, load_seasons};