Wire upload and library controls

This commit is contained in:
Alvin-Zilverstand committed 2026-09-11 09:11:07 +02:00
1 parent b9ecd8b133
commit fb4f19cea8
10 files changed
+922 -94

No files matched your search

+16 -4
View File
@@ -16,7 +16,8 @@
- Stop Capture asks FFmpeg to finalize gracefully, falls back after a short timeout, concatenates recorded segments, and adds the completed full-session MP4 to the local library.
- Manual clips now extract from the rolling segment buffer instead of writing placeholder MP4 files.
- Auto clips now use the same segment extraction/thumbnail pipeline as manual clips.
- Clip detail actions are wired to the backend for Trim, Reveal, Upload, and Delete.
- Clip detail actions are wired to the backend for Trim, Reveal, Upload, Delete, metadata updates, and export copy.
- Clip records now support editable titles and tags, and the SQLite schema migrates older libraries to include clip titles.
- Trim uses FFmpeg copy trimming to create a new local library clip when the source file exists.
- Clip thumbnails are generated with FFmpeg and rendered in the library when available.
- Clip detail preview renders the local MP4 through Tauri's asset URL conversion when available.
@@ -29,20 +30,31 @@
- A localhost Valve GSI receiver on `127.0.0.1:49321` accepts CS2/Dota-style event posts and queues normalized event clips.
- A backend worker loop now refreshes game detection and drains auto-clip integrations while the desktop app is running, independent of the currently selected UI view.
- Local clip library can add, filter, remove, update upload state, write a tab-separated manifest, and persist clip metadata in SQLite.
- Versioned local settings are saved to `settings.json`; replay buffer length and mic toggle are wired from the UI to Rust.
- Versioned local settings are saved to `settings.json`; replay buffer length, audio toggles, mic device, auto-record, upload settings, and auto-clip event toggles are wired from the UI to Rust.
- Storage layer creates the planned folders, sanitizes clip paths, provides test clip builders for unit coverage, and cleans oldest temporary files under a size limit.
- Upload adapters perform live HTTP uploads for Catbox, Litterbox, and custom multipart endpoints; Lustful remains blocked behind unknown API details.
- The UI Upload button currently performs an explicit Catbox upload for the selected clip and saves the returned URL.
- The UI Upload button uses the selected upload provider and saved provider configuration, including Catbox userhash, Litterbox expiry, custom endpoint, response path, and custom headers.
- Auto-upload is persisted and, when enabled, attempts upload after manual and event clips while preserving local clips on failure.
- Upload attempts are recorded in SQLite upload history.
- Vite TypeScript UI builds and has interactive Library, Recording, Auto Clip, Uploads, and Settings views.
- Library search, event/upload filters, and grid/list switching are functional in the UI.
- User-visible notices are shown for major actions and failures instead of relying only on console output.
## Not Fully Working Yet
- Native Windows Graphics Capture is wired for rolling replay capture with native audio; resolution downscaling still needs more work.
- Native WASAPI audio is mixed into a single AAC track for MVP clips; separate audio tracks and per-process audio capture are still future work.
- Capture has not yet been manually QA-tested on real NVIDIA/AMD/Intel gaming systems.
- Upload provider configuration UI is not complete; Catbox is live from the default Upload action, but Litterbox/custom HTTP need UI selection and configuration.
- Upload retry controls and a visible upload-history screen are not complete yet.
- Valve GSI receiver is a lightweight MVP receiver; config templates can be generated from the Auto Clip screen, but richer event mapping per game is still needed.
- Auto start/stop is conservative but live: when auto-record is enabled, supported detected games can start recording and stop when the game disappears.
- Trim still uses timestamp text inputs instead of draggable timeline handles.
- Hotkeys are still hardcoded; editable hotkey registration is future work.
- Screenshot capture is still not implemented.
- Capture source, quality, storage cap, excluded windows, and per-game override UI are still incomplete.
- Storage critical-low-disk guardrails are not fully wired into recording start/stop behavior.
- Recorder service still runs inside the Tauri process instead of a separate background service process.
- Installer onboarding, auto-update, and crash logging are still not implemented.
## Next Engineering Steps
+369 -36
View File
@@ -23,10 +23,10 @@ use clipforge::native_audio::{
};
use clipforge::native_wgc::NativeWgcReplayCaptureBackend;
use clipforge::recorder::{RecorderAction, RecorderService};
use clipforge::settings::{load_or_create_settings, save_settings};
use clipforge::settings::{load_or_create_settings, save_settings, AppSettings};
use clipforge::storage::{clip_path, is_inside_root, LibraryPaths};
use clipforge::upload::{
CatboxUploader, CustomHttpUploader, LitterboxUploader, UploadMetadata, Uploader,
CatboxUploader, CustomHttpUploader, LitterboxUploader, UploadMetadata, UploadResult, Uploader,
};
use serde::Serialize;
use std::env;
@@ -88,6 +88,12 @@ struct DesktopStatus {
mic_device: Option<String>,
auto_record_enabled: bool,
upload_enabled: bool,
upload_provider: String,
catbox_userhash: Option<String>,
litterbox_expiry_hours: u8,
custom_upload_endpoint: Option<String>,
custom_upload_response_url_path: String,
custom_upload_headers: Vec<String>,
session_recording: bool,
capture_active: bool,
capture_backend: Option<String>,
@@ -98,6 +104,7 @@ struct DesktopStatus {
ffmpeg_path: Option<String>,
system_audio_available: bool,
desktop_duplication_available: bool,
auto_clip_enabled_events: Vec<AutoClipEventDto>,
}
#[derive(Debug, Serialize)]
@@ -128,6 +135,13 @@ struct AudioDeviceDto {
kind: String,
}
#[derive(Debug, Serialize)]
struct AutoClipEventDto {
game_id: String,
event_type: String,
enabled: bool,
}
#[tauri::command]
fn get_status(runtime: State<'_, AppRuntime>) -> Result<DesktopStatus, String> {
let recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
@@ -282,6 +296,64 @@ fn set_auto_record_enabled(
Ok(status_from_recorder(&recorder, capture.as_ref()))
}
#[tauri::command]
fn set_upload_settings(
auto_upload_enabled: bool,
provider: String,
catbox_userhash: Option<String>,
litterbox_expiry_hours: u8,
custom_endpoint: Option<String>,
custom_response_url_path: String,
custom_headers: Vec<String>,
runtime: State<'_, AppRuntime>,
) -> Result<DesktopStatus, String> {
let mut recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
let capture = runtime.capture.lock().map_err(|error| error.to_string())?;
recorder.settings.upload.auto_upload_enabled = auto_upload_enabled;
recorder.settings.upload.provider = clean_provider(&provider);
recorder.settings.upload.catbox_userhash = clean_optional(catbox_userhash);
recorder.settings.upload.litterbox_expiry_hours = match litterbox_expiry_hours {
1 | 12 | 24 | 72 => litterbox_expiry_hours,
_ => 24,
};
recorder.settings.upload.custom_endpoint = clean_optional(custom_endpoint);
recorder.settings.upload.custom_response_url_path = if custom_response_url_path.trim().is_empty() {
"url".to_string()
} else {
custom_response_url_path.trim().to_string()
};
recorder.settings.upload.custom_headers = parse_header_lines(&custom_headers.join("\n"));
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save upload settings: {error}"))?;
Ok(status_from_recorder(&recorder, capture.as_ref()))
}
#[tauri::command]
fn set_auto_clip_event_enabled(
game_id: String,
event_type: String,
enabled: bool,
runtime: State<'_, AppRuntime>,
) -> Result<DesktopStatus, 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 defaults = default_auto_clip_events_for_game(&game_id);
let events = recorder
.settings
.auto_clip
.enabled_events_by_game
.entry(game_id)
.or_insert_with(|| defaults.iter().map(|event| (*event).to_string()).collect());
if enabled {
events.insert(event_type);
} else {
events.remove(&event_type);
}
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save auto-clip setting: {error}"))?;
Ok(status_from_recorder(&recorder, capture.as_ref()))
}
#[tauri::command]
fn write_gsi_configs(runtime: State<'_, AppRuntime>) -> Result<Vec<GsiConfigDto>, String> {
write_gsi_config_templates(&runtime.library_root)
@@ -422,6 +494,9 @@ fn save_manual_clip_inner(seconds: u64, runtime: &AppRuntime) -> Result<ClipDto,
recorder.settings.replay_buffer,
active.segment_duration,
);
let mut clip = clip;
maybe_auto_upload_clip(runtime, &mut recorder, &mut clip);
recorder.library.add_clip(clip.clone());
persist_clip(runtime, &clip)?;
save_manifest(&recorder)?;
Ok(clip_to_dto(&clip))
@@ -450,6 +525,10 @@ fn handle_auto_event_inner(
return Ok(None);
}
if !auto_clip_event_enabled(&recorder.settings, &event.game_id, &event.event_type.to_string()) {
return Ok(None);
}
let action = recorder.handle_game_event(event);
let RecorderAction::CreatedClip { clip_id, .. } = action else {
return Ok(None);
@@ -473,6 +552,9 @@ fn handle_auto_event_inner(
if let Some(thumbnail_path) = &clip.thumbnail_path {
let _ = generate_thumbnail(&ffmpeg, &clip.path, thumbnail_path);
}
let mut clip = clip;
maybe_auto_upload_clip(runtime, &mut recorder, &mut clip);
recorder.library.add_clip(clip.clone());
persist_clip(runtime, &clip)?;
save_manifest(&recorder)?;
Ok(Some(clip_to_dto(&clip)))
@@ -706,6 +788,10 @@ fn trim_clip(
let clip = Clip {
id: trimmed_id,
title: source_clip
.title
.as_ref()
.map(|title| format!("{title} (trimmed)")),
session_id: source_clip.session_id.clone(),
game_id: source_clip.game_id.clone(),
path: output_path,
@@ -755,27 +841,32 @@ fn upload_clip(
if !clip.path.exists() {
return Err(format!("Clip file does not exist: {}", clip.path.display()));
}
let metadata = UploadMetadata {
clip_id: clip.id.clone(),
game_id: clip.game_id.clone(),
title: clip.id.clone(),
let provider_name = provider.unwrap_or_else(|| recorder.settings.upload.provider.clone());
let history_provider = clean_provider(&provider_name);
let result = upload_clip_with_settings(
&clip,
&recorder.settings,
Some(provider_name),
custom_endpoint,
custom_response_url_path,
);
let result = match result {
Ok(result) => {
record_upload_history(runtime.inner(), &clip.id, &result.provider.to_string(), "uploaded", Some(&result.url), None);
result
}
Err(error) => {
record_upload_history(
runtime.inner(),
&clip.id,
&history_provider,
"failed",
None,
Some(&error),
);
return Err(error);
}
};
let result = match provider.as_deref().unwrap_or("catbox") {
"catbox" => CatboxUploader::default().upload(&clip.path, &metadata),
"litterbox" => LitterboxUploader::default().upload(&clip.path, &metadata),
"custom_http" => CustomHttpUploader {
endpoint: custom_endpoint.unwrap_or_default(),
method: "POST".to_string(),
multipart_field: "file".to_string(),
response_url_path: custom_response_url_path.unwrap_or_else(|| "url".to_string()),
headers: Vec::new(),
}
.upload(&clip.path, &metadata),
unknown => {
return Err(format!("Unsupported upload provider: {unknown}"));
}
}
.map_err(|error| error.to_string())?;
if !recorder
.library
.update_upload(&clip_id, result.provider, result.url)
@@ -794,6 +885,223 @@ fn upload_clip(
Ok(clip_to_dto(&clip))
}
#[tauri::command]
fn update_clip_metadata(
clip_id: String,
title: Option<String>,
tags: Vec<String>,
runtime: State<'_, AppRuntime>,
) -> Result<ClipDto, String> {
let mut recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
let clip = recorder
.library
.all_mut()
.iter_mut()
.find(|clip| clip.id == clip_id)
.ok_or_else(|| format!("Clip {clip_id} was not found."))?;
clip.title = clean_optional(title);
clip.tags = tags
.into_iter()
.map(|tag| tag.trim().to_string())
.filter(|tag| !tag.is_empty())
.collect();
let clip = clip.clone();
persist_clip(runtime.inner(), &clip)?;
save_manifest(&recorder)?;
Ok(clip_to_dto(&clip))
}
#[tauri::command]
fn export_clip_copy(clip_id: String, runtime: State<'_, AppRuntime>) -> Result<String, String> {
let recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
let clip = recorder
.library
.all()
.iter()
.find(|clip| clip.id == clip_id)
.ok_or_else(|| format!("Clip {clip_id} was not found."))?;
if !clip.path.exists() {
return Err(format!("Clip file does not exist: {}", clip.path.display()));
}
let export_dir = runtime.library_root.join("exports");
fs::create_dir_all(&export_dir).map_err(|error| error.to_string())?;
let title = clip
.title
.as_deref()
.unwrap_or(&clip.id)
.chars()
.map(|ch| if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' { ch } else { '-' })
.collect::<String>()
.trim_matches('-')
.to_string();
let file_name = if title.is_empty() {
format!("{}.mp4", clip.id)
} else {
format!("{title}.mp4")
};
let output = export_dir.join(file_name);
fs::copy(&clip.path, &output).map_err(|error| error.to_string())?;
Ok(output.display().to_string())
}
fn upload_clip_with_settings(
clip: &Clip,
settings: &AppSettings,
provider_override: Option<String>,
custom_endpoint_override: Option<String>,
custom_response_path_override: Option<String>,
) -> Result<UploadResult, String> {
let provider = clean_provider(
provider_override
.as_deref()
.unwrap_or(&settings.upload.provider),
);
let metadata = UploadMetadata {
clip_id: clip.id.clone(),
game_id: clip.game_id.clone(),
title: clip.title.clone().unwrap_or_else(|| clip.id.clone()),
};
match provider.as_str() {
"catbox" => CatboxUploader {
userhash: settings.upload.catbox_userhash.clone(),
}
.upload(&clip.path, &metadata),
"litterbox" => LitterboxUploader {
expiry_hours: settings.upload.litterbox_expiry_hours,
}
.upload(&clip.path, &metadata),
"custom_http" => CustomHttpUploader {
endpoint: custom_endpoint_override
.and_then(|value| clean_optional(Some(value)))
.or_else(|| settings.upload.custom_endpoint.clone())
.unwrap_or_default(),
method: "POST".to_string(),
multipart_field: "file".to_string(),
response_url_path: custom_response_path_override
.and_then(|value| clean_optional(Some(value)))
.unwrap_or_else(|| settings.upload.custom_response_url_path.clone()),
headers: settings.upload.custom_headers.clone(),
}
.upload(&clip.path, &metadata),
"lustful" => clipforge::upload::LustfulUploader::default().upload(&clip.path, &metadata),
unknown => {
return Err(format!("Unsupported upload provider: {unknown}"));
}
}
.map_err(|error| error.to_string())
}
fn maybe_auto_upload_clip(runtime: &AppRuntime, recorder: &mut RecorderService, clip: &mut Clip) {
if !recorder.settings.upload.auto_upload_enabled {
return;
}
let provider = recorder.settings.upload.provider.clone();
match upload_clip_with_settings(clip, &recorder.settings, None, None, None) {
Ok(result) => {
record_upload_history(
runtime,
&clip.id,
&result.provider.to_string(),
"uploaded",
Some(&result.url),
None,
);
clip.upload_provider = Some(result.provider);
clip.upload_url = Some(result.url);
}
Err(error) => {
record_upload_history(runtime, &clip.id, &provider, "failed", None, Some(&error));
clip.upload_url = Some(format!("clipforge://upload-failed/{provider}"));
}
}
}
fn record_upload_history(
runtime: &AppRuntime,
clip_id: &str,
provider: &str,
status: &str,
url: Option<&str>,
error: Option<&str>,
) {
if let Ok(database) = runtime.database.lock() {
let _ = database.insert_upload_history(clip_id, provider, status, url, error, SystemTime::now());
}
}
fn clean_provider(provider: &str) -> String {
match provider.trim() {
"catbox" | "litterbox" | "custom_http" | "lustful" => provider.trim().to_string(),
_ => "catbox".to_string(),
}
}
fn clean_optional(value: Option<String>) -> Option<String> {
value
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
}
fn parse_header_lines(value: &str) -> Vec<(String, String)> {
value
.lines()
.filter_map(|line| {
let (name, value) = line.split_once(':')?;
let name = name.trim();
let value = value.trim();
if name.is_empty() || value.is_empty() {
None
} else {
Some((name.to_string(), value.to_string()))
}
})
.collect()
}
fn default_auto_clip_events_for_game(game_id: &str) -> Vec<&'static str> {
match game_id {
"league-of-legends" => vec!["kill", "death", "assist", "objective", "match_win"],
"counter-strike-2" => vec!["kill", "death", "assist", "round_win", "match_win", "multi_kill"],
"dota-2" => vec!["kill", "death", "assist", "objective", "match_win", "multi_kill"],
_ => Vec::new(),
}
}
fn auto_clip_event_enabled(settings: &AppSettings, game_id: &str, event_type: &str) -> bool {
if !settings.auto_clip.enabled {
return false;
}
settings
.auto_clip
.enabled_events_by_game
.get(game_id)
.map(|events| events.contains(event_type))
.unwrap_or_else(|| {
default_auto_clip_events_for_game(game_id)
.iter()
.any(|event| event == &event_type)
})
}
fn auto_clip_event_dtos(settings: &AppSettings) -> Vec<AutoClipEventDto> {
let games = [
("league-of-legends", default_auto_clip_events_for_game("league-of-legends")),
("counter-strike-2", default_auto_clip_events_for_game("counter-strike-2")),
("dota-2", default_auto_clip_events_for_game("dota-2")),
];
games
.into_iter()
.flat_map(|(game_id, events)| {
events.into_iter().map(move |event_type| AutoClipEventDto {
game_id: game_id.to_string(),
event_type: event_type.to_string(),
enabled: auto_clip_event_enabled(settings, game_id, event_type),
})
})
.collect()
}
fn main() {
let (library_root, recorder, database) =
create_runtime().expect("could not initialize ClipForge runtime");
@@ -863,17 +1171,21 @@ fn main() {
set_mic_enabled,
set_system_audio_enabled,
list_audio_devices,
set_mic_device,
set_auto_record_enabled,
write_gsi_configs,
poll_auto_clip_events,
save_manual_clip,
start_capture,
stop_capture,
delete_clip,
reveal_clip,
trim_clip,
upload_clip
set_mic_device,
set_auto_record_enabled,
set_upload_settings,
set_auto_clip_event_enabled,
write_gsi_configs,
poll_auto_clip_events,
save_manual_clip,
start_capture,
stop_capture,
delete_clip,
reveal_clip,
trim_clip,
upload_clip,
update_clip_metadata,
export_clip_copy
])
.run(tauri::generate_context!())
.expect("error while running ClipForge desktop shell");
@@ -931,6 +1243,7 @@ fn add_session_clip(
let clip = Clip {
id: clip_id.clone(),
title: Some("Full session".to_string()),
session_id,
game_id,
path: output_path,
@@ -1028,7 +1341,19 @@ fn status_from_recorder(recorder: &RecorderService, capture: Option<&ActiveCaptu
mic_enabled: recorder.settings.privacy.mic_enabled,
mic_device: recorder.settings.privacy.mic_device.clone(),
auto_record_enabled: !recorder.settings.privacy.desktop_capture_requires_confirmation,
upload_enabled: false,
upload_enabled: recorder.settings.upload.auto_upload_enabled,
upload_provider: recorder.settings.upload.provider.clone(),
catbox_userhash: recorder.settings.upload.catbox_userhash.clone(),
litterbox_expiry_hours: recorder.settings.upload.litterbox_expiry_hours,
custom_upload_endpoint: recorder.settings.upload.custom_endpoint.clone(),
custom_upload_response_url_path: recorder.settings.upload.custom_response_url_path.clone(),
custom_upload_headers: recorder
.settings
.upload
.custom_headers
.iter()
.map(|(name, value)| format!("{name}: {value}"))
.collect(),
session_recording: matches!(recorder.state.status, RecordingStatus::RecordingSession),
capture_active: capture.is_some(),
capture_backend: capture.map(|active| active.backend.name().to_string()),
@@ -1044,18 +1369,19 @@ fn status_from_recorder(recorder: &RecorderService, capture: Option<&ActiveCaptu
desktop_duplication_available: find_ffmpeg_executable()
.map(|path| ffmpeg_supports_filter(&path, "ddagrab"))
.unwrap_or(false),
auto_clip_enabled_events: auto_clip_event_dtos(&recorder.settings),
}
}
fn clip_to_dto(clip: &Clip) -> ClipDto {
ClipDto {
id: clip.id.clone(),
title: match clip.source {
title: clip.title.clone().unwrap_or_else(|| match clip.source {
ClipSource::ManualHotkey => "Manual clip".to_string(),
ClipSource::AutoEvent => "Auto clip".to_string(),
ClipSource::FullSessionBookmark => "Session bookmark".to_string(),
ClipSource::Imported => "Imported clip".to_string(),
},
}),
game: clip.game_id.clone(),
event: clip
.event_type
@@ -1071,6 +1397,13 @@ fn clip_to_dto(clip: &Clip) -> ClipDto {
duration: format_duration(clip.duration),
created_at: format_system_time(clip.created_at),
upload_state: if clip
.upload_url
.as_deref()
.map(|url| url.starts_with("clipforge://upload-failed/"))
.unwrap_or(false)
{
"Failed".to_string()
} else if clip
.upload_url
.as_deref()
.map(|url| url.starts_with("clipforge://upload-queued/"))
+84 -15
View File
@@ -26,6 +26,7 @@ impl ClipDatabase {
"
CREATE TABLE IF NOT EXISTS clips (
id TEXT PRIMARY KEY NOT NULL,
title TEXT,
session_id TEXT NOT NULL,
game_id TEXT NOT NULL,
path TEXT NOT NULL,
@@ -40,14 +41,29 @@ impl ClipDatabase {
);
CREATE INDEX IF NOT EXISTS clips_created_at_idx ON clips(created_at_ms DESC);
CREATE INDEX IF NOT EXISTS clips_game_id_idx ON clips(game_id);
CREATE TABLE IF NOT EXISTS upload_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
clip_id TEXT NOT NULL,
provider TEXT NOT NULL,
status TEXT NOT NULL,
url TEXT,
error TEXT,
attempted_at_ms INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS upload_history_clip_id_idx ON upload_history(clip_id);
",
)
)?;
if !self.column_exists("clips", "title")? {
self.connection
.execute("ALTER TABLE clips ADD COLUMN title TEXT", [])?;
}
self.connection.pragma_update(None, "user_version", 2)
}
pub fn load_clips(&self) -> rusqlite::Result<Vec<Clip>> {
let mut statement = self.connection.prepare(
"
SELECT id, session_id, game_id, path, thumbnail_path, created_at_ms, duration_ms,
SELECT id, title, session_id, game_id, path, thumbnail_path, created_at_ms, duration_ms,
source, event_type, tags_json, upload_url, upload_provider
FROM clips
ORDER BY created_at_ms DESC
@@ -55,27 +71,28 @@ impl ClipDatabase {
)?;
let rows = statement.query_map([], |row| {
let tags_json: String = row.get(9)?;
let tags_json: String = row.get(10)?;
let tags = serde_json::from_str::<Vec<String>>(&tags_json).unwrap_or_default();
let event_type = row
.get::<_, Option<String>>(8)?
.get::<_, Option<String>>(9)?
.map(|value| parse_event_type(&value));
let upload_provider = row
.get::<_, Option<String>>(11)?
.get::<_, Option<String>>(12)?
.and_then(|value| parse_upload_provider(&value));
Ok(Clip {
id: row.get(0)?,
session_id: row.get(1)?,
game_id: row.get(2)?,
path: PathBuf::from(row.get::<_, String>(3)?),
thumbnail_path: row.get::<_, Option<String>>(4)?.map(PathBuf::from),
created_at: millis_to_system_time(row.get(5)?),
duration: Duration::from_millis(row.get::<_, i64>(6)?.max(0) as u64),
source: parse_clip_source(&row.get::<_, String>(7)?),
title: row.get(1)?,
session_id: row.get(2)?,
game_id: row.get(3)?,
path: PathBuf::from(row.get::<_, String>(4)?),
thumbnail_path: row.get::<_, Option<String>>(5)?.map(PathBuf::from),
created_at: millis_to_system_time(row.get(6)?),
duration: Duration::from_millis(row.get::<_, i64>(7)?.max(0) as u64),
source: parse_clip_source(&row.get::<_, String>(8)?),
event_type,
tags,
upload_url: row.get(10)?,
upload_url: row.get(11)?,
upload_provider,
})
})?;
@@ -88,11 +105,12 @@ impl ClipDatabase {
self.connection.execute(
"
INSERT INTO clips (
id, session_id, game_id, path, thumbnail_path, created_at_ms, duration_ms,
id, title, session_id, game_id, path, thumbnail_path, created_at_ms, duration_ms,
source, event_type, tags_json, upload_url, upload_provider
)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)
ON CONFLICT(id) DO UPDATE SET
title = excluded.title,
session_id = excluded.session_id,
game_id = excluded.game_id,
path = excluded.path,
@@ -107,6 +125,7 @@ impl ClipDatabase {
",
params![
clip.id,
clip.title.as_deref(),
clip.session_id,
clip.game_id,
clip.path.display().to_string(),
@@ -125,11 +144,50 @@ impl ClipDatabase {
Ok(())
}
pub fn insert_upload_history(
&self,
clip_id: &str,
provider: &str,
status: &str,
url: Option<&str>,
error: Option<&str>,
attempted_at: SystemTime,
) -> rusqlite::Result<()> {
self.connection.execute(
"
INSERT INTO upload_history (clip_id, provider, status, url, error, attempted_at_ms)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
",
params![
clip_id,
provider,
status,
url,
error,
system_time_to_millis(attempted_at)
],
)?;
Ok(())
}
pub fn delete_clip(&self, clip_id: &str) -> rusqlite::Result<()> {
self.connection
.execute("DELETE FROM clips WHERE id = ?1", params![clip_id])?;
Ok(())
}
fn column_exists(&self, table: &str, column: &str) -> rusqlite::Result<bool> {
let mut statement = self
.connection
.prepare(&format!("PRAGMA table_info({table})"))?;
let rows = statement.query_map([], |row| row.get::<_, String>(1))?;
for row in rows {
if row? == column {
return Ok(true);
}
}
Ok(false)
}
}
fn parse_clip_source(value: &str) -> ClipSource {
@@ -207,6 +265,7 @@ mod tests {
let database = ClipDatabase::open(&db_path).expect("database");
let clip = Clip {
id: "clip-1".to_string(),
title: Some("Opening ace".to_string()),
session_id: "session-1".to_string(),
game_id: "counter-strike-2".to_string(),
path: PathBuf::from("C:/clips/clip-1.mp4"),
@@ -224,6 +283,16 @@ mod tests {
let loaded = database.load_clips().expect("load");
assert_eq!(loaded, vec![clip]);
database
.insert_upload_history(
"clip-1",
"custom_http",
"uploaded",
Some("https://example.test/clip.mp4"),
None,
SystemTime::now(),
)
.expect("upload history");
database.delete_clip("clip-1").expect("delete");
assert!(database.load_clips().expect("load empty").is_empty());
let _ = std::fs::remove_file(db_path);
+7 -2
View File
@@ -60,6 +60,10 @@ impl ClipLibrary {
&self.clips
}
pub fn all_mut(&mut self) -> &mut [Clip] {
&mut self.clips
}
pub fn filter(&self, filter: &ClipFilter) -> Vec<&Clip> {
self.clips
.iter()
@@ -96,12 +100,13 @@ impl ClipLibrary {
}
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");
let mut manifest = String::from("id\ttitle\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{}",
"{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}",
escape(&clip.id),
escape(clip.title.as_deref().unwrap_or_default()),
escape(&clip.game_id),
escape(&clip.session_id),
escape(&clip.path.to_string_lossy()),
+13
View File
@@ -82,9 +82,22 @@ pub enum UploadProvider {
CustomHttp,
}
impl fmt::Display for UploadProvider {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let value = match self {
Self::Catbox => "catbox",
Self::Litterbox => "litterbox",
Self::Lustful => "lustful",
Self::CustomHttp => "custom_http",
};
f.write_str(value)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Clip {
pub id: String,
pub title: Option<String>,
pub session_id: String,
pub game_id: String,
pub path: PathBuf,
+1
View File
@@ -354,6 +354,7 @@ impl RecorderService {
) -> Clip {
Clip {
id: clip_id.to_string(),
title: None,
session_id: session_id.to_string(),
game_id: game_id.to_string(),
path: clip_path(&self.paths, game_id, created_at, clip_id),
+85 -3
View File
@@ -6,6 +6,8 @@ use std::time::Duration;
use serde::{Deserialize, Serialize};
pub const CURRENT_SCHEMA_VERSION: u32 = 2;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct QualityPreset {
pub name: String,
@@ -46,8 +48,34 @@ pub struct AutoClipSettings {
pub enabled_events_by_game: BTreeMap<String, BTreeSet<String>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UploadSettings {
pub auto_upload_enabled: bool,
pub provider: String,
pub catbox_userhash: Option<String>,
pub litterbox_expiry_hours: u8,
pub custom_endpoint: Option<String>,
pub custom_response_url_path: String,
pub custom_headers: Vec<(String, String)>,
}
impl Default for UploadSettings {
fn default() -> Self {
Self {
auto_upload_enabled: false,
provider: "catbox".to_string(),
catbox_userhash: None,
litterbox_expiry_hours: 24,
custom_endpoint: None,
custom_response_url_path: "url".to_string(),
custom_headers: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AppSettings {
#[serde(default = "default_schema_version")]
pub schema_version: u32,
pub clip_root: PathBuf,
pub buffer_root: PathBuf,
@@ -57,6 +85,8 @@ pub struct AppSettings {
pub hotkeys: HotkeySettings,
pub privacy: PrivacySettings,
pub auto_clip: AutoClipSettings,
#[serde(default)]
pub upload: UploadSettings,
}
impl AppSettings {
@@ -66,7 +96,7 @@ impl AppSettings {
let buffer_root = root.join("buffer");
Self {
schema_version: 1,
schema_version: CURRENT_SCHEMA_VERSION,
clip_root,
buffer_root,
storage_limit_gb: 50,
@@ -100,6 +130,7 @@ impl AppSettings {
merge_window: Duration::from_secs(12),
enabled_events_by_game: BTreeMap::new(),
},
upload: UploadSettings::default(),
}
}
@@ -108,6 +139,21 @@ impl AppSettings {
.replay_buffer
.clamp(Duration::from_secs(15), Duration::from_secs(600));
}
pub fn migrate(&mut self) {
self.clamp_replay_buffer();
self.upload.litterbox_expiry_hours = match self.upload.litterbox_expiry_hours {
1 | 12 | 24 | 72 => self.upload.litterbox_expiry_hours,
_ => 24,
};
if self.upload.provider.trim().is_empty() {
self.upload.provider = "catbox".to_string();
}
if self.upload.custom_response_url_path.trim().is_empty() {
self.upload.custom_response_url_path = "url".to_string();
}
self.schema_version = CURRENT_SCHEMA_VERSION;
}
}
pub fn load_or_create_settings(root: impl Into<PathBuf>) -> io::Result<AppSettings> {
@@ -116,7 +162,11 @@ pub fn load_or_create_settings(root: impl Into<PathBuf>) -> io::Result<AppSettin
if path.exists() {
let mut settings: AppSettings = serde_json::from_str(&fs::read_to_string(&path)?)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
settings.clamp_replay_buffer();
let previous_version = settings.schema_version;
settings.migrate();
if previous_version != settings.schema_version {
save_settings(&root, &settings)?;
}
Ok(settings)
} else {
let settings = AppSettings::default_for_root(&root);
@@ -141,6 +191,10 @@ fn default_true() -> bool {
true
}
fn default_schema_version() -> u32 {
CURRENT_SCHEMA_VERSION
}
#[cfg(test)]
mod tests {
use super::*;
@@ -155,11 +209,39 @@ mod tests {
save_settings(&root, &settings).expect("save");
let loaded = load_or_create_settings(&root).expect("load");
assert_eq!(loaded.schema_version, 1);
assert_eq!(loaded.schema_version, CURRENT_SCHEMA_VERSION);
assert_eq!(loaded.replay_buffer, Duration::from_secs(120));
let _ = fs::remove_dir_all(root);
}
#[test]
fn legacy_settings_migrate_upload_defaults() {
let root = std::env::temp_dir().join(format!(
"clipforge-settings-migrate-{}",
SystemTimeCompat::millis()
));
fs::create_dir_all(&root).expect("settings root");
let mut value =
serde_json::to_value(AppSettings::default_for_root(&root)).expect("settings json");
value["schema_version"] = serde_json::json!(1);
value
.as_object_mut()
.expect("settings object")
.remove("upload");
fs::write(
settings_path(&root),
serde_json::to_string_pretty(&value).expect("legacy settings"),
)
.expect("write legacy settings");
let loaded = load_or_create_settings(&root).expect("load migrated settings");
assert_eq!(loaded.schema_version, CURRENT_SCHEMA_VERSION);
assert_eq!(loaded.upload.provider, "catbox");
assert!(!loaded.upload.auto_upload_enabled);
let _ = fs::remove_dir_all(root);
}
struct SystemTimeCompat;
impl SystemTimeCompat {
+1
View File
@@ -56,6 +56,7 @@ pub fn build_test_clip(
let created_at = SystemTime::now();
Clip {
id: clip_id.to_string(),
title: None,
session_id: session_id.to_string(),
game_id: game_id.to_string(),
path: clip_path(paths, game_id, created_at, clip_id),
+302 -30
View File
@@ -10,6 +10,7 @@ type RecordingState =
type ClipSource = "Auto Event" | "Manual Hotkey" | "Bookmark" | "Imported";
type UploadState = "Local only" | "Uploaded" | "Failed" | "Queued";
type UploadProvider = "catbox" | "litterbox" | "custom_http" | "lustful";
type Clip = {
id: string;
@@ -30,11 +31,19 @@ type Clip = {
type AutoEvent = {
id: string;
gameId: string;
eventType: string;
game: string;
event: string;
enabled: boolean;
};
type AutoClipEventDto = {
game_id: string;
event_type: string;
enabled: boolean;
};
type DesktopStatus = {
recording_state: RecordingState;
detected_game: string | null;
@@ -44,6 +53,12 @@ type DesktopStatus = {
mic_device: string | null;
auto_record_enabled: boolean;
upload_enabled: boolean;
upload_provider: UploadProvider;
catbox_userhash: string | null;
litterbox_expiry_hours: number;
custom_upload_endpoint: string | null;
custom_upload_response_url_path: string;
custom_upload_headers: string[];
session_recording: boolean;
capture_active: boolean;
capture_backend: string | null;
@@ -54,6 +69,7 @@ type DesktopStatus = {
ffmpeg_path: string | null;
system_audio_available: boolean;
desktop_duplication_available: boolean;
auto_clip_enabled_events: AutoClipEventDto[];
};
type ClipDto = {
@@ -100,10 +116,17 @@ type AppState = {
audioDevices: AudioDeviceDto[];
autoRecordEnabled: boolean;
autoUpload: boolean;
uploadProvider: "catbox" | "litterbox" | "custom_http" | "lustful";
uploadProvider: UploadProvider;
catboxUserhash: string;
litterboxExpiryHours: 1 | 12 | 24 | 72;
customUploadEndpoint: string;
customUploadResponsePath: string;
customUploadHeaders: string;
gsiConfigStatus: string;
libraryFilter: "all" | "kills" | "wins" | "uploaded" | "failed";
libraryQuery: string;
libraryViewMode: "grid" | "list";
notice: string;
selectedClipId: string;
clips: Clip[];
autoEvents: AutoEvent[];
@@ -144,17 +167,30 @@ const state: AppState = {
autoRecordEnabled: false,
autoUpload: false,
uploadProvider: "catbox",
catboxUserhash: "",
litterboxExpiryHours: 24,
customUploadEndpoint: "",
customUploadResponsePath: "url",
customUploadHeaders: "",
gsiConfigStatus: "",
libraryFilter: "all",
libraryQuery: "",
libraryViewMode: "grid",
notice: "",
selectedClipId: "",
clips: [],
autoEvents: [
{ id: "cs2-kill", game: "Counter-Strike 2", event: "Kill", enabled: true },
{ id: "cs2-round", game: "Counter-Strike 2", event: "Round win", enabled: true },
{ id: "lol-kill", game: "League of Legends", event: "Champion kill", enabled: true },
{ id: "lol-objective", game: "League of Legends", event: "Objective", enabled: true },
{ id: "dota-objective", game: "Dota 2", event: "Roshan/objective", enabled: false },
{ id: "cs2-kill", gameId: "counter-strike-2", eventType: "kill", game: "Counter-Strike 2", event: "Kill", enabled: true },
{ id: "cs2-death", gameId: "counter-strike-2", eventType: "death", game: "Counter-Strike 2", event: "Death", enabled: true },
{ id: "cs2-round", gameId: "counter-strike-2", eventType: "round_win", game: "Counter-Strike 2", event: "Round win", enabled: true },
{ id: "cs2-multi", gameId: "counter-strike-2", eventType: "multi_kill", game: "Counter-Strike 2", event: "Multi-kill", enabled: true },
{ id: "lol-kill", gameId: "league-of-legends", eventType: "kill", game: "League of Legends", event: "Champion kill", enabled: true },
{ id: "lol-death", gameId: "league-of-legends", eventType: "death", game: "League of Legends", event: "Death", enabled: true },
{ id: "lol-assist", gameId: "league-of-legends", eventType: "assist", game: "League of Legends", event: "Assist", enabled: true },
{ id: "lol-objective", gameId: "league-of-legends", eventType: "objective", game: "League of Legends", event: "Objective", enabled: true },
{ id: "dota-kill", gameId: "dota-2", eventType: "kill", game: "Dota 2", event: "Kill", enabled: true },
{ id: "dota-objective", gameId: "dota-2", eventType: "objective", game: "Dota 2", event: "Roshan/objective", enabled: true },
{ id: "dota-multi", gameId: "dota-2", eventType: "multi_kill", game: "Dota 2", event: "Multi-kill", enabled: true },
],
};
@@ -188,6 +224,7 @@ function render() {
<section class="workspace">
${renderRecordingBar()}
${state.notice ? `<div class="notice" role="status">${escapeHtml(state.notice)}</div>` : ""}
${renderActiveView(selectedClip)}
</section>
</main>
@@ -235,6 +272,7 @@ function renderActiveView(selectedClip: Clip | undefined) {
}
function renderLibraryView(selectedClip: Clip | undefined) {
const clips = filteredClips();
return `
<section class="content-grid">
<section class="library-panel">
@@ -244,18 +282,27 @@ function renderLibraryView(selectedClip: Clip | undefined) {
<h2>Recent Clips</h2>
</div>
<div class="segmented">
<button class="selected">Grid</button>
<button>List</button>
<button class="${state.libraryViewMode === "grid" ? "selected" : ""}" data-view-mode="grid">Grid</button>
<button class="${state.libraryViewMode === "list" ? "selected" : ""}" data-view-mode="list">List</button>
</div>
</div>
<input class="search-input" placeholder="Search clips, games, events, tags" value="${escapeHtml(state.libraryQuery)}" data-action="library-search" />
<div class="filters">
<button class="selected">All</button>
<button>Kills</button>
<button>Wins</button>
<button>Uploaded</button>
${[
["all", "All"],
["kills", "Kills"],
["wins", "Wins"],
["uploaded", "Uploaded"],
["failed", "Failed"],
]
.map(
([filter, label]) =>
`<button class="${state.libraryFilter === filter ? "selected" : ""}" data-library-filter="${filter}">${label}</button>`,
)
.join("")}
</div>
<div class="clip-grid">
${state.clips.length > 0 ? state.clips.map(renderClipCard).join("") : `<div class="empty-state">No clips saved yet</div>`}
<div class="${state.libraryViewMode === "list" ? "clip-list" : "clip-grid"}">
${clips.length > 0 ? clips.map(renderClipCard).join("") : `<div class="empty-state">No matching clips</div>`}
</div>
</section>
${renderClipDetails(selectedClip)}
@@ -286,10 +333,10 @@ function renderClipCard(clip: Clip) {
return `
<article class="clip-card ${state.selectedClipId === clip.id ? "selected" : ""}" data-clip-id="${clip.id}">
<div class="thumb ${clip.colorClass}">
${clip.thumbnailUrl ? `<img src="${clip.thumbnailUrl}" alt="" />` : clip.event}
${clip.thumbnailUrl ? `<img src="${clip.thumbnailUrl}" alt="" />` : escapeHtml(clip.event)}
</div>
<h3>${clip.title}</h3>
<p>${clip.game} · ${clip.source} · ${clip.duration}</p>
<h3>${escapeHtml(clip.title)}</h3>
<p>${escapeHtml(clip.game)} · ${escapeHtml(clip.source)} · ${escapeHtml(clip.duration)}</p>
</article>
`;
}
@@ -314,17 +361,20 @@ function renderClipDetails(clip: Clip | undefined) {
: `<span>Preview</span>`
}
</div>
<h2>${clip.title}</h2>
<p class="muted">${clip.game} · ${clip.event} · ${clip.createdAt} · ${clip.uploadState}</p>
<div class="tag-row">${clip.tags.map((tag) => `<span>${tag}</span>`).join("")}</div>
<p class="muted file-path">${clip.path || "Clip file unavailable"}</p>
<label>Title <input value="${escapeHtml(clip.title)}" data-action="clip-title" /></label>
<p class="muted">${escapeHtml(clip.game)} · ${escapeHtml(clip.event)} · ${escapeHtml(clip.createdAt)} · ${escapeHtml(clip.uploadState)}</p>
<label>Tags <input value="${escapeHtml(clip.tags.join(", "))}" data-action="clip-tags" /></label>
<div class="tag-row">${clip.tags.map((tag) => `<span>${escapeHtml(tag)}</span>`).join("")}</div>
<p class="muted file-path">${escapeHtml(clip.path || "Clip file unavailable")}</p>
<div class="trim-row">
<label>Start <input value="00:00" data-action="trim-start" /></label>
<label>End <input value="${clip.duration}" data-action="trim-end" /></label>
<label>End <input value="${escapeHtml(clip.duration)}" data-action="trim-end" /></label>
</div>
<div class="actions">
<button data-action="save-metadata">Save Info</button>
<button data-action="process">Trim</button>
<button data-action="reveal">Reveal</button>
<button data-action="export-copy">Export</button>
<button data-action="upload">Upload</button>
<button data-action="delete">Delete</button>
</div>
@@ -391,7 +441,7 @@ function renderAutoClipView() {
.map(
(event) => `
<label class="event-row">
<span><strong>${event.game}</strong><small>${event.event}</small></span>
<span><strong>${escapeHtml(event.game)}</strong><small>${escapeHtml(event.event)}</small></span>
<input type="checkbox" ${event.enabled ? "checked" : ""} data-event-id="${event.id}" />
</label>
`,
@@ -407,9 +457,9 @@ function renderAutoClipView() {
}
function renderUploadsView() {
const providers: Array<{ id: AppState["uploadProvider"]; title: string; body: string }> = [
const providers: Array<{ id: UploadProvider; title: string; body: string }> = [
{ id: "catbox", title: "Catbox", body: "Anonymous or userhash-backed permanent uploads." },
{ id: "litterbox", title: "Litterbox", body: "Temporary uploads with a 24 hour default expiry." },
{ id: "litterbox", title: "Litterbox", body: "Temporary uploads with a selectable expiry." },
{ id: "custom_http", title: "Custom HTTP", body: "POST multipart clip files to your own endpoint." },
{ id: "lustful", title: "Lustful", body: "Blocked until API details are confirmed." },
];
@@ -425,11 +475,29 @@ function renderUploadsView() {
</button>
</article>
`).join("")}
<article class="settings-panel">
<p class="eyebrow">Automation</p>
<h2>Upload Rules</h2>
<label class="toggle"><input type="checkbox" ${state.autoUpload ? "checked" : ""} data-action="toggle-auto-upload" /> Auto-upload after clipping</label>
</article>
<article class="settings-panel">
<p class="eyebrow">Catbox</p>
<h2>Userhash</h2>
<label>Optional userhash <input value="${escapeHtml(state.catboxUserhash)}" data-action="catbox-userhash" /></label>
</article>
<article class="settings-panel">
<p class="eyebrow">Litterbox</p>
<h2>Expiry</h2>
<select data-action="litterbox-expiry">
${[1, 12, 24, 72].map((hours) => `<option value="${hours}" ${state.litterboxExpiryHours === hours ? "selected" : ""}>${hours} hour${hours === 1 ? "" : "s"}</option>`).join("")}
</select>
</article>
<article class="settings-panel">
<p class="eyebrow">Custom HTTP</p>
<h2>Endpoint</h2>
<label>URL <input value="${state.customUploadEndpoint}" data-action="custom-upload-endpoint" /></label>
<label>Response path <input value="${state.customUploadResponsePath}" data-action="custom-upload-response-path" /></label>
<label>URL <input value="${escapeHtml(state.customUploadEndpoint)}" data-action="custom-upload-endpoint" /></label>
<label>Response path <input value="${escapeHtml(state.customUploadResponsePath)}" data-action="custom-upload-response-path" /></label>
<label>Headers <textarea data-action="custom-upload-headers">${escapeHtml(state.customUploadHeaders)}</textarea></label>
</article>
</section>
`;
@@ -473,6 +541,25 @@ function bindEvents() {
});
});
appRoot.querySelectorAll<HTMLButtonElement>("[data-view-mode]").forEach((button) => {
button.addEventListener("click", () => {
state.libraryViewMode = button.dataset.viewMode === "list" ? "list" : "grid";
render();
});
});
appRoot.querySelectorAll<HTMLButtonElement>("[data-library-filter]").forEach((button) => {
button.addEventListener("click", () => {
state.libraryFilter = (button.dataset.libraryFilter as AppState["libraryFilter"]) ?? "all";
render();
});
});
appRoot.querySelector<HTMLInputElement>("[data-action='library-search']")?.addEventListener("input", (event) => {
state.libraryQuery = (event.target as HTMLInputElement).value;
render();
});
appRoot.querySelector<HTMLButtonElement>("[data-action='clip']")?.addEventListener("click", () => {
void saveClip();
});
@@ -485,6 +572,10 @@ function bindEvents() {
void trimSelectedClip();
});
appRoot.querySelector<HTMLButtonElement>("[data-action='save-metadata']")?.addEventListener("click", () => {
void saveSelectedClipMetadata();
});
appRoot.querySelector<HTMLButtonElement>("[data-action='reveal']")?.addEventListener("click", () => {
void revealSelectedClip();
});
@@ -493,6 +584,10 @@ function bindEvents() {
void uploadSelectedClip();
});
appRoot.querySelector<HTMLButtonElement>("[data-action='export-copy']")?.addEventListener("click", () => {
void exportSelectedClip();
});
appRoot.querySelector<HTMLButtonElement>("[data-action='write-gsi-configs']")?.addEventListener("click", () => {
void writeGsiConfigs();
});
@@ -529,6 +624,7 @@ function bindEvents() {
appRoot.querySelector<HTMLInputElement>("[data-action='toggle-auto-upload']")?.addEventListener("change", (event) => {
state.autoUpload = (event.target as HTMLInputElement).checked;
render();
void saveUploadSettings();
});
appRoot.querySelector<HTMLInputElement>("[data-action='toggle-auto-record']")?.addEventListener("change", (event) => {
@@ -539,24 +635,49 @@ function bindEvents() {
appRoot.querySelectorAll<HTMLButtonElement>("[data-upload-provider]").forEach((button) => {
button.addEventListener("click", () => {
state.uploadProvider = button.dataset.uploadProvider as AppState["uploadProvider"];
state.uploadProvider = button.dataset.uploadProvider as UploadProvider;
render();
void saveUploadSettings();
});
});
appRoot.querySelector<HTMLInputElement>("[data-action='catbox-userhash']")?.addEventListener("change", (event) => {
state.catboxUserhash = (event.target as HTMLInputElement).value;
void saveUploadSettings();
});
appRoot.querySelector<HTMLSelectElement>("[data-action='litterbox-expiry']")?.addEventListener("change", (event) => {
state.litterboxExpiryHours = Number((event.target as HTMLSelectElement).value) as AppState["litterboxExpiryHours"];
void saveUploadSettings();
});
appRoot.querySelector<HTMLInputElement>("[data-action='custom-upload-endpoint']")?.addEventListener("input", (event) => {
state.customUploadEndpoint = (event.target as HTMLInputElement).value;
});
appRoot.querySelector<HTMLInputElement>("[data-action='custom-upload-endpoint']")?.addEventListener("change", () => {
void saveUploadSettings();
});
appRoot.querySelector<HTMLInputElement>("[data-action='custom-upload-response-path']")?.addEventListener("input", (event) => {
state.customUploadResponsePath = (event.target as HTMLInputElement).value;
});
appRoot.querySelector<HTMLInputElement>("[data-action='custom-upload-response-path']")?.addEventListener("change", () => {
void saveUploadSettings();
});
appRoot.querySelector<HTMLTextAreaElement>("[data-action='custom-upload-headers']")?.addEventListener("input", (event) => {
state.customUploadHeaders = (event.target as HTMLTextAreaElement).value;
});
appRoot.querySelector<HTMLTextAreaElement>("[data-action='custom-upload-headers']")?.addEventListener("change", () => {
void saveUploadSettings();
});
appRoot.querySelectorAll<HTMLInputElement>("[data-event-id]").forEach((input) => {
input.addEventListener("change", () => {
const eventRule = state.autoEvents.find((event) => event.id === input.dataset.eventId);
if (eventRule) {
eventRule.enabled = input.checked;
void saveAutoClipEventSetting(eventRule);
}
});
});
@@ -573,12 +694,14 @@ async function saveClip() {
state.clips.unshift(clip);
state.selectedClipId = clip.id;
state.activeView = "Library";
state.recordingState = "Processing";
await refreshClips();
state.recordingState = "Processing";
await refreshClips();
showNotice("Clip saved");
render();
return;
} catch (error) {
console.error("Could not save desktop clip", error);
showNotice(`Could not save clip: ${String(error)}`);
}
}
@@ -609,10 +732,12 @@ async function toggleRecording() {
const status = await tauriInvoke<DesktopStatus>(state.captureActive ? "stop_capture" : "start_capture");
applyDesktopStatus(status);
await refreshClips();
showNotice(state.captureActive ? "Recording started" : "Recording stopped");
render();
return;
} catch (error) {
console.error("Could not toggle desktop recording", error);
showNotice(`Could not toggle recording: ${String(error)}`);
}
}
@@ -630,6 +755,12 @@ function applyDesktopStatus(status: DesktopStatus) {
state.micDevice = status.mic_device ?? "";
state.autoRecordEnabled = status.auto_record_enabled;
state.autoUpload = status.upload_enabled;
state.uploadProvider = status.upload_provider;
state.catboxUserhash = status.catbox_userhash ?? "";
state.litterboxExpiryHours = validLitterboxExpiry(status.litterbox_expiry_hours);
state.customUploadEndpoint = status.custom_upload_endpoint ?? "";
state.customUploadResponsePath = status.custom_upload_response_url_path;
state.customUploadHeaders = status.custom_upload_headers.join("\n");
state.sessionRecording = status.session_recording;
state.captureActive = status.capture_active;
state.captureBackend = status.capture_backend;
@@ -638,6 +769,14 @@ function applyDesktopStatus(status: DesktopStatus) {
state.ffmpegPath = status.ffmpeg_path;
state.systemAudioAvailable = status.system_audio_available;
state.desktopDuplicationAvailable = status.desktop_duplication_available;
for (const event of state.autoEvents) {
const enabled = status.auto_clip_enabled_events.find(
(candidate) => candidate.game_id === event.gameId && candidate.event_type === event.eventType,
);
if (enabled) {
event.enabled = enabled.enabled;
}
}
}
async function trimSelectedClip() {
@@ -665,9 +804,38 @@ async function trimSelectedClip() {
state.clips.unshift(trimmed);
state.selectedClipId = trimmed.id;
await refreshClips();
showNotice("Trimmed clip created");
render();
} catch (error) {
console.error("Could not trim clip", error);
showNotice(`Could not trim clip: ${String(error)}`);
}
}
async function saveSelectedClipMetadata() {
if (!tauriInvoke || !state.selectedClipId) {
return;
}
const title = appRoot.querySelector<HTMLInputElement>("[data-action='clip-title']")?.value ?? "";
const tags = (appRoot.querySelector<HTMLInputElement>("[data-action='clip-tags']")?.value ?? "")
.split(",")
.map((tag) => tag.trim())
.filter((tag) => tag.length > 0);
try {
const dto = await tauriInvoke<ClipDto>("update_clip_metadata", {
clipId: state.selectedClipId,
title,
tags,
});
const updated = clipFromDto(dto);
state.clips = state.clips.map((clip) => (clip.id === updated.id ? updated : clip));
showNotice("Clip info saved");
render();
} catch (error) {
console.error("Could not save clip info", error);
showNotice(`Could not save clip info: ${String(error)}`);
}
}
@@ -680,6 +848,7 @@ async function revealSelectedClip() {
await tauriInvoke("reveal_clip", { clipId: state.selectedClipId });
} catch (error) {
console.error("Could not reveal clip", error);
showNotice(`Could not reveal clip: ${String(error)}`);
}
}
@@ -697,9 +866,26 @@ async function uploadSelectedClip() {
});
const updated = clipFromDto(dto);
state.clips = state.clips.map((clip) => (clip.id === updated.id ? updated : clip));
showNotice("Clip uploaded");
render();
} catch (error) {
console.error("Could not queue upload", error);
showNotice(`Could not upload clip: ${String(error)}`);
}
}
async function exportSelectedClip() {
if (!tauriInvoke || !state.selectedClipId) {
return;
}
try {
const path = await tauriInvoke<string>("export_clip_copy", { clipId: state.selectedClipId });
showNotice(`Exported to ${path}`);
render();
} catch (error) {
console.error("Could not export clip", error);
showNotice(`Could not export clip: ${String(error)}`);
}
}
@@ -711,6 +897,7 @@ async function writeGsiConfigs() {
try {
const configs = await tauriInvoke<GsiConfigDto[]>("write_gsi_configs");
state.gsiConfigStatus = configs.map((config) => `${config.game_id}: ${config.path}`).join(" · ");
showNotice("GSI configs written");
render();
} catch (error) {
state.gsiConfigStatus = `Could not write GSI configs: ${String(error)}`;
@@ -727,9 +914,11 @@ async function deleteSelectedClip() {
const clips = await tauriInvoke<ClipDto[]>("delete_clip", { clipId: state.selectedClipId });
state.clips = clips.map(clipFromDto);
state.selectedClipId = state.clips[0]?.id ?? "";
showNotice("Clip deleted");
render();
} catch (error) {
console.error("Could not delete clip", error);
showNotice(`Could not delete clip: ${String(error)}`);
}
}
@@ -862,6 +1051,89 @@ async function pollAutoClips() {
}
}
async function saveUploadSettings() {
if (!tauriInvoke) {
return;
}
try {
const status = await tauriInvoke<DesktopStatus>("set_upload_settings", {
autoUploadEnabled: state.autoUpload,
provider: state.uploadProvider,
catboxUserhash: state.catboxUserhash || null,
litterboxExpiryHours: state.litterboxExpiryHours,
customEndpoint: state.customUploadEndpoint || null,
customResponseUrlPath: state.customUploadResponsePath,
customHeaders: state.customUploadHeaders
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0),
});
applyDesktopStatus(status);
showNotice("Upload settings saved");
render();
} catch (error) {
console.warn("Could not save upload settings", error);
showNotice(`Could not save upload settings: ${String(error)}`);
}
}
async function saveAutoClipEventSetting(eventRule: AutoEvent) {
if (!tauriInvoke) {
return;
}
try {
const status = await tauriInvoke<DesktopStatus>("set_auto_clip_event_enabled", {
gameId: eventRule.gameId,
eventType: eventRule.eventType,
enabled: eventRule.enabled,
});
applyDesktopStatus(status);
showNotice("Auto-clip rule saved");
render();
} catch (error) {
console.warn("Could not save auto-clip rule", error);
showNotice(`Could not save auto-clip rule: ${String(error)}`);
}
}
function filteredClips() {
const query = state.libraryQuery.trim().toLowerCase();
return state.clips.filter((clip) => {
const matchesFilter =
state.libraryFilter === "all" ||
(state.libraryFilter === "kills" && clip.event.toLowerCase().includes("kill")) ||
(state.libraryFilter === "wins" && clip.event.toLowerCase().includes("win")) ||
(state.libraryFilter === "uploaded" && clip.uploadState === "Uploaded") ||
(state.libraryFilter === "failed" && clip.uploadState === "Failed");
if (!matchesFilter) {
return false;
}
if (!query) {
return true;
}
return [clip.title, clip.game, clip.event, clip.source, clip.uploadState, clip.path, ...clip.tags]
.join(" ")
.toLowerCase()
.includes(query);
});
}
function validLitterboxExpiry(value: number): AppState["litterboxExpiryHours"] {
return value === 1 || value === 12 || value === 24 || value === 72 ? value : 24;
}
function showNotice(message: string) {
state.notice = message;
window.setTimeout(() => {
if (state.notice === message) {
state.notice = "";
render();
}
}, 5_000);
}
function parseTimestamp(value: string) {
const parts = value.trim().split(":").map(Number);
if (parts.some((part) => Number.isNaN(part))) {
+44 -4
View File
@@ -16,7 +16,8 @@ body {
}
button,
input {
input,
textarea {
font: inherit;
}
@@ -87,6 +88,15 @@ nav {
padding: 18px;
}
.notice {
margin-top: 12px;
padding: 10px 12px;
border: 1px solid #31533f;
border-radius: 8px;
background: #13251b;
color: #b7f7cc;
}
.recording-bar {
display: grid;
grid-template-columns: minmax(220px, 1fr) 150px auto auto auto;
@@ -212,6 +222,10 @@ h3 {
margin-bottom: 16px;
}
.search-input {
margin-bottom: 12px;
}
.filters button {
padding: 8px 11px;
background: #1b2029;
@@ -224,6 +238,22 @@ h3 {
gap: 14px;
}
.clip-list {
display: grid;
gap: 8px;
}
.clip-list .clip-card {
display: grid;
grid-template-columns: 150px minmax(0, 1fr);
align-items: center;
}
.clip-list .thumb {
height: 84px;
margin-bottom: 0;
}
.clip-card {
overflow: hidden;
border: 1px solid #2b3140;
@@ -337,7 +367,8 @@ label {
}
input,
select {
select,
textarea {
width: 100%;
padding: 9px 10px;
border: 1px solid #313847;
@@ -346,12 +377,21 @@ select {
color: #f5f7fb;
}
textarea {
min-height: 92px;
resize: vertical;
}
.actions {
display: grid;
grid-template-columns: repeat(3, 1fr);
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.actions button {
flex: 1 1 96px;
}
.auto-box {
margin-top: 18px;
padding-top: 16px;