Merge branch 'feature/cloud-sync' into feature/game-achievements

# Conflicts:
#	src/locales/en/translation.json
#	src/locales/pt-BR/translation.json
#	src/main/events/library/add-game-to-library.ts
#	src/renderer/src/pages/game-details/sidebar/sidebar.css.ts
#	src/renderer/src/pages/game-details/sidebar/sidebar.tsx
This commit is contained in:
Zamitto
2024-10-07 19:12:57 -03:00
103 changed files with 3548 additions and 584 deletions

View File

@@ -17,4 +17,6 @@ export const seedsPath = app.isPackaged
? path.join(process.resourcesPath, "seeds")
: path.join(__dirname, "..", "..", "seeds");
export const backupsPath = path.join(app.getPath("userData"), "Backups");
export const appVersion = app.getVersion();

View File

@@ -18,6 +18,9 @@ export class GameShopCache {
@Column("text", { nullable: true })
serializedData: string;
/**
* @deprecated Use IndexedDB's `howLongToBeatEntries` instead
*/
@Column("text", { nullable: true })
howLongToBeatSerializedData: string;

View File

@@ -30,7 +30,7 @@ const getCatalogue = async (
title: steamGame.name,
shop: game.shop,
cover: steamUrlBuilder.library(game.objectId),
objectID: game.objectId,
objectId: game.objectId,
};
})
);

View File

