refactor: prettier changes

This commit is contained in:
lilezek 2024-04-30 11:24:35 +02:00
parent a16a30761e
commit e79b6f1391
16 changed files with 380 additions and 332 deletions

View file

@ -21,6 +21,5 @@ export namespace GameStatus {
GameStatus.Decompressing == status; GameStatus.Decompressing == status;
export const isReady = (status: GameStatus | null) => export const isReady = (status: GameStatus | null) =>
status === GameStatus.Finished || status === GameStatus.Finished || status === GameStatus.Seeding;
status === GameStatus.Seeding;
} }

View file

@ -35,4 +35,3 @@ export class UserPreferences {
@UpdateDateColumn() @UpdateDateColumn()
updatedAt: Date; updatedAt: Date;
} }

View file

@ -45,7 +45,7 @@ const cancelGameDownload = async (
game.status !== GameStatus.Seeding game.status !== GameStatus.Seeding
) { ) {
Downloader.cancelDownload(); Downloader.cancelDownload();
if (result.affected) WindowManager.mainWindow.setProgressBar(-1); if (result.affected) WindowManager.mainWindow?.setProgressBar(-1);
} }
}); });
}; };

View file

@ -1,4 +1,4 @@
import { getSteamGameIconUrl, writePipe } from "@main/services"; import { getSteamGameIconUrl } from "@main/services";
import { gameRepository, repackRepository } from "@main/repository"; import { gameRepository, repackRepository } from "@main/repository";
import { registerEvent } from "../register-event"; import { registerEvent } from "../register-event";

View file

