Wire League auto clipping poller
This commit is contained in:
1 parent
4d465759ad
commit
97120d4d18
3 files changed
+287
-1
No files matched your search
+103
-1
@@ -5,11 +5,14 @@ use clipforge::capture::{
|
||||
use clipforge::database::ClipDatabase;
|
||||
use clipforge::game_detection::{default_profiles, detect_game};
|
||||
use clipforge::game_watcher::running_processes;
|
||||
use clipforge::integrations::{
|
||||
GameIntegration, IntegrationError, LeagueIntegration, LeagueLiveClientPoller,
|
||||
};
|
||||
use clipforge::media::{
|
||||
collect_segments, concat_segments, generate_thumbnail, prune_old_segments, recent_segments,
|
||||
trim_clip as ffmpeg_trim_clip,
|
||||
};
|
||||
use clipforge::models::{Clip, ClipSource, RecordingStatus, UploadProvider};
|
||||
use clipforge::models::{Clip, ClipSource, GameEvent, RecordingStatus, UploadProvider};
|
||||
use clipforge::recorder::{RecorderAction, RecorderService};
|
||||
use clipforge::settings::AppSettings;
|
||||
use clipforge::storage::{clip_path, is_inside_root, LibraryPaths};
|
||||
@@ -26,6 +29,7 @@ struct AppRuntime {
|
||||
recorder: Mutex<RecorderService>,
|
||||
database: Mutex<ClipDatabase>,
|
||||
capture: Mutex<Option<ActiveCapture>>,
|
||||
league_poller: Mutex<LeagueLiveClientPoller>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -103,6 +107,51 @@ fn list_clips(runtime: State<'_, AppRuntime>) -> Result<Vec<ClipDto>, String> {
|
||||
Ok(recorder.library.all().iter().map(clip_to_dto).collect())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn poll_auto_clip_events(runtime: State<'_, AppRuntime>) -> Result<Vec<ClipDto>, String> {
|
||||
let (session_id, game_id, session_started_at) = {
|
||||
let recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
|
||||
let capture = runtime.capture.lock().map_err(|error| error.to_string())?;
|
||||
let Some(active) = capture.as_ref() else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let Some(session_id) = recorder.state.active_session_id.clone() else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let Some(game_id) = recorder.state.detected_game_id.clone() else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
(session_id, game_id, active.started_at)
|
||||
};
|
||||
|
||||
if game_id != "league-of-legends" {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let raw_events = {
|
||||
let mut poller = runtime
|
||||
.league_poller
|
||||
.lock()
|
||||
.map_err(|error| error.to_string())?;
|
||||
match poller.poll_new_events(session_started_at) {
|
||||
Ok(events) => events,
|
||||
Err(IntegrationError::Http(_)) => return Ok(Vec::new()),
|
||||
Err(error) => return Err(error.to_string()),
|
||||
}
|
||||
};
|
||||
|
||||
let integration = LeagueIntegration;
|
||||
let mut created = Vec::new();
|
||||
for raw_event in raw_events {
|
||||
if let Some(event) = integration.normalize_event(&raw_event, &session_id) {
|
||||
if let Some(clip) = handle_auto_event_inner(event, runtime.inner())? {
|
||||
created.push(clip);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(created)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn save_manual_clip(seconds: u64, runtime: State<'_, AppRuntime>) -> Result<ClipDto, String> {
|
||||
save_manual_clip_inner(seconds, runtime.inner())
|
||||
@@ -164,6 +213,57 @@ fn save_manual_clip_inner(seconds: u64, runtime: &AppRuntime) -> Result<ClipDto,
|
||||
Ok(clip_to_dto(&clip))
|
||||
}
|
||||
|
||||
fn handle_auto_event_inner(
|
||||
event: GameEvent,
|
||||
runtime: &AppRuntime,
|
||||
) -> Result<Option<ClipDto>, String> {
|
||||
let mut recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
|
||||
let capture = runtime.capture.lock().map_err(|error| error.to_string())?;
|
||||
let Some(active) = capture.as_ref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let ffmpeg = find_ffmpeg_executable()
|
||||
.ok_or_else(|| "FFmpeg was not found on PATH or in the bundled sidecar.".to_string())?;
|
||||
let clip_window = recorder.settings.auto_clip.pre_roll + recorder.settings.auto_clip.post_roll;
|
||||
let segment_paths = recent_segments(
|
||||
&active.buffer_dir,
|
||||
clip_window,
|
||||
active.segment_duration,
|
||||
SystemTime::now(),
|
||||
)
|
||||
.map_err(|error| error.to_string())?;
|
||||
if segment_paths.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let action = recorder.handle_game_event(event);
|
||||
let RecorderAction::CreatedClip { clip_id, .. } = action else {
|
||||
return Ok(None);
|
||||
};
|
||||
let clip = recorder
|
||||
.library
|
||||
.all()
|
||||
.iter()
|
||||
.find(|clip| clip.id == clip_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| "Created auto clip was not found in the library.".to_string())?;
|
||||
|
||||
if let Err(error) = concat_segments(&ffmpeg, &segment_paths, &clip.path) {
|
||||
recorder.library.remove_clip(&clip.id);
|
||||
let _ = runtime
|
||||
.database
|
||||
.lock()
|
||||
.map(|database| database.delete_clip(&clip.id));
|
||||
return Err(error.to_string());
|
||||
}
|
||||
if let Some(thumbnail_path) = &clip.thumbnail_path {
|
||||
let _ = generate_thumbnail(&ffmpeg, &clip.path, thumbnail_path);
|
||||
}
|
||||
persist_clip(runtime, &clip)?;
|
||||
save_manifest(&recorder)?;
|
||||
Ok(Some(clip_to_dto(&clip)))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn start_capture(runtime: State<'_, AppRuntime>) -> Result<DesktopStatus, String> {
|
||||
start_capture_inner(runtime.inner())
|
||||
@@ -418,6 +518,7 @@ fn main() {
|
||||
recorder: Mutex::new(recorder),
|
||||
database: Mutex::new(database),
|
||||
capture: Mutex::new(None),
|
||||
league_poller: Mutex::new(LeagueLiveClientPoller::default()),
|
||||
})
|
||||
.setup(|app| {
|
||||
#[cfg(desktop)]
|
||||
@@ -469,6 +570,7 @@ fn main() {
|
||||
get_status,
|
||||
refresh_detected_game,
|
||||
list_clips,
|
||||
poll_auto_clip_events,
|
||||
save_manual_clip,
|
||||
start_capture,
|
||||
stop_capture,
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
use crate::models::{GameEvent, GameEventType};
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::fmt;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
pub trait GameIntegration {
|
||||
@@ -7,6 +10,21 @@ pub trait GameIntegration {
|
||||
fn normalize_event(&self, raw: &RawGameEvent, session_id: &str) -> Option<GameEvent>;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum IntegrationError {
|
||||
Http(String),
|
||||
Parse(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for IntegrationError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Http(message) => write!(f, "integration HTTP error: {message}"),
|
||||
Self::Parse(message) => write!(f, "integration parse error: {message}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct RawGameEvent {
|
||||
pub event_id: String,
|
||||
@@ -19,6 +37,71 @@ pub struct RawGameEvent {
|
||||
#[derive(Debug, Default)]
|
||||
pub struct LeagueIntegration;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct LeagueLiveClientPoller {
|
||||
seen_event_ids: BTreeSet<u64>,
|
||||
}
|
||||
|
||||
impl LeagueLiveClientPoller {
|
||||
pub fn poll_new_events(
|
||||
&mut self,
|
||||
session_started_at: SystemTime,
|
||||
) -> Result<Vec<RawGameEvent>, IntegrationError> {
|
||||
let client = reqwest::blocking::Client::builder()
|
||||
.danger_accept_invalid_certs(true)
|
||||
.timeout(Duration::from_millis(900))
|
||||
.build()
|
||||
.map_err(|error| IntegrationError::Http(error.to_string()))?;
|
||||
let body = client
|
||||
.get("https://127.0.0.1:2999/liveclientdata/eventdata")
|
||||
.send()
|
||||
.map_err(|error| IntegrationError::Http(error.to_string()))?
|
||||
.error_for_status()
|
||||
.map_err(|error| IntegrationError::Http(error.to_string()))?
|
||||
.text()
|
||||
.map_err(|error| IntegrationError::Http(error.to_string()))?;
|
||||
let events = parse_league_live_events(&body, session_started_at)?;
|
||||
Ok(events
|
||||
.into_iter()
|
||||
.filter(|event| {
|
||||
event
|
||||
.event_id
|
||||
.parse::<u64>()
|
||||
.map(|id| self.seen_event_ids.insert(id))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_league_live_events(
|
||||
body: &str,
|
||||
session_started_at: SystemTime,
|
||||
) -> Result<Vec<RawGameEvent>, IntegrationError> {
|
||||
let value: Value =
|
||||
serde_json::from_str(body).map_err(|error| IntegrationError::Parse(error.to_string()))?;
|
||||
let Some(events) = value.get("Events").and_then(Value::as_array) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
Ok(events
|
||||
.iter()
|
||||
.filter_map(|event| {
|
||||
let event_id = event.get("EventID")?.as_u64()?;
|
||||
let event_name = event.get("EventName")?.as_str()?;
|
||||
let event_time = event
|
||||
.get("EventTime")
|
||||
.and_then(Value::as_f64)
|
||||
.unwrap_or_default();
|
||||
let mut raw =
|
||||
league_event_from_live_client(event_id, event_name, event_time, session_started_at);
|
||||
if let Some(killer) = event.get("KillerName").and_then(Value::as_str) {
|
||||
raw.player = Some(killer.to_string());
|
||||
}
|
||||
Some(raw)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
impl GameIntegration for LeagueIntegration {
|
||||
fn game_id(&self) -> &'static str {
|
||||
"league-of-legends"
|
||||
@@ -94,6 +177,51 @@ impl GameIntegration for ValveGsiIntegration {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn valve_gsi_raw_events(
|
||||
body: &str,
|
||||
now: SystemTime,
|
||||
) -> Result<Vec<RawGameEvent>, IntegrationError> {
|
||||
let value: Value =
|
||||
serde_json::from_str(body).map_err(|error| IntegrationError::Parse(error.to_string()))?;
|
||||
let mut events = Vec::new();
|
||||
|
||||
if let Some(round_phase) = value
|
||||
.pointer("/round/phase")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|phase| *phase == "over")
|
||||
{
|
||||
events.push(RawGameEvent {
|
||||
event_id: format!("round:{round_phase}:{}", millis(now)),
|
||||
name: "round_win".to_string(),
|
||||
timestamp: now,
|
||||
player: None,
|
||||
metadata: BTreeMap::new(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(player_state) = value.pointer("/player/state").and_then(Value::as_object) {
|
||||
if player_state
|
||||
.get("round_kills")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or_default()
|
||||
>= 2
|
||||
{
|
||||
events.push(RawGameEvent {
|
||||
event_id: format!("multi-kill:{}", millis(now)),
|
||||
name: "multi_kill".to_string(),
|
||||
timestamp: now,
|
||||
player: value
|
||||
.pointer("/player/name")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToString::to_string),
|
||||
metadata: BTreeMap::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
fn to_game_event(
|
||||
game_id: &str,
|
||||
raw: &RawGameEvent,
|
||||
@@ -127,6 +255,12 @@ pub fn league_event_from_live_client(
|
||||
}
|
||||
}
|
||||
|
||||
fn millis(time: SystemTime) -> u128 {
|
||||
time.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -143,4 +277,31 @@ mod tests {
|
||||
assert_eq!(event.game_id, "league-of-legends");
|
||||
assert_eq!(event.event_type, GameEventType::Kill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_live_client_events() {
|
||||
let body = r#"{
|
||||
"Events": [
|
||||
{"EventID": 1, "EventName": "GameStart", "EventTime": 0},
|
||||
{"EventID": 2, "EventName": "ChampionKill", "EventTime": 42.5, "KillerName": "Player"}
|
||||
]
|
||||
}"#;
|
||||
|
||||
let events = parse_league_live_events(body, SystemTime::UNIX_EPOCH).expect("events");
|
||||
|
||||
assert_eq!(events.len(), 2);
|
||||
assert_eq!(events[1].event_id, "2");
|
||||
assert_eq!(events[1].player.as_deref(), Some("Player"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_valve_gsi_multi_kill() {
|
||||
let body = r#"{"player":{"name":"Alvin","state":{"round_kills":2}}}"#;
|
||||
|
||||
let events = valve_gsi_raw_events(body, SystemTime::UNIX_EPOCH).expect("events");
|
||||
|
||||
assert_eq!(events.len(), 1);
|
||||
assert_eq!(events[0].name, "multi_kill");
|
||||
assert_eq!(events[0].player.as_deref(), Some("Alvin"));
|
||||
}
|
||||
}
|
||||
@@ -669,6 +669,26 @@ async function refreshStatus() {
|
||||
}
|
||||
}
|
||||
|
||||
async function pollAutoClips() {
|
||||
if (!tauriInvoke || !state.captureActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const clips = await tauriInvoke<ClipDto[]>("poll_auto_clip_events");
|
||||
if (clips.length === 0) {
|
||||
return;
|
||||
}
|
||||
const created = clips.map(clipFromDto);
|
||||
state.clips = [...created, ...state.clips.filter((clip) => !created.some((fresh) => fresh.id === clip.id))];
|
||||
state.selectedClipId = created[0].id;
|
||||
state.activeView = "Library";
|
||||
render();
|
||||
} catch (error) {
|
||||
console.warn("Could not poll auto clips", error);
|
||||
}
|
||||
}
|
||||
|
||||
function parseTimestamp(value: string) {
|
||||
const parts = value.trim().split(":").map(Number);
|
||||
if (parts.some((part) => Number.isNaN(part))) {
|
||||
@@ -704,6 +724,9 @@ async function loadDesktopBridge() {
|
||||
window.setInterval(() => {
|
||||
void refreshStatus();
|
||||
}, 3_000);
|
||||
window.setInterval(() => {
|
||||
void pollAutoClips();
|
||||
}, 2_000);
|
||||
} catch (error) {
|
||||
console.warn("Tauri bridge unavailable", error);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user