@@ -7,16 +7,16 @@ import { registerEvent } from "../register-event";
import { steamGamesWorker } from "@main/workers";
const getLocalizedSteamAppDetails = async (
objectID: string,
objectId: string,
language: string
): Promise<ShopDetails | null> => {
if (language === "english") {
return getSteamAppDetails(objectID, language);
return getSteamAppDetails(objectId, language);
}
return getSteamAppDetails(objectID, language).then(
return getSteamAppDetails(objectId, language).then(
async (localizedAppDetails) => {
const steamGame = await steamGamesWorker.run(Number(objectID), {
const steamGame = await steamGamesWorker.run(Number(objectId), {
name: "getById",
});
@@ -34,21 +34,21 @@ const getLocalizedSteamAppDetails = async (
const getGameShopDetails = async (
_event: Electron.IpcMainInvokeEvent,
objectID: string,
objectId: string,
shop: GameShop,
language: string
): Promise<ShopDetails | null> => {
if (shop === "steam") {
const cachedData = await gameShopCacheRepository.findOne({
where: { objectID, language },
where: { objectID: objectId, language },
});
const appDetails = getLocalizedSteamAppDetails(objectID, language).then(
const appDetails = getLocalizedSteamAppDetails(objectId, language).then(
(result) => {
if (result) {
gameShopCacheRepository.upsert(
{
objectID,
objectID: objectId,
shop: "steam",
language,
serializedData: JSON.stringify(result),
@@ -68,7 +68,7 @@ const getGameShopDetails = async (
if (cachedGame) {
return {
...cachedGame,
objectID,
objectId,
} as ShopDetails;
}

View File

@@ -1,28 +1,29 @@
import type { CatalogueEntry } from "@types";
import { registerEvent } from "../register-event";
import { steamGamesWorker } from "@main/workers";
import { HydraApi } from "@main/services";
import { steamUrlBuilder } from "@shared";
const getGames = async (
_event: Electron.IpcMainInvokeEvent,
take = 12,
cursor = 0
): Promise<{ results: CatalogueEntry[]; cursor: number }> => {
const steamGames = await steamGamesWorker.run(
{ limit: take, offset: cursor },
{ name: "list" }
skip = 0
): Promise<CatalogueEntry[]> => {
const searchParams = new URLSearchParams({
take: take.toString(),
skip: skip.toString(),
});
const games = await HydraApi.get<CatalogueEntry[]>(
`/games/catalogue?${searchParams.toString()}`,
undefined,
{ needsAuth: false }
);
return {
results: steamGames.map((steamGame) => ({
title: steamGame.name,
shop: "steam",
cover: steamUrlBuilder.library(steamGame.id),
objectID: steamGame.id,
})),
cursor: cursor + steamGames.length,
};
return games.map((game) => ({
...game,
cover: steamUrlBuilder.library(game.objectId),
}));
};
registerEvent("getGames", getGames);

View File

@@ -1,45 +1,23 @@
import type { GameShop, HowLongToBeatCategory } from "@types";
import type { HowLongToBeatCategory } from "@types";
import { getHowLongToBeatGame, searchHowLongToBeat } from "@main/services";
import { registerEvent } from "../register-event";
import { gameShopCacheRepository } from "@main/repository";
import { formatName } from "@shared";
const getHowLongToBeat = async (
_event: Electron.IpcMainInvokeEvent,
objectID: string,
shop: GameShop,
title: string
): Promise<HowLongToBeatCategory[] | null> => {
const searchHowLongToBeatPromise = searchHowLongToBeat(title);
const response = await searchHowLongToBeat(title);
const gameShopCache = await gameShopCacheRepository.findOne({
where: { objectID, shop },
const game = response.data.find((game) => {
return formatName(game.game_name) === formatName(title);
});
const howLongToBeatCachedData = gameShopCache?.howLongToBeatSerializedData
? JSON.parse(gameShopCache?.howLongToBeatSerializedData)
: null;
if (howLongToBeatCachedData) return howLongToBeatCachedData;
if (!game) return null;
const howLongToBeat = await getHowLongToBeatGame(String(game.game_id));
return searchHowLongToBeatPromise.then(async (response) => {
const game = response.data.find(
(game) => game.profile_steam === Number(objectID)
);
if (!game) return null;
const howLongToBeat = await getHowLongToBeatGame(String(game.game_id));
gameShopCacheRepository.upsert(
{
objectID,
shop,
howLongToBeatSerializedData: JSON.stringify(howLongToBeat),
},
["objectID"]
);
return howLongToBeat;
});
return howLongToBeat;
};
registerEvent("getHowLongToBeat", getHowLongToBeat);

View File

@@ -0,0 +1,14 @@
import { registerEvent } from "../register-event";
import { GameShop } from "@types";
import { Ludusavi } from "@main/services";
const checkGameCloudSyncSupport = async (
_event: Electron.IpcMainInvokeEvent,
objectId: string,
shop: GameShop
) => {
const games = await Ludusavi.findGames(shop, objectId);
return games.length === 1;
};
registerEvent("checkGameCloudSyncSupport", checkGameCloudSyncSupport);

View File

@@ -0,0 +1,12 @@
import { HydraApi } from "@main/services";
import { registerEvent } from "../register-event";
const deleteGameArtifact = async (
_event: Electron.IpcMainInvokeEvent,
gameArtifactId: string
) =>
HydraApi.delete<{ ok: boolean }>(
`/profile/games/artifacts/${gameArtifactId}`
);
registerEvent("deleteGameArtifact", deleteGameArtifact);

View File

@@ -0,0 +1,139 @@
import { HydraApi, logger, Ludusavi, WindowManager } from "@main/services";
import fs from "node:fs";
import * as tar from "tar";
import { registerEvent } from "../register-event";
import axios from "axios";
import { app } from "electron";
import path from "node:path";
import { backupsPath } from "@main/constants";
import type { GameShop } from "@types";
import YAML from "yaml";
export interface LudusaviBackup {
files: {
[key: string]: {
hash: string;
size: number;
};
};
}
const replaceLudusaviBackupWithCurrentUser = (
gameBackupPath: string,
backupHomeDir: string
) => {
const mappingYamlPath = path.join(gameBackupPath, "mapping.yaml");
const data = fs.readFileSync(mappingYamlPath, "utf8");
const manifest = YAML.parse(data) as {
backups: LudusaviBackup[];
drives: Record<string, string>;
};
const currentHomeDir = app.getPath("home");
// TODO: Only works on Windows
const usersDirPath = path.join(gameBackupPath, "drive-C", "Users");
const oldPath = path.join(usersDirPath, path.basename(backupHomeDir));
const newPath = path.join(usersDirPath, path.basename(currentHomeDir));
// Directories are different, rename
if (backupHomeDir !== currentHomeDir) {
if (fs.existsSync(newPath)) {
fs.rmSync(newPath, {
recursive: true,
force: true,
});
}
fs.renameSync(oldPath, newPath);
}
const backups = manifest.backups.map((backup: LudusaviBackup) => {
const files = Object.entries(backup.files).reduce((prev, [key, value]) => {
return {
...prev,
[key.replace(backupHomeDir, currentHomeDir)]: value,
};
}, {});
return {
...backup,
files,
};
});
fs.writeFileSync(mappingYamlPath, YAML.stringify({ ...manifest, backups }));
};
const downloadGameArtifact = async (
_event: Electron.IpcMainInvokeEvent,
objectId: string,
shop: GameShop,
gameArtifactId: string
) => {
const { downloadUrl, objectKey, homeDir } = await HydraApi.post<{
downloadUrl: string;
objectKey: string;
homeDir: string;
}>(`/profile/games/artifacts/${gameArtifactId}/download`);
const zipLocation = path.join(app.getPath("userData"), objectKey);
const backupPath = path.join(backupsPath, `${shop}-${objectId}`);
if (fs.existsSync(backupPath)) {
fs.rmSync(backupPath, {
recursive: true,
force: true,
});
}
const response = await axios.get(downloadUrl, {
responseType: "stream",
onDownloadProgress: (progressEvent) => {
WindowManager.mainWindow?.webContents.send(
`on-backup-download-progress-${objectId}-${shop}`,
progressEvent
);
},
});
const writer = fs.createWriteStream(zipLocation);
response.data.pipe(writer);
writer.on("error", (err) => {
logger.error("Failed to write zip", err);
throw err;
});
fs.mkdirSync(backupPath, { recursive: true });
writer.on("close", () => {
tar
.x({
file: zipLocation,
cwd: backupPath,
})
.then(async () => {
const [game] = await Ludusavi.findGames(shop, objectId);
if (!game) throw new Error("Game not found in Ludusavi manifest");
replaceLudusaviBackupWithCurrentUser(
path.join(backupPath, game),
path.normalize(homeDir).replace(/\\/g, "/")
);
Ludusavi.restoreBackup(backupPath).then(() => {
WindowManager.mainWindow?.webContents.send(
`on-backup-download-complete-${objectId}-${shop}`,
true
);
});
});
});
};
registerEvent("downloadGameArtifact", downloadGameArtifact);

View File

@@ -0,0 +1,20 @@
import { HydraApi } from "@main/services";
import { registerEvent } from "../register-event";
import type { GameArtifact, GameShop } from "@types";
const getGameArtifacts = async (
_event: Electron.IpcMainInvokeEvent,
objectId: string,
shop: GameShop
) => {
const params = new URLSearchParams({
objectId,
shop,
});
return HydraApi.get<GameArtifact[]>(
`/profile/games/artifacts?${params.toString()}`
);
};
registerEvent("getGameArtifacts", getGameArtifacts);

View File

@@ -0,0 +1,17 @@
import { registerEvent } from "../register-event";
import { GameShop } from "@types";
import { Ludusavi } from "@main/services";
import path from "node:path";
import { backupsPath } from "@main/constants";
const getGameBackupPreview = async (
_event: Electron.IpcMainInvokeEvent,
objectId: string,
shop: GameShop
) => {
const backupPath = path.join(backupsPath, `${shop}-${objectId}`);
return Ludusavi.getBackupPreview(shop, objectId, backupPath);
};
registerEvent("getGameBackupPreview", getGameBackupPreview);

View File

@@ -0,0 +1,87 @@
import { HydraApi, logger, Ludusavi, WindowManager } from "@main/services";
import { registerEvent } from "../register-event";
import fs from "node:fs";
import path from "node:path";
import * as tar from "tar";
import crypto from "node:crypto";
import { GameShop } from "@types";
import axios from "axios";
import os from "node:os";
import { backupsPath } from "@main/constants";
import { app } from "electron";
const bundleBackup = async (shop: GameShop, objectId: string) => {
const backupPath = path.join(backupsPath, `${shop}-${objectId}`);
await Ludusavi.backupGame(shop, objectId, backupPath);
const tarLocation = path.join(backupsPath, `${crypto.randomUUID()}.zip`);
await tar.create(
{
gzip: false,
file: tarLocation,
cwd: backupPath,
},
["."]
);
return tarLocation;
};
const uploadSaveGame = async (
_event: Electron.IpcMainInvokeEvent,
objectId: string,
shop: GameShop
) => {
const bundleLocation = await bundleBackup(shop, objectId);
fs.stat(bundleLocation, async (err, stat) => {
if (err) {
logger.error("Failed to get zip file stats", err);
throw err;
}
const { uploadUrl } = await HydraApi.post<{
id: string;
uploadUrl: string;
}>("/profile/games/artifacts", {
artifactLengthInBytes: stat.size,
shop,
objectId,
hostname: os.hostname(),
homeDir: path.normalize(app.getPath("home")).replace(/\\/g, "/"),
platform: os.platform(),
});
fs.readFile(bundleLocation, async (err, fileBuffer) => {
if (err) {
logger.error("Failed to read zip file", err);
throw err;
}
await axios.put(uploadUrl, fileBuffer, {
headers: {
"Content-Type": "application/tar",
},
onUploadProgress: (progressEvent) => {
console.log(progressEvent);
},
});
WindowManager.mainWindow?.webContents.send(
`on-upload-complete-${objectId}-${shop}`,
true
);
fs.rm(bundleLocation, (err) => {
if (err) {
logger.error("Failed to remove tar file", err);
throw err;
}
});
});
});
};
registerEvent("uploadSaveGame", uploadSaveGame);

View File

@@ -12,7 +12,7 @@ export interface SearchGamesArgs {
export const convertSteamGameToCatalogueEntry = (
game: SteamGame
): CatalogueEntry => ({
objectID: String(game.id),
objectId: String(game.id),
title: game.name,
shop: "steam" as GameShop,
cover: steamUrlBuilder.library(String(game.id)),

View File

@@ -57,6 +57,12 @@ import "./profile/update-profile";
import "./profile/process-profile-image";
import "./profile/send-friend-request";
import "./profile/sync-friend-requests";
import "./cloud-save/download-game-artifact";
import "./cloud-save/get-game-artifacts";
import "./cloud-save/get-game-backup-preview";
import "./cloud-save/upload-save-game";
import "./cloud-save/check-game-cloud-sync-support";
import "./cloud-save/delete-game-artifact";
import "./notifications/publish-new-repacks-notification";
import { isPortableVersion } from "@main/helpers";

View File

@@ -11,14 +11,14 @@ import { updateLocalUnlockedAchivements } from "@main/services/achievements/upda
const addGameToLibrary = async (
_event: Electron.IpcMainInvokeEvent,
objectID: string,
objectId: string,
title: string,
shop: GameShop
) => {
return gameRepository
.update(
{
objectID,
objectID: objectId,
},
{
shop,
@@ -28,23 +28,25 @@ const addGameToLibrary = async (
)
.then(async ({ affected }) => {
if (!affected) {
const steamGame = await steamGamesWorker.run(Number(objectID), {
const steamGame = await steamGamesWorker.run(Number(objectId), {
name: "getById",
});
const iconUrl = steamGame?.clientIcon
? steamUrlBuilder.icon(objectID, steamGame.clientIcon)
? steamUrlBuilder.icon(objectId, steamGame.clientIcon)
: null;
await gameRepository.insert({
title,
iconUrl,
objectID,
objectID: objectId,
shop,
});
}
const game = await gameRepository.findOne({ where: { objectID } });
const game = await gameRepository.findOne({
where: { objectID: objectId },
});
updateLocalUnlockedAchivements(game!);

View File

@@ -2,15 +2,15 @@ import { gameRepository } from "@main/repository";
import { registerEvent } from "../register-event";
const getGameByObjectID = async (
const getGameByObjectId = async (
_event: Electron.IpcMainInvokeEvent,
objectID: string
objectId: string
) =>
gameRepository.findOne({
where: {
objectID,
objectID: objectId,
isDeleted: false,
},
});
registerEvent("getGameByObjectID", getGameByObjectID);
registerEvent("getGameByObjectId", getGameByObjectId);

View File

@@ -14,7 +14,7 @@ const startGameDownload = async (
_event: Electron.IpcMainInvokeEvent,
payload: StartGameDownloadPayload
) => {
const { objectID, title, shop, downloadPath, downloader, uri } = payload;
const { objectId, title, shop, downloadPath, downloader, uri } = payload;
return dataSource.transaction(async (transactionalEntityManager) => {
const gameRepository = transactionalEntityManager.getRepository(Game);
@@ -23,7 +23,7 @@ const startGameDownload = async (
const game = await gameRepository.findOne({
where: {
objectID,
objectID: objectId,
shop,
},
});
@@ -51,18 +51,18 @@ const startGameDownload = async (
}
);
} else {
const steamGame = await steamGamesWorker.run(Number(objectID), {
const steamGame = await steamGamesWorker.run(Number(objectId), {
name: "getById",
});
const iconUrl = steamGame?.clientIcon
? steamUrlBuilder.icon(objectID, steamGame.clientIcon)
? steamUrlBuilder.icon(objectId, steamGame.clientIcon)
: null;
await gameRepository.insert({
title,
iconUrl,
objectID,
objectID: objectId,
downloader,
shop,
status: "active",
@@ -73,7 +73,7 @@ const startGameDownload = async (
const updatedGame = await gameRepository.findOne({
where: {
objectID,
objectID: objectId,
},
});

View File

@@ -1,4 +1,4 @@
import { app, BrowserWindow, net, protocol, session } from "electron";
import { app, BrowserWindow, net, protocol } from "electron";
import { init } from "@sentry/electron/main";
import updater from "electron-updater";
import i18n from "i18next";
@@ -104,46 +104,6 @@ app.whenReady().then(async () => {
WindowManager.createMainWindow();
WindowManager.createNotificationWindow();
WindowManager.createSystemTray(userPreferences?.language || "en");
session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
callback({
requestHeaders: {
...details.requestHeaders,
"user-agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
},
});
});
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
const headers = {
"access-control-allow-origin": ["*"],
"access-control-allow-methods": ["GET, POST, PUT, DELETE, OPTIONS"],
"access-control-expose-headers": ["ETag"],
"access-control-allow-headers": [
"Content-Type, Authorization, X-Requested-With, If-None-Match",
],
"access-control-allow-credentials": ["true"],
};
if (details.method === "OPTIONS") {
callback({
cancel: false,
responseHeaders: {
...details.responseHeaders,
...headers,
},
statusLine: "HTTP/1.1 200 OK",
});
} else {
callback({
responseHeaders: {
...details.responseHeaders,
...headers,
},
});
}
});
});
app.on("browser-window-created", (_, window) => {

View File

@@ -1,32 +1,65 @@
import axios from "axios";
import { requestWebPage } from "@main/helpers";
import { HowLongToBeatCategory } from "@types";
import type {
HowLongToBeatCategory,
HowLongToBeatSearchResponse,
} from "@types";
import { formatName } from "@shared";
import { logger } from "./logger";
import UserAgent from "user-agents";
export interface HowLongToBeatResult {
game_id: number;
profile_steam: number;
}
const state = {
apiKey: null as string | null,
};
export interface HowLongToBeatSearchResponse {
data: HowLongToBeatResult[];
}
const getHowLongToBeatSearchApiKey = async () => {
const userAgent = new UserAgent();
const document = await requestWebPage("https://howlongtobeat.com/");
const scripts = Array.from(document.querySelectorAll("script"));
const appScript = scripts.find((script) =>
script.src.startsWith("/_next/static/chunks/pages/_app")
);
if (!appScript) return null;
const response = await axios.get(
`https://howlongtobeat.com${appScript.src}`,
{
headers: {
"User-Agent": userAgent.toString(),
},
}
);
const results = /fetch\("\/api\/search\/"\.concat\("(.*?)"\)/gm.exec(
response.data
);
if (!results) return null;
return results[1];
};
export const searchHowLongToBeat = async (gameName: string) => {
state.apiKey = state.apiKey ?? (await getHowLongToBeatSearchApiKey());
if (!state.apiKey) return { data: [] };
const userAgent = new UserAgent();
const response = await axios
.post(
"https://howlongtobeat.com/api/search",
"https://howlongtobeat.com/api/search/8fbd64723a8204dd",
{
searchType: "games",
searchTerms: formatName(gameName).split(" "),
searchPage: 1,
size: 100,
size: 20,
},
{
headers: {
"User-Agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
"User-Agent": userAgent.toString(),
Referer: "https://howlongtobeat.com/",
},
}

View File

@@ -8,3 +8,4 @@ export * from "./how-long-to-beat";
export * from "./process-watcher";
export * from "./main-loop";
export * from "./hydra-api";
export * from "./ludusavi";

View File

@@ -0,0 +1,63 @@
import { GameShop, LudusaviBackup } from "@types";
import Piscina from "piscina";
import { app } from "electron";
import path from "node:path";
import ludusaviWorkerPath from "../workers/ludusavi.worker?modulePath";
const binaryPath = app.isPackaged
? path.join(process.resourcesPath, "ludusavi", "ludusavi")
: path.join(__dirname, "..", "..", "ludusavi", "ludusavi");
export class Ludusavi {
private static worker = new Piscina({
filename: ludusaviWorkerPath,
workerData: {
binaryPath,
},
});
static async findGames(shop: GameShop, objectId: string): Promise<string[]> {
const games = await this.worker.run(
{ objectId, shop },
{ name: "findGames" }
);
return games;
}
static async backupGame(
shop: GameShop,
objectId: string,
backupPath: string
): Promise<LudusaviBackup> {
const games = await this.findGames(shop, objectId);
if (!games.length) throw new Error("Game not found");
return this.worker.run(
{ title: games[0], backupPath },
{ name: "backupGame" }
);
}
static async getBackupPreview(
shop: GameShop,
objectId: string,
backupPath: string
): Promise<LudusaviBackup | null> {
const games = await this.findGames(shop, objectId);
if (!games.length) return null;
const backupData = await this.worker.run(
{ title: games[0], backupPath, preview: true },
{ name: "backupGame" }
);
return backupData;
}
static async restoreBackup(backupPath: string) {
return this.worker.run(backupPath, { name: "restoreBackup" });
}
}

View File

@@ -2,7 +2,7 @@ import { IsNull, Not } from "typeorm";
import { gameRepository } from "@main/repository";
import { WindowManager } from "./window-manager";
import { createGame, updateGamePlaytime } from "./library-sync";
import { GameRunning } from "@types";
import type { GameRunning } from "@types";
import { PythonInstance } from "./download";
import { Game } from "@main/entity";

View File

@@ -17,7 +17,7 @@ export const requestSteam250 = async (path: string) => {
return {
title: $title.textContent,
objectID: steamGameUrl.split("/").pop(),
objectId: steamGameUrl.split("/").pop(),
} as Steam250Game;
})
.filter((game) => game != null);
@@ -38,7 +38,7 @@ export const getSteam250List = async () => {
).flat();
const gamesMap: Map<string, Steam250Game> = gamesList.reduce((map, item) => {
if (item) map.set(item.objectID, item);
if (item) map.set(item.objectId, item);
return map;
}, new Map());

View File

@@ -1,3 +1,4 @@
import type { GameShop } from "@types";
import axios from "axios";
export interface SteamGridResponse {
@@ -20,9 +21,9 @@ export interface SteamGridGameResponse {
}
export const getSteamGridData = async (
objectID: string,
objectId: string,
path: string,
shop: string,
shop: GameShop,
params: Record<string, string> = {}
): Promise<SteamGridResponse> => {
const searchParams = new URLSearchParams(params);
@@ -32,7 +33,7 @@ export const getSteamGridData = async (
}
const response = await axios.get(
`https://www.steamgriddb.com/api/v2/${path}/${shop}/${objectID}?${searchParams.toString()}`,
`https://www.steamgriddb.com/api/v2/${path}/${shop}/${objectId}?${searchParams.toString()}`,
{
headers: {
Authorization: `Bearer ${import.meta.env.MAIN_VITE_STEAMGRIDDB_API_KEY}`,
@@ -58,10 +59,10 @@ export const getSteamGridGameById = async (
return response.data;
};
export const getSteamGameClientIcon = async (objectID: string) => {
export const getSteamGameClientIcon = async (objectId: string) => {
const {
data: { id: steamGridGameId },
} = await getSteamGridData(objectID, "games", "steam");
} = await getSteamGridData(objectId, "games", "steam");
const steamGridGame = await getSteamGridGameById(steamGridGameId);
return steamGridGame.data.platforms.steam.metadata.clienticon;

View File

@@ -12,11 +12,11 @@ export interface SteamAppDetailsResponse {
}
export const getSteamAppDetails = async (
objectID: string,
objectId: string,
language: string
) => {
const searchParams = new URLSearchParams({
appids: objectID,
appids: objectId,
l: language,
});
@@ -25,7 +25,7 @@ export const getSteamAppDetails = async (
`http://store.steampowered.com/api/appdetails?${searchParams.toString()}`
)
.then((response) => {
if (response.data[objectID].success) return response.data[objectID].data;
if (response.data[objectId].success) return response.data[objectId].data;
return null;
})
.catch((err) => {

View File

@@ -16,6 +16,7 @@ import trayIcon from "@resources/tray-icon.png?asset";
import { gameRepository, userPreferencesRepository } from "@main/repository";
import { IsNull, Not } from "typeorm";
import { HydraApi } from "./hydra-api";
import UserAgent from "user-agents";
export class WindowManager {
public static mainWindow: Electron.BrowserWindow | null = null;
@@ -77,6 +78,54 @@ export class WindowManager {
show: false,
});
this.mainWindow.webContents.session.webRequest.onBeforeSendHeaders(
(details, callback) => {
const userAgent = new UserAgent();
callback({
requestHeaders: {
...details.requestHeaders,
"user-agent": userAgent.toString(),
},
});
}
);
this.mainWindow.webContents.session.webRequest.onHeadersReceived(
(details, callback) => {
if (details.webContentsId !== this.mainWindow?.webContents.id) {
return callback(details);
}
const headers = {
"access-control-allow-origin": ["*"],
"access-control-allow-methods": ["GET, POST, PUT, DELETE, OPTIONS"],
"access-control-expose-headers": ["ETag"],
"access-control-allow-headers": [
"Content-Type, Authorization, X-Requested-With, If-None-Match",
],
};
if (details.method === "OPTIONS") {
return callback({
cancel: false,
responseHeaders: {
...details.responseHeaders,
...headers,
},
statusLine: "HTTP/1.1 200 OK",
});
}
return callback({
responseHeaders: {
...details.responseHeaders,
...headers,
},
});
}
);
this.loadMainWindowURL();
this.mainWindow.removeMenu();
@@ -116,11 +165,10 @@ export class WindowManager {
sandbox: false,
},
});
this.notificationWindow.setIgnoreMouseEvents(true);
this.notificationWindow.setVisibleOnAllWorkspaces(true, {
visibleOnFullScreen: true,
});
// this.notificationWindow.setVisibleOnAllWorkspaces(true, {
// visibleOnFullScreen: true,
// });
this.notificationWindow.setAlwaysOnTop(true, "screen-saver", 1);
this.loadNotificationWindowURL();
}
@@ -145,6 +193,8 @@ export class WindowManager {
authWindow.removeMenu();
if (!app.isPackaged) authWindow.webContents.openDevTools();
const searchParams = new URLSearchParams({
lng: i18next.language,
});
@@ -176,7 +226,7 @@ export class WindowManager {
}
public static createSystemTray(language: string) {
let tray;
let tray: Tray;
if (process.platform === "darwin") {
const macIcon = nativeImage

View File

@@ -0,0 +1,61 @@
import type { GameShop, LudusaviBackup, LudusaviFindResult } from "@types";
import cp from "node:child_process";
import { workerData } from "node:worker_threads";
const { binaryPath } = workerData;
export const findGames = ({
shop,
objectId,
}: {
shop: GameShop;
objectId: string;
}) => {
const args = ["find", "--api"];
if (shop === "steam") {
args.push("--steam-id", objectId);
}
const result = cp.execFileSync(binaryPath, args);
const games = JSON.parse(result.toString("utf-8")) as LudusaviFindResult;
return Object.keys(games.games);
};
export const backupGame = ({
title,
backupPath,
preview = false,
winePrefix,
}: {
title: string;
backupPath: string;
preview?: boolean;
winePrefix?: string;
}) => {
const args = ["backup", title, "--api", "--force"];
if (preview) args.push("--preview");
if (backupPath) args.push("--path", backupPath);
if (winePrefix) args.push("--wine-prefix", winePrefix);
const result = cp.execFileSync(binaryPath, args);
return JSON.parse(result.toString("utf-8")) as LudusaviBackup;
};
export const restoreBackup = (backupPath: string) => {
const result = cp.execFileSync(binaryPath, [
"restore",
"--path",
backupPath,
"--api",
"--force",
]);
return JSON.parse(result.toString("utf-8")) as LudusaviBackup;
};
// --wine-prefix