feat: adding new messages to hero panel

This commit is contained in:
Chubby Granny Chaser 2024-05-24 00:26:21 +01:00
parent a240c3ae24
commit d431c01d1b
No known key found for this signature in database
28 changed files with 398 additions and 358 deletions

View File

@ -3,9 +3,10 @@ productName: Hydra
directories:
buildResources: build
extraResources:
- aria2
- seeds
- hydra.db
- fastlist.exe
- seeds
files:
- "!**/.vscode/*"
- "!src/*"

View File

@ -50,7 +50,6 @@
"color": "^4.2.3",
"color.js": "^1.2.0",
"date-fns": "^3.6.0",
"easydl": "^1.1.1",
"electron-updater": "^6.1.8",
"fetch-cookie": "^3.0.1",
"flexsearch": "^0.7.43",
@ -59,7 +58,6 @@
"jsdom": "^24.0.0",
"lodash-es": "^4.17.21",
"lottie-react": "^2.4.0",
"node-7z-archive": "^1.1.7",
"parse-torrent": "^11.0.16",
"ps-list": "^8.1.1",
"react-i18next": "^14.1.0",

View File

@ -1,4 +1,41 @@
const fs = require("fs");
const { default: axios } = require("axios");
const util = require("node:util");
const fs = require("node:fs");
const exec = util.promisify(require("node:child_process").exec);
const downloadAria2 = async () => {
if (fs.existsSync("aria2")) {
console.log("Aria2 already exists, skipping download...");
return;
}
const file =
process.platform === "win32"
? "aria2-1.37.0-win-64bit-build1.zip"
: "aria2-1.37.0-aarch64-linux-android-build1.zip";
console.log(`Downloading ${file}...`);
const response = await axios.get(
`https://github.com/aria2/aria2/releases/download/release-1.37.0/${file}`,
{ responseType: "stream" }
);
const stream = response.data.pipe(fs.createWriteStream(file));
stream.on("finish", async () => {
console.log(`Downloaded ${file}, extracting...`);
await exec(`npx extract-zip ${file}`);
console.log("Extracted. Renaming folder...");
fs.renameSync(file.replace(".zip", ""), "aria2");
console.log(`Extracted ${file}, removing zip file...`);
fs.rmSync(file);
});
};
if (process.platform === "win32") {
fs.copyFileSync(
@ -6,3 +43,5 @@ if (process.platform === "win32") {
"fastlist.exe"
);
}
downloadAria2();

View File

@ -10,7 +10,7 @@ const addGameToLibrary = async (
_event: Electron.IpcMainInvokeEvent,
objectID: string,
title: string,
gameShop: GameShop,
shop: GameShop,
executablePath: string | null
) => {
return gameRepository
@ -19,7 +19,7 @@ const addGameToLibrary = async (
objectID,
},
{
shop: gameShop,
shop,
status: null,
executablePath,
isDeleted: false,
@ -40,7 +40,7 @@ const addGameToLibrary = async (
title,
iconUrl,
objectID,
shop: gameShop,
shop,
executablePath,
})
.then(() => {

View File

@ -1,33 +1,18 @@
import {
gameRepository,
repackRepository,
userPreferencesRepository,
} from "@main/repository";
import { gameRepository, repackRepository } from "@main/repository";
import { registerEvent } from "../register-event";
import type { GameShop } from "@types";
import type { StartGameDownloadPayload } from "@types";
import { getFileBase64, getSteamAppAsset } from "@main/helpers";
import { DownloadManager } from "@main/services";
import { Downloader } from "@shared";
import { stateManager } from "@main/state-manager";
import { Not } from "typeorm";
const startGameDownload = async (
_event: Electron.IpcMainInvokeEvent,
repackId: number,
objectID: string,
title: string,
gameShop: GameShop,
downloadPath: string
payload: StartGameDownloadPayload
) => {
const userPreferences = await userPreferencesRepository.findOne({
where: { id: 1 },
});
const downloader = userPreferences?.realDebridApiToken
? Downloader.RealDebrid
: Downloader.Torrent;
const { repackId, objectID, title, shop, downloadPath, downloader } = payload;
const [game, repack] = await Promise.all([
gameRepository.findOne({
@ -83,7 +68,7 @@ const startGameDownload = async (
iconUrl,
objectID,
downloader,
shop: gameShop,
shop,
status: "active",
downloadPath,
repack: { id: repackId },

View File

@ -5,8 +5,8 @@ import {
getNewRepacksFromUser,
getNewRepacksFromXatab,
getNewRepacksFromOnlineFix,
startProcessWatcher,
DownloadManager,
startMainLoop,
} from "./services";
import {
gameRepository,
@ -23,7 +23,7 @@ import { orderBy } from "lodash-es";
import { SteamGame } from "@types";
import { Not } from "typeorm";
startProcessWatcher();
startMainLoop();
const track1337xUsers = async (existingRepacks: Repack[]) => {
for (const repacker of repackersOn1337x) {
@ -88,8 +88,6 @@ const loadState = async (userPreferences: UserPreferences | null) => {
if (userPreferences?.realDebridApiToken)
await RealDebridClient.authorize(userPreferences?.realDebridApiToken);
await DownloadManager.connect();
const game = await gameRepository.findOne({
where: {
status: "active",
@ -99,9 +97,7 @@ const loadState = async (userPreferences: UserPreferences | null) => {
relations: { repack: true },
});
if (game) {
DownloadManager.startDownload(game.id);
}
if (game) DownloadManager.startDownload(game.id);
};
userPreferencesRepository

View File

@ -6,7 +6,7 @@ import { gameRepository, userPreferencesRepository } from "@main/repository";
import path from "node:path";
import { WindowManager } from "./window-manager";
import { RealDebridClient } from "./real-debrid";
import { Notification } from "electron";
import { Notification, app } from "electron";
import { t } from "i18next";
import { Downloader } from "@shared";
import { DownloadProgress } from "@types";
@ -16,33 +16,36 @@ import { Game } from "@main/entity";
export class DownloadManager {
private static downloads = new Map<number, string>();
private static connected = false;
private static gid: string | null = null;
private static gameId: number | null = null;
private static aria2 = new Aria2({});
static async connect() {
const binary = path.join(
__dirname,
"..",
"..",
"aria2-1.37.0-win-64bit-build1",
"aria2c"
);
private static connect(): Promise<boolean> {
return new Promise((resolve) => {
const binaryPath = app.isPackaged
? path.join(process.resourcesPath, "aria2", "aria2c")
: path.join(__dirname, "..", "..", "aria2", "aria2c");
spawn(
binary,
[
const cp = spawn(binaryPath, [
"--enable-rpc",
"--rpc-listen-all",
"--file-allocation=none",
"--allow-overwrite=true",
],
{ stdio: "inherit" }
);
]);
await this.aria2.open();
this.attachListener();
cp.stdout.on("data", async (data) => {
const msg = Buffer.from(data).toString("utf-8");
if (msg.includes("IPv6 RPC: listening on TCP")) {
await this.aria2.open();
this.connected = true;
resolve(true);
}
});
});
}
private static getETA(status: StatusResponse) {
@ -84,91 +87,78 @@ export class DownloadManager {
return "";
}
private static async attachListener() {
// eslint-disable-next-line no-constant-condition
while (true) {
try {
if (!this.gid || !this.gameId) {
continue;
public static async watchDownloads() {
if (!this.gid || !this.gameId) return;
const status = await this.aria2.call("tellStatus", this.gid);
const downloadingMetadata = status.bittorrent && !status.bittorrent?.info;
if (status.followedBy?.length) {
this.gid = status.followedBy[0];
this.downloads.set(this.gameId, this.gid);
return;
}
const progress =
Number(status.completedLength) / Number(status.totalLength);
if (!downloadingMetadata) {
const update: QueryDeepPartialEntity<Game> = {
bytesDownloaded: Number(status.completedLength),
fileSize: Number(status.totalLength),
status: status.status,
};
if (!isNaN(progress)) update.progress = progress;
await gameRepository.update(
{ id: this.gameId },
{
...update,
status: status.status,
folderName: this.getFolderName(status),
}
);
}
const status = await this.aria2.call("tellStatus", this.gid);
const game = await gameRepository.findOne({
where: { id: this.gameId, isDeleted: false },
relations: { repack: true },
});
const downloadingMetadata =
status.bittorrent && !status.bittorrent?.info;
if (status.followedBy?.length) {
this.gid = status.followedBy[0];
this.downloads.set(this.gameId, this.gid);
continue;
}
const progress =
Number(status.completedLength) / Number(status.totalLength);
if (!downloadingMetadata) {
const update: QueryDeepPartialEntity<Game> = {
bytesDownloaded: Number(status.completedLength),
fileSize: Number(status.totalLength),
status: status.status,
};
if (!isNaN(progress)) update.progress = progress;
await gameRepository.update(
{ id: this.gameId },
{
...update,
status: status.status,
folderName: this.getFolderName(status),
}
);
}
const game = await gameRepository.findOne({
where: { id: this.gameId, isDeleted: false },
relations: { repack: true },
});
if (progress === 1 && game && !downloadingMetadata) {
await this.publishNotification();
/*
Only cancel bittorrent downloads to stop seeding
*/
if (status.bittorrent) {
await this.cancelDownload(game.id);
} else {
this.clearCurrentDownload();
}
}
if (WindowManager.mainWindow && game) {
WindowManager.mainWindow.setProgressBar(
progress === 1 || downloadingMetadata ? -1 : progress,
{ mode: downloadingMetadata ? "indeterminate" : "normal" }
);
const payload = {
progress,
bytesDownloaded: Number(status.completedLength),
fileSize: Number(status.totalLength),
numPeers: Number(status.connections),
numSeeds: Number(status.numSeeders ?? 0),
downloadSpeed: Number(status.downloadSpeed),
timeRemaining: this.getETA(status),
downloadingMetadata: !!downloadingMetadata,
game,
} as DownloadProgress;
WindowManager.mainWindow.webContents.send(
"on-download-progress",
JSON.parse(JSON.stringify(payload))
);
}
} finally {
await new Promise((resolve) => setTimeout(resolve, 500));
if (progress === 1 && game && !downloadingMetadata) {
await this.publishNotification();
/*
Only cancel bittorrent downloads to stop seeding
*/
if (status.bittorrent) {
await this.cancelDownload(game.id);
} else {
this.clearCurrentDownload();
}
}
if (WindowManager.mainWindow && game) {
WindowManager.mainWindow.setProgressBar(progress === 1 ? -1 : progress);
const payload = {
progress,
bytesDownloaded: Number(status.completedLength),
fileSize: Number(status.totalLength),
numPeers: Number(status.connections),
numSeeds: Number(status.numSeeders ?? 0),
downloadSpeed: Number(status.downloadSpeed),
timeRemaining: this.getETA(status),
downloadingMetadata: !!downloadingMetadata,
game,
} as DownloadProgress;
WindowManager.mainWindow.webContents.send(
"on-download-progress",
JSON.parse(JSON.stringify(payload))
);
}
}
static async getGame(gameId: number) {
@ -227,6 +217,8 @@ export class DownloadManager {
}
static async startDownload(gameId: number) {
if (!this.connected) await this.connect();
const game = await this.getGame(gameId)!;
if (game) {

View File

@ -8,3 +8,4 @@ export * from "./window-manager";
export * from "./download-manager";
export * from "./how-long-to-beat";
export * from "./process-watcher";
export * from "./main-loop";

View File

@ -0,0 +1,16 @@
import { DownloadManager } from "./download-manager";
import { watchProcesses } from "./process-watcher";
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export const startMainLoop = async () => {
// eslint-disable-next-line no-constant-condition
while (true) {
await Promise.allSettled([
watchProcesses(),
DownloadManager.watchDownloads(),
]);
await sleep(500);
}
};

View File

@ -5,73 +5,58 @@ import { gameRepository } from "@main/repository";
import { getProcesses } from "@main/helpers";
import { WindowManager } from "./window-manager";
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const gamesPlaytime = new Map<number, number>();
export const startProcessWatcher = async () => {
const sleepTime = 500;
const gamesPlaytime = new Map<number, number>();
export const watchProcesses = async () => {
const games = await gameRepository.find({
where: {
executablePath: Not(IsNull()),
isDeleted: false,
},
});
// eslint-disable-next-line no-constant-condition
while (true) {
const games = await gameRepository.find({
where: {
executablePath: Not(IsNull()),
isDeleted: false,
},
if (games.length === 0) return;
const processes = await getProcesses();
for (const game of games) {
const executablePath = game.executablePath!;
const basename = path.win32.basename(executablePath);
const basenameWithoutExtension = path.win32.basename(
executablePath,
path.extname(executablePath)
);
const gameProcess = processes.find((runningProcess) => {
if (process.platform === "win32") {
return runningProcess.name === basename;
}
return [basename, basenameWithoutExtension].includes(runningProcess.name);
});
if (games.length === 0) {
await sleep(sleepTime);
continue;
}
if (gameProcess) {
if (gamesPlaytime.has(game.id)) {
const zero = gamesPlaytime.get(game.id) ?? 0;
const delta = performance.now() - zero;
const processes = await getProcesses();
for (const game of games) {
const executablePath = game.executablePath!;
const basename = path.win32.basename(executablePath);
const basenameWithoutExtension = path.win32.basename(
executablePath,
path.extname(executablePath)
);
const gameProcess = processes.find((runningProcess) => {
if (process.platform === "win32") {
return runningProcess.name === basename;
}
return [basename, basenameWithoutExtension].includes(
runningProcess.name
);
});
if (gameProcess) {
if (gamesPlaytime.has(game.id)) {
const zero = gamesPlaytime.get(game.id) ?? 0;
const delta = performance.now() - zero;
if (WindowManager.mainWindow) {
WindowManager.mainWindow.webContents.send("on-playtime", game.id);
}
await gameRepository.update(game.id, {
playTimeInMilliseconds: game.playTimeInMilliseconds + delta,
});
gameRepository.update(game.id, {
lastTimePlayed: new Date().toUTCString(),
});
}
gamesPlaytime.set(game.id, performance.now());
} else if (gamesPlaytime.has(game.id)) {
gamesPlaytime.delete(game.id);
if (WindowManager.mainWindow) {
WindowManager.mainWindow.webContents.send("on-game-close", game.id);
WindowManager.mainWindow.webContents.send("on-playtime", game.id);
}
await gameRepository.update(game.id, {
playTimeInMilliseconds: game.playTimeInMilliseconds + delta,
lastTimePlayed: new Date().toUTCString(),
});
}
gamesPlaytime.set(game.id, performance.now());
} else if (gamesPlaytime.has(game.id)) {
gamesPlaytime.delete(game.id);
if (WindowManager.mainWindow) {
WindowManager.mainWindow.webContents.send("on-game-close", game.id);
}
}
await sleep(sleepTime);
}
};

View File

@ -7,26 +7,14 @@ import type {
GameShop,
DownloadProgress,
UserPreferences,
AppUpdaterEvents,
AppUpdaterEvent,
StartGameDownloadPayload,
} from "@types";
contextBridge.exposeInMainWorld("electron", {
/* Torrenting */
startGameDownload: (
repackId: number,
objectID: string,
title: string,
shop: GameShop,
downloadPath: string
) =>
ipcRenderer.invoke(
"startGameDownload",
repackId,
objectID,
title,
shop,
downloadPath
),
startGameDownload: (payload: StartGameDownloadPayload) =>
ipcRenderer.invoke("startGameDownload", payload),
cancelGameDownload: (gameId: number) =>
ipcRenderer.invoke("cancelGameDownload", gameId),
pauseGameDownload: (gameId: number) =>
@ -115,10 +103,10 @@ contextBridge.exposeInMainWorld("electron", {
platform: process.platform,
/* Splash */
onAutoUpdaterEvent: (cb: (value: AppUpdaterEvents) => void) => {
onAutoUpdaterEvent: (cb: (value: AppUpdaterEvent) => void) => {
const listener = (
_event: Electron.IpcRendererEvent,
value: AppUpdaterEvents
value: AppUpdaterEvent
) => cb(value);
ipcRenderer.on("autoUpdaterEvent", listener);

View File

@ -15,8 +15,7 @@ export function BottomPanel() {
const { lastPacket, progress, downloadSpeed, eta } = useDownload();
const isGameDownloading =
lastPacket?.game && lastPacket?.game.status === "active";
const isGameDownloading = !!lastPacket?.game;
const [version, setVersion] = useState("");

View File

@ -18,7 +18,6 @@ const base = style({
},
":disabled": {
opacity: vars.opacity.disabled,
pointerEvents: "none",
cursor: "not-allowed",
},
});
@ -30,6 +29,9 @@ export const button = styleVariants({
":hover": {
backgroundColor: "#DADBE1",
},
":disabled": {
backgroundColor: vars.color.muted,
},
},
],
outline: [
@ -41,6 +43,9 @@ export const button = styleVariants({
":hover": {
backgroundColor: "rgba(255, 255, 255, 0.1)",
},
":disabled": {
backgroundColor: "transparent",
},
},
],
dark: [

View File

@ -28,7 +28,6 @@ export const content = recipe({
flexDirection: "column",
padding: `${SPACING_UNIT * 2}px`,
gap: `${SPACING_UNIT * 2}px`,
paddingBottom: "0",
width: "100%",
overflow: "auto",
},

View File

@ -48,10 +48,8 @@ export const toast = recipe({
export const toastContent = style({
display: "flex",
position: "relative",
gap: `${SPACING_UNIT}px`,
padding: `${SPACING_UNIT * 2}px ${SPACING_UNIT * 5}px`,
paddingLeft: `${SPACING_UNIT * 2}px`,
gap: `${SPACING_UNIT * 2}px`,
padding: `${SPACING_UNIT * 2}px ${SPACING_UNIT * 2}px`,
justifyContent: "center",
alignItems: "center",
});
@ -63,13 +61,11 @@ export const progress = style({
backgroundColor: vars.color.darkBackground,
},
"::-webkit-progress-value": {
backgroundColor: "#1c9749",
backgroundColor: vars.color.muted,
},
});
export const closeButton = style({
position: "absolute",
right: `${SPACING_UNIT}px`,
color: vars.color.bodyText,
cursor: "pointer",
padding: "0",
@ -77,5 +73,9 @@ export const closeButton = style({
});
export const successIcon = style({
color: "#1c9749",
color: vars.color.success,
});
export const errorIcon = style({
color: vars.color.danger,
});

View File

@ -1,12 +1,12 @@
import { useCallback, useEffect, useRef, useState } from "react";
import {
CheckCircleFillIcon,
CheckCircleIcon,
XCircleIcon,
XCircleFillIcon,
XIcon,
} from "@primer/octicons-react";
import * as styles from "./toast.css";
import { SPACING_UNIT } from "@renderer/theme.css";
export interface ToastProps {
visible: boolean;
@ -78,8 +78,13 @@ export function Toast({ visible, message, type, onClose }: ToastProps) {
return (
<div className={styles.toast({ closing: isClosing })}>
<div className={styles.toastContent}>
<CheckCircleFillIcon className={styles.successIcon} />
<span style={{ fontWeight: "bold" }}>{message}</span>
<div style={{ display: "flex", gap: `${SPACING_UNIT}px` }}>
{type === "success" && (
<CheckCircleFillIcon className={styles.successIcon} />
)}
{type === "error" && <XCircleFillIcon className={styles.errorIcon} />}
<span style={{ fontWeight: "bold" }}>{message}</span>
</div>
<button
type="button"
@ -87,7 +92,7 @@ export function Toast({ visible, message, type, onClose }: ToastProps) {
onClick={startAnimateClosing}
aria-label="Close toast"
>
<XCircleIcon />
<XIcon />
</button>
</div>

View File

@ -10,6 +10,7 @@ import type {
Steam250Game,
DownloadProgress,
UserPreferences,
StartGameDownloadPayload,
} from "@types";
import type { DiskSpace } from "check-disk-space";
@ -21,13 +22,7 @@ declare global {
interface Electron {
/* Torrenting */
startGameDownload: (
repackId: number,
objectID: string,
title: string,
shop: GameShop,
downloadPath: string
) => Promise<Game>;
startGameDownload: (payload: StartGameDownloadPayload) => Promise<Game>;
cancelGameDownload: (gameId: number) => Promise<void>;
pauseGameDownload: (gameId: number) => Promise<void>;
resumeGameDownload: (gameId: number) => Promise<void>;

View File

@ -9,7 +9,7 @@ import {
setGameDeleting,
removeGameFromDeleting,
} from "@renderer/features";
import type { DownloadProgress, GameShop } from "@types";
import type { DownloadProgress, StartGameDownloadPayload } from "@types";
import { useDate } from "./use-date";
import { formatBytes } from "@shared";
@ -22,21 +22,13 @@ export function useDownload() {
);
const dispatch = useAppDispatch();
const startDownload = (
repackId: number,
objectID: string,
title: string,
shop: GameShop,
downloadPath: string
) =>
window.electron
.startGameDownload(repackId, objectID, title, shop, downloadPath)
.then((game) => {
dispatch(clearDownload());
updateLibrary();
const startDownload = (payload: StartGameDownloadPayload) =>
window.electron.startGameDownload(payload).then((game) => {
dispatch(clearDownload());
updateLibrary();
return game;
});
return game;
});
const pauseDownload = async (gameId: number) => {
await window.electron.pauseGameDownload(gameId);
@ -62,11 +54,11 @@ export function useDownload() {
});
const getETA = () => {
if (lastPacket && lastPacket.timeRemaining < 0) return "";
if (!lastPacket || lastPacket.timeRemaining < 0) return "";
try {
return formatDistance(
addMilliseconds(new Date(), lastPacket?.timeRemaining ?? 1),
addMilliseconds(new Date(), lastPacket.timeRemaining),
new Date(),
{ addSuffix: true }
);
@ -94,7 +86,7 @@ export function useDownload() {
return {
downloadSpeed: `${formatBytes(lastPacket?.downloadSpeed ?? 0)}/s`,
progress: formatDownloadProgress(lastPacket?.game.progress ?? 0),
progress: formatDownloadProgress(lastPacket?.game.progress),
lastPacket,
eta: getETA(),
startDownload,

View File

@ -254,9 +254,7 @@ export function Downloads() {
<button
type="button"
className={styles.downloadTitle}
onClick={() =>
navigate(`/game/${game.shop}/${game.objectID}`)
}
onClick={() => navigate(buildGameDetailsPath(game))}
>
{game.title}
</button>

View File

@ -67,6 +67,7 @@ export const mediaPreviewButton = recipe({
transition: "translate 0.3s ease-in-out, opacity 0.2s ease",
borderRadius: "4px",
border: `solid 1px ${vars.color.border}`,
overflow: "hidden",
":hover": {
opacity: "0.8",
},
@ -84,7 +85,6 @@ export const mediaPreview = style({
width: "100%",
height: "100%",
display: "flex",
flex: "1",
});
export const gallerySliderButton = recipe({

View File

@ -15,6 +15,7 @@ import {
OnlineFixInstallationGuide,
RepacksModal,
} from "./modals";
import { Downloader } from "@shared";
export interface GameDetailsContext {
game: Game | null;
@ -138,15 +139,17 @@ export function GameDetailsContextProvider({
const handleStartDownload = async (
repack: GameRepack,
downloader: Downloader,
downloadPath: string
) => {
await startDownload(
repack.id,
objectID!,
gameTitle,
shop as GameShop,
downloadPath
);
await startDownload({
repackId: repack.id,
objectID: objectID!,
title: gameTitle,
downloader,
shop: shop as GameShop,
downloadPath,
});
await updateGame();
setShowRepacksModal(false);

View File

@ -1,5 +1,6 @@
import { style } from "@vanilla-extract/css";
import { SPACING_UNIT, vars } from "../../../theme.css";
import { recipe } from "@vanilla-extract/recipes";
export const panel = style({
width: "100%",
@ -11,6 +12,8 @@ export const panel = style({
justifyContent: "space-between",
transition: "all ease 0.2s",
borderBottom: `solid 1px ${vars.color.border}`,
position: "relative",
overflow: "hidden",
});
export const content = style({
@ -29,3 +32,27 @@ export const downloadDetailsRow = style({
display: "flex",
alignItems: "flex-end",
});
export const progressBar = recipe({
base: {
position: "absolute",
bottom: "0",
left: "0",
width: "100%",
height: "3px",
transition: "all ease 0.2s",
"::-webkit-progress-bar": {
backgroundColor: "transparent",
},
"::-webkit-progress-value": {
backgroundColor: vars.color.muted,
},
},
variants: {
disabled: {
true: {
opacity: vars.opacity.disabled,
},
},
},
});

View File

@ -33,29 +33,46 @@ export function HeroPanel() {
return game.repack?.fileSize ?? "N/A";
}, [game, lastPacket?.game]);
const isGameDownloading =
game?.status === "active" && lastPacket?.game.id === game?.id;
const getInfo = () => {
if (isGameDeleting(game?.id ?? -1)) return <p>{t("deleting")}</p>;
if (game?.progress === 1) return <HeroPanelPlaytime />;
console.log(lastPacket?.game.id, game?.id);
if (game?.status === "active" && lastPacket?.game.id === game?.id) {
if (lastPacket?.downloadingMetadata) {
return <p>{t("downloading_metadata")}</p>;
if (game?.status === "active") {
if (lastPacket?.downloadingMetadata && isGameDownloading) {
return (
<>
<p>{progress}</p>
<p>{t("downloading_metadata")}</p>
</>
);
}
const sizeDownloaded = formatBytes(
lastPacket?.game?.bytesDownloaded ?? game?.bytesDownloaded
);
const showPeers =
game?.downloader === Downloader.Torrent &&
lastPacket?.numPeers !== undefined;
return (
<>
<p className={styles.downloadDetailsRow}>
{progress}
{isGameDownloading
? progress
: formatDownloadProgress(game?.progress)}
{eta && <small>{t("eta", { eta })}</small>}
</p>
<p className={styles.downloadDetailsRow}>
{formatBytes(lastPacket?.game?.bytesDownloaded ?? 0)} /{" "}
{finalDownloadSize}
{game?.downloader === Downloader.Torrent && (
<span>
{sizeDownloaded} / {finalDownloadSize}
</span>
{showPeers && (
<small>
{lastPacket?.numPeers} peers / {lastPacket?.numSeeds} seeds
</small>
@ -99,6 +116,10 @@ export function HeroPanel() {
? (new Color(gameColor).darken(0.6).toString() as string)
: "";
const showProgressBar =
(game?.status === "active" && game?.progress < 1) ||
game?.status === "paused";
return (
<>
<BinaryNotFoundModal
@ -113,6 +134,18 @@ export function HeroPanel() {
openBinaryNotFoundModal={() => setShowBinaryNotFoundModal(true)}
/>
</div>
{showProgressBar && (
<progress
max={1}
value={
isGameDownloading ? lastPacket?.game.progress : game?.progress
}
className={styles.progressBar({
disabled: game?.status === "paused",
})}
/>
)}
</div>
</>
);

View File

@ -10,10 +10,15 @@ import { SPACING_UNIT } from "../../../theme.css";
import { format } from "date-fns";
import { SelectFolderModal } from "./select-folder-modal";
import { gameDetailsContext } from "../game-details.context";
import { Downloader } from "@shared";
export interface RepacksModalProps {
visible: boolean;
startDownload: (repack: GameRepack, downloadPath: string) => Promise<void>;
startDownload: (
repack: GameRepack,
downloader: Downloader,
downloadPath: string
) => Promise<void>;
onClose: () => void;
}

View File

@ -4,15 +4,19 @@ import { Trans, useTranslation } from "react-i18next";
import { DiskSpace } from "check-disk-space";
import * as styles from "./select-folder-modal.css";
import { Button, Link, Modal, TextField } from "@renderer/components";
import { DownloadIcon } from "@primer/octicons-react";
import { formatBytes } from "@shared";
import { CheckCircleFillIcon, DownloadIcon } from "@primer/octicons-react";
import { Downloader, formatBytes } from "@shared";
import type { GameRepack } from "@types";
import type { GameRepack, UserPreferences } from "@types";
export interface SelectFolderModalProps {
visible: boolean;
onClose: () => void;
startDownload: (repack: GameRepack, downloadPath: string) => Promise<void>;
startDownload: (
repack: GameRepack,
downloader: Downloader,
downloadPath: string
) => Promise<void>;
repack: GameRepack | null;
}
@ -27,6 +31,11 @@ export function SelectFolderModal({
const [diskFreeSpace, setDiskFreeSpace] = useState<DiskSpace | null>(null);
const [selectedPath, setSelectedPath] = useState("");
const [downloadStarting, setDownloadStarting] = useState(false);
const [userPreferences, setUserPreferences] =
useState<UserPreferences | null>(null);
const [selectedDownloader, setSelectedDownloader] = useState(
Downloader.Torrent
);
useEffect(() => {
visible && getDiskFreeSpace(selectedPath);
@ -38,6 +47,11 @@ export function SelectFolderModal({
window.electron.getUserPreferences(),
]).then(([path, userPreferences]) => {
setSelectedPath(userPreferences?.downloadsPath || path);
setUserPreferences(userPreferences);
if (userPreferences?.realDebridApiToken) {
setSelectedDownloader(Downloader.RealDebrid);
}
});
}, []);
@ -63,7 +77,7 @@ export function SelectFolderModal({
if (repack) {
setDownloadStarting(true);
startDownload(repack, selectedPath).finally(() => {
startDownload(repack, selectedDownloader, selectedPath).finally(() => {
setDownloadStarting(false);
onClose();
});
@ -73,7 +87,7 @@ export function SelectFolderModal({
return (
<Modal
visible={visible}
title={t("download_path")}
title="Download options"
description={t("space_left_on_disk", {
space: formatBytes(diskFreeSpace?.free ?? 0),
})}
@ -81,23 +95,43 @@ export function SelectFolderModal({
>
<div className={styles.container}>
<div>
<label style={{ marginBottom: 0, padding: 0 }}>Download method</label>
<label style={{ marginBottom: 0, padding: 0 }}>Method</label>
<div className={styles.downloaders}>
<Button className={styles.downloaderOption} theme="outline">
<Button
className={styles.downloaderOption}
theme={
selectedDownloader === Downloader.Torrent
? "primary"
: "outline"
}
onClick={() => setSelectedDownloader(Downloader.Torrent)}
>
{selectedDownloader === Downloader.Torrent && (
<CheckCircleFillIcon />
)}
Torrent
</Button>
<Button className={styles.downloaderOption}>Real Debrid</Button>
<Button
className={styles.downloaderOption}
theme={
selectedDownloader === Downloader.RealDebrid
? "primary"
: "outline"
}
onClick={() => setSelectedDownloader(Downloader.RealDebrid)}
disabled={!userPreferences?.realDebridApiToken}
>
{selectedDownloader === Downloader.RealDebrid && (
<CheckCircleFillIcon />
)}
Real Debrid
</Button>
</div>
</div>
<div className={styles.downloadsPathField}>
<TextField
value={selectedPath}
readOnly
disabled
label="Download path"
/>
<TextField value={selectedPath} readOnly disabled label="Path" />
<Button
style={{ alignSelf: "flex-end" }}

View File

@ -9,6 +9,8 @@ export const [themeClass, vars] = createTheme({
muted: "#c0c1c7",
bodyText: "#8e919b",
border: "#424244",
success: "#1c9749",
danger: "#e11d48",
},
opacity: {
disabled: "0.5",

View File

@ -148,7 +148,7 @@ export interface SteamGame {
clientIcon: string | null;
}
export type AppUpdaterEvents =
export type AppUpdaterEvent =
| { type: "error" }
| { type: "checking-for-updates" }
| { type: "update-not-available" }
@ -156,3 +156,13 @@ export type AppUpdaterEvents =
| { type: "update-downloaded" }
| { type: "download-progress"; info: ProgressInfo }
| { type: "update-cancelled" };
/* Events */
export interface StartGameDownloadPayload {
repackId: number;
objectID: string;
title: string;
shop: GameShop;
downloadPath: string;
downloader: Downloader;
}

View File

@ -1323,7 +1323,7 @@
dependencies:
undici-types "~5.26.4"
"@types/node@^18.11.18", "@types/node@^18.7.13":
"@types/node@^18.11.18":
version "18.19.33"
resolved "https://registry.yarnpkg.com/@types/node/-/node-18.19.33.tgz#98cd286a1b8a5e11aa06623210240bcc28e95c48"
integrity sha512-NR9+KrpSajr2qBVp/Yt5TU/rp+b5Mayi3+OlMlcg2cVCfRmcG5PWZ7S4+MG9PZ5gWBoc9Pd0BKSRViuBCRPu0A==
@ -1406,11 +1406,6 @@
resolved "https://registry.yarnpkg.com/@types/verror/-/verror-1.10.10.tgz#d5a4b56abac169bfbc8b23d291363a682e6fa087"
integrity sha512-l4MM0Jppn18hb9xmM6wwD1uTdShpf9Pn80aXTStnK1C94gtPvJcV2FrDmbOQUAQfJ1cKZHktkQUDwEqaAKXMMg==
"@types/when@^2.4.34":
version "2.4.41"
resolved "https://registry.yarnpkg.com/@types/when/-/when-2.4.41.tgz#e16e685aa739c696a582b10afc5f1306964846a2"
integrity sha512-o/j5X9Bnv6mMG4ZcNJur8UaU17Rl0mLbTZvWcODVVy+Xdh8LEc7s6I0CvbEuTP786LTa0OyJby5P4hI7C+ZJNg==
"@types/yauzl@^2.9.1":
version "2.10.3"
resolved "https://registry.yarnpkg.com/@types/yauzl/-/yauzl-2.10.3.tgz#e9b2808b4f109504a03cda958259876f61017999"
@ -2686,11 +2681,6 @@ eastasianwidth@^0.2.0:
resolved "https://registry.yarnpkg.com/eastasianwidth/-/eastasianwidth-0.2.0.tgz#696ce2ec0aa0e6ea93a397ffcf24aa7840c827cb"
integrity sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==
easydl@^1.1.1:
version "1.2.0"
resolved "https://registry.yarnpkg.com/easydl/-/easydl-1.2.0.tgz#b2d8bd7e72c055fedc367db4b7b9585eed55c245"
integrity sha512-v0PnU1HGqWd6VAiJY6wwzjsznNVTeFV0YgJcv52qLexR9f5ndsPgwu9Dmf9bGC5j2ZKrO9wqORpulDM7WUBNKA==
ejs@^3.1.8:
version "3.1.10"
resolved "https://registry.yarnpkg.com/ejs/-/ejs-3.1.10.tgz#69ab8358b14e896f80cc39e62087b88500c3ac3b"
@ -4548,11 +4538,6 @@ minimatch@^9.0.1:
dependencies:
brace-expansion "^2.0.1"
minimist@1.2.6:
version "1.2.6"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.6.tgz#8637a5b759ea0d6e98702cfb3a9283323c93af44"
integrity sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==
minimist@^1.2.0, minimist@^1.2.3, minimist@^1.2.6, minimist@^1.2.8:
version "1.2.8"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c"
@ -4662,20 +4647,6 @@ no-case@^3.0.4:
lower-case "^2.0.2"
tslib "^2.0.3"
node-7z-archive@^1.1.7:
version "1.1.7"
resolved "https://registry.yarnpkg.com/node-7z-archive/-/node-7z-archive-1.1.7.tgz#0b037701e016a651d6040b63d8781b2e7102facd"
integrity sha512-gtpWpajFyzeObGiYI9RDq76x5ULnxInvZ1OfA0/MD+2VezcMmMQMK6ITqkvsGEqVy4w/psvmIyowVDoSURAJHg==
dependencies:
fs-extra "^10.1.0"
minimist "^1.2.8"
node-sys "^1.2.2"
node-unar "^1.0.8"
node-wget-fetch "^1.1.3"
when "^3.7.8"
optionalDependencies:
"@types/when" "^2.4.34"
node-abi@^3.3.0:
version "3.62.0"
resolved "https://registry.yarnpkg.com/node-abi/-/node-abi-3.62.0.tgz#017958ed120f89a3a14a7253da810f5d724e3f36"
@ -4693,7 +4664,7 @@ node-domexception@^1.0.0:
resolved "https://registry.yarnpkg.com/node-domexception/-/node-domexception-1.0.0.tgz#6888db46a1f71c0b76b3f7555016b63fe64766e5"
integrity sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==
node-fetch@^2.6.1, node-fetch@^2.6.7:
node-fetch@^2.6.1:
version "2.7.0"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.7.0.tgz#d0f0fa6e3e2dc1d27efcd8ad99d550bda94d187d"
integrity sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==
@ -4714,40 +4685,6 @@ node-releases@^2.0.14:
resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.14.tgz#2ffb053bceb8b2be8495ece1ab6ce600c4461b0b"
integrity sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==
node-stream-zip@^1.12.0:
version "1.15.0"
resolved "https://registry.yarnpkg.com/node-stream-zip/-/node-stream-zip-1.15.0.tgz#158adb88ed8004c6c49a396b50a6a5de3bca33ea"
integrity sha512-LN4fydt9TqhZhThkZIVQnF9cwjU3qmUH9h78Mx/K7d3VvfRqqwthLwJEUOEL0QPZ0XQmNN7be5Ggit5+4dq3Bw==
node-sys@^1.1.7, node-sys@^1.2.2:
version "1.2.4"
resolved "https://registry.yarnpkg.com/node-sys/-/node-sys-1.2.4.tgz#db9c50fd93c8fc62bc4eafe93eae0fd3696c8028"
integrity sha512-71sIz+zgaHfSmP1vHTHXUVb77PqncIB1MBij+Q43fQSz7ceSLrrO5RTTBlnYWDU/M0fEFTZw3Zui/lVeJvoeag==
dependencies:
minimist "1.2.6"
which "^2.0.2"
optionalDependencies:
"@types/node" "^18.7.13"
node-unar@^1.0.8:
version "1.0.8"
resolved "https://registry.yarnpkg.com/node-unar/-/node-unar-1.0.8.tgz#fbf5b05da2ac24278b6160f3b46231d56a73a673"
integrity sha512-AnEdWmV8/Dx1qMB5O2VcemoBmNzW1mhibYNl3YDUI7cVohVuobuIZwxrtRedItO05A6PiLp/HNw1ryg7M17H5g==
dependencies:
node-sys "^1.1.7"
when "^3.7.8"
optionalDependencies:
fs-extra "^9.0.1"
node-stream-zip "^1.12.0"
node-wget-fetch "^1.1.2"
node-wget-fetch@^1.1.2, node-wget-fetch@^1.1.3:
version "1.1.3"
resolved "https://registry.yarnpkg.com/node-wget-fetch/-/node-wget-fetch-1.1.3.tgz#1e4aea2d7093393a961bb9c07cf5c5e33913c437"
integrity sha512-TmjZeeL/zAcB4fpok2iJ6FLbjVzSsjKi7rdk0womqvUY2ouitsEN0kGekndshaB7ENnXocrcgUudpvB4Jo3+LA==
dependencies:
node-fetch "^2.6.7"
normalize-url@^6.0.1:
version "6.1.0"
resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-6.1.0.tgz#40d0885b535deffe3f3147bec877d05fe4c5668a"
@ -6234,11 +6171,6 @@ whatwg-url@^5.0.0:
tr46 "~0.0.3"
webidl-conversions "^3.0.0"
when@^3.7.8:
version "3.7.8"
resolved "https://registry.yarnpkg.com/when/-/when-3.7.8.tgz#c7130b6a7ea04693e842cdc9e7a1f2aa39a39f82"
integrity sha512-5cZ7mecD3eYcMiCH4wtRPA5iFJZ50BJYDfckI5RRpQiktMiYTcn0ccLTZOvcbBume+1304fQztxeNzNS9Gvrnw==
which-boxed-primitive@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz#13757bc89b209b049fe5d86430e21cf40a89a8e6"
@ -6289,7 +6221,7 @@ which-typed-array@^1.1.14, which-typed-array@^1.1.15, which-typed-array@^1.1.9:
gopd "^1.0.1"
has-tostringtag "^1.0.2"
which@^2.0.1, which@^2.0.2:
which@^2.0.1:
version "2.0.2"
resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1"
integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==