Merge branch 'feature/cloud-sync' into feature/game-achievements

# Conflicts:
#	src/main/services/achievements/achievement-watcher.ts
#	src/main/services/achievements/update-local-unlocked-achivements.ts
#	src/main/services/hydra-api.ts
This commit is contained in:
Zamitto 2024-10-21 15:31:26 -03:00
commit f2d66df34f
24 changed files with 288 additions and 255 deletions

View file

@ -1,6 +1,6 @@
import { Downloader } from "@shared";
export const VERSION_CODENAME = "Leviticus";
export const VERSION_CODENAME = "Skyscraper";
export const DOWNLOADER_NAME = {
[Downloader.RealDebrid]: "Real-Debrid",

View file

@ -1,4 +1,3 @@
import { gameBackupsTable } from "@renderer/dexie";
import { useToast } from "@renderer/hooks";
import { logger } from "@renderer/logger";
import type { LudusaviBackup, GameArtifact, GameShop } from "@types";
@ -7,7 +6,6 @@ import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { useTranslation } from "react-i18next";
@ -31,8 +29,10 @@ export interface CloudSyncContext {
deleteGameArtifact: (gameArtifactId: string) => Promise<void>;
setShowCloudSyncFilesModal: React.Dispatch<React.SetStateAction<boolean>>;
getGameBackupPreview: () => Promise<void>;
getGameArtifacts: () => Promise<void>;
restoringBackup: boolean;
uploadingBackup: boolean;
loadingPreview: boolean;
}
export const cloudSyncContext = createContext<CloudSyncContext>({
@ -47,8 +47,10 @@ export const cloudSyncContext = createContext<CloudSyncContext>({
showCloudSyncFilesModal: false,
setShowCloudSyncFilesModal: () => {},
getGameBackupPreview: async () => {},
getGameArtifacts: async () => {},
restoringBackup: false,
uploadingBackup: false,
loadingPreview: false,
});
const { Provider } = cloudSyncContext;
@ -67,8 +69,6 @@ export function CloudSyncContextProvider({
}: CloudSyncContextProviderProps) {
const { t } = useTranslation("game_details");
const backupPreviewLock = useRef("");
const [artifacts, setArtifacts] = useState<GameArtifact[]>([]);
const [showCloudSyncModal, setShowCloudSyncModal] = useState(false);
const [backupPreview, setBackupPreview] = useState<LudusaviBackup | null>(
@ -77,6 +77,7 @@ export function CloudSyncContextProvider({
const [restoringBackup, setRestoringBackup] = useState(false);
const [uploadingBackup, setUploadingBackup] = useState(false);
const [showCloudSyncFilesModal, setShowCloudSyncFilesModal] = useState(false);
const [loadingPreview, setLoadingPreview] = useState(false);
const { showSuccessToast } = useToast();
@ -88,32 +89,25 @@ export function CloudSyncContextProvider({
[objectId, shop]
);
const getGameBackupPreview = useCallback(async () => {
const backupPreviewLockKey = `${objectId}-${shop}`;
const getGameArtifacts = useCallback(async () => {
const results = await window.electron.getGameArtifacts(objectId, shop);
setArtifacts(results);
}, [objectId, shop]);
if (backupPreviewLock.current !== backupPreviewLockKey) {
backupPreviewLock.current = backupPreviewLockKey;
await Promise.allSettled([
window.electron.getGameArtifacts(objectId, shop).then((results) => {
setArtifacts(results);
}),
window.electron
.getGameBackupPreview(objectId, shop)
.then((preview) => {
backupPreviewLock.current = "";
if (preview && Object.keys(preview.games).length) {
setBackupPreview(preview);
}
})
.catch((err) => {
logger.error(
"Failed to get game backup preview",
objectId,
shop,
err
);
}),
]);
const getGameBackupPreview = useCallback(async () => {
setLoadingPreview(true);
try {
const preview = await window.electron.getGameBackupPreview(
objectId,
shop
);
setBackupPreview(preview);
} catch (err) {
logger.error("Failed to get game backup preview", objectId, shop, err);
} finally {
setLoadingPreview(false);
}
}, [objectId, shop]);
@ -131,14 +125,8 @@ export function CloudSyncContextProvider({
shop,
() => {
showSuccessToast(t("backup_uploaded"));
setUploadingBackup(false);
gameBackupsTable.add({
objectId,
shop,
createdAt: new Date(),
});
getGameArtifacts();
getGameBackupPreview();
}
);
@ -148,6 +136,7 @@ export function CloudSyncContextProvider({
showSuccessToast(t("backup_restored"));
setRestoringBackup(false);
getGameArtifacts();
getGameBackupPreview();
});
@ -155,15 +144,23 @@ export function CloudSyncContextProvider({
removeUploadCompleteListener();
removeDownloadCompleteListener();
};
}, [objectId, shop, showSuccessToast, t, getGameBackupPreview]);
}, [
objectId,
shop,
showSuccessToast,
t,
getGameBackupPreview,
getGameArtifacts,
]);
const deleteGameArtifact = useCallback(
async (gameArtifactId: string) => {
return window.electron.deleteGameArtifact(gameArtifactId).then(() => {
getGameBackupPreview();
getGameArtifacts();
});
},
[getGameBackupPreview]
[getGameBackupPreview, getGameArtifacts]
);
useEffect(() => {
@ -194,12 +191,14 @@ export function CloudSyncContextProvider({
restoringBackup,
uploadingBackup,
showCloudSyncFilesModal,
loadingPreview,
setShowCloudSyncModal,
uploadSaveGame,
downloadGameArtifact,
deleteGameArtifact,
setShowCloudSyncFilesModal,
getGameBackupPreview,
getGameArtifacts,
}}
>
{children}

View file

@ -170,6 +170,7 @@ declare global {
showOpenDialog: (
options: Electron.OpenDialogOptions
) => Promise<Electron.OpenDialogReturnValue>;
showItemInFolder: (path: string) => Promise<void>;
platform: NodeJS.Platform;
/* Auto update */

View file

@ -1,13 +1,6 @@
import type { GameShop, HowLongToBeatCategory } from "@types";
import { Dexie } from "dexie";
export interface GameBackup {
id?: number;
shop: GameShop;
objectId: string;
createdAt: Date;
}
export interface HowLongToBeatEntry {
id?: number;
objectId: string;
@ -22,13 +15,11 @@ export const db = new Dexie("Hydra");
db.version(4).stores({
repacks: `++id, title, uris, fileSize, uploadDate, downloadSourceId, repacker, createdAt, updatedAt`,
downloadSources: `++id, url, name, etag, downloadCount, status, createdAt, updatedAt`,
gameBackups: `++id, [shop+objectId], createdAt`,
howLongToBeatEntries: `++id, categories, [shop+objectId], createdAt, updatedAt`,
});
export const downloadSourcesTable = db.table("downloadSources");
export const repacksTable = db.table("repacks");
export const gameBackupsTable = db.table<GameBackup>("gameBackups");
export const howLongToBeatEntriesTable = db.table<HowLongToBeatEntry>(
"howLongToBeatEntries"
);

View file

@ -14,7 +14,6 @@ import type {
UserDetails,
} from "@types";
import { UserFriendModalTab } from "@renderer/pages/shared-modals/user-friend-modal";
import { gameBackupsTable } from "@renderer/dexie";
export function useUserDetails() {
const dispatch = useAppDispatch();
@ -33,7 +32,6 @@ export function useUserDetails() {
dispatch(setUserDetails(null));
dispatch(setProfileBackground(null));
await gameBackupsTable.clear();
window.localStorage.removeItem("userDetails");
}, [dispatch]);
@ -130,7 +128,7 @@ export function useUserDetails() {
const unblockUser = (userId: string) => window.electron.unblockUser(userId);
const hasActiveSubscription = useMemo(() => {
if (!userDetails?.subscription) {
if (!userDetails?.subscription?.plan) {
return false;
}

View file

@ -1,26 +1,9 @@
import { style } from "@vanilla-extract/css";
import { SPACING_UNIT, vars } from "../../../theme.css";
import { SPACING_UNIT } from "../../../theme.css";
export const artifacts = style({
display: "flex",
export const mappingMethods = style({
display: "grid",
gap: `${SPACING_UNIT}px`,
flexDirection: "column",
listStyle: "none",
margin: "0",
padding: "0",
});
export const artifactButton = style({
display: "flex",
textAlign: "left",
flexDirection: "row",
alignItems: "center",
gap: `${SPACING_UNIT}px`,
color: vars.color.body,
padding: `${SPACING_UNIT * 2}px`,
backgroundColor: vars.color.darkBackground,
border: `1px solid ${vars.color.border}`,
borderRadius: "4px",
justifyContent: "space-between",
gridTemplateColumns: "repeat(2, 1fr)",
});

View file

@ -1,18 +1,34 @@
import { Modal, ModalProps } from "@renderer/components";
import { useContext, useMemo } from "react";
import { Button, Modal, ModalProps } from "@renderer/components";
import { useContext, useMemo, useState } from "react";
import { cloudSyncContext } from "@renderer/context";
// import { useTranslation } from "react-i18next";
import { useTranslation } from "react-i18next";
import { CheckCircleFillIcon } from "@primer/octicons-react";
import * as styles from "./cloud-sync-files-modal.css";
import { formatBytes } from "@shared";
import { vars } from "@renderer/theme.css";
// import { useToast } from "@renderer/hooks";
export interface CloudSyncFilesModalProps
extends Omit<ModalProps, "children" | "title"> {}
export enum FileMappingMethod {
Automatic = "AUTOMATIC",
Manual = "MANUAL",
}
export function CloudSyncFilesModal({
visible,
onClose,
}: CloudSyncFilesModalProps) {
const [selectedFileMappingMethod, setSelectedFileMappingMethod] =
useState<FileMappingMethod>(FileMappingMethod.Automatic);
const { backupPreview } = useContext(cloudSyncContext);
// const { gameTitle } = useContext(gameDetailsContext);
// const { t } = useTranslation("game_details");
const { t } = useTranslation("game_details");
// const { showSuccessToast } = useToast();
const files = useMemo(() => {
if (!backupPreview) {
@ -20,6 +36,7 @@ export function CloudSyncFilesModal({
}
const [game] = Object.values(backupPreview.games);
if (!game) return [];
const entries = Object.entries(game.files);
return entries.map(([key, value]) => {
@ -27,6 +44,19 @@ export function CloudSyncFilesModal({
});
}, [backupPreview]);
// const handleAddCustomPathClick = useCallback(async () => {
// const { filePaths } = await window.electron.showOpenDialog({
// properties: ["openDirectory"],
// });
// if (filePaths && filePaths.length > 0) {
// const path = filePaths[0];
// await window.electron.selectGameBackupDirectory(gameTitle, path);
// showSuccessToast("custom_backup_location_set");
// getGameBackupPreview();
// }
// }, [gameTitle, showSuccessToast, getGameBackupPreview]);
return (
<Modal
visible={visible}
@ -34,61 +64,80 @@ export function CloudSyncFilesModal({
description="Escolha quais diretórios serão sincronizados"
onClose={onClose}
>
{/* <div>
{["AUTOMATIC", "CUSTOM"].map((downloader) => (
<Button
key={downloader}
// className={styles.downloaderOption}
theme={selectedDownloader === downloader ? "primary" : "outline"}
disabled={
downloader === Downloader.RealDebrid &&
!userPreferences?.realDebridApiToken
}
onClick={() => setSelectedDownloader(downloader)}
>
{selectedDownloader === downloader && (
<CheckCircleFillIcon className={styles.downloaderIcon} />
)}
{DOWNLOADER_NAME[downloader]}
</Button>
))}
</div> */}
<div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
<span>{t("mapping_method_label")}</span>
{/* <TextField
// value={game.executablePath || ""}
readOnly
theme="dark"
disabled
placeholder={t("no_directory_selected")}
rightContent={
<Button
type="button"
theme="outline"
onClick={handleChangeExecutableLocation}
>
{t("select_directory")}
</Button>
}
/> */}
<table>
<thead>
<tr>
<th style={{ textAlign: "left" }}>Arquivo</th>
<th style={{ textAlign: "left" }}>Hash</th>
<th style={{ textAlign: "left" }}>Tamanho</th>
</tr>
</thead>
<tbody>
{files.map((file) => (
<tr key={file.path}>
<td style={{ textAlign: "left" }}>{file.path}</td>
<td style={{ textAlign: "left" }}>{file.change}</td>
<td style={{ textAlign: "left" }}>{file.path}</td>
</tr>
<div className={styles.mappingMethods}>
{Object.values(FileMappingMethod).map((mappingMethod) => (
<Button
key={mappingMethod}
theme={
selectedFileMappingMethod === mappingMethod
? "primary"
: "outline"
}
onClick={() => setSelectedFileMappingMethod(mappingMethod)}
disabled={mappingMethod === FileMappingMethod.Manual}
>
{selectedFileMappingMethod === mappingMethod && (
<CheckCircleFillIcon />
)}
{t(`mapping_method_${mappingMethod.toLowerCase()}`)}
</Button>
))}
</tbody>
</table>
</div>
</div>
<div style={{ marginTop: 16 }}>
{/* <TextField
readOnly
theme="dark"
disabled
placeholder={t("select_folder")}
rightContent={
<Button
type="button"
theme="outline"
onClick={handleAddCustomPathClick}
>
<FileDirectoryIcon />
{t("select_executable")}
</Button>
}
/> */}
<p>{t("files_automatically_mapped")}</p>
<ul
style={{
listStyle: "none",
margin: 0,
padding: 0,
display: "flex",
flexDirection: "column",
gap: 8,
marginTop: 16,
}}
>
{files.map((file) => (
<li key={file.path} style={{ display: "flex" }}>
<button
style={{
flex: 1,
color: vars.color.muted,
textDecoration: "underline",
display: "flex",
cursor: "pointer",
}}
onClick={() => window.electron.showItemInFolder(file.path)}
>
{file.path.split("/").at(-1)}
</button>
<p>{formatBytes(file.bytes)}</p>
</li>
))}
</ul>
</div>
</Modal>
);
}

View file

@ -49,3 +49,17 @@ export const progress = style({
backgroundColor: vars.color.muted,
},
});
export const manageFilesButton = style({
margin: "0",
padding: "0",
alignSelf: "flex-start",
fontSize: 14,
cursor: "pointer",
textDecoration: "underline",
color: vars.color.body,
":disabled": {
cursor: "not-allowed",
opacity: vars.opacity.disabled,
},
});

View file

@ -6,7 +6,6 @@ import * as styles from "./cloud-sync-modal.css";
import { formatBytes } from "@shared";
import { format } from "date-fns";
import {
CheckCircleFillIcon,
ClockIcon,
DeviceDesktopIcon,
HistoryIcon,
@ -16,18 +15,16 @@ import {
UploadIcon,
} from "@primer/octicons-react";
import { useToast } from "@renderer/hooks";
import { GameBackup, gameBackupsTable } from "@renderer/dexie";
import { useTranslation } from "react-i18next";
import { AxiosProgressEvent } from "axios";
import { formatDownloadProgress } from "@renderer/helpers";
import { SPACING_UNIT, vars } from "@renderer/theme.css";
import { SPACING_UNIT } from "@renderer/theme.css";
export interface CloudSyncModalProps
extends Omit<ModalProps, "children" | "title"> {}
export function CloudSyncModal({ visible, onClose }: CloudSyncModalProps) {
const [deletingArtifact, setDeletingArtifact] = useState(false);
const [lastBackup, setLastBackup] = useState<GameBackup | null>(null);
const [backupDownloadProgress, setBackupDownloadProgress] =
useState<AxiosProgressEvent | null>(null);
@ -38,6 +35,7 @@ export function CloudSyncModal({ visible, onClose }: CloudSyncModalProps) {
backupPreview,
uploadingBackup,
restoringBackup,
loadingPreview,
uploadSaveGame,
downloadGameArtifact,
deleteGameArtifact,
@ -64,11 +62,6 @@ export function CloudSyncModal({ visible, onClose }: CloudSyncModalProps) {
};
useEffect(() => {
gameBackupsTable
.where({ shop: shop, objectId })
.last()
.then((lastBackup) => setLastBackup(lastBackup || null));
const removeBackupDownloadProgressListener =
window.electron.onBackupDownloadProgress(
objectId!,
@ -111,20 +104,19 @@ export function CloudSyncModal({ visible, onClose }: CloudSyncModalProps) {
);
}
if (lastBackup) {
if (loadingPreview) {
return (
<span style={{ display: "flex", alignItems: "center", gap: 8 }}>
<i style={{ color: vars.color.success }}>
<CheckCircleFillIcon />
</i>
{t("last_backup_date", {
date: format(lastBackup.createdAt, "dd/MM/yyyy HH:mm"),
})}
<SyncIcon className={styles.syncIcon} />
{t("loading_save_preview")}
</span>
);
}
if (artifacts.length >= 2) {
return t("max_number_of_artifacts_reached");
}
if (!backupPreview) {
return t("no_backup_preview");
}
@ -133,93 +125,76 @@ export function CloudSyncModal({ visible, onClose }: CloudSyncModalProps) {
}, [
uploadingBackup,
backupDownloadProgress?.progress,
lastBackup,
backupPreview,
restoringBackup,
loadingPreview,
artifacts,
t,
]);
const disableActions = uploadingBackup || restoringBackup || deletingArtifact;
return (
<>
{/* <ConfirmationModal
confirmButtonLabel="confirm"
cancelButtonLabel="cancel"
descriptionText="description"
title="title"
onConfirm={() => {}}
onClose={() => {}}
visible
/> */}
<Modal
visible={visible}
title={t("cloud_save")}
description={t("cloud_save_description")}
onClose={onClose}
large
<Modal
visible={visible}
title={t("cloud_save")}
description={t("cloud_save_description")}
onClose={onClose}
large
>
<div
style={{
marginBottom: 24,
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<div style={{ display: "flex", gap: 4, flexDirection: "column" }}>
<h2>{gameTitle}</h2>
<p>{backupStateLabel}</p>
<button
type="button"
className={styles.manageFilesButton}
onClick={() => setShowCloudSyncFilesModal(true)}
disabled={disableActions || !backupPreview?.overall.totalGames}
>
{t("manage_files")}
</button>
</div>
<Button
type="button"
onClick={() => uploadSaveGame(lastDownloadedOption?.title ?? null)}
disabled={
disableActions ||
!backupPreview?.overall.totalGames ||
artifacts.length >= 2
}
>
<UploadIcon />
{t("create_backup")}
</Button>
</div>
<div style={{ display: "flex", justifyContent: "space-between" }}>
<div
style={{
marginBottom: 24,
marginBottom: 16,
display: "flex",
justifyContent: "space-between",
alignItems: "center",
gap: SPACING_UNIT,
}}
>
<div style={{ display: "flex", gap: 4, flexDirection: "column" }}>
<h2>{gameTitle}</h2>
<p>{backupStateLabel}</p>
<button
type="button"
style={{
margin: 0,
padding: 0,
alignSelf: "flex-start",
fontSize: 14,
cursor: "pointer",
textDecoration: "underline",
color: vars.color.body,
}}
onClick={() => setShowCloudSyncFilesModal(true)}
>
Gerenciar arquivos
</button>
</div>
<Button
type="button"
onClick={() => uploadSaveGame(lastDownloadedOption?.title ?? null)}
disabled={disableActions || !backupPreview}
>
<UploadIcon />
{t("create_backup")}
</Button>
</div>
<div style={{ display: "flex", justifyContent: "space-between" }}>
<div
style={{
marginBottom: 16,
display: "flex",
alignItems: "center",
gap: SPACING_UNIT,
}}
>
<h2>{t("backups")}</h2>
<small>{artifacts.length} / 2</small>
</div>
<div style={{ display: "flex", flexDirection: "column" }}>
<small>Espaço usado</small>
<progress className={styles.progress} />
</div>
<h2>{t("backups")}</h2>
<small>{artifacts.length} / 2</small>
</div>
</div>
{artifacts.length > 0 ? (
<ul className={styles.artifacts}>
{artifacts.map((artifact) => (
{artifacts.map((artifact, index) => (
<li key={artifact.id} className={styles.artifactButton}>
<div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
<div
@ -230,7 +205,7 @@ export function CloudSyncModal({ visible, onClose }: CloudSyncModalProps) {
marginBottom: 4,
}}
>
<h3>Backup do dia {format(artifact.createdAt, "dd/MM")}</h3>
<h3>{t("backup_title", { number: index + 1 })}</h3>
<small>{formatBytes(artifact.artifactLengthInBytes)}</small>
</div>
@ -272,7 +247,9 @@ export function CloudSyncModal({ visible, onClose }: CloudSyncModalProps) {
</li>
))}
</ul>
</Modal>
</>
) : (
<p>{t("no_backups_created")}</p>
)}
</Modal>
);
}

View file

@ -36,7 +36,7 @@ export function GameDetailsContent() {
const { userDetails, hasActiveSubscription } = useUserDetails();
const { setShowCloudSyncModal, getGameBackupPreview } =
const { setShowCloudSyncModal, getGameBackupPreview, getGameArtifacts } =
useContext(cloudSyncContext);
const aboutTheGame = useMemo(() => {
@ -113,7 +113,8 @@ export function GameDetailsContent() {
useEffect(() => {
getGameBackupPreview();
}, [getGameBackupPreview]);
getGameArtifacts();
}, [getGameBackupPreview, getGameArtifacts]);
return (
<div className={styles.wrapper({ blurredContent: hasNSFWContentBlocked })}>

View file

@ -34,6 +34,7 @@ export default function Home() {
>({
[CatalogueCategory.Hot]: [],
[CatalogueCategory.Weekly]: [],
[CatalogueCategory.Achievements]: [],
});
const getCatalogue = useCallback((category: CatalogueCategory) => {

View file

@ -52,8 +52,7 @@ export const profileDisplayName = style({
display: "flex",
alignItems: "center",
position: "relative",
textShadow:
"0 0 40px rgb(0 0 0), 0 0 20px rgb(0 0 0 / 50%), 0 0 10px rgb(0 0 0 / 20%)",
textShadow: "0 0 5px rgb(0 0 0 / 40%)",
});
export const heroPanel = style({

View file

@ -5,11 +5,14 @@ import { userProfileContext } from "@renderer/context";
import * as styles from "./upload-background-image-button.css";
import { useToast, useUserDetails } from "@renderer/hooks";
import { useTranslation } from "react-i18next";
export function UploadBackgroundImageButton() {
const [isUploadingBackgroundImage, setIsUploadingBackgorundImage] =
useState(false);
const { hasActiveSubscription } = useUserDetails();
const { userDetails } = useUserDetails();
const { t } = useTranslation("user_profile");
const { isMe, setSelectedBackgroundImage } = useContext(userProfileContext);
const { patchUser, fetchUserDetails } = useUserDetails();
@ -44,7 +47,8 @@ export function UploadBackgroundImageButton() {
}
};
if (!isMe || !hasActiveSubscription) return null;
if (!isMe || !userDetails?.subscription) return null;
if (userDetails.subscription.plan.name !== "plus") return null;
return (
<Button
@ -54,7 +58,7 @@ export function UploadBackgroundImageButton() {
disabled={isUploadingBackgroundImage}
>
<UploadIcon />
{isUploadingBackgroundImage ? "Uploading..." : "Upload background"}
{isUploadingBackgroundImage ? t("uploading_banner") : t("upload_banner")}
</Button>
);
}