Fix lints and add back the option to seed after download complete

This commit is contained in:
mircea32000 2025-02-11 00:58:47 +02:00
parent d08d14a9e4
commit 9e6143ebc9
15 changed files with 360 additions and 295 deletions

View file

@ -8,7 +8,7 @@ const authenticateAllDebrid = async (
AllDebridClient.authorize(apiKey); AllDebridClient.authorize(apiKey);
const result = await AllDebridClient.getUser(); const result = await AllDebridClient.getUser();
if ('error_code' in result) { if ("error_code" in result) {
return { error_code: result.error_code }; return { error_code: result.error_code };
} }

View file

@ -31,9 +31,7 @@ const updateUserPreferences = async (
} }
if (preferences.allDebridApiKey) { if (preferences.allDebridApiKey) {
preferences.allDebridApiKey = Crypto.encrypt( preferences.allDebridApiKey = Crypto.encrypt(preferences.allDebridApiKey);
preferences.allDebridApiKey
);
} }
if (preferences.torBoxApiToken) { if (preferences.torBoxApiToken) {

View file

@ -45,15 +45,11 @@ export const loadState = async () => {
} }
if (userPreferences?.allDebridApiKey) { if (userPreferences?.allDebridApiKey) {
AllDebridClient.authorize( AllDebridClient.authorize(Crypto.decrypt(userPreferences.allDebridApiKey));
Crypto.decrypt(userPreferences.allDebridApiKey)
);
} }
if (userPreferences?.torBoxApiToken) { if (userPreferences?.torBoxApiToken) {
TorBoxClient.authorize( TorBoxClient.authorize(Crypto.decrypt(userPreferences.torBoxApiToken));
Crypto.decrypt(userPreferences.torBoxApiToken)
);
} }
Ludusavi.addManifestToLudusaviConfig(); Ludusavi.addManifestToLudusaviConfig();
@ -126,7 +122,8 @@ const migrateFromSqlite = async () => {
.select("*") .select("*")
.then(async (userPreferences) => { .then(async (userPreferences) => {
if (userPreferences.length > 0) { if (userPreferences.length > 0) {
const { realDebridApiToken, allDebridApiKey, ...rest } = userPreferences[0]; const { realDebridApiToken, allDebridApiKey, ...rest } =
userPreferences[0];
await db.put<string, UserPreferences>( await db.put<string, UserPreferences>(
levelKeys.userPreferences, levelKeys.userPreferences,

View file

@ -43,8 +43,8 @@ export class AllDebridClient {
baseURL: this.baseURL, baseURL: this.baseURL,
params: { params: {
agent: "hydra", agent: "hydra",
apikey: apiKey apikey: apiKey,
} },
}); });
} }
@ -81,7 +81,10 @@ export class AllDebridClient {
return { error_code: "alldebrid_invalid_response" }; return { error_code: "alldebrid_invalid_response" };
} }
logger.info("[AllDebrid] Successfully got user:", response.data.data.user.username); logger.info(
"[AllDebrid] Successfully got user:",
response.data.data.user.username
);
return { user: response.data.data.user }; return { user: response.data.data.user };
} catch (error: any) { } catch (error: any) {
logger.error("[AllDebrid] Request Error:", error); logger.error("[AllDebrid] Request Error:", error);
@ -98,18 +101,24 @@ export class AllDebridClient {
const response = await this.instance.get("/magnet/upload", { const response = await this.instance.get("/magnet/upload", {
params: { params: {
magnets: [magnet] magnets: [magnet],
} },
}); });
logger.info("[AllDebrid] Upload Magnet Raw Response:", JSON.stringify(response.data, null, 2)); logger.info(
"[AllDebrid] Upload Magnet Raw Response:",
JSON.stringify(response.data, null, 2)
);
if (response.data.status === "error") { if (response.data.status === "error") {
throw new Error(response.data.error?.message || "Unknown error"); throw new Error(response.data.error?.message || "Unknown error");
} }
const magnetInfo = response.data.data.magnets[0]; const magnetInfo = response.data.data.magnets[0];
logger.info("[AllDebrid] Magnet Info:", JSON.stringify(magnetInfo, null, 2)); logger.info(
"[AllDebrid] Magnet Info:",
JSON.stringify(magnetInfo, null, 2)
);
if (magnetInfo.error) { if (magnetInfo.error) {
throw new Error(magnetInfo.error.message); throw new Error(magnetInfo.error.message);
@ -122,17 +131,22 @@ export class AllDebridClient {
} }
} }
private static async checkMagnetStatus(magnetId: number): Promise<AllDebridMagnetStatus> { private static async checkMagnetStatus(
magnetId: number
): Promise<AllDebridMagnetStatus> {
try { try {
logger.info("[AllDebrid] Checking magnet status for ID:", magnetId); logger.info("[AllDebrid] Checking magnet status for ID:", magnetId);
const response = await this.instance.get(`/magnet/status`, { const response = await this.instance.get(`/magnet/status`, {
params: { params: {
id: magnetId id: magnetId,
} },
}); });
logger.info("[AllDebrid] Check Magnet Status Raw Response:", JSON.stringify(response.data, null, 2)); logger.info(
"[AllDebrid] Check Magnet Status Raw Response:",
JSON.stringify(response.data, null, 2)
);
if (!response.data) { if (!response.data) {
throw new Error("No response data received"); throw new Error("No response data received");
@ -144,8 +158,11 @@ export class AllDebridClient {
// Verificăm noua structură a răspunsului // Verificăm noua structură a răspunsului
const magnetData = response.data.data?.magnets; const magnetData = response.data.data?.magnets;
if (!magnetData || typeof magnetData !== 'object') { if (!magnetData || typeof magnetData !== "object") {
logger.error("[AllDebrid] Invalid response structure:", JSON.stringify(response.data, null, 2)); logger.error(
"[AllDebrid] Invalid response structure:",
JSON.stringify(response.data, null, 2)
);
throw new Error("Invalid magnet status response format"); throw new Error("Invalid magnet status response format");
} }
@ -163,14 +180,17 @@ export class AllDebridClient {
uploadSpeed: magnetData.uploadSpeed, uploadSpeed: magnetData.uploadSpeed,
uploadDate: magnetData.uploadDate, uploadDate: magnetData.uploadDate,
completionDate: magnetData.completionDate, completionDate: magnetData.completionDate,
links: magnetData.links.map(link => ({ links: magnetData.links.map((link) => ({
link: link.link, link: link.link,
filename: link.filename, filename: link.filename,
size: link.size size: link.size,
})) })),
}; };
logger.info("[AllDebrid] Magnet Status:", JSON.stringify(magnetStatus, null, 2)); logger.info(
"[AllDebrid] Magnet Status:",
JSON.stringify(magnetStatus, null, 2)
);
return magnetStatus; return magnetStatus;
} catch (error: any) { } catch (error: any) {
@ -187,8 +207,8 @@ export class AllDebridClient {
error?: AllDebridError; error?: AllDebridError;
}>("/link/unlock", { }>("/link/unlock", {
params: { params: {
link link,
} },
}); });
if (response.data.status === "error") { if (response.data.status === "error") {
@ -207,7 +227,9 @@ export class AllDebridClient {
} }
} }
public static async getDownloadUrls(uri: string): Promise<AllDebridDownloadUrl[]> { public static async getDownloadUrls(
uri: string
): Promise<AllDebridDownloadUrl[]> {
try { try {
logger.info("[AllDebrid] Getting download URLs for URI:", uri); logger.info("[AllDebrid] Getting download URLs for URI:", uri);
@ -223,45 +245,64 @@ export class AllDebridClient {
do { do {
magnetStatus = await this.checkMagnetStatus(magnetId); magnetStatus = await this.checkMagnetStatus(magnetId);
logger.info("[AllDebrid] Magnet status:", magnetStatus.status, "statusCode:", magnetStatus.statusCode); logger.info(
"[AllDebrid] Magnet status:",
magnetStatus.status,
"statusCode:",
magnetStatus.statusCode
);
if (magnetStatus.statusCode === 4) { // Ready if (magnetStatus.statusCode === 4) {
// Ready
// Deblocăm fiecare link în parte și aruncăm eroare dacă oricare eșuează // Deblocăm fiecare link în parte și aruncăm eroare dacă oricare eșuează
const unlockedLinks = await Promise.all( const unlockedLinks = await Promise.all(
magnetStatus.links.map(async link => { magnetStatus.links.map(async (link) => {
try { try {
const unlockedLink = await this.unlockLink(link.link); const unlockedLink = await this.unlockLink(link.link);
logger.info("[AllDebrid] Successfully unlocked link:", unlockedLink); logger.info(
"[AllDebrid] Successfully unlocked link:",
unlockedLink
);
return { return {
link: unlockedLink, link: unlockedLink,
size: link.size, size: link.size,
filename: link.filename filename: link.filename,
}; };
} catch (error) { } catch (error) {
logger.error("[AllDebrid] Failed to unlock link:", link.link, error); logger.error(
"[AllDebrid] Failed to unlock link:",
link.link,
error
);
throw new Error("Failed to unlock all links"); throw new Error("Failed to unlock all links");
} }
}) })
); );
logger.info("[AllDebrid] Got unlocked download links:", unlockedLinks); logger.info(
"[AllDebrid] Got unlocked download links:",
unlockedLinks
);
return unlockedLinks; return unlockedLinks;
} }
if (retries++ > 30) { // Maximum 30 de încercări if (retries++ > 30) {
// Maximum 30 de încercări
throw new Error("Timeout waiting for magnet to be ready"); throw new Error("Timeout waiting for magnet to be ready");
} }
await new Promise(resolve => setTimeout(resolve, 2000)); // Așteptăm 2 secunde între verificări await new Promise((resolve) => setTimeout(resolve, 2000)); // Așteptăm 2 secunde între verificări
} while (true); } while (true);
} else { } else {
logger.info("[AllDebrid] Regular link, unlocking..."); logger.info("[AllDebrid] Regular link, unlocking...");
// Pentru link-uri normale, doar debridam link-ul // Pentru link-uri normale, doar debridam link-ul
const downloadUrl = await this.unlockLink(uri); const downloadUrl = await this.unlockLink(uri);
logger.info("[AllDebrid] Got unlocked download URL:", downloadUrl); logger.info("[AllDebrid] Got unlocked download URL:", downloadUrl);
return [{ return [
link: downloadUrl {
}]; link: downloadUrl,
},
];
} }
} catch (error: any) { } catch (error: any) {
logger.error("[AllDebrid] Get Download URLs Error:", error); logger.error("[AllDebrid] Get Download URLs Error:", error);

View file

@ -17,17 +17,6 @@ import { db, downloadsSublevel, gamesSublevel, levelKeys } from "@main/level";
import { sortBy } from "lodash-es"; import { sortBy } from "lodash-es";
import { TorBoxClient } from "./torbox"; import { TorBoxClient } from "./torbox";
import { AllDebridClient } from "./all-debrid"; import { AllDebridClient } from "./all-debrid";
import { spawn } from "child_process";
interface GamePayload {
action: string;
game_id: string;
url: string | string[];
save_path: string;
header?: string;
out?: string;
total_size?: number;
}
export class DownloadManager { export class DownloadManager {
private static downloadingGameId: string | null = null; private static downloadingGameId: string | null = null;
@ -44,6 +33,7 @@ export class DownloadManager {
}) })
: undefined, : undefined,
downloadsToSeed?.map((download) => ({ downloadsToSeed?.map((download) => ({
action: "seed",
game_id: levelKeys.game(download.shop, download.objectId), game_id: levelKeys.game(download.shop, download.objectId),
url: download.uri, url: download.uri,
save_path: download.downloadPath, save_path: download.downloadPath,
@ -145,18 +135,48 @@ export class DownloadManager {
if (progress === 1 && download) { if (progress === 1 && download) {
publishDownloadCompleteNotification(game); publishDownloadCompleteNotification(game);
await downloadsSublevel.put(gameId, { if (
userPreferences?.seedAfterDownloadComplete &&
download.downloader === Downloader.Torrent
) {
downloadsSublevel.put(gameId, {
...download,
status: "seeding",
shouldSeed: true,
queued: false,
});
} else {
downloadsSublevel.put(gameId, {
...download, ...download,
status: "complete", status: "complete",
shouldSeed: false, shouldSeed: false,
queued: false, queued: false,
}); });
await this.cancelDownload(gameId); this.cancelDownload(gameId);
}
const downloads = await downloadsSublevel
.values()
.all()
.then((games) => {
return sortBy(
games.filter((game) => game.status === "paused" && game.queued),
"timestamp",
"DESC"
);
});
const [nextItemOnQueue] = downloads;
if (nextItemOnQueue) {
this.resumeDownload(nextItemOnQueue);
} else {
this.downloadingGameId = null; this.downloadingGameId = null;
} }
} }
} }
}
public static async getSeedStatus() { public static async getSeedStatus() {
const seedStatus = await PythonRPC.rpc const seedStatus = await PythonRPC.rpc
@ -296,6 +316,21 @@ export class DownloadManager {
save_path: download.downloadPath, save_path: download.downloadPath,
}; };
} }
case Downloader.AllDebrid: {
const downloadUrls = await AllDebridClient.getDownloadUrls(download.uri);
if (!downloadUrls.length) throw new Error(DownloadError.NotCachedInAllDebrid);
const totalSize = downloadUrls.reduce((total, url) => total + (url.size || 0), 0);
return {
action: "start",
game_id: downloadId,
url: downloadUrls.map(d => d.link),
save_path: download.downloadPath,
total_size: totalSize
};
}
case Downloader.Torrent: case Downloader.Torrent:
return { return {
action: "start", action: "start",
@ -315,21 +350,6 @@ export class DownloadManager {
save_path: download.downloadPath, save_path: download.downloadPath,
}; };
} }
case Downloader.AllDebrid: {
const downloadUrls = await AllDebridClient.getDownloadUrls(download.uri);
if (!downloadUrls.length) throw new Error(DownloadError.NotCachedInAllDebrid);
const totalSize = downloadUrls.reduce((total, url) => total + (url.size || 0), 0);
return {
action: "start",
game_id: downloadId,
url: downloadUrls.map(d => d.link),
save_path: download.downloadPath,
total_size: totalSize
};
}
case Downloader.TorBox: { case Downloader.TorBox: {
const { name, url } = await TorBoxClient.getDownloadInfo(download.uri); const { name, url } = await TorBoxClient.getDownloadInfo(download.uri);

View file

@ -10,9 +10,13 @@ import { Readable } from "node:stream";
import { app, dialog } from "electron"; import { app, dialog } from "electron";
interface GamePayload { interface GamePayload {
action: string;
game_id: string; game_id: string;
url: string; url: string | string[];
save_path: string; save_path: string;
header?: string;
out?: string;
total_size?: number;
} }
const binaryNameByPlatform: Partial<Record<NodeJS.Platform, string>> = { const binaryNameByPlatform: Partial<Record<NodeJS.Platform, string>> = {

View file

@ -29,6 +29,7 @@ import type {
LibraryGame, LibraryGame,
GameRunning, GameRunning,
TorBoxUser, TorBoxUser,
AllDebridUser,
} from "@types"; } from "@types";
import type { AxiosProgressEvent } from "axios"; import type { AxiosProgressEvent } from "axios";
import type disk from "diskusage"; import type disk from "diskusage";
@ -150,6 +151,7 @@ declare global {
minimized: boolean; minimized: boolean;
}) => Promise<void>; }) => Promise<void>;
authenticateRealDebrid: (apiToken: string) => Promise<RealDebridUser>; authenticateRealDebrid: (apiToken: string) => Promise<RealDebridUser>;
authenticateAllDebrid: (apiKey: string) => Promise<AllDebridUser | { error_code: string }>;
authenticateTorBox: (apiToken: string) => Promise<TorBoxUser>; authenticateTorBox: (apiToken: string) => Promise<TorBoxUser>;
onAchievementUnlocked: (cb: () => void) => () => Electron.IpcRenderer; onAchievementUnlocked: (cb: () => void) => () => Electron.IpcRenderer;

View file

@ -196,7 +196,6 @@ export function HeroPanelActions() {
{game.favorite ? <HeartFillIcon /> : <HeartIcon />} {game.favorite ? <HeartFillIcon /> : <HeartIcon />}
</Button> </Button>
<Button <Button
onClick={() => setShowGameOptionsModal(true)} onClick={() => setShowGameOptionsModal(true)}
theme="outline" theme="outline"

View file

@ -176,7 +176,6 @@ export function DownloadSettingsModal({
} }
onClick={() => setSelectedDownloader(downloader)} onClick={() => setSelectedDownloader(downloader)}
> >
{selectedDownloader === downloader && ( {selectedDownloader === downloader && (
<CheckCircleFillIcon className="download-settings-modal__downloader-icon" /> <CheckCircleFillIcon className="download-settings-modal__downloader-icon" />
)} )}

View file

@ -53,7 +53,7 @@ export function SettingsAllDebrid() {
form.allDebridApiKey form.allDebridApiKey
); );
if ('error_code' in result) { if ("error_code" in result) {
showErrorToast(t(result.error_code)); showErrorToast(t(result.error_code));
return; return;
} }

View file

@ -95,7 +95,12 @@ export const getDownloadersForUri = (uri: string) => {
return [Downloader.RealDebrid]; return [Downloader.RealDebrid];
if (uri.startsWith("magnet:")) { if (uri.startsWith("magnet:")) {
return [Downloader.Torrent, Downloader.TorBox, Downloader.RealDebrid, Downloader.AllDebrid]; return [
Downloader.Torrent,
Downloader.TorBox,
Downloader.RealDebrid,
Downloader.AllDebrid,
];
} }
return []; return [];