Compare commits

..

1 Commits

Author SHA1 Message Date
0147956b5f chore: Most refactoring except appstate, backuperror, and main workspace
Still needs a massive go-over because there shouldn't be anything referencing tauri in any of the workspaces except the original one

Signed-off-by: quexeky <git@quexeky.dev>
2025-10-09 07:46:17 +11:00
199 changed files with 14880 additions and 16806 deletions

2
.gitignore vendored
View File

@ -30,5 +30,3 @@ src-tauri/perf*
/*.AppImage /*.AppImage
/squashfs-root /squashfs-root
/target/

View File

@ -1,5 +1,5 @@
<template> <template>
<NuxtLoadingIndicator color="#2563eb" /> <NuxtLoadingIndicator color="#2563eb" />
<NuxtLayout class="select-none w-screen h-screen"> <NuxtLayout class="select-none w-screen h-screen">
<NuxtPage /> <NuxtPage />
<ModalStack /> <ModalStack />
@ -7,7 +7,14 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import "~/composables/downloads.js";
import { invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
import { useAppState } from "./composables/app-state.js";
import {
initialNavigation,
setupHooks,
} from "./composables/state-navigation.js";
const router = useRouter(); const router = useRouter();

View File

@ -2,7 +2,9 @@
<div class="h-16 bg-zinc-950 flex flex-row justify-between"> <div class="h-16 bg-zinc-950 flex flex-row justify-between">
<div class="flex flex-row grow items-center pl-5 pr-2 py-3"> <div class="flex flex-row grow items-center pl-5 pr-2 py-3">
<div class="inline-flex items-center gap-x-10"> <div class="inline-flex items-center gap-x-10">
<Wordmark class="h-8 mb-0.5" /> <NuxtLink to="/store">
<Wordmark class="h-8 mb-0.5" />
</NuxtLink>
<nav class="inline-flex items-center mt-0.5"> <nav class="inline-flex items-center mt-0.5">
<ol class="inline-flex items-center gap-x-6"> <ol class="inline-flex items-center gap-x-6">
<NuxtLink <NuxtLink
@ -40,7 +42,7 @@
</ol> </ol>
</div> </div>
</div> </div>
<WindowControl /> <WindowControl />
</div> </div>
</template> </template>

View File

@ -76,6 +76,7 @@ import { Menu, MenuButton, MenuItem, MenuItems } from "@headlessui/vue";
import { ChevronDownIcon } from "@heroicons/vue/16/solid"; import { ChevronDownIcon } from "@heroicons/vue/16/solid";
import type { NavigationItem } from "../types"; import type { NavigationItem } from "../types";
import HeaderWidget from "./HeaderWidget.vue"; import HeaderWidget from "./HeaderWidget.vue";
import { useAppState } from "~/composables/app-state";
import { invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
const open = ref(false); const open = ref(false);

View File

@ -73,7 +73,7 @@
alt="" alt=""
/> />
</div> </div>
<div class="flex flex-col gap-x-2"> <div class="inline-flex items-center gap-x-2">
<p <p
class="text-sm whitespace-nowrap font-display font-semibold" class="text-sm whitespace-nowrap font-display font-semibold"
> >

View 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>

View File

@ -1,5 +1,5 @@
import { convertFileSrc } from "@tauri-apps/api/core"; import { convertFileSrc } from "@tauri-apps/api/core";
export const useObject = (id: string) => { export const useObject = async (id: string) => {
return convertFileSrc(id, "object"); return convertFileSrc(id, "object");
}; };

View File

@ -9,17 +9,13 @@ export default defineNuxtConfig({
}, },
}, },
css: ["~/assets/main.scss"],
ssr: false, ssr: false,
extends: ["../shared", "../libs/drop-base"], extends: [["../libs/drop-base"]],
app: { app: {
baseURL: "/main", baseURL: "/main",
}, }
devtools: {
enabled: false,
},
}); });

View File

@ -7,7 +7,6 @@ export default {
"./plugins/**/*.{js,ts}", "./plugins/**/*.{js,ts}",
"./app.vue", "./app.vue",
"./error.vue", "./error.vue",
"../shared/components/**/*.vue"
], ],
theme: { theme: {
extend: { extend: {

View File

@ -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>

View File

@ -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;
}

View File

@ -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">&larr;</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>

View File

@ -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,
},
});

View File

@ -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"
}

View File

@ -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')],
};

View File

@ -1,5 +0,0 @@
{
// https://nuxt.com/docs/guide/concepts/typescript
"extends": "./.nuxt/tsconfig.json",
"exclude": ["src-tauri/**/*"]
}

View File

@ -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;
};

File diff suppressed because it is too large Load Diff

113
src-tauri/Cargo.lock generated
View File

