mirror of
https://github.com/Drop-OSS/drop-app.git
synced 2025-11-13 00:02:41 +10:00
Compare commits
5 Commits
bigpicture
...
AdenMGB-sm
| Author | SHA1 | Date | |
|---|---|---|---|
| 40a490fda4 | |||
| 6d2b8c88e8 | |||
| 262c8505b7 | |||
| e798d258dc | |||
| 105b3e9bc4 |
4
.gitignore
vendored
4
.gitignore
vendored
@ -29,6 +29,4 @@ src-tauri/flamegraph.svg
|
|||||||
src-tauri/perf*
|
src-tauri/perf*
|
||||||
|
|
||||||
/*.AppImage
|
/*.AppImage
|
||||||
/squashfs-root
|
/squashfs-root
|
||||||
|
|
||||||
/target/
|
|
||||||
24
README.md
24
README.md
@ -1,21 +1,29 @@
|
|||||||
# Drop Desktop Client
|
# Drop App
|
||||||
|
|
||||||
The Drop Desktop Client is the companion app for [Drop](https://github.com/Drop-OSS/drop). It is the official & intended way to download and play games on your Drop server.
|
Drop app is the companion app for [Drop](https://github.com/Drop-OSS/drop). It uses a Tauri base with Nuxt 3 + TailwindCSS on top of it, so we can re-use components from the web UI.
|
||||||
|
|
||||||
## Internals
|
## Running
|
||||||
|
Before setting up the drop app, be sure that you have a server set up.
|
||||||
|
The instructions for this can be found on the [Drop Docs](https://docs.droposs.org/docs/guides/quickstart)
|
||||||
|
|
||||||
It uses a Tauri base with Nuxt 3 + TailwindCSS on top of it, so we can re-use components from the web UI.
|
## Current features
|
||||||
|
Currently supported are the following features:
|
||||||
|
- Signin (with custom server)
|
||||||
|
- Database registering & recovery
|
||||||
|
- Dynamic library fetching from server
|
||||||
|
- Installing & uninstalling games
|
||||||
|
- Download progress monitoring
|
||||||
|
- Launching / playing games
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
Before setting up a development environemnt, be sure that you have a server set up. The instructions for this can be found on the [Drop Docs](https://docs.droposs.org/docs/guides/quickstart).
|
|
||||||
|
|
||||||
Then, install dependencies with `yarn`. This'll install the custom builder's dependencies. Then, check everything works properly with `yarn tauri build`.
|
Install dependencies with `yarn`
|
||||||
|
|
||||||
Run the app in development with `yarn tauri dev`. NVIDIA users on Linux, use shell script `./nvidia-prop-dev.sh`
|
Run the app in development with `yarn tauri dev`. NVIDIA users on Linux, use shell script `./nvidia-prop-dev.sh`
|
||||||
|
|
||||||
To manually specify the logging level, add the environment variable `RUST_LOG=[debug, info, warn, error]` to `yarn tauri dev`:
|
To manually specify the logging level, add the environment variable `RUST_LOG=[debug, info, warn, error]` to `yarn tauri dev`:
|
||||||
|
|
||||||
e.g. `RUST_LOG=debug yarn tauri dev`
|
e.g. `RUST_LOG=debug yarn tauri dev`
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
Check out the contributing guide on our Developer Docs: [Drop Developer Docs - Contributing](https://developer.droposs.org/contributing).
|
Check the original [Drop repo](https://github.com/Drop-OSS/drop/blob/main/CONTRIBUTING.md) for contributing guidelines.
|
||||||
13
main/app.vue
13
main/app.vue
@ -1,5 +1,5 @@
|
|||||||
<template>
|
<template>
|
||||||
<NuxtLoadingIndicator color="#2563eb" />
|
<NuxtLoadingIndicator color="#2563eb" />
|
||||||
<NuxtLayout class="select-none w-screen h-screen">
|
<NuxtLayout class="select-none w-screen h-screen">
|
||||||
<NuxtPage />
|
<NuxtPage />
|
||||||
<ModalStack />
|
<ModalStack />
|
||||||
@ -7,7 +7,14 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import "~/composables/downloads.js";
|
||||||
|
|
||||||
import { invoke } from "@tauri-apps/api/core";
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
|
import { useAppState } from "./composables/app-state.js";
|
||||||
|
import {
|
||||||
|
initialNavigation,
|
||||||
|
setupHooks,
|
||||||
|
} from "./composables/state-navigation.js";
|
||||||
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
@ -37,6 +44,10 @@ router.beforeEach(async () => {
|
|||||||
setupHooks();
|
setupHooks();
|
||||||
initialNavigation(state);
|
initialNavigation(state);
|
||||||
|
|
||||||
|
// Setup playtime event listeners
|
||||||
|
const { setupEventListeners } = usePlaytime();
|
||||||
|
setupEventListeners();
|
||||||
|
|
||||||
useHead({
|
useHead({
|
||||||
title: "Drop",
|
title: "Drop",
|
||||||
});
|
});
|
||||||
|
|||||||
@ -2,7 +2,9 @@
|
|||||||
<div class="h-16 bg-zinc-950 flex flex-row justify-between">
|
<div class="h-16 bg-zinc-950 flex flex-row justify-between">
|
||||||
<div class="flex flex-row grow items-center pl-5 pr-2 py-3">
|
<div class="flex flex-row grow items-center pl-5 pr-2 py-3">
|
||||||
<div class="inline-flex items-center gap-x-10">
|
<div class="inline-flex items-center gap-x-10">
|
||||||
<Wordmark class="h-8 mb-0.5" />
|
<NuxtLink to="/store">
|
||||||
|
<Wordmark class="h-8 mb-0.5" />
|
||||||
|
</NuxtLink>
|
||||||
<nav class="inline-flex items-center mt-0.5">
|
<nav class="inline-flex items-center mt-0.5">
|
||||||
<ol class="inline-flex items-center gap-x-6">
|
<ol class="inline-flex items-center gap-x-6">
|
||||||
<NuxtLink
|
<NuxtLink
|
||||||
@ -40,7 +42,7 @@
|
|||||||
</ol>
|
</ol>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<WindowControl />
|
<WindowControl />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|||||||
@ -76,6 +76,7 @@ import { Menu, MenuButton, MenuItem, MenuItems } from "@headlessui/vue";
|
|||||||
import { ChevronDownIcon } from "@heroicons/vue/16/solid";
|
import { ChevronDownIcon } from "@heroicons/vue/16/solid";
|
||||||
import type { NavigationItem } from "../types";
|
import type { NavigationItem } from "../types";
|
||||||
import HeaderWidget from "./HeaderWidget.vue";
|
import HeaderWidget from "./HeaderWidget.vue";
|
||||||
|
import { useAppState } from "~/composables/app-state";
|
||||||
import { invoke } from "@tauri-apps/api/core";
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
|
|
||||||
const open = ref(false);
|
const open = ref(false);
|
||||||
|
|||||||
@ -73,7 +73,7 @@
|
|||||||
alt=""
|
alt=""
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-col gap-x-2">
|
<div class="inline-flex items-center gap-x-2">
|
||||||
<p
|
<p
|
||||||
class="text-sm whitespace-nowrap font-display font-semibold"
|
class="text-sm whitespace-nowrap font-display font-semibold"
|
||||||
>
|
>
|
||||||
|
|||||||
7
main/components/PageWidget.vue
Normal file
7
main/components/PageWidget.vue
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
<template>
|
||||||
|
<NuxtLink
|
||||||
|
class="inline-flex items-center gap-x-2 px-1 py-0.5 rounded bg-blue-900 text-zinc-100 hover:bg-blue-800"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</NuxtLink>
|
||||||
|
</template>
|
||||||
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,
|
||||||
|
};
|
||||||
|
};
|
||||||
@ -1,5 +1,5 @@
|
|||||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||||
|
|
||||||
export const useObject = (id: string) => {
|
export const useObject = async (id: string) => {
|
||||||
return convertFileSrc(id, "object");
|
return convertFileSrc(id, "object");
|
||||||
};
|
};
|
||||||
@ -9,17 +9,13 @@ export default defineNuxtConfig({
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
|
css: ["~/assets/main.scss"],
|
||||||
|
|
||||||
ssr: false,
|
ssr: false,
|
||||||
|
|
||||||
extends: ["../shared", "../libs/drop-base"],
|
extends: [["../libs/drop-base"]],
|
||||||
|
|
||||||
app: {
|
app: {
|
||||||
baseURL: "/main",
|
baseURL: "/main",
|
||||||
},
|
}
|
||||||
|
|
||||||
devtools: {
|
|
||||||
enabled: false,
|
|
||||||
},
|
|
||||||
|
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|||||||
@ -18,10 +18,20 @@
|
|||||||
<div class="relative z-10">
|
<div class="relative z-10">
|
||||||
<div class="px-8 pb-4">
|
<div class="px-8 pb-4">
|
||||||
<h1
|
<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 }}
|
{{ game.mName }}
|
||||||
</h1>
|
</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">
|
<div class="flex flex-row gap-x-4 items-stretch mb-8">
|
||||||
<!-- Do not add scale animations to this: https://stackoverflow.com/a/35683068 -->
|
<!-- Do not add scale animations to this: https://stackoverflow.com/a/35683068 -->
|
||||||
@ -60,6 +70,12 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="space-y-6">
|
<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">
|
<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">
|
<h2 class="text-xl font-display font-semibold text-zinc-100 mb-4">
|
||||||
Game Images
|
Game Images
|
||||||
@ -528,6 +544,19 @@ const currentImageIndex = ref(0);
|
|||||||
|
|
||||||
const configureModalOpen = ref(false);
|
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() {
|
async function installFlow() {
|
||||||
installFlowOpen.value = true;
|
installFlowOpen.value = true;
|
||||||
versionOptions.value = undefined;
|
versionOptions.value = undefined;
|
||||||
|
|||||||
@ -7,7 +7,6 @@ export default {
|
|||||||
"./plugins/**/*.{js,ts}",
|
"./plugins/**/*.{js,ts}",
|
||||||
"./app.vue",
|
"./app.vue",
|
||||||
"./error.vue",
|
"./error.vue",
|
||||||
"../shared/components/**/*.vue"
|
|
||||||
],
|
],
|
||||||
theme: {
|
theme: {
|
||||||
extend: {
|
extend: {
|
||||||
|
|||||||
@ -94,3 +94,37 @@ export type Settings = {
|
|||||||
maxDownloadThreads: number;
|
maxDownloadThreads: number;
|
||||||
forceOffline: boolean;
|
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;
|
||||||
|
};
|
||||||
@ -14,8 +14,7 @@
|
|||||||
"@tauri-apps/plugin-os": "^2.3.0",
|
"@tauri-apps/plugin-os": "^2.3.0",
|
||||||
"@tauri-apps/plugin-shell": "^2.3.0",
|
"@tauri-apps/plugin-shell": "^2.3.0",
|
||||||
"pino": "^9.7.0",
|
"pino": "^9.7.0",
|
||||||
"pino-pretty": "^13.1.1",
|
"pino-pretty": "^13.1.1"
|
||||||
"tauri": "^0.15.0"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tauri-apps/cli": "^2.7.1"
|
"@tauri-apps/cli": "^2.7.1"
|
||||||
|
|||||||
@ -1,50 +0,0 @@
|
|||||||
<template>
|
|
||||||
<NuxtLoadingIndicator color="#2563eb" />
|
|
||||||
<NuxtLayout class="select-none w-screen h-screen">
|
|
||||||
<NuxtPage />
|
|
||||||
<ModalStack />
|
|
||||||
</NuxtLayout>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup lang="ts">
|
|
||||||
import "~/composables/downloads.js";
|
|
||||||
|
|
||||||
import { invoke } from "@tauri-apps/api/core";
|
|
||||||
import { useAppState } from "./composables/app-state.js";
|
|
||||||
import {
|
|
||||||
initialNavigation,
|
|
||||||
setupHooks,
|
|
||||||
} from "./composables/state-navigation.js";
|
|
||||||
|
|
||||||
const router = useRouter();
|
|
||||||
|
|
||||||
const state = useAppState();
|
|
||||||
|
|
||||||
async function fetchState() {
|
|
||||||
try {
|
|
||||||
state.value = JSON.parse(await invoke("fetch_state"));
|
|
||||||
if (!state.value)
|
|
||||||
throw createError({
|
|
||||||
statusCode: 500,
|
|
||||||
statusMessage: `App state is: ${state.value}`,
|
|
||||||
fatal: true,
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
console.error("failed to parse state", e);
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
await fetchState();
|
|
||||||
|
|
||||||
// This is inefficient but apparently we do it lol
|
|
||||||
router.beforeEach(async () => {
|
|
||||||
await fetchState();
|
|
||||||
});
|
|
||||||
|
|
||||||
setupHooks();
|
|
||||||
initialNavigation(state);
|
|
||||||
|
|
||||||
useHead({
|
|
||||||
title: "Drop",
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
@ -1,84 +0,0 @@
|
|||||||
@tailwind base;
|
|
||||||
@tailwind components;
|
|
||||||
@tailwind utilities;
|
|
||||||
|
|
||||||
html,
|
|
||||||
body {
|
|
||||||
-ms-overflow-style: none; /* IE and Edge /
|
|
||||||
scrollbar-width: none; / Firefox */
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Hide scrollbar for Chrome, Safari and Opera */
|
|
||||||
html::-webkit-scrollbar {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
$motiva: (
|
|
||||||
("MotivaSansThin.ttf", "ttf", 100, normal),
|
|
||||||
("MotivaSansLight.woff.ttf", "woff", 300, normal),
|
|
||||||
("MotivaSansRegular.woff.ttf", "woff", 400, normal),
|
|
||||||
("MotivaSansMedium.woff.ttf", "woff", 500, normal),
|
|
||||||
("MotivaSansBold.woff.ttf", "woff", 600, normal),
|
|
||||||
("MotivaSansExtraBold.ttf", "woff", 700, normal),
|
|
||||||
("MotivaSansBlack.woff.ttf", "woff", 900, normal)
|
|
||||||
);
|
|
||||||
|
|
||||||
$helvetica: (
|
|
||||||
("Helvetica.woff", "woff", 400, normal),
|
|
||||||
("Helvetica-Oblique.woff", "woff", 400, italic),
|
|
||||||
("Helvetica-Bold.woff", "woff", 600, normal),
|
|
||||||
("Helvetica-BoldOblique.woff", "woff", 600, italic),
|
|
||||||
("helvetica-light-587ebe5a59211.woff2", "woff2", 300, normal)
|
|
||||||
);
|
|
||||||
|
|
||||||
@each $file, $format, $weight, $style in $motiva {
|
|
||||||
@font-face {
|
|
||||||
font-family: "Motiva Sans";
|
|
||||||
src: url("/fonts/motiva/#{$file}") format($format);
|
|
||||||
font-weight: $weight;
|
|
||||||
font-style: $style;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@each $file, $format, $weight, $style in $helvetica {
|
|
||||||
@font-face {
|
|
||||||
font-family: "Helvetica";
|
|
||||||
src: url("/fonts/helvetica/#{$file}") format($format);
|
|
||||||
font-weight: $weight;
|
|
||||||
font-style: $style;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@font-face {
|
|
||||||
font-family: "Inter";
|
|
||||||
src: url("/fonts/inter/InterVariable.ttf");
|
|
||||||
font-style: normal;
|
|
||||||
}
|
|
||||||
|
|
||||||
@font-face {
|
|
||||||
font-family: "Inter";
|
|
||||||
src: url("/fonts/inter/InterVariable-Italic.ttf");
|
|
||||||
font-style: italic;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ===== Scrollbar CSS ===== */
|
|
||||||
/* Firefox */
|
|
||||||
* {
|
|
||||||
scrollbar-width: 4px;
|
|
||||||
scrollbar-color: #52525b #00000000;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Chrome, Edge, and Safari */
|
|
||||||
*::-webkit-scrollbar {
|
|
||||||
width: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
*::-webkit-scrollbar-track {
|
|
||||||
background: transparent;
|
|
||||||
}
|
|
||||||
|
|
||||||
*::-webkit-scrollbar-thumb {
|
|
||||||
background-color: #52525b;
|
|
||||||
border-radius: 10px;
|
|
||||||
border: 3px solid #52525b;
|
|
||||||
}
|
|
||||||
@ -1,91 +0,0 @@
|
|||||||
<template>
|
|
||||||
<NuxtLayout name="default">
|
|
||||||
<div
|
|
||||||
class="grid min-h-full grid-cols-1 grid-rows-[1fr,auto,1fr] lg:grid-cols-[max(50%,36rem),1fr]"
|
|
||||||
>
|
|
||||||
<header
|
|
||||||
class="mx-auto w-full max-w-7xl px-6 pt-6 sm:pt-10 lg:col-span-2 lg:col-start-1 lg:row-start-1 lg:px-8"
|
|
||||||
>
|
|
||||||
<Logo class="h-10 w-auto sm:h-12" />
|
|
||||||
|
|
||||||
</header>
|
|
||||||
<main
|
|
||||||
class="mx-auto w-full max-w-7xl px-6 py-24 sm:py-32 lg:col-span-2 lg:col-start-1 lg:row-start-2 lg:px-8"
|
|
||||||
>
|
|
||||||
<div class="max-w-lg">
|
|
||||||
<p class="text-base font-semibold leading-8 text-blue-600">
|
|
||||||
{{ error?.statusCode }}
|
|
||||||
</p>
|
|
||||||
<h1
|
|
||||||
class="mt-4 text-3xl font-bold font-display tracking-tight text-zinc-100 sm:text-5xl"
|
|
||||||
>
|
|
||||||
Oh no!
|
|
||||||
</h1>
|
|
||||||
<p
|
|
||||||
v-if="message"
|
|
||||||
class="mt-3 font-bold text-base leading-7 text-red-500"
|
|
||||||
>
|
|
||||||
{{ message }}
|
|
||||||
</p>
|
|
||||||
<p class="mt-6 text-base leading-7 text-zinc-400">
|
|
||||||
An error occurred while responding to your request. If you believe
|
|
||||||
this to be a bug, please report it. Try signing in and see if it
|
|
||||||
resolves the issue.
|
|
||||||
</p>
|
|
||||||
<div class="mt-10">
|
|
||||||
<!-- full app reload to fix errors -->
|
|
||||||
<a
|
|
||||||
href="/store"
|
|
||||||
class="text-sm font-semibold leading-7 text-blue-600"
|
|
||||||
><span aria-hidden="true">←</span> Back to store</a
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
<footer class="self-end lg:col-span-2 lg:col-start-1 lg:row-start-3">
|
|
||||||
<div class="border-t border-zinc-700 bg-zinc-900 py-10">
|
|
||||||
<nav
|
|
||||||
class="mx-auto flex w-full max-w-7xl items-center gap-x-4 px-6 text-sm leading-7 text-zinc-400 lg:px-8"
|
|
||||||
>
|
|
||||||
<NuxtLink href="/docs">Documentation</NuxtLink>
|
|
||||||
<svg
|
|
||||||
viewBox="0 0 2 2"
|
|
||||||
aria-hidden="true"
|
|
||||||
class="h-0.5 w-0.5 fill-zinc-600"
|
|
||||||
>
|
|
||||||
<circle cx="1" cy="1" r="1" />
|
|
||||||
</svg>
|
|
||||||
<a href="https://discord.gg/NHx46XKJWA" target="_blank"
|
|
||||||
>Support Discord</a
|
|
||||||
>
|
|
||||||
</nav>
|
|
||||||
</div>
|
|
||||||
</footer>
|
|
||||||
<div
|
|
||||||
class="hidden lg:relative lg:col-start-2 lg:row-start-1 lg:row-end-4 lg:block"
|
|
||||||
>
|
|
||||||
<img
|
|
||||||
src="@/assets/wallpaper.jpg"
|
|
||||||
alt=""
|
|
||||||
class="absolute inset-0 h-full w-full object-cover"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</NuxtLayout>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup lang="ts">
|
|
||||||
import type { NuxtError } from "#app";
|
|
||||||
|
|
||||||
const props = defineProps({
|
|
||||||
error: Object as () => NuxtError,
|
|
||||||
});
|
|
||||||
|
|
||||||
const statusCode = props.error?.statusCode;
|
|
||||||
const message =
|
|
||||||
props.error?.statusMessage ||
|
|
||||||
props.error?.message ||
|
|
||||||
"An unknown error occurred.";
|
|
||||||
|
|
||||||
console.error(props.error);
|
|
||||||
</script>
|
|
||||||
@ -1,25 +0,0 @@
|
|||||||
// https://nuxt.com/docs/api/configuration/nuxt-config
|
|
||||||
export default defineNuxtConfig({
|
|
||||||
compatibilityDate: "2024-04-03",
|
|
||||||
|
|
||||||
postcss: {
|
|
||||||
plugins: {
|
|
||||||
tailwindcss: {},
|
|
||||||
autoprefixer: {},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
css: ["~/assets/main.scss"],
|
|
||||||
|
|
||||||
ssr: false,
|
|
||||||
|
|
||||||
extends: [["../libs/drop-base"]],
|
|
||||||
|
|
||||||
app: {
|
|
||||||
baseURL: "/main",
|
|
||||||
},
|
|
||||||
|
|
||||||
devtools: {
|
|
||||||
enabled: false,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@ -1,37 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "view",
|
|
||||||
"private": true,
|
|
||||||
"version": "0.3.3",
|
|
||||||
"type": "module",
|
|
||||||
"scripts": {
|
|
||||||
"build": "nuxt generate",
|
|
||||||
"dev": "nuxt dev",
|
|
||||||
"postinstall": "nuxt prepare",
|
|
||||||
"tauri": "tauri"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@headlessui/vue": "^1.7.23",
|
|
||||||
"@heroicons/vue": "^2.1.5",
|
|
||||||
"@nuxtjs/tailwindcss": "^6.12.2",
|
|
||||||
"@tauri-apps/api": "^2.7.0",
|
|
||||||
"koa": "^2.16.1",
|
|
||||||
"markdown-it": "^14.1.0",
|
|
||||||
"micromark": "^4.0.1",
|
|
||||||
"nuxt": "^3.16.0",
|
|
||||||
"scss": "^0.2.4",
|
|
||||||
"vue-router": "latest",
|
|
||||||
"vuedraggable": "^4.1.0"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@tailwindcss/forms": "^0.5.9",
|
|
||||||
"@tailwindcss/typography": "^0.5.15",
|
|
||||||
"@types/markdown-it": "^14.1.2",
|
|
||||||
"autoprefixer": "^10.4.20",
|
|
||||||
"postcss": "^8.4.47",
|
|
||||||
"sass-embedded": "^1.79.4",
|
|
||||||
"tailwindcss": "^3.4.13",
|
|
||||||
"typescript": "^5.8.3",
|
|
||||||
"vue-tsc": "^2.2.10"
|
|
||||||
},
|
|
||||||
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
|
|
||||||
}
|
|
||||||
@ -1,20 +0,0 @@
|
|||||||
/** @type {import('tailwindcss').Config} */
|
|
||||||
export default {
|
|
||||||
content: [
|
|
||||||
"./components/**/*.{js,vue,ts}",
|
|
||||||
"./layouts/**/*.vue",
|
|
||||||
"./pages/**/*.vue",
|
|
||||||
"./plugins/**/*.{js,ts}",
|
|
||||||
"./app.vue",
|
|
||||||
"./error.vue",
|
|
||||||
],
|
|
||||||
theme: {
|
|
||||||
extend: {
|
|
||||||
fontFamily: {
|
|
||||||
sans: ["Inter"],
|
|
||||||
display: ["Motiva Sans"],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
plugins: [require("@tailwindcss/forms"), require('@tailwindcss/typography')],
|
|
||||||
};
|
|
||||||
@ -1,5 +0,0 @@
|
|||||||
{
|
|
||||||
// https://nuxt.com/docs/guide/concepts/typescript
|
|
||||||
"extends": "./.nuxt/tsconfig.json",
|
|
||||||
"exclude": ["src-tauri/**/*"]
|
|
||||||
}
|
|
||||||
@ -1,96 +0,0 @@
|
|||||||
import type { Component } from "vue";
|
|
||||||
|
|
||||||
export type NavigationItem = {
|
|
||||||
prefix: string;
|
|
||||||
route: string;
|
|
||||||
label: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type QuickActionNav = {
|
|
||||||
icon: Component;
|
|
||||||
notifications?: number;
|
|
||||||
action: () => Promise<void>;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type User = {
|
|
||||||
id: string;
|
|
||||||
username: string;
|
|
||||||
admin: boolean;
|
|
||||||
displayName: string;
|
|
||||||
profilePictureObjectId: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type AppState = {
|
|
||||||
status: AppStatus;
|
|
||||||
user?: User;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type Game = {
|
|
||||||
id: string;
|
|
||||||
mName: string;
|
|
||||||
mShortDescription: string;
|
|
||||||
mDescription: string;
|
|
||||||
mIconObjectId: string;
|
|
||||||
mBannerObjectId: string;
|
|
||||||
mCoverObjectId: string;
|
|
||||||
mImageLibraryObjectIds: string[];
|
|
||||||
mImageCarouselObjectIds: string[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export type Collection = {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
isDefault: boolean;
|
|
||||||
entries: Array<{ gameId: string; game: Game }>;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type GameVersion = {
|
|
||||||
launchCommandTemplate: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export enum AppStatus {
|
|
||||||
NotConfigured = "NotConfigured",
|
|
||||||
Offline = "Offline",
|
|
||||||
SignedOut = "SignedOut",
|
|
||||||
SignedIn = "SignedIn",
|
|
||||||
SignedInNeedsReauth = "SignedInNeedsReauth",
|
|
||||||
ServerUnavailable = "ServerUnavailable",
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum GameStatusEnum {
|
|
||||||
Remote = "Remote",
|
|
||||||
Queued = "Queued",
|
|
||||||
Downloading = "Downloading",
|
|
||||||
Validating = "Validating",
|
|
||||||
Installed = "Installed",
|
|
||||||
Updating = "Updating",
|
|
||||||
Uninstalling = "Uninstalling",
|
|
||||||
SetupRequired = "SetupRequired",
|
|
||||||
Running = "Running",
|
|
||||||
PartiallyInstalled = "PartiallyInstalled",
|
|
||||||
}
|
|
||||||
|
|
||||||
export type GameStatus = {
|
|
||||||
type: GameStatusEnum;
|
|
||||||
version_name?: string;
|
|
||||||
install_dir?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export enum DownloadableType {
|
|
||||||
Game = "Game",
|
|
||||||
Tool = "Tool",
|
|
||||||
DLC = "DLC",
|
|
||||||
Mod = "Mod",
|
|
||||||
}
|
|
||||||
|
|
||||||
export type DownloadableMetadata = {
|
|
||||||
id: string;
|
|
||||||
version: string;
|
|
||||||
downloadType: DownloadableType;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type Settings = {
|
|
||||||
autostart: boolean;
|
|
||||||
maxDownloadThreads: number;
|
|
||||||
forceOffline: boolean;
|
|
||||||
};
|
|
||||||
8091
shared/yarn.lock
8091
shared/yarn.lock
File diff suppressed because it is too large
Load Diff
2373
src-tauri/Cargo.lock
generated
2373
src-tauri/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -78,16 +78,6 @@ futures-core = "0.3.31"
|
|||||||
bytes = "1.10.1"
|
bytes = "1.10.1"
|
||||||
# tailscale = { path = "./tailscale" }
|
# tailscale = { path = "./tailscale" }
|
||||||
|
|
||||||
|
|
||||||
# Workspaces
|
|
||||||
client = { version = "0.1.0", path = "./client" }
|
|
||||||
database = { path = "./database" }
|
|
||||||
process = { path = "./process" }
|
|
||||||
remote = { version = "0.1.0", path = "./remote" }
|
|
||||||
utils = { path = "./utils" }
|
|
||||||
games = { version = "0.1.0", path = "./games" }
|
|
||||||
download_manager = { version = "0.1.0", path = "./download_manager" }
|
|
||||||
|
|
||||||
[dependencies.dynfmt]
|
[dependencies.dynfmt]
|
||||||
version = "0.1.5"
|
version = "0.1.5"
|
||||||
features = ["curly"]
|
features = ["curly"]
|
||||||
@ -137,18 +127,3 @@ features = ["derive", "rc"]
|
|||||||
lto = true
|
lto = true
|
||||||
codegen-units = 1
|
codegen-units = 1
|
||||||
panic = 'abort'
|
panic = 'abort'
|
||||||
|
|
||||||
|
|
||||||
[workspace]
|
|
||||||
members = [
|
|
||||||
"client",
|
|
||||||
"database",
|
|
||||||
"process",
|
|
||||||
"remote",
|
|
||||||
"utils",
|
|
||||||
"cloud_saves",
|
|
||||||
"download_manager",
|
|
||||||
"games",
|
|
||||||
]
|
|
||||||
|
|
||||||
resolver = "3"
|
|
||||||
4862
src-tauri/client/Cargo.lock
generated
4862
src-tauri/client/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -1,12 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "client"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
bitcode = "0.6.7"
|
|
||||||
database = { version = "0.1.0", path = "../database" }
|
|
||||||
log = "0.4.28"
|
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
|
||||||
tauri = "2.8.5"
|
|
||||||
tauri-plugin-autostart = "2.5.0"
|
|
||||||
@ -1,12 +0,0 @@
|
|||||||
use serde::Serialize;
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Serialize, Eq, PartialEq)]
|
|
||||||
pub enum AppStatus {
|
|
||||||
NotConfigured,
|
|
||||||
Offline,
|
|
||||||
ServerError,
|
|
||||||
SignedOut,
|
|
||||||
SignedIn,
|
|
||||||
SignedInNeedsReauth,
|
|
||||||
ServerUnavailable,
|
|
||||||
}
|
|
||||||
@ -1,26 +0,0 @@
|
|||||||
use database::borrow_db_checked;
|
|
||||||
use log::debug;
|
|
||||||
use tauri::AppHandle;
|
|
||||||
use tauri_plugin_autostart::ManagerExt;
|
|
||||||
|
|
||||||
// New function to sync state on startup
|
|
||||||
pub fn sync_autostart_on_startup(app: &AppHandle) -> Result<(), String> {
|
|
||||||
let db_handle = borrow_db_checked();
|
|
||||||
let should_be_enabled = db_handle.settings.autostart;
|
|
||||||
drop(db_handle);
|
|
||||||
|
|
||||||
let manager = app.autolaunch();
|
|
||||||
let current_state = manager.is_enabled().map_err(|e| e.to_string())?;
|
|
||||||
|
|
||||||
if current_state != should_be_enabled {
|
|
||||||
if should_be_enabled {
|
|
||||||
manager.enable().map_err(|e| e.to_string())?;
|
|
||||||
debug!("synced autostart: enabled");
|
|
||||||
} else {
|
|
||||||
manager.disable().map_err(|e| e.to_string())?;
|
|
||||||
debug!("synced autostart: disabled");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@ -1,52 +0,0 @@
|
|||||||
use std::{
|
|
||||||
ffi::OsStr,
|
|
||||||
path::PathBuf,
|
|
||||||
process::{Command, Stdio},
|
|
||||||
sync::LazyLock,
|
|
||||||
};
|
|
||||||
|
|
||||||
use log::info;
|
|
||||||
|
|
||||||
pub static COMPAT_INFO: LazyLock<Option<CompatInfo>> = LazyLock::new(create_new_compat_info);
|
|
||||||
|
|
||||||
pub static UMU_LAUNCHER_EXECUTABLE: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
|
|
||||||
let x = get_umu_executable();
|
|
||||||
info!("{:?}", &x);
|
|
||||||
x
|
|
||||||
});
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct CompatInfo {
|
|
||||||
pub umu_installed: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn create_new_compat_info() -> Option<CompatInfo> {
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
return None;
|
|
||||||
|
|
||||||
let has_umu_installed = UMU_LAUNCHER_EXECUTABLE.is_some();
|
|
||||||
Some(CompatInfo {
|
|
||||||
umu_installed: has_umu_installed,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const UMU_BASE_LAUNCHER_EXECUTABLE: &str = "umu-run";
|
|
||||||
const UMU_INSTALL_DIRS: [&str; 4] = ["/app/share", "/use/local/share", "/usr/share", "/opt"];
|
|
||||||
|
|
||||||
fn get_umu_executable() -> Option<PathBuf> {
|
|
||||||
if check_executable_exists(UMU_BASE_LAUNCHER_EXECUTABLE) {
|
|
||||||
return Some(PathBuf::from(UMU_BASE_LAUNCHER_EXECUTABLE));
|
|
||||||
}
|
|
||||||
|
|
||||||
for dir in UMU_INSTALL_DIRS {
|
|
||||||
let p = PathBuf::from(dir).join(UMU_BASE_LAUNCHER_EXECUTABLE);
|
|
||||||
if check_executable_exists(&p) {
|
|
||||||
return Some(p);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
fn check_executable_exists<P: AsRef<OsStr>>(exec: P) -> bool {
|
|
||||||
let has_umu_installed = Command::new(exec).stdout(Stdio::null()).output();
|
|
||||||
has_umu_installed.is_ok()
|
|
||||||
}
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
pub mod app_status;
|
|
||||||
pub mod autostart;
|
|
||||||
pub mod compat;
|
|
||||||
pub mod user;
|
|
||||||
@ -1,12 +0,0 @@
|
|||||||
use bitcode::{Decode, Encode};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
#[derive(Clone, Serialize, Deserialize, Encode, Decode)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct User {
|
|
||||||
id: String,
|
|
||||||
username: String,
|
|
||||||
admin: bool,
|
|
||||||
display_name: String,
|
|
||||||
profile_picture_object_id: String,
|
|
||||||
}
|
|
||||||
@ -1,19 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "cloud_saves"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
database = { version = "0.1.0", path = "../database" }
|
|
||||||
dirs = "6.0.0"
|
|
||||||
log = "0.4.28"
|
|
||||||
regex = "1.11.3"
|
|
||||||
rustix = "1.1.2"
|
|
||||||
serde = "1.0.228"
|
|
||||||
serde_json = "1.0.145"
|
|
||||||
serde_with = "3.15.0"
|
|
||||||
tar = "0.4.44"
|
|
||||||
tempfile = "3.23.0"
|
|
||||||
uuid = "1.18.1"
|
|
||||||
whoami = "1.6.1"
|
|
||||||
zstd = "0.13.3"
|
|
||||||
@ -1,234 +0,0 @@
|
|||||||
use std::{collections::HashMap, path::PathBuf, str::FromStr};
|
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
use database::platform::Platform;
|
|
||||||
use database::{GameVersion, db::DATA_ROOT_DIR};
|
|
||||||
use log::warn;
|
|
||||||
|
|
||||||
use crate::error::BackupError;
|
|
||||||
|
|
||||||
use super::path::CommonPath;
|
|
||||||
|
|
||||||
pub struct BackupManager<'a> {
|
|
||||||
pub current_platform: Platform,
|
|
||||||
pub sources: HashMap<(Platform, Platform), &'a (dyn BackupHandler + Sync + Send)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for BackupManager<'_> {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BackupManager<'_> {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
BackupManager {
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
current_platform: Platform::Windows,
|
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
current_platform: Platform::MacOs,
|
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
current_platform: Platform::Linux,
|
|
||||||
|
|
||||||
sources: HashMap::from([
|
|
||||||
// Current platform to target platform
|
|
||||||
(
|
|
||||||
(Platform::Windows, Platform::Windows),
|
|
||||||
&WindowsBackupManager {} as &(dyn BackupHandler + Sync + Send),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
(Platform::Linux, Platform::Linux),
|
|
||||||
&LinuxBackupManager {} as &(dyn BackupHandler + Sync + Send),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
(Platform::MacOs, Platform::MacOs),
|
|
||||||
&MacBackupManager {} as &(dyn BackupHandler + Sync + Send),
|
|
||||||
),
|
|
||||||
]),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait BackupHandler: Send + Sync {
|
|
||||||
fn root_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
|
||||||
Ok(DATA_ROOT_DIR.join("games"))
|
|
||||||
}
|
|
||||||
fn game_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> {
|
|
||||||
Ok(PathBuf::from_str(&game.game_id).unwrap())
|
|
||||||
}
|
|
||||||
fn base_translate(&self, path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> {
|
|
||||||
Ok(self
|
|
||||||
.root_translate(path, game)?
|
|
||||||
.join(self.game_translate(path, game)?))
|
|
||||||
}
|
|
||||||
fn home_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
|
||||||
let c = CommonPath::Home.get().ok_or(BackupError::NotFound);
|
|
||||||
println!("{:?}", c);
|
|
||||||
c
|
|
||||||
}
|
|
||||||
fn store_user_id_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
PathBuf::from_str(&game.game_id).map_err(|_| BackupError::ParseError)
|
|
||||||
}
|
|
||||||
fn os_user_name_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
Ok(PathBuf::from_str(&whoami::username()).unwrap())
|
|
||||||
}
|
|
||||||
fn win_app_data_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
warn!("Unexpected Windows Reference in Backup <winAppData>");
|
|
||||||
Err(BackupError::InvalidSystem)
|
|
||||||
}
|
|
||||||
fn win_local_app_data_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
warn!("Unexpected Windows Reference in Backup <winLocalAppData>");
|
|
||||||
Err(BackupError::InvalidSystem)
|
|
||||||
}
|
|
||||||
fn win_local_app_data_low_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
warn!("Unexpected Windows Reference in Backup <winLocalAppDataLow>");
|
|
||||||
Err(BackupError::InvalidSystem)
|
|
||||||
}
|
|
||||||
fn win_documents_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
warn!("Unexpected Windows Reference in Backup <winDocuments>");
|
|
||||||
Err(BackupError::InvalidSystem)
|
|
||||||
}
|
|
||||||
fn win_public_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
warn!("Unexpected Windows Reference in Backup <winPublic>");
|
|
||||||
Err(BackupError::InvalidSystem)
|
|
||||||
}
|
|
||||||
fn win_program_data_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
warn!("Unexpected Windows Reference in Backup <winProgramData>");
|
|
||||||
Err(BackupError::InvalidSystem)
|
|
||||||
}
|
|
||||||
fn win_dir_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
warn!("Unexpected Windows Reference in Backup <winDir>");
|
|
||||||
Err(BackupError::InvalidSystem)
|
|
||||||
}
|
|
||||||
fn xdg_data_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
warn!("Unexpected XDG Reference in Backup <xdgData>");
|
|
||||||
Err(BackupError::InvalidSystem)
|
|
||||||
}
|
|
||||||
fn xdg_config_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
warn!("Unexpected XDG Reference in Backup <xdgConfig>");
|
|
||||||
Err(BackupError::InvalidSystem)
|
|
||||||
}
|
|
||||||
fn skip_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
|
||||||
Ok(PathBuf::new())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct LinuxBackupManager {}
|
|
||||||
impl BackupHandler for LinuxBackupManager {
|
|
||||||
fn xdg_config_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
CommonPath::Data.get().ok_or(BackupError::NotFound)
|
|
||||||
}
|
|
||||||
fn xdg_data_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
CommonPath::Config.get().ok_or(BackupError::NotFound)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub struct WindowsBackupManager {}
|
|
||||||
impl BackupHandler for WindowsBackupManager {
|
|
||||||
fn win_app_data_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
CommonPath::Config.get().ok_or(BackupError::NotFound)
|
|
||||||
}
|
|
||||||
fn win_local_app_data_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
CommonPath::DataLocal.get().ok_or(BackupError::NotFound)
|
|
||||||
}
|
|
||||||
fn win_local_app_data_low_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
CommonPath::DataLocalLow
|
|
||||||
.get()
|
|
||||||
.ok_or(BackupError::NotFound)
|
|
||||||
}
|
|
||||||
fn win_dir_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
Ok(PathBuf::from_str("C:/Windows").unwrap())
|
|
||||||
}
|
|
||||||
fn win_documents_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
CommonPath::Document.get().ok_or(BackupError::NotFound)
|
|
||||||
}
|
|
||||||
fn win_program_data_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
Ok(PathBuf::from_str("C:/ProgramData").unwrap())
|
|
||||||
}
|
|
||||||
fn win_public_translate(
|
|
||||||
&self,
|
|
||||||
_path: &PathBuf,
|
|
||||||
_game: &GameVersion,
|
|
||||||
) -> Result<PathBuf, BackupError> {
|
|
||||||
CommonPath::Public.get().ok_or(BackupError::NotFound)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub struct MacBackupManager {}
|
|
||||||
impl BackupHandler for MacBackupManager {}
|
|
||||||
@ -1,27 +0,0 @@
|
|||||||
use std::fmt::Display;
|
|
||||||
|
|
||||||
use serde_with::SerializeDisplay;
|
|
||||||
|
|
||||||
#[derive(Debug, SerializeDisplay, Clone, Copy)]
|
|
||||||
|
|
||||||
pub enum BackupError {
|
|
||||||
InvalidSystem,
|
|
||||||
|
|
||||||
NotFound,
|
|
||||||
|
|
||||||
ParseError,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for BackupError {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
let s = match self {
|
|
||||||
BackupError::InvalidSystem => "Attempted to generate path for invalid system",
|
|
||||||
|
|
||||||
BackupError::NotFound => "Could not generate or find path",
|
|
||||||
|
|
||||||
BackupError::ParseError => "Failed to parse path",
|
|
||||||
};
|
|
||||||
|
|
||||||
write!(f, "{}", s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,8 +0,0 @@
|
|||||||
pub mod backup_manager;
|
|
||||||
pub mod conditions;
|
|
||||||
pub mod error;
|
|
||||||
pub mod metadata;
|
|
||||||
pub mod normalise;
|
|
||||||
pub mod path;
|
|
||||||
pub mod placeholder;
|
|
||||||
pub mod resolver;
|
|
||||||
@ -1,15 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "database"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
chrono = "0.4.42"
|
|
||||||
dirs = "6.0.0"
|
|
||||||
log = "0.4.28"
|
|
||||||
native_model = { version = "0.6.4", features = ["rmp_serde_1_3"], git = "https://github.com/Drop-OSS/native_model.git"}
|
|
||||||
rustbreak = "2.0.0"
|
|
||||||
serde = "1.0.228"
|
|
||||||
serde_with = "3.15.0"
|
|
||||||
url = "2.5.7"
|
|
||||||
whoami = "1.6.1"
|
|
||||||
@ -1,45 +0,0 @@
|
|||||||
use std::{
|
|
||||||
path::PathBuf,
|
|
||||||
sync::{Arc, LazyLock},
|
|
||||||
};
|
|
||||||
|
|
||||||
use rustbreak::{DeSerError, DeSerializer};
|
|
||||||
use serde::{Serialize, de::DeserializeOwned};
|
|
||||||
|
|
||||||
use crate::interface::{DatabaseImpls, DatabaseInterface};
|
|
||||||
|
|
||||||
pub static DB: LazyLock<DatabaseInterface> = LazyLock::new(DatabaseInterface::set_up_database);
|
|
||||||
|
|
||||||
#[cfg(not(debug_assertions))]
|
|
||||||
static DATA_ROOT_PREFIX: &str = "drop";
|
|
||||||
#[cfg(debug_assertions)]
|
|
||||||
static DATA_ROOT_PREFIX: &str = "drop-debug";
|
|
||||||
|
|
||||||
pub static DATA_ROOT_DIR: LazyLock<Arc<PathBuf>> = LazyLock::new(|| {
|
|
||||||
Arc::new(
|
|
||||||
dirs::data_dir()
|
|
||||||
.expect("Failed to get data dir")
|
|
||||||
.join(DATA_ROOT_PREFIX),
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
// Custom JSON serializer to support everything we need
|
|
||||||
#[derive(Debug, Default, Clone)]
|
|
||||||
pub struct DropDatabaseSerializer;
|
|
||||||
|
|
||||||
impl<T: native_model::Model + Serialize + DeserializeOwned> DeSerializer<T>
|
|
||||||
for DropDatabaseSerializer
|
|
||||||
{
|
|
||||||
fn serialize(&self, val: &T) -> rustbreak::error::DeSerResult<Vec<u8>> {
|
|
||||||
native_model::encode(val).map_err(|e| DeSerError::Internal(e.to_string()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn deserialize<R: std::io::Read>(&self, mut s: R) -> rustbreak::error::DeSerResult<T> {
|
|
||||||
let mut buf = Vec::new();
|
|
||||||
s.read_to_end(&mut buf)
|
|
||||||
.map_err(|e| rustbreak::error::DeSerError::Other(e.into()))?;
|
|
||||||
let (val, _version) =
|
|
||||||
native_model::decode(buf).map_err(|e| DeSerError::Internal(e.to_string()))?;
|
|
||||||
Ok(val)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,14 +0,0 @@
|
|||||||
#![feature(nonpoison_rwlock)]
|
|
||||||
|
|
||||||
pub mod db;
|
|
||||||
pub mod debug;
|
|
||||||
pub mod interface;
|
|
||||||
pub mod models;
|
|
||||||
pub mod platform;
|
|
||||||
|
|
||||||
pub use db::DB;
|
|
||||||
pub use interface::{borrow_db_checked, borrow_db_mut_checked};
|
|
||||||
pub use models::data::{
|
|
||||||
ApplicationTransientStatus, Database, DatabaseApplications, DatabaseAuth, DownloadType,
|
|
||||||
DownloadableMetadata, GameDownloadStatus, GameVersion, Settings,
|
|
||||||
};
|
|
||||||
@ -1,46 +0,0 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
#[derive(Eq, Hash, PartialEq, Serialize, Deserialize, Clone, Copy, Debug)]
|
|
||||||
pub enum Platform {
|
|
||||||
Windows,
|
|
||||||
Linux,
|
|
||||||
MacOs,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Platform {
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
pub const HOST: Platform = Self::Windows;
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
pub const HOST: Platform = Self::MacOs;
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
pub const HOST: Platform = Self::Linux;
|
|
||||||
|
|
||||||
pub fn is_case_sensitive(&self) -> bool {
|
|
||||||
match self {
|
|
||||||
Self::Windows | Self::MacOs => false,
|
|
||||||
Self::Linux => true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<&str> for Platform {
|
|
||||||
fn from(value: &str) -> Self {
|
|
||||||
match value.to_lowercase().trim() {
|
|
||||||
"windows" => Self::Windows,
|
|
||||||
"linux" => Self::Linux,
|
|
||||||
"mac" | "macos" => Self::MacOs,
|
|
||||||
_ => unimplemented!(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<whoami::Platform> for Platform {
|
|
||||||
fn from(value: whoami::Platform) -> Self {
|
|
||||||
match value {
|
|
||||||
whoami::Platform::Windows => Platform::Windows,
|
|
||||||
whoami::Platform::Linux => Platform::Linux,
|
|
||||||
whoami::Platform::MacOS => Platform::MacOs,
|
|
||||||
platform => unimplemented!("Playform {} is not supported", platform),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,17 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "download_manager"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
atomic-instant-full = "0.1.0"
|
|
||||||
database = { version = "0.1.0", path = "../database" }
|
|
||||||
humansize = "2.1.3"
|
|
||||||
log = "0.4.28"
|
|
||||||
parking_lot = "0.12.5"
|
|
||||||
remote = { version = "0.1.0", path = "../remote" }
|
|
||||||
serde = "1.0.228"
|
|
||||||
serde_with = "3.15.0"
|
|
||||||
tauri = "2.8.5"
|
|
||||||
throttle_my_fn = "0.2.6"
|
|
||||||
utils = { version = "0.1.0", path = "../utils" }
|
|
||||||
@ -1,80 +0,0 @@
|
|||||||
use humansize::{BINARY, format_size};
|
|
||||||
use std::{
|
|
||||||
fmt::{Display, Formatter},
|
|
||||||
io,
|
|
||||||
sync::{Arc, mpsc::SendError},
|
|
||||||
};
|
|
||||||
|
|
||||||
use remote::error::RemoteAccessError;
|
|
||||||
use serde_with::SerializeDisplay;
|
|
||||||
|
|
||||||
#[derive(SerializeDisplay)]
|
|
||||||
pub enum DownloadManagerError<T> {
|
|
||||||
IOError(io::Error),
|
|
||||||
SignalError(SendError<T>),
|
|
||||||
}
|
|
||||||
impl<T> Display for DownloadManagerError<T> {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
match self {
|
|
||||||
DownloadManagerError::IOError(error) => write!(f, "{error}"),
|
|
||||||
DownloadManagerError::SignalError(send_error) => write!(f, "{send_error}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl<T> From<SendError<T>> for DownloadManagerError<T> {
|
|
||||||
fn from(value: SendError<T>) -> Self {
|
|
||||||
DownloadManagerError::SignalError(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl<T> From<io::Error> for DownloadManagerError<T> {
|
|
||||||
fn from(value: io::Error) -> Self {
|
|
||||||
DownloadManagerError::IOError(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Rename / separate from downloads
|
|
||||||
#[derive(Debug, SerializeDisplay)]
|
|
||||||
pub enum ApplicationDownloadError {
|
|
||||||
NotInitialized,
|
|
||||||
Communication(RemoteAccessError),
|
|
||||||
DiskFull(u64, u64),
|
|
||||||
#[allow(dead_code)]
|
|
||||||
Checksum,
|
|
||||||
Lock,
|
|
||||||
IoError(Arc<io::Error>),
|
|
||||||
DownloadError(RemoteAccessError),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for ApplicationDownloadError {
|
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
|
||||||
match self {
|
|
||||||
ApplicationDownloadError::NotInitialized => {
|
|
||||||
write!(f, "Download not initalized, did something go wrong?")
|
|
||||||
}
|
|
||||||
ApplicationDownloadError::DiskFull(required, available) => write!(
|
|
||||||
f,
|
|
||||||
"Game requires {}, {} remaining left on disk.",
|
|
||||||
format_size(*required, BINARY),
|
|
||||||
format_size(*available, BINARY),
|
|
||||||
),
|
|
||||||
ApplicationDownloadError::Communication(error) => write!(f, "{error}"),
|
|
||||||
ApplicationDownloadError::Lock => write!(
|
|
||||||
f,
|
|
||||||
"failed to acquire lock. Something has gone very wrong internally. Please restart the application"
|
|
||||||
),
|
|
||||||
ApplicationDownloadError::Checksum => {
|
|
||||||
write!(f, "checksum failed to validate for download")
|
|
||||||
}
|
|
||||||
ApplicationDownloadError::IoError(error) => write!(f, "io error: {error}"),
|
|
||||||
ApplicationDownloadError::DownloadError(error) => {
|
|
||||||
write!(f, "Download failed with error {error:?}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<io::Error> for ApplicationDownloadError {
|
|
||||||
fn from(value: io::Error) -> Self {
|
|
||||||
ApplicationDownloadError::IoError(Arc::new(value))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,24 +0,0 @@
|
|||||||
use database::DownloadableMetadata;
|
|
||||||
use serde::Serialize;
|
|
||||||
|
|
||||||
use crate::download_manager_frontend::DownloadStatus;
|
|
||||||
|
|
||||||
#[derive(Serialize, Clone)]
|
|
||||||
pub struct QueueUpdateEventQueueData {
|
|
||||||
pub meta: DownloadableMetadata,
|
|
||||||
pub status: DownloadStatus,
|
|
||||||
pub progress: f64,
|
|
||||||
pub current: usize,
|
|
||||||
pub max: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Clone)]
|
|
||||||
pub struct QueueUpdateEvent {
|
|
||||||
pub queue: Vec<QueueUpdateEventQueueData>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Clone)]
|
|
||||||
pub struct StatsUpdateEvent {
|
|
||||||
pub speed: usize,
|
|
||||||
pub time: usize,
|
|
||||||
}
|
|
||||||
@ -1,44 +0,0 @@
|
|||||||
#![feature(duration_millis_float)]
|
|
||||||
#![feature(nonpoison_mutex)]
|
|
||||||
#![feature(sync_nonpoison)]
|
|
||||||
|
|
||||||
use std::{ops::Deref, sync::OnceLock};
|
|
||||||
|
|
||||||
use tauri::AppHandle;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
download_manager_builder::DownloadManagerBuilder, download_manager_frontend::DownloadManager,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub mod download_manager_builder;
|
|
||||||
pub mod download_manager_frontend;
|
|
||||||
pub mod downloadable;
|
|
||||||
pub mod error;
|
|
||||||
pub mod frontend_updates;
|
|
||||||
pub mod util;
|
|
||||||
|
|
||||||
pub static DOWNLOAD_MANAGER: DownloadManagerWrapper = DownloadManagerWrapper::new();
|
|
||||||
|
|
||||||
pub struct DownloadManagerWrapper(OnceLock<DownloadManager>);
|
|
||||||
impl DownloadManagerWrapper {
|
|
||||||
const fn new() -> Self {
|
|
||||||
DownloadManagerWrapper(OnceLock::new())
|
|
||||||
}
|
|
||||||
pub fn init(app_handle: AppHandle) {
|
|
||||||
DOWNLOAD_MANAGER
|
|
||||||
.0
|
|
||||||
.set(DownloadManagerBuilder::build(app_handle))
|
|
||||||
.expect("Failed to initialise download manager");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Deref for DownloadManagerWrapper {
|
|
||||||
type Target = DownloadManager;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
match self.0.get() {
|
|
||||||
Some(download_manager) => download_manager,
|
|
||||||
None => unreachable!("Download manager should always be initialised"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,26 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "games"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
atomic-instant-full = "0.1.0"
|
|
||||||
bitcode = "0.6.7"
|
|
||||||
boxcar = "0.2.14"
|
|
||||||
database = { version = "0.1.0", path = "../database" }
|
|
||||||
download_manager = { version = "0.1.0", path = "../download_manager" }
|
|
||||||
hex = "0.4.3"
|
|
||||||
log = "0.4.28"
|
|
||||||
md5 = "0.8.0"
|
|
||||||
rayon = "1.11.0"
|
|
||||||
remote = { version = "0.1.0", path = "../remote" }
|
|
||||||
reqwest = "0.12.23"
|
|
||||||
rustix = "1.1.2"
|
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
|
||||||
serde_with = "3.15.0"
|
|
||||||
sysinfo = "0.37.2"
|
|
||||||
tauri = "2.8.5"
|
|
||||||
throttle_my_fn = "0.2.6"
|
|
||||||
utils = { version = "0.1.0", path = "../utils" }
|
|
||||||
native_model = { version = "0.6.4", features = ["rmp_serde_1_3"], git = "https://github.com/Drop-OSS/native_model.git"}
|
|
||||||
serde_json = "1.0.145"
|
|
||||||
@ -1,29 +0,0 @@
|
|||||||
use std::fmt::Display;
|
|
||||||
|
|
||||||
use serde_with::SerializeDisplay;
|
|
||||||
|
|
||||||
#[derive(SerializeDisplay)]
|
|
||||||
pub enum LibraryError {
|
|
||||||
MetaNotFound(String),
|
|
||||||
VersionNotFound(String),
|
|
||||||
}
|
|
||||||
impl Display for LibraryError {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"{}",
|
|
||||||
match self {
|
|
||||||
LibraryError::MetaNotFound(id) => {
|
|
||||||
format!(
|
|
||||||
"Could not locate any installed version of game ID {id} in the database"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
LibraryError::VersionNotFound(game_id) => {
|
|
||||||
format!(
|
|
||||||
"Could not locate any installed version for game id {game_id} in the database"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,300 +0,0 @@
|
|||||||
use bitcode::{Decode, Encode};
|
|
||||||
use database::{
|
|
||||||
ApplicationTransientStatus, Database, DownloadableMetadata, GameDownloadStatus, GameVersion,
|
|
||||||
borrow_db_checked, borrow_db_mut_checked,
|
|
||||||
};
|
|
||||||
use log::{debug, error, warn};
|
|
||||||
use remote::{
|
|
||||||
auth::generate_authorization_header, error::RemoteAccessError, requests::generate_url,
|
|
||||||
utils::DROP_CLIENT_SYNC,
|
|
||||||
};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use std::fs::remove_dir_all;
|
|
||||||
use std::thread::spawn;
|
|
||||||
use tauri::AppHandle;
|
|
||||||
use utils::app_emit;
|
|
||||||
|
|
||||||
use crate::state::{GameStatusManager, GameStatusWithTransient};
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
|
||||||
pub struct FetchGameStruct {
|
|
||||||
game: Game,
|
|
||||||
status: GameStatusWithTransient,
|
|
||||||
version: Option<GameVersion>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FetchGameStruct {
|
|
||||||
pub fn new(game: Game, status: GameStatusWithTransient, version: Option<GameVersion>) -> Self {
|
|
||||||
Self {
|
|
||||||
game,
|
|
||||||
status,
|
|
||||||
version,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, Default, Encode, Decode)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct Game {
|
|
||||||
id: String,
|
|
||||||
m_name: String,
|
|
||||||
m_short_description: String,
|
|
||||||
m_description: String,
|
|
||||||
// mDevelopers
|
|
||||||
// mPublishers
|
|
||||||
m_icon_object_id: String,
|
|
||||||
m_banner_object_id: String,
|
|
||||||
m_cover_object_id: String,
|
|
||||||
m_image_library_object_ids: Vec<String>,
|
|
||||||
m_image_carousel_object_ids: Vec<String>,
|
|
||||||
}
|
|
||||||
impl Game {
|
|
||||||
pub fn id(&self) -> &String {
|
|
||||||
&self.id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#[derive(serde::Serialize, Clone)]
|
|
||||||
pub struct GameUpdateEvent {
|
|
||||||
pub game_id: String,
|
|
||||||
pub status: (
|
|
||||||
Option<GameDownloadStatus>,
|
|
||||||
Option<ApplicationTransientStatus>,
|
|
||||||
),
|
|
||||||
pub version: Option<GameVersion>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Called by:
|
|
||||||
* - on_cancel, when cancelled, for obvious reasons
|
|
||||||
* - when downloading, so if drop unexpectedly quits, we can resume the download. hidden by the "Downloading..." transient state, though
|
|
||||||
* - when scanning, to import the game
|
|
||||||
*/
|
|
||||||
pub fn set_partially_installed(
|
|
||||||
meta: &DownloadableMetadata,
|
|
||||||
install_dir: String,
|
|
||||||
app_handle: Option<&AppHandle>,
|
|
||||||
) {
|
|
||||||
set_partially_installed_db(&mut borrow_db_mut_checked(), meta, install_dir, app_handle);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_partially_installed_db(
|
|
||||||
db_lock: &mut Database,
|
|
||||||
meta: &DownloadableMetadata,
|
|
||||||
install_dir: String,
|
|
||||||
app_handle: Option<&AppHandle>,
|
|
||||||
) {
|
|
||||||
db_lock.applications.transient_statuses.remove(meta);
|
|
||||||
db_lock.applications.game_statuses.insert(
|
|
||||||
meta.id.clone(),
|
|
||||||
GameDownloadStatus::PartiallyInstalled {
|
|
||||||
version_name: meta.version.as_ref().unwrap().clone(),
|
|
||||||
install_dir,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
db_lock
|
|
||||||
.applications
|
|
||||||
.installed_game_version
|
|
||||||
.insert(meta.id.clone(), meta.clone());
|
|
||||||
|
|
||||||
if let Some(app_handle) = app_handle {
|
|
||||||
push_game_update(
|
|
||||||
app_handle,
|
|
||||||
&meta.id,
|
|
||||||
None,
|
|
||||||
GameStatusManager::fetch_state(&meta.id, db_lock),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn uninstall_game_logic(meta: DownloadableMetadata, app_handle: &AppHandle) {
|
|
||||||
debug!("triggered uninstall for agent");
|
|
||||||
let mut db_handle = borrow_db_mut_checked();
|
|
||||||
db_handle
|
|
||||||
.applications
|
|
||||||
.transient_statuses
|
|
||||||
.insert(meta.clone(), ApplicationTransientStatus::Uninstalling {});
|
|
||||||
|
|
||||||
push_game_update(
|
|
||||||
app_handle,
|
|
||||||
&meta.id,
|
|
||||||
None,
|
|
||||||
GameStatusManager::fetch_state(&meta.id, &db_handle),
|
|
||||||
);
|
|
||||||
|
|
||||||
let previous_state = db_handle.applications.game_statuses.get(&meta.id).cloned();
|
|
||||||
|
|
||||||
let previous_state = if let Some(state) = previous_state {
|
|
||||||
state
|
|
||||||
} else {
|
|
||||||
warn!("uninstall job doesn't have previous state, failing silently");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Some((_, install_dir)) = match previous_state {
|
|
||||||
GameDownloadStatus::Installed {
|
|
||||||
version_name,
|
|
||||||
install_dir,
|
|
||||||
} => Some((version_name, install_dir)),
|
|
||||||
GameDownloadStatus::SetupRequired {
|
|
||||||
version_name,
|
|
||||||
install_dir,
|
|
||||||
} => Some((version_name, install_dir)),
|
|
||||||
GameDownloadStatus::PartiallyInstalled {
|
|
||||||
version_name,
|
|
||||||
install_dir,
|
|
||||||
} => Some((version_name, install_dir)),
|
|
||||||
_ => None,
|
|
||||||
} {
|
|
||||||
db_handle
|
|
||||||
.applications
|
|
||||||
.transient_statuses
|
|
||||||
.insert(meta.clone(), ApplicationTransientStatus::Uninstalling {});
|
|
||||||
|
|
||||||
drop(db_handle);
|
|
||||||
|
|
||||||
let app_handle = app_handle.clone();
|
|
||||||
spawn(move || {
|
|
||||||
if let Err(e) = remove_dir_all(install_dir) {
|
|
||||||
error!("{e}");
|
|
||||||
} else {
|
|
||||||
let mut db_handle = borrow_db_mut_checked();
|
|
||||||
db_handle.applications.transient_statuses.remove(&meta);
|
|
||||||
db_handle
|
|
||||||
.applications
|
|
||||||
.installed_game_version
|
|
||||||
.remove(&meta.id);
|
|
||||||
db_handle
|
|
||||||
.applications
|
|
||||||
.game_statuses
|
|
||||||
.insert(meta.id.clone(), GameDownloadStatus::Remote {});
|
|
||||||
let _ = db_handle.applications.transient_statuses.remove(&meta);
|
|
||||||
|
|
||||||
push_game_update(
|
|
||||||
&app_handle,
|
|
||||||
&meta.id,
|
|
||||||
None,
|
|
||||||
GameStatusManager::fetch_state(&meta.id, &db_handle),
|
|
||||||
);
|
|
||||||
|
|
||||||
debug!("uninstalled game id {}", &meta.id);
|
|
||||||
app_emit!(&app_handle, "update_library", ());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
warn!("invalid previous state for uninstall, failing silently.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_current_meta(game_id: &String) -> Option<DownloadableMetadata> {
|
|
||||||
borrow_db_checked()
|
|
||||||
.applications
|
|
||||||
.installed_game_version
|
|
||||||
.get(game_id)
|
|
||||||
.cloned()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn on_game_complete(
|
|
||||||
meta: &DownloadableMetadata,
|
|
||||||
install_dir: String,
|
|
||||||
app_handle: &AppHandle,
|
|
||||||
) -> Result<(), RemoteAccessError> {
|
|
||||||
// Fetch game version information from remote
|
|
||||||
if meta.version.is_none() {
|
|
||||||
return Err(RemoteAccessError::GameNotFound(meta.id.clone()));
|
|
||||||
}
|
|
||||||
|
|
||||||
let client = DROP_CLIENT_SYNC.clone();
|
|
||||||
let response = generate_url(
|
|
||||||
&["/api/v1/client/game/version"],
|
|
||||||
&[
|
|
||||||
("id", &meta.id),
|
|
||||||
("version", meta.version.as_ref().unwrap()),
|
|
||||||
],
|
|
||||||
)?;
|
|
||||||
let response = client
|
|
||||||
.get(response)
|
|
||||||
.header("Authorization", generate_authorization_header())
|
|
||||||
.send()?;
|
|
||||||
|
|
||||||
let game_version: GameVersion = response.json()?;
|
|
||||||
|
|
||||||
let mut handle = borrow_db_mut_checked();
|
|
||||||
handle
|
|
||||||
.applications
|
|
||||||
.game_versions
|
|
||||||
.entry(meta.id.clone())
|
|
||||||
.or_default()
|
|
||||||
.insert(meta.version.clone().unwrap(), game_version.clone());
|
|
||||||
handle
|
|
||||||
.applications
|
|
||||||
.installed_game_version
|
|
||||||
.insert(meta.id.clone(), meta.clone());
|
|
||||||
|
|
||||||
drop(handle);
|
|
||||||
|
|
||||||
let status = if game_version.setup_command.is_empty() {
|
|
||||||
GameDownloadStatus::Installed {
|
|
||||||
version_name: meta.version.clone().unwrap(),
|
|
||||||
install_dir,
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
GameDownloadStatus::SetupRequired {
|
|
||||||
version_name: meta.version.clone().unwrap(),
|
|
||||||
install_dir,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut db_handle = borrow_db_mut_checked();
|
|
||||||
db_handle
|
|
||||||
.applications
|
|
||||||
.game_statuses
|
|
||||||
.insert(meta.id.clone(), status.clone());
|
|
||||||
drop(db_handle);
|
|
||||||
app_emit!(
|
|
||||||
app_handle,
|
|
||||||
&format!("update_game/{}", meta.id),
|
|
||||||
GameUpdateEvent {
|
|
||||||
game_id: meta.id.clone(),
|
|
||||||
status: (Some(status), None),
|
|
||||||
version: Some(game_version),
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn push_game_update(
|
|
||||||
app_handle: &AppHandle,
|
|
||||||
game_id: &String,
|
|
||||||
version: Option<GameVersion>,
|
|
||||||
status: GameStatusWithTransient,
|
|
||||||
) {
|
|
||||||
if let Some(GameDownloadStatus::Installed { .. } | GameDownloadStatus::SetupRequired { .. }) =
|
|
||||||
&status.0
|
|
||||||
&& version.is_none()
|
|
||||||
{
|
|
||||||
panic!("pushed game for installed game that doesn't have version information");
|
|
||||||
}
|
|
||||||
|
|
||||||
app_emit!(
|
|
||||||
app_handle,
|
|
||||||
&format!("update_game/{game_id}"),
|
|
||||||
GameUpdateEvent {
|
|
||||||
game_id: game_id.clone(),
|
|
||||||
status,
|
|
||||||
version,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct FrontendGameOptions {
|
|
||||||
launch_string: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FrontendGameOptions {
|
|
||||||
pub fn launch_string(&self) -> &String {
|
|
||||||
&self.launch_string
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,19 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "process"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
chrono = "0.4.42"
|
|
||||||
client = { version = "0.1.0", path = "../client" }
|
|
||||||
database = { version = "0.1.0", path = "../database" }
|
|
||||||
dynfmt = "0.1.5"
|
|
||||||
games = { version = "0.1.0", path = "../games" }
|
|
||||||
log = "0.4.28"
|
|
||||||
page_size = "0.6.0"
|
|
||||||
serde = "1.0.228"
|
|
||||||
serde_with = "3.15.0"
|
|
||||||
shared_child = "1.1.1"
|
|
||||||
tauri = "2.8.5"
|
|
||||||
tauri-plugin-opener = "2.5.0"
|
|
||||||
utils = { version = "0.1.0", path = "../utils" }
|
|
||||||
@ -1,41 +0,0 @@
|
|||||||
#![feature(nonpoison_mutex)]
|
|
||||||
#![feature(sync_nonpoison)]
|
|
||||||
|
|
||||||
use std::{
|
|
||||||
ops::Deref,
|
|
||||||
sync::{OnceLock, nonpoison::Mutex},
|
|
||||||
};
|
|
||||||
|
|
||||||
use tauri::AppHandle;
|
|
||||||
|
|
||||||
use crate::process_manager::ProcessManager;
|
|
||||||
|
|
||||||
pub static PROCESS_MANAGER: ProcessManagerWrapper = ProcessManagerWrapper::new();
|
|
||||||
|
|
||||||
pub mod error;
|
|
||||||
pub mod format;
|
|
||||||
pub mod process_handlers;
|
|
||||||
pub mod process_manager;
|
|
||||||
|
|
||||||
pub struct ProcessManagerWrapper(OnceLock<Mutex<ProcessManager<'static>>>);
|
|
||||||
impl ProcessManagerWrapper {
|
|
||||||
const fn new() -> Self {
|
|
||||||
ProcessManagerWrapper(OnceLock::new())
|
|
||||||
}
|
|
||||||
pub fn init(app_handle: AppHandle) {
|
|
||||||
PROCESS_MANAGER
|
|
||||||
.0
|
|
||||||
.set(Mutex::new(ProcessManager::new(app_handle)))
|
|
||||||
.unwrap_or_else(|_| panic!("Failed to initialise Process Manager")); // Using panic! here because we can't implement Debug
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl Deref for ProcessManagerWrapper {
|
|
||||||
type Target = Mutex<ProcessManager<'static>>;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
match self.0.get() {
|
|
||||||
Some(process_manager) => process_manager,
|
|
||||||
None => unreachable!("Download manager should always be initialised"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,23 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "remote"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
bitcode = "0.6.7"
|
|
||||||
chrono = "0.4.42"
|
|
||||||
client = { version = "0.1.0", path = "../client" }
|
|
||||||
database = { version = "0.1.0", path = "../database" }
|
|
||||||
droplet-rs = "0.7.3"
|
|
||||||
gethostname = "1.0.2"
|
|
||||||
hex = "0.4.3"
|
|
||||||
http = "1.3.1"
|
|
||||||
log = "0.4.28"
|
|
||||||
md5 = "0.8.0"
|
|
||||||
reqwest = "0.12.23"
|
|
||||||
reqwest-websocket = "0.5.1"
|
|
||||||
serde = "1.0.228"
|
|
||||||
serde_with = "3.15.0"
|
|
||||||
tauri = "2.8.5"
|
|
||||||
url = "2.5.7"
|
|
||||||
utils = { version = "0.1.0", path = "../utils" }
|
|
||||||
@ -1,152 +0,0 @@
|
|||||||
use std::{collections::HashMap, env};
|
|
||||||
|
|
||||||
use chrono::Utc;
|
|
||||||
use client::{app_status::AppStatus, user::User};
|
|
||||||
use database::{DatabaseAuth, interface::borrow_db_checked};
|
|
||||||
use droplet_rs::ssl::sign_nonce;
|
|
||||||
use gethostname::gethostname;
|
|
||||||
use log::{error, warn};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use url::Url;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
error::{DropServerError, RemoteAccessError},
|
|
||||||
requests::make_authenticated_get,
|
|
||||||
utils::DROP_CLIENT_SYNC,
|
|
||||||
};
|
|
||||||
|
|
||||||
use super::{
|
|
||||||
cache::{cache_object, get_cached_object},
|
|
||||||
requests::generate_url,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
struct CapabilityConfiguration {}
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
struct InitiateRequestBody {
|
|
||||||
name: String,
|
|
||||||
platform: String,
|
|
||||||
capabilities: HashMap<String, CapabilityConfiguration>,
|
|
||||||
mode: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct HandshakeRequestBody {
|
|
||||||
client_id: String,
|
|
||||||
token: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HandshakeRequestBody {
|
|
||||||
pub fn new(client_id: String, token: String) -> Self {
|
|
||||||
Self { client_id, token }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct HandshakeResponse {
|
|
||||||
private: String,
|
|
||||||
certificate: String,
|
|
||||||
id: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<HandshakeResponse> for DatabaseAuth {
|
|
||||||
fn from(value: HandshakeResponse) -> Self {
|
|
||||||
DatabaseAuth::new(value.private, value.certificate, value.id, None)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn generate_authorization_header() -> String {
|
|
||||||
let certs = {
|
|
||||||
let db = borrow_db_checked();
|
|
||||||
db.auth.clone().expect("Authorisation not initialised")
|
|
||||||
};
|
|
||||||
|
|
||||||
let nonce = Utc::now().timestamp_millis().to_string();
|
|
||||||
|
|
||||||
let signature =
|
|
||||||
sign_nonce(certs.private, nonce.clone()).expect("Failed to generate authorisation header");
|
|
||||||
|
|
||||||
format!("Nonce {} {} {}", certs.client_id, nonce, signature)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn fetch_user() -> Result<User, RemoteAccessError> {
|
|
||||||
let response = make_authenticated_get(generate_url(&["/api/v1/client/user"], &[])?).await?;
|
|
||||||
if response.status() != 200 {
|
|
||||||
let err: DropServerError = response.json().await?;
|
|
||||||
warn!("{err:?}");
|
|
||||||
|
|
||||||
if err.status_message == "Nonce expired" {
|
|
||||||
return Err(RemoteAccessError::OutOfSync);
|
|
||||||
}
|
|
||||||
|
|
||||||
return Err(RemoteAccessError::InvalidResponse(err));
|
|
||||||
}
|
|
||||||
|
|
||||||
response
|
|
||||||
.json::<User>()
|
|
||||||
.await
|
|
||||||
.map_err(std::convert::Into::into)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn auth_initiate_logic(mode: String) -> Result<String, RemoteAccessError> {
|
|
||||||
let base_url = {
|
|
||||||
let db_lock = borrow_db_checked();
|
|
||||||
Url::parse(&db_lock.base_url.clone())?
|
|
||||||
};
|
|
||||||
|
|
||||||
let hostname = gethostname();
|
|
||||||
|
|
||||||
let endpoint = base_url.join("/api/v1/client/auth/initiate")?;
|
|
||||||
let body = InitiateRequestBody {
|
|
||||||
name: format!("{} (Desktop)", hostname.display()),
|
|
||||||
platform: env::consts::OS.to_string(),
|
|
||||||
capabilities: HashMap::from([
|
|
||||||
("peerAPI".to_owned(), CapabilityConfiguration {}),
|
|
||||||
("cloudSaves".to_owned(), CapabilityConfiguration {}),
|
|
||||||
]),
|
|
||||||
mode,
|
|
||||||
};
|
|
||||||
|
|
||||||
let client = DROP_CLIENT_SYNC.clone();
|
|
||||||
let response = client.post(endpoint.to_string()).json(&body).send()?;
|
|
||||||
|
|
||||||
if response.status() != 200 {
|
|
||||||
let data: DropServerError = response.json()?;
|
|
||||||
error!("could not start handshake: {}", data.status_message);
|
|
||||||
|
|
||||||
return Err(RemoteAccessError::HandshakeFailed(data.status_message));
|
|
||||||
}
|
|
||||||
|
|
||||||
let response = response.text()?;
|
|
||||||
|
|
||||||
Ok(response)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn setup() -> (AppStatus, Option<User>) {
|
|
||||||
let auth = {
|
|
||||||
let data = borrow_db_checked();
|
|
||||||
data.auth.clone()
|
|
||||||
};
|
|
||||||
|
|
||||||
if auth.is_some() {
|
|
||||||
let user_result = match fetch_user().await {
|
|
||||||
Ok(data) => data,
|
|
||||||
Err(RemoteAccessError::FetchError(_)) => {
|
|
||||||
let user = get_cached_object::<User>("user").ok();
|
|
||||||
return (AppStatus::Offline, user);
|
|
||||||
}
|
|
||||||
Err(_) => return (AppStatus::SignedInNeedsReauth, None),
|
|
||||||
};
|
|
||||||
if let Err(e) = cache_object("user", &user_result) {
|
|
||||||
warn!("Could not cache user object with error {e}");
|
|
||||||
}
|
|
||||||
return (AppStatus::SignedIn, Some(user_result));
|
|
||||||
}
|
|
||||||
|
|
||||||
(AppStatus::SignedOut, None)
|
|
||||||
}
|
|
||||||
@ -1,82 +0,0 @@
|
|||||||
use database::{DB, interface::DatabaseImpls};
|
|
||||||
use http::{Response, header::CONTENT_TYPE, response::Builder as ResponseBuilder};
|
|
||||||
use log::{debug, warn};
|
|
||||||
use tauri::UriSchemeResponder;
|
|
||||||
|
|
||||||
use crate::{error::CacheError, utils::DROP_CLIENT_ASYNC};
|
|
||||||
|
|
||||||
use super::{
|
|
||||||
auth::generate_authorization_header,
|
|
||||||
cache::{ObjectCache, cache_object, get_cached_object},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub async fn fetch_object_wrapper(request: http::Request<Vec<u8>>, responder: UriSchemeResponder) {
|
|
||||||
match fetch_object(request).await {
|
|
||||||
Ok(r) => responder.respond(r),
|
|
||||||
Err(e) => {
|
|
||||||
warn!("Cache error: {e}");
|
|
||||||
responder.respond(
|
|
||||||
Response::builder()
|
|
||||||
.status(500)
|
|
||||||
.body(Vec::new())
|
|
||||||
.expect("Failed to build error response"),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn fetch_object(
|
|
||||||
request: http::Request<Vec<u8>>,
|
|
||||||
) -> Result<Response<Vec<u8>>, CacheError> {
|
|
||||||
// Drop leading /
|
|
||||||
let object_id = &request.uri().path()[1..];
|
|
||||||
|
|
||||||
let cache_result = get_cached_object::<ObjectCache>(object_id);
|
|
||||||
if let Ok(cache_result) = &cache_result
|
|
||||||
&& !cache_result.has_expired()
|
|
||||||
{
|
|
||||||
return cache_result.try_into();
|
|
||||||
}
|
|
||||||
|
|
||||||
let header = generate_authorization_header();
|
|
||||||
let client = DROP_CLIENT_ASYNC.clone();
|
|
||||||
let url = format!("{}api/v1/client/object/{object_id}", DB.fetch_base_url());
|
|
||||||
let response = client.get(url).header("Authorization", header).send().await;
|
|
||||||
|
|
||||||
match response {
|
|
||||||
Ok(r) => {
|
|
||||||
let resp_builder = ResponseBuilder::new().header(
|
|
||||||
CONTENT_TYPE,
|
|
||||||
r.headers()
|
|
||||||
.get("Content-Type")
|
|
||||||
.expect("Failed get Content-Type header"),
|
|
||||||
);
|
|
||||||
let data = match r.bytes().await {
|
|
||||||
Ok(data) => Vec::from(data),
|
|
||||||
Err(e) => {
|
|
||||||
warn!("Could not get data from cache object {object_id} with error {e}",);
|
|
||||||
Vec::new()
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let resp = resp_builder
|
|
||||||
.body(data)
|
|
||||||
.expect("Failed to build object cache response body");
|
|
||||||
if cache_result.map_or(true, |x| x.has_expired()) {
|
|
||||||
cache_object::<ObjectCache>(object_id, &resp.clone().try_into()?)
|
|
||||||
.expect("Failed to create cached object");
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(resp)
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
debug!("Object fetch failed with error {e}. Attempting to download from cache");
|
|
||||||
match cache_result {
|
|
||||||
Ok(cache_result) => cache_result.try_into(),
|
|
||||||
Err(e) => {
|
|
||||||
warn!("{e}");
|
|
||||||
Err(CacheError::Remote(e))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,108 +0,0 @@
|
|||||||
use std::str::FromStr;
|
|
||||||
|
|
||||||
use database::borrow_db_checked;
|
|
||||||
use http::{Request, Response, StatusCode, Uri, uri::PathAndQuery};
|
|
||||||
use log::{error, warn};
|
|
||||||
use tauri::UriSchemeResponder;
|
|
||||||
use utils::webbrowser_open::webbrowser_open;
|
|
||||||
|
|
||||||
use crate::utils::DROP_CLIENT_SYNC;
|
|
||||||
|
|
||||||
pub async fn handle_server_proto_offline_wrapper(
|
|
||||||
request: Request<Vec<u8>>,
|
|
||||||
responder: UriSchemeResponder,
|
|
||||||
) {
|
|
||||||
responder.respond(match handle_server_proto_offline(request).await {
|
|
||||||
Ok(res) => res,
|
|
||||||
Err(_) => unreachable!(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn handle_server_proto_offline(
|
|
||||||
_request: Request<Vec<u8>>,
|
|
||||||
) -> Result<Response<Vec<u8>>, StatusCode> {
|
|
||||||
Ok(Response::builder()
|
|
||||||
.status(StatusCode::NOT_FOUND)
|
|
||||||
.body(Vec::new())
|
|
||||||
.expect("Failed to build error response for proto offline"))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn handle_server_proto_wrapper(request: Request<Vec<u8>>, responder: UriSchemeResponder) {
|
|
||||||
match handle_server_proto(request).await {
|
|
||||||
Ok(r) => responder.respond(r),
|
|
||||||
Err(e) => {
|
|
||||||
warn!("Cache error: {e}");
|
|
||||||
responder.respond(
|
|
||||||
Response::builder()
|
|
||||||
.status(e)
|
|
||||||
.body(Vec::new())
|
|
||||||
.expect("Failed to build error response"),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle_server_proto(request: Request<Vec<u8>>) -> Result<Response<Vec<u8>>, StatusCode> {
|
|
||||||
let db_handle = borrow_db_checked();
|
|
||||||
let auth = match db_handle.auth.as_ref() {
|
|
||||||
Some(auth) => auth,
|
|
||||||
None => {
|
|
||||||
error!("Could not find auth in database");
|
|
||||||
return Err(StatusCode::UNAUTHORIZED);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let web_token = match &auth.web_token {
|
|
||||||
Some(token) => token,
|
|
||||||
None => return Err(StatusCode::UNAUTHORIZED),
|
|
||||||
};
|
|
||||||
let remote_uri = db_handle
|
|
||||||
.base_url
|
|
||||||
.parse::<Uri>()
|
|
||||||
.expect("Failed to parse base url");
|
|
||||||
|
|
||||||
let path = request.uri().path();
|
|
||||||
|
|
||||||
let mut new_uri = request.uri().clone().into_parts();
|
|
||||||
new_uri.path_and_query = Some(
|
|
||||||
PathAndQuery::from_str(&format!("{path}?noWrapper=true"))
|
|
||||||
.expect("Failed to parse request path in proto"),
|
|
||||||
);
|
|
||||||
new_uri.authority = remote_uri.authority().cloned();
|
|
||||||
new_uri.scheme = remote_uri.scheme().cloned();
|
|
||||||
let err_msg = &format!("Failed to build new uri from parts {new_uri:?}");
|
|
||||||
let new_uri = Uri::from_parts(new_uri).expect(err_msg);
|
|
||||||
|
|
||||||
let whitelist_prefix = ["/store", "/api", "/_", "/fonts"];
|
|
||||||
|
|
||||||
if whitelist_prefix.iter().all(|f| !path.starts_with(f)) {
|
|
||||||
webbrowser_open(new_uri.to_string());
|
|
||||||
return Ok(Response::new(Vec::new()));
|
|
||||||
}
|
|
||||||
|
|
||||||
let client = DROP_CLIENT_SYNC.clone();
|
|
||||||
let response = match client
|
|
||||||
.request(request.method().clone(), new_uri.to_string())
|
|
||||||
.header("Authorization", format!("Bearer {web_token}"))
|
|
||||||
.headers(request.headers().clone())
|
|
||||||
.send()
|
|
||||||
{
|
|
||||||
Ok(response) => response,
|
|
||||||
Err(e) => {
|
|
||||||
warn!("Could not send response. Got {e} when sending");
|
|
||||||
return Err(e.status().unwrap_or(StatusCode::BAD_REQUEST));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let response_status = response.status();
|
|
||||||
let response_body = match response.bytes() {
|
|
||||||
Ok(bytes) => bytes,
|
|
||||||
Err(e) => return Err(e.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)),
|
|
||||||
};
|
|
||||||
|
|
||||||
let http_response = Response::builder()
|
|
||||||
.status(response_status)
|
|
||||||
.body(response_body.to_vec())
|
|
||||||
.expect("Failed to build server proto response");
|
|
||||||
|
|
||||||
Ok(http_response)
|
|
||||||
}
|
|
||||||
@ -1,119 +0,0 @@
|
|||||||
use std::{
|
|
||||||
fs::{self, File},
|
|
||||||
io::Read,
|
|
||||||
sync::LazyLock,
|
|
||||||
};
|
|
||||||
|
|
||||||
use database::db::DATA_ROOT_DIR;
|
|
||||||
use log::{debug, info, warn};
|
|
||||||
use reqwest::Certificate;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct DropHealthcheck {
|
|
||||||
app_name: String,
|
|
||||||
}
|
|
||||||
impl DropHealthcheck {
|
|
||||||
pub fn app_name(&self) -> &String {
|
|
||||||
&self.app_name
|
|
||||||
}
|
|
||||||
}
|
|
||||||
static DROP_CERT_BUNDLE: LazyLock<Vec<Certificate>> = LazyLock::new(fetch_certificates);
|
|
||||||
pub static DROP_CLIENT_SYNC: LazyLock<reqwest::blocking::Client> = LazyLock::new(get_client_sync);
|
|
||||||
pub static DROP_CLIENT_ASYNC: LazyLock<reqwest::Client> = LazyLock::new(get_client_async);
|
|
||||||
pub static DROP_CLIENT_WS_CLIENT: LazyLock<reqwest::Client> = LazyLock::new(get_client_ws);
|
|
||||||
|
|
||||||
fn fetch_certificates() -> Vec<Certificate> {
|
|
||||||
let certificate_dir = DATA_ROOT_DIR.join("certificates");
|
|
||||||
|
|
||||||
let mut certs = Vec::new();
|
|
||||||
match fs::read_dir(certificate_dir) {
|
|
||||||
Ok(c) => {
|
|
||||||
for entry in c {
|
|
||||||
match entry {
|
|
||||||
Ok(c) => {
|
|
||||||
let mut buf = Vec::new();
|
|
||||||
match File::open(c.path()) {
|
|
||||||
Ok(f) => f,
|
|
||||||
Err(e) => {
|
|
||||||
warn!(
|
|
||||||
"Failed to open file at {} with error {}",
|
|
||||||
c.path().display(),
|
|
||||||
e
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.read_to_end(&mut buf)
|
|
||||||
.unwrap_or_else(|e| {
|
|
||||||
panic!(
|
|
||||||
"Failed to read to end of certificate file {} with error {}",
|
|
||||||
c.path().display(),
|
|
||||||
e
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
match Certificate::from_pem_bundle(&buf) {
|
|
||||||
Ok(certificates) => {
|
|
||||||
for cert in certificates {
|
|
||||||
certs.push(cert);
|
|
||||||
}
|
|
||||||
info!(
|
|
||||||
"added {} certificate(s) from {}",
|
|
||||||
certs.len(),
|
|
||||||
c.file_name().display()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Err(e) => warn!(
|
|
||||||
"Invalid certificate file {} with error {}",
|
|
||||||
c.path().display(),
|
|
||||||
e
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(_) => todo!(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
debug!("not loading certificates due to error: {e}");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
certs
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_client_sync() -> reqwest::blocking::Client {
|
|
||||||
let mut client = reqwest::blocking::ClientBuilder::new();
|
|
||||||
|
|
||||||
for cert in DROP_CERT_BUNDLE.iter() {
|
|
||||||
client = client.add_root_certificate(cert.clone());
|
|
||||||
}
|
|
||||||
client
|
|
||||||
.use_rustls_tls()
|
|
||||||
.build()
|
|
||||||
.expect("Failed to build synchronous client")
|
|
||||||
}
|
|
||||||
pub fn get_client_async() -> reqwest::Client {
|
|
||||||
let mut client = reqwest::ClientBuilder::new();
|
|
||||||
|
|
||||||
for cert in DROP_CERT_BUNDLE.iter() {
|
|
||||||
client = client.add_root_certificate(cert.clone());
|
|
||||||
}
|
|
||||||
client
|
|
||||||
.use_rustls_tls()
|
|
||||||
.build()
|
|
||||||
.expect("Failed to build asynchronous client")
|
|
||||||
}
|
|
||||||
pub fn get_client_ws() -> reqwest::Client {
|
|
||||||
let mut client = reqwest::ClientBuilder::new();
|
|
||||||
|
|
||||||
for cert in DROP_CERT_BUNDLE.iter() {
|
|
||||||
client = client.add_root_certificate(cert.clone());
|
|
||||||
}
|
|
||||||
client
|
|
||||||
.use_rustls_tls()
|
|
||||||
.http1_only()
|
|
||||||
.build()
|
|
||||||
.expect("Failed to build websocket client")
|
|
||||||
}
|
|
||||||
@ -1,41 +1,9 @@
|
|||||||
use std::sync::nonpoison::Mutex;
|
use crate::database::db::{borrow_db_checked, borrow_db_mut_checked};
|
||||||
|
use log::debug;
|
||||||
use database::{borrow_db_checked, borrow_db_mut_checked};
|
|
||||||
use download_manager::DOWNLOAD_MANAGER;
|
|
||||||
use log::{debug, error};
|
|
||||||
use tauri::AppHandle;
|
use tauri::AppHandle;
|
||||||
use tauri_plugin_autostart::ManagerExt;
|
use tauri_plugin_autostart::ManagerExt;
|
||||||
|
|
||||||
use crate::AppState;
|
pub fn toggle_autostart_logic(app: AppHandle, enabled: bool) -> Result<(), String> {
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn fetch_state(state: tauri::State<'_, Mutex<AppState>>) -> Result<String, String> {
|
|
||||||
let guard = state.lock();
|
|
||||||
let cloned_state = serde_json::to_string(&guard.clone()).map_err(|e| e.to_string())?;
|
|
||||||
drop(guard);
|
|
||||||
Ok(cloned_state)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn quit(app: tauri::AppHandle) {
|
|
||||||
cleanup_and_exit(&app);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn cleanup_and_exit(app: &AppHandle) {
|
|
||||||
debug!("cleaning up and exiting application");
|
|
||||||
match DOWNLOAD_MANAGER.ensure_terminated() {
|
|
||||||
Ok(res) => match res {
|
|
||||||
Ok(()) => debug!("download manager terminated correctly"),
|
|
||||||
Err(()) => error!("download manager failed to terminate correctly"),
|
|
||||||
},
|
|
||||||
Err(e) => panic!("{e:?}"),
|
|
||||||
}
|
|
||||||
|
|
||||||
app.exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn toggle_autostart(app: AppHandle, enabled: bool) -> Result<(), String> {
|
|
||||||
let manager = app.autolaunch();
|
let manager = app.autolaunch();
|
||||||
if enabled {
|
if enabled {
|
||||||
manager.enable().map_err(|e| e.to_string())?;
|
manager.enable().map_err(|e| e.to_string())?;
|
||||||
@ -48,11 +16,13 @@ pub fn toggle_autostart(app: AppHandle, enabled: bool) -> Result<(), String> {
|
|||||||
// Store the state in DB
|
// Store the state in DB
|
||||||
let mut db_handle = borrow_db_mut_checked();
|
let mut db_handle = borrow_db_mut_checked();
|
||||||
db_handle.settings.autostart = enabled;
|
db_handle.settings.autostart = enabled;
|
||||||
|
drop(db_handle);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
pub fn get_autostart_enabled_logic(app: AppHandle) -> Result<bool, tauri_plugin_autostart::Error> {
|
||||||
pub fn get_autostart_enabled(app: AppHandle) -> Result<bool, tauri_plugin_autostart::Error> {
|
// First check DB state
|
||||||
let db_handle = borrow_db_checked();
|
let db_handle = borrow_db_checked();
|
||||||
let db_state = db_handle.settings.autostart;
|
let db_state = db_handle.settings.autostart;
|
||||||
drop(db_handle);
|
drop(db_handle);
|
||||||
@ -72,3 +42,34 @@ pub fn get_autostart_enabled(app: AppHandle) -> Result<bool, tauri_plugin_autost
|
|||||||
|
|
||||||
Ok(db_state)
|
Ok(db_state)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// New function to sync state on startup
|
||||||
|
pub fn sync_autostart_on_startup(app: &AppHandle) -> Result<(), String> {
|
||||||
|
let db_handle = borrow_db_checked();
|
||||||
|
let should_be_enabled = db_handle.settings.autostart;
|
||||||
|
drop(db_handle);
|
||||||
|
|
||||||
|
let manager = app.autolaunch();
|
||||||
|
let current_state = manager.is_enabled().map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
if current_state != should_be_enabled {
|
||||||
|
if should_be_enabled {
|
||||||
|
manager.enable().map_err(|e| e.to_string())?;
|
||||||
|
debug!("synced autostart: enabled");
|
||||||
|
} else {
|
||||||
|
manager.disable().map_err(|e| e.to_string())?;
|
||||||
|
debug!("synced autostart: disabled");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn toggle_autostart(app: AppHandle, enabled: bool) -> Result<(), String> {
|
||||||
|
toggle_autostart_logic(app, enabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn get_autostart_enabled(app: AppHandle) -> Result<bool, tauri_plugin_autostart::Error> {
|
||||||
|
get_autostart_enabled_logic(app)
|
||||||
|
}
|
||||||
23
src-tauri/src/client/cleanup.rs
Normal file
23
src-tauri/src/client/cleanup.rs
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
use log::{debug, error};
|
||||||
|
use tauri::AppHandle;
|
||||||
|
|
||||||
|
use crate::AppState;
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn quit(app: tauri::AppHandle, state: tauri::State<'_, std::sync::Mutex<AppState<'_>>>) {
|
||||||
|
cleanup_and_exit(&app, &state);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cleanup_and_exit(app: &AppHandle, state: &tauri::State<'_, std::sync::Mutex<AppState<'_>>>) {
|
||||||
|
debug!("cleaning up and exiting application");
|
||||||
|
let download_manager = state.lock().unwrap().download_manager.clone();
|
||||||
|
match download_manager.ensure_terminated() {
|
||||||
|
Ok(res) => match res {
|
||||||
|
Ok(()) => debug!("download manager terminated correctly"),
|
||||||
|
Err(()) => error!("download manager failed to terminate correctly"),
|
||||||
|
},
|
||||||
|
Err(e) => panic!("{e:?}"),
|
||||||
|
}
|
||||||
|
|
||||||
|
app.exit(0);
|
||||||
|
}
|
||||||
11
src-tauri/src/client/commands.rs
Normal file
11
src-tauri/src/client/commands.rs
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
use crate::AppState;
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn fetch_state(
|
||||||
|
state: tauri::State<'_, std::sync::Mutex<AppState<'_>>>,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
let guard = state.lock().unwrap();
|
||||||
|
let cloned_state = serde_json::to_string(&guard.clone()).map_err(|e| e.to_string())?;
|
||||||
|
drop(guard);
|
||||||
|
Ok(cloned_state)
|
||||||
|
}
|
||||||
3
src-tauri/src/client/mod.rs
Normal file
3
src-tauri/src/client/mod.rs
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
pub mod autostart;
|
||||||
|
pub mod cleanup;
|
||||||
|
pub mod commands;
|
||||||
102
src-tauri/src/cloud_saves/backup_manager.rs
Normal file
102
src-tauri/src/cloud_saves/backup_manager.rs
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
use std::{collections::HashMap, path::PathBuf, str::FromStr};
|
||||||
|
|
||||||
|
use log::warn;
|
||||||
|
|
||||||
|
use crate::{database::db::{GameVersion, DATA_ROOT_DIR}, error::backup_error::BackupError, process::process_manager::Platform};
|
||||||
|
|
||||||
|
use super::path::CommonPath;
|
||||||
|
|
||||||
|
pub struct BackupManager<'a> {
|
||||||
|
pub current_platform: Platform,
|
||||||
|
pub sources: HashMap<(Platform, Platform), &'a (dyn BackupHandler + Sync + Send)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BackupManager<'_> {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
BackupManager {
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
current_platform: Platform::Windows,
|
||||||
|
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
current_platform: Platform::MacOs,
|
||||||
|
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
current_platform: Platform::Linux,
|
||||||
|
|
||||||
|
sources: HashMap::from([
|
||||||
|
// Current platform to target platform
|
||||||
|
(
|
||||||
|
(Platform::Windows, Platform::Windows),
|
||||||
|
&WindowsBackupManager {} as &(dyn BackupHandler + Sync + Send),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
(Platform::Linux, Platform::Linux),
|
||||||
|
&LinuxBackupManager {} as &(dyn BackupHandler + Sync + Send),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
(Platform::MacOs, Platform::MacOs),
|
||||||
|
&MacBackupManager {} as &(dyn BackupHandler + Sync + Send),
|
||||||
|
),
|
||||||
|
|
||||||
|
]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait BackupHandler: Send + Sync {
|
||||||
|
fn root_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(DATA_ROOT_DIR.lock().unwrap().join("games")) }
|
||||||
|
fn game_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(PathBuf::from_str(&game.game_id).unwrap()) }
|
||||||
|
fn base_translate(&self, path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(self.root_translate(path, game)?.join(self.game_translate(path, game)?)) }
|
||||||
|
fn home_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { let c = CommonPath::Home.get().ok_or(BackupError::NotFound); println!("{:?}", c); c }
|
||||||
|
fn store_user_id_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { PathBuf::from_str(&game.game_id).map_err(|_| BackupError::ParseError) }
|
||||||
|
fn os_user_name_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(PathBuf::from_str(&whoami::username()).unwrap()) }
|
||||||
|
fn win_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winAppData>"); Err(BackupError::InvalidSystem) }
|
||||||
|
fn win_local_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winLocalAppData>"); Err(BackupError::InvalidSystem) }
|
||||||
|
fn win_local_app_data_low_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winLocalAppDataLow>"); Err(BackupError::InvalidSystem) }
|
||||||
|
fn win_documents_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winDocuments>"); Err(BackupError::InvalidSystem) }
|
||||||
|
fn win_public_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winPublic>"); Err(BackupError::InvalidSystem) }
|
||||||
|
fn win_program_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winProgramData>"); Err(BackupError::InvalidSystem) }
|
||||||
|
fn win_dir_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winDir>"); Err(BackupError::InvalidSystem) }
|
||||||
|
fn xdg_data_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected XDG Reference in Backup <xdgData>"); Err(BackupError::InvalidSystem) }
|
||||||
|
fn xdg_config_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected XDG Reference in Backup <xdgConfig>"); Err(BackupError::InvalidSystem) }
|
||||||
|
fn skip_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(PathBuf::new()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct LinuxBackupManager {}
|
||||||
|
impl BackupHandler for LinuxBackupManager {
|
||||||
|
fn xdg_config_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||||
|
Ok(CommonPath::Data.get().ok_or(BackupError::NotFound)?)
|
||||||
|
}
|
||||||
|
fn xdg_data_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||||
|
Ok(CommonPath::Config.get().ok_or(BackupError::NotFound)?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub struct WindowsBackupManager {}
|
||||||
|
impl BackupHandler for WindowsBackupManager {
|
||||||
|
fn win_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||||
|
Ok(CommonPath::Config.get().ok_or(BackupError::NotFound)?)
|
||||||
|
}
|
||||||
|
fn win_local_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||||
|
Ok(CommonPath::DataLocal.get().ok_or(BackupError::NotFound)?)
|
||||||
|
}
|
||||||
|
fn win_local_app_data_low_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||||
|
Ok(CommonPath::DataLocalLow.get().ok_or(BackupError::NotFound)?)
|
||||||
|
}
|
||||||
|
fn win_dir_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||||
|
Ok(PathBuf::from_str("C:/Windows").unwrap())
|
||||||
|
}
|
||||||
|
fn win_documents_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||||
|
Ok(CommonPath::Document.get().ok_or(BackupError::NotFound)?)
|
||||||
|
|
||||||
|
}
|
||||||
|
fn win_program_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||||
|
Ok(PathBuf::from_str("C:/ProgramData").unwrap())
|
||||||
|
}
|
||||||
|
fn win_public_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||||
|
Ok(CommonPath::Public.get().ok_or(BackupError::NotFound)?)
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub struct MacBackupManager {}
|
||||||
|
impl BackupHandler for MacBackupManager {}
|
||||||
@ -1,7 +1,6 @@
|
|||||||
use database::platform::Platform;
|
use crate::process::process_manager::Platform;
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||||
pub enum Condition {
|
pub enum Condition {
|
||||||
Os(Platform),
|
Os(Platform)
|
||||||
Other
|
|
||||||
}
|
}
|
||||||
@ -1,6 +1,7 @@
|
|||||||
use database::GameVersion;
|
use crate::database::db::GameVersion;
|
||||||
|
|
||||||
|
use super::conditions::{Condition};
|
||||||
|
|
||||||
use super::conditions::Condition;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||||
pub struct CloudSaveMetadata {
|
pub struct CloudSaveMetadata {
|
||||||
@ -15,17 +16,15 @@ pub struct GameFile {
|
|||||||
pub id: Option<String>,
|
pub id: Option<String>,
|
||||||
pub data_type: DataType,
|
pub data_type: DataType,
|
||||||
pub tags: Vec<Tag>,
|
pub tags: Vec<Tag>,
|
||||||
pub conditions: Vec<Condition>,
|
pub conditions: Vec<Condition>
|
||||||
}
|
}
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
|
||||||
pub enum DataType {
|
pub enum DataType {
|
||||||
Registry,
|
Registry,
|
||||||
File,
|
File,
|
||||||
Other,
|
Other
|
||||||
}
|
}
|
||||||
#[derive(
|
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
|
||||||
Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
|
|
||||||
)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub enum Tag {
|
pub enum Tag {
|
||||||
Config,
|
Config,
|
||||||
@ -33,4 +32,4 @@ pub enum Tag {
|
|||||||
#[default]
|
#[default]
|
||||||
#[serde(other)]
|
#[serde(other)]
|
||||||
Other,
|
Other,
|
||||||
}
|
}
|
||||||
@ -1,10 +1,11 @@
|
|||||||
use std::sync::LazyLock;
|
use std::sync::LazyLock;
|
||||||
|
|
||||||
use database::platform::Platform;
|
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
|
use crate::process::process_manager::Platform;
|
||||||
|
|
||||||
use super::placeholder::*;
|
use super::placeholder::*;
|
||||||
|
|
||||||
|
|
||||||
pub fn normalize(path: &str, os: Platform) -> String {
|
pub fn normalize(path: &str, os: Platform) -> String {
|
||||||
let mut path = path.trim().trim_end_matches(['/', '\\']).replace('\\', "/");
|
let mut path = path.trim().trim_end_matches(['/', '\\']).replace('\\', "/");
|
||||||
|
|
||||||
@ -13,25 +14,18 @@ pub fn normalize(path: &str, os: Platform) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static CONSECUTIVE_SLASHES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"/{2,}").unwrap());
|
static CONSECUTIVE_SLASHES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"/{2,}").unwrap());
|
||||||
static UNNECESSARY_DOUBLE_STAR_1: LazyLock<Regex> =
|
static UNNECESSARY_DOUBLE_STAR_1: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"([^/*])\*{2,}").unwrap());
|
||||||
LazyLock::new(|| Regex::new(r"([^/*])\*{2,}").unwrap());
|
static UNNECESSARY_DOUBLE_STAR_2: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*{2,}([^/*])").unwrap());
|
||||||
static UNNECESSARY_DOUBLE_STAR_2: LazyLock<Regex> =
|
|
||||||
LazyLock::new(|| Regex::new(r"\*{2,}([^/*])").unwrap());
|
|
||||||
static ENDING_WILDCARD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\*)+$").unwrap());
|
static ENDING_WILDCARD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\*)+$").unwrap());
|
||||||
static ENDING_DOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\.)$").unwrap());
|
static ENDING_DOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\.)$").unwrap());
|
||||||
static INTERMEDIATE_DOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\./)").unwrap());
|
static INTERMEDIATE_DOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\./)").unwrap());
|
||||||
static BLANK_SEGMENT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\s+/)").unwrap());
|
static BLANK_SEGMENT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\s+/)").unwrap());
|
||||||
static APP_DATA: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%appdata%").unwrap());
|
static APP_DATA: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%appdata%").unwrap());
|
||||||
static APP_DATA_ROAMING: LazyLock<Regex> =
|
static APP_DATA_ROAMING: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Roaming").unwrap());
|
||||||
LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Roaming").unwrap());
|
static APP_DATA_LOCAL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%localappdata%").unwrap());
|
||||||
static APP_DATA_LOCAL: LazyLock<Regex> =
|
static APP_DATA_LOCAL_2: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Local/").unwrap());
|
||||||
LazyLock::new(|| Regex::new(r"(?i)%localappdata%").unwrap());
|
static USER_PROFILE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%").unwrap());
|
||||||
static APP_DATA_LOCAL_2: LazyLock<Regex> =
|
static DOCUMENTS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/Documents").unwrap());
|
||||||
LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Local/").unwrap());
|
|
||||||
static USER_PROFILE: LazyLock<Regex> =
|
|
||||||
LazyLock::new(|| Regex::new(r"(?i)%userprofile%").unwrap());
|
|
||||||
static DOCUMENTS: LazyLock<Regex> =
|
|
||||||
LazyLock::new(|| Regex::new(r"(?i)%userprofile%/Documents").unwrap());
|
|
||||||
|
|
||||||
for (pattern, replacement) in [
|
for (pattern, replacement) in [
|
||||||
(&CONSECUTIVE_SLASHES, "/"),
|
(&CONSECUTIVE_SLASHES, "/"),
|
||||||
@ -72,9 +66,7 @@ pub fn normalize(path: &str, os: Platform) -> String {
|
|||||||
|
|
||||||
fn too_broad(path: &str) -> bool {
|
fn too_broad(path: &str) -> bool {
|
||||||
println!("Path: {}", path);
|
println!("Path: {}", path);
|
||||||
use {
|
use {BASE, HOME, ROOT, STORE_USER_ID, WIN_APP_DATA, WIN_DIR, WIN_DOCUMENTS, XDG_CONFIG, XDG_DATA};
|
||||||
BASE, HOME, ROOT, STORE_USER_ID, WIN_APP_DATA, WIN_DIR, WIN_DOCUMENTS, XDG_CONFIG, XDG_DATA,
|
|
||||||
};
|
|
||||||
|
|
||||||
let path_lower = path.to_lowercase();
|
let path_lower = path.to_lowercase();
|
||||||
|
|
||||||
@ -85,9 +77,7 @@ fn too_broad(path: &str) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for item in AVOID_WILDCARDS {
|
for item in AVOID_WILDCARDS {
|
||||||
if path.starts_with(&format!("{}/*", item))
|
if path.starts_with(&format!("{}/*", item)) || path.starts_with(&format!("{}/{}", item, STORE_USER_ID)) {
|
||||||
|| path.starts_with(&format!("{}/{}", item, STORE_USER_ID))
|
|
||||||
{
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -134,6 +124,7 @@ fn too_broad(path: &str) -> bool {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Drive letters:
|
// Drive letters:
|
||||||
let drives: Regex = Regex::new(r"^[a-zA-Z]:$").unwrap();
|
let drives: Regex = Regex::new(r"^[a-zA-Z]:$").unwrap();
|
||||||
@ -168,4 +159,4 @@ pub fn usable(path: &str) -> bool {
|
|||||||
&& !path.starts_with("../")
|
&& !path.starts_with("../")
|
||||||
&& !too_broad(path)
|
&& !too_broad(path)
|
||||||
&& !unprintable.is_match(path)
|
&& !unprintable.is_match(path)
|
||||||
}
|
}
|
||||||
@ -13,12 +13,12 @@ pub enum CommonPath {
|
|||||||
|
|
||||||
impl CommonPath {
|
impl CommonPath {
|
||||||
pub fn get(&self) -> Option<PathBuf> {
|
pub fn get(&self) -> Option<PathBuf> {
|
||||||
static CONFIG: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::config_dir);
|
static CONFIG: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::config_dir());
|
||||||
static DATA: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::data_dir);
|
static DATA: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::data_dir());
|
||||||
static DATA_LOCAL: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::data_local_dir);
|
static DATA_LOCAL: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::data_local_dir());
|
||||||
static DOCUMENT: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::document_dir);
|
static DOCUMENT: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::document_dir());
|
||||||
static HOME: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::home_dir);
|
static HOME: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::home_dir());
|
||||||
static PUBLIC: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::public_dir);
|
static PUBLIC: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::public_dir());
|
||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
static DATA_LOCAL_LOW: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
|
static DATA_LOCAL_LOW: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
|
||||||
@ -48,4 +48,4 @@ pub const XDG_DATA: &str = "<xdgData>"; // %WINDIR% on Windows
|
|||||||
pub const XDG_CONFIG: &str = "<xdgConfig>"; // $XDG_DATA_HOME on Linux
|
pub const XDG_CONFIG: &str = "<xdgConfig>"; // $XDG_DATA_HOME on Linux
|
||||||
pub const SKIP: &str = "<skip>"; // $XDG_CONFIG_HOME on Linux
|
pub const SKIP: &str = "<skip>"; // $XDG_CONFIG_HOME on Linux
|
||||||
|
|
||||||
pub static OS_USERNAME: LazyLock<String> = LazyLock::new(whoami::username);
|
pub static OS_USERNAME: LazyLock<String> = LazyLock::new(|| whoami::username());
|
||||||
@ -1,17 +1,22 @@
|
|||||||
use std::{
|
use std::{
|
||||||
fs::{self, File, create_dir_all},
|
fs::{self, create_dir_all, File},
|
||||||
io::{self, Read, Write},
|
io::{self, ErrorKind, Read, Write},
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
|
thread::sleep,
|
||||||
|
time::Duration,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::error::BackupError;
|
use super::{
|
||||||
|
backup_manager::BackupHandler, conditions::Condition, metadata::GameFile, placeholder::*,
|
||||||
use super::{backup_manager::BackupHandler, placeholder::*};
|
};
|
||||||
use database::GameVersion;
|
|
||||||
use log::{debug, warn};
|
use log::{debug, warn};
|
||||||
use rustix::path::Arg;
|
use rustix::path::Arg;
|
||||||
use tempfile::tempfile;
|
use tempfile::tempfile;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
database::db::GameVersion, error::backup_error::BackupError, process::process_manager::Platform,
|
||||||
|
};
|
||||||
|
|
||||||
use super::{backup_manager::BackupManager, metadata::CloudSaveMetadata, normalise::normalize};
|
use super::{backup_manager::BackupManager, metadata::CloudSaveMetadata, normalise::normalize};
|
||||||
|
|
||||||
pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
|
pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
|
||||||
@ -26,7 +31,7 @@ pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
|
|||||||
.iter()
|
.iter()
|
||||||
.find_map(|p| match p {
|
.find_map(|p| match p {
|
||||||
super::conditions::Condition::Os(os) => Some(os),
|
super::conditions::Condition::Os(os) => Some(os),
|
||||||
_ => None
|
_ => None,
|
||||||
})
|
})
|
||||||
.cloned()
|
.cloned()
|
||||||
{
|
{
|
||||||
@ -59,7 +64,7 @@ pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
|
|||||||
let binding = serde_json::to_string(meta).unwrap();
|
let binding = serde_json::to_string(meta).unwrap();
|
||||||
let serialized = binding.as_bytes();
|
let serialized = binding.as_bytes();
|
||||||
let mut file = tempfile().unwrap();
|
let mut file = tempfile().unwrap();
|
||||||
file.write_all(serialized).unwrap();
|
file.write(serialized).unwrap();
|
||||||
tarball.append_file("metadata", &mut file).unwrap();
|
tarball.append_file("metadata", &mut file).unwrap();
|
||||||
tarball.into_inner().unwrap().finish().unwrap()
|
tarball.into_inner().unwrap().finish().unwrap()
|
||||||
}
|
}
|
||||||
@ -92,7 +97,7 @@ pub fn extract(file: PathBuf) -> Result<(), BackupError> {
|
|||||||
.iter()
|
.iter()
|
||||||
.find_map(|p| match p {
|
.find_map(|p| match p {
|
||||||
super::conditions::Condition::Os(os) => Some(os),
|
super::conditions::Condition::Os(os) => Some(os),
|
||||||
_ => None
|
_ => None,
|
||||||
})
|
})
|
||||||
.cloned()
|
.cloned()
|
||||||
{
|
{
|
||||||
@ -111,7 +116,7 @@ pub fn extract(file: PathBuf) -> Result<(), BackupError> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let new_path = parse_path(file.path.into(), handler, &manifest.game_version)?;
|
let new_path = parse_path(file.path.into(), handler, &manifest.game_version)?;
|
||||||
create_dir_all(new_path.parent().unwrap()).unwrap();
|
create_dir_all(&new_path.parent().unwrap()).unwrap();
|
||||||
|
|
||||||
println!(
|
println!(
|
||||||
"Current path {:?} copying to {:?}",
|
"Current path {:?} copying to {:?}",
|
||||||
@ -128,22 +133,23 @@ pub fn copy_item<P: AsRef<Path>>(src: P, dest: P) -> io::Result<()> {
|
|||||||
let src_path = src.as_ref();
|
let src_path = src.as_ref();
|
||||||
let dest_path = dest.as_ref();
|
let dest_path = dest.as_ref();
|
||||||
|
|
||||||
let metadata = fs::metadata(src_path)?;
|
let metadata = fs::metadata(&src_path)?;
|
||||||
|
|
||||||
if metadata.is_file() {
|
if metadata.is_file() {
|
||||||
// Ensure the parent directory of the destination exists for a file copy
|
// Ensure the parent directory of the destination exists for a file copy
|
||||||
if let Some(parent) = dest_path.parent() {
|
if let Some(parent) = dest_path.parent() {
|
||||||
fs::create_dir_all(parent)?;
|
fs::create_dir_all(parent)?;
|
||||||
}
|
}
|
||||||
fs::copy(src_path, dest_path)?;
|
fs::copy(&src_path, &dest_path)?;
|
||||||
} else if metadata.is_dir() {
|
} else if metadata.is_dir() {
|
||||||
// For directories, we call the recursive helper function.
|
// For directories, we call the recursive helper function.
|
||||||
// The destination for the recursive copy is the `dest_path` itself.
|
// The destination for the recursive copy is the `dest_path` itself.
|
||||||
copy_dir_recursive(src_path, dest_path)?;
|
copy_dir_recursive(&src_path, &dest_path)?;
|
||||||
} else {
|
} else {
|
||||||
// Handle other file types like symlinks if necessary,
|
// Handle other file types like symlinks if necessary,
|
||||||
// for now, return an error or skip.
|
// for now, return an error or skip.
|
||||||
return Err(io::Error::other(
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::Other,
|
||||||
format!("Source {:?} is neither a file nor a directory", src_path),
|
format!("Source {:?} is neither a file nor a directory", src_path),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@ -152,7 +158,7 @@ pub fn copy_item<P: AsRef<Path>>(src: P, dest: P) -> io::Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn copy_dir_recursive(src: &Path, dest: &Path) -> io::Result<()> {
|
fn copy_dir_recursive(src: &Path, dest: &Path) -> io::Result<()> {
|
||||||
fs::create_dir_all(dest)?;
|
fs::create_dir_all(&dest)?;
|
||||||
|
|
||||||
for entry in fs::read_dir(src)? {
|
for entry in fs::read_dir(src)? {
|
||||||
let entry = entry?;
|
let entry = entry?;
|
||||||
@ -214,3 +220,43 @@ pub fn parse_path(
|
|||||||
println!("Final line: {:?}", &s);
|
println!("Final line: {:?}", &s);
|
||||||
Ok(s)
|
Ok(s)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn test() {
|
||||||
|
let mut meta = CloudSaveMetadata {
|
||||||
|
files: vec![
|
||||||
|
GameFile {
|
||||||
|
path: String::from("<home>/favicon.png"),
|
||||||
|
id: None,
|
||||||
|
data_type: super::metadata::DataType::File,
|
||||||
|
tags: Vec::new(),
|
||||||
|
conditions: vec![Condition::Os(Platform::Linux)],
|
||||||
|
},
|
||||||
|
GameFile {
|
||||||
|
path: String::from("<home>/Documents/Pixel Art"),
|
||||||
|
id: None,
|
||||||
|
data_type: super::metadata::DataType::File,
|
||||||
|
tags: Vec::new(),
|
||||||
|
conditions: vec![Condition::Os(Platform::Linux)],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
game_version: GameVersion {
|
||||||
|
game_id: String::new(),
|
||||||
|
version_name: String::new(),
|
||||||
|
platform: Platform::Linux,
|
||||||
|
launch_command: String::new(),
|
||||||
|
launch_args: Vec::new(),
|
||||||
|
launch_command_template: String::new(),
|
||||||
|
setup_command: String::new(),
|
||||||
|
setup_args: Vec::new(),
|
||||||
|
setup_command_template: String::new(),
|
||||||
|
only_setup: true,
|
||||||
|
version_index: 0,
|
||||||
|
delta: false,
|
||||||
|
umu_id_override: None,
|
||||||
|
},
|
||||||
|
save_id: String::from("aaaaaaa"),
|
||||||
|
};
|
||||||
|
//resolve(&mut meta);
|
||||||
|
|
||||||
|
extract("save".into()).unwrap();
|
||||||
|
}
|
||||||
@ -4,14 +4,18 @@ use std::{
|
|||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
};
|
};
|
||||||
|
|
||||||
use database::{
|
|
||||||
Settings, borrow_db_checked, borrow_db_mut_checked, db::DATA_ROOT_DIR, debug::SystemData,
|
|
||||||
};
|
|
||||||
use download_manager::error::DownloadManagerError;
|
|
||||||
use games::scan::scan_install_dirs;
|
|
||||||
use log::error;
|
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
database::{db::borrow_db_mut_checked, scan::scan_install_dirs}, error::download_manager_error::DownloadManagerError,
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
db::{borrow_db_checked, DATA_ROOT_DIR},
|
||||||
|
debug::SystemData,
|
||||||
|
models::data::Settings,
|
||||||
|
};
|
||||||
|
|
||||||
// Will, in future, return disk/remaining size
|
// Will, in future, return disk/remaining size
|
||||||
// Just returns the directories that have been set up
|
// Just returns the directories that have been set up
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@ -63,25 +67,11 @@ pub fn add_download_dir(new_dir: PathBuf) -> Result<(), DownloadManagerError<()>
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn update_settings(new_settings: Value) {
|
pub fn update_settings(new_settings: Value) {
|
||||||
let mut db_lock = borrow_db_mut_checked();
|
let mut db_lock = borrow_db_mut_checked();
|
||||||
let mut current_settings =
|
let mut current_settings = serde_json::to_value(db_lock.settings.clone()).unwrap();
|
||||||
serde_json::to_value(db_lock.settings.clone()).expect("Failed to parse existing settings");
|
for (key, value) in new_settings.as_object().unwrap() {
|
||||||
let values = match new_settings.as_object() {
|
|
||||||
Some(values) => values,
|
|
||||||
None => {
|
|
||||||
error!("Could not parse settings values into object");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
for (key, value) in values {
|
|
||||||
current_settings[key] = value.clone();
|
current_settings[key] = value.clone();
|
||||||
}
|
}
|
||||||
let new_settings: Settings = match serde_json::from_value(current_settings) {
|
let new_settings: Settings = serde_json::from_value(current_settings).unwrap();
|
||||||
Ok(settings) => settings,
|
|
||||||
Err(e) => {
|
|
||||||
error!("Could not parse settings with error {}", e);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
db_lock.settings = new_settings;
|
db_lock.settings = new_settings;
|
||||||
}
|
}
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@ -3,18 +3,48 @@ use std::{
|
|||||||
mem::ManuallyDrop,
|
mem::ManuallyDrop,
|
||||||
ops::{Deref, DerefMut},
|
ops::{Deref, DerefMut},
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
sync::{RwLockReadGuard, RwLockWriteGuard},
|
sync::{Arc, LazyLock, RwLockReadGuard, RwLockWriteGuard},
|
||||||
};
|
};
|
||||||
|
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use log::{debug, error, info, warn};
|
use log::{debug, error, info, warn};
|
||||||
use rustbreak::{PathDatabase, RustbreakError};
|
use rustbreak::{DeSerError, DeSerializer, PathDatabase, RustbreakError};
|
||||||
|
use serde::{Serialize, de::DeserializeOwned};
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
use crate::{
|
use crate::DB;
|
||||||
db::{DATA_ROOT_DIR, DB, DropDatabaseSerializer},
|
|
||||||
models::data::Database,
|
use super::models::data::Database;
|
||||||
};
|
|
||||||
|
#[cfg(not(debug_assertions))]
|
||||||
|
static DATA_ROOT_PREFIX: &'static str = "drop";
|
||||||
|
#[cfg(debug_assertions)]
|
||||||
|
static DATA_ROOT_PREFIX: &str = "drop-debug";
|
||||||
|
|
||||||
|
pub static DATA_ROOT_DIR: LazyLock<Arc<PathBuf>> =
|
||||||
|
LazyLock::new(|| Arc::new(dirs::data_dir().unwrap().join(DATA_ROOT_PREFIX)));
|
||||||
|
|
||||||
|
// Custom JSON serializer to support everything we need
|
||||||
|
#[derive(Debug, Default, Clone)]
|
||||||
|
pub struct DropDatabaseSerializer;
|
||||||
|
|
||||||
|
impl<T: native_model::Model + Serialize + DeserializeOwned> DeSerializer<T>
|
||||||
|
for DropDatabaseSerializer
|
||||||
|
{
|
||||||
|
fn serialize(&self, val: &T) -> rustbreak::error::DeSerResult<Vec<u8>> {
|
||||||
|
native_model::encode(val)
|
||||||
|
.map_err(|e| DeSerError::Internal(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize<R: std::io::Read>(&self, mut s: R) -> rustbreak::error::DeSerResult<T> {
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
s.read_to_end(&mut buf)
|
||||||
|
.map_err(|e| rustbreak::error::DeSerError::Other(e.into()))?;
|
||||||
|
let (val, _version) = native_model::decode(buf)
|
||||||
|
.map_err(|e| DeSerError::Internal(e.to_string()))?;
|
||||||
|
Ok(val)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub type DatabaseInterface =
|
pub type DatabaseInterface =
|
||||||
rustbreak::Database<Database, rustbreak::backend::PathBackend, DropDatabaseSerializer>;
|
rustbreak::Database<Database, rustbreak::backend::PathBackend, DropDatabaseSerializer>;
|
||||||
@ -33,49 +63,13 @@ impl DatabaseImpls for DatabaseInterface {
|
|||||||
let pfx_dir = DATA_ROOT_DIR.join("pfx");
|
let pfx_dir = DATA_ROOT_DIR.join("pfx");
|
||||||
|
|
||||||
debug!("creating data directory at {DATA_ROOT_DIR:?}");
|
debug!("creating data directory at {DATA_ROOT_DIR:?}");
|
||||||
create_dir_all(DATA_ROOT_DIR.as_path()).unwrap_or_else(|e| {
|
create_dir_all(DATA_ROOT_DIR.as_path()).unwrap();
|
||||||
panic!(
|
create_dir_all(&games_base_dir).unwrap();
|
||||||
"Failed to create directory {} with error {}",
|
create_dir_all(&logs_root_dir).unwrap();
|
||||||
DATA_ROOT_DIR.display(),
|
create_dir_all(&cache_dir).unwrap();
|
||||||
e
|
create_dir_all(&pfx_dir).unwrap();
|
||||||
)
|
|
||||||
});
|
|
||||||
create_dir_all(&games_base_dir).unwrap_or_else(|e| {
|
|
||||||
panic!(
|
|
||||||
"Failed to create directory {} with error {}",
|
|
||||||
games_base_dir.display(),
|
|
||||||
e
|
|
||||||
)
|
|
||||||
});
|
|
||||||
create_dir_all(&logs_root_dir).unwrap_or_else(|e| {
|
|
||||||
panic!(
|
|
||||||
"Failed to create directory {} with error {}",
|
|
||||||
logs_root_dir.display(),
|
|
||||||
e
|
|
||||||
)
|
|
||||||
});
|
|
||||||
create_dir_all(&cache_dir).unwrap_or_else(|e| {
|
|
||||||
panic!(
|
|
||||||
"Failed to create directory {} with error {}",
|
|
||||||
cache_dir.display(),
|
|
||||||
e
|
|
||||||
)
|
|
||||||
});
|
|
||||||
create_dir_all(&pfx_dir).unwrap_or_else(|e| {
|
|
||||||
panic!(
|
|
||||||
"Failed to create directory {} with error {}",
|
|
||||||
pfx_dir.display(),
|
|
||||||
e
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
let exists = fs::exists(db_path.clone()).unwrap_or_else(|e| {
|
let exists = fs::exists(db_path.clone()).unwrap();
|
||||||
panic!(
|
|
||||||
"Failed to find if {} exists with error {}",
|
|
||||||
db_path.display(),
|
|
||||||
e
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
if exists {
|
if exists {
|
||||||
match PathDatabase::load_from_path(db_path.clone()) {
|
match PathDatabase::load_from_path(db_path.clone()) {
|
||||||
@ -84,19 +78,21 @@ impl DatabaseImpls for DatabaseInterface {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let default = Database::new(games_base_dir, None, cache_dir);
|
let default = Database::new(games_base_dir, None, cache_dir);
|
||||||
debug!("Creating database at path {}", db_path.display());
|
debug!(
|
||||||
|
"Creating database at path {}",
|
||||||
|
db_path.as_os_str().to_str().unwrap()
|
||||||
|
);
|
||||||
PathDatabase::create_at_path(db_path, default).expect("Database could not be created")
|
PathDatabase::create_at_path(db_path, default).expect("Database could not be created")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn database_is_set_up(&self) -> bool {
|
fn database_is_set_up(&self) -> bool {
|
||||||
!borrow_db_checked().base_url.is_empty()
|
!self.borrow_data().unwrap().base_url.is_empty()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn fetch_base_url(&self) -> Url {
|
fn fetch_base_url(&self) -> Url {
|
||||||
let handle = borrow_db_checked();
|
let handle = self.borrow_data().unwrap();
|
||||||
Url::parse(&handle.base_url)
|
Url::parse(&handle.base_url).unwrap()
|
||||||
.unwrap_or_else(|_| panic!("Failed to parse base url {}", handle.base_url))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -115,16 +111,13 @@ fn handle_invalid_database(
|
|||||||
base
|
base
|
||||||
};
|
};
|
||||||
info!("old database stored at: {}", new_path.to_string_lossy());
|
info!("old database stored at: {}", new_path.to_string_lossy());
|
||||||
fs::rename(&db_path, &new_path).unwrap_or_else(|e| {
|
fs::rename(&db_path, &new_path).unwrap();
|
||||||
panic!(
|
|
||||||
"Could not rename database {} to {} with error {}",
|
|
||||||
db_path.display(),
|
|
||||||
new_path.display(),
|
|
||||||
e
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
let db = Database::new(games_base_dir, Some(new_path), cache_dir);
|
let db = Database::new(
|
||||||
|
games_base_dir.into_os_string().into_string().unwrap(),
|
||||||
|
Some(new_path),
|
||||||
|
cache_dir,
|
||||||
|
);
|
||||||
|
|
||||||
PathDatabase::create_at_path(db_path, db).expect("Database could not be created")
|
PathDatabase::create_at_path(db_path, db).expect("Database could not be created")
|
||||||
}
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user