init
This commit is contained in:
commit
42ef2f9674
468 files changed
+645161
No files matched your search
+264
@@ -0,0 +1,264 @@
|
||||
use std::fmt;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum CaptureSource {
|
||||
GameWindow {
|
||||
process_name: String,
|
||||
window_title: String,
|
||||
},
|
||||
Monitor {
|
||||
display_id: String,
|
||||
},
|
||||
Desktop,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum EncoderPreference {
|
||||
HardwareH264,
|
||||
SoftwareH264,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CaptureConfig {
|
||||
pub source: CaptureSource,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub fps: u32,
|
||||
pub bitrate_kbps: u32,
|
||||
pub encoder: EncoderPreference,
|
||||
pub mic_enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum CaptureError {
|
||||
UnsupportedPlatform,
|
||||
DeviceUnavailable(String),
|
||||
PermissionDenied(String),
|
||||
EncoderUnavailable(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for CaptureError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::UnsupportedPlatform => {
|
||||
f.write_str("capture is currently implemented for Windows only")
|
||||
}
|
||||
Self::DeviceUnavailable(message) => write!(f, "capture device unavailable: {message}"),
|
||||
Self::PermissionDenied(message) => write!(f, "capture permission denied: {message}"),
|
||||
Self::EncoderUnavailable(message) => write!(f, "encoder unavailable: {message}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait CaptureBackend {
|
||||
fn name(&self) -> &'static str;
|
||||
fn start(&mut self, config: CaptureConfig) -> Result<(), CaptureError>;
|
||||
fn stop(&mut self) -> Result<(), CaptureError>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct WindowsCaptureBackend {
|
||||
active: bool,
|
||||
}
|
||||
|
||||
impl CaptureBackend for WindowsCaptureBackend {
|
||||
fn name(&self) -> &'static str {
|
||||
"windows-graphics-capture"
|
||||
}
|
||||
|
||||
fn start(&mut self, _config: CaptureConfig) -> Result<(), CaptureError> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
self.active = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
Err(CaptureError::UnsupportedPlatform)
|
||||
}
|
||||
}
|
||||
|
||||
fn stop(&mut self) -> Result<(), CaptureError> {
|
||||
self.active = false;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_ffmpeg_executable() -> Option<PathBuf> {
|
||||
let bundled = std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|path| path.parent().map(|parent| parent.to_path_buf()))
|
||||
.map(|parent| parent.join("ffmpeg-x86_64-pc-windows-msvc.exe"));
|
||||
if let Some(path) = bundled {
|
||||
if path.exists() {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
|
||||
let candidates = ["ffmpeg.exe", "ffmpeg"];
|
||||
for candidate in candidates {
|
||||
if Command::new(candidate).arg("-version").output().is_ok() {
|
||||
return Some(PathBuf::from(candidate));
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
pub fn ffmpeg_is_available() -> bool {
|
||||
find_ffmpeg_executable().is_some()
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FfmpegRecordingPlan {
|
||||
pub executable: PathBuf,
|
||||
pub args: Vec<String>,
|
||||
}
|
||||
|
||||
impl FfmpegRecordingPlan {
|
||||
pub fn for_windows_desktop(
|
||||
executable: impl Into<PathBuf>,
|
||||
output: impl Into<PathBuf>,
|
||||
config: &CaptureConfig,
|
||||
) -> Self {
|
||||
let preset = match config.encoder {
|
||||
EncoderPreference::HardwareH264 => "h264_mf",
|
||||
EncoderPreference::SoftwareH264 => "libx264",
|
||||
};
|
||||
let output = output.into();
|
||||
let size = format!("{}x{}", config.width, config.height);
|
||||
let fps = config.fps.to_string();
|
||||
let bitrate = format!("{}k", config.bitrate_kbps);
|
||||
|
||||
Self {
|
||||
executable: executable.into(),
|
||||
args: vec![
|
||||
"-y".to_string(),
|
||||
"-hide_banner".to_string(),
|
||||
"-loglevel".to_string(),
|
||||
"error".to_string(),
|
||||
"-f".to_string(),
|
||||
"gdigrab".to_string(),
|
||||
"-framerate".to_string(),
|
||||
fps,
|
||||
"-video_size".to_string(),
|
||||
size,
|
||||
"-i".to_string(),
|
||||
"desktop".to_string(),
|
||||
"-c:v".to_string(),
|
||||
preset.to_string(),
|
||||
"-b:v".to_string(),
|
||||
bitrate,
|
||||
"-pix_fmt".to_string(),
|
||||
"yuv420p".to_string(),
|
||||
"-movflags".to_string(),
|
||||
"+faststart".to_string(),
|
||||
output.display().to_string(),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct FfmpegCaptureBackend {
|
||||
executable: PathBuf,
|
||||
output: PathBuf,
|
||||
child: Option<Child>,
|
||||
}
|
||||
|
||||
impl FfmpegCaptureBackend {
|
||||
pub fn new(executable: impl Into<PathBuf>, output: impl Into<PathBuf>) -> Self {
|
||||
Self {
|
||||
executable: executable.into(),
|
||||
output: output.into(),
|
||||
child: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn plan(&self, config: &CaptureConfig) -> FfmpegRecordingPlan {
|
||||
FfmpegRecordingPlan::for_windows_desktop(&self.executable, &self.output, config)
|
||||
}
|
||||
}
|
||||
|
||||
impl CaptureBackend for FfmpegCaptureBackend {
|
||||
fn name(&self) -> &'static str {
|
||||
"ffmpeg-gdigrab"
|
||||
}
|
||||
|
||||
fn start(&mut self, config: CaptureConfig) -> Result<(), CaptureError> {
|
||||
if self.child.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let plan = self.plan(&config);
|
||||
let child = Command::new(&plan.executable)
|
||||
.args(&plan.args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?;
|
||||
self.child = Some(child);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stop(&mut self) -> Result<(), CaptureError> {
|
||||
if let Some(mut child) = self.child.take() {
|
||||
if let Some(stdin) = child.stdin.as_mut() {
|
||||
let _ = stdin.write_all(b"q\n");
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
if child
|
||||
.try_wait()
|
||||
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?
|
||||
.is_some()
|
||||
{
|
||||
break;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
break;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FfmpegCaptureBackend {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ffmpeg_plan_prefers_media_foundation_h264() {
|
||||
let config = CaptureConfig {
|
||||
source: CaptureSource::Desktop,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
fps: 30,
|
||||
bitrate_kbps: 6000,
|
||||
encoder: EncoderPreference::HardwareH264,
|
||||
mic_enabled: false,
|
||||
};
|
||||
|
||||
let plan = FfmpegRecordingPlan::for_windows_desktop("ffmpeg", "out.mp4", &config);
|
||||
|
||||
assert!(plan.args.contains(&"h264_mf".to_string()));
|
||||
assert!(plan.args.contains(&"1280x720".to_string()));
|
||||
assert!(plan.args.contains(&"6000k".to_string()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RunningProcess {
|
||||
pub pid: u32,
|
||||
pub process_name: String,
|
||||
pub executable_path: String,
|
||||
pub window_title: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct GameProfile {
|
||||
pub game_id: String,
|
||||
pub display_name: String,
|
||||
pub process_names: Vec<String>,
|
||||
pub window_title_contains: Vec<String>,
|
||||
pub auto_record: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DetectedGame {
|
||||
pub game_id: String,
|
||||
pub display_name: String,
|
||||
pub process: RunningProcess,
|
||||
}
|
||||
|
||||
pub fn detect_game(processes: &[RunningProcess], profiles: &[GameProfile]) -> Option<DetectedGame> {
|
||||
profiles.iter().find_map(|profile| {
|
||||
processes.iter().find_map(|process| {
|
||||
let process_matches = profile
|
||||
.process_names
|
||||
.iter()
|
||||
.any(|name| name.eq_ignore_ascii_case(&process.process_name));
|
||||
let title_matches = process
|
||||
.window_title
|
||||
.as_deref()
|
||||
.map(|title| {
|
||||
profile
|
||||
.window_title_contains
|
||||
.iter()
|
||||
.any(|needle| title.to_lowercase().contains(&needle.to_lowercase()))
|
||||
})
|
||||
.unwrap_or(false);
|
||||
|
||||
if process_matches || title_matches {
|
||||
Some(DetectedGame {
|
||||
game_id: profile.game_id.clone(),
|
||||
display_name: profile.display_name.clone(),
|
||||
process: process.clone(),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn default_profiles() -> Vec<GameProfile> {
|
||||
vec![
|
||||
GameProfile {
|
||||
game_id: "league-of-legends".to_string(),
|
||||
display_name: "League of Legends".to_string(),
|
||||
process_names: vec!["League of Legends.exe".to_string()],
|
||||
window_title_contains: vec!["League of Legends".to_string()],
|
||||
auto_record: true,
|
||||
},
|
||||
GameProfile {
|
||||
game_id: "counter-strike-2".to_string(),
|
||||
display_name: "Counter-Strike 2".to_string(),
|
||||
process_names: vec!["cs2.exe".to_string()],
|
||||
window_title_contains: vec!["Counter-Strike 2".to_string()],
|
||||
auto_record: true,
|
||||
},
|
||||
GameProfile {
|
||||
game_id: "dota-2".to_string(),
|
||||
display_name: "Dota 2".to_string(),
|
||||
process_names: vec!["dota2.exe".to_string()],
|
||||
window_title_contains: vec!["Dota 2".to_string()],
|
||||
auto_record: true,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn detects_by_process_name() {
|
||||
let process = RunningProcess {
|
||||
pid: 42,
|
||||
process_name: "cs2.exe".to_string(),
|
||||
executable_path: "C:/Steam/cs2.exe".to_string(),
|
||||
window_title: None,
|
||||
};
|
||||
|
||||
let detected =
|
||||
detect_game(&[process], &default_profiles()).expect("game should be detected");
|
||||
assert_eq!(detected.game_id, "counter-strike-2");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum HotkeyAction {
|
||||
SaveReplay { length: Duration },
|
||||
ToggleSessionRecording,
|
||||
Screenshot,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct HotkeyBinding {
|
||||
pub accelerator: String,
|
||||
pub action: HotkeyAction,
|
||||
}
|
||||
|
||||
pub fn default_bindings() -> Vec<HotkeyBinding> {
|
||||
vec![
|
||||
HotkeyBinding {
|
||||
accelerator: "F8".to_string(),
|
||||
action: HotkeyAction::SaveReplay {
|
||||
length: Duration::from_secs(60),
|
||||
},
|
||||
},
|
||||
HotkeyBinding {
|
||||
accelerator: "Shift+F8".to_string(),
|
||||
action: HotkeyAction::SaveReplay {
|
||||
length: Duration::from_secs(30),
|
||||
},
|
||||
},
|
||||
HotkeyBinding {
|
||||
accelerator: "Alt+F7".to_string(),
|
||||
action: HotkeyAction::ToggleSessionRecording,
|
||||
},
|
||||
HotkeyBinding {
|
||||
accelerator: "F9".to_string(),
|
||||
action: HotkeyAction::Screenshot,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
pub fn parse_hotkey_action(accelerator: &str, bindings: &[HotkeyBinding]) -> Option<HotkeyAction> {
|
||||
bindings
|
||||
.iter()
|
||||
.find(|binding| binding.accelerator.eq_ignore_ascii_case(accelerator))
|
||||
.map(|binding| binding.action.clone())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_default_save_replay_hotkey() {
|
||||
let action = parse_hotkey_action("f8", &default_bindings());
|
||||
assert_eq!(
|
||||
action,
|
||||
Some(HotkeyAction::SaveReplay {
|
||||
length: Duration::from_secs(60)
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
use crate::models::{GameEvent, GameEventType};
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
pub trait GameIntegration {
|
||||
fn game_id(&self) -> &'static str;
|
||||
fn normalize_event(&self, raw: &RawGameEvent, session_id: &str) -> Option<GameEvent>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct RawGameEvent {
|
||||
pub event_id: String,
|
||||
pub name: String,
|
||||
pub timestamp: SystemTime,
|
||||
pub player: Option<String>,
|
||||
pub metadata: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct LeagueIntegration;
|
||||
|
||||
impl GameIntegration for LeagueIntegration {
|
||||
fn game_id(&self) -> &'static str {
|
||||
"league-of-legends"
|
||||
}
|
||||
|
||||
fn normalize_event(&self, raw: &RawGameEvent, session_id: &str) -> Option<GameEvent> {
|
||||
let event_type = match raw.name.as_str() {
|
||||
"ChampionKill" => GameEventType::Kill,
|
||||
"Multikill" => GameEventType::MultiKill,
|
||||
"FirstBrick" | "TurretKilled" | "DragonKill" | "HeraldKill" | "BaronKill" => {
|
||||
GameEventType::Objective
|
||||
}
|
||||
"GameEnd" => GameEventType::MatchWin,
|
||||
_ => return None,
|
||||
};
|
||||
Some(to_game_event(self.game_id(), raw, session_id, event_type))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ValveGame {
|
||||
CounterStrike2,
|
||||
Dota2,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ValveGsiIntegration {
|
||||
game: ValveGame,
|
||||
}
|
||||
|
||||
impl ValveGsiIntegration {
|
||||
pub fn counter_strike_2() -> Self {
|
||||
Self {
|
||||
game: ValveGame::CounterStrike2,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dota_2() -> Self {
|
||||
Self {
|
||||
game: ValveGame::Dota2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GameIntegration for ValveGsiIntegration {
|
||||
fn game_id(&self) -> &'static str {
|
||||
match self.game {
|
||||
ValveGame::CounterStrike2 => "counter-strike-2",
|
||||
ValveGame::Dota2 => "dota-2",
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_event(&self, raw: &RawGameEvent, session_id: &str) -> Option<GameEvent> {
|
||||
let lower = raw.name.to_lowercase();
|
||||
let event_type = if lower.contains("kill") {
|
||||
GameEventType::Kill
|
||||
} else if lower.contains("death") {
|
||||
GameEventType::Death
|
||||
} else if lower.contains("assist") {
|
||||
GameEventType::Assist
|
||||
} else if lower.contains("round") && lower.contains("win") {
|
||||
GameEventType::RoundWin
|
||||
} else if lower.contains("match") && lower.contains("win") {
|
||||
GameEventType::MatchWin
|
||||
} else if lower.contains("objective") || lower.contains("aegis") || lower.contains("roshan")
|
||||
{
|
||||
GameEventType::Objective
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
|
||||
Some(to_game_event(self.game_id(), raw, session_id, event_type))
|
||||
}
|
||||
}
|
||||
|
||||
fn to_game_event(
|
||||
game_id: &str,
|
||||
raw: &RawGameEvent,
|
||||
session_id: &str,
|
||||
event_type: GameEventType,
|
||||
) -> GameEvent {
|
||||
let mut event = GameEvent::new(
|
||||
format!("{game_id}:{}", raw.event_id),
|
||||
game_id,
|
||||
session_id,
|
||||
event_type,
|
||||
raw.timestamp,
|
||||
);
|
||||
event.player = raw.player.clone();
|
||||
event.metadata = raw.metadata.clone();
|
||||
event
|
||||
}
|
||||
|
||||
pub fn league_event_from_live_client(
|
||||
event_id: u64,
|
||||
event_name: &str,
|
||||
game_time_seconds: f64,
|
||||
session_started_at: SystemTime,
|
||||
) -> RawGameEvent {
|
||||
RawGameEvent {
|
||||
event_id: event_id.to_string(),
|
||||
name: event_name.to_string(),
|
||||
timestamp: session_started_at + Duration::from_millis((game_time_seconds * 1000.0) as u64),
|
||||
player: None,
|
||||
metadata: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn normalizes_league_kill() {
|
||||
let integration = LeagueIntegration;
|
||||
let raw = league_event_from_live_client(8, "ChampionKill", 15.0, SystemTime::UNIX_EPOCH);
|
||||
|
||||
let event = integration
|
||||
.normalize_event(&raw, "session")
|
||||
.expect("event should normalize");
|
||||
|
||||
assert_eq!(event.game_id, "league-of-legends");
|
||||
assert_eq!(event.event_type, GameEventType::Kill);
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
use crate::models::UploadProvider;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum JobStatus {
|
||||
Queued,
|
||||
Running,
|
||||
Completed,
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TrimJob {
|
||||
pub id: String,
|
||||
pub clip_id: String,
|
||||
pub input_path: PathBuf,
|
||||
pub output_path: PathBuf,
|
||||
pub start: Duration,
|
||||
pub end: Duration,
|
||||
pub status: JobStatus,
|
||||
}
|
||||
|
||||
impl TrimJob {
|
||||
pub fn new(
|
||||
id: impl Into<String>,
|
||||
clip_id: impl Into<String>,
|
||||
input_path: impl Into<PathBuf>,
|
||||
output_path: impl Into<PathBuf>,
|
||||
start: Duration,
|
||||
end: Duration,
|
||||
) -> Result<Self, String> {
|
||||
if end <= start {
|
||||
return Err("trim end must be after trim start".to_string());
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
id: id.into(),
|
||||
clip_id: clip_id.into(),
|
||||
input_path: input_path.into(),
|
||||
output_path: output_path.into(),
|
||||
start,
|
||||
end,
|
||||
status: JobStatus::Queued,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UploadJob {
|
||||
pub id: String,
|
||||
pub clip_id: String,
|
||||
pub provider: UploadProvider,
|
||||
pub queued_at: SystemTime,
|
||||
pub attempts: u8,
|
||||
pub status: JobStatus,
|
||||
}
|
||||
|
||||
impl UploadJob {
|
||||
pub fn new(
|
||||
id: impl Into<String>,
|
||||
clip_id: impl Into<String>,
|
||||
provider: UploadProvider,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: id.into(),
|
||||
clip_id: clip_id.into(),
|
||||
provider,
|
||||
queued_at: SystemTime::now(),
|
||||
attempts: 0,
|
||||
status: JobStatus::Queued,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn trim_job_rejects_empty_window() {
|
||||
let result = TrimJob::new(
|
||||
"job",
|
||||
"clip",
|
||||
"in.mp4",
|
||||
"out.mp4",
|
||||
Duration::from_secs(10),
|
||||
Duration::from_secs(10),
|
||||
);
|
||||
|
||||
assert!(result.is_err());
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
pub mod capture;
|
||||
pub mod game_detection;
|
||||
pub mod hotkeys;
|
||||
pub mod integrations;
|
||||
pub mod jobs;
|
||||
pub mod library;
|
||||
pub mod models;
|
||||
pub mod recorder;
|
||||
pub mod settings;
|
||||
pub mod storage;
|
||||
pub mod upload;
|
||||
|
||||
pub use models::{Clip, ClipSource, GameEvent, GameEventType, RecordingStatus, UploadProvider};
|
||||
pub use recorder::{AutoClipPolicy, EventDebouncer, RecorderService, ReplayBuffer};
|
||||
pub use settings::AppSettings;
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
use crate::models::{Clip, ClipSource, GameEventType, UploadProvider};
|
||||
use std::fmt::Write as _;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ClipFilter {
|
||||
pub game_id: Option<String>,
|
||||
pub event_type: Option<GameEventType>,
|
||||
pub upload_provider: Option<UploadProvider>,
|
||||
pub tag: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ClipLibrary {
|
||||
clips: Vec<Clip>,
|
||||
}
|
||||
|
||||
impl ClipLibrary {
|
||||
pub fn new() -> Self {
|
||||
Self { clips: Vec::new() }
|
||||
}
|
||||
|
||||
pub fn add_clip(&mut self, clip: Clip) {
|
||||
if let Some(existing) = self
|
||||
.clips
|
||||
.iter_mut()
|
||||
.find(|existing| existing.id == clip.id)
|
||||
{
|
||||
*existing = clip;
|
||||
} else {
|
||||
self.clips.push(clip);
|
||||
self.clips
|
||||
.sort_by(|left, right| right.created_at.cmp(&left.created_at));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove_clip(&mut self, clip_id: &str) -> Option<Clip> {
|
||||
let index = self.clips.iter().position(|clip| clip.id == clip_id)?;
|
||||
Some(self.clips.remove(index))
|
||||
}
|
||||
|
||||
pub fn update_upload(
|
||||
&mut self,
|
||||
clip_id: &str,
|
||||
provider: UploadProvider,
|
||||
url: impl Into<String>,
|
||||
) -> bool {
|
||||
let Some(clip) = self.clips.iter_mut().find(|clip| clip.id == clip_id) else {
|
||||
return false;
|
||||
};
|
||||
clip.upload_provider = Some(provider);
|
||||
clip.upload_url = Some(url.into());
|
||||
true
|
||||
}
|
||||
|
||||
pub fn all(&self) -> &[Clip] {
|
||||
&self.clips
|
||||
}
|
||||
|
||||
pub fn filter(&self, filter: &ClipFilter) -> Vec<&Clip> {
|
||||
self.clips
|
||||
.iter()
|
||||
.filter(|clip| {
|
||||
filter
|
||||
.game_id
|
||||
.as_ref()
|
||||
.map(|game_id| &clip.game_id == game_id)
|
||||
.unwrap_or(true)
|
||||
&& filter
|
||||
.event_type
|
||||
.as_ref()
|
||||
.map(|event_type| clip.event_type.as_ref() == Some(event_type))
|
||||
.unwrap_or(true)
|
||||
&& filter
|
||||
.upload_provider
|
||||
.as_ref()
|
||||
.map(|provider| clip.upload_provider.as_ref() == Some(provider))
|
||||
.unwrap_or(true)
|
||||
&& filter
|
||||
.tag
|
||||
.as_ref()
|
||||
.map(|tag| clip.tags.iter().any(|clip_tag| clip_tag == tag))
|
||||
.unwrap_or(true)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn save_manifest(&self, path: &Path) -> io::Result<()> {
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::write(path, self.to_manifest())
|
||||
}
|
||||
|
||||
pub fn to_manifest(&self) -> String {
|
||||
let mut manifest = String::from("id\tgame_id\tsession_id\tpath\tduration_ms\tsource\tevent_type\ttags\tupload_provider\tupload_url\n");
|
||||
for clip in &self.clips {
|
||||
let _ = writeln!(
|
||||
manifest,
|
||||
"{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}",
|
||||
escape(&clip.id),
|
||||
escape(&clip.game_id),
|
||||
escape(&clip.session_id),
|
||||
escape(&clip.path.to_string_lossy()),
|
||||
clip.duration.as_millis(),
|
||||
clip_source_name(&clip.source),
|
||||
clip.event_type
|
||||
.as_ref()
|
||||
.map(ToString::to_string)
|
||||
.unwrap_or_default(),
|
||||
escape(&clip.tags.join(",")),
|
||||
clip.upload_provider
|
||||
.as_ref()
|
||||
.map(upload_provider_name)
|
||||
.unwrap_or_default(),
|
||||
escape(clip.upload_url.as_deref().unwrap_or_default())
|
||||
);
|
||||
}
|
||||
manifest
|
||||
}
|
||||
}
|
||||
|
||||
pub fn deterministic_clip_id(prefix: &str, at: SystemTime) -> String {
|
||||
let millis = at
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis();
|
||||
format!("{prefix}-{millis}")
|
||||
}
|
||||
|
||||
fn escape(value: &str) -> String {
|
||||
value.replace('\t', " ").replace('\n', " ")
|
||||
}
|
||||
|
||||
fn clip_source_name(source: &ClipSource) -> &'static str {
|
||||
match source {
|
||||
ClipSource::ManualHotkey => "manual_hotkey",
|
||||
ClipSource::AutoEvent => "auto_event",
|
||||
ClipSource::FullSessionBookmark => "full_session_bookmark",
|
||||
ClipSource::Imported => "imported",
|
||||
}
|
||||
}
|
||||
|
||||
fn upload_provider_name(provider: &UploadProvider) -> &'static str {
|
||||
match provider {
|
||||
UploadProvider::Catbox => "catbox",
|
||||
UploadProvider::Litterbox => "litterbox",
|
||||
UploadProvider::Lustful => "lustful",
|
||||
UploadProvider::CustomHttp => "custom_http",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn total_clip_bytes(clips: &[Clip]) -> u64 {
|
||||
clips
|
||||
.iter()
|
||||
.filter_map(|clip| clip.path.metadata().ok())
|
||||
.map(|metadata| metadata.len())
|
||||
.sum()
|
||||
}
|
||||
|
||||
pub fn trim_duration(start: Duration, end: Duration) -> Option<Duration> {
|
||||
end.checked_sub(start)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::storage::{build_placeholder_clip, LibraryPaths};
|
||||
|
||||
#[test]
|
||||
fn filters_by_game_and_tag() {
|
||||
let paths = LibraryPaths::new("root");
|
||||
let mut library = ClipLibrary::new();
|
||||
let mut clip = build_placeholder_clip(
|
||||
&paths,
|
||||
"clip",
|
||||
"session",
|
||||
"counter-strike-2",
|
||||
Duration::from_secs(18),
|
||||
);
|
||||
clip.tags.push("clutch".to_string());
|
||||
library.add_clip(clip);
|
||||
|
||||
let filter = ClipFilter {
|
||||
game_id: Some("counter-strike-2".to_string()),
|
||||
tag: Some("clutch".to_string()),
|
||||
..ClipFilter::default()
|
||||
};
|
||||
|
||||
assert_eq!(library.filter(&filter).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifest_contains_clip_rows() {
|
||||
let paths = LibraryPaths::new("root");
|
||||
let mut library = ClipLibrary::new();
|
||||
library.add_clip(build_placeholder_clip(
|
||||
&paths,
|
||||
"clip",
|
||||
"session",
|
||||
"dota-2",
|
||||
Duration::from_secs(60),
|
||||
));
|
||||
|
||||
assert!(library.to_manifest().contains("dota-2"));
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
use clipforge::game_detection::{default_profiles, detect_game, RunningProcess};
|
||||
use clipforge::recorder::{BufferSegment, RecorderAction, RecorderService};
|
||||
use clipforge::settings::AppSettings;
|
||||
use clipforge::storage::{write_placeholder_mp4, LibraryPaths};
|
||||
use std::env;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
fn main() {
|
||||
let root = env::current_dir()
|
||||
.unwrap_or_else(|_| PathBuf::from("."))
|
||||
.join("work")
|
||||
.join("clipforge-library");
|
||||
let settings = AppSettings::default_for_root(&root);
|
||||
let paths = LibraryPaths::new(&root);
|
||||
|
||||
if let Err(error) = paths.ensure() {
|
||||
eprintln!("Could not prepare local clip library: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
let sample_processes = vec![RunningProcess {
|
||||
pid: 730,
|
||||
process_name: "cs2.exe".to_string(),
|
||||
executable_path: "C:/Program Files (x86)/Steam/steamapps/common/Counter-Strike Global Offensive/game/bin/win64/cs2.exe".to_string(),
|
||||
window_title: Some("Counter-Strike 2".to_string()),
|
||||
}];
|
||||
let detected = detect_game(&sample_processes, &default_profiles());
|
||||
let mut service = RecorderService::new(settings, paths.clone());
|
||||
let now = SystemTime::now();
|
||||
|
||||
if let Some(game) = detected {
|
||||
println!(
|
||||
"Sample game detection: {} ({})",
|
||||
game.display_name, game.game_id
|
||||
);
|
||||
println!("{:?}", service.start_for_game(game.game_id, now));
|
||||
|
||||
for index in 0..12 {
|
||||
service.add_segment(BufferSegment {
|
||||
id: format!("segment-{index}"),
|
||||
started_at: now + Duration::from_secs(index * 5),
|
||||
duration: Duration::from_secs(5),
|
||||
path_hint: format!("segment_{index}.mp4"),
|
||||
});
|
||||
}
|
||||
|
||||
let clip_action =
|
||||
service.save_manual_clip(Duration::from_secs(60), now + Duration::from_secs(60));
|
||||
if let Some(RecorderAction::CreatedClip { clip_id, .. }) = clip_action {
|
||||
if let Some(clip) = service.library.all().iter().find(|clip| clip.id == clip_id) {
|
||||
if let Err(error) = write_placeholder_mp4(&clip.path, &clip.id) {
|
||||
eprintln!("Could not write placeholder clip: {error}");
|
||||
}
|
||||
}
|
||||
println!("Created manual clip: {clip_id}");
|
||||
}
|
||||
} else {
|
||||
println!("Sample game detection: waiting for game");
|
||||
}
|
||||
|
||||
let manifest_path = root.join("library.tsv");
|
||||
if let Err(error) = service.library.save_manifest(&manifest_path) {
|
||||
eprintln!("Could not save clip manifest: {error}");
|
||||
}
|
||||
|
||||
println!("ClipForge recorder scaffold");
|
||||
println!("Library root: {}", root.display());
|
||||
println!("Manifest: {}", manifest_path.display());
|
||||
println!("Replay segments retained: {}", service.replay_buffer.len());
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum GameEventType {
|
||||
Kill,
|
||||
Death,
|
||||
Assist,
|
||||
RoundWin,
|
||||
MatchWin,
|
||||
Objective,
|
||||
MultiKill,
|
||||
Bookmark,
|
||||
Unknown(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for GameEventType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let value = match self {
|
||||
Self::Kill => "kill",
|
||||
Self::Death => "death",
|
||||
Self::Assist => "assist",
|
||||
Self::RoundWin => "round_win",
|
||||
Self::MatchWin => "match_win",
|
||||
Self::Objective => "objective",
|
||||
Self::MultiKill => "multi_kill",
|
||||
Self::Bookmark => "bookmark",
|
||||
Self::Unknown(value) => value,
|
||||
};
|
||||
f.write_str(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct GameEvent {
|
||||
pub id: String,
|
||||
pub game_id: String,
|
||||
pub session_id: String,
|
||||
pub event_type: GameEventType,
|
||||
pub occurred_at: SystemTime,
|
||||
pub confidence: f32,
|
||||
pub player: Option<String>,
|
||||
pub metadata: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl GameEvent {
|
||||
pub fn new(
|
||||
id: impl Into<String>,
|
||||
game_id: impl Into<String>,
|
||||
session_id: impl Into<String>,
|
||||
event_type: GameEventType,
|
||||
occurred_at: SystemTime,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: id.into(),
|
||||
game_id: game_id.into(),
|
||||
session_id: session_id.into(),
|
||||
event_type,
|
||||
occurred_at,
|
||||
confidence: 1.0,
|
||||
player: None,
|
||||
metadata: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ClipSource {
|
||||
ManualHotkey,
|
||||
AutoEvent,
|
||||
FullSessionBookmark,
|
||||
Imported,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum UploadProvider {
|
||||
Catbox,
|
||||
Litterbox,
|
||||
Lustful,
|
||||
CustomHttp,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Clip {
|
||||
pub id: String,
|
||||
pub session_id: String,
|
||||
pub game_id: String,
|
||||
pub path: PathBuf,
|
||||
pub thumbnail_path: Option<PathBuf>,
|
||||
pub created_at: SystemTime,
|
||||
pub duration: Duration,
|
||||
pub source: ClipSource,
|
||||
pub event_type: Option<GameEventType>,
|
||||
pub tags: Vec<String>,
|
||||
pub upload_url: Option<String>,
|
||||
pub upload_provider: Option<UploadProvider>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RecordingStatus {
|
||||
WaitingForGame,
|
||||
Buffering,
|
||||
RecordingSession,
|
||||
Clipping,
|
||||
Processing,
|
||||
StorageLow,
|
||||
Error(String),
|
||||
}
|
||||
+478
@@ -0,0 +1,478 @@
|
||||
use crate::library::{deterministic_clip_id, ClipLibrary};
|
||||
use crate::models::{Clip, ClipSource, GameEvent, RecordingStatus};
|
||||
use crate::settings::AppSettings;
|
||||
use crate::storage::{clip_path, LibraryPaths};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BufferSegment {
|
||||
pub id: String,
|
||||
pub started_at: SystemTime,
|
||||
pub duration: Duration,
|
||||
pub path_hint: String,
|
||||
}
|
||||
|
||||
impl BufferSegment {
|
||||
fn ends_at(&self) -> SystemTime {
|
||||
self.started_at + self.duration
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ReplayBuffer {
|
||||
capacity: Duration,
|
||||
segments: VecDeque<BufferSegment>,
|
||||
}
|
||||
|
||||
impl ReplayBuffer {
|
||||
pub fn new(capacity: Duration) -> Self {
|
||||
Self {
|
||||
capacity,
|
||||
segments: VecDeque::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push(&mut self, segment: BufferSegment) {
|
||||
self.segments.push_back(segment);
|
||||
self.prune();
|
||||
}
|
||||
|
||||
pub fn segments_for_window(&self, end: SystemTime, length: Duration) -> Vec<BufferSegment> {
|
||||
let start = end.checked_sub(length).unwrap_or(SystemTime::UNIX_EPOCH);
|
||||
self.segments
|
||||
.iter()
|
||||
.filter(|segment| segment.ends_at() >= start && segment.started_at <= end)
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.segments.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.segments.is_empty()
|
||||
}
|
||||
|
||||
fn prune(&mut self) {
|
||||
let Some(newest) = self.segments.back().map(BufferSegment::ends_at) else {
|
||||
return;
|
||||
};
|
||||
let cutoff = newest
|
||||
.checked_sub(self.capacity)
|
||||
.unwrap_or(SystemTime::UNIX_EPOCH);
|
||||
while self
|
||||
.segments
|
||||
.front()
|
||||
.map(|segment| segment.ends_at() < cutoff)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
self.segments.pop_front();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AutoClipPolicy {
|
||||
pub pre_roll: Duration,
|
||||
pub post_roll: Duration,
|
||||
pub merge_window: Duration,
|
||||
}
|
||||
|
||||
impl Default for AutoClipPolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
pre_roll: Duration::from_secs(10),
|
||||
post_roll: Duration::from_secs(8),
|
||||
merge_window: Duration::from_secs(12),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&AppSettings> for AutoClipPolicy {
|
||||
fn from(settings: &AppSettings) -> Self {
|
||||
Self {
|
||||
pre_roll: settings.auto_clip.pre_roll,
|
||||
post_roll: settings.auto_clip.post_roll,
|
||||
merge_window: settings.auto_clip.merge_window,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum AutoClipDecision {
|
||||
CreateClip {
|
||||
event: GameEvent,
|
||||
start: SystemTime,
|
||||
end: SystemTime,
|
||||
},
|
||||
MergeIntoPrevious {
|
||||
event: GameEvent,
|
||||
previous_event_id: String,
|
||||
},
|
||||
Duplicate,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EventDebouncer {
|
||||
policy: AutoClipPolicy,
|
||||
seen_ids: HashMap<String, SystemTime>,
|
||||
last_created_event: Option<GameEvent>,
|
||||
}
|
||||
|
||||
impl EventDebouncer {
|
||||
pub fn new(policy: AutoClipPolicy) -> Self {
|
||||
Self {
|
||||
policy,
|
||||
seen_ids: HashMap::new(),
|
||||
last_created_event: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn decide(&mut self, event: GameEvent) -> AutoClipDecision {
|
||||
if self.seen_ids.contains_key(&event.id) {
|
||||
return AutoClipDecision::Duplicate;
|
||||
}
|
||||
|
||||
self.seen_ids.insert(event.id.clone(), event.occurred_at);
|
||||
|
||||
if let Some(previous) = &self.last_created_event {
|
||||
if same_session(previous, &event)
|
||||
&& within_merge_window(
|
||||
previous.occurred_at,
|
||||
event.occurred_at,
|
||||
self.policy.merge_window,
|
||||
)
|
||||
{
|
||||
return AutoClipDecision::MergeIntoPrevious {
|
||||
event,
|
||||
previous_event_id: previous.id.clone(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let start = event
|
||||
.occurred_at
|
||||
.checked_sub(self.policy.pre_roll)
|
||||
.unwrap_or(SystemTime::UNIX_EPOCH);
|
||||
let end = event.occurred_at + self.policy.post_roll;
|
||||
self.last_created_event = Some(event.clone());
|
||||
|
||||
AutoClipDecision::CreateClip { event, start, end }
|
||||
}
|
||||
}
|
||||
|
||||
fn same_session(left: &GameEvent, right: &GameEvent) -> bool {
|
||||
left.session_id == right.session_id && left.game_id == right.game_id
|
||||
}
|
||||
|
||||
fn within_merge_window(left: SystemTime, right: SystemTime, window: Duration) -> bool {
|
||||
left.duration_since(right)
|
||||
.or_else(|_| right.duration_since(left))
|
||||
.map(|delta| delta <= window)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RecorderState {
|
||||
pub status: RecordingStatus,
|
||||
pub detected_game_id: Option<String>,
|
||||
pub active_session_id: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for RecorderState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
status: RecordingStatus::WaitingForGame,
|
||||
detected_game_id: None,
|
||||
active_session_id: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum RecorderAction {
|
||||
StartedSession {
|
||||
session_id: String,
|
||||
game_id: String,
|
||||
},
|
||||
StoppedSession {
|
||||
session_id: String,
|
||||
},
|
||||
CreatedClip {
|
||||
clip_id: String,
|
||||
segment_count: usize,
|
||||
},
|
||||
CreatedBookmark {
|
||||
event_id: String,
|
||||
},
|
||||
MergedEvent {
|
||||
event_id: String,
|
||||
into_event_id: String,
|
||||
},
|
||||
IgnoredDuplicate {
|
||||
event_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RecorderService {
|
||||
pub settings: AppSettings,
|
||||
pub paths: LibraryPaths,
|
||||
pub state: RecorderState,
|
||||
pub replay_buffer: ReplayBuffer,
|
||||
pub library: ClipLibrary,
|
||||
debouncer: EventDebouncer,
|
||||
session_recording: bool,
|
||||
}
|
||||
|
||||
impl RecorderService {
|
||||
pub fn new(settings: AppSettings, paths: LibraryPaths) -> Self {
|
||||
let policy = AutoClipPolicy::from(&settings);
|
||||
Self {
|
||||
replay_buffer: ReplayBuffer::new(settings.replay_buffer),
|
||||
debouncer: EventDebouncer::new(policy),
|
||||
settings,
|
||||
paths,
|
||||
state: RecorderState::default(),
|
||||
library: ClipLibrary::new(),
|
||||
session_recording: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_for_game(
|
||||
&mut self,
|
||||
game_id: impl Into<String>,
|
||||
now: SystemTime,
|
||||
) -> RecorderAction {
|
||||
let game_id = game_id.into();
|
||||
let session_id = deterministic_clip_id("session", now);
|
||||
self.state.status = RecordingStatus::Buffering;
|
||||
self.state.detected_game_id = Some(game_id.clone());
|
||||
self.state.active_session_id = Some(session_id.clone());
|
||||
RecorderAction::StartedSession {
|
||||
session_id,
|
||||
game_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stop(&mut self) -> Option<RecorderAction> {
|
||||
let session_id = self.state.active_session_id.take()?;
|
||||
self.state.status = RecordingStatus::WaitingForGame;
|
||||
self.state.detected_game_id = None;
|
||||
self.session_recording = false;
|
||||
Some(RecorderAction::StoppedSession { session_id })
|
||||
}
|
||||
|
||||
pub fn toggle_session_recording(&mut self) {
|
||||
self.session_recording = !self.session_recording;
|
||||
self.state.status = if self.session_recording {
|
||||
RecordingStatus::RecordingSession
|
||||
} else {
|
||||
RecordingStatus::Buffering
|
||||
};
|
||||
}
|
||||
|
||||
pub fn add_segment(&mut self, segment: BufferSegment) {
|
||||
self.replay_buffer.push(segment);
|
||||
}
|
||||
|
||||
pub fn save_manual_clip(
|
||||
&mut self,
|
||||
length: Duration,
|
||||
now: SystemTime,
|
||||
) -> Option<RecorderAction> {
|
||||
let game_id = self.state.detected_game_id.clone()?;
|
||||
let session_id = self.state.active_session_id.clone()?;
|
||||
let segments = self.replay_buffer.segments_for_window(now, length);
|
||||
let clip_id = deterministic_clip_id("manual", now);
|
||||
let clip = self.build_clip(
|
||||
&clip_id,
|
||||
&session_id,
|
||||
&game_id,
|
||||
length,
|
||||
ClipSource::ManualHotkey,
|
||||
None,
|
||||
now,
|
||||
);
|
||||
self.library.add_clip(clip);
|
||||
self.state.status = RecordingStatus::Processing;
|
||||
Some(RecorderAction::CreatedClip {
|
||||
clip_id,
|
||||
segment_count: segments.len(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn handle_game_event(&mut self, event: GameEvent) -> RecorderAction {
|
||||
if self.session_recording {
|
||||
return RecorderAction::CreatedBookmark { event_id: event.id };
|
||||
}
|
||||
|
||||
match self.debouncer.decide(event) {
|
||||
AutoClipDecision::CreateClip { event, start, end } => {
|
||||
let duration = end.duration_since(start).unwrap_or_default();
|
||||
let segments = self.replay_buffer.segments_for_window(end, duration);
|
||||
let clip_id = deterministic_clip_id("auto", event.occurred_at);
|
||||
let clip = self.build_clip(
|
||||
&clip_id,
|
||||
&event.session_id,
|
||||
&event.game_id,
|
||||
duration,
|
||||
ClipSource::AutoEvent,
|
||||
Some(event.event_type),
|
||||
event.occurred_at,
|
||||
);
|
||||
self.library.add_clip(clip);
|
||||
RecorderAction::CreatedClip {
|
||||
clip_id,
|
||||
segment_count: segments.len(),
|
||||
}
|
||||
}
|
||||
AutoClipDecision::MergeIntoPrevious {
|
||||
event,
|
||||
previous_event_id,
|
||||
} => RecorderAction::MergedEvent {
|
||||
event_id: event.id,
|
||||
into_event_id: previous_event_id,
|
||||
},
|
||||
AutoClipDecision::Duplicate => RecorderAction::IgnoredDuplicate {
|
||||
event_id: "duplicate".to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn build_clip(
|
||||
&self,
|
||||
clip_id: &str,
|
||||
session_id: &str,
|
||||
game_id: &str,
|
||||
duration: Duration,
|
||||
source: ClipSource,
|
||||
event_type: Option<crate::models::GameEventType>,
|
||||
created_at: SystemTime,
|
||||
) -> Clip {
|
||||
Clip {
|
||||
id: clip_id.to_string(),
|
||||
session_id: session_id.to_string(),
|
||||
game_id: game_id.to_string(),
|
||||
path: clip_path(&self.paths, game_id, created_at, clip_id),
|
||||
thumbnail_path: Some(self.paths.thumbs_root.join(format!("{clip_id}.jpg"))),
|
||||
created_at,
|
||||
duration,
|
||||
source,
|
||||
event_type,
|
||||
tags: Vec::new(),
|
||||
upload_url: None,
|
||||
upload_provider: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::models::{GameEvent, GameEventType};
|
||||
|
||||
#[test]
|
||||
fn replay_buffer_prunes_old_segments() {
|
||||
let base = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000);
|
||||
let mut buffer = ReplayBuffer::new(Duration::from_secs(10));
|
||||
|
||||
for index in 0..5 {
|
||||
buffer.push(BufferSegment {
|
||||
id: format!("seg-{index}"),
|
||||
started_at: base + Duration::from_secs(index * 5),
|
||||
duration: Duration::from_secs(5),
|
||||
path_hint: format!("segment_{index}.mp4"),
|
||||
});
|
||||
}
|
||||
|
||||
assert_eq!(buffer.len(), 3);
|
||||
let ids: Vec<_> = buffer
|
||||
.segments_for_window(base + Duration::from_secs(24), Duration::from_secs(10))
|
||||
.into_iter()
|
||||
.map(|segment| segment.id)
|
||||
.collect();
|
||||
assert_eq!(ids, vec!["seg-2", "seg-3", "seg-4"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debouncer_creates_merges_and_rejects_duplicates() {
|
||||
let base = SystemTime::UNIX_EPOCH + Duration::from_secs(2_000);
|
||||
let policy = AutoClipPolicy::default();
|
||||
let mut debouncer = EventDebouncer::new(policy);
|
||||
let first = GameEvent::new("1", "league", "session", GameEventType::Kill, base);
|
||||
let second = GameEvent::new(
|
||||
"2",
|
||||
"league",
|
||||
"session",
|
||||
GameEventType::Assist,
|
||||
base + Duration::from_secs(5),
|
||||
);
|
||||
|
||||
assert!(matches!(
|
||||
debouncer.decide(first.clone()),
|
||||
AutoClipDecision::CreateClip { .. }
|
||||
));
|
||||
assert!(matches!(
|
||||
debouncer.decide(second),
|
||||
AutoClipDecision::MergeIntoPrevious { previous_event_id, .. } if previous_event_id == "1"
|
||||
));
|
||||
assert_eq!(debouncer.decide(first), AutoClipDecision::Duplicate);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recorder_service_creates_manual_clip() {
|
||||
let root = LibraryPaths::new("root");
|
||||
let settings = AppSettings::default_for_root("root");
|
||||
let mut service = RecorderService::new(settings, root);
|
||||
let base = SystemTime::UNIX_EPOCH + Duration::from_secs(10_000);
|
||||
service.start_for_game("counter-strike-2", base);
|
||||
service.add_segment(BufferSegment {
|
||||
id: "segment".to_string(),
|
||||
started_at: base,
|
||||
duration: Duration::from_secs(5),
|
||||
path_hint: "segment.mp4".to_string(),
|
||||
});
|
||||
|
||||
let action = service
|
||||
.save_manual_clip(Duration::from_secs(60), base + Duration::from_secs(5))
|
||||
.expect("manual clip should be created");
|
||||
|
||||
assert!(matches!(
|
||||
action,
|
||||
RecorderAction::CreatedClip {
|
||||
segment_count: 1,
|
||||
..
|
||||
}
|
||||
));
|
||||
assert_eq!(service.library.all().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recorder_service_creates_bookmark_during_full_session() {
|
||||
let root = LibraryPaths::new("root");
|
||||
let settings = AppSettings::default_for_root("root");
|
||||
let mut service = RecorderService::new(settings, root);
|
||||
let base = SystemTime::UNIX_EPOCH + Duration::from_secs(10_000);
|
||||
service.start_for_game("league-of-legends", base);
|
||||
service.toggle_session_recording();
|
||||
let event = GameEvent::new(
|
||||
"event",
|
||||
"league-of-legends",
|
||||
"session",
|
||||
GameEventType::Kill,
|
||||
base,
|
||||
);
|
||||
|
||||
let action = service.handle_game_event(event);
|
||||
|
||||
assert_eq!(
|
||||
action,
|
||||
RecorderAction::CreatedBookmark {
|
||||
event_id: "event".to_string()
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct QualityPreset {
|
||||
pub name: String,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub fps: u32,
|
||||
pub bitrate_kbps: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct HotkeySettings {
|
||||
pub clip_last_60s: String,
|
||||
pub clip_last_30s: String,
|
||||
pub toggle_session_recording: String,
|
||||
pub screenshot: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PrivacySettings {
|
||||
pub mic_enabled: bool,
|
||||
pub desktop_capture_requires_confirmation: bool,
|
||||
pub excluded_window_titles: Vec<String>,
|
||||
pub upload_requires_confirmation: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AutoClipSettings {
|
||||
pub enabled: bool,
|
||||
pub pre_roll: Duration,
|
||||
pub post_roll: Duration,
|
||||
pub merge_window: Duration,
|
||||
pub enabled_events_by_game: BTreeMap<String, BTreeSet<String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AppSettings {
|
||||
pub schema_version: u32,
|
||||
pub clip_root: PathBuf,
|
||||
pub buffer_root: PathBuf,
|
||||
pub storage_limit_gb: u64,
|
||||
pub replay_buffer: Duration,
|
||||
pub quality: QualityPreset,
|
||||
pub hotkeys: HotkeySettings,
|
||||
pub privacy: PrivacySettings,
|
||||
pub auto_clip: AutoClipSettings,
|
||||
}
|
||||
|
||||
impl AppSettings {
|
||||
pub fn default_for_root(root: impl Into<PathBuf>) -> Self {
|
||||
let root = root.into();
|
||||
let clip_root = root.join("clips");
|
||||
let buffer_root = root.join("buffer");
|
||||
|
||||
Self {
|
||||
schema_version: 1,
|
||||
clip_root,
|
||||
buffer_root,
|
||||
storage_limit_gb: 50,
|
||||
replay_buffer: Duration::from_secs(60),
|
||||
quality: QualityPreset {
|
||||
name: "Performance 720p30".to_string(),
|
||||
width: 1280,
|
||||
height: 720,
|
||||
fps: 30,
|
||||
bitrate_kbps: 6_000,
|
||||
},
|
||||
hotkeys: HotkeySettings {
|
||||
clip_last_60s: "F8".to_string(),
|
||||
clip_last_30s: "Shift+F8".to_string(),
|
||||
toggle_session_recording: "Alt+F7".to_string(),
|
||||
screenshot: "F9".to_string(),
|
||||
},
|
||||
privacy: PrivacySettings {
|
||||
mic_enabled: false,
|
||||
desktop_capture_requires_confirmation: true,
|
||||
excluded_window_titles: Vec::new(),
|
||||
upload_requires_confirmation: true,
|
||||
},
|
||||
auto_clip: AutoClipSettings {
|
||||
enabled: true,
|
||||
pre_roll: Duration::from_secs(10),
|
||||
post_roll: Duration::from_secs(8),
|
||||
merge_window: Duration::from_secs(12),
|
||||
enabled_events_by_game: BTreeMap::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clamp_replay_buffer(&mut self) {
|
||||
self.replay_buffer = self
|
||||
.replay_buffer
|
||||
.clamp(Duration::from_secs(15), Duration::from_secs(600));
|
||||
}
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
use crate::models::{Clip, ClipSource};
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct LibraryPaths {
|
||||
pub clip_root: PathBuf,
|
||||
pub thumbs_root: PathBuf,
|
||||
pub sessions_root: PathBuf,
|
||||
pub buffer_root: PathBuf,
|
||||
}
|
||||
|
||||
impl LibraryPaths {
|
||||
pub fn new(root: impl Into<PathBuf>) -> Self {
|
||||
let root = root.into();
|
||||
Self {
|
||||
clip_root: root.join("clips"),
|
||||
thumbs_root: root.join("thumbs"),
|
||||
sessions_root: root.join("sessions"),
|
||||
buffer_root: root.join("buffer"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ensure(&self) -> io::Result<()> {
|
||||
fs::create_dir_all(&self.clip_root)?;
|
||||
fs::create_dir_all(&self.thumbs_root)?;
|
||||
fs::create_dir_all(&self.sessions_root)?;
|
||||
fs::create_dir_all(&self.buffer_root)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clip_path(
|
||||
paths: &LibraryPaths,
|
||||
game_id: &str,
|
||||
created_at: SystemTime,
|
||||
clip_id: &str,
|
||||
) -> PathBuf {
|
||||
let month_bucket = month_bucket(created_at);
|
||||
paths
|
||||
.clip_root
|
||||
.join(sanitize_path_component(game_id))
|
||||
.join(month_bucket)
|
||||
.join(format!("{}.mp4", sanitize_path_component(clip_id)))
|
||||
}
|
||||
|
||||
pub fn build_placeholder_clip(
|
||||
paths: &LibraryPaths,
|
||||
clip_id: &str,
|
||||
session_id: &str,
|
||||
game_id: &str,
|
||||
duration: Duration,
|
||||
) -> Clip {
|
||||
let created_at = SystemTime::now();
|
||||
Clip {
|
||||
id: clip_id.to_string(),
|
||||
session_id: session_id.to_string(),
|
||||
game_id: game_id.to_string(),
|
||||
path: clip_path(paths, game_id, created_at, clip_id),
|
||||
thumbnail_path: Some(paths.thumbs_root.join(format!("{clip_id}.jpg"))),
|
||||
created_at,
|
||||
duration,
|
||||
source: ClipSource::ManualHotkey,
|
||||
event_type: None,
|
||||
tags: Vec::new(),
|
||||
upload_url: None,
|
||||
upload_provider: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sanitize_path_component(value: &str) -> String {
|
||||
value
|
||||
.chars()
|
||||
.map(|ch| {
|
||||
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
|
||||
ch
|
||||
} else {
|
||||
'-'
|
||||
}
|
||||
})
|
||||
.collect::<String>()
|
||||
.trim_matches('-')
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn month_bucket(created_at: SystemTime) -> String {
|
||||
let days = created_at
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs()
|
||||
/ 86_400;
|
||||
let approx_year = 1970 + days / 365;
|
||||
let approx_month = ((days % 365) / 31) + 1;
|
||||
format!("{approx_year:04}-{approx_month:02}")
|
||||
}
|
||||
|
||||
pub fn is_inside_root(root: &Path, candidate: &Path) -> bool {
|
||||
let Ok(root) = root.canonicalize() else {
|
||||
return false;
|
||||
};
|
||||
let Ok(candidate) = candidate.canonicalize() else {
|
||||
return false;
|
||||
};
|
||||
candidate.starts_with(root)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct StorageCleanupReport {
|
||||
pub deleted_files: usize,
|
||||
pub deleted_bytes: u64,
|
||||
pub remaining_bytes: u64,
|
||||
}
|
||||
|
||||
pub fn cleanup_oldest_files_until_under_limit(
|
||||
root: &Path,
|
||||
max_bytes: u64,
|
||||
) -> io::Result<StorageCleanupReport> {
|
||||
let mut files = collect_files(root)?;
|
||||
let mut total_bytes: u64 = files.iter().map(|file| file.bytes).sum();
|
||||
let mut deleted_files = 0;
|
||||
let mut deleted_bytes = 0;
|
||||
|
||||
files.sort_by_key(|file| file.modified_at);
|
||||
|
||||
for file in files {
|
||||
if total_bytes <= max_bytes {
|
||||
break;
|
||||
}
|
||||
fs::remove_file(&file.path)?;
|
||||
total_bytes = total_bytes.saturating_sub(file.bytes);
|
||||
deleted_files += 1;
|
||||
deleted_bytes += file.bytes;
|
||||
}
|
||||
|
||||
Ok(StorageCleanupReport {
|
||||
deleted_files,
|
||||
deleted_bytes,
|
||||
remaining_bytes: total_bytes,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct FileFact {
|
||||
path: PathBuf,
|
||||
bytes: u64,
|
||||
modified_at: SystemTime,
|
||||
}
|
||||
|
||||
fn collect_files(root: &Path) -> io::Result<Vec<FileFact>> {
|
||||
let mut files = Vec::new();
|
||||
if !root.exists() {
|
||||
return Ok(files);
|
||||
}
|
||||
|
||||
for entry in fs::read_dir(root)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
files.extend(collect_files(&path)?);
|
||||
} else {
|
||||
let metadata = entry.metadata()?;
|
||||
files.push(FileFact {
|
||||
path,
|
||||
bytes: metadata.len(),
|
||||
modified_at: metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
pub fn write_placeholder_mp4(path: &Path, label: &str) -> io::Result<()> {
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::write(path, format!("ClipForge placeholder video: {label}\n"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::env;
|
||||
use std::fs;
|
||||
|
||||
#[test]
|
||||
fn sanitizes_path_components() {
|
||||
assert_eq!(
|
||||
sanitize_path_component("Counter Strike 2!"),
|
||||
"Counter-Strike-2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_removes_old_files_until_under_limit() {
|
||||
let root = env::temp_dir().join(format!(
|
||||
"clipforge-cleanup-{}",
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos()
|
||||
));
|
||||
fs::create_dir_all(&root).expect("test root");
|
||||
fs::write(root.join("one.tmp"), vec![1_u8; 10]).expect("file one");
|
||||
fs::write(root.join("two.tmp"), vec![1_u8; 10]).expect("file two");
|
||||
|
||||
let report = cleanup_oldest_files_until_under_limit(&root, 10).expect("cleanup");
|
||||
|
||||
assert_eq!(report.deleted_files, 1);
|
||||
assert_eq!(report.remaining_bytes, 10);
|
||||
let _ = fs::remove_dir_all(root);
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
use crate::models::UploadProvider;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UploadMetadata {
|
||||
pub clip_id: String,
|
||||
pub game_id: String,
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UploadResult {
|
||||
pub provider: UploadProvider,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AuthField {
|
||||
pub name: String,
|
||||
pub required: bool,
|
||||
pub secret: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UploaderInfo {
|
||||
pub name: String,
|
||||
pub provider: UploadProvider,
|
||||
pub max_file_size_mb: Option<u64>,
|
||||
pub auth_schema: Vec<AuthField>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum UploadError {
|
||||
NotConfigured(String),
|
||||
FileTooLarge { max_mb: u64 },
|
||||
Network(String),
|
||||
Provider(String),
|
||||
}
|
||||
|
||||
pub trait Uploader {
|
||||
fn info(&self) -> UploaderInfo;
|
||||
fn upload(&self, file: &Path, metadata: &UploadMetadata) -> Result<UploadResult, UploadError>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CatboxUploader {
|
||||
pub userhash: Option<String>,
|
||||
}
|
||||
|
||||
impl Uploader for CatboxUploader {
|
||||
fn info(&self) -> UploaderInfo {
|
||||
UploaderInfo {
|
||||
name: "Catbox".to_string(),
|
||||
provider: UploadProvider::Catbox,
|
||||
max_file_size_mb: Some(200),
|
||||
auth_schema: vec![AuthField {
|
||||
name: "userhash".to_string(),
|
||||
required: false,
|
||||
secret: true,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn upload(&self, file: &Path, _metadata: &UploadMetadata) -> Result<UploadResult, UploadError> {
|
||||
ensure_file_limit(file, 200)?;
|
||||
Err(UploadError::Network(
|
||||
"Catbox upload is wired at the adapter boundary; enable HTTP client dependency for live uploads."
|
||||
.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LitterboxUploader {
|
||||
pub expiry_hours: u8,
|
||||
}
|
||||
|
||||
impl Default for LitterboxUploader {
|
||||
fn default() -> Self {
|
||||
Self { expiry_hours: 24 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Uploader for LitterboxUploader {
|
||||
fn info(&self) -> UploaderInfo {
|
||||
UploaderInfo {
|
||||
name: "Litterbox".to_string(),
|
||||
provider: UploadProvider::Litterbox,
|
||||
max_file_size_mb: Some(1_000),
|
||||
auth_schema: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn upload(&self, file: &Path, _metadata: &UploadMetadata) -> Result<UploadResult, UploadError> {
|
||||
ensure_file_limit(file, 1_000)?;
|
||||
if !matches!(self.expiry_hours, 1 | 12 | 24 | 72) {
|
||||
return Err(UploadError::Provider(
|
||||
"Litterbox expiry must be one of 1, 12, 24, or 72 hours.".to_string(),
|
||||
));
|
||||
}
|
||||
Err(UploadError::Network(
|
||||
"Litterbox upload is wired at the adapter boundary; enable HTTP client dependency for live uploads."
|
||||
.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CustomHttpUploader {
|
||||
pub endpoint: String,
|
||||
pub method: String,
|
||||
pub multipart_field: String,
|
||||
pub response_url_path: String,
|
||||
}
|
||||
|
||||
impl Uploader for CustomHttpUploader {
|
||||
fn info(&self) -> UploaderInfo {
|
||||
UploaderInfo {
|
||||
name: "Custom HTTP".to_string(),
|
||||
provider: UploadProvider::CustomHttp,
|
||||
max_file_size_mb: None,
|
||||
auth_schema: vec![AuthField {
|
||||
name: "headers".to_string(),
|
||||
required: false,
|
||||
secret: true,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn upload(
|
||||
&self,
|
||||
_file: &Path,
|
||||
_metadata: &UploadMetadata,
|
||||
) -> Result<UploadResult, UploadError> {
|
||||
if self.endpoint.trim().is_empty() {
|
||||
return Err(UploadError::NotConfigured(
|
||||
"custom upload endpoint is required".to_string(),
|
||||
));
|
||||
}
|
||||
Err(UploadError::Network(
|
||||
"Custom upload is configured; enable HTTP client dependency for live uploads."
|
||||
.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct LustfulUploader;
|
||||
|
||||
impl Uploader for LustfulUploader {
|
||||
fn info(&self) -> UploaderInfo {
|
||||
UploaderInfo {
|
||||
name: "Lustful".to_string(),
|
||||
provider: UploadProvider::Lustful,
|
||||
max_file_size_mb: None,
|
||||
auth_schema: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn upload(
|
||||
&self,
|
||||
_file: &Path,
|
||||
_metadata: &UploadMetadata,
|
||||
) -> Result<UploadResult, UploadError> {
|
||||
Err(UploadError::NotConfigured(
|
||||
"Lustful API details must be confirmed before live uploads are enabled.".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_file_limit(file: &Path, max_mb: u64) -> Result<(), UploadError> {
|
||||
let Ok(metadata) = file.metadata() else {
|
||||
return Ok(());
|
||||
};
|
||||
if metadata.len() > max_mb * 1024 * 1024 {
|
||||
return Err(UploadError::FileTooLarge { max_mb });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn litterbox_rejects_invalid_expiry() {
|
||||
let uploader = LitterboxUploader { expiry_hours: 8 };
|
||||
let result = uploader.upload(
|
||||
Path::new("missing.mp4"),
|
||||
&UploadMetadata {
|
||||
clip_id: "clip".to_string(),
|
||||
game_id: "game".to_string(),
|
||||
title: "Clip".to_string(),
|
||||
},
|
||||
);
|
||||
|
||||
assert!(matches!(result, Err(UploadError::Provider(_))));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user