@ -381,9 +381,9 @@ dependencies = [
[[package]] [[package]]
name = "atomic-instant-full" name = "atomic-instant-full"
version = "0.1.1" version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83148e838612d8d701ce16b9f64b8674c097e1b4a14037b294baec03d9072228" checksum = "db6541700e074cda41b1c6f98c2cae6cde819967bf142078f069cad85387cdbe"
[[package]] [[package]]
name = "atomic-waker" name = "atomic-waker"
@ -510,7 +510,7 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4"
dependencies = [ dependencies = [
"generic-array 0.14.8", "generic-array 0.14.7",
] ]
[[package]] [[package]]
@ -519,7 +519,7 @@ version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [ dependencies = [
"generic-array 0.14.8", "generic-array 0.14.7",
] ]
[[package]] [[package]]
@ -735,14 +735,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "374b7c592d9c00c1f4972ea58390ac6b18cbb6ab79011f3bdc90a0b82ca06b77" checksum = "374b7c592d9c00c1f4972ea58390ac6b18cbb6ab79011f3bdc90a0b82ca06b77"
dependencies = [ dependencies = [
"serde", "serde",
"toml 0.9.8", "toml 0.9.7",
] ]
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.2.41" version = "1.2.40"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac9fe6cdbb24b6ade63616c0a0688e45bb56732262c158df3c0c4bea4ca47cb7" checksum = "e1d05d92f4b1fd76aad469d46cdd858ca761576082cd37df81416691e50199fb"
dependencies = [ dependencies = [
"find-msvc-tools", "find-msvc-tools",
"jobserver", "jobserver",
@ -826,7 +826,6 @@ dependencies = [
"rustix 1.1.2", "rustix 1.1.2",
"serde", "serde",
"serde_json", "serde_json",
"serde_with",
"tar", "tar",
"tempfile", "tempfile",
"uuid", "uuid",
@ -1003,7 +1002,7 @@ version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [ dependencies = [
"generic-array 0.14.8", "generic-array 0.14.7",
"typenum", "typenum",
] ]
@ -1199,7 +1198,7 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066"
dependencies = [ dependencies = [
"generic-array 0.14.8", "generic-array 0.14.7",
] ]
[[package]] [[package]]
@ -1375,13 +1374,11 @@ dependencies = [
"database", "database",
"deranged 0.4.0", "deranged 0.4.0",
"dirs 6.0.0", "dirs 6.0.0",
"download_manager",
"droplet-rs", "droplet-rs",
"dynfmt", "dynfmt",
"filetime", "filetime",
"futures-core", "futures-core",
"futures-lite", "futures-lite",
"games",
"gethostname", "gethostname",
"hex 0.4.3", "hex 0.4.3",
"http 1.3.1", "http 1.3.1",
@ -1509,7 +1506,7 @@ dependencies = [
"cc", "cc",
"memchr", "memchr",
"rustc_version", "rustc_version",
"toml 0.9.8", "toml 0.9.7",
"vswhom", "vswhom",
"winreg 0.55.0", "winreg 0.55.0",
] ]
@ -1664,9 +1661,9 @@ dependencies = [
[[package]] [[package]]
name = "find-msvc-tools" name = "find-msvc-tools"
version = "0.1.4" version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52051878f80a721bb68ebfbc930e07b65ba72f2da88968ea5c06fd6ca3d3a127" checksum = "0399f9d26e5191ce32c498bebd31e7a3ceabc2745f0ac54af3f335126c3f24b3"
[[package]] [[package]]
name = "flate2" name = "flate2"
@ -1992,9 +1989,9 @@ dependencies = [
[[package]] [[package]]
name = "generic-array" name = "generic-array"
version = "0.14.8" version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dc8f7d2ded5f9209535e4b3fd4d39c002f30902ff5ce9f64e2c33d549576500" checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [ dependencies = [
"typenum", "typenum",
"version_check", "version_check",
@ -2886,11 +2883,11 @@ dependencies = [
[[package]] [[package]]
name = "known-folders" name = "known-folders"
version = "1.4.0" version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d463f34ca3c400fde3a054da0e0b8c6ffa21e4590922f3e18281bb5eeef4cbdc" checksum = "c644f4623d1c55eb60a9dac35e0858a59f982fb87db6ce34c872372b0a5b728f"
dependencies = [ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.60.2",
] ]
[[package]] [[package]]
@ -2946,9 +2943,9 @@ dependencies = [
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.177" version = "0.2.176"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" checksum = "58f929b4d672ea937a23a1ab494143d968337a5f47e56d0815df1e0890ddf174"
[[package]] [[package]]
name = "libloading" name = "libloading"
@ -3848,12 +3845,12 @@ dependencies = [
[[package]] [[package]]
name = "os_pipe" name = "os_pipe"
version = "1.2.3" version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" checksum = "db335f4760b14ead6290116f2427bf33a14d4f0617d49f78a246de10c1831224"
dependencies = [ dependencies = [
"libc", "libc",
"windows-sys 0.61.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@ -3959,12 +3956,12 @@ checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"
[[package]] [[package]]
name = "pem" name = "pem"
version = "3.0.6" version = "3.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" checksum = "38af38e8470ac9dee3ce1bae1af9c1671fffc44ddfd8bd1d0a3445bf349a8ef3"
dependencies = [ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"serde_core", "serde",
] ]
[[package]] [[package]]
@ -4232,7 +4229,7 @@ version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "219cb19e96be00ab2e37d6e299658a0cfa83e52429179969b0f0121b4ac46983" checksum = "219cb19e96be00ab2e37d6e299658a0cfa83e52429179969b0f0121b4ac46983"
dependencies = [ dependencies = [
"toml_edit 0.23.7", "toml_edit 0.23.6",
] ]
[[package]] [[package]]
@ -4282,9 +4279,7 @@ dependencies = [
"client", "client",
"database", "database",
"dynfmt", "dynfmt",
"games",
"log", "log",
"page_size",
"serde", "serde",
"serde_with", "serde_with",
"shared_child", "shared_child",
@ -4605,9 +4600,9 @@ dependencies = [
[[package]] [[package]]
name = "regex" name = "regex"
version = "1.12.1" version = "1.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a52d8d02cacdb176ef4678de6c052efb4b3da14b78e4db683a4252762be5433" checksum = "8b5288124840bee7b386bc413c487869b360b2b4ec421ea56425128692f2a82c"
dependencies = [ dependencies = [
"aho-corasick", "aho-corasick",
"memchr", "memchr",
@ -4617,9 +4612,9 @@ dependencies = [
[[package]] [[package]]
name = "regex-automata" name = "regex-automata"
version = "0.4.12" version = "0.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "722166aa0d7438abbaa4d5cc2c649dac844e8c56d82fb3d33e9c34b5cd268fc6" checksum = "833eb9ce86d40ef33cb1306d8accf7bc8ec2bfea4355cbdebb3df68b40925cad"
dependencies = [ dependencies = [
"aho-corasick", "aho-corasick",
"memchr", "memchr",
@ -4628,9 +4623,9 @@ dependencies = [
[[package]] [[package]]
name = "regex-syntax" name = "regex-syntax"
version = "0.8.7" version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3160422bbd54dd5ecfdca71e5fd59b7b8fe2b1697ab2baf64f6d05dcc66d298" checksum = "caf4aa5b0f434c91fe5c7f1ecb6a5ece2130b02ad2a590589dda5146df959001"
[[package]] [[package]]
name = "remote" name = "remote"
@ -5251,9 +5246,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_spanned" name = "serde_spanned"
version = "1.0.3" version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e24345aa0fe688594e73770a5f6d1b216508b4f93484c0026d521acd30134392" checksum = "5417783452c2be558477e104686f7de5dae53dba813c28435e0e70f82d9b04ee"
dependencies = [ dependencies = [
"serde_core", "serde_core",
] ]
@ -5619,9 +5614,9 @@ dependencies = [
[[package]] [[package]]
name = "stable_deref_trait" name = "stable_deref_trait"
version = "1.2.1" version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
[[package]] [[package]]
name = "static_assertions" name = "static_assertions"
@ -5965,7 +5960,7 @@ dependencies = [
"serde_json", "serde_json",
"tauri-utils", "tauri-utils",
"tauri-winres", "tauri-winres",
"toml 0.9.8", "toml 0.9.7",
"walkdir", "walkdir",
] ]
@ -6023,7 +6018,7 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"tauri-utils", "tauri-utils",
"toml 0.9.8", "toml 0.9.7",
"walkdir", "walkdir",
] ]
@ -6098,7 +6093,7 @@ dependencies = [
"tauri-plugin", "tauri-plugin",
"tauri-utils", "tauri-utils",
"thiserror 2.0.17", "thiserror 2.0.17",
"toml 0.9.8", "toml 0.9.7",
"url", "url",
] ]
@ -6262,7 +6257,7 @@ dependencies = [
"serde_with", "serde_with",
"swift-rs", "swift-rs",
"thiserror 2.0.17", "thiserror 2.0.17",
"toml 0.9.8", "toml 0.9.7",
"url", "url",
"urlpattern", "urlpattern",
"uuid", "uuid",
@ -6276,7 +6271,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd21509dd1fa9bd355dc29894a6ff10635880732396aa38c0066c1e6c1ab8074" checksum = "fd21509dd1fa9bd355dc29894a6ff10635880732396aa38c0066c1e6c1ab8074"
dependencies = [ dependencies = [
"embed-resource", "embed-resource",
"toml 0.9.8", "toml 0.9.7",
] ]
[[package]] [[package]]
@ -6509,14 +6504,14 @@ dependencies = [
[[package]] [[package]]
name = "toml" name = "toml"
version = "0.9.8" version = "0.9.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0dc8b1fb61449e27716ec0e1bdf0f6b8f3e8f6b05391e8497b8b6d7804ea6d8" checksum = "00e5e5d9bf2475ac9d4f0d9edab68cc573dc2fd644b0dba36b0c30a92dd9eaa0"
dependencies = [ dependencies = [
"indexmap 2.11.4", "indexmap 2.11.4",
"serde_core", "serde_core",
"serde_spanned 1.0.3", "serde_spanned 1.0.2",
"toml_datetime 0.7.3", "toml_datetime 0.7.2",
"toml_parser", "toml_parser",
"toml_writer", "toml_writer",
"winnow 0.7.13", "winnow 0.7.13",
@ -6533,9 +6528,9 @@ dependencies = [
[[package]] [[package]]
name = "toml_datetime" name = "toml_datetime"
version = "0.7.3" version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2cdb639ebbc97961c51720f858597f7f24c4fc295327923af55b74c3c724533" checksum = "32f1085dec27c2b6632b04c80b3bb1b4300d6495d1e129693bdda7d91e72eec1"
dependencies = [ dependencies = [
"serde_core", "serde_core",
] ]
@ -6566,30 +6561,30 @@ dependencies = [
[[package]] [[package]]
name = "toml_edit" name = "toml_edit"
version = "0.23.7" version = "0.23.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6485ef6d0d9b5d0ec17244ff7eb05310113c3f316f2d14200d4de56b3cb98f8d" checksum = "f3effe7c0e86fdff4f69cdd2ccc1b96f933e24811c5441d44904e8683e27184b"
dependencies = [ dependencies = [
"indexmap 2.11.4", "indexmap 2.11.4",
"toml_datetime 0.7.3", "toml_datetime 0.7.2",
"toml_parser", "toml_parser",
"winnow 0.7.13", "winnow 0.7.13",
] ]
[[package]] [[package]]
name = "toml_parser" name = "toml_parser"
version = "1.0.4" version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0cbe268d35bdb4bb5a56a2de88d0ad0eb70af5384a99d648cd4b3d04039800e" checksum = "4cf893c33be71572e0e9aa6dd15e6677937abd686b066eac3f8cd3531688a627"
dependencies = [ dependencies = [
"winnow 0.7.13", "winnow 0.7.13",
] ]
[[package]] [[package]]
name = "toml_writer" name = "toml_writer"
version = "1.0.4" version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df8b2b54733674ad286d16267dcfc7a71ed5c776e4ac7aa3c3e2561f7c637bf2" checksum = "d163a63c116ce562a22cda521fcc4d79152e7aba014456fb5eb442f6d6a10109"
[[package]] [[package]]
name = "tower" name = "tower"

View File

@ -1,148 +1,8 @@
[package]
name = "drop-app"
version = "0.3.3"
description = "The client application for the open-source, self-hosted game distribution platform Drop"
authors = ["Drop OSS"]
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[target."cfg(any(target_os = \"macos\", windows, target_os = \"linux\"))".dependencies]
tauri-plugin-single-instance = { version = "2.0.0", features = ["deep-link"] }
[lib]
# The `_lib` suffix may seem redundant but it is necessary
# to make the lib name unique and wouldn't conflict with the bin name.
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
name = "drop_app_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
rustflags = ["-C", "target-feature=+aes,+sse2"]
[build-dependencies]
tauri-build = { version = "2.0.0", features = [] }
[dependencies]
tauri-plugin-shell = "2.2.1"
serde_json = "1"
rayon = "1.10.0"
webbrowser = "1.0.2"
url = "2.5.2"
tauri-plugin-deep-link = "2"
log = "0.4.22"
hex = "0.4.3"
tauri-plugin-dialog = "2"
http = "1.1.0"
urlencoding = "2.1.3"
md5 = "0.7.0"
chrono = "0.4.38"
tauri-plugin-os = "2"
boxcar = "0.2.7"
umu-wrapper-lib = "0.1.0"
tauri-plugin-autostart = "2.0.0"
shared_child = "1.0.1"
serde_with = "3.12.0"
slice-deque = "0.3.0"
throttle_my_fn = "0.2.6"
parking_lot = "0.12.3"
atomic-instant-full = "0.1.0"
cacache = "13.1.0"
http-serde = "2.1.1"
reqwest-middleware = "0.4.0"
reqwest-middleware-cache = "0.1.1"
deranged = "=0.4.0"
droplet-rs = "0.7.3"
gethostname = "1.0.1"
zstd = "0.13.3"
tar = "0.4.44"
rand = "0.9.1"
regex = "1.11.1"
tempfile = "3.19.1"
schemars = "0.8.22"
sha1 = "0.10.6"
dirs = "6.0.0"
whoami = "1.6.0"
filetime = "0.2.25"
walkdir = "2.5.0"
known-folders = "1.2.0"
native_model = { version = "0.6.4", features = ["rmp_serde_1_3"], git = "https://github.com/Drop-OSS/native_model.git"}
tauri-plugin-opener = "2.4.0"
bitcode = "0.6.6"
reqwest-websocket = "0.5.0"
futures-lite = "2.6.0"
page_size = "0.6.0"
sysinfo = "0.36.1"
humansize = "2.1.3"
tokio-util = { version = "0.7.16", features = ["io"] }
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"]
[dependencies.tauri]
version = "2.7.0"
features = ["protocol-asset", "tray-icon"]
[dependencies.tokio]
version = "1.40.0"
features = ["rt", "tokio-macros", "signal"]
[dependencies.log4rs]
version = "1.3.0"
features = ["console_appender", "file_appender"]
[dependencies.rustix]
version = "0.38.37"
features = ["fs"]
[dependencies.uuid]
version = "1.10.0"
features = ["v4", "fast-rng", "macro-diagnostics"]
[dependencies.rustbreak]
version = "2"
features = ["other_errors"] # You can also use "yaml_enc" or "bin_enc"
[dependencies.reqwest]
version = "0.12.22"
default-features = false
features = [
"json",
"http2",
"blocking",
"rustls-tls",
"native-tls-alpn",
"rustls-tls-native-roots",
"stream",
]
[dependencies.serde]
version = "1"
features = ["derive", "rc"]
[profile.release]
lto = true
codegen-units = 1
panic = 'abort'
[workspace] [workspace]
members = [ members = [
"client", "client",
"database", "database",
"src-tauri",
"process", "process",
"remote", "remote",
"utils", "utils",

View File

@ -1,8 +1,48 @@
use database::borrow_db_checked; use database::{borrow_db_checked, borrow_db_mut_checked};
use log::debug; use log::debug;
use tauri::AppHandle; use tauri::AppHandle;
use tauri_plugin_autostart::ManagerExt; use tauri_plugin_autostart::ManagerExt;
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())?;
debug!("enabled autostart");
} else {
manager.disable().map_err(|e| e.to_string())?;
debug!("eisabled autostart");
}
// Store the state in DB
let mut db_handle = borrow_db_mut_checked();
db_handle.settings.autostart = enabled;
drop(db_handle);
Ok(())
}
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);
// Get actual system state
let manager = app.autolaunch();
let system_state = manager.is_enabled()?;
// If they don't match, sync to DB state
if db_state != system_state {
if db_state {
manager.enable()?;
} else {
manager.disable()?;
}
}
Ok(db_state)
}
// New function to sync state on startup // New function to sync state on startup
pub fn sync_autostart_on_startup(app: &AppHandle) -> Result<(), String> { pub fn sync_autostart_on_startup(app: &AppHandle) -> Result<(), String> {
let db_handle = borrow_db_checked(); let db_handle = borrow_db_checked();

View File

@ -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()
}

View File

@ -1,4 +1,3 @@
pub mod app_status;
pub mod autostart; pub mod autostart;
pub mod compat;
pub mod user; pub mod user;
pub mod app_status;

View File

@ -10,3 +10,8 @@ pub struct User {
display_name: String, display_name: String,
profile_picture_object_id: String, profile_picture_object_id: String,
} }
#[derive(Clone)]
pub struct CompatInfo {
umu_installed: bool,
}

View File

@ -11,7 +11,6 @@ regex = "1.11.3"
rustix = "1.1.2" rustix = "1.1.2"
serde = "1.0.228" serde = "1.0.228"
serde_json = "1.0.145" serde_json = "1.0.145"
serde_with = "3.15.0"
tar = "0.4.44" tar = "0.4.44"
tempfile = "3.23.0" tempfile = "3.23.0"
uuid = "1.18.1" uuid = "1.18.1"

View File

@ -2,7 +2,7 @@ use std::{collections::HashMap, path::PathBuf, str::FromStr};
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
use database::platform::Platform; use database::platform::Platform;
use database::{GameVersion, db::DATA_ROOT_DIR}; use database::{db::DATA_ROOT_DIR, GameVersion};
use log::warn; use log::warn;
use crate::error::BackupError; use crate::error::BackupError;
@ -14,12 +14,6 @@ pub struct BackupManager<'a> {
pub sources: HashMap<(Platform, Platform), &'a (dyn BackupHandler + Sync + Send)>, pub sources: HashMap<(Platform, Platform), &'a (dyn BackupHandler + Sync + Send)>,
} }
impl Default for BackupManager<'_> {
fn default() -> Self {
Self::new()
}
}
impl BackupManager<'_> { impl BackupManager<'_> {
pub fn new() -> Self { pub fn new() -> Self {
BackupManager { BackupManager {
@ -46,188 +40,65 @@ impl BackupManager<'_> {
(Platform::MacOs, Platform::MacOs), (Platform::MacOs, Platform::MacOs),
&MacBackupManager {} as &(dyn BackupHandler + Sync + Send), &MacBackupManager {} as &(dyn BackupHandler + Sync + Send),
), ),
]), ]),
} }
} }
} }
pub trait BackupHandler: Send + Sync { pub trait BackupHandler: Send + Sync {
fn root_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { fn root_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(DATA_ROOT_DIR.join("games")) }
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 game_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { fn home_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { let c = CommonPath::Home.get().ok_or(BackupError::NotFound); println!("{:?}", c); c }
Ok(PathBuf::from_str(&game.game_id).unwrap()) 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 base_translate(&self, path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { fn win_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winAppData>"); Err(BackupError::InvalidSystem) }
Ok(self fn win_local_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winLocalAppData>"); Err(BackupError::InvalidSystem) }
.root_translate(path, game)? 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) }
.join(self.game_translate(path, game)?)) 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 home_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { fn win_program_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winProgramData>"); Err(BackupError::InvalidSystem) }
let c = CommonPath::Home.get().ok_or(BackupError::NotFound); fn win_dir_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winDir>"); Err(BackupError::InvalidSystem) }
println!("{:?}", c); fn xdg_data_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected XDG Reference in Backup <xdgData>"); Err(BackupError::InvalidSystem) }
c 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()) }
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 {} pub struct LinuxBackupManager {}
impl BackupHandler for LinuxBackupManager { impl BackupHandler for LinuxBackupManager {
fn xdg_config_translate( fn xdg_config_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> {
&self, Ok(CommonPath::Data.get().ok_or(BackupError::NotFound)?)
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::Data.get().ok_or(BackupError::NotFound)
} }
fn xdg_data_translate( fn xdg_data_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> {
&self, Ok(CommonPath::Config.get().ok_or(BackupError::NotFound)?)
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::Config.get().ok_or(BackupError::NotFound)
} }
} }
pub struct WindowsBackupManager {} pub struct WindowsBackupManager {}
impl BackupHandler for WindowsBackupManager { impl BackupHandler for WindowsBackupManager {
fn win_app_data_translate( fn win_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
&self, Ok(CommonPath::Config.get().ok_or(BackupError::NotFound)?)
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::Config.get().ok_or(BackupError::NotFound)
} }
fn win_local_app_data_translate( fn win_local_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
&self, Ok(CommonPath::DataLocal.get().ok_or(BackupError::NotFound)?)
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::DataLocal.get().ok_or(BackupError::NotFound)
} }
fn win_local_app_data_low_translate( fn win_local_app_data_low_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
&self, Ok(CommonPath::DataLocalLow.get().ok_or(BackupError::NotFound)?)
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::DataLocalLow
.get()
.ok_or(BackupError::NotFound)
} }
fn win_dir_translate( fn win_dir_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> {
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
Ok(PathBuf::from_str("C:/Windows").unwrap()) Ok(PathBuf::from_str("C:/Windows").unwrap())
} }
fn win_documents_translate( fn win_documents_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
&self, Ok(CommonPath::Document.get().ok_or(BackupError::NotFound)?)
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::Document.get().ok_or(BackupError::NotFound)
} }
fn win_program_data_translate( fn win_program_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
Ok(PathBuf::from_str("C:/ProgramData").unwrap()) Ok(PathBuf::from_str("C:/ProgramData").unwrap())
} }
fn win_public_translate( fn win_public_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
&self, Ok(CommonPath::Public.get().ok_or(BackupError::NotFound)?)
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::Public.get().ok_or(BackupError::NotFound)
} }
} }
pub struct MacBackupManager {} pub struct MacBackupManager {}

View File

@ -2,6 +2,5 @@ use database::platform::Platform;
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Condition { pub enum Condition {
Os(Platform), Os(Platform)
Other
} }

View File

@ -1,27 +1,5 @@
use std::fmt::Display;
use serde_with::SerializeDisplay;
#[derive(Debug, SerializeDisplay, Clone, Copy)]
pub enum BackupError { pub enum BackupError {
InvalidSystem, InvalidSystem,
NotFound,
ParseError, ParseError,
} NotFound
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)
}
} }