@ -10,7 +10,7 @@ import { TorrentUpdate } from "./torrent-client";
import { HTTPDownloader } from "./http-downloader"; import { HTTPDownloader } from "./http-downloader";
import { Unrar } from "../unrar"; import { Unrar } from "../unrar";
import { GameStatus } from "@globals"; import { GameStatus } from "@globals";
import path from 'node:path'; import path from "node:path";
interface DownloadStatus { interface DownloadStatus {
numPeers: number; numPeers: number;
@ -23,12 +23,14 @@ export class Downloader {
private static lastHttpDownloader: HTTPDownloader | null = null; private static lastHttpDownloader: HTTPDownloader | null = null;
static async usesRealDebrid() { static async usesRealDebrid() {
const userPreferences = await userPreferencesRepository.findOne({ where: { id: 1 } }); const userPreferences = await userPreferencesRepository.findOne({
where: { id: 1 },
});
return userPreferences!.realDebridApiToken !== null; return userPreferences!.realDebridApiToken !== null;
} }
static async cancelDownload() { static async cancelDownload() {
if (!await this.usesRealDebrid()) { if (!(await this.usesRealDebrid())) {
writePipe.write({ action: "cancel" }); writePipe.write({ action: "cancel" });
} else { } else {
if (this.lastHttpDownloader) { if (this.lastHttpDownloader) {
@ -38,7 +40,7 @@ export class Downloader {
} }
static async pauseDownload() { static async pauseDownload() {
if (!await this.usesRealDebrid()) { if (!(await this.usesRealDebrid())) {
writePipe.write({ action: "pause" }); writePipe.write({ action: "pause" });
} else { } else {
if (this.lastHttpDownloader) { if (this.lastHttpDownloader) {
@ -48,7 +50,7 @@ export class Downloader {
} }
static async resumeDownload() { static async resumeDownload() {
if (!await this.usesRealDebrid()) { if (!(await this.usesRealDebrid())) {
writePipe.write({ action: "pause" }); writePipe.write({ action: "pause" });
} else { } else {
if (this.lastHttpDownloader) { if (this.lastHttpDownloader) {
@ -58,7 +60,7 @@ export class Downloader {
} }
static async downloadGame(game: Game, repack: Repack) { static async downloadGame(game: Game, repack: Repack) {
if (!await this.usesRealDebrid()) { if (!(await this.usesRealDebrid())) {
writePipe.write({ writePipe.write({
action: "start", action: "start",
game_id: game.id, game_id: game.id,
@ -73,7 +75,11 @@ export class Downloader {
const { links } = await RealDebridClient.getInfo(torrent.id); const { links } = await RealDebridClient.getInfo(torrent.id);
const { download } = await RealDebridClient.unrestrictLink(links[0]); const { download } = await RealDebridClient.unrestrictLink(links[0]);
this.lastHttpDownloader = new HTTPDownloader(); this.lastHttpDownloader = new HTTPDownloader();
this.lastHttpDownloader.download(download, game.downloadPath!, game.id); this.lastHttpDownloader.download(
download,
game.downloadPath!,
game.id
);
} }
} catch (e) { } catch (e) {
console.error(e); console.error(e);
@ -81,7 +87,11 @@ export class Downloader {
} }
} }
static async updateGameProgress(gameId: number, gameUpdate: QueryDeepPartialEntity<Game>, downloadStatus: DownloadStatus) { static async updateGameProgress(
gameId: number,
gameUpdate: QueryDeepPartialEntity<Game>,
downloadStatus: DownloadStatus
) {
await gameRepository.update({ id: gameId }, gameUpdate); await gameRepository.update({ id: gameId }, gameUpdate);
const game = await gameRepository.findOne({ const game = await gameRepository.findOne({
@ -89,7 +99,10 @@ export class Downloader {
relations: { repack: true }, relations: { repack: true },
}); });
if (gameUpdate.progress === 1 && gameUpdate.status !== GameStatus.Decompressing) { if (
gameUpdate.progress === 1 &&
gameUpdate.status !== GameStatus.Decompressing
) {
const userPreferences = await userPreferencesRepository.findOne({ const userPreferences = await userPreferencesRepository.findOne({
where: { id: 1 }, where: { id: 1 },
}); });
@ -109,13 +122,24 @@ export class Downloader {
} }
} }
if (game && gameUpdate.decompressionProgress === 0 && gameUpdate.status === GameStatus.Decompressing) { if (
const unrar = await Unrar.fromFilePath(game.rarPath!, path.join(game.downloadPath!, game.folderName!)); game &&
gameUpdate.decompressionProgress === 0 &&
gameUpdate.status === GameStatus.Decompressing
) {
const unrar = await Unrar.fromFilePath(
game.rarPath!,
path.join(game.downloadPath!, game.folderName!)
);
unrar.extract(); unrar.extract();
this.updateGameProgress(gameId, { this.updateGameProgress(
gameId,
{
decompressionProgress: 1, decompressionProgress: 1,
status: GameStatus.Finished, status: GameStatus.Finished,
}, downloadStatus); },
downloadStatus
);
} }
if (WindowManager.mainWindow && game) { if (WindowManager.mainWindow && game) {
@ -124,8 +148,9 @@ export class Downloader {
WindowManager.mainWindow.webContents.send( WindowManager.mainWindow.webContents.send(
"on-download-progress", "on-download-progress",
JSON.parse(JSON.stringify({ JSON.parse(
...{ JSON.stringify({
...({
progress: gameUpdate.progress, progress: gameUpdate.progress,
bytesDownloaded: gameUpdate.bytesDownloaded, bytesDownloaded: gameUpdate.bytesDownloaded,
fileSize: gameUpdate.fileSize, fileSize: gameUpdate.fileSize,
@ -134,15 +159,19 @@ export class Downloader {
numSeeds: downloadStatus.numSeeds, numSeeds: downloadStatus.numSeeds,
downloadSpeed: downloadStatus.downloadSpeed, downloadSpeed: downloadStatus.downloadSpeed,
timeRemaining: downloadStatus.timeRemaining, timeRemaining: downloadStatus.timeRemaining,
} as TorrentUpdate, game } as TorrentUpdate),
})) game,
})
)
); );
} }
} }
static getGameProgress(game: Game) { static getGameProgress(game: Game) {
if (game.status === GameStatus.CheckingFiles) return game.fileVerificationProgress; if (game.status === GameStatus.CheckingFiles)
if (game.status === GameStatus.Decompressing) return game.decompressionProgress; return game.fileVerificationProgress;
if (game.status === GameStatus.Decompressing)
return game.decompressionProgress;
return game.progress; return game.progress;
} }
} }

View file

@ -1,12 +1,12 @@
import { Game } from '@main/entity'; import { Game } from "@main/entity";
import { ElectronDownloadManager } from 'electron-dl-manager'; import { ElectronDownloadManager } from "electron-dl-manager";
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity'; import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity";
import { WindowManager } from '../window-manager'; import { WindowManager } from "../window-manager";
import { Downloader } from './downloader'; import { Downloader } from "./downloader";
import { GameStatus } from '@globals'; import { GameStatus } from "@globals";
function dropExtension(fileName: string) { function dropExtension(fileName: string) {
return fileName.split('.').slice(0, -1).join('.'); return fileName.split(".").slice(0, -1).join(".");
} }
export class HTTPDownloader { export class HTTPDownloader {
@ -31,7 +31,7 @@ export class HTTPDownloader {
bytesDownloaded: 0, bytesDownloaded: 0,
fileSize: ev.item.getTotalBytes(), fileSize: ev.item.getTotalBytes(),
rarPath: `${destination}/.rd/${ev.resolvedFilename}`, rarPath: `${destination}/.rd/${ev.resolvedFilename}`,
folderName: dropExtension(ev.resolvedFilename) folderName: dropExtension(ev.resolvedFilename),
}; };
const downloadStatus = { const downloadStatus = {
numPeers: 0, numPeers: 0,
@ -39,7 +39,11 @@ export class HTTPDownloader {
downloadSpeed: 0, downloadSpeed: 0,
timeRemaining: Number.POSITIVE_INFINITY, timeRemaining: Number.POSITIVE_INFINITY,
}; };
await Downloader.updateGameProgress(gameId, updatePayload, downloadStatus); await Downloader.updateGameProgress(
gameId,
updatePayload,
downloadStatus
);
}, },
onDownloadCompleted: async (ev) => { onDownloadCompleted: async (ev) => {
const updatePayload: QueryDeepPartialEntity<Game> = { const updatePayload: QueryDeepPartialEntity<Game> = {
@ -54,7 +58,11 @@ export class HTTPDownloader {
downloadSpeed: 0, downloadSpeed: 0,
timeRemaining: 0, timeRemaining: 0,
}; };
await Downloader.updateGameProgress(gameId, updatePayload, downloadStatus); await Downloader.updateGameProgress(
gameId,
updatePayload,
downloadStatus
);
}, },
onDownloadProgress: async (ev) => { onDownloadProgress: async (ev) => {
const updatePayload: QueryDeepPartialEntity<Game> = { const updatePayload: QueryDeepPartialEntity<Game> = {
@ -67,8 +75,12 @@ export class HTTPDownloader {
downloadSpeed: ev.downloadRateBytesPerSecond, downloadSpeed: ev.downloadRateBytesPerSecond,
timeRemaining: ev.estimatedTimeRemainingSeconds, timeRemaining: ev.estimatedTimeRemainingSeconds,
}; };
await Downloader.updateGameProgress(gameId, updatePayload, downloadStatus); await Downloader.updateGameProgress(
} gameId,
updatePayload,
downloadStatus
);
},
}, },
directory: `${destination}/.rd/`, directory: `${destination}/.rd/`,
}); });

View file

@ -13,41 +13,41 @@ export interface RealDebridUnrestrictLink {
} }
export interface RealDebridAddMagnet { export interface RealDebridAddMagnet {
"id": string, id: string;
// URL of the created ressource // URL of the created ressource
"uri": string uri: string;
} }
export interface RealDebridTorrentInfo { export interface RealDebridTorrentInfo {
"id": string, id: string;
"filename": string, filename: string;
"original_filename": string, // Original name of the torrent original_filename: string; // Original name of the torrent
"hash": string, // SHA1 Hash of the torrent hash: string; // SHA1 Hash of the torrent
"bytes": number, // Size of selected files only bytes: number; // Size of selected files only
"original_bytes": number, // Total size of the torrent original_bytes: number; // Total size of the torrent
"host": string, // Host main domain host: string; // Host main domain
"split": number, // Split size of links split: number; // Split size of links
"progress": number, // Possible values: 0 to 100 progress: number; // Possible values: 0 to 100
"status": "downloaded", // Current status of the torrent: magnet_error, magnet_conversion, waiting_files_selection, queued, downloading, downloaded, error, virus, compressing, uploading, dead status: "downloaded"; // Current status of the torrent: magnet_error, magnet_conversion, waiting_files_selection, queued, downloading, downloaded, error, virus, compressing, uploading, dead
"added": string, // jsonDate added: string; // jsonDate
"files": [ files: [
{ {
"id": number, id: number;
"path": string, // Path to the file inside the torrent, starting with "/" path: string; // Path to the file inside the torrent, starting with "/"
"bytes": number, bytes: number;
"selected": number // 0 or 1 selected: number; // 0 or 1
}, },
{ {
"id": number, id: number;
"path": string, // Path to the file inside the torrent, starting with "/" path: string; // Path to the file inside the torrent, starting with "/"
"bytes": number, bytes: number;
"selected": number // 0 or 1 selected: number; // 0 or 1
} },
], ];
"links": [ links: [
"string" // Host URL "string", // Host URL
], ];
"ended": string, // !! Only present when finished, jsonDate ended: string; // !! Only present when finished, jsonDate
"speed": number, // !! Only present in "downloading", "compressing", "uploading" status speed: number; // !! Only present in "downloading", "compressing", "uploading" status
"seeders": number // !! Only present in "downloading", "magnet_conversion" status seeders: number; // !! Only present in "downloading", "magnet_conversion" status
} }

View file

@ -1,6 +1,10 @@
import { userPreferencesRepository } from "@main/repository"; import { userPreferencesRepository } from "@main/repository";
import fetch from "node-fetch"; import fetch from "node-fetch";
import { RealDebridAddMagnet, RealDebridTorrentInfo, RealDebridUnrestrictLink } from "./real-debrid-types"; import {
RealDebridAddMagnet,
RealDebridTorrentInfo,
RealDebridUnrestrictLink,
} from "./real-debrid-types";
const base = "https://api.real-debrid.com/rest/1.0"; const base = "https://api.real-debrid.com/rest/1.0";
@ -9,9 +13,9 @@ export class RealDebridClient {
const response = await fetch(`${base}/torrents/addMagnet`, { const response = await fetch(`${base}/torrents/addMagnet`, {
method: "POST", method: "POST",
headers: { headers: {
"Authorization": `Bearer ${await this.getApiToken()}`, Authorization: `Bearer ${await this.getApiToken()}`,
}, },
body: `magnet=${encodeURIComponent(magnet)}` body: `magnet=${encodeURIComponent(magnet)}`,
}); });
return response.json() as Promise<RealDebridAddMagnet>; return response.json() as Promise<RealDebridAddMagnet>;
@ -20,20 +24,20 @@ export class RealDebridClient {
static async getInfo(id: string) { static async getInfo(id: string) {
const response = await fetch(`${base}/torrents/info/${id}`, { const response = await fetch(`${base}/torrents/info/${id}`, {
headers: { headers: {
"Authorization": `Bearer ${await this.getApiToken()}` Authorization: `Bearer ${await this.getApiToken()}`,
} },
}); });
return response.json() as Promise<RealDebridTorrentInfo>; return response.json() as Promise<RealDebridTorrentInfo>;
} }
static async selectAllFiles(id: string) { static async selectAllFiles(id: string) {
const response = await fetch(`${base}/torrents/selectFiles/${id}`, { await fetch(`${base}/torrents/selectFiles/${id}`, {
method: "POST", method: "POST",
headers: { headers: {
"Authorization": `Bearer ${await this.getApiToken()}`, Authorization: `Bearer ${await this.getApiToken()}`,
}, },
body: "files=all" body: "files=all",
}); });
} }
@ -41,15 +45,17 @@ export class RealDebridClient {
const response = await fetch(`${base}/unrestrict/link`, { const response = await fetch(`${base}/unrestrict/link`, {
method: "POST", method: "POST",
headers: { headers: {
"Authorization": `Bearer ${await this.getApiToken()}`, Authorization: `Bearer ${await this.getApiToken()}`,
}, },
body: `link=${link}` body: `link=${link}`,
}); });
return response.json() as Promise<RealDebridUnrestrictLink>; return response.json() as Promise<RealDebridUnrestrictLink>;
} }
static getApiToken() { static getApiToken() {
return userPreferencesRepository.findOne({ where: { id: 1 } }).then(userPreferences => userPreferences!.realDebridApiToken); return userPreferencesRepository
.findOne({ where: { id: 1 } })
.then((userPreferences) => userPreferences!.realDebridApiToken);
} }
} }

View file

@ -1,7 +1,9 @@
import { Extractor, createExtractorFromFile } from 'node-unrar-js'; import { Extractor, createExtractorFromFile } from "node-unrar-js";
import fs from 'node:fs'; import fs from "node:fs";
const wasmBinary = fs.readFileSync(require.resolve('node-unrar-js/esm/js/unrar.wasm')); const wasmBinary = fs.readFileSync(
require.resolve("node-unrar-js/esm/js/unrar.wasm")
);
export class Unrar { export class Unrar {
private constructor(private extractor: Extractor<Uint8Array>) {} private constructor(private extractor: Extractor<Uint8Array>) {}

View file

@ -118,7 +118,8 @@ export function Sidebar() {
}, [isResizing]); }, [isResizing]);
const getGameTitle = (game: Game) => { const getGameTitle = (game: Game) => {
if (game.status === GameStatus.Paused) return t("paused", { title: game.title }); if (game.status === GameStatus.Paused)
return t("paused", { title: game.title });
if (gameDownloading?.id === game.id) { if (gameDownloading?.id === game.id) {
const isVerifying = GameStatus.isVerifying(gameDownloading.status); const isVerifying = GameStatus.isVerifying(gameDownloading.status);