Show live Arena champion picks and crowd favorites (#13)

This commit is contained in:
nessar authored and nessar committed 2026-11-19 22:17:14 +01:00
1 parent fabaa8a60f
commit f4a9e5e7a8
11 files changed
+636 -39

No files matched your search

+121
View File
@@ -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<u32>,
/// The five anvil champions. None when the client could not report the list.
pub crowd_favorites: Option<Vec<u32>>,
pub pickable: HashSet<u32>,
}
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()))
}
impl ChampSelect {
pub fn available_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())
}
pub fn from_session(
body: &str,
mut pickable: HashSet<u32>,
crowd_favorites: Option<Vec<u32>>,
) -> Result<Self, ClientError> {
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])
);
}
}
+9
View File
@@ -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<Option<u32>, ClientError>;
/// Reads the live Arena selection after gameflow enters champ select.
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
}
}
#[derive(Debug, Clone, PartialEq)]
+16 -3
View File
@@ -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<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()?))
})
}
/// 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
}
}
}
+69 -6
View File
@@ -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<HashMap<String, (String, Option<String>)>>,
events: Mutex<Option<Events>>,
pool: Mutex<Option<ChampionPool>>,
}
struct ChampionPool {
available: std::collections::HashSet<u32>,
favorites: Option<Vec<u32>>,
next_favorites_read: Instant,
}
struct Events(WebSocket<MaybeTlsStream<TcpStream>>);
@@ -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<Gameflow, ClientError> {
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<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 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<Option<u32>, 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<PathBuf> {
(!path.is_empty()).then(|| path.into())
}
fn parse(body: &str) -> Result<Value, ClientError> {
pub(crate) fn parse(body: &str) -> Result<Value, ClientError> {
serde_json::from_str(body)
.map_err(|e| ClientError::Other(format!("Réponse du client illisible : {e}")))
}
+2
View File
@@ -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};