This commit is contained in:
lilezek
2024-04-30 10:01:52 +02:00
156 changed files with 2841 additions and 7759 deletions

View File

@@ -15,7 +15,7 @@ import { databasePath } from "./constants";
export const createDataSource = (options: Partial<SqliteConnectionOptions>) =>
new DataSource({
type: "sqlite",
type: "better-sqlite3",
database: databasePath,
entities: [
Game,

View File

@@ -44,7 +44,7 @@ export class Game {
shop: GameShop;
@Column("text", { nullable: true })
status: GameStatus | "";
status: GameStatus | null;
/**
* Progress is a float between 0 and 1

View File

@@ -9,7 +9,7 @@ const steamGames = stateManager.getValue("steamGames");
const getGames = async (
_event: Electron.IpcMainInvokeEvent,
take?: number,
take = 12,
cursor = 0
): Promise<{ results: CatalogueEntry[]; cursor: number }> => {
const results: CatalogueEntry[] = [];

View File

@@ -1,27 +1,40 @@
import shuffle from "lodash/shuffle";
import { shuffle } from "lodash-es";
import { getRandomSteam250List } from "@main/services";
import { Steam250Game, getSteam250List } from "@main/services";
import { registerEvent } from "../register-event";
import { searchGames, searchRepacks } from "../helpers/search-games";
import { formatName } from "@main/helpers";
const state = { games: Array<Steam250Game>(), index: 0 };
const getRandomGame = async (_event: Electron.IpcMainInvokeEvent) => {
return getRandomSteam250List().then(async (games) => {
const shuffledList = shuffle(games);
if (state.games.length == 0) {
const steam250List = await getSteam250List();
for (const game of shuffledList) {
const repacks = searchRepacks(formatName(game.title));
const filteredSteam250List = steam250List.filter((game) => {
const repacks = searchRepacks(game.title);
const catalogue = searchGames({ query: game.title });
if (repacks.length) {
const results = await searchGames({ query: game.title });
return repacks.length && catalogue.length;
});
if (results.length) {
return results[0].objectID;
}
}
}
});
state.games = shuffle(filteredSteam250List);
}
if (state.games.length == 0) {
return "";
}
const resultObjectId = state.games[state.index].objectID;
state.index += 1;
if (state.index == state.games.length) {
state.index = 0;
state.games = shuffle(state.games);
}
return resultObjectId;
};
registerEvent(getRandomGame, {

View File

@@ -1,11 +1,15 @@
import { registerEvent } from "../register-event";
import { searchGames } from "../helpers/search-games";
import { CatalogueEntry } from "@types";
registerEvent(
(_event: Electron.IpcMainInvokeEvent, query: string) =>
searchGames({ query, take: 12 }),
{
name: "searchGames",
memoize: true,
}
);
const searchGamesEvent = async (
_event: Electron.IpcMainInvokeEvent,
query: string
): Promise<CatalogueEntry[]> => {
return searchGames({ query, take: 12 });
};
registerEvent(searchGamesEvent, {
name: "searchGames",
memoize: true,
});

View File

@@ -1,5 +1,5 @@
import flexSearch from "flexsearch";
import orderBy from "lodash/orderBy";
import { orderBy } from "lodash-es";
import type { GameRepack, GameShop, CatalogueEntry } from "@types";
@@ -42,11 +42,11 @@ export interface SearchGamesArgs {
skip?: number;
}
export const searchGames = async ({
export const searchGames = ({
query,
take,
skip,
}: SearchGamesArgs): Promise<CatalogueEntry[]> => {
}: SearchGamesArgs): CatalogueEntry[] => {
const results = steamGamesIndex
.search(formatName(query || ""), { limit: take, offset: skip })
.map((index) => {
@@ -61,11 +61,9 @@ export const searchGames = async ({
};
});
return Promise.all(results).then((resultsWithRepacks) =>
orderBy(
resultsWithRepacks,
[({ repacks }) => repacks.length, "repacks"],
["desc"]
)
return orderBy(
results,
[({ repacks }) => repacks.length, "repacks"],
["desc"]
);
};

View File

@@ -10,12 +10,13 @@ import "./catalogue/search-games";
import "./hardware/get-disk-free-space";
import "./library/add-game-to-library";
import "./library/close-game";
import "./torrenting/delete-game-folder";
import "./library/delete-game-folder";
import "./library/get-game-by-object-id";
import "./library/get-library";
import "./library/get-repackers-friendly-names";
import "./library/open-game";
import "./library/open-game-installer";
import "./library/remove-game";
import "./library/remove-game-from-library";
import "./misc/get-or-cache-image";
import "./misc/open-external";
@@ -24,7 +25,6 @@ import "./torrenting/cancel-game-download";
import "./torrenting/pause-game-download";
import "./torrenting/resume-game-download";
import "./torrenting/start-game-download";
import "./torrenting/remove-game-from-download";
import "./user-preferences/get-user-preferences";
import "./user-preferences/update-user-preferences";

View File

@@ -1,9 +1,9 @@
import path from "node:path";
import { gameRepository } from "@main/repository";
import { getProcesses } from "@main/helpers";
import { registerEvent } from "../register-event";
import { getProcesses } from "@main/helpers";
const closeGame = async (
_event: Electron.IpcMainInvokeEvent,
@@ -12,13 +12,17 @@ const closeGame = async (
const processes = await getProcesses();
const game = await gameRepository.findOne({ where: { id: gameId } });
const gameProcess = processes.find((runningProcess) => {
const basename = path.win32.basename(game.executablePath);
const basenameWithoutExtension = path.win32.basename(
game.executablePath,
path.extname(game.executablePath)
);
if (!game) return false;
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;
}

View File

@@ -2,10 +2,10 @@ import { gameRepository } from "@main/repository";
import { searchRepacks } from "../helpers/search-games";
import { registerEvent } from "../register-event";
import sortBy from "lodash/sortBy";
import { GameStatus } from "@globals";
import { sortBy } from "lodash-es";
const getLibrary = async (_event: Electron.IpcMainInvokeEvent) =>
const getLibrary = async () =>
gameRepository
.find({
where: {

View File

@@ -1,7 +1,7 @@
import { registerEvent } from "../register-event";
import { stateManager } from "@main/state-manager";
const getRepackersFriendlyNames = async (_event: Electron.IpcMainInvokeEvent) =>
const getRepackersFriendlyNames = async () =>
stateManager.getValue("repackersFriendlyNames").reduce((prev, next) => {
return { ...prev, [next.name]: next.friendlyName };
}, {});

View File

@@ -1,25 +1,16 @@
import { GameStatus } from "@globals";
import { gameRepository } from "@main/repository";
import { registerEvent } from "../register-event";
import { gameRepository } from "../../repository";
import { GameStatus } from "@globals";
const removeGameFromDownload = async (
const removeGame = async (
_event: Electron.IpcMainInvokeEvent,
gameId: number
) => {
const game = await gameRepository.findOne({
where: {
await gameRepository.update(
{
id: gameId,
status: GameStatus.Cancelled,
},
});
if (!game) return;
gameRepository.update(
{
id: game.id,
},
{
status: null,
downloadPath: null,
@@ -29,6 +20,6 @@ const removeGameFromDownload = async (
);
};
registerEvent(removeGameFromDownload, {
name: "removeGameFromDownload",
registerEvent(removeGame, {
name: "removeGame",
});

View File

@@ -25,7 +25,7 @@ const pauseGameDownload = async (
.then((result) => {
if (result.affected) {
Downloader.pauseDownload();
WindowManager.mainWindow.setProgressBar(-1);
WindowManager.mainWindow?.setProgressBar(-1);
}
});
};

View File

@@ -1,7 +1,7 @@
import { userPreferencesRepository } from "@main/repository";
import { registerEvent } from "../register-event";
const getUserPreferences = async (_event: Electron.IpcMainInvokeEvent) =>
const getUserPreferences = async () =>
userPreferencesRepository.findOne({
where: { id: 1 },
});

View File

@@ -1,52 +1,68 @@
import { stateManager } from "./state-manager";
import { repackers } from "./constants";
import {
getNewGOGGames,
getNewRepacksFromCPG,
getNewRepacksFromUser,
getNewRepacksFromXatab,
// getNewRepacksFromOnlineFix,
readPipe,
startProcessWatcher,
writePipe,
} from "./services";
import {
gameRepository,
repackRepository,
repackerFriendlyNameRepository,
steamGameRepository,
userPreferencesRepository,
} from "./repository";
import { TorrentClient } from "./services/donwloaders/torrent-client";
import { Repack } from "./entity";
import { Notification } from "electron";
import { t } from "i18next";
import { In } from "typeorm";
import { Downloader } from "./services/donwloaders/downloader";
import { GameStatus } from "@globals";
import { app, BrowserWindow } from "electron";
import { init } from "@sentry/electron/main";
import i18n from "i18next";
import path from "node:path";
import { electronApp, optimizer } from "@electron-toolkit/utils";
import { resolveDatabaseUpdates, WindowManager } from "@main/services";
import { dataSource } from "@main/data-source";
import * as resources from "@locales";
import { userPreferencesRepository } from "@main/repository";
startProcessWatcher();
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) app.quit();
TorrentClient.startTorrentClient(writePipe.socketPath, readPipe.socketPath);
if (import.meta.env.MAIN_VITE_SENTRY_DSN) {
init({
dsn: import.meta.env.MAIN_VITE_SENTRY_DSN,
beforeSend: async (event) => {
const userPreferences = await userPreferencesRepository.findOne({
where: { id: 1 },
});
Promise.all([writePipe.createPipe(), readPipe.createPipe()]).then(async () => {
const game = await gameRepository.findOne({
where: {
status: In([
GameStatus.Downloading,
GameStatus.DownloadingMetadata,
GameStatus.CheckingFiles,
]),
if (userPreferences?.telemetryEnabled) return event;
return null;
},
relations: { repack: true },
});
}
if (game) {
Downloader.downloadGame(game, game.repack);
i18n.init({
resources,
lng: "en",
fallbackLng: "en",
interpolation: {
escapeValue: false,
},
});
const PROTOCOL = "hydralauncher";
if (process.defaultApp) {
if (process.argv.length >= 2) {
app.setAsDefaultProtocolClient(PROTOCOL, process.execPath, [
path.resolve(process.argv[1]),
]);
}
} else {
app.setAsDefaultProtocolClient(PROTOCOL);
}
readPipe.socket.on("data", (data) => {
TorrentClient.onSocketData(data);
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
electronApp.setAppUserModelId("site.hydralauncher.hydra");
dataSource.initialize().then(async () => {
await resolveDatabaseUpdates();
await import("./main");
const userPreferences = await userPreferencesRepository.findOne({
where: { id: 1 },
});
WindowManager.createMainWindow();
WindowManager.createSystemTray(userPreferences?.language || "en");
});
});
@@ -64,63 +80,49 @@ const checkForNewRepacks = async () => {
where: { id: 1 },
});
const existingRepacks = stateManager.getValue("repacks");
Promise.allSettled([
getNewGOGGames(
existingRepacks.filter((repack) => repack.repacker === "GOG")
),
getNewRepacksFromXatab(
existingRepacks.filter((repack) => repack.repacker === "Xatab")
),
getNewRepacksFromCPG(
existingRepacks.filter((repack) => repack.repacker === "CPG")
),
// getNewRepacksFromOnlineFix(
// existingRepacks.filter((repack) => repack.repacker === "onlinefix")
// ),
track1337xUsers(existingRepacks),
]).then(() => {
repackRepository.count().then((count) => {
const total = count - stateManager.getValue("repacks").length;
if (total > 0 && userPreferences?.repackUpdatesNotificationsEnabled) {
new Notification({
title: t("repack_list_updated", {
ns: "notifications",
lng: userPreferences?.language || "en",
}),
body: t("repack_count", {
ns: "notifications",
lng: userPreferences?.language || "en",
count: total,
}),
}).show();
}
});
WindowManager.createMainWindow();
WindowManager.createSystemTray(userPreferences?.language || "en");
});
};
});
const loadState = async () => {
const [friendlyNames, repacks, steamGames] = await Promise.all([
repackerFriendlyNameRepository.find(),
repackRepository.find({
order: {
createdAt: "desc",
},
}),
steamGameRepository.find({
order: {
name: "asc",
},
}),
]);
app.on("browser-window-created", (_, window) => {
optimizer.watchWindowShortcuts(window);
});
stateManager.setValue("repackersFriendlyNames", friendlyNames);
stateManager.setValue("repacks", repacks);
stateManager.setValue("steamGames", steamGames);
app.on("second-instance", (_event, commandLine) => {
// Someone tried to run a second instance, we should focus our window.
if (WindowManager.mainWindow) {
if (WindowManager.mainWindow.isMinimized())
WindowManager.mainWindow.restore();
import("./events");
};
WindowManager.mainWindow.focus();
} else {
WindowManager.createMainWindow();
}
loadState().then(() => checkForNewRepacks());
const [, path] = commandLine.pop().split("://");
if (path) WindowManager.redirect(path);
});
app.on("open-url", (_event, url) => {
const [, path] = url.split("://");
WindowManager.redirect(path);
});
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", () => {
WindowManager.mainWindow = null;
});
app.on("activate", () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
WindowManager.createMainWindow();
}
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.

129
src/main/main.ts Normal file
View File

@@ -0,0 +1,129 @@
import { stateManager } from "./state-manager";
import { GameStatus, repackers } from "./constants";
import {
getNewGOGGames,
getNewRepacksFromCPG,
getNewRepacksFromUser,
getNewRepacksFromXatab,
// getNewRepacksFromOnlineFix,
readPipe,
startProcessWatcher,
writePipe,
} from "./services";
import {
gameRepository,
repackRepository,
repackerFriendlyNameRepository,
steamGameRepository,
userPreferencesRepository,
} from "./repository";
import { TorrentClient } from "./services/torrent-client";
import { Repack } from "./entity";
import { Notification } from "electron";
import { t } from "i18next";
import { In } from "typeorm";
startProcessWatcher();
TorrentClient.startTorrentClient(writePipe.socketPath, readPipe.socketPath);
Promise.all([writePipe.createPipe(), readPipe.createPipe()]).then(async () => {
const game = await gameRepository.findOne({
where: {
status: In([
GameStatus.Downloading,
GameStatus.DownloadingMetadata,
GameStatus.CheckingFiles,
]),
},
relations: { repack: true },
});
if (game) {
writePipe.write({
action: "start",
game_id: game.id,
magnet: game.repack.magnet,
save_path: game.downloadPath,
});
}
readPipe.socket?.on("data", (data) => {
TorrentClient.onSocketData(data);
});
});
const track1337xUsers = async (existingRepacks: Repack[]) => {
for (const repacker of repackers) {
await getNewRepacksFromUser(
repacker,
existingRepacks.filter((repack) => repack.repacker === repacker)
);
}
};
const checkForNewRepacks = async () => {
const userPreferences = await userPreferencesRepository.findOne({
where: { id: 1 },
});
const existingRepacks = stateManager.getValue("repacks");
Promise.allSettled([
getNewGOGGames(
existingRepacks.filter((repack) => repack.repacker === "GOG")
),
getNewRepacksFromXatab(
existingRepacks.filter((repack) => repack.repacker === "Xatab")
),
getNewRepacksFromCPG(
existingRepacks.filter((repack) => repack.repacker === "CPG")
),
// getNewRepacksFromOnlineFix(
// existingRepacks.filter((repack) => repack.repacker === "onlinefix")
// ),
track1337xUsers(existingRepacks),
]).then(() => {
repackRepository.count().then((count) => {
const total = count - stateManager.getValue("repacks").length;
if (total > 0 && userPreferences?.repackUpdatesNotificationsEnabled) {
new Notification({
title: t("repack_list_updated", {
ns: "notifications",
lng: userPreferences?.language || "en",
}),
body: t("repack_count", {
ns: "notifications",
lng: userPreferences?.language || "en",
count: total,
}),
}).show();
}
});
});
};
const loadState = async () => {
const [friendlyNames, repacks, steamGames] = await Promise.all([
repackerFriendlyNameRepository.find(),
repackRepository.find({
order: {
createdAt: "desc",
},
}),
steamGameRepository.find({
order: {
name: "asc",
},
}),
]);
stateManager.setValue("repackersFriendlyNames", friendlyNames);
stateManager.setValue("repacks", repacks);
stateManager.setValue("steamGames", steamGames);
import("./events");
};
loadState().then(() => checkForNewRepacks());

View File

@@ -46,10 +46,9 @@ export class TorrentClient {
const commonArgs = [BITTORRENT_PORT, writePipePath, readPipePath];
if (app.isPackaged) {
const binaryName = binaryNameByPlatform[process.platform];
const binaryName = binaryNameByPlatform[process.platform]!;
const binaryPath = path.join(
process.resourcesPath,
"dist",
"hydra-download-manager",
binaryName
);

View File

@@ -28,10 +28,11 @@ export const startProcessWatcher = async () => {
const processes = await getProcesses();
for (const game of games) {
const basename = path.win32.basename(game.executablePath);
const executablePath = game.executablePath!;
const basename = path.win32.basename(executablePath);
const basenameWithoutExtension = path.win32.basename(
game.executablePath,
path.extname(game.executablePath)
executablePath,
path.extname(executablePath)
);
const gameProcess = processes.find((runningProcess) => {
@@ -46,7 +47,7 @@ export const startProcessWatcher = async () => {
if (gameProcess) {
if (gamesPlaytime.has(game.id)) {
const zero = gamesPlaytime.get(game.id);
const zero = gamesPlaytime.get(game.id) ?? 0;
const delta = performance.now() - zero;
if (WindowManager.mainWindow) {

View File

@@ -4,7 +4,6 @@ import { formatUploadDate } from "@main/helpers";
import { Repack } from "@main/entity";
import { requestWebPage, savePage } from "./helpers";
import type { GameRepackInput } from "./helpers";
export const request1337x = async (path: string) =>
requestWebPage(`https://1337xx.to${path}`);
@@ -68,7 +67,7 @@ export const extractTorrentsFromDocument = async (
user: string,
document: Document,
existingRepacks: Repack[] = []
): Promise<GameRepackInput[]> => {
) => {
const $trs = Array.from(document.querySelectorAll("tbody tr"));
return Promise.all(
@@ -108,7 +107,7 @@ export const getNewRepacksFromUser = async (
user: string,
existingRepacks: Repack[],
page = 1
): Promise<Repack[]> => {
) => {
const response = await request1337x(`/user/${user}/${page}`);
const { window } = new JSDOM(response);

View File

@@ -3,7 +3,6 @@ import { JSDOM } from "jsdom";
import { Repack } from "@main/entity";
import { requestWebPage, savePage } from "./helpers";
import type { GameRepackInput } from "./helpers";
import { logger } from "../logger";
export const getNewRepacksFromCPG = async (
@@ -14,22 +13,22 @@ export const getNewRepacksFromCPG = async (
const { window } = new JSDOM(data);
const repacks: GameRepackInput[] = [];
const repacks = [];
try {
Array.from(window.document.querySelectorAll(".post")).forEach(($post) => {
const $title = $post.querySelector(".entry-title");
const uploadDate = $post.querySelector("time").getAttribute("datetime");
const uploadDate = $post.querySelector("time")?.getAttribute("datetime");
const $downloadInfo = Array.from(
$post.querySelectorAll(".wp-block-heading")
).find(($heading) => $heading.textContent.startsWith("Download"));
).find(($heading) => $heading.textContent?.startsWith("Download"));
/* Side note: CPG often misspells "Magnet" as "Magent" */
const $magnet = Array.from($post.querySelectorAll("a")).find(
($a) =>
$a.textContent.startsWith("Magnet") ||
$a.textContent.startsWith("Magent")
$a.textContent?.startsWith("Magnet") ||
$a.textContent?.startsWith("Magent")
);
const fileSize = $downloadInfo.textContent

View File

@@ -1,7 +1,8 @@
import { JSDOM, VirtualConsole } from "jsdom";
import { GameRepackInput, requestWebPage, savePage } from "./helpers";
import { requestWebPage, savePage } from "./helpers";
import { Repack } from "@main/entity";
import { logger } from "../logger";
import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity";
const virtualConsole = new VirtualConsole();
@@ -36,43 +37,35 @@ const getGOGGame = async (url: string) => {
};
export const getNewGOGGames = async (existingRepacks: Repack[] = []) => {
try {
const data = await requestWebPage(
"https://freegogpcgames.com/a-z-games-list/"
);
const data = await requestWebPage(
"https://freegogpcgames.com/a-z-games-list/"
);
const { window } = new JSDOM(data, { virtualConsole });
const { window } = new JSDOM(data, { virtualConsole });
const $uls = Array.from(window.document.querySelectorAll(".az-columns"));
const $uls = Array.from(window.document.querySelectorAll(".az-columns"));
for (const $ul of $uls) {
const repacks: GameRepackInput[] = [];
const $lis = Array.from($ul.querySelectorAll("li"));
for (const $ul of $uls) {
const repacks: QueryDeepPartialEntity<Repack>[] = [];
const $lis = Array.from($ul.querySelectorAll("li"));
for (const $li of $lis) {
const $a = $li.querySelector("a");
const href = $a.href;
for (const $li of $lis) {
const $a = $li.querySelector("a");
const href = $a.href;
const title = $a.textContent.trim();
const title = $a.textContent.trim();
const gameExists = existingRepacks.some(
(existingRepack) => existingRepack.title === title
);
const gameExists = existingRepacks.some(
(existingRepack) => existingRepack.title === title
);
if (!gameExists) {
try {
const game = await getGOGGame(href);
if (!gameExists) {
const game = await getGOGGame(href);
repacks.push({ ...game, title });
} catch (err) {
logger.error(err.message, { method: "getGOGGame", url: href });
}
}
repacks.push({ ...game, title });
}
if (repacks.length) await savePage(repacks);
}
} catch (err) {
logger.error(err.message, { method: "getNewGOGGames" });
if (repacks.length) await savePage(repacks);
}
};

View File

@@ -1,13 +1,9 @@
import type { Repack } from "@main/entity";
import { repackRepository } from "@main/repository";
import type { GameRepack } from "@types";
import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity";
export type GameRepackInput = Omit<
GameRepack,
"id" | "repackerFriendlyName" | "createdAt" | "updatedAt"
>;
export const savePage = async (repacks: GameRepackInput[]) =>
export const savePage = async (repacks: QueryDeepPartialEntity<Repack>[]) =>
Promise.all(
repacks.map((repack) => repackRepository.insert(repack).catch(() => {}))
);

View File

@@ -1,6 +1,5 @@
import { Repack } from "@main/entity";
import { savePage } from "./helpers";
import type { GameRepackInput } from "./helpers";
import { logger } from "../logger";
import parseTorrent, {
toMagnetURI,
@@ -21,7 +20,8 @@ export const getNewRepacksFromOnlineFix = async (
cookieJar = new CookieJar()
): Promise<void> => {
const hasCredentials =
process.env.ONLINEFIX_USERNAME && process.env.ONLINEFIX_PASSWORD;
import.meta.env.MAIN_VITE_ONLINEFIX_USERNAME &&
import.meta.env.MAIN_VITE_ONLINEFIX_PASSWORD;
if (!hasCredentials) return;
const http = gotScraping.extend({
@@ -58,8 +58,8 @@ export const getNewRepacksFromOnlineFix = async (
if (!preLogin.field || !preLogin.value) return;
const params = new URLSearchParams({
login_name: process.env.ONLINEFIX_USERNAME,
login_password: process.env.ONLINEFIX_PASSWORD,
login_name: import.meta.env.MAIN_VITE_ONLINEFIX_USERNAME,
login_password: import.meta.env.MAIN_VITE_ONLINEFIX_PASSWORD,
login: "submit",
[preLogin.field]: preLogin.value,
});
@@ -84,10 +84,10 @@ export const getNewRepacksFromOnlineFix = async (
});
const document = new JSDOM(home.body).window.document;
const repacks: GameRepackInput[] = [];
const repacks = [];
const articles = Array.from(document.querySelectorAll(".news"));
const totalPages = Number(
document.querySelector("nav > a:nth-child(13)").textContent
document.querySelector("nav > a:nth-child(13)")?.textContent
);
try {
@@ -185,8 +185,10 @@ export const getNewRepacksFromOnlineFix = async (
});
})
);
} catch (err) {
logger.error(err.message, { method: "getNewRepacksFromOnlineFix" });
} catch (err: unknown) {
logger.error((err as Error).message, {
method: "getNewRepacksFromOnlineFix",
});
}
const newRepacks = repacks.filter(

View File

@@ -1,16 +1,14 @@
import { JSDOM } from "jsdom";
import parseTorrent, { toMagnetURI } from "parse-torrent";
import { Repack } from "@main/entity";
import { logger } from "../logger";
import { requestWebPage, savePage } from "./helpers";
import type { GameRepackInput } from "./helpers";
const getTorrentBuffer = (url: string) =>
fetch(url, { method: "GET" }).then((response) =>
response.arrayBuffer().then((buffer) => Buffer.from(buffer))
);
import createWorker from "@main/workers/torrent-parser.worker?nodeWorker";
import { toMagnetURI } from "parse-torrent";
import type { Instance } from "parse-torrent";
const worker = createWorker({});
const formatXatabDate = (str: string) => {
const date = new Date();
@@ -28,28 +26,36 @@ const formatXatabDate = (str: string) => {
const formatXatabDownloadSize = (str: string) =>
str.replace(",", ".").replace(/Гб/g, "GB").replace(/Мб/g, "MB");
const getXatabRepack = async (url: string) => {
const data = await requestWebPage(url);
const { window } = new JSDOM(data);
const getXatabRepack = (url: string) => {
return new Promise((resolve) => {
(async () => {
const data = await requestWebPage(url);
const { window } = new JSDOM(data);
const { document } = window;
const $uploadDate = window.document.querySelector(".entry__date");
const $size = window.document.querySelector(".entry__info-size");
const $uploadDate = document.querySelector(".entry__date");
const $size = document.querySelector(".entry__info-size");
const $downloadButton = window.document.querySelector(
".download-torrent"
) as HTMLAnchorElement;
const $downloadButton = document.querySelector(
".download-torrent"
) as HTMLAnchorElement;
if (!$downloadButton) throw new Error("Download button not found");
if (!$downloadButton) throw new Error("Download button not found");
const torrentBuffer = await getTorrentBuffer($downloadButton.href);
const onMessage = (torrent: Instance) => {
resolve({
fileSize: formatXatabDownloadSize($size.textContent).toUpperCase(),
magnet: toMagnetURI(torrent),
uploadDate: formatXatabDate($uploadDate.textContent),
});
return {
fileSize: formatXatabDownloadSize($size.textContent).toUpperCase(),
magnet: toMagnetURI({
infoHash: parseTorrent(torrentBuffer).infoHash,
}),
uploadDate: formatXatabDate($uploadDate.textContent),
};
worker.removeListener("message", onMessage);
};
worker.on("message", onMessage);
worker.postMessage($downloadButton.href);
})();
});
};
export const getNewRepacksFromXatab = async (
@@ -60,7 +66,7 @@ export const getNewRepacksFromXatab = async (
const { window } = new JSDOM(data);
const repacks: GameRepackInput[] = [];
const repacks = [];
for (const $a of Array.from(
window.document.querySelectorAll(".entry__title a")
@@ -74,14 +80,15 @@ export const getNewRepacksFromXatab = async (
...repack,
page,
});
} catch (err) {
logger.error(err.message, { method: "getNewRepacksFromXatab" });
} catch (err: unknown) {
logger.error((err as Error).message, {
method: "getNewRepacksFromXatab",
});
}
}
const newRepacks = repacks.filter(
(repack) =>
repack.uploadDate &&
!existingRepacks.some(
(existingRepack) => existingRepack.title === repack.title
)

View File

@@ -1,24 +1,31 @@
import axios from "axios";
import { JSDOM } from "jsdom";
import shuffle from "lodash/shuffle";
export interface Steam250Game {
title: string;
objectID: string;
}
export const requestSteam250 = async (path: string) => {
return axios.get(`https://steam250.com${path}`).then((response) => {
const { window } = new JSDOM(response.data);
const { document } = window;
return axios
.get(`https://steam250.com${path}`)
.then((response) => {
const { window } = new JSDOM(response.data);
const { document } = window;
return Array.from(document.querySelectorAll(".appline .title a")).map(
($title: HTMLAnchorElement) => {
const steamGameUrl = $title.href;
if (!steamGameUrl) return null;
return Array.from(document.querySelectorAll(".appline .title a"))
.map(($title) => {
const steamGameUrl = ($title as HTMLAnchorElement).href;
if (!steamGameUrl) return null;
return {
title: $title.textContent,
objectID: steamGameUrl.split("/").pop(),
};
}
);
});
return {
title: $title.textContent,
objectID: steamGameUrl.split("/").pop(),
} as Steam250Game;
})
.filter((game) => game != null);
})
.catch((_) => [] as Steam250Game[]);
};
const steam250Paths = [
@@ -28,7 +35,15 @@ const steam250Paths = [
"/most_played",
];
export const getRandomSteam250List = async () => {
const [path] = shuffle(steam250Paths);
return requestSteam250(path);
export const getSteam250List = async () => {
const gamesList = (
await Promise.all(steam250Paths.map((path) => requestSteam250(path)))
).flat();
const gamesMap: Map<string, Steam250Game> = gamesList.reduce((map, item) => {
map.set(item.objectID, item);
return map;
}, new Map());
return [...gamesMap.values()];
};

View File

@@ -32,7 +32,7 @@ export const getSteamGridData = async (
{
method: "GET",
headers: {
Authorization: `Bearer ${process.env.STEAMGRIDDB_API_KEY}`,
Authorization: `Bearer ${import.meta.env.MAIN_VITE_STEAMGRIDDB_API_KEY}`,
},
}
);

View File

@@ -1,7 +1,7 @@
import path from "node:path";
import { app } from "electron";
import chunk from "lodash/chunk";
import { chunk } from "lodash-es";
import { createDataSource, dataSource } from "@main/data-source";
import { Repack, RepackerFriendlyName, SteamGame } from "@main/entity";
@@ -109,7 +109,7 @@ export const resolveDatabaseUpdates = async () => {
const updateDataSource = createDataSource({
database: app.isPackaged
? path.join(process.resourcesPath, "hydra.db")
: path.join(__dirname, "..", "..", "resources", "hydra.db"),
: path.join(__dirname, "..", "..", "hydra.db"),
});
return updateDataSource.initialize().then(async () => {

View File

@@ -1,16 +1,30 @@
import { BrowserWindow, Menu, Tray, app } from "electron";
import { is } from "@electron-toolkit/utils";
import { t } from "i18next";
import path from "node:path";
// This allows TypeScript to pick up the magic constants that's auto-generated by Forge's Webpack
// plugin that tells the Electron app where to look for the Webpack-bundled app code (depending on
// whether you're running in development or production).
declare const MAIN_WINDOW_WEBPACK_ENTRY: string;
declare const MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY: string;
import icon from "@resources/icon.png?asset";
import trayIcon from "@resources/tray-icon.png?asset";
export class WindowManager {
public static mainWindow: Electron.BrowserWindow | null = null;
private static loadURL(hash = "") {
// HMR for renderer base on electron-vite cli.
// Load the remote URL for development or the local html file for production.
if (is.dev && process.env["ELECTRON_RENDERER_URL"]) {
this.mainWindow?.loadURL(
`${process.env["ELECTRON_RENDERER_URL"]}#/${hash}`
);
} else {
this.mainWindow?.loadFile(
path.join(__dirname, "../renderer/index.html"),
{
hash,
}
);
}
}
public static createMainWindow() {
// Create the browser window.
this.mainWindow = new BrowserWindow({
@@ -19,7 +33,7 @@ export class WindowManager {
minWidth: 1024,
minHeight: 540,
titleBarStyle: "hidden",
icon: path.join(__dirname, "..", "..", "images", "icon.png"),
...(process.platform === "linux" ? { icon } : {}),
trafficLightPosition: { x: 16, y: 16 },
titleBarOverlay: {
symbolColor: "#DADBE1",
@@ -27,40 +41,29 @@ export class WindowManager {
height: 34,
},
webPreferences: {
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
preload: path.join(__dirname, "../preload/index.mjs"),
sandbox: false,
},
});
this.loadURL();
this.mainWindow.removeMenu();
this.mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);
this.mainWindow.webContents.on("did-finish-load", () => {
if (!app.isPackaged) {
// Open the DevTools.
this.mainWindow.webContents.openDevTools();
}
});
this.mainWindow.on("close", () => {
WindowManager.mainWindow.setProgressBar(-1);
WindowManager.mainWindow?.setProgressBar(-1);
});
}
public static redirect(path: string) {
public static redirect(hash: string) {
if (!this.mainWindow) this.createMainWindow();
this.mainWindow.loadURL(`${MAIN_WINDOW_WEBPACK_ENTRY}#${path}`);
this.loadURL(hash);
if (this.mainWindow.isMinimized()) this.mainWindow.restore();
this.mainWindow.focus();
if (this.mainWindow?.isMinimized()) this.mainWindow.restore();
this.mainWindow?.focus();
}
public static createSystemTray(language: string) {
const tray = new Tray(
app.isPackaged
? path.join(process.resourcesPath, "icon_tray.png")
: path.join(__dirname, "..", "..", "resources", "icon_tray.png")
);
const tray = new Tray(trayIcon);
const contextMenu = Menu.buildFromTemplate([
{
@@ -93,10 +96,10 @@ export class WindowManager {
if (process.platform === "win32") {
tray.addListener("click", () => {
if (this.mainWindow) {
if (WindowManager.mainWindow.isMinimized())
if (WindowManager.mainWindow?.isMinimized())
WindowManager.mainWindow.restore();
WindowManager.mainWindow.focus();
WindowManager.mainWindow?.focus();
return;
}

12
src/main/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1,12 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly MAIN_VITE_STEAMGRIDDB_API_KEY: string;
readonly MAIN_VITE_ONLINEFIX_USERNAME: string;
readonly MAIN_VITE_ONLINEFIX_PASSWORD: string;
readonly MAIN_VITE_SENTRY_DSN: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}

View File

@@ -0,0 +1,17 @@
import { parentPort } from "worker_threads";
import parseTorrent from "parse-torrent";
const port = parentPort;
if (!port) throw new Error("IllegalState");
const getTorrentBuffer = (url: string) =>
fetch(url, { method: "GET" }).then((response) =>
response.arrayBuffer().then((buffer) => Buffer.from(buffer))
);
port.on("message", async (url: string) => {
const buffer = await getTorrentBuffer(url);
const torrent = await parseTorrent(buffer);
port.postMessage(torrent);
});