Files
leaguerecorder/app/src/history.rs
T
vhaudiquet 6584b2f92f app: read the history a page at a time and open clips on demand
Every launch parsed all 313 timelines, raw responses and all, which put
2.1 GB of JSON on the heap at startup.

The list now holds `Summary` rows: `history::summaries` parses a file,
keeps the champion, queue, scoreline, LP change and event count, then
drops the timeline. Files are listed by write time, and `poll` reads the
next 20 when the list is scrolled near its end or when the filtered rows
do not fill the screen. Selecting a row hands its id to the review
screen, which reads that one timeline on a thread.

Peak memory over 313 recordings: 165 MB.
2026-11-16 23:48:58 +01:00

681 lines
23 KiB
Rust

//! Reading the daemon's timelines from disk and the values the screens show.
//!
//! Ported from `tauri-app/src-tauri/src/lib.rs` (`get_game_history`, `get_timeline`,
//! `find_video_file`) and the extractors in `tauri-app/src/types/timeline.ts`.
use std::path::{Path, PathBuf};
use chrono::{DateTime, Utc};
use serde::Deserialize;
use serde_json::Value;
use crate::daemon;
#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)] // every field mirrors the daemon's timeline JSON
pub struct Timeline {
pub recording_id: String,
pub start_time: DateTime<Utc>,
#[serde(default)]
pub end_time: Option<DateTime<Utc>>,
#[serde(default)]
pub duration_secs: i64,
#[serde(default)]
pub events: Vec<TimelineEvent>,
#[serde(default)]
pub game_id: Option<u64>,
#[serde(default)]
pub raw_session: Option<Value>,
#[serde(default)]
pub raw_summoner: Option<Value>,
#[serde(default)]
pub raw_champion_select: Option<Value>,
#[serde(default)]
pub raw_rune_page: Option<Value>,
#[serde(default)]
pub raw_live_client_data: Option<Value>,
#[serde(default)]
pub raw_end_game_stats: Option<Value>,
#[serde(default)]
pub video_file: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)]
pub struct TimelineEvent {
/// `(seconds, nanos)` since the recording started.
#[serde(default)]
pub video_timestamp: (i64, i32),
#[serde(default)]
pub game_timestamp: Option<(i64, i32)>,
#[serde(default)]
pub timestamp: Option<DateTime<Utc>>,
#[serde(default)]
pub event_type: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub raw_data: Value,
#[serde(default)]
pub uri: String,
}
impl TimelineEvent {
pub fn time(&self) -> f64 {
self.video_timestamp.0 as f64 + self.video_timestamp.1 as f64 / 1e9
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
Victory,
Defeat,
Terminated,
}
impl Outcome {
pub fn label(self) -> &'static str {
match self {
Outcome::Victory => "Victory",
Outcome::Defeat => "Defeat",
Outcome::Terminated => "Terminated",
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Stats {
pub kills: u32,
pub deaths: u32,
pub assists: u32,
pub creep_score: u32,
pub gold_earned: u64,
pub damage_dealt: u64,
pub vision_score: u32,
pub game_duration: u64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct LpChange {
pub delta: i64,
pub league_points: u32,
pub tier: String,
pub division: String,
pub in_promos: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueueCategory {
RankedSolo,
RankedFlex,
Normals,
Aram,
Custom,
}
impl QueueCategory {
pub fn label(self) -> &'static str {
match self {
QueueCategory::RankedSolo => "Ranked Solo",
QueueCategory::RankedFlex => "Ranked Flex",
QueueCategory::Normals => "Normals",
QueueCategory::Aram => "ARAM",
QueueCategory::Custom => "Custom",
}
}
}
/// The timeline folder the daemon writes.
pub fn timeline_dir() -> PathBuf {
daemon::recordings_dir().join("timelines")
}
/// Timeline files on disk, most recently written first.
///
/// The name is a recording id, so the write time is the only cheap order there is. A
/// recording is written when its game ends, which matches when it started closely enough for
/// a list that gets re-sorted by `start_time` as pages arrive.
pub fn timeline_paths() -> Vec<PathBuf> {
let dir = timeline_dir();
let Ok(entries) = std::fs::read_dir(&dir) else {
return Vec::new();
};
let mut found: Vec<(std::time::SystemTime, PathBuf)> = entries
.flatten()
.map(|entry| entry.path())
.filter(|path| path.extension().and_then(|e| e.to_str()) == Some("json"))
.filter_map(|path| {
let written = std::fs::metadata(&path).ok()?.modified().ok()?;
Some((written, path))
})
.collect();
found.sort_by_key(|(written, _)| std::cmp::Reverse(*written));
found.into_iter().map(|(_, path)| path).collect()
}
/// The rows for a page of timelines.
///
/// Each file is parsed whole, because the champion, the scoreline and the queue only exist
/// inside the raw responses, and the [`Timeline`] is dropped as soon as its [`Summary`] is
/// built. Only the summaries are kept, so the events and the raw JSON do not pile up.
pub fn summaries(paths: &[PathBuf]) -> Vec<Summary> {
paths.iter().filter_map(|path| summary_of(path)).collect()
}
fn summary_of(path: &Path) -> Option<Summary> {
let text = std::fs::read_to_string(path).ok()?;
match serde_json::from_str::<Timeline>(&text) {
Ok(timeline) => Some(timeline.summary()),
Err(e) => {
eprintln!("skipping {}: {e}", path.display());
None
}
}
}
/// What the match history list needs from a recording.
///
/// The list shows 309 rows of this at a time and the events and raw responses of the timeline
/// stay on disk until a row is opened, so this carries only the values they were read for.
#[derive(Debug, Clone)]
pub struct Summary {
pub recording_id: String,
pub start_time: DateTime<Utc>,
pub duration_secs: i64,
champion: Option<String>,
summoner: Option<String>,
queue_label: String,
category: QueueCategory,
outcome: Outcome,
stats: Option<Stats>,
lp: Option<LpChange>,
pub event_count: usize,
}
impl Summary {
pub fn champion(&self) -> Option<String> {
self.champion.clone()
}
pub fn summoner(&self) -> Option<String> {
self.summoner.clone()
}
pub fn queue_label(&self) -> &str {
&self.queue_label
}
pub fn category(&self) -> QueueCategory {
self.category
}
pub fn outcome(&self) -> Outcome {
self.outcome
}
pub fn stats(&self) -> Option<Stats> {
self.stats
}
pub fn lp_change(&self) -> Option<LpChange> {
self.lp.clone()
}
}
impl Timeline {
/// The list row for this recording, computed before the timeline is dropped.
pub fn summary(&self) -> Summary {
Summary {
recording_id: self.recording_id.clone(),
start_time: self.start_time,
duration_secs: self.duration_secs,
champion: self.champion(),
summoner: self.summoner(),
queue_label: self.queue_label(),
category: self.category(),
outcome: self.outcome(),
stats: self.stats(),
lp: self.lp_change(),
event_count: self.events.len(),
}
}
}
pub fn load(recording_id: &str) -> Option<Timeline> {
let path = timeline_dir().join(format!("{recording_id}.json"));
let text = std::fs::read_to_string(path).ok()?;
serde_json::from_str(&text).ok()
}
impl Timeline {
fn end_stats(&self) -> Option<&Value> {
self.raw_end_game_stats.as_ref()
}
pub fn outcome(&self) -> Outcome {
let stats = self
.end_stats()
.and_then(|s| s.get("localPlayer"))
.and_then(|p| p.get("stats"));
if stats.and_then(|s| s.get("WIN")).and_then(|v| v.as_u64()) == Some(1) {
Outcome::Victory
} else if stats.and_then(|s| s.get("LOSE")).and_then(|v| v.as_u64()) == Some(1) {
Outcome::Defeat
} else {
Outcome::Terminated
}
}
pub fn champion(&self) -> Option<String> {
if let Some(name) = self
.end_stats()
.and_then(|s| s.pointer("/localPlayer/championName"))
.and_then(|v| v.as_str())
{
return Some(name.to_string());
}
self.raw_live_client_data
.as_ref()
.and_then(|s| s.pointer("/activePlayer/championName"))
.and_then(|v| v.as_str())
.map(str::to_string)
}
pub fn summoner(&self) -> Option<String> {
if let Some(game_name) = self
.end_stats()
.and_then(|s| s.pointer("/localPlayer/riotIdGameName"))
.and_then(|v| v.as_str())
{
let tag = self
.end_stats()
.and_then(|s| s.pointer("/localPlayer/riotIdTagLine"))
.and_then(|v| v.as_str())
.unwrap_or("");
return Some(if tag.is_empty() {
game_name.to_string()
} else {
format!("{game_name}#{tag}")
});
}
let summoner = self.raw_summoner.as_ref()?;
if let Some(name) = summoner.get("gameName").and_then(|v| v.as_str()) {
let tag = summoner
.get("tagLine")
.and_then(|v| v.as_str())
.unwrap_or("");
return Some(if tag.is_empty() {
name.to_string()
} else {
format!("{name}#{tag}")
});
}
summoner
.get("displayName")
.or_else(|| summoner.get("name"))
.and_then(|v| v.as_str())
.map(str::to_string)
}
pub fn queue_name(&self) -> Option<String> {
self.raw_session
.as_ref()
.and_then(|s| s.pointer("/gameData/queue/name"))
.and_then(|v| v.as_str())
.map(str::to_string)
}
pub fn queue_id(&self) -> Option<u64> {
self.raw_session
.as_ref()
.and_then(|s| s.pointer("/gameData/queue/id"))
.and_then(|v| v.as_u64())
}
/// A display name for the queue, falling back to the queue id table.
pub fn queue_label(&self) -> String {
if let Some(name) = self.queue_name() {
if name.contains("Practice") {
return "Practice Tool".into();
}
if name.contains("Ranked Solo") {
return "Ranked Solo".into();
}
if name.contains("Ranked Flex") {
return "Ranked Flex".into();
}
if name.contains("ARAM") {
return "ARAM".into();
}
if name.contains("Normal") {
return "Normal".into();
}
if name.contains("Co-op") {
return "Co-op vs AI".into();
}
return name;
}
match self.queue_id() {
Some(420) => "Ranked Solo".into(),
Some(440) => "Ranked Flex".into(),
Some(450) => "ARAM".into(),
Some(400) => "Normal Draft".into(),
Some(430) => "Normal Blind".into(),
Some(800..=850) => "Co-op vs AI".into(),
Some(3140) => "Practice Tool".into(),
Some(_) => "Custom Game".into(),
None => "Custom Game".into(),
}
}
pub fn category(&self) -> QueueCategory {
if let Some(name) = self.queue_name() {
if name.contains("Ranked Solo") {
return QueueCategory::RankedSolo;
}
if name.contains("Ranked Flex") {
return QueueCategory::RankedFlex;
}
if name.contains("ARAM") {
return QueueCategory::Aram;
}
if name.contains("Normal") || name.contains("Draft") || name.contains("Blind") {
return QueueCategory::Normals;
}
if name.contains("Custom") || name.contains("Practice") {
return QueueCategory::Custom;
}
}
match self.queue_id() {
Some(420) => QueueCategory::RankedSolo,
Some(440) => QueueCategory::RankedFlex,
Some(400 | 430) => QueueCategory::Normals,
Some(450) => QueueCategory::Aram,
_ => QueueCategory::Custom,
}
}
pub fn stats(&self) -> Option<Stats> {
let player = self.end_stats()?.get("localPlayer")?;
let s = player.get("stats")?;
let n = |k: &str| s.get(k).and_then(|v| v.as_u64()).unwrap_or(0);
Some(Stats {
kills: n("CHAMPIONS_KILLED") as u32,
deaths: n("NUM_DEATHS") as u32,
assists: n("ASSISTS") as u32,
creep_score: n("MINIONS_KILLED") as u32,
gold_earned: n("GOLD_EARNED"),
damage_dealt: n("TOTAL_DAMAGE_DEALT_TO_CHAMPIONS"),
vision_score: n("VISION_SCORE") as u32,
game_duration: self
.end_stats()
.and_then(|s| s.get("gameLength"))
.and_then(|v| v.as_u64())
.unwrap_or(self.duration_secs.max(0) as u64),
})
}
pub fn lp_change(&self) -> Option<LpChange> {
let lp_events: Vec<&TimelineEvent> = self
.events
.iter()
.filter(|e| e.event_type == "lp_change")
.collect();
let ranked = lp_events.iter().find(|e| {
e.raw_data
.get("tier")
.and_then(|v| v.as_str())
.is_some_and(|t| t != "UNRANKED")
});
let event = ranked
.or_else(|| {
lp_events.iter().find(|e| {
e.raw_data.get("leaguePointsDelta").and_then(|v| v.as_i64()) != Some(0)
})
})
.or_else(|| lp_events.first())?;
let raw = &event.raw_data;
let delta = raw.get("leaguePointsDelta").and_then(|v| v.as_i64())?;
Some(LpChange {
delta,
league_points: raw
.get("leaguePoints")
.and_then(|v| v.as_u64())
.unwrap_or(0) as u32,
tier: raw
.get("tier")
.and_then(|v| v.as_str())
.unwrap_or("UNRANKED")
.to_string(),
division: raw
.get("division")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
in_promos: raw
.get("miniseriesProgress")
.and_then(|v| v.as_str())
.is_some_and(|s| !s.is_empty()),
})
}
/// The recording's video file, by name or by the timestamp prefix.
pub fn video_path(&self) -> Option<PathBuf> {
let dir = daemon::recordings_dir();
find_video_file(&dir, self.video_file.as_deref()?)
}
}
/// Exact name first, then a file sharing the timestamp prefix.
pub fn find_video_file(dir: &Path, filename: &str) -> Option<PathBuf> {
let exact = dir.join(filename);
if exact.exists() {
return Some(exact);
}
let prefix = filename.replace("_unknown.mp4", "");
let entries = std::fs::read_dir(dir).ok()?;
for entry in entries.flatten() {
let path = entry.path();
let video = matches!(
path.extension().and_then(|e| e.to_str()),
Some("mp4" | "mkv" | "mov")
);
if !video {
continue;
}
let name = path.file_name()?.to_string_lossy().to_string();
if name.starts_with(&prefix) {
return Some(path);
}
}
None
}
/// Two made-up recordings for `--scene` snapshots and for checking layout without a daemon.
pub fn sample() -> Vec<Timeline> {
let now = Utc::now();
let game = |id: &str,
hours_ago: i64,
champion: &str,
win: bool,
kills: u64,
deaths: u64,
assists: u64,
cs: u64| {
let start = now - chrono::Duration::hours(hours_ago);
let event = |at: f64, kind: &str, description: &str, raw: Value| TimelineEvent {
video_timestamp: (at as i64, ((at.fract()) * 1e9) as i32),
game_timestamp: None,
timestamp: None,
event_type: kind.to_string(),
description: description.to_string(),
raw_data: raw,
uri: String::new(),
};
let events = vec![
event(12.0, "game_start", "Game start", Value::Null),
event(
212.0,
"kill",
"Killed Ahri",
serde_json::json!({"KillerName": "Demo#EUW", "VictimName": "Ahri", "Assisters": ["Thresh"]}),
),
event(
368.0,
"kill",
"Killed Lee Sin",
serde_json::json!({"KillerName": "Demo#EUW", "VictimName": "Lee Sin", "Assisters": []}),
),
event(
402.0,
"kill",
"Killed by Zed",
serde_json::json!({"KillerName": "Zed", "VictimName": "Demo#EUW", "Assisters": []}),
),
event(744.0, "objective", "Dragon", Value::Null),
event(1500.0, "game_end", "Game end", Value::Null),
event(
1510.0,
"lp_change",
if win { "+21 LP" } else { "-19 LP" },
serde_json::json!({
"leaguePointsDelta": if win { 21 } else { -19 },
"leaguePoints": if win { 74 } else { 54 },
"tier": "EMERALD",
"division": "II",
"queueType": "RANKED_SOLO_5x5"
}),
),
];
Timeline {
recording_id: id.to_string(),
start_time: start,
end_time: Some(start + chrono::Duration::seconds(1830)),
duration_secs: 1830,
events,
game_id: Some(7_000_000),
raw_session: Some(
serde_json::json!({"gameData": {"queue": {"name": "Ranked Solo", "id": 420}}}),
),
raw_summoner: Some(serde_json::json!({"gameName": "Demo", "tagLine": "EUW"})),
raw_champion_select: None,
raw_rune_page: None,
raw_live_client_data: None,
raw_end_game_stats: Some(serde_json::json!({
"gameLength": 1830,
"localPlayer": {
"championName": champion,
"riotIdGameName": "Demo",
"riotIdTagLine": "EUW",
"stats": {
"CHAMPIONS_KILLED": kills,
"NUM_DEATHS": deaths,
"ASSISTS": assists,
"MINIONS_KILLED": cs,
"GOLD_EARNED": 13_450,
"TOTAL_DAMAGE_DEALT_TO_CHAMPIONS": 24_800,
"VISION_SCORE": 32,
"WIN": if win { 1 } else { 0 },
"LOSE": if win { 0 } else { 1 }
}
}
})),
video_file: None,
}
};
vec![
game("demo-1", 3, "Kai'Sa", true, 9, 3, 7, 214),
game("demo-2", 27, "Jinx", false, 4, 8, 5, 188),
]
}
#[cfg(test)]
mod tests {
use super::*;
const TIMELINE: &str = r#"{
"recording_id": "0b7d3f6e-2f4a-4b83-9f0e-0d5c9f1a2b3c",
"start_time": "2026-03-27T16:42:52Z",
"end_time": "2026-03-27T17:13:22Z",
"duration_secs": 1830,
"events": [
{"video_timestamp": [212, 0], "game_timestamp": null, "timestamp": "2026-03-27T16:46:24Z",
"event_type": "kill", "description": "Killed Ahri", "uri": "",
"raw_data": {"KillerName": "Me#EUW", "VictimName": "Ahri", "Assisters": []}},
{"video_timestamp": [1500, 500000000], "event_type": "lp_change", "description": "",
"raw_data": {"leaguePointsDelta": 21, "leaguePoints": 74, "tier": "EMERALD", "division": "II"}}
],
"raw_session": {"gameData": {"queue": {"name": "Ranked Solo", "id": 420}}},
"raw_end_game_stats": {"gameLength": 1830, "localPlayer": {"championName": "Kai'Sa",
"riotIdGameName": "Demo", "riotIdTagLine": "EUW",
"stats": {"CHAMPIONS_KILLED": 9, "NUM_DEATHS": 3, "ASSISTS": 7, "MINIONS_KILLED": 214,
"GOLD_EARNED": 13450, "VISION_SCORE": 32, "WIN": 1, "LOSE": 0}}},
"video_file": "2026-03-27_16-42-52_unknown.mp4"
}"#;
fn parsed() -> Timeline {
serde_json::from_str(TIMELINE).unwrap()
}
#[test]
fn a_timeline_parses_with_duration_tuples() {
let timeline = parsed();
assert_eq!(timeline.duration_secs, 1830);
assert!((timeline.events[0].time() - 212.0).abs() < 1e-9);
assert!((timeline.events[1].time() - 1500.5).abs() < 1e-6);
}
#[test]
fn the_game_values_come_out_of_the_raw_responses() {
let timeline = parsed();
assert_eq!(timeline.champion().as_deref(), Some("Kai'Sa"));
assert_eq!(timeline.summoner().as_deref(), Some("Demo#EUW"));
assert_eq!(timeline.outcome(), Outcome::Victory);
assert_eq!(timeline.queue_label(), "Ranked Solo");
assert_eq!(timeline.category(), QueueCategory::RankedSolo);
let stats = timeline.stats().unwrap();
assert_eq!((stats.kills, stats.deaths, stats.assists), (9, 3, 7));
assert_eq!(stats.creep_score, 214);
}
#[test]
fn the_lp_event_is_the_ranked_one() {
let lp = parsed().lp_change().unwrap();
assert_eq!(lp.delta, 21);
assert_eq!(lp.tier, "EMERALD");
assert_eq!(lp.league_points, 74);
}
#[test]
fn a_summary_keeps_what_the_row_shows() {
let summary = parsed().summary();
assert_eq!(summary.recording_id, "0b7d3f6e-2f4a-4b83-9f0e-0d5c9f1a2b3c");
assert_eq!(summary.champion().as_deref(), Some("Kai'Sa"));
assert_eq!(summary.queue_label(), "Ranked Solo");
assert_eq!(summary.outcome(), Outcome::Victory);
assert_eq!(summary.event_count, 2);
assert_eq!(summary.stats().unwrap().kills, 9);
assert_eq!(summary.lp_change().unwrap().delta, 21);
}
#[test]
fn pages_read_summaries_from_disk() {
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("game.json");
std::fs::write(&path, TIMELINE).unwrap();
let rows = summaries(&[path, dir.join("missing.json")]);
assert_eq!(rows.len(), 1, "a file that cannot be read is skipped");
assert_eq!(rows[0].champion().as_deref(), Some("Kai'Sa"));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_video_is_found_by_its_timestamp_prefix() {
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("2026-03-27_16-42-52_kai_sa.mp4"), b"x").unwrap();
let found = find_video_file(&dir, "2026-03-27_16-42-52_unknown.mp4").unwrap();
assert!(found.ends_with("2026-03-27_16-42-52_kai_sa.mp4"));
let _ = std::fs::remove_dir_all(dir);
}
}