Compare commits

..

6 Commits

Author SHA1 Message Date
31f7d5bcfa Merge branch 'develop' into bigpicturemode 2025-10-14 17:23:52 +11:00
87bbe1da49 156 refactor into workspaces (#157)
* chore: Major refactoring

Still needs a massive go-over because there shouldn't be anything referencing tauri in any of the workspaces except the original one. Process manager has been refactored as an example

Signed-off-by: quexeky <git@quexeky.dev>

* fix: Remote tauri dependency from process

Signed-off-by: quexeky <git@quexeky.dev>

* refactor: Improvements to src-tauri

Signed-off-by: quexeky <git@quexeky.dev>

* refactor: Builds, but some logic still left to move back

Signed-off-by: quexeky <git@quexeky.dev>

* refactor: Finish refactor

Signed-off-by: quexeky <git@quexeky.dev>

* chore: Run cargo clippy && cargo fmt

Signed-off-by: quexeky <git@quexeky.dev>

* refactor: Move everything into src-tauri

Signed-off-by: quexeky <git@quexeky.dev>

---------

Signed-off-by: quexeky <git@quexeky.dev>
2025-10-14 17:12:51 +11:00
ab9e06f6c4 feat: improvements to jump calculator 2025-09-24 07:38:37 +10:00
dbf9c8e8e5 feat: prototype big picture mode 2025-09-23 18:05:35 +10:00
864640d6ae feat: finish big picture navigation 2025-09-23 16:37:25 +10:00
e29d5c8ead partial: mutationobserver 2025-09-23 15:38:30 +10:00
199 changed files with 16805 additions and 14879 deletions

2
.gitignore vendored
View File

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

View File

@ -7,14 +7,7 @@
</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,9 +2,7 @@
<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">
<NuxtLink to="/store">
<Wordmark class="h-8 mb-0.5" /> <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

View File

@ -76,7 +76,6 @@ 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="inline-flex items-center gap-x-2"> <div class="flex flex-col 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

@ -1,7 +0,0 @@
<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

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

View File

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

50
shared/app.vue Normal file
View File

@ -0,0 +1,50 @@
<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>

84
shared/assets/main.scss Normal file
View File

@ -0,0 +1,84 @@
@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,5 +1,5 @@
import { convertFileSrc } from "@tauri-apps/api/core"; import { convertFileSrc } from "@tauri-apps/api/core";
export const useObject = async (id: string) => { export const useObject = (id: string) => {
return convertFileSrc(id, "object"); return convertFileSrc(id, "object");
}; };

91
shared/error.vue Normal file
View File

@ -0,0 +1,91 @@
<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>

25
shared/nuxt.config.ts Normal file
View File

@ -0,0 +1,25 @@
// 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,
},
});

37
shared/package.json Normal file
View File

@ -0,0 +1,37 @@
{
"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"
}

20
shared/tailwind.config.js Normal file
View File