View File

@ -1,8 +1,8 @@
pub mod backup_manager;
pub mod conditions; pub mod conditions;
pub mod error;
pub mod metadata; pub mod metadata;
pub mod resolver;
pub mod placeholder;
pub mod normalise; pub mod normalise;
pub mod path; pub mod path;
pub mod placeholder; pub mod backup_manager;
pub mod resolver; pub mod error;

View File

@ -1,6 +1,7 @@
use database::GameVersion; use database::GameVersion;
use super::conditions::Condition; use super::conditions::{Condition};
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct CloudSaveMetadata { pub struct CloudSaveMetadata {
@ -15,17 +16,15 @@ pub struct GameFile {
pub id: Option<String>, pub id: Option<String>,
pub data_type: DataType, pub data_type: DataType,
pub tags: Vec<Tag>, pub tags: Vec<Tag>,
pub conditions: Vec<Condition>, pub conditions: Vec<Condition>
} }
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
pub enum DataType { pub enum DataType {
Registry, Registry,
File, File,
Other, Other
} }
#[derive( #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub enum Tag { pub enum Tag {
Config, Config,

View File

@ -5,6 +5,7 @@ use regex::Regex;
use super::placeholder::*; use super::placeholder::*;
pub fn normalize(path: &str, os: Platform) -> String { pub fn normalize(path: &str, os: Platform) -> String {
let mut path = path.trim().trim_end_matches(['/', '\\']).replace('\\', "/"); let mut path = path.trim().trim_end_matches(['/', '\\']).replace('\\', "/");
@ -13,25 +14,18 @@ pub fn normalize(path: &str, os: Platform) -> String {
} }
static CONSECUTIVE_SLASHES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"/{2,}").unwrap()); static CONSECUTIVE_SLASHES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"/{2,}").unwrap());
static UNNECESSARY_DOUBLE_STAR_1: LazyLock<Regex> = static UNNECESSARY_DOUBLE_STAR_1: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"([^/*])\*{2,}").unwrap());
LazyLock::new(|| Regex::new(r"([^/*])\*{2,}").unwrap()); static UNNECESSARY_DOUBLE_STAR_2: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*{2,}([^/*])").unwrap());
static UNNECESSARY_DOUBLE_STAR_2: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"\*{2,}([^/*])").unwrap());
static ENDING_WILDCARD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\*)+$").unwrap()); static ENDING_WILDCARD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\*)+$").unwrap());
static ENDING_DOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\.)$").unwrap()); static ENDING_DOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\.)$").unwrap());
static INTERMEDIATE_DOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\./)").unwrap()); static INTERMEDIATE_DOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\./)").unwrap());
static BLANK_SEGMENT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\s+/)").unwrap()); static BLANK_SEGMENT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\s+/)").unwrap());
static APP_DATA: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%appdata%").unwrap()); static APP_DATA: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%appdata%").unwrap());
static APP_DATA_ROAMING: LazyLock<Regex> = static APP_DATA_ROAMING: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Roaming").unwrap());
LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Roaming").unwrap()); static APP_DATA_LOCAL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%localappdata%").unwrap());
static APP_DATA_LOCAL: LazyLock<Regex> = static APP_DATA_LOCAL_2: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Local/").unwrap());
LazyLock::new(|| Regex::new(r"(?i)%localappdata%").unwrap()); static USER_PROFILE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%").unwrap());
static APP_DATA_LOCAL_2: LazyLock<Regex> = static DOCUMENTS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/Documents").unwrap());
LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Local/").unwrap());
static USER_PROFILE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)%userprofile%").unwrap());
static DOCUMENTS: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)%userprofile%/Documents").unwrap());
for (pattern, replacement) in [ for (pattern, replacement) in [
(&CONSECUTIVE_SLASHES, "/"), (&CONSECUTIVE_SLASHES, "/"),
@ -72,9 +66,7 @@ pub fn normalize(path: &str, os: Platform) -> String {
fn too_broad(path: &str) -> bool { fn too_broad(path: &str) -> bool {
println!("Path: {}", path); println!("Path: {}", path);
use { use {BASE, HOME, ROOT, STORE_USER_ID, WIN_APP_DATA, WIN_DIR, WIN_DOCUMENTS, XDG_CONFIG, XDG_DATA};
BASE, HOME, ROOT, STORE_USER_ID, WIN_APP_DATA, WIN_DIR, WIN_DOCUMENTS, XDG_CONFIG, XDG_DATA,
};
let path_lower = path.to_lowercase(); let path_lower = path.to_lowercase();
@ -85,9 +77,7 @@ fn too_broad(path: &str) -> bool {
} }
for item in AVOID_WILDCARDS { for item in AVOID_WILDCARDS {
if path.starts_with(&format!("{}/*", item)) if path.starts_with(&format!("{}/*", item)) || path.starts_with(&format!("{}/{}", item, STORE_USER_ID)) {
|| path.starts_with(&format!("{}/{}", item, STORE_USER_ID))
{
return true; return true;
} }
} }
@ -135,6 +125,7 @@ fn too_broad(path: &str) -> bool {
} }
} }
// Drive letters: // Drive letters:
let drives: Regex = Regex::new(r"^[a-zA-Z]:$").unwrap(); let drives: Regex = Regex::new(r"^[a-zA-Z]:$").unwrap();
if drives.is_match(path) { if drives.is_match(path) {

View File

@ -13,12 +13,12 @@ pub enum CommonPath {
impl CommonPath { impl CommonPath {
pub fn get(&self) -> Option<PathBuf> { pub fn get(&self) -> Option<PathBuf> {
static CONFIG: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::config_dir); static CONFIG: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::config_dir());
static DATA: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::data_dir); static DATA: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::data_dir());
static DATA_LOCAL: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::data_local_dir); static DATA_LOCAL: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::data_local_dir());
static DOCUMENT: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::document_dir); static DOCUMENT: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::document_dir());
static HOME: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::home_dir); static HOME: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::home_dir());
static PUBLIC: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::public_dir); static PUBLIC: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::public_dir());
#[cfg(windows)] #[cfg(windows)]
static DATA_LOCAL_LOW: LazyLock<Option<PathBuf>> = LazyLock::new(|| { static DATA_LOCAL_LOW: LazyLock<Option<PathBuf>> = LazyLock::new(|| {

View File

@ -48,4 +48,4 @@ pub const XDG_DATA: &str = "<xdgData>"; // %WINDIR% on Windows
pub const XDG_CONFIG: &str = "<xdgConfig>"; // $XDG_DATA_HOME on Linux pub const XDG_CONFIG: &str = "<xdgConfig>"; // $XDG_DATA_HOME on Linux
pub const SKIP: &str = "<skip>"; // $XDG_CONFIG_HOME on Linux pub const SKIP: &str = "<skip>"; // $XDG_CONFIG_HOME on Linux
pub static OS_USERNAME: LazyLock<String> = LazyLock::new(whoami::username); pub static OS_USERNAME: LazyLock<String> = LazyLock::new(|| whoami::username());

View File

@ -1,13 +1,17 @@
use std::{ use std::{
fs::{self, File, create_dir_all}, fs::{self, create_dir_all, File},
io::{self, Read, Write}, io::{self, ErrorKind, Read, Write},
path::{Path, PathBuf}, path::{Path, PathBuf},
thread::sleep,
time::Duration,
}; };
use crate::error::BackupError; use crate::error::BackupError;
use super::{backup_manager::BackupHandler, placeholder::*}; use super::{
use database::GameVersion; backup_manager::BackupHandler, conditions::Condition, metadata::GameFile, placeholder::*,
};
use database::{platform::Platform, GameVersion};
use log::{debug, warn}; use log::{debug, warn};
use rustix::path::Arg; use rustix::path::Arg;
use tempfile::tempfile; use tempfile::tempfile;
@ -26,7 +30,7 @@ pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
.iter() .iter()
.find_map(|p| match p { .find_map(|p| match p {
super::conditions::Condition::Os(os) => Some(os), super::conditions::Condition::Os(os) => Some(os),
_ => None _ => None,
}) })
.cloned() .cloned()
{ {
@ -59,7 +63,7 @@ pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
let binding = serde_json::to_string(meta).unwrap(); let binding = serde_json::to_string(meta).unwrap();
let serialized = binding.as_bytes(); let serialized = binding.as_bytes();
let mut file = tempfile().unwrap(); let mut file = tempfile().unwrap();
file.write_all(serialized).unwrap(); file.write(serialized).unwrap();
tarball.append_file("metadata", &mut file).unwrap(); tarball.append_file("metadata", &mut file).unwrap();
tarball.into_inner().unwrap().finish().unwrap() tarball.into_inner().unwrap().finish().unwrap()
} }
@ -92,7 +96,7 @@ pub fn extract(file: PathBuf) -> Result<(), BackupError> {
.iter() .iter()
.find_map(|p| match p { .find_map(|p| match p {
super::conditions::Condition::Os(os) => Some(os), super::conditions::Condition::Os(os) => Some(os),
_ => None _ => None,
}) })
.cloned() .cloned()
{ {
@ -111,7 +115,7 @@ pub fn extract(file: PathBuf) -> Result<(), BackupError> {
}; };
let new_path = parse_path(file.path.into(), handler, &manifest.game_version)?; let new_path = parse_path(file.path.into(), handler, &manifest.game_version)?;
create_dir_all(new_path.parent().unwrap()).unwrap(); create_dir_all(&new_path.parent().unwrap()).unwrap();
println!( println!(
"Current path {:?} copying to {:?}", "Current path {:?} copying to {:?}",
@ -128,22 +132,23 @@ pub fn copy_item<P: AsRef<Path>>(src: P, dest: P) -> io::Result<()> {
let src_path = src.as_ref(); let src_path = src.as_ref();
let dest_path = dest.as_ref(); let dest_path = dest.as_ref();
let metadata = fs::metadata(src_path)?; let metadata = fs::metadata(&src_path)?;
if metadata.is_file() { if metadata.is_file() {
// Ensure the parent directory of the destination exists for a file copy // Ensure the parent directory of the destination exists for a file copy
if let Some(parent) = dest_path.parent() { if let Some(parent) = dest_path.parent() {
fs::create_dir_all(parent)?; fs::create_dir_all(parent)?;
} }
fs::copy(src_path, dest_path)?; fs::copy(&src_path, &dest_path)?;
} else if metadata.is_dir() { } else if metadata.is_dir() {
// For directories, we call the recursive helper function. // For directories, we call the recursive helper function.
// The destination for the recursive copy is the `dest_path` itself. // The destination for the recursive copy is the `dest_path` itself.
copy_dir_recursive(src_path, dest_path)?; copy_dir_recursive(&src_path, &dest_path)?;
} else { } else {
// Handle other file types like symlinks if necessary, // Handle other file types like symlinks if necessary,
// for now, return an error or skip. // for now, return an error or skip.
return Err(io::Error::other( return Err(io::Error::new(
io::ErrorKind::Other,
format!("Source {:?} is neither a file nor a directory", src_path), format!("Source {:?} is neither a file nor a directory", src_path),
)); ));
} }
@ -152,7 +157,7 @@ pub fn copy_item<P: AsRef<Path>>(src: P, dest: P) -> io::Result<()> {
} }
fn copy_dir_recursive(src: &Path, dest: &Path) -> io::Result<()> { fn copy_dir_recursive(src: &Path, dest: &Path) -> io::Result<()> {
fs::create_dir_all(dest)?; fs::create_dir_all(&dest)?;
for entry in fs::read_dir(src)? { for entry in fs::read_dir(src)? {
let entry = entry?; let entry = entry?;
@ -214,3 +219,43 @@ pub fn parse_path(
println!("Final line: {:?}", &s); println!("Final line: {:?}", &s);
Ok(s) Ok(s)
} }
pub fn test() {
let mut meta = CloudSaveMetadata {
files: vec![
GameFile {
path: String::from("<home>/favicon.png"),
id: None,
data_type: super::metadata::DataType::File,
tags: Vec::new(),
conditions: vec![Condition::Os(Platform::Linux)],
},
GameFile {
path: String::from("<home>/Documents/Pixel Art"),
id: None,
data_type: super::metadata::DataType::File,
tags: Vec::new(),
conditions: vec![Condition::Os(Platform::Linux)],
},
],
game_version: GameVersion {
game_id: String::new(),
version_name: String::new(),
platform: Platform::Linux,
launch_command: String::new(),
launch_args: Vec::new(),
launch_command_template: String::new(),
setup_command: String::new(),
setup_args: Vec::new(),
setup_command_template: String::new(),
only_setup: true,
version_index: 0,
delta: false,
umu_id_override: None,
},
save_id: String::from("aaaaaaa"),
};
//resolve(&mut meta);
extract("save".into()).unwrap();
}

View File

@ -10,6 +10,7 @@ use crate::interface::{DatabaseImpls, DatabaseInterface};
pub static DB: LazyLock<DatabaseInterface> = LazyLock::new(DatabaseInterface::set_up_database); pub static DB: LazyLock<DatabaseInterface> = LazyLock::new(DatabaseInterface::set_up_database);
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
static DATA_ROOT_PREFIX: &str = "drop"; static DATA_ROOT_PREFIX: &str = "drop";
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
@ -31,15 +32,16 @@ impl<T: native_model::Model + Serialize + DeserializeOwned> DeSerializer<T>
for DropDatabaseSerializer for DropDatabaseSerializer
{ {
fn serialize(&self, val: &T) -> rustbreak::error::DeSerResult<Vec<u8>> { fn serialize(&self, val: &T) -> rustbreak::error::DeSerResult<Vec<u8>> {
native_model::encode(val).map_err(|e| DeSerError::Internal(e.to_string())) 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> { fn deserialize<R: std::io::Read>(&self, mut s: R) -> rustbreak::error::DeSerResult<T> {
let mut buf = Vec::new(); let mut buf = Vec::new();
s.read_to_end(&mut buf) s.read_to_end(&mut buf)
.map_err(|e| rustbreak::error::DeSerError::Other(e.into()))?; .map_err(|e| rustbreak::error::DeSerError::Other(e.into()))?;
let (val, _version) = let (val, _version) = native_model::decode(buf)
native_model::decode(buf).map_err(|e| DeSerError::Internal(e.to_string()))?; .map_err(|e| DeSerError::Internal(e.to_string()))?;
Ok(val) Ok(val)
} }
} }

View File

@ -1,20 +1,11 @@
use std::{ use std::{fs::{self, create_dir_all}, mem::ManuallyDrop, ops::{Deref, DerefMut}, path::PathBuf, sync::{RwLockReadGuard, RwLockWriteGuard}};
fs::{self, create_dir_all},
mem::ManuallyDrop,
ops::{Deref, DerefMut},
path::PathBuf,
sync::{RwLockReadGuard, RwLockWriteGuard},
};
use chrono::Utc; use chrono::Utc;
use log::{debug, error, info, warn}; use log::{debug, error, info, warn};
use rustbreak::{PathDatabase, RustbreakError}; use rustbreak::{PathDatabase, RustbreakError};
use url::Url; use url::Url;
use crate::{ use crate::{db::{DropDatabaseSerializer, DATA_ROOT_DIR, DB}, models::data::Database};
db::{DATA_ROOT_DIR, DB, DropDatabaseSerializer},
models::data::Database,
};
pub type DatabaseInterface = pub type DatabaseInterface =
rustbreak::Database<Database, rustbreak::backend::PathBackend, DropDatabaseSerializer>; rustbreak::Database<Database, rustbreak::backend::PathBackend, DropDatabaseSerializer>;

View File

@ -2,13 +2,20 @@
pub mod db; pub mod db;
pub mod debug; pub mod debug;
pub mod interface;
pub mod models; pub mod models;
pub mod platform; pub mod platform;
pub mod interface;
pub use models::data::{
ApplicationTransientStatus,
Database,
DatabaseApplications,
DatabaseAuth,
DownloadType,
DownloadableMetadata,
GameDownloadStatus,
GameVersion,
Settings
};
pub use db::DB; pub use db::DB;
pub use interface::{borrow_db_checked, borrow_db_mut_checked}; pub use interface::{borrow_db_checked, borrow_db_mut_checked};
pub use models::data::{
ApplicationTransientStatus, Database, DatabaseApplications, DatabaseAuth, DownloadType,
DownloadableMetadata, GameDownloadStatus, GameVersion, Settings,
};

View File

@ -191,7 +191,9 @@ pub mod data {
use serde_with::serde_as; 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)] #[native_model(id = 1, version = 2, with = native_model::rmp_serde_1_3::RmpSerde, from = v1::Database)]
#[derive(Serialize, Deserialize, Clone, Default)] #[derive(Serialize, Deserialize, Clone, Default)]
@ -280,8 +282,7 @@ pub mod data {
pub installed_game_version: HashMap<String, v1::DownloadableMetadata>, pub installed_game_version: HashMap<String, v1::DownloadableMetadata>,
#[serde(skip)] #[serde(skip)]
pub transient_statuses: pub transient_statuses: HashMap<v1::DownloadableMetadata, v1::ApplicationTransientStatus>,
HashMap<v1::DownloadableMetadata, v1::ApplicationTransientStatus>,
} }
impl From<v1::DatabaseApplications> for DatabaseApplications { impl From<v1::DatabaseApplications> for DatabaseApplications {
fn from(value: v1::DatabaseApplications) -> Self { fn from(value: v1::DatabaseApplications) -> Self {
@ -302,7 +303,10 @@ pub mod data {
mod v3 { mod v3 {
use std::path::PathBuf; 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)] #[native_model(id = 1, version = 3, with = native_model::rmp_serde_1_3::RmpSerde, from = v2::Database)]
#[derive(Serialize, Deserialize, Clone, Default)] #[derive(Serialize, Deserialize, Clone, Default)]
pub struct Database { pub struct Database {
@ -354,20 +358,6 @@ pub mod data {
compat_info: None, 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,
}
}
} }
} }

View File

@ -1,5 +1,6 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Eq, Hash, PartialEq, Serialize, Deserialize, Clone, Copy, Debug)] #[derive(Eq, Hash, PartialEq, Serialize, Deserialize, Clone, Copy, Debug)]
pub enum Platform { pub enum Platform {
Windows, Windows,

View File

@ -9,14 +9,11 @@ use std::{
use database::DownloadableMetadata; use database::DownloadableMetadata;
use log::{debug, error, info, warn}; use log::{debug, error, info, warn};
use tauri::AppHandle; use tauri::{AppHandle, Emitter};
use utils::{app_emit, lock, send}; use utils::{app_emit, lock, send};
use crate::{
download_manager_frontend::DownloadStatus, use crate::{download_manager_frontend::DownloadStatus, error::ApplicationDownloadError, frontend_updates::{QueueUpdateEvent, QueueUpdateEventQueueData, StatsUpdateEvent}};
error::ApplicationDownloadError,
frontend_updates::{QueueUpdateEvent, QueueUpdateEventQueueData, StatsUpdateEvent},
};
use super::{ use super::{
download_manager_frontend::{DownloadManager, DownloadManagerSignal, DownloadManagerStatus}, download_manager_frontend::{DownloadManager, DownloadManagerSignal, DownloadManagerStatus},
@ -292,10 +289,7 @@ impl DownloadManagerBuilder {
if validate_result { if validate_result {
download_agent.on_complete(&app_handle); download_agent.on_complete(&app_handle);
send!( send!(sender, DownloadManagerSignal::Completed(download_agent.metadata()));
sender,
DownloadManagerSignal::Completed(download_agent.metadata())
);
send!(sender, DownloadManagerSignal::UpdateUIQueue); send!(sender, DownloadManagerSignal::UpdateUIQueue);
return; return;
} }
@ -376,7 +370,7 @@ impl DownloadManagerBuilder {
fn push_ui_stats_update(&self, kbs: usize, time: usize) { fn push_ui_stats_update(&self, kbs: usize, time: usize) {
let event_data = StatsUpdateEvent { speed: kbs, time }; let event_data = StatsUpdateEvent { speed: kbs, time };
app_emit!(&self.app_handle, "update_stats", event_data); app_emit!(self.app_handle, "update_stats", event_data);
} }
fn push_ui_queue_update(&self) { fn push_ui_queue_update(&self) {
let queue = &self.download_queue.read(); let queue = &self.download_queue.read();
@ -395,6 +389,6 @@ impl DownloadManagerBuilder {
.collect(); .collect();
let event_data = QueueUpdateEvent { queue: queue_objs }; let event_data = QueueUpdateEvent { queue: queue_objs };
app_emit!(&self.app_handle, "update_queue", event_data); app_emit!(self.app_handle, "update_queue", event_data);
} }
} }

View File

@ -14,6 +14,7 @@ use log::{debug, info};
use serde::Serialize; use serde::Serialize;
use utils::{lock, send}; use utils::{lock, send};
use crate::error::ApplicationDownloadError; use crate::error::ApplicationDownloadError;
use super::{ use super::{
@ -79,7 +80,6 @@ pub enum DownloadStatus {
/// The actual download queue may be accessed through the .`edit()` function, /// The actual download queue may be accessed through the .`edit()` function,
/// which provides raw access to the underlying queue. /// which provides raw access to the underlying queue.
/// THIS EDITING IS BLOCKING!!! /// THIS EDITING IS BLOCKING!!!
#[derive(Debug)]
pub struct DownloadManager { pub struct DownloadManager {
terminator: Mutex<Option<JoinHandle<Result<(), ()>>>>, terminator: Mutex<Option<JoinHandle<Result<(), ()>>>>,
download_queue: Queue, download_queue: Queue,
@ -124,11 +124,8 @@ impl DownloadManager {
} }
pub fn rearrange_string(&self, meta: &DownloadableMetadata, new_index: usize) { pub fn rearrange_string(&self, meta: &DownloadableMetadata, new_index: usize) {
let mut queue = self.edit(); let mut queue = self.edit();
let current_index = let current_index = get_index_from_id(&mut queue, meta).expect("Failed to get meta index from id");
get_index_from_id(&mut queue, meta).expect("Failed to get meta index from id"); let to_move = queue.remove(current_index).expect("Failed to remove meta at index from queue");
let to_move = queue
.remove(current_index)
.expect("Failed to remove meta at index from queue");
queue.insert(new_index, to_move); queue.insert(new_index, to_move);
send!(self.command_sender, DownloadManagerSignal::UpdateUIQueue); send!(self.command_sender, DownloadManagerSignal::UpdateUIQueue);
} }

View File

@ -3,6 +3,7 @@ use std::sync::Arc;
use database::DownloadableMetadata; use database::DownloadableMetadata;
use tauri::AppHandle; use tauri::AppHandle;
use crate::error::ApplicationDownloadError; use crate::error::ApplicationDownloadError;
use super::{ use super::{

View File

@ -1,9 +1,5 @@
use humansize::{BINARY, format_size}; use std::{fmt::{Display, Formatter}, io, sync::{mpsc::SendError, Arc}};
use std::{ use humansize::{format_size, BINARY};
fmt::{Display, Formatter},
io,
sync::{Arc, mpsc::SendError},
};
use remote::error::RemoteAccessError; use remote::error::RemoteAccessError;
use serde_with::SerializeDisplay; use serde_with::SerializeDisplay;
@ -48,9 +44,7 @@ pub enum ApplicationDownloadError {
impl Display for ApplicationDownloadError { impl Display for ApplicationDownloadError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self { match self {
ApplicationDownloadError::NotInitialized => { ApplicationDownloadError::NotInitialized => write!(f, "Download not initalized, did something go wrong?"),
write!(f, "Download not initalized, did something go wrong?")
}
ApplicationDownloadError::DiskFull(required, available) => write!( ApplicationDownloadError::DiskFull(required, available) => write!(
f, f,
"Game requires {}, {} remaining left on disk.", "Game requires {}, {} remaining left on disk.",
@ -66,9 +60,10 @@ impl Display for ApplicationDownloadError {
write!(f, "checksum failed to validate for download") write!(f, "checksum failed to validate for download")
} }
ApplicationDownloadError::IoError(error) => write!(f, "io error: {error}"), ApplicationDownloadError::IoError(error) => write!(f, "io error: {error}"),
ApplicationDownloadError::DownloadError(error) => { ApplicationDownloadError::DownloadError(error) => write!(
write!(f, "Download failed with error {error:?}") f,
} "Download failed with error {error:?}"
),
} }
} }
} }

View File

@ -17,7 +17,7 @@ pub struct QueueUpdateEvent {
pub queue: Vec<QueueUpdateEventQueueData>, pub queue: Vec<QueueUpdateEventQueueData>,
} }
#[derive(Serialize, Clone)] #[derive(serde::Serialize, Clone)]
pub struct StatsUpdateEvent { pub struct StatsUpdateEvent {
pub speed: usize, pub speed: usize,
pub time: usize, pub time: usize,

View File

@ -1,44 +1,8 @@
#![feature(duration_millis_float)] #![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_builder;
pub mod download_manager_frontend; pub mod download_manager_frontend;
pub mod downloadable; pub mod downloadable;
pub mod util;
pub mod error; pub mod error;
pub mod frontend_updates; 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"),
}
}
}

View File

@ -1,6 +1,6 @@
use std::sync::{ use std::sync::{
Arc,
atomic::{AtomicBool, Ordering}, atomic::{AtomicBool, Ordering},
Arc,
}; };
#[derive(PartialEq, Eq, PartialOrd, Ord)] #[derive(PartialEq, Eq, PartialOrd, Ord)]
@ -22,11 +22,7 @@ impl From<DownloadThreadControlFlag> for bool {
/// false => Stop /// false => Stop
impl From<bool> for DownloadThreadControlFlag { impl From<bool> for DownloadThreadControlFlag {
fn from(value: bool) -> Self { fn from(value: bool) -> Self {
if value { if value { DownloadThreadControlFlag::Go } else { DownloadThreadControlFlag::Stop }
DownloadThreadControlFlag::Go
} else {
DownloadThreadControlFlag::Stop
}
} }
} }

View File

@ -15,7 +15,7 @@ use crate::download_manager_frontend::DownloadManagerSignal;
use super::rolling_progress_updates::RollingProgressWindow; use super::rolling_progress_updates::RollingProgressWindow;
#[derive(Clone, Debug)] #[derive(Clone)]
pub struct ProgressObject { pub struct ProgressObject {
max: Arc<Mutex<usize>>, max: Arc<Mutex<usize>>,
progress_instances: Arc<Mutex<Vec<Arc<AtomicUsize>>>>, progress_instances: Arc<Mutex<Vec<Arc<AtomicUsize>>>>,
@ -117,9 +117,7 @@ pub fn calculate_update(progress: &ProgressObject) {
let last_update_time = progress let last_update_time = progress
.last_update_time .last_update_time
.swap(Instant::now(), Ordering::SeqCst); .swap(Instant::now(), Ordering::SeqCst);
let time_since_last_update = Instant::now() let time_since_last_update = Instant::now().duration_since(last_update_time).as_millis_f64();
.duration_since(last_update_time)
.as_millis_f64();
let current_bytes_downloaded = progress.sum(); let current_bytes_downloaded = progress.sum();
let max = progress.get_max(); let max = progress.get_max();
@ -127,8 +125,7 @@ pub fn calculate_update(progress: &ProgressObject) {
.bytes_last_update .bytes_last_update
.swap(current_bytes_downloaded, Ordering::Acquire); .swap(current_bytes_downloaded, Ordering::Acquire);
let bytes_since_last_update = let bytes_since_last_update = current_bytes_downloaded.saturating_sub(bytes_at_last_update) as f64;
current_bytes_downloaded.saturating_sub(bytes_at_last_update) as f64;
let kilobytes_per_second = bytes_since_last_update / time_since_last_update; let kilobytes_per_second = bytes_since_last_update / time_since_last_update;

View File

@ -6,7 +6,7 @@ use std::{
use database::DownloadableMetadata; use database::DownloadableMetadata;
use utils::lock; use utils::lock;
#[derive(Clone, Debug)] #[derive(Clone)]
pub struct Queue { pub struct Queue {
inner: Arc<Mutex<VecDeque<DownloadableMetadata>>>, inner: Arc<Mutex<VecDeque<DownloadableMetadata>>>,
} }

View File

@ -3,17 +3,11 @@ use std::sync::{
atomic::{AtomicUsize, Ordering}, atomic::{AtomicUsize, Ordering},
}; };
#[derive(Clone, Debug)] #[derive(Clone)]
pub struct RollingProgressWindow<const S: usize> { pub struct RollingProgressWindow<const S: usize> {
window: Arc<[AtomicUsize; S]>, window: Arc<[AtomicUsize; S]>,
current: Arc<AtomicUsize>, current: Arc<AtomicUsize>,
} }
impl<const S: usize> Default for RollingProgressWindow<S> {
fn default() -> Self {
Self::new()
}
}
impl<const S: usize> RollingProgressWindow<S> { impl<const S: usize> RollingProgressWindow<S> {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {

View File

@ -1,13 +1,8 @@
use database::{ use database::{borrow_db_checked, borrow_db_mut_checked, ApplicationTransientStatus, DownloadType, DownloadableMetadata};
ApplicationTransientStatus, DownloadType, DownloadableMetadata, borrow_db_checked,
borrow_db_mut_checked,
};
use download_manager::download_manager_frontend::{DownloadManagerSignal, DownloadStatus}; use download_manager::download_manager_frontend::{DownloadManagerSignal, DownloadStatus};
use download_manager::downloadable::Downloadable; use download_manager::downloadable::Downloadable;
use download_manager::error::ApplicationDownloadError; use download_manager::error::ApplicationDownloadError;
use download_manager::util::download_thread_control_flag::{ use download_manager::util::download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag};
DownloadThreadControl, DownloadThreadControlFlag,
};
use download_manager::util::progress_object::{ProgressHandle, ProgressObject}; use download_manager::util::progress_object::{ProgressHandle, ProgressObject};
use log::{debug, error, info, warn}; use log::{debug, error, info, warn};
use rayon::ThreadPoolBuilder; use rayon::ThreadPoolBuilder;
@ -15,6 +10,7 @@ use remote::auth::generate_authorization_header;
use remote::error::RemoteAccessError; use remote::error::RemoteAccessError;
use remote::requests::generate_url; use remote::requests::generate_url;
use remote::utils::{DROP_CLIENT_ASYNC, DROP_CLIENT_SYNC}; use remote::utils::{DROP_CLIENT_ASYNC, DROP_CLIENT_SYNC};
use utils::{app_emit, lock, send};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::fs::{OpenOptions, create_dir_all}; use std::fs::{OpenOptions, create_dir_all};
use std::io; use std::io;
@ -22,15 +18,12 @@ use std::path::{Path, PathBuf};
use std::sync::mpsc::Sender; use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::time::Instant; use std::time::Instant;
use tauri::AppHandle; use tauri::{AppHandle, Emitter};
use utils::{app_emit, lock, send};
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
use rustix::fs::{FallocateFlags, fallocate}; use rustix::fs::{FallocateFlags, fallocate};
use crate::downloads::manifest::{ use crate::downloads::manifest::{DownloadBucket, DownloadContext, DownloadDrop, DropManifest, DropValidateContext, ManifestBody};
DownloadBucket, DownloadContext, DownloadDrop, DropManifest, DropValidateContext, ManifestBody,
};
use crate::downloads::utils::get_disk_available; use crate::downloads::utils::get_disk_available;
use crate::downloads::validate::validate_game_chunk; use crate::downloads::validate::validate_game_chunk;
use crate::library::{on_game_complete, push_game_update, set_partially_installed}; use crate::library::{on_game_complete, push_game_update, set_partially_installed};
@ -104,7 +97,8 @@ impl GameDownloadAgent {
result.ensure_manifest_exists().await?; result.ensure_manifest_exists().await?;
let required_space = lock!(result.manifest) let required_space = lock!(result
.manifest)
.as_ref() .as_ref()
.unwrap() .unwrap()
.values() .values()
@ -453,13 +447,9 @@ impl GameDownloadAgent {
let sender = self.sender.clone(); let sender = self.sender.clone();
let download_context = let download_context = download_contexts
download_contexts.get(&bucket.version).unwrap_or_else(|| { .get(&bucket.version)
panic!( .unwrap_or_else(|| panic!("Could not get bucket version {}. Corrupted state.", bucket.version));
"Could not get bucket version {}. Corrupted state.",
bucket.version
)
});
scope.spawn(move |_| { scope.spawn(move |_| {
// 3 attempts // 3 attempts
@ -697,10 +687,7 @@ impl Downloadable for GameDownloadAgent {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(e) => {
error!("could not mark game as complete: {e}"); error!("could not mark game as complete: {e}");
send!( send!(self.sender, DownloadManagerSignal::Error(ApplicationDownloadError::DownloadError(e)));
self.sender,
DownloadManagerSignal::Error(ApplicationDownloadError::DownloadError(e))
);
} }
} }
} }

View File

@ -11,9 +11,7 @@ use std::{
}; };
use download_manager::error::ApplicationDownloadError; use download_manager::error::ApplicationDownloadError;
use download_manager::util::download_thread_control_flag::{ use download_manager::util::download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag};
DownloadThreadControl, DownloadThreadControlFlag,
};
use download_manager::util::progress_object::ProgressHandle; use download_manager::util::progress_object::ProgressHandle;
use log::{debug, info, warn}; use log::{debug, info, warn};
use md5::{Context, Digest}; use md5::{Context, Digest};
@ -49,7 +47,7 @@ impl DropWriter<File> {
fn finish(mut self) -> io::Result<Digest> { fn finish(mut self) -> io::Result<Digest> {
self.flush()?; self.flush()?;
Ok(self.hasher.finalize()) Ok(self.hasher.compute())
} }
} }
// Write automatically pushes to file and hasher // Write automatically pushes to file and hasher
@ -118,12 +116,9 @@ impl<'a> DropDownloadPipeline<'a, Response, File> {
let mut last_bump = 0; let mut last_bump = 0;
loop { loop {
let size = MAX_PACKET_LENGTH.min(remaining); let size = MAX_PACKET_LENGTH.min(remaining);
let size = self let size = self.source.read(&mut copy_buffer[0..size]).inspect_err(|_| {
.source info!("got error from {}", drop.filename);
.read(&mut copy_buffer[0..size]) })?;
.inspect_err(|_| {
info!("got error from {}", drop.filename);
})?;
remaining -= size; remaining -= size;
last_bump += size; last_bump += size;

View File

@ -1,8 +1,5 @@
use std::{ use std::{
collections::HashMap, collections::HashMap, fs::File, io::{self, Read, Write}, path::{Path, PathBuf}
fs::File,
io::{self, Read, Write},
path::{Path, PathBuf},
}; };
use log::error; use log::error;
@ -80,10 +77,7 @@ impl DropData {
} }
} }
pub fn set_contexts(&self, completed_contexts: &[(String, bool)]) { pub fn set_contexts(&self, completed_contexts: &[(String, bool)]) {
*lock!(self.contexts) = completed_contexts *lock!(self.contexts) = completed_contexts.iter().map(|s| (s.0.clone(), s.1)).collect();
.iter()
.map(|s| (s.0.clone(), s.1))
.collect();
} }
pub fn set_context(&self, context: String, state: bool) { pub fn set_context(&self, context: String, state: bool) {
lock!(self.contexts).entry(context).insert_entry(state); lock!(self.contexts).entry(context).insert_entry(state);

View File

@ -1,4 +1,4 @@
use std::fmt::Display; use std::fmt::{Display};
use serde_with::SerializeDisplay; use serde_with::SerializeDisplay;
@ -9,21 +9,13 @@ pub enum LibraryError {
} }
impl Display for LibraryError { impl Display for LibraryError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!( write!(f, "{}", match self {
f, LibraryError::MetaNotFound(id) => {
"{}", format!("Could not locate any installed version of game ID {id} in the database")
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"
)
}
} }
) LibraryError::VersionNotFound(game_id) => {
format!("Could not locate any installed version for game id {game_id} in the database")
}
})
} }
} }

View File

@ -3,5 +3,5 @@ mod download_logic;
pub mod drop_data; pub mod drop_data;
pub mod error; pub mod error;
mod manifest; mod manifest;
pub mod utils;
pub mod validate; pub mod validate;
pub mod utils;

View File

@ -19,7 +19,7 @@ pub fn get_disk_available(mount_point: PathBuf) -> Result<u64, ApplicationDownlo
return Ok(disk.available_space()); return Ok(disk.available_space());
} }
} }
Err(ApplicationDownloadError::IoError(Arc::new( Err(ApplicationDownloadError::IoError(Arc::new(io::Error::other(
io::Error::other("could not find disk of path"), "could not find disk of path",
))) ))))
} }

View File

@ -3,13 +3,7 @@ use std::{
io::{self, BufWriter, Read, Seek, SeekFrom, Write}, io::{self, BufWriter, Read, Seek, SeekFrom, Write},
}; };
use download_manager::{ use download_manager::{error::ApplicationDownloadError, util::{download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag}, progress_object::ProgressHandle}};
error::ApplicationDownloadError,
util::{
download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag},
progress_object::ProgressHandle,
},
};
use log::debug; use log::debug;
use md5::Context; use md5::Context;
@ -22,10 +16,7 @@ pub fn validate_game_chunk(
) -> Result<bool, ApplicationDownloadError> { ) -> Result<bool, ApplicationDownloadError> {
debug!( debug!(
"Starting chunk validation {}, {}, {} #{}", "Starting chunk validation {}, {}, {} #{}",
ctx.path.display(), ctx.path.display(), ctx.index, ctx.offset, ctx.checksum
ctx.index,
ctx.offset,
ctx.checksum
); );
// If we're paused // If we're paused
if control_flag.get() == DownloadThreadControlFlag::Stop { if control_flag.get() == DownloadThreadControlFlag::Stop {
@ -45,12 +36,13 @@ pub fn validate_game_chunk(
let mut hasher = md5::Context::new(); let mut hasher = md5::Context::new();
let completed = validate_copy(&mut source, &mut hasher, ctx.length, control_flag, progress)?; let completed =
validate_copy(&mut source, &mut hasher, ctx.length, control_flag, progress)?;
if !completed { if !completed {
return Ok(false); return Ok(false);
} }
let res = hex::encode(hasher.finalize().0); let res = hex::encode(hasher.compute().0);
if res != ctx.checksum { if res != ctx.checksum {
return Ok(false); return Ok(false);
} }

View File

@ -3,5 +3,4 @@
pub mod collections; pub mod collections;
pub mod downloads; pub mod downloads;
pub mod library; pub mod library;
pub mod scan;
pub mod state; pub mod state;

View File

@ -1,20 +1,15 @@
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::fs::remove_dir_all;
use std::sync::Mutex;
use std::thread::spawn; use std::thread::spawn;
use bitcode::{Decode, Encode};
use database::{borrow_db_checked, borrow_db_mut_checked, ApplicationTransientStatus, Database, DownloadableMetadata, GameDownloadStatus, GameVersion};
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 tauri::AppHandle; use tauri::AppHandle;
use utils::app_emit; use utils::app_emit;
use crate::state::{GameStatusManager, GameStatusWithTransient}; use crate::{downloads::error::LibraryError, state::{GameStatusManager, GameStatusWithTransient}};
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct FetchGameStruct { pub struct FetchGameStruct {
@ -23,16 +18,6 @@ pub struct FetchGameStruct {
version: Option<GameVersion>, 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)] #[derive(Serialize, Deserialize, Clone, Debug, Default, Encode, Decode)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct Game { pub struct Game {
@ -48,11 +33,6 @@ pub struct Game {
m_image_library_object_ids: Vec<String>, m_image_library_object_ids: Vec<String>,
m_image_carousel_object_ids: Vec<String>, m_image_carousel_object_ids: Vec<String>,
} }
impl Game {
pub fn id(&self) -> &String {
&self.id
}
}
#[derive(serde::Serialize, Clone)] #[derive(serde::Serialize, Clone)]
pub struct GameUpdateEvent { pub struct GameUpdateEvent {
pub game_id: String, pub game_id: String,
@ -177,7 +157,7 @@ pub fn uninstall_game_logic(meta: DownloadableMetadata, app_handle: &AppHandle)
); );
debug!("uninstalled game id {}", &meta.id); debug!("uninstalled game id {}", &meta.id);
app_emit!(&app_handle, "update_library", ()); app_emit!(app_handle, "update_library", ());
} }
}); });
} else { } else {
@ -293,8 +273,41 @@ pub struct FrontendGameOptions {
launch_string: String, launch_string: String,
} }
impl FrontendGameOptions { #[tauri::command]
pub fn launch_string(&self) -> &String { pub fn update_game_configuration(
&self.launch_string game_id: String,
} options: FrontendGameOptions,
) -> Result<(), LibraryError> {
let mut handle = borrow_db_mut_checked();
let installed_version = handle
.applications
.installed_game_version
.get(&game_id)
.ok_or(LibraryError::MetaNotFound(game_id))?;
let id = installed_version.id.clone();
let version = installed_version.version.clone().ok_or(LibraryError::VersionNotFound(id.clone()))?;
let mut existing_configuration = handle
.applications
.game_versions
.get(&id)
.unwrap()
.get(&version)
.unwrap()
.clone();
// Add more options in here
existing_configuration.launch_command_template = options.launch_string;
// Add no more options past here
handle
.applications
.game_versions
.get_mut(&id)
.unwrap()
.insert(version.to_string(), existing_configuration);
Ok(())
} }

View File

@ -1,11 +1,16 @@
use std::fs; use std::fs;
use database::{DownloadType, DownloadableMetadata, borrow_db_mut_checked};
use log::warn; use log::warn;
use crate::{ use crate::{
downloads::drop_data::{DROP_DATA_PATH, DropData}, database::{
library::set_partially_installed_db, 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() { pub fn scan_install_dirs() {

View File

@ -8,9 +8,7 @@ chrono = "0.4.42"
client = { version = "0.1.0", path = "../client" } client = { version = "0.1.0", path = "../client" }
database = { version = "0.1.0", path = "../database" } database = { version = "0.1.0", path = "../database" }
dynfmt = "0.1.5" dynfmt = "0.1.5"
games = { version = "0.1.0", path = "../games" }
log = "0.4.28" log = "0.4.28"
page_size = "0.6.0"
serde = "1.0.228" serde = "1.0.228"
serde_with = "3.15.0" serde_with = "3.15.0"
shared_child = "1.1.1" shared_child = "1.1.1"

View File

@ -12,8 +12,7 @@ pub enum ProcessError {
FormatError(String), // String errors supremacy FormatError(String), // String errors supremacy
InvalidPlatform, InvalidPlatform,
OpenerError(tauri_plugin_opener::Error), OpenerError(tauri_plugin_opener::Error),
InvalidArguments(String), InvalidArguments(String)
FailedLaunch(String),
} }
impl Display for ProcessError { impl Display for ProcessError {
@ -27,13 +26,8 @@ impl Display for ProcessError {
ProcessError::InvalidPlatform => "This game cannot be played on the current platform", ProcessError::InvalidPlatform => "This game cannot be played on the current platform",
ProcessError::FormatError(error) => &format!("Could not format template: {error:?}"), ProcessError::FormatError(error) => &format!("Could not format template: {error:?}"),
ProcessError::OpenerError(error) => &format!("Could not open directory: {error:?}"), ProcessError::OpenerError(error) => &format!("Could not open directory: {error:?}"),
ProcessError::InvalidArguments(arguments) => { ProcessError::InvalidArguments(arguments) => &format!("Invalid arguments in command {arguments}"),
&format!("Invalid arguments in command {arguments}") };
}
ProcessError::FailedLaunch(game_id) => {
&format!("Drop detected that the game {game_id} may have failed to launch properly")
}
};
write!(f, "{s}") write!(f, "{s}")
} }
} }

View File

@ -8,12 +8,7 @@ pub struct DropFormatArgs {
} }
impl DropFormatArgs { impl DropFormatArgs {
pub fn new( pub fn new(launch_string: String, working_dir: &String, executable_name: &String, absolute_executable_name: String) -> Self {
launch_string: String,
working_dir: &String,
executable_name: &String,
absolute_executable_name: String,
) -> Self {
let mut positional = Vec::new(); let mut positional = Vec::new();
let mut map: HashMap<&'static str, String> = HashMap::new(); let mut map: HashMap<&'static str, String> = HashMap::new();

View File

@ -1,41 +1,4 @@
#![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 mod process_manager;
pub mod process_handlers;
pub struct ProcessManagerWrapper(OnceLock<Mutex<ProcessManager<'static>>>); pub mod format;
impl ProcessManagerWrapper { pub mod error;
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"),
}
}
}

View File

@ -1,6 +1,13 @@
use client::compat::{COMPAT_INFO, UMU_LAUNCHER_EXECUTABLE}; use std::{
use database::{Database, DownloadableMetadata, GameVersion, platform::Platform}; ffi::OsStr,
use log::debug; path::PathBuf,
process::{Command, Stdio},
sync::LazyLock,
};
use database::{platform::Platform, Database, DownloadableMetadata, GameVersion};
use log::{debug, info};
use crate::{error::ProcessError, process_manager::ProcessHandler}; use crate::{error::ProcessError, process_manager::ProcessHandler};
@ -17,11 +24,36 @@ impl ProcessHandler for NativeGameLauncher {
Ok(format!("\"{}\" {}", launch_command, args.join(" "))) Ok(format!("\"{}\" {}", launch_command, args.join(" ")))
} }
fn valid_for_platform(&self, _db: &Database, _target: &Platform) -> bool { fn valid_for_platform(&self, _db: &Database, _state: &AppState, _target: &Platform) -> bool {
true true
} }
} }
pub static UMU_LAUNCHER_EXECUTABLE: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
let x = get_umu_executable();
info!("{:?}", &x);
x
});
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()
}
pub struct UMULauncher; pub struct UMULauncher;
impl ProcessHandler for UMULauncher { impl ProcessHandler for UMULauncher {
fn create_launch_process( fn create_launch_process(
@ -45,16 +77,14 @@ impl ProcessHandler for UMULauncher {
}; };
Ok(format!( Ok(format!(
"GAMEID={game_id} {umu:?} \"{launch}\" {args}", "GAMEID={game_id} {umu:?} \"{launch}\" {args}",
umu = UMU_LAUNCHER_EXECUTABLE umu = UMU_LAUNCHER_EXECUTABLE.as_ref().expect("Failed to get UMU_LAUNCHER_EXECUTABLE as ref"),
.as_ref()
.expect("Failed to get UMU_LAUNCHER_EXECUTABLE as ref"),
launch = launch_command, launch = launch_command,
args = args.join(" ") args = args.join(" ")
)) ))
} }
fn valid_for_platform(&self, _db: &Database, _target: &Platform) -> bool { fn valid_for_platform(&self, _db: &Database, state: &AppState, _target: &Platform) -> bool {
let Some(compat_info) = &*COMPAT_INFO else { let Some(ref compat_info) = state.compat_info else {
return false; return false;
}; };
compat_info.umu_installed compat_info.umu_installed
@ -87,19 +117,14 @@ impl ProcessHandler for AsahiMuvmLauncher {
.next() .next()
.ok_or(ProcessError::InvalidArguments(umu_string.clone()))? .ok_or(ProcessError::InvalidArguments(umu_string.clone()))?
.trim(); .trim();
let cmd = format!( let cmd = format!("umu-run{}", args_cmd.next().ok_or(ProcessError::InvalidArguments(umu_string.clone()))?);
"umu-run{}",
args_cmd
.next()
.ok_or(ProcessError::InvalidArguments(umu_string.clone()))?
);
Ok(format!("{args} muvm -- {cmd}")) Ok(format!("{args} muvm -- {cmd}"))
} }
#[allow(unreachable_code)] #[allow(unreachable_code)]
#[allow(unused_variables)] #[allow(unused_variables)]
fn valid_for_platform(&self, _db: &Database, _target: &Platform) -> bool { fn valid_for_platform(&self, _db: &Database, state: &AppState, _target: &Platform) -> bool {
#[cfg(not(target_os = "linux"))] #[cfg(not(target_os = "linux"))]
return false; return false;
@ -111,7 +136,7 @@ impl ProcessHandler for AsahiMuvmLauncher {
return false; return false;
} }
let Some(compat_info) = &*COMPAT_INFO else { let Some(ref compat_info) = state.compat_info else {
return false; return false;
}; };

View File

@ -1,32 +1,27 @@
use std::{ use std::{
collections::HashMap, collections::HashMap,
fs::{OpenOptions, create_dir_all}, fs::{OpenOptions, create_dir_all},
io, io::{self},
path::PathBuf, path::PathBuf,
process::{Command, ExitStatus}, process::{Command, ExitStatus},
str::FromStr, str::FromStr,
sync::Arc, sync::{Arc, Mutex},
thread::spawn, thread::spawn,
time::{Duration, SystemTime}, time::{Duration, SystemTime},
}; };
use database::{ use database::{borrow_db_checked, borrow_db_mut_checked, db::DATA_ROOT_DIR, platform::Platform, ApplicationTransientStatus, Database, DownloadType, DownloadableMetadata, GameDownloadStatus, GameVersion};
ApplicationTransientStatus, Database, DownloadType, DownloadableMetadata, GameDownloadStatus,
GameVersion, borrow_db_checked, borrow_db_mut_checked, db::DATA_ROOT_DIR, platform::Platform,
};
use dynfmt::Format; use dynfmt::Format;
use dynfmt::SimpleCurlyFormat; use dynfmt::SimpleCurlyFormat;
use games::{library::push_game_update, state::GameStatusManager};
use log::{debug, info, warn}; use log::{debug, info, warn};
use serde::{Deserialize, Serialize};
use shared_child::SharedChild; use shared_child::SharedChild;
use tauri::AppHandle; use tauri::{AppHandle, Emitter, Manager};
use tauri_plugin_opener::OpenerExt;
use utils::lock;
use crate::{error::ProcessError, format::DropFormatArgs, process_handlers::{AsahiMuvmLauncher, NativeGameLauncher, UMULauncher}};
use crate::{
PROCESS_MANAGER,
error::ProcessError,
format::DropFormatArgs,
process_handlers::{AsahiMuvmLauncher, NativeGameLauncher, UMULauncher},
};
pub struct RunningProcess { pub struct RunningProcess {
handle: Arc<SharedChild>, handle: Arc<SharedChild>,
@ -38,11 +33,11 @@ pub struct ProcessManager<'a> {
current_platform: Platform, current_platform: Platform,
log_output_dir: PathBuf, log_output_dir: PathBuf,
processes: HashMap<String, RunningProcess>, processes: HashMap<String, RunningProcess>,
app_handle: AppHandle,
game_launchers: Vec<( game_launchers: Vec<(
(Platform, Platform), (Platform, Platform),
&'a (dyn ProcessHandler + Sync + Send + 'static), &'a (dyn ProcessHandler + Sync + Send + 'static),
)>, )>,
app_handle: AppHandle,
} }
impl ProcessManager<'_> { impl ProcessManager<'_> {
@ -59,6 +54,7 @@ impl ProcessManager<'_> {
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
current_platform: Platform::Linux, current_platform: Platform::Linux,
app_handle,
processes: HashMap::new(), processes: HashMap::new(),
log_output_dir, log_output_dir,
game_launchers: vec![ game_launchers: vec![
@ -84,7 +80,6 @@ impl ProcessManager<'_> {
&UMULauncher {} as &(dyn ProcessHandler + Sync + Send + 'static), &UMULauncher {} as &(dyn ProcessHandler + Sync + Send + 'static),
), ),
], ],
app_handle,
} }
} }
@ -103,20 +98,25 @@ impl ProcessManager<'_> {
} }
} }
pub fn get_log_dir(&self, game_id: String) -> PathBuf { fn get_log_dir(&self, game_id: String) -> PathBuf {
self.log_output_dir.join(game_id) self.log_output_dir.join(game_id)
} }
fn on_process_finish( pub fn open_process_logs(&mut self, game_id: String) -> Result<(), ProcessError> {
&mut self, let dir = self.get_log_dir(game_id);
game_id: String, self.app_handle
result: Result<ExitStatus, std::io::Error>, .opener()
) -> Result<(), ProcessError> { .open_path(dir.display().to_string(), None::<&str>)
.map_err(ProcessError::OpenerError)?;
Ok(())
}
fn on_process_finish(&mut self, game_id: String, result: Result<ExitStatus, std::io::Error>) {
if !self.processes.contains_key(&game_id) { if !self.processes.contains_key(&game_id) {
warn!( warn!(
"process on_finish was called, but game_id is no longer valid. finished with result: {result:?}" "process on_finish was called, but game_id is no longer valid. finished with result: {result:?}"
); );
return Ok(()); return;
} }
debug!("process for {:?} exited with {:?}", &game_id, result); debug!("process for {:?} exited with {:?}", &game_id, result);
@ -125,7 +125,7 @@ impl ProcessManager<'_> {
Some(process) => process, Some(process) => process,
None => { None => {
info!("Attempted to stop process {game_id} which didn't exist"); info!("Attempted to stop process {game_id} which didn't exist");
return Ok(()); return;
} }
}; };
@ -163,8 +163,7 @@ impl ProcessManager<'_> {
&& (elapsed.as_secs() <= 2 || result.map_or(true, |r| !r.success())) && (elapsed.as_secs() <= 2 || result.map_or(true, |r| !r.success()))
{ {
warn!("drop detected that the game {game_id} may have failed to launch properly"); warn!("drop detected that the game {game_id} may have failed to launch properly");
return Err(ProcessError::FailedLaunch(game_id)); let _ = self.app_handle.emit("launch_external_error", &game_id);
// let _ = self.app_handle.emit("launch_external_error", &game_id);
} }
let version_data = match db_handle.applications.game_versions.get(&game_id) { let version_data = match db_handle.applications.game_versions.get(&game_id) {
@ -181,12 +180,12 @@ impl ProcessManager<'_> {
Some(version_data.clone()), Some(version_data.clone()),
status, status,
); );
Ok(())
} }
fn fetch_process_handler( fn fetch_process_handler(
&self, &self,
db_lock: &Database, db_lock: &Database,
state: &AppState,
target_platform: &Platform, target_platform: &Platform,
) -> Result<&(dyn ProcessHandler + Send + Sync), ProcessError> { ) -> Result<&(dyn ProcessHandler + Send + Sync), ProcessError> {
Ok(self Ok(self
@ -196,20 +195,23 @@ impl ProcessManager<'_> {
let (e_current, e_target) = e.0; let (e_current, e_target) = e.0;
e_current == self.current_platform e_current == self.current_platform
&& e_target == *target_platform && e_target == *target_platform
&& e.1.valid_for_platform(db_lock, target_platform) && e.1.valid_for_platform(db_lock, state, target_platform)
}) })
.ok_or(ProcessError::InvalidPlatform)? .ok_or(ProcessError::InvalidPlatform)?
.1) .1)
} }
pub fn valid_platform(&self, platform: &Platform) -> bool { pub fn valid_platform(&self, platform: &Platform, state: &AppState) -> bool {
let db_lock = borrow_db_checked(); let db_lock = borrow_db_checked();
let process_handler = self.fetch_process_handler(&db_lock, platform); let process_handler = self.fetch_process_handler(&db_lock, state, platform);
process_handler.is_ok() process_handler.is_ok()
} }
/// Must be called through spawn as it is currently blocking pub fn launch_process(
pub fn launch_process(&mut self, game_id: String) -> Result<(), ProcessError> { &mut self,
game_id: String,
state: &AppState,
) -> Result<(), ProcessError> {
if self.processes.contains_key(&game_id) { if self.processes.contains_key(&game_id) {
return Err(ProcessError::AlreadyRunning); return Err(ProcessError::AlreadyRunning);
} }
@ -291,7 +293,7 @@ impl ProcessManager<'_> {
let target_platform = game_version.platform; let target_platform = game_version.platform;
let process_handler = self.fetch_process_handler(&db_lock, &target_platform)?; let process_handler = self.fetch_process_handler(&db_lock, state, &target_platform)?;
let (launch, args) = match game_status { let (launch, args) = match game_status {
GameDownloadStatus::Installed { GameDownloadStatus::Installed {
@ -373,8 +375,27 @@ impl ProcessManager<'_> {
); );
let wait_thread_handle = launch_process_handle.clone(); let wait_thread_handle = launch_process_handle.clone();
let wait_thread_apphandle = self.app_handle.clone();
let wait_thread_game_id = meta.clone(); let wait_thread_game_id = meta.clone();
spawn(move || {
let result: Result<ExitStatus, std::io::Error> = launch_process_handle.wait();
let app_state = wait_thread_apphandle.state::<Mutex<AppState>>();
let app_state_handle = lock!(app_state);
let mut process_manager_handle = app_state_handle
.process_manager
.lock()
.expect("Failed to lock onto process manager");
process_manager_handle.on_process_finish(wait_thread_game_id.id, result);
// As everything goes out of scope, they should get dropped
// But just to explicit about it
drop(process_manager_handle);
drop(app_state_handle);
});
self.processes.insert( self.processes.insert(
meta.id, meta.id,
RunningProcess { RunningProcess {
@ -383,13 +404,6 @@ impl ProcessManager<'_> {
manually_killed: false, manually_killed: false,
}, },
); );
spawn(move || {
let result: Result<ExitStatus, std::io::Error> = launch_process_handle.wait();
PROCESS_MANAGER
.lock()
.on_process_finish(wait_thread_game_id.id, result)
});
Ok(()) Ok(())
} }
} }
@ -404,5 +418,5 @@ pub trait ProcessHandler: Send + 'static {
current_dir: &str, current_dir: &str,
) -> Result<String, ProcessError>; ) -> Result<String, ProcessError>;
fn valid_for_platform(&self, db: &Database, target: &Platform) -> bool; fn valid_for_platform(&self, db: &Database, state: &AppState, target: &Platform) -> bool;
} }

View File

@ -2,18 +2,14 @@ use std::{collections::HashMap, env};
use chrono::Utc; use chrono::Utc;
use client::{app_status::AppStatus, user::User}; use client::{app_status::AppStatus, user::User};
use database::{DatabaseAuth, interface::borrow_db_checked}; use database::interface::borrow_db_checked;
use droplet_rs::ssl::sign_nonce; use droplet_rs::ssl::sign_nonce;
use gethostname::gethostname; use gethostname::gethostname;
use log::{error, warn}; use log::{error, warn};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use url::Url; use url::Url;
use crate::{ use crate::{error::{DropServerError, RemoteAccessError}, requests::make_authenticated_get, utils::DROP_CLIENT_SYNC};
error::{DropServerError, RemoteAccessError},
requests::make_authenticated_get,
utils::DROP_CLIENT_SYNC,
};
use super::{ use super::{
cache::{cache_object, get_cached_object}, cache::{cache_object, get_cached_object},
@ -35,31 +31,19 @@ struct InitiateRequestBody {
#[derive(Serialize)] #[derive(Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct HandshakeRequestBody { struct HandshakeRequestBody {
client_id: String, client_id: String,
token: String, token: String,
} }
impl HandshakeRequestBody {
pub fn new(client_id: String, token: String) -> Self {
Self { client_id, token }
}
}
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct HandshakeResponse { struct HandshakeResponse {
private: String, private: String,
certificate: String, certificate: String,
id: 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 { pub fn generate_authorization_header() -> String {
let certs = { let certs = {
let db = borrow_db_checked(); let db = borrow_db_checked();

View File

@ -6,8 +6,8 @@ use std::{
}; };
use bitcode::{Decode, DecodeOwned, Encode}; use bitcode::{Decode, DecodeOwned, Encode};
use database::{Database, borrow_db_checked}; use database::{borrow_db_checked, Database};
use http::{Response, header::CONTENT_TYPE, response::Builder as ResponseBuilder}; use http::{header::{CONTENT_TYPE}, response::Builder as ResponseBuilder, Response};
use crate::error::{CacheError, RemoteAccessError}; use crate::error::{CacheError, RemoteAccessError};
@ -15,9 +15,7 @@ use crate::error::{CacheError, RemoteAccessError};
macro_rules! offline { macro_rules! offline {
($var:expr, $func1:expr, $func2:expr, $( $arg:expr ),* ) => { ($var:expr, $func1:expr, $func2:expr, $( $arg:expr ),* ) => {
async move { async move { if $crate::borrow_db_checked().settings.force_offline || $crate::lock!($var).status == $crate::AppStatus::Offline {
if ::database::borrow_db_checked().settings.force_offline
|| $var.lock().status == ::client::app_status::AppStatus::Offline {
$func2( $( $arg ), *).await $func2( $( $arg ), *).await
} else { } else {
$func1( $( $arg ), *).await $func1( $( $arg ), *).await
@ -83,7 +81,10 @@ pub fn get_cached_object_db<D: DecodeOwned>(
pub fn clear_cached_object(key: &str) -> Result<(), RemoteAccessError> { pub fn clear_cached_object(key: &str) -> Result<(), RemoteAccessError> {
clear_cached_object_db(key, &borrow_db_checked()) clear_cached_object_db(key, &borrow_db_checked())
} }
pub fn clear_cached_object_db(key: &str, db: &Database) -> Result<(), RemoteAccessError> { pub fn clear_cached_object_db(
key: &str,
db: &Database,
) -> Result<(), RemoteAccessError> {
delete_sync(&db.cache_dir, key).map_err(RemoteAccessError::Cache)?; delete_sync(&db.cache_dir, key).map_err(RemoteAccessError::Cache)?;
Ok(()) Ok(())
} }
@ -117,15 +118,14 @@ impl TryFrom<Response<Vec<u8>>> for ObjectCache {
body: value.body().clone(), body: value.body().clone(),
expiry: get_sys_time_in_secs() + 60 * 60 * 24, expiry: get_sys_time_in_secs() + 60 * 60 * 24,
}) })
} }
} }
impl TryFrom<ObjectCache> for Response<Vec<u8>> { impl TryFrom<ObjectCache> for Response<Vec<u8>> {
type Error = CacheError; type Error = CacheError;
fn try_from(value: ObjectCache) -> Result<Self, Self::Error> { fn try_from(value: ObjectCache) -> Result<Self, Self::Error> {
let resp_builder = ResponseBuilder::new().header(CONTENT_TYPE, value.content_type); let resp_builder = ResponseBuilder::new().header(CONTENT_TYPE, value.content_type);
resp_builder resp_builder.body(value.body).map_err(CacheError::ConstructionError)
.body(value.body)
.map_err(CacheError::ConstructionError)
} }
} }
impl TryFrom<&ObjectCache> for Response<Vec<u8>> { impl TryFrom<&ObjectCache> for Response<Vec<u8>> {
@ -133,8 +133,6 @@ impl TryFrom<&ObjectCache> for Response<Vec<u8>> {
fn try_from(value: &ObjectCache) -> Result<Self, Self::Error> { fn try_from(value: &ObjectCache) -> Result<Self, Self::Error> {
let resp_builder = ResponseBuilder::new().header(CONTENT_TYPE, value.content_type.clone()); let resp_builder = ResponseBuilder::new().header(CONTENT_TYPE, value.content_type.clone());
resp_builder resp_builder.body(value.body.clone()).map_err(CacheError::ConstructionError)
.body(value.body.clone())
.map_err(CacheError::ConstructionError)
} }
} }

View File

@ -4,7 +4,7 @@ use std::{
sync::Arc, sync::Arc,
}; };
use http::{HeaderName, StatusCode, header::ToStrError}; use http::{header::ToStrError, HeaderName, StatusCode};
use serde_with::SerializeDisplay; use serde_with::SerializeDisplay;
use url::ParseError; use url::ParseError;
@ -19,6 +19,7 @@ pub struct DropServerError {
// pub url: String, // pub url: String,
} }
#[derive(Debug, SerializeDisplay)] #[derive(Debug, SerializeDisplay)]
pub enum RemoteAccessError { pub enum RemoteAccessError {
FetchError(Arc<reqwest::Error>), FetchError(Arc<reqwest::Error>),
@ -119,24 +120,16 @@ pub enum CacheError {
HeaderNotFound(HeaderName), HeaderNotFound(HeaderName),
ParseError(ToStrError), ParseError(ToStrError),
Remote(RemoteAccessError), Remote(RemoteAccessError),
ConstructionError(http::Error), ConstructionError(http::Error)
} }
impl Display for CacheError { impl Display for CacheError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self { let s = match self {
CacheError::HeaderNotFound(header_name) => { CacheError::HeaderNotFound(header_name) => format!("Could not find header {header_name} in cache"),
format!("Could not find header {header_name} in cache") CacheError::ParseError(to_str_error) => format!("Could not parse cache with error {to_str_error}"),
} CacheError::Remote(remote_access_error) => format!("Cache got remote access error: {remote_access_error}"),
CacheError::ParseError(to_str_error) => { CacheError::ConstructionError(error) => format!("Could not construct cache body with error {error}"),
format!("Could not parse cache with error {to_str_error}")
}
CacheError::Remote(remote_access_error) => {
format!("Cache got remote access error: {remote_access_error}")
}
CacheError::ConstructionError(error) => {
format!("Could not construct cache body with error {error}")
}
}; };
write!(f, "{s}") write!(f, "{s}")
} }

View File

@ -1,5 +1,5 @@
use database::{DB, interface::DatabaseImpls}; use database::{interface::DatabaseImpls, DB};
use http::{Response, header::CONTENT_TYPE, response::Builder as ResponseBuilder}; use http::{header::CONTENT_TYPE, response::Builder as ResponseBuilder, Response};
use log::{debug, warn}; use log::{debug, warn};
use tauri::UriSchemeResponder; use tauri::UriSchemeResponder;
@ -15,19 +15,13 @@ pub async fn fetch_object_wrapper(request: http::Request<Vec<u8>>, responder: Ur
Ok(r) => responder.respond(r), Ok(r) => responder.respond(r),
Err(e) => { Err(e) => {
warn!("Cache error: {e}"); warn!("Cache error: {e}");
responder.respond( responder.respond(Response::builder().status(500).body(Vec::new()).expect("Failed to build error response"));
Response::builder()
.status(500)
.body(Vec::new())
.expect("Failed to build error response"),
);
} }
}; };
} }
pub async fn fetch_object( pub async fn fetch_object(request: http::Request<Vec<u8>>) -> Result<Response<Vec<u8>>, CacheError>
request: http::Request<Vec<u8>>, {
) -> Result<Response<Vec<u8>>, CacheError> {
// Drop leading / // Drop leading /
let object_id = &request.uri().path()[1..]; let object_id = &request.uri().path()[1..];
@ -54,13 +48,13 @@ pub async fn fetch_object(
let data = match r.bytes().await { let data = match r.bytes().await {
Ok(data) => Vec::from(data), Ok(data) => Vec::from(data),
Err(e) => { Err(e) => {
warn!("Could not get data from cache object {object_id} with error {e}",); warn!(
"Could not get data from cache object {object_id} with error {e}",
);
Vec::new() Vec::new()
} }
}; };
let resp = resp_builder let resp = resp_builder.body(data).expect("Failed to build object cache response body");
.body(data)
.expect("Failed to build object cache response body");
if cache_result.map_or(true, |x| x.has_expired()) { if cache_result.map_or(true, |x| x.has_expired()) {
cache_object::<ObjectCache>(object_id, &resp.clone().try_into()?) cache_object::<ObjectCache>(object_id, &resp.clone().try_into()?)
.expect("Failed to create cached object"); .expect("Failed to create cached object");

View File

@ -1,10 +1,10 @@
pub mod auth; pub mod auth;
#[macro_use] #[macro_use]
pub mod cache; pub mod cache;
pub mod error;
pub mod fetch_object; pub mod fetch_object;
pub mod requests; pub mod requests;
pub mod server_proto; pub mod server_proto;
pub mod utils; pub mod utils;
pub mod error;
pub use auth::setup; pub use auth::setup;

View File

@ -1,4 +1,4 @@
use database::{DB, interface::DatabaseImpls}; use database::{interface::DatabaseImpls, DB};
use url::Url; use url::Url;
use crate::{ use crate::{

View File

@ -1,30 +1,26 @@
use std::str::FromStr; use std::str::FromStr;
use database::borrow_db_checked; use database::borrow_db_checked;
use http::{Request, Response, StatusCode, Uri, uri::PathAndQuery}; use http::{uri::PathAndQuery, Request, Response, StatusCode, Uri};
use log::{error, warn}; use log::{error, warn};
use tauri::UriSchemeResponder; use tauri::UriSchemeResponder;
use utils::webbrowser_open::webbrowser_open; use utils::webbrowser_open::webbrowser_open;
use crate::utils::DROP_CLIENT_SYNC; use crate::utils::DROP_CLIENT_SYNC;
pub async fn handle_server_proto_offline_wrapper( pub async fn handle_server_proto_offline_wrapper(request: Request<Vec<u8>>, responder: UriSchemeResponder) {
request: Request<Vec<u8>>,
responder: UriSchemeResponder,
) {
responder.respond(match handle_server_proto_offline(request).await { responder.respond(match handle_server_proto_offline(request).await {
Ok(res) => res, Ok(res) => res,
Err(_) => unreachable!(), Err(_) => unreachable!()
}); });
} }
pub async fn handle_server_proto_offline( pub async fn handle_server_proto_offline(_request: Request<Vec<u8>>) -> Result<Response<Vec<u8>>, StatusCode>{
_request: Request<Vec<u8>>,
) -> Result<Response<Vec<u8>>, StatusCode> {
Ok(Response::builder() Ok(Response::builder()
.status(StatusCode::NOT_FOUND) .status(StatusCode::NOT_FOUND)
.body(Vec::new()) .body(Vec::new())
.expect("Failed to build error response for proto offline")) .expect("Failed to build error response for proto offline"))
} }
pub async fn handle_server_proto_wrapper(request: Request<Vec<u8>>, responder: UriSchemeResponder) { pub async fn handle_server_proto_wrapper(request: Request<Vec<u8>>, responder: UriSchemeResponder) {
@ -32,12 +28,7 @@ pub async fn handle_server_proto_wrapper(request: Request<Vec<u8>>, responder: U
Ok(r) => responder.respond(r), Ok(r) => responder.respond(r),
Err(e) => { Err(e) => {
warn!("Cache error: {e}"); warn!("Cache error: {e}");
responder.respond( responder.respond(Response::builder().status(e).body(Vec::new()).expect("Failed to build error response"));
Response::builder()
.status(e)
.body(Vec::new())
.expect("Failed to build error response"),
);
} }
} }
} }
@ -48,25 +39,20 @@ async fn handle_server_proto(request: Request<Vec<u8>>) -> Result<Response<Vec<u
Some(auth) => auth, Some(auth) => auth,
None => { None => {
error!("Could not find auth in database"); error!("Could not find auth in database");
return Err(StatusCode::UNAUTHORIZED); return Err(StatusCode::UNAUTHORIZED)
} }
}; };
let web_token = match &auth.web_token { let web_token = match &auth.web_token {
Some(token) => token, Some(token) => token,
None => return Err(StatusCode::UNAUTHORIZED), None => return Err(StatusCode::UNAUTHORIZED),
}; };
let remote_uri = db_handle let remote_uri = db_handle.base_url.parse::<Uri>().expect("Failed to parse base url");
.base_url
.parse::<Uri>()
.expect("Failed to parse base url");
let path = request.uri().path(); let path = request.uri().path();
let mut new_uri = request.uri().clone().into_parts(); let mut new_uri = request.uri().clone().into_parts();
new_uri.path_and_query = Some( new_uri.path_and_query =
PathAndQuery::from_str(&format!("{path}?noWrapper=true")) Some(PathAndQuery::from_str(&format!("{path}?noWrapper=true")).expect("Failed to parse request path in proto"));
.expect("Failed to parse request path in proto"),
);
new_uri.authority = remote_uri.authority().cloned(); new_uri.authority = remote_uri.authority().cloned();
new_uri.scheme = remote_uri.scheme().cloned(); new_uri.scheme = remote_uri.scheme().cloned();
let err_msg = &format!("Failed to build new uri from parts {new_uri:?}"); let err_msg = &format!("Failed to build new uri from parts {new_uri:?}");
@ -76,7 +62,7 @@ async fn handle_server_proto(request: Request<Vec<u8>>) -> Result<Response<Vec<u
if whitelist_prefix.iter().all(|f| !path.starts_with(f)) { if whitelist_prefix.iter().all(|f| !path.starts_with(f)) {
webbrowser_open(new_uri.to_string()); webbrowser_open(new_uri.to_string());
return Ok(Response::new(Vec::new())); return Ok(Response::new(Vec::new()))
} }
let client = DROP_CLIENT_SYNC.clone(); let client = DROP_CLIENT_SYNC.clone();
@ -84,14 +70,13 @@ async fn handle_server_proto(request: Request<Vec<u8>>) -> Result<Response<Vec<u
.request(request.method().clone(), new_uri.to_string()) .request(request.method().clone(), new_uri.to_string())
.header("Authorization", format!("Bearer {web_token}")) .header("Authorization", format!("Bearer {web_token}"))
.headers(request.headers().clone()) .headers(request.headers().clone())
.send() .send() {
{ Ok(response) => response,
Ok(response) => response, Err(e) => {
Err(e) => { warn!("Could not send response. Got {e} when sending");
warn!("Could not send response. Got {e} when sending"); return Err(e.status().unwrap_or(StatusCode::BAD_REQUEST))
return Err(e.status().unwrap_or(StatusCode::BAD_REQUEST)); },
} };
};
let response_status = response.status(); let response_status = response.status();
let response_body = match response.bytes() { let response_body = match response.bytes() {

Some files were not shown because too many files have changed in this diff Show More