mirror of
https://github.com/Drop-OSS/drop-app.git
synced 2025-11-13 00:02:41 +10:00
Compare commits
4 Commits
31f7d5bcfa
...
113-bug-li
| Author | SHA1 | Date | |
|---|---|---|---|
| fe456cc2ef | |||
| 42ff3b1331 | |||
| db485b946b | |||
| 346ee1dddc |
4
.gitignore
vendored
4
.gitignore
vendored
@ -29,6 +29,4 @@ src-tauri/flamegraph.svg
|
||||
src-tauri/perf*
|
||||
|
||||
/*.AppImage
|
||||
/squashfs-root
|
||||
|
||||
/target/
|
||||
/squashfs-root
|
||||
@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<NuxtLoadingIndicator color="#2563eb" />
|
||||
<NuxtLoadingIndicator color="#2563eb" />
|
||||
<NuxtLayout class="select-none w-screen h-screen">
|
||||
<NuxtPage />
|
||||
<ModalStack />
|
||||
@ -7,7 +7,14 @@
|
||||
</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();
|
||||
|
||||
|
||||
@ -2,7 +2,9 @@
|
||||
<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="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">
|
||||
<ol class="inline-flex items-center gap-x-6">
|
||||
<NuxtLink
|
||||
@ -40,7 +42,7 @@
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
<WindowControl />
|
||||
<WindowControl />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@ -76,6 +76,7 @@ import { Menu, MenuButton, MenuItem, MenuItems } from "@headlessui/vue";
|
||||
import { ChevronDownIcon } from "@heroicons/vue/16/solid";
|
||||
import type { NavigationItem } from "../types";
|
||||
import HeaderWidget from "./HeaderWidget.vue";
|
||||
import { useAppState } from "~/composables/app-state";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
|
||||
const open = ref(false);
|
||||
|
||||
@ -73,7 +73,7 @@
|
||||
alt=""
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-col gap-x-2">
|
||||
<div class="inline-flex items-center gap-x-2">
|
||||
<p
|
||||
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>
|
||||
@ -1,5 +1,5 @@
|
||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
|
||||
export const useObject = (id: string) => {
|
||||
export const useObject = async (id: string) => {
|
||||
return convertFileSrc(id, "object");
|
||||
};
|
||||
@ -9,17 +9,13 @@ export default defineNuxtConfig({
|
||||
},
|
||||
},
|
||||
|
||||
css: ["~/assets/main.scss"],
|
||||
|
||||
ssr: false,
|
||||
|
||||
extends: ["../shared", "../libs/drop-base"],
|
||||
extends: [["../libs/drop-base"]],
|
||||
|
||||
app: {
|
||||
baseURL: "/main",
|
||||
},
|
||||
|
||||
devtools: {
|
||||
enabled: false,
|
||||
},
|
||||
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
@ -7,7 +7,6 @@ export default {
|
||||
"./plugins/**/*.{js,ts}",
|
||||
"./app.vue",
|
||||
"./error.vue",
|
||||
"../shared/components/**/*.vue"
|
||||
],
|
||||
theme: {
|
||||
extend: {
|
||||
|
||||
@ -14,8 +14,7 @@
|
||||
"@tauri-apps/plugin-os": "^2.3.0",
|
||||
"@tauri-apps/plugin-shell": "^2.3.0",
|
||||
"pino": "^9.7.0",
|
||||
"pino-pretty": "^13.1.1",
|
||||
"tauri": "^0.15.0"
|
||||
"pino-pretty": "^13.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@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"
|
||||
# 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]
|
||||
version = "0.1.5"
|
||||
features = ["curly"]
|
||||
@ -137,18 +127,3 @@ features = ["derive", "rc"]
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
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 database::{borrow_db_checked, borrow_db_mut_checked};
|
||||
use download_manager::DOWNLOAD_MANAGER;
|
||||
use log::{debug, error};
|
||||
use crate::database::db::{borrow_db_checked, borrow_db_mut_checked};
|
||||
use log::debug;
|
||||
use tauri::AppHandle;
|
||||
use tauri_plugin_autostart::ManagerExt;
|
||||
|
||||
use crate::AppState;
|
||||
|
||||
#[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> {
|
||||
pub fn toggle_autostart_logic(app: AppHandle, enabled: bool) -> Result<(), String> {
|
||||
let manager = app.autolaunch();
|
||||
if enabled {
|
||||
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
|
||||
let mut db_handle = borrow_db_mut_checked();
|
||||
db_handle.settings.autostart = enabled;
|
||||
drop(db_handle);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_autostart_enabled(app: AppHandle) -> Result<bool, tauri_plugin_autostart::Error> {
|
||||
pub fn get_autostart_enabled_logic(app: AppHandle) -> Result<bool, tauri_plugin_autostart::Error> {
|
||||
// First check DB state
|
||||
let db_handle = borrow_db_checked();
|
||||
let db_state = db_handle.settings.autostart;
|
||||
drop(db_handle);
|
||||
@ -72,3 +42,34 @@ pub fn get_autostart_enabled(app: AppHandle) -> Result<bool, tauri_plugin_autost
|
||||
|
||||
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)]
|
||||
pub enum Condition {
|
||||
Os(Platform),
|
||||
Other
|
||||
Os(Platform)
|
||||
}
|
||||
@ -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)]
|
||||
pub struct CloudSaveMetadata {
|
||||
@ -15,17 +16,15 @@ pub struct GameFile {
|
||||
pub id: Option<String>,
|
||||
pub data_type: DataType,
|
||||
pub tags: Vec<Tag>,
|
||||
pub conditions: Vec<Condition>,
|
||||
pub conditions: Vec<Condition>
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
|
||||
pub enum DataType {
|
||||
Registry,
|
||||
File,
|
||||
Other,
|
||||
Other
|
||||
}
|
||||
#[derive(
|
||||
Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
|
||||
)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Tag {
|
||||
Config,
|
||||
@ -33,4 +32,4 @@ pub enum Tag {
|
||||
#[default]
|
||||
#[serde(other)]
|
||||
Other,
|
||||
}
|
||||
}
|
||||
@ -1,10 +1,11 @@
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use database::platform::Platform;
|
||||
use regex::Regex;
|
||||
use crate::process::process_manager::Platform;
|
||||
|
||||
use super::placeholder::*;
|
||||
|
||||
|
||||
pub fn normalize(path: &str, os: Platform) -> String {
|
||||
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 UNNECESSARY_DOUBLE_STAR_1: LazyLock<Regex> =
|
||||
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_1: 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_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 APP_DATA: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%appdata%").unwrap());
|
||||
static APP_DATA_ROAMING: LazyLock<Regex> =
|
||||
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_2: LazyLock<Regex> =
|
||||
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());
|
||||
static APP_DATA_ROAMING: LazyLock<Regex> = 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_2: LazyLock<Regex> = 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 [
|
||||
(&CONSECUTIVE_SLASHES, "/"),
|
||||
@ -72,9 +66,7 @@ pub fn normalize(path: &str, os: Platform) -> String {
|
||||
|
||||
fn too_broad(path: &str) -> bool {
|
||||
println!("Path: {}", path);
|
||||
use {
|
||||
BASE, HOME, ROOT, STORE_USER_ID, WIN_APP_DATA, WIN_DIR, WIN_DOCUMENTS, XDG_CONFIG, XDG_DATA,
|
||||
};
|
||||
use {BASE, HOME, ROOT, STORE_USER_ID, WIN_APP_DATA, WIN_DIR, WIN_DOCUMENTS, XDG_CONFIG, XDG_DATA};
|
||||
|
||||
let path_lower = path.to_lowercase();
|
||||
|
||||
@ -85,9 +77,7 @@ fn too_broad(path: &str) -> bool {
|
||||
}
|
||||
|
||||
for item in AVOID_WILDCARDS {
|
||||
if path.starts_with(&format!("{}/*", item))
|
||||
|| path.starts_with(&format!("{}/{}", item, STORE_USER_ID))
|
||||
{
|
||||
if path.starts_with(&format!("{}/*", item)) || path.starts_with(&format!("{}/{}", item, STORE_USER_ID)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -134,6 +124,7 @@ fn too_broad(path: &str) -> bool {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Drive letters:
|
||||
let drives: Regex = Regex::new(r"^[a-zA-Z]:$").unwrap();
|
||||
@ -168,4 +159,4 @@ pub fn usable(path: &str) -> bool {
|
||||
&& !path.starts_with("../")
|
||||
&& !too_broad(path)
|
||||
&& !unprintable.is_match(path)
|
||||
}
|
||||
}
|
||||
@ -13,12 +13,12 @@ pub enum CommonPath {
|
||||
|
||||
impl CommonPath {
|
||||
pub fn get(&self) -> Option<PathBuf> {
|
||||
static CONFIG: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::config_dir);
|
||||
static DATA: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::data_dir);
|
||||
static DATA_LOCAL: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::data_local_dir);
|
||||
static DOCUMENT: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::document_dir);
|
||||
static HOME: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::home_dir);
|
||||
static PUBLIC: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::public_dir);
|
||||
static CONFIG: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::config_dir());
|
||||
static DATA: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::data_dir());
|
||||
static DATA_LOCAL: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::data_local_dir());
|
||||
static DOCUMENT: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::document_dir());
|
||||
static HOME: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::home_dir());
|
||||
static PUBLIC: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::public_dir());
|
||||
|
||||
#[cfg(windows)]
|
||||
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 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::{
|
||||
fs::{self, File, create_dir_all},
|
||||
io::{self, Read, Write},
|
||||
fs::{self, create_dir_all, File},
|
||||
io::{self, ErrorKind, Read, Write},
|
||||
path::{Path, PathBuf},
|
||||
thread::sleep,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use crate::error::BackupError;
|
||||
|
||||
use super::{backup_manager::BackupHandler, placeholder::*};
|
||||
use database::GameVersion;
|
||||
use super::{
|
||||
backup_manager::BackupHandler, conditions::Condition, metadata::GameFile, placeholder::*,
|
||||
};
|
||||
use log::{debug, warn};
|
||||
use rustix::path::Arg;
|
||||
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};
|
||||
|
||||
pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
|
||||
@ -26,7 +31,7 @@ pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
|
||||
.iter()
|
||||
.find_map(|p| match p {
|
||||
super::conditions::Condition::Os(os) => Some(os),
|
||||
_ => None
|
||||
_ => None,
|
||||
})
|
||||
.cloned()
|
||||
{
|
||||
@ -59,7 +64,7 @@ pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
|
||||
let binding = serde_json::to_string(meta).unwrap();
|
||||
let serialized = binding.as_bytes();
|
||||
let mut file = tempfile().unwrap();
|
||||
file.write_all(serialized).unwrap();
|
||||
file.write(serialized).unwrap();
|
||||
tarball.append_file("metadata", &mut file).unwrap();
|
||||
tarball.into_inner().unwrap().finish().unwrap()
|
||||
}
|
||||
@ -92,7 +97,7 @@ pub fn extract(file: PathBuf) -> Result<(), BackupError> {
|
||||
.iter()
|
||||
.find_map(|p| match p {
|
||||
super::conditions::Condition::Os(os) => Some(os),
|
||||
_ => None
|
||||
_ => None,
|
||||
})
|
||||
.cloned()
|
||||
{
|
||||
@ -111,7 +116,7 @@ pub fn extract(file: PathBuf) -> Result<(), BackupError> {
|
||||
};
|
||||
|
||||
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!(
|
||||
"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 dest_path = dest.as_ref();
|
||||
|
||||
let metadata = fs::metadata(src_path)?;
|
||||
let metadata = fs::metadata(&src_path)?;
|
||||
|
||||
if metadata.is_file() {
|
||||
// Ensure the parent directory of the destination exists for a file copy
|
||||
if let Some(parent) = dest_path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::copy(src_path, dest_path)?;
|
||||
fs::copy(&src_path, &dest_path)?;
|
||||
} else if metadata.is_dir() {
|
||||
// For directories, we call the recursive helper function.
|
||||
// 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 {
|
||||
// Handle other file types like symlinks if necessary,
|
||||
// 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),
|
||||
));
|
||||
}
|
||||
@ -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<()> {
|
||||
fs::create_dir_all(dest)?;
|
||||
fs::create_dir_all(&dest)?;
|
||||
|
||||
for entry in fs::read_dir(src)? {
|
||||
let entry = entry?;
|
||||
@ -214,3 +220,43 @@ pub fn parse_path(
|
||||
println!("Final line: {:?}", &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},
|
||||
};
|
||||
|
||||
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 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
|
||||
// Just returns the directories that have been set up
|
||||
#[tauri::command]
|
||||
@ -63,25 +67,11 @@ pub fn add_download_dir(new_dir: PathBuf) -> Result<(), DownloadManagerError<()>
|
||||
#[tauri::command]
|
||||
pub fn update_settings(new_settings: Value) {
|
||||
let mut db_lock = borrow_db_mut_checked();
|
||||
let mut current_settings =
|
||||
serde_json::to_value(db_lock.settings.clone()).expect("Failed to parse existing settings");
|
||||
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 {
|
||||
let mut current_settings = serde_json::to_value(db_lock.settings.clone()).unwrap();
|
||||
for (key, value) in new_settings.as_object().unwrap() {
|
||||
current_settings[key] = value.clone();
|
||||
}
|
||||
let new_settings: Settings = match serde_json::from_value(current_settings) {
|
||||
Ok(settings) => settings,
|
||||
Err(e) => {
|
||||
error!("Could not parse settings with error {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let new_settings: Settings = serde_json::from_value(current_settings).unwrap();
|
||||
db_lock.settings = new_settings;
|
||||
}
|
||||
#[tauri::command]
|
||||
@ -3,18 +3,48 @@ use std::{
|
||||
mem::ManuallyDrop,
|
||||
ops::{Deref, DerefMut},
|
||||
path::PathBuf,
|
||||
sync::{RwLockReadGuard, RwLockWriteGuard},
|
||||
sync::{Arc, LazyLock, RwLockReadGuard, RwLockWriteGuard},
|
||||
};
|
||||
|
||||
use chrono::Utc;
|
||||
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 crate::{
|
||||
db::{DATA_ROOT_DIR, DB, DropDatabaseSerializer},
|
||||
models::data::Database,
|
||||
};
|
||||
use crate::DB;
|
||||
|
||||
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 =
|
||||
rustbreak::Database<Database, rustbreak::backend::PathBackend, DropDatabaseSerializer>;
|
||||
@ -33,49 +63,13 @@ impl DatabaseImpls for DatabaseInterface {
|
||||
let pfx_dir = DATA_ROOT_DIR.join("pfx");
|
||||
|
||||
debug!("creating data directory at {DATA_ROOT_DIR:?}");
|
||||
create_dir_all(DATA_ROOT_DIR.as_path()).unwrap_or_else(|e| {
|
||||
panic!(
|
||||
"Failed to create directory {} with error {}",
|
||||
DATA_ROOT_DIR.display(),
|
||||
e
|
||||
)
|
||||
});
|
||||
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
|
||||
)
|
||||
});
|
||||
create_dir_all(DATA_ROOT_DIR.as_path()).unwrap();
|
||||
create_dir_all(&games_base_dir).unwrap();
|
||||
create_dir_all(&logs_root_dir).unwrap();
|
||||
create_dir_all(&cache_dir).unwrap();
|
||||
create_dir_all(&pfx_dir).unwrap();
|
||||
|
||||
let exists = fs::exists(db_path.clone()).unwrap_or_else(|e| {
|
||||
panic!(
|
||||
"Failed to find if {} exists with error {}",
|
||||
db_path.display(),
|
||||
e
|
||||
)
|
||||
});
|
||||
let exists = fs::exists(db_path.clone()).unwrap();
|
||||
|
||||
if exists {
|
||||
match PathDatabase::load_from_path(db_path.clone()) {
|
||||
@ -84,19 +78,21 @@ impl DatabaseImpls for DatabaseInterface {
|
||||
}
|
||||
} else {
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
let handle = borrow_db_checked();
|
||||
Url::parse(&handle.base_url)
|
||||
.unwrap_or_else(|_| panic!("Failed to parse base url {}", handle.base_url))
|
||||
let handle = self.borrow_data().unwrap();
|
||||
Url::parse(&handle.base_url).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
@ -115,16 +111,13 @@ fn handle_invalid_database(
|
||||
base
|
||||
};
|
||||
info!("old database stored at: {}", new_path.to_string_lossy());
|
||||
fs::rename(&db_path, &new_path).unwrap_or_else(|e| {
|
||||
panic!(
|
||||
"Could not rename database {} to {} with error {}",
|
||||
db_path.display(),
|
||||
new_path.display(),
|
||||
e
|
||||
)
|
||||
});
|
||||
fs::rename(&db_path, &new_path).unwrap();
|
||||
|
||||
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")
|
||||
}
|
||||
5
src-tauri/src/database/mod.rs
Normal file
5
src-tauri/src/database/mod.rs
Normal file
@ -0,0 +1,5 @@
|
||||
pub mod commands;
|
||||
pub mod db;
|
||||
pub mod debug;
|
||||
pub mod models;
|
||||
pub mod scan;
|
||||
@ -4,7 +4,7 @@ pub mod data {
|
||||
use native_model::native_model;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// NOTE: Within each version, you should NEVER use these types.
|
||||
// NOTE: Within each version, you should NEVER use these types.
|
||||
// Declare it using the actual version that it is from, i.e. v1::Settings rather than just Settings from here
|
||||
|
||||
pub type GameVersion = v1::GameVersion;
|
||||
@ -37,18 +37,17 @@ pub mod data {
|
||||
}
|
||||
|
||||
mod v1 {
|
||||
use crate::process::process_manager::Platform;
|
||||
use serde_with::serde_as;
|
||||
use std::{collections::HashMap, path::PathBuf};
|
||||
|
||||
use crate::platform::Platform;
|
||||
|
||||
use super::{Deserialize, Serialize, native_model};
|
||||
|
||||
fn default_template() -> String {
|
||||
"{}".to_owned()
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[native_model(id = 2, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
||||
pub struct GameVersion {
|
||||
@ -191,7 +190,9 @@ pub mod data {
|
||||
|
||||
use serde_with::serde_as;
|
||||
|
||||
use super::{Deserialize, Serialize, native_model, v1};
|
||||
use super::{
|
||||
Deserialize, Serialize, native_model, v1,
|
||||
};
|
||||
|
||||
#[native_model(id = 1, version = 2, with = native_model::rmp_serde_1_3::RmpSerde, from = v1::Database)]
|
||||
#[derive(Serialize, Deserialize, Clone, Default)]
|
||||
@ -275,13 +276,12 @@ pub mod data {
|
||||
pub install_dirs: Vec<PathBuf>,
|
||||
// Guaranteed to exist if the game also exists in the app state map
|
||||
pub game_statuses: HashMap<String, GameDownloadStatus>,
|
||||
|
||||
|
||||
pub game_versions: HashMap<String, HashMap<String, v1::GameVersion>>,
|
||||
pub installed_game_version: HashMap<String, v1::DownloadableMetadata>,
|
||||
|
||||
#[serde(skip)]
|
||||
pub transient_statuses:
|
||||
HashMap<v1::DownloadableMetadata, v1::ApplicationTransientStatus>,
|
||||
pub transient_statuses: HashMap<v1::DownloadableMetadata, v1::ApplicationTransientStatus>,
|
||||
}
|
||||
impl From<v1::DatabaseApplications> for DatabaseApplications {
|
||||
fn from(value: v1::DatabaseApplications) -> Self {
|
||||
@ -302,7 +302,10 @@ pub mod data {
|
||||
mod v3 {
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::{Deserialize, Serialize, native_model, v1, v2};
|
||||
use super::{
|
||||
Deserialize, Serialize,
|
||||
native_model, v2, v1,
|
||||
};
|
||||
#[native_model(id = 1, version = 3, with = native_model::rmp_serde_1_3::RmpSerde, from = v2::Database)]
|
||||
#[derive(Serialize, Deserialize, Clone, Default)]
|
||||
pub struct Database {
|
||||
@ -354,20 +357,6 @@ pub mod data {
|
||||
compat_info: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl DatabaseAuth {
|
||||
pub fn new(
|
||||
private: String,
|
||||
cert: String,
|
||||
client_id: String,
|
||||
web_token: Option<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
private,
|
||||
cert,
|
||||
client_id,
|
||||
web_token,
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@ -1,11 +1,16 @@
|
||||
use std::fs;
|
||||
|
||||
use database::{DownloadType, DownloadableMetadata, borrow_db_mut_checked};
|
||||
use log::warn;
|
||||
|
||||
use crate::{
|
||||
downloads::drop_data::{DROP_DATA_PATH, DropData},
|
||||
library::set_partially_installed_db,
|
||||
database::{
|
||||
db::borrow_db_mut_checked,
|
||||
models::data::{DownloadType, DownloadableMetadata},
|
||||
},
|
||||
games::{
|
||||
downloads::drop_data::{DropData, DROP_DATA_PATH},
|
||||
library::set_partially_installed_db,
|
||||
},
|
||||
};
|
||||
|
||||
pub fn scan_install_dirs() {
|
||||
@ -19,11 +24,11 @@ pub fn scan_install_dirs() {
|
||||
if !drop_data_file.exists() {
|
||||
continue;
|
||||
}
|
||||
let game_id = game.file_name().display().to_string();
|
||||
let game_id = game.file_name().into_string().unwrap();
|
||||
let Ok(drop_data) = DropData::read(&game.path()) else {
|
||||
warn!(
|
||||
".dropdata exists for {}, but couldn't read it. is it corrupted?",
|
||||
game.file_name().display()
|
||||
game.file_name().into_string().unwrap()
|
||||
);
|
||||
continue;
|
||||
};
|
||||
@ -1,22 +0,0 @@
|
||||
use database::DownloadableMetadata;
|
||||
use download_manager::DOWNLOAD_MANAGER;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn pause_downloads() {
|
||||
DOWNLOAD_MANAGER.pause_downloads();
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn resume_downloads() {
|
||||
DOWNLOAD_MANAGER.resume_downloads();
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn move_download_in_queue(old_index: usize, new_index: usize) {
|
||||
DOWNLOAD_MANAGER.rearrange(old_index, new_index);
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn cancel_game(meta: DownloadableMetadata) {
|
||||
DOWNLOAD_MANAGER.cancel(meta);
|
||||
}
|
||||
31
src-tauri/src/download_manager/commands.rs
Normal file
31
src-tauri/src/download_manager/commands.rs
Normal file
@ -0,0 +1,31 @@
|
||||
use std::sync::Mutex;
|
||||
|
||||
use crate::{database::models::data::DownloadableMetadata, AppState};
|
||||
|
||||
#[tauri::command]
|
||||
pub fn pause_downloads(state: tauri::State<'_, Mutex<AppState>>) {
|
||||
state.lock().unwrap().download_manager.pause_downloads();
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn resume_downloads(state: tauri::State<'_, Mutex<AppState>>) {
|
||||
state.lock().unwrap().download_manager.resume_downloads();
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn move_download_in_queue(
|
||||
state: tauri::State<'_, Mutex<AppState>>,
|
||||
old_index: usize,
|
||||
new_index: usize,
|
||||
) {
|
||||
state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.download_manager
|
||||
.rearrange(old_index, new_index);
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn cancel_game(state: tauri::State<'_, Mutex<AppState>>, meta: DownloadableMetadata) {
|
||||
state.lock().unwrap().download_manager.cancel(meta);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user