Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.
Rust downloadmanagerguihacktoberfesthomebrewlightweightlinuxlinux-distributionlocal-firstmacosmacos-packagemedia-toolboxopen-sourcerustsveltetauritrendingtrending-repositorieswindowswindows-desktopytdlp
feat(league): player search, best duos, jungle pathing and chat summary
tonhowtfd9765907d058
diff --git a/src-tauri/src/commands/league/analysis.rs b/src-tauri/src/commands/league/analysis.rsnew file mode 100644index 00000000..16d666cb--- /dev/null+++ b/src-tauri/src/commands/league/analysis.rs@@ -0,0 +1,365 @@+//! Aggregations over match history: champion records, duo synergy and the+//! early-game map reading used for jungle pathing.++use super::stats;++/// Summoner's Rift is roughly a 15000x15000 square with mid on the diagonal.+pub const MAP_MAX: f64 = 15_000.0;++/// Minutes of a game considered "early" for pathing purposes.+pub const EARLY_MINUTES: usize = 14;++/// A kill counts for more than a position sample when reading intent.+pub const KILL_WEIGHT: f64 = 5.0;++/// Lanes of the map, plus the ambiguous middle ground.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Zone {+ Top,+ Mid,+ Bot,+}++/// Classifies a map coordinate into a lane.+///+/// The top-left and bottom-right corners are unambiguous; everything else is+/// decided by distance from the mid diagonal (`y == x`).+pub fn classify_zone(x: f64, y: f64) -> Zone {+ if x < 5_000.0 && y > 9_000.0 {+ return Zone::Top;+ }+ if x > 9_000.0 && y < 5_000.0 {+ return Zone::Bot;+ }+ if (y - x).abs() <= 3_500.0 {+ return Zone::Mid;+ }+ if y > x {+ Zone::Top+ } else {+ Zone::Bot+ }+}++/// Share of early-game presence per lane, from position samples and kills.+#[derive(Debug, Clone, Copy, Default, PartialEq)]+pub struct ZoneWeights {+ pub top: f64,+ pub mid: f64,+ pub bot: f64,+}++impl ZoneWeights {+ pub fn add(&mut self, zone: Zone, weight: f64) {+ match zone {+ Zone::Top => self.top += weight,+ Zone::Mid => self.mid += weight,+ Zone::Bot => self.bot += weight,+ }+ }++ pub fn total(&self) -> f64 {+ self.top + self.mid + self.bot+ }++ /// Normalises to shares that sum to 1 (all zeros when there is no data).+ pub fn shares(&self) -> ZoneWeights {+ let t = self.total();+ if t <= 0.0 {+ return ZoneWeights::default();+ }+ ZoneWeights {+ top: self.top / t,+ mid: self.mid / t,+ bot: self.bot / t,+ }+ }++ /// Short verdict about where this jungler spends the early game.+ pub fn preference(&self) -> &'static str {+ let s = self.shares();+ if s.total() <= 0.0 {+ return "unknown";+ }+ let max = s.top.max(s.mid).max(s.bot);+ if s.mid + s.bot >= 0.70 && s.top <= 0.28 {+ return "mid_bot";+ }+ if s.top + s.mid >= 0.70 && s.bot <= 0.28 {+ return "top_mid";+ }+ let second = {+ let mut v = [s.top, s.mid, s.bot];+ v.sort_by(|a, b| b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal));+ v[1]+ };+ if max >= 0.40 && max - second >= 0.08 {+ if (max - s.top).abs() < f64::EPSILON {+ "top"+ } else if (max - s.mid).abs() < f64::EPSILON {+ "mid"+ } else {+ "bot"+ }+ } else {+ "balanced"+ }+ }+}++/// The eight buff camps, as (x, y, blue_side).+pub const CAMPS: [(&str, f64, f64, bool); 8] = [+ ("blue_buff", 3_830.0, 7_880.0, true),+ ("wolves", 3_800.0, 6_440.0, true),+ ("red_buff", 7_760.0, 4_010.0, true),+ ("raptors", 6_970.0, 5_460.0, true),+ ("blue_buff", 10_990.0, 7_000.0, false),+ ("wolves", 11_020.0, 8_440.0, false),+ ("red_buff", 7_060.0, 10_870.0, false),+ ("raptors", 7_850.0, 9_420.0, false),+];++/// Nearest starting camp to a position, and whether it sits on the blue side.+pub fn nearest_camp(x: f64, y: f64) -> (&'static str, bool) {+ let mut best = (CAMPS[0].0, CAMPS[0].3);+ let mut best_d = f64::MAX;+ for (name, cx, cy, blue) in CAMPS.iter() {+ let d = (x - cx).powi(2) + (y - cy).powi(2);+ if d < best_d {+ best_d = d;+ best = (name, *blue);+ }+ }+ best+}++/// True when the first camp visited belongs to the opposing side of the map.+pub fn is_invade(first_camp_blue_side: bool, player_on_blue_side: bool) -> bool {+ first_camp_blue_side != player_on_blue_side+}++/// A gank is likely when the clear was cut short: enough camps for level 3 but+/// well below a full clear, with champion damage already dealt.+pub fn looks_like_level3_gank(cs_at_frame3: u32, level: u32, had_champion_action: bool) -> bool {+ (12..20).contains(&cs_at_frame3) && level == 3 && had_champion_action+}++/// One champion's record inside a player's history.+#[derive(Debug, Clone, Default)]+pub struct ChampionRecord {+ pub champion_id: i64,+ pub games: u32,+ pub wins: u32,+ pub kills: u32,+ pub deaths: u32,+ pub assists: u32,+ pub cs: f64,+ pub seconds: f64,+}++impl ChampionRecord {+ pub fn winrate(&self) -> f64 {+ if self.games == 0 {+ 0.0+ } else {+ self.wins as f64 / self.games as f64+ }+ }++ pub fn kda(&self) -> f64 {+ stats::kda(self.kills, self.deaths, self.assists)+ }++ pub fn cs_per_min(&self) -> f64 {+ stats::per_minute(self.cs, self.seconds)+ }+}++/// Sorts champion records the way a profile page does: most played first, then+/// win rate. Records under `min_games` are dropped (op.gg shows 2+ games).+pub fn rank_champion_records(+ mut records: Vec<ChampionRecord>,+ min_games: u32,+) -> Vec<ChampionRecord> {+ records.retain(|r| r.games >= min_games);+ records.sort_by(|a, b| {+ b.games.cmp(&a.games).then(+ b.winrate()+ .partial_cmp(&a.winrate())+ .unwrap_or(std::cmp::Ordering::Equal),+ )+ });+ records+}++/// A teammate the player keeps queueing with.+#[derive(Debug, Clone)]+pub struct DuoRecord {+ pub puuid: String,+ pub games: u32,+ pub wins: u32,+}++impl DuoRecord {+ pub fn winrate(&self) -> f64 {+ if self.games == 0 {+ 0.0+ } else {+ self.wins as f64 / self.games as f64+ }+ }++ /// Shrunk win rate, so a 2-game 100% duo cannot outrank a 40-game 60% one.+ pub fn score(&self) -> f64 {+ stats::shrunk_winrate(self.wins, self.games - self.wins, stats::PRIOR_GAMES)+ }+}++/// Orders duos by shrunk win rate, keeping only those with enough games.+pub fn rank_duos(mut duos: Vec<DuoRecord>, min_games: u32) -> Vec<DuoRecord> {+ duos.retain(|d| d.games >= min_games);+ duos.sort_by(|a, b| {+ b.score()+ .partial_cmp(&a.score())+ .unwrap_or(std::cmp::Ordering::Equal)+ .then(b.games.cmp(&a.games))+ });+ duos+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn zones_match_the_map_corners() {+ // Top lane sits in the upper-left, bot lane in the lower-right.+ assert_eq!(classify_zone(1_500.0, 12_000.0), Zone::Top);+ assert_eq!(classify_zone(12_500.0, 2_000.0), Zone::Bot);+ // Mid follows the diagonal.+ assert_eq!(classify_zone(7_500.0, 7_500.0), Zone::Mid);+ assert_eq!(classify_zone(6_000.0, 8_000.0), Zone::Mid);+ // Off-diagonal but not in a corner: decided by which side of mid.+ assert_eq!(classify_zone(2_000.0, 7_000.0), Zone::Top);+ assert_eq!(classify_zone(9_000.0, 3_000.0), Zone::Bot);+ }++ #[test]+ fn zone_weights_normalise_and_read_preference() {+ let mut w = ZoneWeights::default();+ for _ in 0..8 {+ w.add(Zone::Bot, 1.0);+ }+ for _ in 0..6 {+ w.add(Zone::Mid, 1.0);+ }+ w.add(Zone::Top, 1.0);+ let s = w.shares();+ assert!((s.top + s.mid + s.bot - 1.0).abs() < 1e-9);+ assert_eq!(w.preference(), "mid_bot");++ // No samples must not divide by zero.+ assert_eq!(ZoneWeights::default().preference(), "unknown");+ assert_eq!(ZoneWeights::default().shares().total(), 0.0);+ }++ #[test]+ fn balanced_pathing_is_reported_as_balanced() {+ let mut w = ZoneWeights::default();+ w.add(Zone::Top, 10.0);+ w.add(Zone::Mid, 10.0);+ w.add(Zone::Bot, 10.0);+ assert_eq!(w.preference(), "balanced");+ }++ #[test]+ fn kills_weigh_more_than_standing_around() {+ let mut w = ZoneWeights::default();+ w.add(Zone::Top, 1.0);+ w.add(Zone::Bot, KILL_WEIGHT);+ let s = w.shares();+ assert!(s.bot > s.top * 4.0);+ }++ #[test]+ fn first_camp_detects_side_and_invade() {+ // Standing on the blue-side blue buff at minute one.+ let (camp, blue) = nearest_camp(3_900.0, 7_900.0);+ assert_eq!(camp, "blue_buff");+ assert!(blue);+ // A blue-side jungler starting there is not invading.+ assert!(!is_invade(blue, true));+ // The same player showing up in the red-side jungle is.+ let (_, enemy_side) = nearest_camp(11_000.0, 7_100.0);+ assert!(!enemy_side);+ assert!(is_invade(enemy_side, true));+ }++ #[test]+ fn level3_gank_heuristic_needs_all_three_signals() {+ // Clear cut short at 15 CS, level 3, already fought: a gank.+ assert!(looks_like_level3_gank(15, 3, true));+ // A full clear reaches ~20 CS and means no detour.+ assert!(!looks_like_level3_gank(24, 3, true));+ // Damage matters: farming quietly is not a gank.+ assert!(!looks_like_level3_gank(15, 3, false));+ // Wrong level is not a level-3 gank.+ assert!(!looks_like_level3_gank(15, 4, true));+ }++ #[test]+ fn champion_records_rank_like_a_profile_page() {+ let make = |id, games, wins| ChampionRecord {+ champion_id: id,+ games,+ wins,+ seconds: 1_800.0 * games as f64,+ cs: 200.0 * games as f64,+ ..Default::default()+ };+ let ranked = rank_champion_records(vec![make(1, 3, 1), make(2, 9, 5), make(3, 1, 1)], 2);+ // The single-game champion is dropped, the most played leads.+ assert_eq!(ranked.len(), 2);+ assert_eq!(ranked[0].champion_id, 2);+ assert_eq!(ranked[1].champion_id, 1);+ assert!((ranked[0].winrate() - 5.0 / 9.0).abs() < 1e-9);+ assert!((ranked[0].cs_per_min() - 200.0 / 30.0).abs() < 1e-9);+ }++ #[test]+ fn duos_are_ranked_by_shrunk_winrate() {+ let lucky = DuoRecord {+ puuid: "lucky".into(),+ games: 2,+ wins: 2,+ };+ let proven = DuoRecord {+ puuid: "proven".into(),+ games: 40,+ wins: 24,+ };+ let ranked = rank_duos(vec![lucky, proven], 2);+ assert_eq!(+ ranked[0].puuid, "proven",+ "a 40-game 60% duo must beat a 2-game 100% duo"+ );+ assert!((ranked[0].winrate() - 0.6).abs() < 1e-9);+ }++ #[test]+ fn duos_below_the_minimum_are_dropped() {+ let one_off = DuoRecord {+ puuid: "stranger".into(),+ games: 1,+ wins: 1,+ };+ assert!(rank_duos(vec![one_off], 2).is_empty());+ // A perfect record still scores below 100% after shrinkage.+ let d = DuoRecord {+ puuid: "x".into(),+ games: 10,+ wins: 10,+ };+ assert!(d.score() < 0.7 && d.score() > 0.5, "score={}", d.score());+ }+}diff --git a/src-tauri/src/commands/league/mod.rs b/src-tauri/src/commands/league/mod.rsindex 3eb4bb47..3fc1ffb1 100644--- a/src-tauri/src/commands/league/mod.rs+++ b/src-tauri/src/commands/league/mod.rs@@ -1,3 +1,4 @@+pub mod analysis;pub mod stats;use once_cell::sync::Lazy;@@ -1132,6 +1133,617 @@ pub async fn league_live_metrics() -> Result<Value, String> {}))}+/// Aggregates a player's champion records the way a profile page shows them.+fn champion_records_from_history(games: &[Value]) -> Vec<analysis::ChampionRecord> {+ let mut map: std::collections::HashMap<i64, analysis::ChampionRecord> =+ std::collections::HashMap::new();+ for game in games {+ let participant = match game+ .get("participants")+ .and_then(Value::as_array)+ .and_then(|a| a.first())+ {+ Some(p) => p,+ None => continue,+ };+ let champion_id = participant+ .get("championId")+ .and_then(Value::as_i64)+ .unwrap_or(0);+ if champion_id <= 0 {+ continue;+ }+ let s = participant.get("stats").cloned().unwrap_or(Value::Null);+ let num = |key: &str| s.get(key).and_then(Value::as_i64).unwrap_or(0).max(0) as u32;+ let entry = map+ .entry(champion_id)+ .or_insert_with(|| analysis::ChampionRecord {+ champion_id,+ ..Default::default()+ });+ entry.games += 1;+ if s.get("win").and_then(Value::as_bool).unwrap_or(false) {+ entry.wins += 1;+ }+ entry.kills += num("kills");+ entry.deaths += num("deaths");+ entry.assists += num("assists");+ entry.cs += (num("totalMinionsKilled") + num("neutralMinionsKilled")) as f64;+ entry.seconds += game+ .get("gameDuration")+ .and_then(Value::as_f64)+ .unwrap_or(0.0);+ }+ analysis::rank_champion_records(map.into_values().collect(), 2)+}++fn champion_records_json(records: &[analysis::ChampionRecord]) -> Vec<Value> {+ records+ .iter()+ .map(|r| {+ json!({+ "championId": r.champion_id,+ "games": r.games,+ "wins": r.wins,+ "winrate": (r.winrate() * 1000.0).round() / 10.0,+ "kda": (r.kda() * 100.0).round() / 100.0,+ "csPerMin": (r.cs_per_min() * 10.0).round() / 10.0,+ "kills": r.kills,+ "deaths": r.deaths,+ "assists": r.assists,+ })+ })+ .collect()+}++/// Resolves a Riot ID to a full profile: rank, level, champion records and+/// mastery, in the shape a profile page needs.+#[tauri::command]+pub async fn league_search_player(game_name: String, tag_line: String) -> Result<Value, String> {+ ensure_enabled()?;+ let client = get_client().await?;+ let name = game_name.trim().to_string();+ let tag = tag_line.trim().trim_start_matches('#').to_string();+ if name.is_empty() {+ return Err("empty name".to_string());+ }++ let found = lcu_send(+ &client,+ reqwest::Method::POST,+ "/lol-summoner/v1/summoners/aliases",+ Some(json!([{ "gameName": name, "tagLine": tag }])),+ )+ .await?;+ let summoner = found+ .as_array()+ .and_then(|a| a.first())+ .cloned()+ .ok_or_else(|| "player not found".to_string())?;+ let puuid = summoner+ .get("puuid")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_string();+ if puuid.is_empty() {+ return Err("player not found".to_string());+ }++ let profile = league_player_report(puuid.clone()).await?;+ let history = lcu_get_raw(+ &client,+ &format!(+ "/lol-match-history/v1/products/lol/{}/matches?begIndex=0&endIndex=19",+ puuid+ ),+ )+ .await+ .unwrap_or(Value::Null);+ let games: Vec<Value> = history+ .get("games")+ .and_then(|g| g.get("games"))+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();+ let records = champion_records_from_history(&games);++ Ok(json!({+ "summoner": summoner,+ "report": profile,+ "champions": champion_records_json(&records),+ "games": games,+ }))+}++/// Teammates the player wins the most with, ranked by shrunk win rate.+#[tauri::command]+pub async fn league_duos(sample: Option<u32>) -> Result<Value, String> {+ ensure_enabled()?;+ let client = get_client().await?;+ let me = lcu_get_raw(&client, "/lol-summoner/v1/current-summoner").await?;+ let my_puuid = me+ .get("puuid")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_string();+ if my_puuid.is_empty() {+ return Err("no puuid".to_string());+ }+ let count = sample.unwrap_or(20).clamp(5, 50);+ let history = lcu_get_raw(+ &client,+ &format!(+ "/lol-match-history/v1/products/lol/{}/matches?begIndex=0&endIndex={}",+ my_puuid,+ count.saturating_sub(1)+ ),+ )+ .await?;+ let games: Vec<Value> = history+ .get("games")+ .and_then(|g| g.get("games"))+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();++ let mut tasks = Vec::new();+ for game in &games {+ let game_id = match game.get("gameId").and_then(Value::as_i64) {+ Some(id) => id,+ None => continue,+ };+ let task_client = client.clone();+ tasks.push(tauri::async_runtime::spawn(async move {+ lcu_get_raw(+ &task_client,+ &format!("/lol-match-history/v1/games/{}", game_id),+ )+ .await+ .ok()+ }));+ }++ let mut tally: std::collections::HashMap<String, (u32, u32)> =+ std::collections::HashMap::new();+ let mut names: std::collections::HashMap<String, Value> = std::collections::HashMap::new();+ let mut analysed = 0u32;++ for task in tasks {+ let detail = match task.await {+ Ok(Some(d)) => d,+ _ => continue,+ };+ let identities: Vec<Value> = detail+ .get("participantIdentities")+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();+ let participants: Vec<Value> = detail+ .get("participants")+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();+ if identities.len() < 2 || participants.is_empty() {+ continue;+ }+ let pid_of = |puuid: &str| -> Option<i64> {+ identities+ .iter()+ .find(|i| {+ i.get("player")+ .and_then(|p| p.get("puuid"))+ .and_then(Value::as_str)+ == Some(puuid)+ })+ .and_then(|i| i.get("participantId").and_then(Value::as_i64))+ };+ let my_pid = match pid_of(&my_puuid) {+ Some(p) => p,+ None => continue,+ };+ let team_of = |pid: i64| -> Option<i64> {+ participants+ .iter()+ .find(|p| p.get("participantId").and_then(Value::as_i64) == Some(pid))+ .and_then(|p| p.get("teamId").and_then(Value::as_i64))+ };+ let my_team = match team_of(my_pid) {+ Some(t) => t,+ None => continue,+ };+ let won = participants+ .iter()+ .find(|p| p.get("participantId").and_then(Value::as_i64) == Some(my_pid))+ .and_then(|p| p.get("stats"))+ .and_then(|s| s.get("win"))+ .and_then(Value::as_bool)+ .unwrap_or(false);+ analysed += 1;++ for identity in &identities {+ let player = identity.get("player").cloned().unwrap_or(Value::Null);+ let puuid = player.get("puuid").and_then(Value::as_str).unwrap_or("");+ if puuid.is_empty() || puuid == my_puuid {+ continue;+ }+ let pid = identity+ .get("participantId")+ .and_then(Value::as_i64)+ .unwrap_or(-1);+ if team_of(pid) != Some(my_team) {+ continue;+ }+ let entry = tally.entry(puuid.to_string()).or_insert((0, 0));+ entry.0 += 1;+ if won {+ entry.1 += 1;+ }+ names.entry(puuid.to_string()).or_insert(player);+ }+ }++ let duos: Vec<analysis::DuoRecord> = tally+ .iter()+ .map(|(puuid, (games, wins))| analysis::DuoRecord {+ puuid: puuid.clone(),+ games: *games,+ wins: *wins,+ })+ .collect();+ let ranked = analysis::rank_duos(duos, 2);++ let list: Vec<Value> = ranked+ .iter()+ .take(15)+ .map(|d| {+ let player = names.get(&d.puuid).cloned().unwrap_or(Value::Null);+ json!({+ "puuid": d.puuid,+ "gameName": player.get("gameName").or_else(|| player.get("summonerName")),+ "tagLine": player.get("tagLine"),+ "games": d.games,+ "wins": d.wins,+ "winrate": (d.winrate() * 1000.0).round() / 10.0,+ "score": (d.score() * 1000.0).round() / 10.0,+ })+ })+ .collect();++ Ok(json!({ "analysedGames": analysed, "duos": list }))+}++/// Early-game map reading for a jungler, from match timelines.+#[tauri::command]+pub async fn league_jungle_report(puuid: String, sample: Option<u32>) -> Result<Value, String> {+ ensure_enabled()?;+ if puuid.is_empty() {+ return Err("empty puuid".to_string());+ }+ let client = get_client().await?;+ let count = sample.unwrap_or(8).clamp(1, 15);+ let history = lcu_get_raw(+ &client,+ &format!(+ "/lol-match-history/v1/products/lol/{}/matches?begIndex=0&endIndex={}",+ puuid,+ count.saturating_sub(1)+ ),+ )+ .await?;+ let games: Vec<Value> = history+ .get("games")+ .and_then(|g| g.get("games"))+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();++ let mut tasks = Vec::new();+ for game in &games {+ // Only Summoner's Rift games carry a meaningful jungle path.+ if game.get("mapId").and_then(Value::as_i64) != Some(11) {+ continue;+ }+ let game_id = match game.get("gameId").and_then(Value::as_i64) {+ Some(id) => id,+ None => continue,+ };+ let task_client = client.clone();+ tasks.push(tauri::async_runtime::spawn(async move {+ let detail = lcu_get_raw(+ &task_client,+ &format!("/lol-match-history/v1/games/{}", game_id),+ )+ .await+ .ok();+ let timeline = lcu_get_raw(+ &task_client,+ &format!("/lol-match-history/v1/game-timelines/{}", game_id),+ )+ .await+ .ok();+ (detail, timeline)+ }));+ }++ let mut weights = analysis::ZoneWeights::default();+ let mut analysed = 0u32;+ let mut invades = 0u32;+ let mut level3_ganks = 0u32;+ let mut first_camps: std::collections::HashMap<String, u32> =+ std::collections::HashMap::new();+ let mut objectives: std::collections::HashMap<String, u32> =+ std::collections::HashMap::new();++ for task in tasks {+ let (detail, timeline) = match task.await {+ Ok(pair) => pair,+ Err(_) => continue,+ };+ let (detail, timeline) = match (detail, timeline) {+ (Some(d), Some(t)) => (d, t),+ _ => continue,+ };+ let identities: Vec<Value> = detail+ .get("participantIdentities")+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();+ let pid = identities+ .iter()+ .find(|i| {+ i.get("player")+ .and_then(|p| p.get("puuid"))+ .and_then(Value::as_str)+ == Some(puuid.as_str())+ })+ .and_then(|i| i.get("participantId").and_then(Value::as_i64));+ let pid = match pid {+ Some(p) => p,+ None => continue,+ };+ let team_id = detail+ .get("participants")+ .and_then(Value::as_array)+ .and_then(|arr| {+ arr.iter()+ .find(|p| p.get("participantId").and_then(Value::as_i64) == Some(pid))+ })+ .and_then(|p| p.get("teamId").and_then(Value::as_i64))+ .unwrap_or(100);+ let on_blue_side = team_id == 100;++ let frames: Vec<Value> = timeline+ .get("frames")+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();+ if frames.is_empty() {+ continue;+ }+ analysed += 1;++ let frame_participant = |frame: &Value| -> Option<Value> {+ frame+ .get("participantFrames")+ .and_then(Value::as_object)+ .and_then(|obj| {+ obj.values()+ .find(|v| v.get("participantId").and_then(Value::as_i64) == Some(pid))+ .cloned()+ })+ };++ for frame in frames.iter().take(analysis::EARLY_MINUTES + 1).skip(1) {+ if let Some(pf) = frame_participant(frame) {+ if let Some(pos) = pf.get("position") {+ let x = pos.get("x").and_then(Value::as_f64).unwrap_or(-1.0);+ let y = pos.get("y").and_then(Value::as_f64).unwrap_or(-1.0);+ if x >= 0.0 && y >= 0.0 {+ weights.add(analysis::classify_zone(x, y), 1.0);+ }+ }+ }+ }++ if let Some(pf) = frames.get(1).and_then(frame_participant) {+ if let Some(pos) = pf.get("position") {+ let x = pos.get("x").and_then(Value::as_f64).unwrap_or(-1.0);+ let y = pos.get("y").and_then(Value::as_f64).unwrap_or(-1.0);+ if x >= 0.0 && y >= 0.0 {+ let (camp, camp_blue) = analysis::nearest_camp(x, y);+ *first_camps.entry(camp.to_string()).or_insert(0) += 1;+ if analysis::is_invade(camp_blue, on_blue_side) {+ invades += 1;+ }+ }+ }+ }++ let early_ms = (analysis::EARLY_MINUTES as i64) * 60_000;+ let mut acted_early = false;+ for frame in &frames {+ for event in frame+ .get("events")+ .and_then(Value::as_array)+ .unwrap_or(&Vec::new())+ {+ let ts = event.get("timestamp").and_then(Value::as_i64).unwrap_or(0);+ let kind = event.get("type").and_then(Value::as_str).unwrap_or("");+ if kind == "CHAMPION_KILL" && ts <= early_ms {+ let involved = event.get("killerId").and_then(Value::as_i64) == Some(pid)+ || event+ .get("assistingParticipantIds")+ .and_then(Value::as_array)+ .map(|a| a.iter().any(|v| v.as_i64() == Some(pid)))+ .unwrap_or(false);+ if involved {+ if ts <= 180_000 {+ acted_early = true;+ }+ if let Some(pos) = event.get("position") {+ let x = pos.get("x").and_then(Value::as_f64).unwrap_or(-1.0);+ let y = pos.get("y").and_then(Value::as_f64).unwrap_or(-1.0);+ if x >= 0.0 && y >= 0.0 {+ weights.add(+ analysis::classify_zone(x, y),+ analysis::KILL_WEIGHT,+ );+ }+ }+ }+ }+ if kind == "ELITE_MONSTER_KILL"+ && event.get("killerId").and_then(Value::as_i64) == Some(pid)+ {+ let monster = event+ .get("monsterType")+ .and_then(Value::as_str)+ .unwrap_or("UNKNOWN");+ *objectives.entry(monster.to_string()).or_insert(0) += 1;+ }+ }+ }++ if let Some(pf3) = frames.get(3).and_then(frame_participant) {+ let cs = (pf3.get("minionsKilled").and_then(Value::as_i64).unwrap_or(0)+ + pf3+ .get("jungleMinionsKilled")+ .and_then(Value::as_i64)+ .unwrap_or(0))+ .max(0) as u32;+ let level = pf3.get("level").and_then(Value::as_i64).unwrap_or(0).max(0) as u32;+ if analysis::looks_like_level3_gank(cs, level, acted_early) {+ level3_ganks += 1;+ }+ }+ }++ let shares = weights.shares();+ Ok(json!({+ "analysedGames": analysed,+ "zones": {+ "top": (shares.top * 1000.0).round() / 10.0,+ "mid": (shares.mid * 1000.0).round() / 10.0,+ "bot": (shares.bot * 1000.0).round() / 10.0,+ },+ "preference": weights.preference(),+ "invadeRate": if analysed > 0 { ((invades as f64 / analysed as f64) * 1000.0).round() / 10.0 } else { 0.0 },+ "level3GankRate": if analysed > 0 { ((level3_ganks as f64 / analysed as f64) * 1000.0).round() / 10.0 } else { 0.0 },+ "firstCamps": first_camps,+ "objectives": objectives,+ }))+}++/// Applies a rune page for a champion, replacing a page OmniGet owns.+#[tauri::command]+pub async fn league_apply_runes(+ name: String,+ primary_style_id: i64,+ sub_style_id: i64,+ selected_perk_ids: Vec<i64>,+ spell1: Option<i64>,+ spell2: Option<i64>,+) -> Result<Value, String> {+ ensure_enabled()?;+ if selected_perk_ids.len() < 6 {+ return Err("a rune page needs at least 6 perks".to_string());+ }+ let client = get_client().await?;++ // Reuse our own page when it exists so the user's own pages survive.+ let pages = lcu_get_raw(&client, "/lol-perks/v1/pages")+ .await+ .unwrap_or(Value::Null);+ let owned: Option<i64> = pages.as_array().and_then(|arr| {+ arr.iter()+ .find(|p| {+ p.get("name")+ .and_then(Value::as_str)+ .map(|n| n.starts_with("OmniGet"))+ .unwrap_or(false)+ && p.get("isDeletable")+ .and_then(Value::as_bool)+ .unwrap_or(false)+ })+ .and_then(|p| p.get("id").and_then(Value::as_i64))+ });+ if let Some(id) = owned {+ let _ = lcu_send(+ &client,+ reqwest::Method::DELETE,+ &format!("/lol-perks/v1/pages/{}", id),+ None,+ )+ .await;+ }++ let page = lcu_send(+ &client,+ reqwest::Method::POST,+ "/lol-perks/v1/pages",+ Some(json!({+ "name": format!("OmniGet · {}", name),+ "primaryStyleId": primary_style_id,+ "subStyleId": sub_style_id,+ "selectedPerkIds": selected_perk_ids,+ "current": true,+ })),+ )+ .await?;++ if let (Some(s1), Some(s2)) = (spell1, spell2) {+ let _ = lcu_send(+ &client,+ reqwest::Method::PATCH,+ "/lol-champ-select/v1/session/my-selection",+ Some(json!({ "spell1Id": s1, "spell2Id": s2 })),+ )+ .await;+ }++ Ok(page)+}++/// Sends a line to the champion-select (or lobby) chat.+#[tauri::command]+pub async fn league_send_chat(message: String) -> Result<(), String> {+ ensure_enabled()?;+ let text = message.trim();+ if text.is_empty() {+ return Err("empty message".to_string());+ }+ let client = get_client().await?;+ let conversations = lcu_get_raw(&client, "/lol-chat/v1/conversations").await?;+ let target = conversations+ .as_array()+ .and_then(|arr| {+ arr.iter()+ .find(|c| {+ matches!(+ c.get("type").and_then(Value::as_str),+ Some("championSelect") | Some("customGame")+ )+ })+ .or_else(|| {+ arr.iter().find(|c| {+ c.get("type").and_then(Value::as_str) == Some("chat")+ && c.get("isMuted").and_then(Value::as_bool) == Some(false)+ })+ })+ })+ .and_then(|c| c.get("id").and_then(Value::as_str).map(String::from))+ .ok_or_else(|| "no champion select chat open".to_string())?;++ lcu_send(+ &client,+ reqwest::Method::POST,+ &format!("/lol-chat/v1/conversations/{}/messages", target),+ Some(json!({ "body": text, "type": "chat" })),+ )+ .await?;+ Ok(())+}+#[tauri::command]pub async fn league_auto_accept_set(enabled: bool) -> Result<(), String> {ensure_enabled()?;diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 75974ada..6c08dd3b 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -726,6 +726,11 @@ pub fn run() {commands::league::league_player_report,commands::league::league_match_analysis,commands::league::league_live_metrics,+ commands::league::league_search_player,+ commands::league::league_duos,+ commands::league::league_jungle_report,+ commands::league::league_apply_runes,+ commands::league::league_send_chat,commands::bilibili_auth::bilibili_qr_generate,commands::bilibili_auth::bilibili_qr_poll,commands::bilibili_auth::bilibili_captcha_challenge,diff --git a/src/lib/i18n/el.json b/src/lib/i18n/el.jsonindex 3cc20b75..97118a79 100644--- a/src/lib/i18n/el.json+++ b/src/lib/i18n/el.json@@ -37,6 +37,39 @@"nav_downloads": "Μετάβαση στις Λήψεις"},"league": {+ "tab_search": "Αναζήτηση",+ "search_title": "Εύρεση παίκτη",+ "search_placeholder": "Riot ID, π.χ. Faker#KR1",+ "search_button": "Αναζήτηση",+ "searching_player": "Αναζήτηση…",+ "search_hint": "Γράψε ένα Riot ID με το tag για να δεις βαθμίδα, πρόσφατη φόρμα και απόδοση ανά ήρωα.",+ "search_recent": "Πρόσφατη φόρμα",+ "search_champions": "Ήρωες",+ "search_champions_hint": "2+ αγώνες, πρώτα οι πιο παιγμένοι",+ "search_mastery": "Mastery",+ "stat_winrate": "Νίκες",+ "games_short": "αγώνες",+ "duos_title": "Καλύτερα δίδυμα",+ "duos_desc": "Συμπαίκτες με τους οποίους κερδίζεις περισσότερο, από πρόσφατους αγώνες. Η βαθμολογία συρρικνώνει μικρά δείγματα ώστε ένα τυχερό δίδυμο να μην κορυφώνει τη λίστα.",+ "duos_empty": "Δεν υπάρχουν επαναλαμβανόμενοι συμπαίκτες ακόμα.",+ "duos_score": "βαθμολογία",+ "jungle_title": "Πρώιμη διαδρομή jungle",+ "jungle_empty": "Δεν υπάρχουν δεδομένα timeline για αυτούς τους αγώνες.",+ "jungle_invade": "invade",+ "jungle_gank3": "gank επιπέδου 3",+ "zone_top": "Top",+ "zone_mid": "Mid",+ "zone_bot": "Bot",+ "pref_top": "εστίαση στο top",+ "pref_mid": "εστίαση στο mid",+ "pref_bot": "εστίαση στο bot",+ "pref_top_mid": "εστίαση σε top και mid",+ "pref_mid_bot": "εστίαση σε mid και bot",+ "pref_balanced": "ισορροπημένη διαδρομή",+ "pref_unknown": "ανεπαρκή δεδομένα",+ "chat_placeholder": "Μήνυμα για αποστολή στην επιλογή",+ "chat_build": "Δημιουργία σύνοψης",+ "chat_send": "Αποστολή","tab_overview": "Επισκόπηση","tab_analysis": "Ανάλυση","tab_live": "Ζωντανά",diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.jsonindex 116725f5..a7fffb57 100644--- a/src/lib/i18n/en.json+++ b/src/lib/i18n/en.json@@ -37,6 +37,39 @@"nav_downloads": "Go to Downloads"},"league": {+ "tab_search": "Search",+ "search_title": "Find a player",+ "search_placeholder": "Riot ID, e.g. Faker#KR1",+ "search_button": "Search",+ "searching_player": "Searching…",+ "search_hint": "Type a Riot ID with its tag to see rank, recent form and champion record.",+ "search_recent": "Recent form",+ "search_champions": "Champions",+ "search_champions_hint": "2+ games, most played first",+ "search_mastery": "Mastery",+ "stat_winrate": "Win rate",+ "games_short": "games",+ "duos_title": "Best duos",+ "duos_desc": "Teammates you win the most with, from your recent games. The score shrinks small samples so a lucky pair of games does not top the list.",+ "duos_empty": "No repeated teammates in the sample yet.",+ "duos_score": "score",+ "jungle_title": "Early jungle path",+ "jungle_empty": "No timeline data for these games.",+ "jungle_invade": "invade",+ "jungle_gank3": "lv3 gank",+ "zone_top": "Top",+ "zone_mid": "Mid",+ "zone_bot": "Bot",+ "pref_top": "top focused",+ "pref_mid": "mid focused",+ "pref_bot": "bot focused",+ "pref_top_mid": "top and mid focused",+ "pref_mid_bot": "mid and bot focused",+ "pref_balanced": "balanced path",+ "pref_unknown": "not enough data",+ "chat_placeholder": "Message to send in champion select",+ "chat_build": "Build summary",+ "chat_send": "Send","tab_overview": "Overview","tab_analysis": "Analysis","tab_live": "Live",diff --git a/src/lib/i18n/es.json b/src/lib/i18n/es.jsonindex b390f68b..f9a9777c 100644--- a/src/lib/i18n/es.json+++ b/src/lib/i18n/es.json@@ -37,6 +37,39 @@"nav_downloads": "Ir a Descargas"},"league": {+ "tab_search": "Buscar",+ "search_title": "Buscar jugador",+ "search_placeholder": "Riot ID, p. ej. Faker#KR1",+ "search_button": "Buscar",+ "searching_player": "Buscando…",+ "search_hint": "Escribe un Riot ID con su tag para ver el rango, la forma reciente y el rendimiento por campeón.",+ "search_recent": "Forma reciente",+ "search_champions": "Campeones",+ "search_champions_hint": "2+ partidas, más jugados primero",+ "search_mastery": "Maestría",+ "stat_winrate": "Victorias",+ "games_short": "partidas",+ "duos_title": "Mejores dúos",+ "duos_desc": "Compañeros con los que más ganas, según tus partidas recientes. La puntuación reduce las muestras pequeñas para que un dúo con suerte no encabece la lista.",+ "duos_empty": "Aún no hay compañeros repetidos en la muestra.",+ "duos_score": "puntuación",+ "jungle_title": "Ruta inicial de jungla",+ "jungle_empty": "Sin datos de línea temporal en estas partidas.",+ "jungle_invade": "invadir",+ "jungle_gank3": "gank nivel 3",+ "zone_top": "Superior",+ "zone_mid": "Central",+ "zone_bot": "Inferior",+ "pref_top": "enfoque superior",+ "pref_mid": "enfoque central",+ "pref_bot": "enfoque inferior",+ "pref_top_mid": "enfoque superior y central",+ "pref_mid_bot": "enfoque central e inferior",+ "pref_balanced": "ruta equilibrada",+ "pref_unknown": "datos insuficientes",+ "chat_placeholder": "Mensaje para enviar en la selección",+ "chat_build": "Crear resumen",+ "chat_send": "Enviar","tab_overview": "Resumen","tab_analysis": "Análisis","tab_live": "En vivo",diff --git a/src/lib/i18n/fr.json b/src/lib/i18n/fr.jsonindex 42b9706d..a341d3f3 100644--- a/src/lib/i18n/fr.json+++ b/src/lib/i18n/fr.json@@ -37,6 +37,39 @@"nav_downloads": "Aller aux Téléchargements"},"league": {+ "tab_search": "Rechercher",+ "search_title": "Trouver un joueur",+ "search_placeholder": "Riot ID, ex. Faker#KR1",+ "search_button": "Rechercher",+ "searching_player": "Recherche…",+ "search_hint": "Saisissez un Riot ID avec son tag pour voir le rang, la forme récente et les performances par champion.",+ "search_recent": "Forme récente",+ "search_champions": "Champions",+ "search_champions_hint": "2+ parties, les plus jouées d'abord",+ "search_mastery": "Maîtrise",+ "stat_winrate": "Victoires",+ "games_short": "parties",+ "duos_title": "Meilleurs duos",+ "duos_desc": "Coéquipiers avec qui vous gagnez le plus, d'après vos parties récentes. Le score réduit les petits échantillons pour qu'un duo chanceux ne domine pas la liste.",+ "duos_empty": "Aucun coéquipier récurrent dans l'échantillon.",+ "duos_score": "score",+ "jungle_title": "Trajet de jungle initial",+ "jungle_empty": "Pas de données de timeline pour ces parties.",+ "jungle_invade": "invasion",+ "jungle_gank3": "gank niveau 3",+ "zone_top": "Top",+ "zone_mid": "Milieu",+ "zone_bot": "Bot",+ "pref_top": "axé top",+ "pref_mid": "axé milieu",+ "pref_bot": "axé bot",+ "pref_top_mid": "axé top et milieu",+ "pref_mid_bot": "axé milieu et bot",+ "pref_balanced": "trajet équilibré",+ "pref_unknown": "données insuffisantes",+ "chat_placeholder": "Message à envoyer en sélection",+ "chat_build": "Créer le résumé",+ "chat_send": "Envoyer","tab_overview": "Aperçu","tab_analysis": "Analyse","tab_live": "En direct",diff --git a/src/lib/i18n/it.json b/src/lib/i18n/it.jsonindex f03fbbab..aef0391d 100644--- a/src/lib/i18n/it.json+++ b/src/lib/i18n/it.json@@ -37,6 +37,39 @@"nav_downloads": "Vai ai Download"},"league": {+ "tab_search": "Cerca",+ "search_title": "Trova giocatore",+ "search_placeholder": "Riot ID, es. Faker#KR1",+ "search_button": "Cerca",+ "searching_player": "Ricerca…",+ "search_hint": "Inserisci un Riot ID con il tag per vedere grado, forma recente e rendimento per campione.",+ "search_recent": "Forma recente",+ "search_champions": "Campioni",+ "search_champions_hint": "2+ partite, più giocati prima",+ "search_mastery": "Maestria",+ "stat_winrate": "Vittorie",+ "games_short": "partite",+ "duos_title": "Migliori duo",+ "duos_desc": "Compagni con cui vinci di più, dalle tue partite recenti. Il punteggio riduce i campioni piccoli così un duo fortunato non guida la lista.",+ "duos_empty": "Nessun compagno ripetuto nel campione.",+ "duos_score": "punteggio",+ "jungle_title": "Percorso iniziale in giungla",+ "jungle_empty": "Nessun dato di timeline per queste partite.",+ "jungle_invade": "invasione",+ "jungle_gank3": "gank livello 3",+ "zone_top": "Top",+ "zone_mid": "Mid",+ "zone_bot": "Bot",+ "pref_top": "focus top",+ "pref_mid": "focus mid",+ "pref_bot": "focus bot",+ "pref_top_mid": "focus top e mid",+ "pref_mid_bot": "focus mid e bot",+ "pref_balanced": "percorso equilibrato",+ "pref_unknown": "dati insufficienti",+ "chat_placeholder": "Messaggio da inviare in selezione",+ "chat_build": "Crea riepilogo",+ "chat_send": "Invia","tab_overview": "Panoramica","tab_analysis": "Analisi","tab_live": "In diretta",diff --git a/src/lib/i18n/ja.json b/src/lib/i18n/ja.jsonindex ab84ef90..0512741f 100644--- a/src/lib/i18n/ja.json+++ b/src/lib/i18n/ja.json@@ -37,6 +37,39 @@"nav_downloads": "ダウンロードへ移動"},"league": {+ "tab_search": "検索",+ "search_title": "プレイヤー検索",+ "search_placeholder": "Riot ID(例: Faker#KR1)",+ "search_button": "検索",+ "searching_player": "検索中…",+ "search_hint": "タグ付きのRiot IDを入力すると、ランク・直近の調子・チャンピオン別成績が表示されます。",+ "search_recent": "直近の調子",+ "search_champions": "チャンピオン",+ "search_champions_hint": "2試合以上、使用回数順",+ "search_mastery": "マスタリー",+ "stat_winrate": "勝率",+ "games_short": "試合",+ "duos_title": "ベストデュオ",+ "duos_desc": "直近の試合で最も勝率が高い味方。少ないサンプルは縮小されるため、まぐれの2試合が上位に来ません。",+ "duos_empty": "サンプル内に繰り返しの味方はまだいません。",+ "duos_score": "スコア",+ "jungle_title": "序盤のジャングル動線",+ "jungle_empty": "これらの試合のタイムラインデータがありません。",+ "jungle_invade": "侵入",+ "jungle_gank3": "レベル3ガンク",+ "zone_top": "トップ",+ "zone_mid": "ミッド",+ "zone_bot": "ボット",+ "pref_top": "トップ寄り",+ "pref_mid": "ミッド寄り",+ "pref_bot": "ボット寄り",+ "pref_top_mid": "トップ・ミッド寄り",+ "pref_mid_bot": "ミッド・ボット寄り",+ "pref_balanced": "バランス型",+ "pref_unknown": "データ不足",+ "chat_placeholder": "チャンピオン選択で送るメッセージ",+ "chat_build": "要約を作成",+ "chat_send": "送信","tab_overview": "概要","tab_analysis": "分析","tab_live": "ライブ",diff --git a/src/lib/i18n/keys.ts b/src/lib/i18n/keys.tsindex 034ba5fc..f153a5c2 100644--- a/src/lib/i18n/keys.ts+++ b/src/lib/i18n/keys.ts@@ -377,6 +377,9 @@ export type TranslationKeys =| 'league.ban_list'| 'league.bench_title'| 'league.champ_select_title'+ | 'league.chat_build'+ | 'league.chat_placeholder'+ | 'league.chat_send'| 'league.col_diff'| 'league.col_gold'| 'league.col_player'@@ -386,7 +389,12 @@ export type TranslationKeys =| 'league.disabled_title'| 'league.disconnected_body'| 'league.disconnected_title'+ | 'league.duos_desc'+ | 'league.duos_empty'+ | 'league.duos_score'+ | 'league.duos_title'| 'league.enemy_team'+ | 'league.games_short'| 'league.goal_cs'| 'league.goal_gold'| 'league.goal_kda'@@ -400,6 +408,10 @@ export type TranslationKeys =| 'league.gold_unavailable'| 'league.history_empty'| 'league.history_title'+ | 'league.jungle_empty'+ | 'league.jungle_gank3'+ | 'league.jungle_invade'+ | 'league.jungle_title'| 'league.leave_lobby'| 'league.level'| 'league.list_hint'@@ -418,6 +430,13 @@ export type TranslationKeys =| 'league.pick_list'| 'league.play_again'| 'league.players'+ | 'league.pref_balanced'+ | 'league.pref_bot'+ | 'league.pref_mid'+ | 'league.pref_mid_bot'+ | 'league.pref_top'+ | 'league.pref_top_mid'+ | 'league.pref_unknown'| 'league.premades'| 'league.ranked_flex'| 'league.ranked_solo'@@ -436,8 +455,17 @@ export type TranslationKeys =| 'league.scout_note_placeholder'| 'league.scout_private'| 'league.scout_title'+ | 'league.search_button'| 'league.search_champion'+ | 'league.search_champions'+ | 'league.search_champions_hint'+ | 'league.search_hint'+ | 'league.search_mastery'+ | 'league.search_placeholder'+ | 'league.search_recent'+ | 'league.search_title'| 'league.searching'+ | 'league.searching_player'| 'league.settings_auto_accept'| 'league.settings_auto_accept_desc'| 'league.settings_desc'@@ -445,6 +473,7 @@ export type TranslationKeys =| 'league.settings_enable_desc'| 'league.settings_title'| 'league.start_queue'+ | 'league.stat_winrate'| 'league.stop_queue'| 'league.swap'| 'league.tab_analysis'@@ -453,6 +482,7 @@ export type TranslationKeys =| 'league.tab_history'| 'league.tab_live'| 'league.tab_overview'+ | 'league.tab_search'| 'league.tag_cold_streak'| 'league.tag_high_kda'| 'league.tag_high_winrate'@@ -470,6 +500,9 @@ export type TranslationKeys =| 'league.win_title'| 'league.win_unavailable'| 'league.your_team'+ | 'league.zone_bot'+ | 'league.zone_mid'+ | 'league.zone_top'| 'legal.acknowledge'| 'legal.body_paragraph_1'diff --git a/src/lib/i18n/pt.json b/src/lib/i18n/pt.jsonindex 7688f836..f7d75a0a 100644--- a/src/lib/i18n/pt.json+++ b/src/lib/i18n/pt.json@@ -37,6 +37,39 @@"nav_downloads": "Ir para Downloads"},"league": {+ "tab_search": "Buscar",+ "search_title": "Procurar jogador",+ "search_placeholder": "Riot ID, ex.: Faker#KR1",+ "search_button": "Buscar",+ "searching_player": "Buscando…",+ "search_hint": "Digite um Riot ID com a tag para ver elo, forma recente e desempenho por campeão.",+ "search_recent": "Forma recente",+ "search_champions": "Campeões",+ "search_champions_hint": "2+ partidas, mais jogados primeiro",+ "search_mastery": "Maestria",+ "stat_winrate": "Vitórias",+ "games_short": "partidas",+ "duos_title": "Melhores duos",+ "duos_desc": "Companheiros com quem você mais vence, das suas partidas recentes. A pontuação encolhe amostras pequenas para uma dupla de sorte não liderar a lista.",+ "duos_empty": "Nenhum companheiro repetido na amostra ainda.",+ "duos_score": "pontuação",+ "jungle_title": "Rota inicial da selva",+ "jungle_empty": "Sem dados de timeline nessas partidas.",+ "jungle_invade": "invade",+ "jungle_gank3": "gank nível 3",+ "zone_top": "Topo",+ "zone_mid": "Meio",+ "zone_bot": "Base",+ "pref_top": "foco no topo",+ "pref_mid": "foco no meio",+ "pref_bot": "foco na base",+ "pref_top_mid": "foco em topo e meio",+ "pref_mid_bot": "foco em meio e base",+ "pref_balanced": "rota equilibrada",+ "pref_unknown": "dados insuficientes",+ "chat_placeholder": "Mensagem para enviar na seleção",+ "chat_build": "Montar resumo",+ "chat_send": "Enviar","tab_overview": "Visão geral","tab_analysis": "Análise","tab_live": "Ao vivo",diff --git a/src/lib/i18n/ru.json b/src/lib/i18n/ru.jsonindex 28290f7c..02bc56dc 100644--- a/src/lib/i18n/ru.json+++ b/src/lib/i18n/ru.json@@ -37,6 +37,39 @@"nav_downloads": "Перейти к загрузкам"},"league": {+ "tab_search": "Поиск",+ "search_title": "Найти игрока",+ "search_placeholder": "Riot ID, напр. Faker#KR1",+ "search_button": "Найти",+ "searching_player": "Поиск…",+ "search_hint": "Введите Riot ID с тегом, чтобы увидеть ранг, текущую форму и статистику по чемпионам.",+ "search_recent": "Текущая форма",+ "search_champions": "Чемпионы",+ "search_champions_hint": "2+ игр, сначала популярные",+ "search_mastery": "Мастерство",+ "stat_winrate": "Победы",+ "games_short": "игр",+ "duos_title": "Лучшие дуо",+ "duos_desc": "Союзники, с которыми вы чаще побеждаете, по недавним играм. Оценка сжимает малые выборки, чтобы удачная пара игр не возглавила список.",+ "duos_empty": "Повторяющихся союзников пока нет.",+ "duos_score": "оценка",+ "jungle_title": "Ранний маршрут в лесу",+ "jungle_empty": "Нет данных таймлайна для этих игр.",+ "jungle_invade": "вторжение",+ "jungle_gank3": "ганк 3 ур.",+ "zone_top": "Топ",+ "zone_mid": "Мид",+ "zone_bot": "Бот",+ "pref_top": "фокус на топ",+ "pref_mid": "фокус на мид",+ "pref_bot": "фокус на бот",+ "pref_top_mid": "фокус на топ и мид",+ "pref_mid_bot": "фокус на мид и бот",+ "pref_balanced": "сбалансированный маршрут",+ "pref_unknown": "мало данных",+ "chat_placeholder": "Сообщение для отправки в выборе",+ "chat_build": "Собрать сводку",+ "chat_send": "Отправить","tab_overview": "Обзор","tab_analysis": "Анализ","tab_live": "В игре",diff --git a/src/lib/i18n/zh-TW.json b/src/lib/i18n/zh-TW.jsonindex 4a4891af..5c30088a 100644--- a/src/lib/i18n/zh-TW.json+++ b/src/lib/i18n/zh-TW.json@@ -37,6 +37,39 @@"nav_downloads": "前往下載"},"league": {+ "tab_search": "搜尋",+ "search_title": "尋找玩家",+ "search_placeholder": "Riot ID,例如 Faker#KR1",+ "search_button": "搜尋",+ "searching_player": "搜尋中…",+ "search_hint": "輸入帶標籤的 Riot ID,查看段位、近期狀態與各英雄表現。",+ "search_recent": "近期狀態",+ "search_champions": "英雄",+ "search_champions_hint": "2 場以上,依場次排序",+ "search_mastery": "熟練度",+ "stat_winrate": "勝率",+ "games_short": "場",+ "duos_title": "最佳雙排",+ "duos_desc": "根據近期對戰,與你勝率最高的隊友。評分會壓縮小樣本,避免運氣好的兩場登頂。",+ "duos_empty": "樣本中還沒有重複出現的隊友。",+ "duos_score": "評分",+ "jungle_title": "前期打野路線",+ "jungle_empty": "這些對戰沒有時間軸資料。",+ "jungle_invade": "入侵",+ "jungle_gank3": "3 等 gank",+ "zone_top": "上路",+ "zone_mid": "中路",+ "zone_bot": "下路",+ "pref_top": "偏上路",+ "pref_mid": "偏中路",+ "pref_bot": "偏下路",+ "pref_top_mid": "偏上中路",+ "pref_mid_bot": "偏中下路",+ "pref_balanced": "路線均衡",+ "pref_unknown": "資料不足",+ "chat_placeholder": "在英雄選擇中傳送的訊息",+ "chat_build": "產生摘要",+ "chat_send": "傳送","tab_overview": "總覽","tab_analysis": "分析","tab_live": "即時",diff --git a/src/lib/i18n/zh.json b/src/lib/i18n/zh.jsonindex b2f9bab5..11a677a1 100644--- a/src/lib/i18n/zh.json+++ b/src/lib/i18n/zh.json@@ -37,6 +37,39 @@"nav_downloads": "前往下载"},"league": {+ "tab_search": "搜索",+ "search_title": "查找玩家",+ "search_placeholder": "Riot ID,例如 Faker#KR1",+ "search_button": "搜索",+ "searching_player": "搜索中…",+ "search_hint": "输入带标签的 Riot ID,查看段位、近期状态和各英雄表现。",+ "search_recent": "近期状态",+ "search_champions": "英雄",+ "search_champions_hint": "2 场以上,按场次排序",+ "search_mastery": "熟练度",+ "stat_winrate": "胜率",+ "games_short": "场",+ "duos_title": "最佳双排",+ "duos_desc": "根据近期对局,与你胜率最高的队友。评分会压缩小样本,避免运气好的两场登顶。",+ "duos_empty": "样本中还没有重复出现的队友。",+ "duos_score": "评分",+ "jungle_title": "前期打野路线",+ "jungle_empty": "这些对局没有时间轴数据。",+ "jungle_invade": "入侵",+ "jungle_gank3": "3 级 gank",+ "zone_top": "上路",+ "zone_mid": "中路",+ "zone_bot": "下路",+ "pref_top": "偏上路",+ "pref_mid": "偏中路",+ "pref_bot": "偏下路",+ "pref_top_mid": "偏上中路",+ "pref_mid_bot": "偏中下路",+ "pref_balanced": "路线均衡",+ "pref_unknown": "数据不足",+ "chat_placeholder": "在英雄选择中发送的消息",+ "chat_build": "生成摘要",+ "chat_send": "发送","tab_overview": "总览","tab_analysis": "分析","tab_live": "实时",diff --git a/src/routes/league/+page.svelte b/src/routes/league/+page.svelteindex a7fd669e..93197a49 100644--- a/src/routes/league/+page.svelte+++ b/src/routes/league/+page.svelte@@ -99,7 +99,7 @@];}- const TAB_IDS = ["overview", "analysis", "live", "goals", "automation", "history"] as const;+ const TAB_IDS = ["overview", "analysis", "search", "live", "goals", "automation", "history"] as const;type Tab = (typeof TAB_IDS)[number];let tab = $state<Tab>("overview");@@ -221,6 +221,81 @@];});+ let searchQuery = $state("");+ let searchResult = $state<any>(null);+ let searchLoading = $state(false);+ let searchError = $state("");+ let jungleReport = $state<any>(null);+ let duos = $state<any>(null);+ let duosLoading = $state(false);+ let chatSending = $state(false);+ let chatPreview = $state("");++ async function runSearch() {+ const raw = searchQuery.trim();+ if (!raw || searchLoading) return;+ const [namePart, tagPart = ""] = raw.split("#");+ searchLoading = true;+ searchError = "";+ jungleReport = null;+ try {+ searchResult = await invoke<any>("league_search_player", {+ gameName: namePart.trim(),+ tagLine: tagPart.trim(),+ });+ const puuid = searchResult?.summoner?.puuid;+ if (puuid) {+ invoke<any>("league_jungle_report", { puuid, sample: 8 })+ .then((r) => { jungleReport = r; })+ .catch(() => { jungleReport = null; });+ }+ } catch (e: any) {+ searchResult = null;+ searchError = typeof e === "string" ? e : (e?.message ?? String(e));+ } finally {+ searchLoading = false;+ }+ }++ async function loadDuos() {+ if (duosLoading) return;+ duosLoading = true;+ try {+ duos = await invoke<any>("league_duos", { sample: 20 });+ } catch {+ duos = { duos: [] };+ } finally {+ duosLoading = false;+ }+ }++ // Builds the one-line-per-player summary that gets posted to champ select.+ function buildChatSummary(): string {+ const parts: string[] = [];+ for (const p of scoutPlayers.filter((x) => !x.isAlly)) {+ const r = p.puuid ? scoutReports[p.puuid] : null;+ if (!r?.stats?.games) continue;+ const champ = championById.get(p.championId)?.name ?? "";+ parts.push(`${champ || p.gameName}: ${r.stats.winrate}%WR ${r.stats.kda}KDA (${r.stats.games})`);+ }+ return parts.join(" | ");+ }++ async function sendChatSummary() {+ const text = chatPreview.trim();+ if (!text || chatSending) return;+ chatSending = true;+ actionError = "";+ try {+ await invoke("league_send_chat", { message: text });+ chatPreview = "";+ } catch (e: any) {+ actionError = typeof e === "string" ? e : (e?.message ?? String(e));+ } finally {+ chatSending = false;+ }+ }+const PHASE_KEYS: Record<string, string> = {Lobby: "league.phase_lobby",Matchmaking: "league.phase_matchmaking",@@ -675,6 +750,15 @@{$t("league.win_gap")} {analysis.ratingGap > 0 ? "+" : ""}{analysis.ratingGap} · {analysis.knownPlayers}/{analysis.totalPlayers} {$t("league.win_known")}</p><p class="win-disclaimer">{$t("league.win_disclaimer")}</p>+ <div class="chat-send">+ <input+ class="input-text"+ placeholder={$t("league.chat_placeholder") as string}+ bind:value={chatPreview}+ />+ <button class="button" onclick={() => (chatPreview = buildChatSummary())}>{$t("league.chat_build")}</button>+ <button class="button primary" onclick={sendChatSummary} disabled={chatSending || !chatPreview.trim()}>{$t("league.chat_send")}</button>+ </div>{#if analysis.premades?.length}<div class="premade-row"><span class="bench-label">{$t("league.premades")}</span>@@ -757,6 +841,162 @@{/if}{/if}+ {#if tab === "search"}+ <section class="card">+ <div class="card-head">+ <h3>{$t("league.search_title")}</h3>+ </div>+ <form class="search-form" onsubmit={(e) => { e.preventDefault(); runSearch(); }}>+ <input+ class="input-text"+ placeholder={$t("league.search_placeholder") as string}+ bind:value={searchQuery}+ spellcheck="false"+ />+ <button class="button primary" type="submit" disabled={searchLoading}>+ {searchLoading ? $t("league.searching_player") : $t("league.search_button")}+ </button>+ </form>+ {#if searchError}+ <p class="action-error" role="alert">{searchError}</p>+ {:else}+ <p class="win-disclaimer">{$t("league.search_hint")}</p>+ {/if}+ </section>++ {#if searchResult}+ {@const s = searchResult.summoner}+ {@const r = searchResult.report}+ <section class="profile-card">+ <img class="profile-icon" src={`${CDRAGON}/profile-icons/${s.profileIconId}.jpg`} alt="" loading="lazy" />+ <div class="profile-info">+ <span class="profile-name">{s.gameName}<span class="tag">#{s.tagLine}</span></span>+ <span class="profile-level">{$t("league.level")} {s.summonerLevel ?? "—"}</span>+ </div>+ <div class="ranked-chips">+ <div class="ranked-chip">+ <span class="ranked-queue">{$t("league.ranked_solo")}</span>+ <span class="ranked-value">{rankLabel(r?.solo)}</span>+ </div>+ <div class="ranked-chip">+ <span class="ranked-queue">{$t("league.ranked_flex")}</span>+ <span class="ranked-value">{rankLabel(r?.flex)}</span>+ </div>+ </div>+ </section>++ {#if r?.stats?.games > 0}+ <section class="card">+ <div class="card-head"><h3>{$t("league.search_recent")}</h3></div>+ <div class="stat-grid">+ <div class="stat-cell">+ <span class="stat-value" class:good={r.stats.winrate >= 55} class:bad={r.stats.winrate <= 45}>{r.stats.winrate}%</span>+ <span class="stat-label">{$t("league.stat_winrate")} ({r.stats.games})</span>+ </div>+ <div class="stat-cell">+ <span class="stat-value">{r.stats.kda}</span>+ <span class="stat-label">KDA</span>+ </div>+ <div class="stat-cell">+ <span class="stat-value">{r.stats.streak?.length ?? 0}</span>+ <span class="stat-label">{r.stats.streak?.win ? $t("league.tag_hot_streak") : $t("league.tag_cold_streak")}</span>+ </div>+ </div>+ {#if r.stats.insights?.length}+ <div class="scout-champs">+ {#each r.stats.insights as tagId (tagId)}+ <span class="scout-tag">{$t(TAG_KEYS[tagId] ?? tagId)}</span>+ {/each}+ </div>+ {/if}+ </section>+ {/if}++ {#if searchResult.champions?.length}+ <section class="card">+ <div class="card-head">+ <h3>{$t("league.search_champions")}</h3>+ <span class="phase-tag">{$t("league.search_champions_hint")}</span>+ </div>+ <div class="champ-table">+ {#each searchResult.champions as ch (ch.championId)}+ <div class="champ-row">+ <img class="champ-icon small" src={`${CDRAGON}/champion-icons/${ch.championId}.png`} alt="" loading="lazy" />+ <span class="champ-row-name">{championById.get(ch.championId)?.name ?? ch.championId}</span>+ <span class="champ-row-games">{ch.games} {$t("league.games_short")}</span>+ <span class="champ-row-wr" class:good={ch.winrate >= 55} class:bad={ch.winrate <= 45}>{ch.winrate}%</span>+ <span class="champ-row-kda">{ch.kda} KDA</span>+ <span class="champ-row-cs dim">{ch.csPerMin}/m</span>+ </div>+ {/each}+ </div>+ </section>+ {/if}++ {#if r?.mastery?.length}+ <section class="card">+ <div class="card-head"><h3>{$t("league.search_mastery")}</h3></div>+ <div class="scout-champs">+ {#each r.mastery as m (m.championId)}+ <span class="champ-chip">+ <img class="champ-icon tiny" src={`${CDRAGON}/champion-icons/${m.championId}.png`} alt="" loading="lazy" />+ {championById.get(m.championId)?.name ?? m.championId}+ <span class="dim">M{m.championLevel} · {Math.round((m.championPoints ?? 0) / 1000)}k</span>+ </span>+ {/each}+ </div>+ </section>+ {/if}++ {#if jungleReport}+ <section class="card">+ <div class="card-head">+ <h3>{$t("league.jungle_title")}</h3>+ <span class="phase-tag">{jungleReport.analysedGames} {$t("league.games_short")}</span>+ </div>+ {#if jungleReport.analysedGames > 0}+ <div class="zone-bars">+ {#each [["top", jungleReport.zones.top], ["mid", jungleReport.zones.mid], ["bot", jungleReport.zones.bot]] as [zone, pct] (zone)}+ <div class="zone-row">+ <span class="zone-name">{$t(`league.zone_${zone}`)}</span>+ <div class="goal-bar"><div class="goal-fill" style={`width:${pct}%`}></div></div>+ <span class="goal-value">{pct}%</span>+ </div>+ {/each}+ </div>+ <p class="win-note">+ {$t(`league.pref_${jungleReport.preference}`)} · {$t("league.jungle_invade")} {jungleReport.invadeRate}% · {$t("league.jungle_gank3")} {jungleReport.level3GankRate}%+ </p>+ {:else}+ <p class="empty-hint">{$t("league.jungle_empty")}</p>+ {/if}+ </section>+ {/if}+ {/if}++ <section class="card">+ <div class="card-head">+ <h3>{$t("league.duos_title")}</h3>+ <button class="button" onclick={loadDuos} disabled={duosLoading}>{$t("league.refresh")}</button>+ </div>+ <p class="win-disclaimer">{$t("league.duos_desc")}</p>+ {#if duos?.duos?.length}+ <div class="champ-table">+ {#each duos.duos as d (d.puuid)}+ <div class="champ-row">+ <span class="champ-row-name">{d.gameName ?? "—"}{#if d.tagLine}<span class="dim">#{d.tagLine}</span>{/if}</span>+ <span class="champ-row-games">{d.games} {$t("league.games_short")}</span>+ <span class="champ-row-wr" class:good={d.winrate >= 55} class:bad={d.winrate <= 45}>{d.winrate}%</span>+ <span class="champ-row-kda dim">{$t("league.duos_score")} {d.score}%</span>+ </div>+ {/each}+ </div>+ {:else if duos}+ <p class="empty-hint">{$t("league.duos_empty")}</p>+ {/if}+ </section>+ {/if}+{#if tab === "live"}{#if liveMetrics?.players?.length}<section class="card">@@ -1677,6 +1917,127 @@color: var(--text);}+ .search-form {+ display: flex;+ gap: 8px;+ flex-wrap: wrap;+ }++ .search-form .input-text {+ flex: 1;+ min-width: 180px;+ }++ .stat-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(110px, 1fr));+ gap: 10px;+ }++ .stat-cell {+ display: flex;+ flex-direction: column;+ gap: 2px;+ padding: 10px 12px;+ background: var(--button);+ border: 1px solid var(--input-border);+ border-radius: calc(var(--border-radius) - 2px);+ }++ .stat-value {+ font-size: 19px;+ font-weight: 600;+ font-variant-numeric: tabular-nums;+ }++ .stat-value.good {+ color: var(--success);+ }++ .stat-value.bad {+ color: var(--danger);+ }++ .stat-label {+ font-size: 11.5px;+ color: var(--gray);+ }++ .champ-table {+ display: flex;+ flex-direction: column;+ gap: 3px;+ }++ .champ-row {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 6px 8px;+ background: var(--button);+ border-radius: calc(var(--border-radius) - 4px);+ font-size: 12.5px;+ font-variant-numeric: tabular-nums;+ }++ .champ-row-name {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .champ-row-games,+ .champ-row-kda,+ .champ-row-cs {+ color: var(--gray);+ flex-shrink: 0;+ }++ .champ-row-wr {+ flex-shrink: 0;+ font-weight: 600;+ }++ .champ-row-wr.good {+ color: var(--success);+ }++ .champ-row-wr.bad {+ color: var(--danger);+ }++ .zone-bars {+ display: flex;+ flex-direction: column;+ gap: 7px;+ }++ .zone-row {+ display: grid;+ grid-template-columns: 60px 1fr 52px;+ gap: 10px;+ align-items: center;+ font-size: 12.5px;+ }++ .zone-name {+ color: var(--gray);+ }++ .chat-send {+ display: flex;+ gap: 8px;+ margin-top: 12px;+ flex-wrap: wrap;+ }++ .chat-send .input-text {+ flex: 1;+ min-width: 180px;+ }+.scout-teams {display: grid;grid-template-columns: 1fr 1fr;