mirror of
https://github.com/Drop-OSS/drop-app.git
synced 2025-11-12 07:42:44 +10:00
Compare commits
5 Commits
42ff3b1331
...
AdenMGB-sm
| Author | SHA1 | Date | |
|---|---|---|---|
| 40a490fda4 | |||
| 6d2b8c88e8 | |||
| 262c8505b7 | |||
| e798d258dc | |||
| 105b3e9bc4 |
@ -44,6 +44,10 @@ router.beforeEach(async () => {
|
||||
setupHooks();
|
||||
initialNavigation(state);
|
||||
|
||||
// Setup playtime event listeners
|
||||
const { setupEventListeners } = usePlaytime();
|
||||
setupEventListeners();
|
||||
|
||||
useHead({
|
||||
title: "Drop",
|
||||
});
|
||||
|
||||
53
main/components/PlaytimeDisplay.vue
Normal file
53
main/components/PlaytimeDisplay.vue
Normal file
@ -0,0 +1,53 @@
|
||||
<template>
|
||||
<div v-if="stats" class="flex flex-col gap-1">
|
||||
<!-- Main playtime display -->
|
||||
<div class="flex items-center gap-2">
|
||||
<ClockIcon class="w-5 h-5 text-zinc-400" />
|
||||
<span class="text-base text-zinc-300 font-medium">
|
||||
{{ formatPlaytime(stats.totalPlaytimeSeconds) }} played
|
||||
</span>
|
||||
<span v-if="isActive && showActiveIndicator" class="text-sm text-green-400 font-medium">
|
||||
• Playing
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Additional details when expanded -->
|
||||
<div v-if="showDetails" class="text-xs text-zinc-400 space-y-1 ml-7">
|
||||
<div>{{ stats.sessionCount }} session{{ stats.sessionCount !== 1 ? 's' : '' }}</div>
|
||||
<div v-if="stats.sessionCount > 0">
|
||||
Avg: {{ formatPlaytime(stats.averageSessionLength) }} per session
|
||||
</div>
|
||||
<div v-if="stats.currentSessionDuration">
|
||||
Current session: {{ formatPlaytime(stats.currentSessionDuration) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- No playtime data -->
|
||||
<div v-else-if="showWhenEmpty" class="flex items-center gap-2 text-zinc-500">
|
||||
<ClockIcon class="w-5 h-5" />
|
||||
<span class="text-base">Never played</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ClockIcon } from "@heroicons/vue/20/solid";
|
||||
import type { GamePlaytimeStats } from "~/types";
|
||||
|
||||
interface Props {
|
||||
stats: GamePlaytimeStats | null;
|
||||
isActive?: boolean;
|
||||
showDetails?: boolean;
|
||||
showWhenEmpty?: boolean;
|
||||
showActiveIndicator?: boolean;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
isActive: false,
|
||||
showDetails: false,
|
||||
showWhenEmpty: true,
|
||||
showActiveIndicator: true,
|
||||
});
|
||||
|
||||
const { formatPlaytime } = usePlaytime();
|
||||
</script>
|
||||
76
main/components/PlaytimeStats.vue
Normal file
76
main/components/PlaytimeStats.vue
Normal file
@ -0,0 +1,76 @@
|
||||
<template>
|
||||
<div class="bg-zinc-800/50 rounded-lg p-4 space-y-4">
|
||||
<div class="flex items-center gap-2">
|
||||
<ChartBarIcon class="w-5 h-5 text-zinc-400" />
|
||||
<h3 class="text-lg font-semibold text-zinc-100">Playtime Statistics</h3>
|
||||
</div>
|
||||
|
||||
<div v-if="stats" class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<!-- Total Playtime -->
|
||||
<div class="bg-zinc-700/50 rounded-lg p-3">
|
||||
<div class="flex items-center gap-2 mb-2">
|
||||
<ClockIcon class="w-4 h-4 text-blue-400" />
|
||||
<span class="text-sm font-medium text-zinc-300">Total Playtime</span>
|
||||
</div>
|
||||
<div class="text-2xl font-bold text-zinc-100">
|
||||
{{ formatDetailedPlaytime(stats.totalPlaytimeSeconds) }}
|
||||
</div>
|
||||
<div v-if="stats.currentSessionDuration" class="text-xs text-green-400 mt-1">
|
||||
+{{ formatPlaytime(stats.currentSessionDuration) }} this session
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Sessions -->
|
||||
<div class="bg-zinc-700/50 rounded-lg p-3">
|
||||
<div class="flex items-center gap-2 mb-2">
|
||||
<PlayIcon class="w-4 h-4 text-green-400" />
|
||||
<span class="text-sm font-medium text-zinc-300">Sessions</span>
|
||||
</div>
|
||||
<div class="text-2xl font-bold text-zinc-100">
|
||||
{{ stats.sessionCount }}
|
||||
</div>
|
||||
<div class="text-xs text-zinc-400 mt-1">
|
||||
Avg: {{ formatPlaytime(stats.averageSessionLength) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- No stats available -->
|
||||
<div v-else class="text-center py-8">
|
||||
<ClockIcon class="w-12 h-12 text-zinc-600 mx-auto mb-3" />
|
||||
<p class="text-zinc-400">No playtime data available</p>
|
||||
<p class="text-sm text-zinc-500 mt-1">Statistics will appear after you start playing</p>
|
||||
</div>
|
||||
|
||||
<!-- Current session indicator -->
|
||||
<div v-if="isActive && stats" class="border-t border-zinc-700 pt-3">
|
||||
<div class="flex items-center gap-2 text-green-400">
|
||||
<div class="w-2 h-2 bg-green-400 rounded-full animate-pulse"></div>
|
||||
<span class="text-sm font-medium">Currently playing</span>
|
||||
<span v-if="stats.currentSessionDuration" class="text-xs text-zinc-400">
|
||||
{{ formatPlaytime(stats.currentSessionDuration) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
ChartBarIcon,
|
||||
ClockIcon,
|
||||
PlayIcon
|
||||
} from "@heroicons/vue/20/solid";
|
||||
import type { GamePlaytimeStats } from "~/types";
|
||||
|
||||
interface Props {
|
||||
stats: GamePlaytimeStats | null;
|
||||
isActive?: boolean;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
isActive: false,
|
||||
});
|
||||
|
||||
const { formatPlaytime, formatDetailedPlaytime } = usePlaytime();
|
||||
</script>
|
||||
193
main/composables/playtime.ts
Normal file
193
main/composables/playtime.ts
Normal file
@ -0,0 +1,193 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import type {
|
||||
GamePlaytimeStats,
|
||||
PlaytimeUpdateEvent,
|
||||
PlaytimeSessionStartEvent,
|
||||
PlaytimeSessionEndEvent
|
||||
} from "~/types";
|
||||
|
||||
export const usePlaytime = () => {
|
||||
const playtimeStats = useState<Record<string, GamePlaytimeStats>>('playtime-stats', () => ({}));
|
||||
const activeSessions = useState<Set<string>>('active-sessions', () => new Set());
|
||||
|
||||
// Fetch playtime stats for a specific game
|
||||
const fetchGamePlaytime = async (gameId: string): Promise<GamePlaytimeStats | null> => {
|
||||
try {
|
||||
const stats = await invoke<GamePlaytimeStats | null>("fetch_game_playtime", { gameId });
|
||||
if (stats) {
|
||||
playtimeStats.value[gameId] = stats;
|
||||
}
|
||||
return stats;
|
||||
} catch (error) {
|
||||
console.error(`Failed to fetch playtime for game ${gameId}:`, error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// Fetch all playtime stats
|
||||
const fetchAllPlaytimeStats = async (): Promise<Record<string, GamePlaytimeStats>> => {
|
||||
try {
|
||||
const stats = await invoke<Record<string, GamePlaytimeStats>>("fetch_all_playtime_stats");
|
||||
playtimeStats.value = stats;
|
||||
return stats;
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch all playtime stats:", error);
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
// Check if a session is active
|
||||
const isSessionActive = async (gameId: string): Promise<boolean> => {
|
||||
try {
|
||||
return await invoke<boolean>("is_playtime_session_active", { gameId });
|
||||
} catch (error) {
|
||||
console.error(`Failed to check session status for game ${gameId}:`, error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Get all active sessions
|
||||
const getActiveSessions = async (): Promise<string[]> => {
|
||||
try {
|
||||
const sessions = await invoke<string[]>("get_active_playtime_sessions");
|
||||
activeSessions.value = new Set(sessions);
|
||||
return sessions;
|
||||
} catch (error) {
|
||||
console.error("Failed to get active sessions:", error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
// Format playtime duration
|
||||
const formatPlaytime = (seconds: number): string => {
|
||||
if (seconds < 60) {
|
||||
return `${seconds}s`;
|
||||
} else if (seconds < 3600) {
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
return `${minutes}m`;
|
||||
} else {
|
||||
const hours = Math.floor(seconds / 3600);
|
||||
const minutes = Math.floor((seconds % 3600) / 60);
|
||||
if (minutes === 0) {
|
||||
return `${hours}h`;
|
||||
}
|
||||
return `${hours}h ${minutes}m`;
|
||||
}
|
||||
};
|
||||
|
||||
// Format detailed playtime
|
||||
const formatDetailedPlaytime = (seconds: number): string => {
|
||||
if (seconds < 60) {
|
||||
return `${seconds} seconds`;
|
||||
} else if (seconds < 3600) {
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const remainingSeconds = seconds % 60;
|
||||
if (remainingSeconds === 0) {
|
||||
return `${minutes} minutes`;
|
||||
}
|
||||
return `${minutes} minutes, ${remainingSeconds} seconds`;
|
||||
} else {
|
||||
const hours = Math.floor(seconds / 3600);
|
||||
const minutes = Math.floor((seconds % 3600) / 60);
|
||||
if (minutes === 0) {
|
||||
return `${hours} hours`;
|
||||
}
|
||||
return `${hours} hours, ${minutes} minutes`;
|
||||
}
|
||||
};
|
||||
|
||||
// Format relative time (e.g., "2 hours ago")
|
||||
const formatRelativeTime = (timestamp: string): string => {
|
||||
const date = new Date(timestamp);
|
||||
const now = new Date();
|
||||
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
|
||||
|
||||
if (diffInSeconds < 60) {
|
||||
return "Just now";
|
||||
} else if (diffInSeconds < 3600) {
|
||||
const minutes = Math.floor(diffInSeconds / 60);
|
||||
return `${minutes} minute${minutes !== 1 ? 's' : ''} ago`;
|
||||
} else if (diffInSeconds < 86400) {
|
||||
const hours = Math.floor(diffInSeconds / 3600);
|
||||
return `${hours} hour${hours !== 1 ? 's' : ''} ago`;
|
||||
} else if (diffInSeconds < 604800) {
|
||||
const days = Math.floor(diffInSeconds / 86400);
|
||||
return `${days} day${days !== 1 ? 's' : ''} ago`;
|
||||
} else {
|
||||
return date.toLocaleDateString();
|
||||
}
|
||||
};
|
||||
|
||||
// Get playtime stats for a game (from cache or fetch)
|
||||
const getGamePlaytime = async (gameId: string): Promise<GamePlaytimeStats | null> => {
|
||||
if (playtimeStats.value[gameId]) {
|
||||
return playtimeStats.value[gameId];
|
||||
}
|
||||
return await fetchGamePlaytime(gameId);
|
||||
};
|
||||
|
||||
// Setup event listeners
|
||||
const setupEventListeners = () => {
|
||||
// Listen for general playtime updates
|
||||
listen<PlaytimeUpdateEvent>("playtime_update", (event) => {
|
||||
const { gameId, stats, isActive } = event.payload;
|
||||
playtimeStats.value[gameId] = stats;
|
||||
|
||||
if (isActive) {
|
||||
activeSessions.value.add(gameId);
|
||||
} else {
|
||||
activeSessions.value.delete(gameId);
|
||||
}
|
||||
});
|
||||
|
||||
// Listen for session start events
|
||||
listen<PlaytimeSessionStartEvent>("playtime_session_start", (event) => {
|
||||
const { gameId } = event.payload;
|
||||
activeSessions.value.add(gameId);
|
||||
});
|
||||
|
||||
// Listen for session end events
|
||||
listen<PlaytimeSessionEndEvent>("playtime_session_end", (event) => {
|
||||
const { gameId } = event.payload;
|
||||
activeSessions.value.delete(gameId);
|
||||
});
|
||||
};
|
||||
|
||||
// Setup game-specific event listeners
|
||||
const setupGameEventListeners = (gameId: string) => {
|
||||
listen<PlaytimeUpdateEvent>(`playtime_update/${gameId}`, (event) => {
|
||||
const { stats, isActive } = event.payload;
|
||||
playtimeStats.value[gameId] = stats;
|
||||
|
||||
if (isActive) {
|
||||
activeSessions.value.add(gameId);
|
||||
} else {
|
||||
activeSessions.value.delete(gameId);
|
||||
}
|
||||
});
|
||||
|
||||
listen<PlaytimeSessionStartEvent>(`playtime_session_start/${gameId}`, () => {
|
||||
activeSessions.value.add(gameId);
|
||||
});
|
||||
|
||||
listen<PlaytimeSessionEndEvent>(`playtime_session_end/${gameId}`, () => {
|
||||
activeSessions.value.delete(gameId);
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
playtimeStats: readonly(playtimeStats),
|
||||
activeSessions: readonly(activeSessions),
|
||||
fetchGamePlaytime,
|
||||
fetchAllPlaytimeStats,
|
||||
isSessionActive,
|
||||
getActiveSessions,
|
||||
formatPlaytime,
|
||||
formatDetailedPlaytime,
|
||||
formatRelativeTime,
|
||||
getGamePlaytime,
|
||||
setupEventListeners,
|
||||
setupGameEventListeners,
|
||||
};
|
||||
};
|
||||
@ -18,10 +18,20 @@
|
||||
<div class="relative z-10">
|
||||
<div class="px-8 pb-4">
|
||||
<h1
|
||||
class="text-5xl text-zinc-100 font-bold font-display drop-shadow-lg mb-8"
|
||||
class="text-5xl text-zinc-100 font-bold font-display drop-shadow-lg mb-4"
|
||||
>
|
||||
{{ game.mName }}
|
||||
</h1>
|
||||
|
||||
<!-- Playtime Display -->
|
||||
<div class="mb-8">
|
||||
<PlaytimeDisplay
|
||||
:stats="gamePlaytime"
|
||||
:is-active="isPlaytimeActive"
|
||||
:show-details="false"
|
||||
:show-active-indicator="false"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-row gap-x-4 items-stretch mb-8">
|
||||
<!-- Do not add scale animations to this: https://stackoverflow.com/a/35683068 -->
|
||||
@ -60,6 +70,12 @@
|
||||
</div>
|
||||
|
||||
<div class="space-y-6">
|
||||
<!-- Playtime Statistics -->
|
||||
<PlaytimeStats
|
||||
:stats="gamePlaytime"
|
||||
:is-active="isPlaytimeActive"
|
||||
/>
|
||||
|
||||
<div class="bg-zinc-800/50 rounded-xl p-6 backdrop-blur-sm">
|
||||
<h2 class="text-xl font-display font-semibold text-zinc-100 mb-4">
|
||||
Game Images
|
||||
@ -528,6 +544,19 @@ const currentImageIndex = ref(0);
|
||||
|
||||
const configureModalOpen = ref(false);
|
||||
|
||||
// Playtime tracking
|
||||
const {
|
||||
getGamePlaytime,
|
||||
setupGameEventListeners,
|
||||
activeSessions
|
||||
} = usePlaytime();
|
||||
|
||||
const gamePlaytime = ref(await getGamePlaytime(id));
|
||||
const isPlaytimeActive = computed(() => activeSessions.value.has(id));
|
||||
|
||||
// Setup playtime event listeners for this game
|
||||
setupGameEventListeners(id);
|
||||
|
||||
async function installFlow() {
|
||||
installFlowOpen.value = true;
|
||||
versionOptions.value = undefined;
|
||||
|
||||
@ -94,3 +94,37 @@ export type Settings = {
|
||||
maxDownloadThreads: number;
|
||||
forceOffline: boolean;
|
||||
};
|
||||
|
||||
export type GamePlaytimeStats = {
|
||||
gameId: string;
|
||||
totalPlaytimeSeconds: number;
|
||||
sessionCount: number;
|
||||
firstPlayed: string;
|
||||
lastPlayed: string;
|
||||
averageSessionLength: number;
|
||||
currentSessionDuration?: number;
|
||||
};
|
||||
|
||||
export type PlaytimeSession = {
|
||||
gameId: string;
|
||||
startTime: string;
|
||||
sessionId: string;
|
||||
};
|
||||
|
||||
export type PlaytimeUpdateEvent = {
|
||||
gameId: string;
|
||||
stats: GamePlaytimeStats;
|
||||
isActive: boolean;
|
||||
};
|
||||
|
||||
export type PlaytimeSessionStartEvent = {
|
||||
gameId: string;
|
||||
startTime: string;
|
||||
};
|
||||
|
||||
export type PlaytimeSessionEndEvent = {
|
||||
gameId: string;
|
||||
sessionDurationSeconds: number;
|
||||
totalPlaytimeSeconds: number;
|
||||
sessionCount: number;
|
||||
};
|
||||
@ -8,7 +8,7 @@ pub mod data {
|
||||
// Declare it using the actual version that it is from, i.e. v1::Settings rather than just Settings from here
|
||||
|
||||
pub type GameVersion = v1::GameVersion;
|
||||
pub type Database = v3::Database;
|
||||
pub type Database = v4::Database;
|
||||
pub type Settings = v1::Settings;
|
||||
pub type DatabaseAuth = v1::DatabaseAuth;
|
||||
|
||||
@ -20,7 +20,10 @@ pub mod data {
|
||||
pub type DownloadableMetadata = v1::DownloadableMetadata;
|
||||
pub type DownloadType = v1::DownloadType;
|
||||
pub type DatabaseApplications = v2::DatabaseApplications;
|
||||
// pub type DatabaseCompatInfo = v2::DatabaseCompatInfo;
|
||||
//pub type DatabaseCompatInfo = v2::DatabaseCompatInfo;
|
||||
pub type PlaytimeData = v4::PlaytimeData;
|
||||
pub type GamePlaytimeStats = v4::GamePlaytimeStats;
|
||||
pub type PlaytimeSession = v4::PlaytimeSession;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
@ -355,6 +358,108 @@ pub mod data {
|
||||
settings: Settings::default(),
|
||||
cache_dir,
|
||||
compat_info: None,
|
||||
playtime_data: PlaytimeData::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod v4 {
|
||||
use std::{collections::HashMap, path::PathBuf, time::SystemTime};
|
||||
|
||||
use super::{
|
||||
DatabaseApplications, DatabaseAuth, DatabaseCompatInfo, Deserialize, Serialize,
|
||||
Settings, native_model, v3,
|
||||
};
|
||||
|
||||
#[native_model(id = 1, version = 4, with = native_model::rmp_serde_1_3::RmpSerde)]
|
||||
#[derive(Serialize, Deserialize, Clone, Default)]
|
||||
pub struct Database {
|
||||
#[serde(default)]
|
||||
pub settings: Settings,
|
||||
pub auth: Option<DatabaseAuth>,
|
||||
pub base_url: String,
|
||||
pub applications: DatabaseApplications,
|
||||
#[serde(skip)]
|
||||
pub prev_database: Option<PathBuf>,
|
||||
pub cache_dir: PathBuf,
|
||||
pub compat_info: Option<DatabaseCompatInfo>,
|
||||
#[serde(default)]
|
||||
pub playtime_data: PlaytimeData,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Default)]
|
||||
#[native_model(id = 9, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
||||
pub struct PlaytimeData {
|
||||
pub game_sessions: HashMap<String, GamePlaytimeStats>,
|
||||
#[serde(skip)]
|
||||
pub active_sessions: HashMap<String, PlaytimeSession>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
#[native_model(id = 10, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
||||
pub struct GamePlaytimeStats {
|
||||
pub game_id: String,
|
||||
pub total_playtime_seconds: u64,
|
||||
pub session_count: u32,
|
||||
pub first_played: SystemTime,
|
||||
pub last_played: SystemTime,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
#[native_model(id = 11, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
||||
pub struct PlaytimeSession {
|
||||
pub game_id: String,
|
||||
pub start_time: SystemTime,
|
||||
pub session_id: String,
|
||||
}
|
||||
|
||||
impl GamePlaytimeStats {
|
||||
pub fn new(game_id: String) -> Self {
|
||||
let now = SystemTime::now();
|
||||
Self {
|
||||
game_id,
|
||||
total_playtime_seconds: 0,
|
||||
session_count: 0,
|
||||
first_played: now,
|
||||
last_played: now,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn average_session_length(&self) -> u64 {
|
||||
if self.session_count == 0 {
|
||||
0
|
||||
} else {
|
||||
self.total_playtime_seconds / self.session_count as u64
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PlaytimeSession {
|
||||
pub fn new(game_id: String) -> Self {
|
||||
Self {
|
||||
game_id,
|
||||
start_time: SystemTime::now(),
|
||||
session_id: uuid::Uuid::new_v4().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn duration(&self) -> std::time::Duration {
|
||||
self.start_time.elapsed().unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<v3::Database> for Database {
|
||||
fn from(value: v3::Database) -> Self {
|
||||
Self {
|
||||
settings: value.settings,
|
||||
auth: value.auth,
|
||||
base_url: value.base_url,
|
||||
applications: value.applications,
|
||||
prev_database: value.prev_database,
|
||||
cache_dir: value.cache_dir,
|
||||
compat_info: value.compat_info,
|
||||
playtime_data: PlaytimeData::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -11,7 +11,8 @@ pub enum ProcessError {
|
||||
IOError(Error),
|
||||
FormatError(String), // String errors supremacy
|
||||
InvalidPlatform,
|
||||
OpenerError(tauri_plugin_opener::Error)
|
||||
OpenerError(tauri_plugin_opener::Error),
|
||||
PlaytimeError(String),
|
||||
}
|
||||
|
||||
impl Display for ProcessError {
|
||||
@ -25,6 +26,7 @@ impl Display for ProcessError {
|
||||
ProcessError::InvalidPlatform => "This game cannot be played on the current platform",
|
||||
ProcessError::FormatError(e) => &format!("Failed to format template: {e}"),
|
||||
ProcessError::OpenerError(error) => &format!("Failed to open directory: {error}"),
|
||||
ProcessError::PlaytimeError(error) => &format!("Playtime tracking error: {error}"),
|
||||
};
|
||||
write!(f, "{s}")
|
||||
}
|
||||
|
||||
@ -11,6 +11,7 @@ mod games;
|
||||
mod client;
|
||||
mod download_manager;
|
||||
mod error;
|
||||
mod playtime;
|
||||
mod process;
|
||||
mod remote;
|
||||
|
||||
@ -46,6 +47,12 @@ use games::commands::{
|
||||
use games::downloads::commands::download_game;
|
||||
use games::library::{Game, update_game_configuration};
|
||||
use log::{LevelFilter, debug, info, warn};
|
||||
use playtime::manager::PlaytimeManager;
|
||||
use playtime::commands::{
|
||||
start_playtime_tracking, end_playtime_tracking, fetch_game_playtime,
|
||||
fetch_all_playtime_stats, is_playtime_session_active, get_active_playtime_sessions,
|
||||
cleanup_orphaned_playtime_sessions
|
||||
};
|
||||
use log4rs::Config;
|
||||
use log4rs::append::console::ConsoleAppender;
|
||||
use log4rs::append::file::FileAppender;
|
||||
@ -127,7 +134,11 @@ pub struct AppState<'a> {
|
||||
#[serde(skip_serializing)]
|
||||
process_manager: Arc<Mutex<ProcessManager<'a>>>,
|
||||
#[serde(skip_serializing)]
|
||||
playtime_manager: Arc<Mutex<PlaytimeManager>>,
|
||||
#[serde(skip_serializing)]
|
||||
compat_info: Option<CompatInfo>,
|
||||
#[serde(skip_serializing)]
|
||||
app_handle: AppHandle,
|
||||
}
|
||||
|
||||
async fn setup(handle: AppHandle) -> AppState<'static> {
|
||||
@ -164,6 +175,7 @@ async fn setup(handle: AppHandle) -> AppState<'static> {
|
||||
let games = HashMap::new();
|
||||
let download_manager = Arc::new(DownloadManagerBuilder::build(handle.clone()));
|
||||
let process_manager = Arc::new(Mutex::new(ProcessManager::new(handle.clone())));
|
||||
let playtime_manager = Arc::new(Mutex::new(PlaytimeManager::new(handle.clone())));
|
||||
let compat_info = create_new_compat_info();
|
||||
|
||||
debug!("checking if database is set up");
|
||||
@ -178,7 +190,9 @@ async fn setup(handle: AppHandle) -> AppState<'static> {
|
||||
games,
|
||||
download_manager,
|
||||
process_manager,
|
||||
playtime_manager,
|
||||
compat_info,
|
||||
app_handle: handle.clone(),
|
||||
};
|
||||
}
|
||||
|
||||
@ -237,13 +251,20 @@ async fn setup(handle: AppHandle) -> AppState<'static> {
|
||||
warn!("failed to sync autostart state: {e}");
|
||||
}
|
||||
|
||||
// Clean up any orphaned playtime sessions
|
||||
if let Err(e) = playtime_manager.lock().unwrap().cleanup_orphaned_sessions() {
|
||||
warn!("failed to cleanup orphaned playtime sessions: {e}");
|
||||
}
|
||||
|
||||
AppState {
|
||||
status: app_status,
|
||||
user,
|
||||
games,
|
||||
download_manager,
|
||||
process_manager,
|
||||
playtime_manager,
|
||||
compat_info,
|
||||
app_handle: handle.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@ -334,7 +355,15 @@ pub fn run() {
|
||||
kill_game,
|
||||
toggle_autostart,
|
||||
get_autostart_enabled,
|
||||
open_process_logs
|
||||
open_process_logs,
|
||||
// Playtime tracking
|
||||
start_playtime_tracking,
|
||||
end_playtime_tracking,
|
||||
fetch_game_playtime,
|
||||
fetch_all_playtime_stats,
|
||||
is_playtime_session_active,
|
||||
get_active_playtime_sessions,
|
||||
cleanup_orphaned_playtime_sessions
|
||||
])
|
||||
.plugin(tauri_plugin_shell::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
|
||||
95
src-tauri/src/playtime/commands.rs
Normal file
95
src-tauri/src/playtime/commands.rs
Normal file
@ -0,0 +1,95 @@
|
||||
use std::collections::HashMap;
|
||||
use tauri::State;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use crate::AppState;
|
||||
use super::manager::PlaytimeStats;
|
||||
use super::events::{push_playtime_update, push_session_start, push_session_end};
|
||||
|
||||
#[tauri::command]
|
||||
pub fn start_playtime_tracking(
|
||||
game_id: String,
|
||||
state: State<'_, Mutex<AppState<'_>>>,
|
||||
) -> Result<(), String> {
|
||||
let state_lock = state.lock().unwrap();
|
||||
let playtime_manager_lock = state_lock.playtime_manager.lock().unwrap();
|
||||
|
||||
match playtime_manager_lock.start_session(game_id.clone()) {
|
||||
Ok(()) => {
|
||||
push_session_start(&state_lock.app_handle, &game_id);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn end_playtime_tracking(
|
||||
game_id: String,
|
||||
state: State<'_, Mutex<AppState<'_>>>,
|
||||
) -> Result<PlaytimeStats, String> {
|
||||
let state_lock = state.lock().unwrap();
|
||||
let playtime_manager_lock = state_lock.playtime_manager.lock().unwrap();
|
||||
|
||||
match playtime_manager_lock.end_session(game_id.clone()) {
|
||||
Ok(stats) => {
|
||||
push_session_end(&state_lock.app_handle, &game_id, &stats);
|
||||
push_playtime_update(&state_lock.app_handle, &game_id, stats.clone(), false);
|
||||
Ok(stats)
|
||||
}
|
||||
Err(e) => Err(e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn fetch_game_playtime(
|
||||
game_id: String,
|
||||
state: State<'_, Mutex<AppState<'_>>>,
|
||||
) -> Result<Option<PlaytimeStats>, String> {
|
||||
let state_lock = state.lock().unwrap();
|
||||
let playtime_manager_lock = state_lock.playtime_manager.lock().unwrap();
|
||||
|
||||
Ok(playtime_manager_lock.get_game_stats(&game_id))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn fetch_all_playtime_stats(
|
||||
state: State<'_, Mutex<AppState<'_>>>,
|
||||
) -> Result<HashMap<String, PlaytimeStats>, String> {
|
||||
let state_lock = state.lock().unwrap();
|
||||
let playtime_manager_lock = state_lock.playtime_manager.lock().unwrap();
|
||||
|
||||
Ok(playtime_manager_lock.get_all_stats())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn is_playtime_session_active(
|
||||
game_id: String,
|
||||
state: State<'_, Mutex<AppState<'_>>>,
|
||||
) -> Result<bool, String> {
|
||||
let state_lock = state.lock().unwrap();
|
||||
let playtime_manager_lock = state_lock.playtime_manager.lock().unwrap();
|
||||
|
||||
Ok(playtime_manager_lock.is_session_active(&game_id))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_active_playtime_sessions(
|
||||
state: State<'_, Mutex<AppState<'_>>>,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let state_lock = state.lock().unwrap();
|
||||
let playtime_manager_lock = state_lock.playtime_manager.lock().unwrap();
|
||||
|
||||
Ok(playtime_manager_lock.get_active_sessions())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn cleanup_orphaned_playtime_sessions(
|
||||
state: State<'_, Mutex<AppState<'_>>>,
|
||||
) -> Result<(), String> {
|
||||
let state_lock = state.lock().unwrap();
|
||||
let playtime_manager_lock = state_lock.playtime_manager.lock().unwrap();
|
||||
|
||||
playtime_manager_lock.cleanup_orphaned_sessions()
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
81
src-tauri/src/playtime/events.rs
Normal file
81
src-tauri/src/playtime/events.rs
Normal file
@ -0,0 +1,81 @@
|
||||
use serde::Serialize;
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use log::warn;
|
||||
|
||||
use super::manager::PlaytimeStats;
|
||||
|
||||
#[derive(Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PlaytimeUpdateEvent {
|
||||
pub game_id: String,
|
||||
pub stats: PlaytimeStats,
|
||||
pub is_active: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PlaytimeSessionStartEvent {
|
||||
pub game_id: String,
|
||||
pub start_time: std::time::SystemTime,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PlaytimeSessionEndEvent {
|
||||
pub game_id: String,
|
||||
pub session_duration_seconds: u64,
|
||||
pub total_playtime_seconds: u64,
|
||||
pub session_count: u32,
|
||||
}
|
||||
|
||||
/// Push a playtime update event to the frontend
|
||||
pub fn push_playtime_update(app_handle: &AppHandle, game_id: &str, stats: PlaytimeStats, is_active: bool) {
|
||||
let event = PlaytimeUpdateEvent {
|
||||
game_id: game_id.to_string(),
|
||||
stats,
|
||||
is_active,
|
||||
};
|
||||
|
||||
if let Err(e) = app_handle.emit(&format!("playtime_update/{}", game_id), &event) {
|
||||
warn!("Failed to emit playtime update event for {}: {}", game_id, e);
|
||||
}
|
||||
|
||||
// Also emit a general playtime update event for global listeners
|
||||
if let Err(e) = app_handle.emit("playtime_update", &event) {
|
||||
warn!("Failed to emit general playtime update event: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Push a session start event to the frontend
|
||||
pub fn push_session_start(app_handle: &AppHandle, game_id: &str) {
|
||||
let event = PlaytimeSessionStartEvent {
|
||||
game_id: game_id.to_string(),
|
||||
start_time: std::time::SystemTime::now(),
|
||||
};
|
||||
|
||||
if let Err(e) = app_handle.emit(&format!("playtime_session_start/{}", game_id), &event) {
|
||||
warn!("Failed to emit session start event for {}: {}", game_id, e);
|
||||
}
|
||||
|
||||
if let Err(e) = app_handle.emit("playtime_session_start", &event) {
|
||||
warn!("Failed to emit general session start event: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Push a session end event to the frontend
|
||||
pub fn push_session_end(app_handle: &AppHandle, game_id: &str, stats: &PlaytimeStats) {
|
||||
let event = PlaytimeSessionEndEvent {
|
||||
game_id: game_id.to_string(),
|
||||
session_duration_seconds: stats.current_session_duration.unwrap_or(0),
|
||||
total_playtime_seconds: stats.total_playtime_seconds,
|
||||
session_count: stats.session_count,
|
||||
};
|
||||
|
||||
if let Err(e) = app_handle.emit(&format!("playtime_session_end/{}", game_id), &event) {
|
||||
warn!("Failed to emit session end event for {}: {}", game_id, e);
|
||||
}
|
||||
|
||||
if let Err(e) = app_handle.emit("playtime_session_end", &event) {
|
||||
warn!("Failed to emit general session end event: {}", e);
|
||||
}
|
||||
}
|
||||
255
src-tauri/src/playtime/manager.rs
Normal file
255
src-tauri/src/playtime/manager.rs
Normal file
@ -0,0 +1,255 @@
|
||||
use std::collections::HashMap;
|
||||
use std::time::SystemTime;
|
||||
use std::fmt;
|
||||
|
||||
use log::{debug, warn};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::AppHandle;
|
||||
|
||||
use crate::database::db::{borrow_db_checked, borrow_db_mut_checked};
|
||||
use crate::database::models::data::{GamePlaytimeStats, PlaytimeSession};
|
||||
use crate::error::process_error::ProcessError;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum PlaytimeError {
|
||||
DatabaseError(String),
|
||||
SessionNotFound(String),
|
||||
SessionAlreadyActive(String),
|
||||
InvalidGameId(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for PlaytimeError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
PlaytimeError::DatabaseError(msg) => write!(f, "Database error: {}", msg),
|
||||
PlaytimeError::SessionNotFound(game_id) => write!(f, "Session not found for game: {}", game_id),
|
||||
PlaytimeError::SessionAlreadyActive(game_id) => write!(f, "Session already active for game: {}", game_id),
|
||||
PlaytimeError::InvalidGameId(game_id) => write!(f, "Invalid game ID: {}", game_id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for PlaytimeError {}
|
||||
|
||||
impl From<PlaytimeError> for ProcessError {
|
||||
fn from(error: PlaytimeError) -> Self {
|
||||
ProcessError::PlaytimeError(error.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PlaytimeStats {
|
||||
pub game_id: String,
|
||||
pub total_playtime_seconds: u64,
|
||||
pub session_count: u32,
|
||||
pub first_played: SystemTime,
|
||||
pub last_played: SystemTime,
|
||||
pub average_session_length: u64,
|
||||
pub current_session_duration: Option<u64>,
|
||||
}
|
||||
|
||||
impl From<GamePlaytimeStats> for PlaytimeStats {
|
||||
fn from(stats: GamePlaytimeStats) -> Self {
|
||||
let average_length = stats.average_session_length();
|
||||
Self {
|
||||
game_id: stats.game_id,
|
||||
total_playtime_seconds: stats.total_playtime_seconds,
|
||||
session_count: stats.session_count,
|
||||
first_played: stats.first_played,
|
||||
last_played: stats.last_played,
|
||||
average_session_length: average_length,
|
||||
current_session_duration: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PlaytimeManager {
|
||||
app_handle: AppHandle,
|
||||
}
|
||||
|
||||
impl PlaytimeManager {
|
||||
pub fn new(app_handle: AppHandle) -> Self {
|
||||
Self { app_handle }
|
||||
}
|
||||
|
||||
/// Start tracking playtime for a game
|
||||
pub fn start_session(&self, game_id: String) -> Result<(), PlaytimeError> {
|
||||
debug!("Starting playtime session for game: {}", game_id);
|
||||
|
||||
let mut db_handle = borrow_db_mut_checked();
|
||||
|
||||
// Check if session is already active
|
||||
if db_handle.playtime_data.active_sessions.contains_key(&game_id) {
|
||||
warn!("Session already active for game: {}", game_id);
|
||||
return Err(PlaytimeError::SessionAlreadyActive(game_id));
|
||||
}
|
||||
|
||||
// Create new session
|
||||
let session = PlaytimeSession::new(game_id.clone());
|
||||
db_handle.playtime_data.active_sessions.insert(game_id.clone(), session);
|
||||
|
||||
debug!("Started playtime tracking for game: {}", game_id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// End tracking playtime for a game and update stats
|
||||
pub fn end_session(&self, game_id: String) -> Result<PlaytimeStats, PlaytimeError> {
|
||||
debug!("Ending playtime session for game: {}", game_id);
|
||||
|
||||
let mut db_handle = borrow_db_mut_checked();
|
||||
|
||||
// Get active session
|
||||
let session = db_handle.playtime_data.active_sessions.remove(&game_id)
|
||||
.ok_or_else(|| PlaytimeError::SessionNotFound(game_id.clone()))?;
|
||||
|
||||
let session_duration = session.duration().as_secs();
|
||||
debug!("Session duration for {}: {} seconds", game_id, session_duration);
|
||||
|
||||
// Update or create game stats
|
||||
let stats = db_handle.playtime_data.game_sessions
|
||||
.entry(game_id.clone())
|
||||
.or_insert_with(|| GamePlaytimeStats::new(game_id.clone()));
|
||||
|
||||
// Update stats
|
||||
stats.total_playtime_seconds += session_duration;
|
||||
stats.session_count += 1;
|
||||
stats.last_played = SystemTime::now();
|
||||
|
||||
// If this is the first session, update first_played
|
||||
if stats.session_count == 1 {
|
||||
stats.first_played = session.start_time;
|
||||
}
|
||||
|
||||
let result_stats = PlaytimeStats {
|
||||
game_id: stats.game_id.clone(),
|
||||
total_playtime_seconds: stats.total_playtime_seconds,
|
||||
session_count: stats.session_count,
|
||||
first_played: stats.first_played,
|
||||
last_played: stats.last_played,
|
||||
average_session_length: stats.average_session_length(),
|
||||
current_session_duration: Some(session_duration),
|
||||
};
|
||||
|
||||
debug!("Updated playtime stats for {}: {} total seconds, {} sessions",
|
||||
game_id, stats.total_playtime_seconds, stats.session_count);
|
||||
|
||||
Ok(result_stats)
|
||||
}
|
||||
|
||||
/// Get playtime stats for a specific game
|
||||
pub fn get_game_stats(&self, game_id: &str) -> Option<PlaytimeStats> {
|
||||
let db_handle = borrow_db_checked();
|
||||
|
||||
if let Some(stats) = db_handle.playtime_data.game_sessions.get(game_id) {
|
||||
let mut playtime_stats: PlaytimeStats = stats.clone().into();
|
||||
|
||||
// If there's an active session, include current session duration
|
||||
if let Some(session) = db_handle.playtime_data.active_sessions.get(game_id) {
|
||||
playtime_stats.current_session_duration = Some(session.duration().as_secs());
|
||||
}
|
||||
|
||||
Some(playtime_stats)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Get playtime stats for all games
|
||||
pub fn get_all_stats(&self) -> HashMap<String, PlaytimeStats> {
|
||||
let db_handle = borrow_db_checked();
|
||||
let mut result = HashMap::new();
|
||||
|
||||
for (game_id, stats) in &db_handle.playtime_data.game_sessions {
|
||||
let mut playtime_stats: PlaytimeStats = stats.clone().into();
|
||||
|
||||
// If there's an active session, include current session duration
|
||||
if let Some(session) = db_handle.playtime_data.active_sessions.get(game_id) {
|
||||
playtime_stats.current_session_duration = Some(session.duration().as_secs());
|
||||
}
|
||||
|
||||
result.insert(game_id.clone(), playtime_stats);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Check if a game has an active session
|
||||
pub fn is_session_active(&self, game_id: &str) -> bool {
|
||||
let db_handle = borrow_db_checked();
|
||||
db_handle.playtime_data.active_sessions.contains_key(game_id)
|
||||
}
|
||||
|
||||
/// Get active sessions (for debugging/monitoring)
|
||||
pub fn get_active_sessions(&self) -> Vec<String> {
|
||||
let db_handle = borrow_db_checked();
|
||||
db_handle.playtime_data.active_sessions.keys().cloned().collect()
|
||||
}
|
||||
|
||||
/// Clean up any orphaned sessions (called on startup)
|
||||
pub fn cleanup_orphaned_sessions(&self) -> Result<(), PlaytimeError> {
|
||||
debug!("Cleaning up orphaned playtime sessions");
|
||||
|
||||
let mut db_handle = borrow_db_mut_checked();
|
||||
let orphaned_sessions: Vec<String> = db_handle.playtime_data.active_sessions.keys().cloned().collect();
|
||||
|
||||
for game_id in orphaned_sessions {
|
||||
warn!("Found orphaned session for game: {}, ending it", game_id);
|
||||
|
||||
if let Some(session) = db_handle.playtime_data.active_sessions.remove(&game_id) {
|
||||
let session_duration = session.duration().as_secs();
|
||||
|
||||
// Only count sessions that lasted more than 5 seconds to avoid counting crashes
|
||||
if session_duration > 5 {
|
||||
let stats = db_handle.playtime_data.game_sessions
|
||||
.entry(game_id.clone())
|
||||
.or_insert_with(|| GamePlaytimeStats::new(game_id.clone()));
|
||||
|
||||
stats.total_playtime_seconds += session_duration;
|
||||
stats.session_count += 1;
|
||||
stats.last_played = SystemTime::now();
|
||||
|
||||
if stats.session_count == 1 {
|
||||
stats.first_played = session.start_time;
|
||||
}
|
||||
|
||||
debug!("Recovered orphaned session for {}: {} seconds", game_id, session_duration);
|
||||
} else {
|
||||
debug!("Discarded short orphaned session for {}: {} seconds", game_id, session_duration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Future server-side methods (ready for migration)
|
||||
|
||||
/// Start session with server sync (placeholder for future implementation)
|
||||
#[allow(dead_code)]
|
||||
pub async fn sync_session_start(&self, game_id: String) -> Result<(), PlaytimeError> {
|
||||
// For now, just call local method
|
||||
self.start_session(game_id)?;
|
||||
|
||||
// Future: Send to server
|
||||
// let response = self.api_client.post("/api/v1/playtime/start")
|
||||
// .json(&StartSessionRequest { game_id })
|
||||
// .send().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// End session with server sync (placeholder for future implementation)
|
||||
#[allow(dead_code)]
|
||||
pub async fn sync_session_end(&self, game_id: String) -> Result<PlaytimeStats, PlaytimeError> {
|
||||
// For now, just call local method
|
||||
let stats = self.end_session(game_id)?;
|
||||
|
||||
// Future: Send to server
|
||||
// let response = self.api_client.post("/api/v1/playtime/end")
|
||||
// .json(&EndSessionRequest { game_id, duration: stats.current_session_duration })
|
||||
// .send().await?;
|
||||
|
||||
Ok(stats)
|
||||
}
|
||||
}
|
||||
3
src-tauri/src/playtime/mod.rs
Normal file
3
src-tauri/src/playtime/mod.rs
Normal file
@ -0,0 +1,3 @@
|
||||
pub mod commands;
|
||||
pub mod events;
|
||||
pub mod manager;
|
||||
@ -16,14 +16,28 @@ pub fn launch_game(
|
||||
// download_type: DownloadType::Game,
|
||||
//};
|
||||
|
||||
match process_manager_lock.launch_process(id, &state_lock) {
|
||||
Ok(()) => {}
|
||||
Err(e) => return Err(e),
|
||||
match process_manager_lock.launch_process(id.clone(), &state_lock) {
|
||||
Ok(()) => {
|
||||
// Start playtime tracking after successful launch
|
||||
drop(process_manager_lock);
|
||||
|
||||
let playtime_manager_lock = state_lock.playtime_manager.lock().unwrap();
|
||||
if let Err(e) = playtime_manager_lock.start_session(id.clone()) {
|
||||
log::warn!("Failed to start playtime tracking for {}: {}", id, e);
|
||||
} else {
|
||||
log::debug!("Started playtime tracking for game: {}", id);
|
||||
crate::playtime::events::push_session_start(&state_lock.app_handle, &id);
|
||||
}
|
||||
drop(playtime_manager_lock);
|
||||
}
|
||||
Err(e) => {
|
||||
drop(process_manager_lock);
|
||||
drop(state_lock);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
drop(process_manager_lock);
|
||||
drop(state_lock);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@ -33,6 +47,18 @@ pub fn kill_game(
|
||||
state: tauri::State<'_, Mutex<AppState>>,
|
||||
) -> Result<(), ProcessError> {
|
||||
let state_lock = state.lock().unwrap();
|
||||
let mut process_manager_lock = state_lock.process_manager.lock().unwrap();
|
||||
|
||||
// End playtime tracking before killing the game
|
||||
drop(process_manager_lock);
|
||||
let playtime_manager_lock = state_lock.playtime_manager.lock().unwrap();
|
||||
if let Ok(stats) = playtime_manager_lock.end_session(game_id.clone()) {
|
||||
log::debug!("Ended playtime tracking for game: {} (manual kill)", game_id);
|
||||
crate::playtime::events::push_session_end(&state_lock.app_handle, &game_id, &stats);
|
||||
crate::playtime::events::push_playtime_update(&state_lock.app_handle, &game_id, stats, false);
|
||||
}
|
||||
drop(playtime_manager_lock);
|
||||
|
||||
let mut process_manager_lock = state_lock.process_manager.lock().unwrap();
|
||||
process_manager_lock
|
||||
.kill_game(game_id)
|
||||
|
||||
@ -29,6 +29,7 @@ use crate::{
|
||||
},
|
||||
error::process_error::ProcessError,
|
||||
games::{library::push_game_update, state::GameStatusManager},
|
||||
playtime::events::{push_session_end, push_playtime_update},
|
||||
process::{
|
||||
format::DropFormatArgs,
|
||||
process_handlers::{AsahiMuvmLauncher, NativeGameLauncher, UMULauncher},
|
||||
@ -394,6 +395,15 @@ impl ProcessManager<'_> {
|
||||
let app_state = wait_thread_apphandle.state::<Mutex<AppState>>();
|
||||
let app_state_handle = app_state.lock().unwrap();
|
||||
|
||||
// End playtime tracking before processing finish
|
||||
let playtime_manager_lock = app_state_handle.playtime_manager.lock().unwrap();
|
||||
if let Ok(stats) = playtime_manager_lock.end_session(wait_thread_game_id.id.clone()) {
|
||||
debug!("Ended playtime tracking for game: {} (process finished)", wait_thread_game_id.id);
|
||||
push_session_end(&app_state_handle.app_handle, &wait_thread_game_id.id, &stats);
|
||||
push_playtime_update(&app_state_handle.app_handle, &wait_thread_game_id.id, stats, false);
|
||||
}
|
||||
drop(playtime_manager_lock);
|
||||
|
||||
let mut process_manager_handle = app_state_handle.process_manager.lock().unwrap();
|
||||
process_manager_handle.on_process_finish(wait_thread_game_id.id, result);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user