@ -0,0 +1,20 @@
/** @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')],
};

5
shared/tsconfig.json Normal file
View File

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

96
shared/types.ts Normal file
View File

@ -0,0 +1,96 @@
import type { Component } from "vue";
export type NavigationItem = {
prefix: string;
route: string;
label: string;
};
export type QuickActionNav = {
icon: Component;
notifications?: number;
action: () => Promise<void>;
};
export type User = {
id: string;
username: string;
admin: boolean;
displayName: string;
profilePictureObjectId: string;
};
export type AppState = {
status: AppStatus;
user?: User;
};
export type Game = {
id: string;
mName: string;
mShortDescription: string;
mDescription: string;
mIconObjectId: string;
mBannerObjectId: string;
mCoverObjectId: string;
mImageLibraryObjectIds: string[];
mImageCarouselObjectIds: string[];
};
export type Collection = {
id: string;
name: string;
isDefault: boolean;
entries: Array<{ gameId: string; game: Game }>;
};
export type GameVersion = {
launchCommandTemplate: string;
};
export enum AppStatus {
NotConfigured = "NotConfigured",
Offline = "Offline",
SignedOut = "SignedOut",
SignedIn = "SignedIn",
SignedInNeedsReauth = "SignedInNeedsReauth",
ServerUnavailable = "ServerUnavailable",
}
export enum GameStatusEnum {
Remote = "Remote",
Queued = "Queued",
Downloading = "Downloading",
Validating = "Validating",
Installed = "Installed",
Updating = "Updating",
Uninstalling = "Uninstalling",
SetupRequired = "SetupRequired",
Running = "Running",
PartiallyInstalled = "PartiallyInstalled",
}
export type GameStatus = {
type: GameStatusEnum;
version_name?: string;
install_dir?: string;
};
export enum DownloadableType {
Game = "Game",
Tool = "Tool",
DLC = "DLC",
Mod = "Mod",
}
export type DownloadableMetadata = {
id: string;
version: string;
downloadType: DownloadableType;
};
export type Settings = {
autostart: boolean;
maxDownloadThreads: number;
forceOffline: boolean;
};

8091
shared/yarn.lock Normal file

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

View File

@ -1,8 +1,148 @@
[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,48 +1,8 @@
use database::{borrow_db_checked, borrow_db_mut_checked}; use database::borrow_db_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

@ -0,0 +1,52 @@
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,3 +1,4 @@
pub mod autostart;
pub mod user;
pub mod app_status; pub mod app_status;
pub mod autostart;
pub mod compat;
pub mod user;

View File

@ -10,8 +10,3 @@ 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,6 +11,7 @@ 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::{db::DATA_ROOT_DIR, GameVersion}; use database::{GameVersion, db::DATA_ROOT_DIR};
use log::warn; use log::warn;
use crate::error::BackupError; use crate::error::BackupError;
@ -14,6 +14,12 @@ 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 {
@ -40,65 +46,188 @@ 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> { Ok(DATA_ROOT_DIR.join("games")) } fn root_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
fn game_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(PathBuf::from_str(&game.game_id).unwrap()) } Ok(DATA_ROOT_DIR.join("games"))
fn base_translate(&self, path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(self.root_translate(path, game)?.join(self.game_translate(path, game)?)) } }
fn home_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { let c = CommonPath::Home.get().ok_or(BackupError::NotFound); println!("{:?}", c); c } fn game_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> {
fn store_user_id_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { PathBuf::from_str(&game.game_id).map_err(|_| BackupError::ParseError) } Ok(PathBuf::from_str(&game.game_id).unwrap())
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 base_translate(&self, path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> {
fn win_local_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winLocalAppData>"); Err(BackupError::InvalidSystem) } Ok(self
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) } .root_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) } .join(self.game_translate(path, game)?))
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 home_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
fn win_dir_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winDir>"); Err(BackupError::InvalidSystem) } let c = CommonPath::Home.get().ok_or(BackupError::NotFound);
fn xdg_data_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected XDG Reference in Backup <xdgData>"); Err(BackupError::InvalidSystem) } println!("{:?}", c);
fn xdg_config_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected XDG Reference in Backup <xdgConfig>"); Err(BackupError::InvalidSystem) } c
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(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { fn xdg_config_translate(
Ok(CommonPath::Data.get().ok_or(BackupError::NotFound)?) &self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::Data.get().ok_or(BackupError::NotFound)
} }
fn xdg_data_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { fn xdg_data_translate(
Ok(CommonPath::Config.get().ok_or(BackupError::NotFound)?) &self,
_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(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { fn win_app_data_translate(
Ok(CommonPath::Config.get().ok_or(BackupError::NotFound)?) &self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::Config.get().ok_or(BackupError::NotFound)
} }
fn win_local_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { fn win_local_app_data_translate(
Ok(CommonPath::DataLocal.get().ok_or(BackupError::NotFound)?) &self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::DataLocal.get().ok_or(BackupError::NotFound)
} }
fn win_local_app_data_low_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { fn win_local_app_data_low_translate(
Ok(CommonPath::DataLocalLow.get().ok_or(BackupError::NotFound)?) &self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::DataLocalLow
.get()
.ok_or(BackupError::NotFound)
} }
fn win_dir_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { fn win_dir_translate(
&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(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { fn win_documents_translate(
Ok(CommonPath::Document.get().ok_or(BackupError::NotFound)?) &self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::Document.get().ok_or(BackupError::NotFound)
} }
fn win_program_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { fn win_program_data_translate(
&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(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { fn win_public_translate(
Ok(CommonPath::Public.get().ok_or(BackupError::NotFound)?) &self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::Public.get().ok_or(BackupError::NotFound)
} }
} }
pub struct MacBackupManager {} pub struct MacBackupManager {}

View File

@ -2,5 +2,6 @@ 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,5 +1,27 @@
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 backup_manager; pub mod placeholder;
pub mod error; pub mod resolver;

View File

@ -1,7 +1,6 @@
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 {
@ -16,15 +15,17 @@ 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(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] #[derive(
Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub enum Tag { pub enum Tag {
Config, Config,

View File

@ -5,7 +5,6 @@ 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('\\', "/");
@ -14,18 +13,25 @@ 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> = LazyLock::new(|| Regex::new(r"([^/*])\*{2,}").unwrap()); static UNNECESSARY_DOUBLE_STAR_1: LazyLock<Regex> =
static UNNECESSARY_DOUBLE_STAR_2: 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 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> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Roaming").unwrap()); static APP_DATA_ROAMING: LazyLock<Regex> =
static APP_DATA_LOCAL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%localappdata%").unwrap()); LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Roaming").unwrap());
static APP_DATA_LOCAL_2: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Local/").unwrap()); static APP_DATA_LOCAL: LazyLock<Regex> =
static USER_PROFILE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%").unwrap()); LazyLock::new(|| Regex::new(r"(?i)%localappdata%").unwrap());
static DOCUMENTS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/Documents").unwrap()); static APP_DATA_LOCAL_2: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Local/").unwrap());
static USER_PROFILE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)%userprofile%").unwrap());
static DOCUMENTS: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)%userprofile%/Documents").unwrap());
for (pattern, replacement) in [ for (pattern, replacement) in [
(&CONSECUTIVE_SLASHES, "/"), (&CONSECUTIVE_SLASHES, "/"),
@ -66,7 +72,9 @@ 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 {BASE, HOME, ROOT, STORE_USER_ID, WIN_APP_DATA, WIN_DIR, WIN_DOCUMENTS, XDG_CONFIG, XDG_DATA}; use {
BASE, HOME, ROOT, STORE_USER_ID, WIN_APP_DATA, WIN_DIR, WIN_DOCUMENTS, XDG_CONFIG, XDG_DATA,
};
let path_lower = path.to_lowercase(); let path_lower = path.to_lowercase();
@ -77,7 +85,9 @@ fn too_broad(path: &str) -> bool {
} }
for item in AVOID_WILDCARDS { for item in AVOID_WILDCARDS {
if path.starts_with(&format!("{}/*", item)) || path.starts_with(&format!("{}/{}", item, STORE_USER_ID)) { if path.starts_with(&format!("{}/*", item))
|| path.starts_with(&format!("{}/{}", item, STORE_USER_ID))
{
return true; return true;
} }
} }
@ -125,7 +135,6 @@ 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,17 +1,13 @@
use std::{ use std::{
fs::{self, create_dir_all, File}, fs::{self, File, create_dir_all},
io::{self, ErrorKind, Read, Write}, io::{self, Read, Write},
path::{Path, PathBuf}, path::{Path, PathBuf},
thread::sleep,
time::Duration,
}; };
use crate::error::BackupError; use crate::error::BackupError;
use super::{ use super::{backup_manager::BackupHandler, placeholder::*};
backup_manager::BackupHandler, conditions::Condition, metadata::GameFile, placeholder::*, use database::GameVersion;
};
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;
@ -30,7 +26,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()
{ {
@ -63,7 +59,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(serialized).unwrap(); file.write_all(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()
} }
@ -96,7 +92,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()
{ {
@ -115,7 +111,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 {:?}",
@ -132,23 +128,22 @@ 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::new( return Err(io::Error::other(
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),
)); ));
} }
@ -157,7 +152,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?;
@ -219,43 +214,3 @@ 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,7 +10,6 @@ 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)]
@ -32,16 +31,15 @@ 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) native_model::encode(val).map_err(|e| DeSerError::Internal(e.to_string()))
.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) = native_model::decode(buf) let (val, _version) =
.map_err(|e| DeSerError::Internal(e.to_string()))?; native_model::decode(buf).map_err(|e| DeSerError::Internal(e.to_string()))?;
Ok(val) Ok(val)
} }
} }

View File

@ -1,11 +1,20 @@
use std::{fs::{self, create_dir_all}, mem::ManuallyDrop, ops::{Deref, DerefMut}, path::PathBuf, sync::{RwLockReadGuard, RwLockWriteGuard}}; use std::{
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::{db::{DropDatabaseSerializer, DATA_ROOT_DIR, DB}, models::data::Database}; use crate::{
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,20 +2,13 @@
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,9 +191,7 @@ pub mod data {
use serde_with::serde_as; use serde_with::serde_as;
use super::{ use super::{Deserialize, Serialize, native_model, v1};
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)]
@ -282,7 +280,8 @@ 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: HashMap<v1::DownloadableMetadata, v1::ApplicationTransientStatus>, pub transient_statuses:
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 {
@ -303,10 +302,7 @@ pub mod data {
mod v3 { mod v3 {
use std::path::PathBuf; use std::path::PathBuf;
use super::{ use super::{Deserialize, Serialize, native_model, v1, v2};
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 {
@ -358,6 +354,20 @@ 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,6 +1,5 @@
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,11 +9,14 @@ use std::{
use database::DownloadableMetadata; use database::DownloadableMetadata;
use log::{debug, error, info, warn}; use log::{debug, error, info, warn};
use tauri::{AppHandle, Emitter}; use tauri::AppHandle;
use utils::{app_emit, lock, send}; use utils::{app_emit, lock, send};
use crate::{
use crate::{download_manager_frontend::DownloadStatus, error::ApplicationDownloadError, frontend_updates::{QueueUpdateEvent, QueueUpdateEventQueueData, StatsUpdateEvent}}; download_manager_frontend::DownloadStatus,
error::ApplicationDownloadError,
frontend_updates::{QueueUpdateEvent, QueueUpdateEventQueueData, StatsUpdateEvent},
};
use super::{ use super::{
download_manager_frontend::{DownloadManager, DownloadManagerSignal, DownloadManagerStatus}, download_manager_frontend::{DownloadManager, DownloadManagerSignal, DownloadManagerStatus},
@ -289,7 +292,10 @@ impl DownloadManagerBuilder {
if validate_result { if validate_result {
download_agent.on_complete(&app_handle); download_agent.on_complete(&app_handle);
send!(sender, DownloadManagerSignal::Completed(download_agent.metadata())); send!(
sender,
DownloadManagerSignal::Completed(download_agent.metadata())
);
send!(sender, DownloadManagerSignal::UpdateUIQueue); send!(sender, DownloadManagerSignal::UpdateUIQueue);
return; return;
} }
@ -370,7 +376,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();
@ -389,6 +395,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,7 +14,6 @@ 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::{
@ -80,6 +79,7 @@ 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,8 +124,11 @@ 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 = get_index_from_id(&mut queue, meta).expect("Failed to get meta index from id"); let current_index =
let to_move = queue.remove(current_index).expect("Failed to remove meta at index from queue"); 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");
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,7 +3,6 @@ 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,5 +1,9 @@
use std::{fmt::{Display, Formatter}, io, sync::{mpsc::SendError, Arc}}; use humansize::{BINARY, format_size};
use humansize::{format_size, BINARY}; use std::{
fmt::{Display, Formatter},
io,
sync::{Arc, mpsc::SendError},
};
use remote::error::RemoteAccessError; use remote::error::RemoteAccessError;
use serde_with::SerializeDisplay; use serde_with::SerializeDisplay;
@ -44,7 +48,9 @@ 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 => write!(f, "Download not initalized, did something go wrong?"), ApplicationDownloadError::NotInitialized => {
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.",
@ -60,10 +66,9 @@ 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) => write!( ApplicationDownloadError::DownloadError(error) => {
f, write!(f, "Download failed with error {error:?}")
"Download failed with error {error:?}" }
),
} }
} }
} }

View File

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

View File

@ -1,8 +1,44 @@
#![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::{
atomic::{AtomicBool, Ordering},
Arc, Arc,
atomic::{AtomicBool, Ordering},
}; };
#[derive(PartialEq, Eq, PartialOrd, Ord)] #[derive(PartialEq, Eq, PartialOrd, Ord)]
@ -22,7 +22,11 @@ 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 { DownloadThreadControlFlag::Go } else { DownloadThreadControlFlag::Stop } if value {
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)] #[derive(Clone, Debug)]
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,7 +117,9 @@ 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().duration_since(last_update_time).as_millis_f64(); let time_since_last_update = Instant::now()
.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();
@ -125,7 +127,8 @@ 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 = current_bytes_downloaded.saturating_sub(bytes_at_last_update) as f64; let bytes_since_last_update =
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)] #[derive(Clone, Debug)]
pub struct Queue { pub struct Queue {
inner: Arc<Mutex<VecDeque<DownloadableMetadata>>>, inner: Arc<Mutex<VecDeque<DownloadableMetadata>>>,
} }

View File

@ -3,11 +3,17 @@ use std::sync::{
atomic::{AtomicUsize, Ordering}, atomic::{AtomicUsize, Ordering},
}; };
#[derive(Clone)] #[derive(Clone, Debug)]
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,8 +1,13 @@
use database::{borrow_db_checked, borrow_db_mut_checked, ApplicationTransientStatus, DownloadType, DownloadableMetadata}; use database::{
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::{DownloadThreadControl, DownloadThreadControlFlag}; use download_manager::util::download_thread_control_flag::{
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;
@ -10,7 +15,6 @@ 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;
@ -18,12 +22,15 @@ 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, Emitter}; use tauri::AppHandle;
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::{DownloadBucket, DownloadContext, DownloadDrop, DropManifest, DropValidateContext, ManifestBody}; use crate::downloads::manifest::{
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};
@ -97,8 +104,7 @@ impl GameDownloadAgent {
result.ensure_manifest_exists().await?; result.ensure_manifest_exists().await?;
let required_space = lock!(result let required_space = lock!(result.manifest)
.manifest)
.as_ref() .as_ref()
.unwrap() .unwrap()
.values() .values()
@ -447,9 +453,13 @@ impl GameDownloadAgent {
let sender = self.sender.clone(); let sender = self.sender.clone();
let download_context = download_contexts let download_context =
.get(&bucket.version) download_contexts.get(&bucket.version).unwrap_or_else(|| {
.unwrap_or_else(|| panic!("Could not get bucket version {}. Corrupted state.", bucket.version)); panic!(
"Could not get bucket version {}. Corrupted state.",
bucket.version
)
});
scope.spawn(move |_| { scope.spawn(move |_| {
// 3 attempts // 3 attempts
@ -687,7 +697,10 @@ 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!(self.sender, DownloadManagerSignal::Error(ApplicationDownloadError::DownloadError(e))); send!(
self.sender,
DownloadManagerSignal::Error(ApplicationDownloadError::DownloadError(e))
);
} }
} }
} }

View File

@ -11,7 +11,9 @@ use std::{
}; };
use download_manager::error::ApplicationDownloadError; use download_manager::error::ApplicationDownloadError;
use download_manager::util::download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag}; use download_manager::util::download_thread_control_flag::{
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};
@ -47,7 +49,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.compute()) Ok(self.hasher.finalize())
} }
} }
// Write automatically pushes to file and hasher // Write automatically pushes to file and hasher
@ -116,7 +118,10 @@ 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.source.read(&mut copy_buffer[0..size]).inspect_err(|_| { let size = self
.source
.read(&mut copy_buffer[0..size])
.inspect_err(|_| {
info!("got error from {}", drop.filename); info!("got error from {}", drop.filename);
})?; })?;
remaining -= size; remaining -= size;

View File

@ -1,5 +1,8 @@
use std::{ use std::{
collections::HashMap, fs::File, io::{self, Read, Write}, path::{Path, PathBuf} collections::HashMap,
fs::File,
io::{self, Read, Write},
path::{Path, PathBuf},
}; };
use log::error; use log::error;
@ -77,7 +80,10 @@ 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.iter().map(|s| (s.0.clone(), s.1)).collect(); *lock!(self.contexts) = completed_contexts
.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,13 +9,21 @@ 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!(f, "{}", match self { write!(
f,
"{}",
match self {
LibraryError::MetaNotFound(id) => { LibraryError::MetaNotFound(id) => {
format!("Could not locate any installed version of game ID {id} in the database") format!(
"Could not locate any installed version of game ID {id} in the database"
)
} }
LibraryError::VersionNotFound(game_id) => { LibraryError::VersionNotFound(game_id) => {
format!("Could not locate any installed version for game id {game_id} in the database") 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 validate;
pub mod utils; pub mod utils;
pub mod validate;

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(io::Error::other( Err(ApplicationDownloadError::IoError(Arc::new(
"could not find disk of path", io::Error::other("could not find disk of path"),
)))) )))
} }

View File

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

View File

@ -3,4 +3,5 @@
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,15 +1,20 @@
use std::fs::remove_dir_all;
use std::sync::Mutex;
use std::thread::spawn;
use bitcode::{Decode, Encode}; use bitcode::{Decode, Encode};
use database::{borrow_db_checked, borrow_db_mut_checked, ApplicationTransientStatus, Database, DownloadableMetadata, GameDownloadStatus, GameVersion}; use database::{
ApplicationTransientStatus, Database, DownloadableMetadata, GameDownloadStatus, GameVersion,
borrow_db_checked, borrow_db_mut_checked,
};
use log::{debug, error, warn}; use log::{debug, error, warn};
use remote::{auth::generate_authorization_header, error::RemoteAccessError, requests::generate_url, utils::DROP_CLIENT_SYNC}; use remote::{
auth::generate_authorization_header, error::RemoteAccessError, requests::generate_url,
utils::DROP_CLIENT_SYNC,
};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fs::remove_dir_all;
use std::thread::spawn;
use tauri::AppHandle; use tauri::AppHandle;
use utils::app_emit; use utils::app_emit;
use crate::{downloads::error::LibraryError, state::{GameStatusManager, GameStatusWithTransient}}; use crate::state::{GameStatusManager, GameStatusWithTransient};
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct FetchGameStruct { pub struct FetchGameStruct {
@ -18,6 +23,16 @@ 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 {
@ -33,6 +48,11 @@ 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,
@ -157,7 +177,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 {
@ -273,41 +293,8 @@ pub struct FrontendGameOptions {
launch_string: String, launch_string: String,
} }
#[tauri::command] impl FrontendGameOptions {
pub fn update_game_configuration( pub fn launch_string(&self) -> &String {
game_id: String, &self.launch_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,16 +1,11 @@
use std::fs; use std::fs;
use database::{DownloadType, DownloadableMetadata, borrow_db_mut_checked};
use log::warn; use log::warn;
use crate::{ use crate::{
database::{ downloads::drop_data::{DROP_DATA_PATH, DropData},
db::borrow_db_mut_checked,
models::data::{DownloadType, DownloadableMetadata},
},
games::{
downloads::drop_data::{DropData, DROP_DATA_PATH},
library::set_partially_installed_db, library::set_partially_installed_db,
},
}; };
pub fn scan_install_dirs() { pub fn scan_install_dirs() {

View File

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

View File

Before

Width:  |  Height:  |  Size: 6.0 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

View File

Before

Width:  |  Height:  |  Size: 911 B

After

Width:  |  Height:  |  Size: 911 B

View File

Before

Width:  |  Height:  |  Size: 2.4 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

View File

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

View File

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

View File

Before

Width:  |  Height:  |  Size: 6.9 KiB

After

Width:  |  Height:  |  Size: 6.9 KiB

View File

Before

Width:  |  Height:  |  Size: 803 B

After

Width:  |  Height:  |  Size: 803 B

View File

Before

Width:  |  Height:  |  Size: 7.5 KiB

After

Width:  |  Height:  |  Size: 7.5 KiB

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

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