Skip to content

Commit

Permalink
fix some bugs in auto-delete feature
Browse files Browse the repository at this point in the history
  • Loading branch information
FFFFFFFXXXXXXX committed Mar 8, 2024
1 parent 7519b83 commit 864f1b3
Show file tree
Hide file tree
Showing 8 changed files with 68 additions and 60 deletions.
4 changes: 2 additions & 2 deletions src-tauri/default-settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@
"recordAudio": "APPLICATION",
"onlyRecordRanked": false,
"autostart": false,
"maxRecordingAge": null,
"maxRecordingsSize": null
"maxRecordingAgeDays": null,
"maxRecordingsSizeGb": null
}
15 changes: 5 additions & 10 deletions src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
*/

use std::cmp::Ordering;
use std::fs::{metadata, read_to_string, remove_file, rename, write, File};
use std::fs::{metadata, read_to_string, rename, write, File};
use std::io::BufReader;
use std::path::PathBuf;

use tauri::{api::shell, AppHandle, Manager, State};

use crate::game_data::GameMetadata;
use crate::helpers::{self, compare_time, get_recordings, show_window};
use crate::helpers::{self, compare_time, delete_recording, get_recordings, show_window};
use crate::state::{MarkerFlags, SettingsFile, SettingsWrapper};

