feat: get process list from rpc

This commit is contained in:
Zamitto 2024-07-03 11:23:50 -03:00
parent 0c1a75eedd
commit 75c8f69e81
10 changed files with 57 additions and 49 deletions

View File

@ -1,6 +1,6 @@
import { registerEvent } from "../register-event"; import { registerEvent } from "../register-event";
import * as Sentry from "@sentry/electron/main"; import * as Sentry from "@sentry/electron/main";
import { HydraApi, TorrentDownloader, gamesPlaytime } from "@main/services"; import { HydraApi, RPCManager, gamesPlaytime } from "@main/services";
import { dataSource } from "@main/data-source"; import { dataSource } from "@main/data-source";
import { DownloadQueue, Game, UserAuth } from "@main/entity"; import { DownloadQueue, Game, UserAuth } from "@main/entity";
@ -24,7 +24,7 @@ const signOut = async (_event: Electron.IpcMainInvokeEvent) => {
Sentry.setUser(null); Sentry.setUser(null);
/* Disconnects libtorrent */ /* Disconnects libtorrent */
TorrentDownloader.kill(); RPCManager.kill();
await Promise.all([ await Promise.all([
databaseOperations, databaseOperations,

View File

@ -5,7 +5,7 @@ import i18n from "i18next";
import path from "node:path"; import path from "node:path";
import url from "node:url"; import url from "node:url";
import { electronApp, optimizer } from "@electron-toolkit/utils"; import { electronApp, optimizer } from "@electron-toolkit/utils";
import { logger, TorrentDownloader, WindowManager } from "@main/services"; import { logger, RPCManager, WindowManager } from "@main/services";
import { dataSource } from "@main/data-source"; import { dataSource } from "@main/data-source";
import * as resources from "@locales"; import * as resources from "@locales";
import { userPreferencesRepository } from "@main/repository"; import { userPreferencesRepository } from "@main/repository";
@ -116,7 +116,7 @@ app.on("window-all-closed", () => {
app.on("before-quit", () => { app.on("before-quit", () => {
/* Disconnects libtorrent */ /* Disconnects libtorrent */
TorrentDownloader.kill(); RPCManager.kill();
}); });
app.on("activate", () => { app.on("activate", () => {

View File

@ -1,4 +1,9 @@
import { DownloadManager, RepacksManager, startMainLoop } from "./services"; import {
DownloadManager,
RepacksManager,
RPCManager,
startMainLoop,
} from "./services";
import { import {
downloadQueueRepository, downloadQueueRepository,
repackRepository, repackRepository,
@ -12,8 +17,6 @@ import { MoreThan } from "typeorm";
import { HydraApi } from "./services/hydra-api"; import { HydraApi } from "./services/hydra-api";
import { uploadGamesBatch } from "./services/library-sync"; import { uploadGamesBatch } from "./services/library-sync";
startMainLoop();
const loadState = async (userPreferences: UserPreferences | null) => { const loadState = async (userPreferences: UserPreferences | null) => {
await RepacksManager.updateRepacks(); await RepacksManager.updateRepacks();
@ -35,8 +38,13 @@ const loadState = async (userPreferences: UserPreferences | null) => {
}, },
}); });
if (nextQueueItem?.game.status === "active") if (nextQueueItem?.game.status === "active") {
DownloadManager.startDownload(nextQueueItem.game); DownloadManager.startDownload(nextQueueItem.game);
} else {
RPCManager.spawn();
}
startMainLoop();
const now = new Date(); const now = new Date();

View File

@ -1,6 +1,6 @@
import { Game } from "@main/entity"; import { Game } from "@main/entity";
import { Downloader } from "@shared"; import { Downloader } from "@shared";
import { TorrentDownloader } from "./torrent-downloader"; import { RPCManager } from "./rpc-manager";
import { WindowManager } from "../window-manager"; import { WindowManager } from "../window-manager";
import { downloadQueueRepository, gameRepository } from "@main/repository"; import { downloadQueueRepository, gameRepository } from "@main/repository";
import { publishDownloadCompleteNotification } from "../notifications"; import { publishDownloadCompleteNotification } from "../notifications";
@ -16,7 +16,7 @@ export class DownloadManager {
if (this.currentDownloader === Downloader.RealDebrid) { if (this.currentDownloader === Downloader.RealDebrid) {
status = await RealDebridDownloader.getStatus(); status = await RealDebridDownloader.getStatus();
} else { } else {
status = await TorrentDownloader.getStatus(); status = await RPCManager.getStatus();
} }
if (status) { if (status) {
@ -65,7 +65,7 @@ export class DownloadManager {
if (this.currentDownloader === Downloader.RealDebrid) { if (this.currentDownloader === Downloader.RealDebrid) {
RealDebridDownloader.pauseDownload(); RealDebridDownloader.pauseDownload();
} else { } else {
await TorrentDownloader.pauseDownload(); await RPCManager.pauseDownload();
} }
WindowManager.mainWindow?.setProgressBar(-1); WindowManager.mainWindow?.setProgressBar(-1);
@ -77,7 +77,7 @@ export class DownloadManager {
RealDebridDownloader.startDownload(game); RealDebridDownloader.startDownload(game);
this.currentDownloader = Downloader.RealDebrid; this.currentDownloader = Downloader.RealDebrid;
} else { } else {
TorrentDownloader.startDownload(game); RPCManager.startDownload(game);
this.currentDownloader = Downloader.Torrent; this.currentDownloader = Downloader.Torrent;
} }
} }
@ -86,7 +86,7 @@ export class DownloadManager {
if (this.currentDownloader === Downloader.RealDebrid) { if (this.currentDownloader === Downloader.RealDebrid) {
RealDebridDownloader.cancelDownload(); RealDebridDownloader.cancelDownload();
} else { } else {
TorrentDownloader.cancelDownload(gameId); RPCManager.cancelDownload(gameId);
} }
WindowManager.mainWindow?.setProgressBar(-1); WindowManager.mainWindow?.setProgressBar(-1);
@ -98,7 +98,7 @@ export class DownloadManager {
RealDebridDownloader.startDownload(game); RealDebridDownloader.startDownload(game);
this.currentDownloader = Downloader.RealDebrid; this.currentDownloader = Downloader.RealDebrid;
} else { } else {
TorrentDownloader.startDownload(game); RPCManager.startDownload(game);
this.currentDownloader = Downloader.Torrent; this.currentDownloader = Downloader.Torrent;
} }
} }

View File

@ -1,2 +1,2 @@
export * from "./download-manager"; export * from "./download-manager";
export * from "./torrent-downloader"; export * from "./rpc-manager";

View File

@ -15,8 +15,8 @@ import {
LibtorrentPayload, LibtorrentPayload,
} from "./types"; } from "./types";
export class TorrentDownloader { export class RPCManager {
private static torrentClient: cp.ChildProcess | null = null; private static rpcProcess: cp.ChildProcess | null = null;
private static downloadingGameId = -1; private static downloadingGameId = -1;
private static rpc = axios.create({ private static rpc = axios.create({
@ -26,18 +26,22 @@ export class TorrentDownloader {
}, },
}); });
private static spawn(args: StartDownloadPayload) { public static spawn(args?: StartDownloadPayload) {
this.torrentClient = startTorrentClient(args); this.rpcProcess = startTorrentClient(args);
} }
public static kill() { public static kill() {
if (this.torrentClient) { if (this.rpcProcess) {
this.torrentClient.kill(); this.rpcProcess.kill();
this.torrentClient = null; this.rpcProcess = null;
this.downloadingGameId = -1; this.downloadingGameId = -1;
} }
} }
public static async getProccessList() {
return (await this.rpc.get<string[] | null>("/process-list")).data;
}
public static async getStatus() { public static async getStatus() {
if (this.downloadingGameId === -1) return null; if (this.downloadingGameId === -1) return null;
@ -113,7 +117,7 @@ export class TorrentDownloader {
} }
static async startDownload(game: Game) { static async startDownload(game: Game) {
if (!this.torrentClient) { if (!this.rpcProcess) {
this.spawn({ this.spawn({
game_id: game.id, game_id: game.id,
magnet: game.uri!, magnet: game.uri!,

View File

@ -15,12 +15,12 @@ export const BITTORRENT_PORT = "5881";
export const RPC_PORT = "8084"; export const RPC_PORT = "8084";
export const RPC_PASSWORD = crypto.randomBytes(32).toString("hex"); export const RPC_PASSWORD = crypto.randomBytes(32).toString("hex");
export const startTorrentClient = (args: StartDownloadPayload) => { export const startTorrentClient = (args?: StartDownloadPayload) => {
const commonArgs = [ const commonArgs = [
BITTORRENT_PORT, BITTORRENT_PORT,
RPC_PORT, RPC_PORT,
RPC_PASSWORD, RPC_PASSWORD,
encodeURIComponent(JSON.stringify(args)), args ? encodeURIComponent(JSON.stringify(args)) : "",
]; ];
if (app.isPackaged) { if (app.isPackaged) {

View File

@ -1,11 +1,9 @@
import path from "node:path";
import { IsNull, Not } from "typeorm"; import { IsNull, Not } from "typeorm";
import { gameRepository } from "@main/repository"; import { gameRepository } from "@main/repository";
import { getProcesses } from "@main/helpers";
import { WindowManager } from "./window-manager"; import { WindowManager } from "./window-manager";
import { createGame, updateGamePlaytime } from "./library-sync"; import { createGame, updateGamePlaytime } from "./library-sync";
import { GameRunning } from "@types"; import { GameRunning } from "@types";
import { RPCManager } from "./download";
export const gamesPlaytime = new Map< export const gamesPlaytime = new Map<
number, number,
@ -22,22 +20,13 @@ export const watchProcesses = async () => {
if (games.length === 0) return; if (games.length === 0) return;
const processes = await getProcesses(); const processes = (await RPCManager.getProccessList()) || [];
for (const game of games) { for (const game of games) {
const executablePath = game.executablePath!; const executablePath = game.executablePath!;
const basename = path.win32.basename(executablePath);
const basenameWithoutExtension = path.win32.basename(
executablePath,
path.extname(executablePath)
);
const gameProcess = processes.find((runningProcess) => { const gameProcess = processes.find((runningProcess) => {
if (process.platform === "win32") { return executablePath == runningProcess;
return runningProcess.name === basename;
}
return [basename, basenameWithoutExtension].includes(runningProcess.name);
}); });
if (gameProcess) { if (gameProcess) {

View File

@ -122,7 +122,7 @@ export function HeroPanelActions() {
<Button <Button
onClick={() => setShowGameOptionsModal(true)} onClick={() => setShowGameOptionsModal(true)}
theme="outline" theme="outline"
disabled={deleting || isGameRunning} disabled={deleting}
className={styles.heroPanelAction} className={styles.heroPanelAction}
> >
<GearIcon /> <GearIcon />

View File

@ -4,15 +4,16 @@ import json
import urllib.parse import urllib.parse
import psutil import psutil
from downloader import Downloader from downloader import Downloader
from time import time
torrent_port = sys.argv[1] torrent_port = sys.argv[1]
http_port = sys.argv[2] http_port = sys.argv[2]
rpc_password = sys.argv[3] rpc_password = sys.argv[3]
downloader = None
if sys.argv[4]:
initial_download = json.loads(urllib.parse.unquote(sys.argv[4])) initial_download = json.loads(urllib.parse.unquote(sys.argv[4]))
downloader = Downloader(torrent_port) downloader = Downloader(torrent_port)
downloader.start_download(initial_download['game_id'], initial_download['magnet'], initial_download['save_path']) downloader.start_download(initial_download['game_id'], initial_download['magnet'], initial_download['save_path'])
class Handler(BaseHTTPRequestHandler): class Handler(BaseHTTPRequestHandler):
@ -36,14 +37,17 @@ class Handler(BaseHTTPRequestHandler):
self.send_response(200) self.send_response(200)
self.end_headers() self.end_headers()
if self.path == "/process": if self.path == "/process-list":
start_time = time() if self.headers.get(self.rpc_password_header) != rpc_password:
process_path = set([proc.info["exe"] for proc in psutil.process_iter(['exe'])]) self.send_response(401)
self.end_headers()
return
process_path = list(set([proc.info["exe"] for proc in psutil.process_iter(['exe'])]))
self.send_response(200) self.send_response(200)
self.send_header("Content-type", "application/json") self.send_header("Content-type", "application/json")
self.end_headers() self.end_headers()
self.wfile.write(json.dumps(list(process_path)).encode('utf-8')) self.wfile.write(json.dumps(process_path).encode('utf-8'))
print(time() - start_time)
def do_POST(self): def do_POST(self):
if self.path == "/action": if self.path == "/action":
@ -56,6 +60,9 @@ class Handler(BaseHTTPRequestHandler):
post_data = self.rfile.read(content_length) post_data = self.rfile.read(content_length)
data = json.loads(post_data.decode('utf-8')) data = json.loads(post_data.decode('utf-8'))
if downloader is None:
downloader = Downloader(torrent_port)
if data['action'] == 'start': if data['action'] == 'start':
downloader.start_download(data['game_id'], data['magnet'], data['save_path']) downloader.start_download(data['game_id'], data['magnet'], data['save_path'])
elif data['action'] == 'pause': elif data['action'] == 'pause':