hydra/src/main/services/process-watcher.ts

83 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-04-18 10:46:06 +03:00
import path from "node:path";
import { IsNull, Not } from "typeorm";
import { exec } from "child_process"
2024-04-18 10:46:06 +03:00
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));
export const startProcessWatcher = async () => {
const sleepTime = 100;
const gamesPlaytime = new Map<number, number>();
// eslint-disable-next-line no-constant-condition
while (true) {
await sleep(sleepTime);
2024-04-24 03:42:35 +03:00
console.log("loopTotalTime")
2024-04-18 10:46:06 +03:00
const games = await gameRepository.find({
where: {
executablePath: Not(IsNull()),
},
});
if (games.length == 0) {
continue;
}
console.time("getProcesses")
2024-04-18 10:46:06 +03:00
const processes = await getProcesses();
console.timeEnd("getProcesses")
2024-04-18 10:46:06 +03:00
for (const game of games) {
2024-04-24 03:42:35 +03:00
const basename = path.win32.basename(game.executablePath);
2024-04-18 10:46:06 +03:00
const basenameWithoutExtension = path.win32.basename(
game.executablePath,
path.extname(game.executablePath)
);
2024-04-24 03:42:35 +03:00
const gameProcess = processes.find((runningProcess) => {
2024-04-18 10:46:06 +03:00
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);
const delta = performance.now() - zero;
if (WindowManager.mainWindow) {
WindowManager.mainWindow.webContents.send("on-playtime", game.id);
}
2024-04-18 10:46:06 +03:00
await gameRepository.update(game.id, {
playTimeInMilliseconds: game.playTimeInMilliseconds + delta,
});
2024-04-20 19:11:35 +03:00
gameRepository.update(game.id, {
lastTimePlayed: new Date().toUTCString(),
});
2024-04-18 10:46:06 +03:00
}
gamesPlaytime.set(game.id, performance.now());
continue;
}
if (gamesPlaytime.has(game.id)) {
gamesPlaytime.delete(game.id);
if (WindowManager.mainWindow) {
WindowManager.mainWindow.webContents.send("on-game-close", game.id);
}
2024-04-18 10:46:06 +03:00
}
}
}
};