#[cfg_attr(test, specta::specta)]
Expand Down Expand Up @@ -121,16 +121,11 @@ pub fn rename_video(video_id: String, new_video_id: String, state: State<'_, Set
#[cfg_attr(test, specta::specta)]
#[tauri::command]
pub fn delete_video(video_id: String, state: State<'_, SettingsWrapper>) -> bool {
// remove video
let mut path = state.get_recordings_path().join(video_id);
if remove_file(&path).is_err() {
// if video delete fails return and dont delete json file
return false;
let recording = state.get_recordings_path().join(video_id);
if let Err(e) = delete_recording(recording) {
log::error!("deleting video failed: {e}");
}

// remove json file if it exists
path.set_extension("json");
_ = remove_file(path);
true
}

Expand Down
4 changes: 1 addition & 3 deletions src-tauri/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ pub fn create_system_tray() -> SystemTray {

pub fn system_tray_event_handler(app_handle: &AppHandle, event: SystemTrayEvent) {
match event {
SystemTrayEvent::DoubleClick { .. } => {
create_window(app_handle);
}
SystemTrayEvent::DoubleClick { .. } => create_window(app_handle),
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
"settings" => let_user_edit_settings(app_handle),
"open" => create_window(app_handle),
Expand Down
37 changes: 29 additions & 8 deletions src-tauri/src/helpers.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use std::cmp::Ordering;
use std::fs;
use std::fs::File;
use std::io;
use std::io::BufReader;
use std::fs::{self, File};
use std::io::{self, BufReader};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, SystemTime};
Expand All @@ -18,8 +16,6 @@ use crate::filewatcher;
use crate::game_data::GameMetadata;
use crate::state::{CurrentlyRecording, SettingsFile, SettingsWrapper, WindowState};

const GITHUB_LATEST: &str = "https://github.com/FFFFFFFXXXXXXX/league_record/releases/latest";

pub fn create_tray_menu() -> SystemTrayMenu {
SystemTrayMenu::new()
.add_item(CustomMenuItem::new("rec", "Recording").disabled())
Expand All @@ -38,6 +34,8 @@ pub fn set_recording_tray_item(app_handle: &AppHandle, recording: bool) {
}

pub fn check_updates(app_handle: &AppHandle) {
const GITHUB_LATEST: &str = "https://github.com/FFFFFFFXXXXXXX/league_record/releases/latest";

let config = app_handle.config();
let version = config.package.version.as_ref().unwrap();

Expand Down Expand Up @@ -277,6 +275,8 @@ pub fn let_user_edit_settings(app_handle: &AppHandle) {
log::error!("failed to emit 'markerflags_changed' event: {e}");
}
}

cleanup_recordings(&app_handle);
}
}
});
Expand All @@ -295,13 +295,24 @@ fn cleanup_recordings_by_size(app_handle: &AppHandle) {
recordings.sort_by(|a, b| compare_time(a, b).unwrap_or(Ordering::Equal));

let mut total_size = 0;

// add size from video thats currently being recorded to the total (in case there is one)
// so the total size of all videos stays below the threshhold set in settings
if let Some(currently_recording_metadata) = app_handle
.state::<CurrentlyRecording>()
.get()
.and_then(|pb| pb.metadata().ok())
{
total_size += currently_recording_metadata.len();
}

for recording in recordings {
if let Ok(metadata) = recording.metadata() {
total_size += metadata.len();
};

if total_size > max_size && !get_metadata(&recording).map(|md| md.favorite).unwrap_or_default() {
if let Err(e) = fs::remove_file(recording) {
if let Err(e) = delete_recording(recording) {
log::error!("deleting file due to size limit failed: {e}");
}
}
Expand All @@ -322,13 +333,23 @@ fn cleanup_recordings_by_age(app_handle: &AppHandle) {
if file_too_old(&recording, max_age, now).unwrap_or(false)
&& !get_metadata(&recording).map(|md| md.favorite).unwrap_or_default()
{
if let Err(e) = fs::remove_file(recording) {
if let Err(e) = delete_recording(recording) {
log::error!("deleting file due to age limit failed: {e}");
}
}
}
}

pub fn delete_recording(recording: PathBuf) -> anyhow::Result<()> {
fs::remove_file(&recording)?;

let mut metadata_file = recording;
metadata_file.set_extension("json");
fs::remove_file(metadata_file)?;

Ok(())
}

pub fn get_metadata(video_path: &Path) -> anyhow::Result<GameMetadata> {
let mut video_path = video_path.to_owned();
video_path.set_extension("json");
Expand Down
26 changes: 14 additions & 12 deletions src-tauri/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,11 +198,11 @@ impl SettingsWrapper {
}

pub fn max_recording_age(&self) -> Option<u64> {
self.0.read().unwrap().max_recording_age
self.0.read().unwrap().max_recording_age_days
}

pub fn max_recordings_size(&self) -> Option<u64> {
self.0.read().unwrap().max_recordings_size
self.0.read().unwrap().max_recordings_size_gb
}

pub fn debug_log(&self) -> bool {
Expand Down Expand Up @@ -233,8 +233,8 @@ pub struct Settings {
record_audio: AudioSource,
only_record_ranked: bool,
autostart: bool,
max_recording_age: Option<u64>,
max_recordings_size: Option<u64>,
max_recording_age_days: Option<u64>,
max_recordings_size_gb: Option<u64>,
}

const DEFAULT_UPDATE_CHECK: bool = true;
Expand All @@ -243,8 +243,8 @@ const DEFAULT_ENCODING_QUALITY: u32 = 25;
const DEFAULT_RECORD_AUDIO: AudioSource = AudioSource::APPLICATION;
const DEFAULT_ONLY_RECORD_RANKED: bool = false;
const DEFAULT_AUTOSTART: bool = false;
const DEFAULT_MAX_RECORDING_AGE: Option<u64> = None;
const DEFAULT_MAX_RECORDINGS_SIZE: Option<u64> = None;
const DEFAULT_MAX_RECORDING_AGE_DAYS: Option<u64> = None;
const DEFAULT_MAX_RECORDINGS_SIZE_GB: Option<u64> = None;

#[inline]
fn default_recordings_folder() -> PathBuf {
Expand Down Expand Up @@ -275,8 +275,8 @@ impl Default for Settings {
record_audio: DEFAULT_RECORD_AUDIO,
only_record_ranked: DEFAULT_ONLY_RECORD_RANKED,
autostart: false,
max_recording_age: None,
max_recordings_size: None,
max_recording_age_days: None,
max_recordings_size_gb: None,
}
}
}
Expand Down Expand Up @@ -337,11 +337,13 @@ impl<'de> Deserialize<'de> for Settings {
"autostart" => {
settings.autostart = map.next_value().unwrap_or(DEFAULT_AUTOSTART);
}
"maxRecordingAge" => {
settings.max_recording_age = map.next_value().unwrap_or(DEFAULT_MAX_RECORDING_AGE);
"maxRecordingAgeDays" => {
settings.max_recording_age_days =
map.next_value().unwrap_or(DEFAULT_MAX_RECORDING_AGE_DAYS);
}
"maxRecordingsSize" => {
settings.max_recordings_size = map.next_value().unwrap_or(DEFAULT_MAX_RECORDINGS_SIZE);
"maxRecordingsSizeGb" => {
settings.max_recordings_size_gb =
map.next_value().unwrap_or(DEFAULT_MAX_RECORDINGS_SIZE_GB);
}
_ => { /* ignored */ }
}
Expand Down
21 changes: 4 additions & 17 deletions src/bindings.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
/* eslint-disable */
// This file was generated by [tauri-specta](https://github.com/oscartbeaumont/tauri-specta). Do not edit this file manually.

import type { GameMetadata, MarkerFlags, Recording } from "@fffffffxxxxxxx/league_record_types";

declare global {
interface Window {
__TAURI_INVOKE__<T>(cmd: string, args?: Record<string, unknown>): Promise<T>;
Expand Down Expand Up @@ -43,28 +45,13 @@ export function deleteVideo(videoId: string) {
}

export function renameVideo(videoId: string, newVideoId: string) {
return invoke()<boolean>("rename_video", { videoId,newVideoId })
return invoke()<boolean>("rename_video", { videoId, newVideoId })
}

export function getMetadata(videoId: string) {
return invoke()<GameMetadata | null>("get_metadata", { videoId })
}

export function toggleFavorite(videoId: string) {
return invoke()<boolean>("toggle_favorite", { videoId })
return invoke()<boolean | null>("toggle_favorite", { videoId })
}

export type GameMetadata = { ingameTimeRecStartOffset: number; queue: Queue; player: Player; championName: string; stats: Stats; participantId: number; events: GameEvent[]; favorite: boolean }
export type BuildingType = { buildingType: "INHIBITOR_BUILDING"; lane_type: LaneType } | { buildingType: "TOWER_BUILDING"; lane_type: LaneType; tower_type: TowerType }
export type TowerType = "OUTER_TURRET" | "INNER_TURRET" | "BASE_TURRET" | "NEXUS_TURRET"
export type GameEvent = { ChampionKill: { timestamp: number; victim_id: number; killer_id: number; assisting_participant_ids: number[]; position: Position } } | { BuildingKill: { timestamp: number; team_id: Team; killer_id: number; building_type: BuildingType; assisting_participant_ids: number[] } } | { EliteMonsterKill: { timestamp: number; killer_id: number; monster_type: MonsterType; assisting_participant_ids: number[] } }
export type Queue = { id: number; name: string; description: string }
export type LaneType = "TOP_LANE" | "MID_LANE" | "BOT_LANE"
export type Stats = { kills: number; deaths: number; assists: number; largestMultiKill: number; neutralMinionsKilled: number; neutralMinionsKilledEnemyJungle: number; neutralMinionsKilledTeamJungle: number; totalMinionsKilled: number; visionScore: number; visionWardsBoughtInGame: number; wardsPlaced: number; wardsKilled: number; win: boolean }
export type MarkerFlags = { kill: boolean; death: boolean; assist: boolean; turret: boolean; inhibitor: boolean; dragon: boolean; herald: boolean; baron: boolean }
export type MonsterType = { monsterType: "HORDE" } | { monsterType: "RIFTHERALD" } | { monsterType: "BARON_NASHOR" } | { monsterType: "DRAGON"; monsterSubType: DragonType }
export type Player = { gameName: string; tagLine: string; summonerId?: number | null }
export type Team = "BLUE" | "RED"
export type Position = { x: number; y: number }
export type Recording = { video_id: string; metadata: GameMetadata | null }
export type DragonType = "FIRE_DRAGON" | "EARTH_DRAGON" | "WATER_DRAGON" | "AIR_DRAGON" | "HEXTECH_DRAGON" | "CHEMTECH_DRAGON" | "ELDER_DRAGON"
9 changes: 6 additions & 3 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,10 @@ async function main() {

// add events to html elements
ui.setRecordingsFolderBtnOnClickHandler(tauri.openRecordingsFolder);
ui.setCheckboxOnClickHandler(changeMarkers);
ui.setCheckboxOnClickHandler(() => {
changeMarkers()
tauri.setMarkerFlags(ui.getMarkerFlags())
});

// listen if the videojs player fills the whole window
// and keep the tauri fullscreen setting in sync
Expand Down Expand Up @@ -165,7 +168,7 @@ async function setMetadata(videoId: string) {
changeMarkers();
}

async function toggleFavorite(video_id: string): Promise<boolean> {
async function toggleFavorite(video_id: string): Promise<boolean | null> {
return await tauri.toggleFavorite(video_id)
}

Expand All @@ -175,7 +178,7 @@ function changeMarkers() {
return;
}

const checkbox = ui.getCheckboxes();
const checkbox = ui.getMarkerFlags();
const { participantId, recordingOffset } = currentEvents;

const markers = new Array<MarkerOptions>();
Expand Down
12 changes: 7 additions & 5 deletions src/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export default class UI {
recordingsSizeGb: number,
recordings: ReadonlyArray<Recording>,
onVideo: (videoId: string) => void,
onFavorite: (videoId: string) => Promise<boolean>,
onFavorite: (videoId: string) => Promise<boolean | null>,
onRename: (videoId: string) => void,
onDelete: (videoId: string) => void
) {
Expand All @@ -93,8 +93,10 @@ export default class UI {
onclick: (e: MouseEvent) => {
e.stopPropagation();
onFavorite(recording.video_id).then(fav => {
favoriteBtn.innerHTML = fav ? '★' : '☆'
favoriteBtn.style.color = fav ? 'gold' : ''
if (fav !== null) {
favoriteBtn.innerHTML = fav ? '★' : '☆'
favoriteBtn.style.color = fav ? 'gold' : ''
}
})
}
},
Expand Down Expand Up @@ -130,7 +132,7 @@ export default class UI {
return this.vjs.dom.createEl(
'li',
{ onclick: () => onVideo(recording.video_id) },
{ id: recording },
{ id: recording.video_id },
[
this.vjs.dom.createEl('span', {}, { class: 'video-name' }, videoName),
favoriteBtn,
Expand Down Expand Up @@ -334,7 +336,7 @@ export default class UI {
this.checkboxBaron.checked = settings.baron;
}

public getCheckboxes(): MarkerFlags {
public getMarkerFlags(): MarkerFlags {
return {
kill: this.checkboxKill.checked,
death: this.checkboxDeath.checked,
Expand Down

0 comments on commit 864f1b3

Please sign in to comment.