feat: refactoring code

This commit is contained in:
Zamitto 2024-10-03 11:16:30 -03:00
parent 9c7651d8e2
commit 7cddcd8147
10 changed files with 273 additions and 334 deletions

View File

@ -9,12 +9,11 @@ const getGameStats = async (
objectId: string,
shop: GameShop
) => {
const response = await HydraApi.get<GameStats>(
return HydraApi.get<GameStats>(
`/games/stats`,
{ objectId, shop },
{ needsAuth: false }
);
return response;
};
registerEvent("getGameStats", getGameStats);

View File

@ -44,7 +44,7 @@ const addGameToLibrary = async (
});
}
updateLocalUnlockedAchivements(true, objectID);
updateLocalUnlockedAchivements(objectID);
const game = await gameRepository.findOne({ where: { objectID } });

View File

@ -1,39 +1,34 @@
import { checkUnlockedAchievements } from "./check-unlocked-achievements";
import { parseAchievementFile } from "./parse-achievement-file";
import { Game } from "@main/entity";
import { mergeAchievements } from "./merge-achievements";
import fs from "node:fs";
import {
findAchievementFileInExecutableDirectory,
findAllSteamGameAchievementFiles,
} from "./find-steam-game-achivement-files";
findAllAchievementFiles,
} from "./find-achivement-files";
import type { AchievementFile } from "@types";
import { logger } from "../logger";
const fileStats: Map<string, number> = new Map();
const processAchievementFile = async (game: Game, file: AchievementFile) => {
const localAchievementFile = await parseAchievementFile(
const processAchievementFileDiff = async (
game: Game,
file: AchievementFile
) => {
const unlockedAchievements = await parseAchievementFile(
file.filePath,
file.type
);
logger.log("Parsed achievements file", file.filePath, localAchievementFile);
if (localAchievementFile) {
const unlockedAchievements = checkUnlockedAchievements(
file.type,
localAchievementFile
);
logger.log("Achievements from file", file.filePath, unlockedAchievements);
logger.log("Achievements from file", file.filePath, unlockedAchievements);
if (unlockedAchievements.length) {
return mergeAchievements(
game.objectID,
game.shop,
unlockedAchievements,
true
);
}
if (unlockedAchievements.length) {
return mergeAchievements(
game.objectID,
game.shop,
unlockedAchievements,
true
);
}
};
@ -53,14 +48,14 @@ const compareFile = async (game: Game, file: AchievementFile) => {
stat.mtimeMs,
fileStats.get(file.filePath)
);
await processAchievementFile(game, file);
await processAchievementFileDiff(game, file);
} catch (err) {
fileStats.set(file.filePath, -1);
}
};
export const startGameAchievementObserver = async (games: Game[]) => {
const achievementFiles = findAllSteamGameAchievementFiles();
export const checkAchievementFileChange = async (games: Game[]) => {
const achievementFiles = findAllAchievementFiles();
for (const game of games) {
const gameAchievementFiles = achievementFiles.get(game.objectID) || [];

View File

@ -1,5 +1,5 @@
import { gameRepository } from "@main/repository";
import { startGameAchievementObserver as searchForAchievements } from "./game-achievements-observer";
import { checkAchievementFileChange as searchForAchievements } from "./achievement-file-observer";
export const watchAchievements = async () => {
const games = await gameRepository.find({

View File

@ -1,82 +0,0 @@
import { Cracker } from "@shared";
import type { UnlockedAchievement } from "@types";
export const checkUnlockedAchievements = (
type: Cracker,
unlockedAchievements: any
): UnlockedAchievement[] => {
if (type === Cracker.onlineFix) return onlineFixMerge(unlockedAchievements);
if (type === Cracker.goldberg || type === Cracker.goldberg2)
return goldbergUnlockedAchievements(unlockedAchievements);
if (type == Cracker.generic) return genericMerge(unlockedAchievements);
return defaultMerge(unlockedAchievements);
};
const onlineFixMerge = (unlockedAchievements: any): UnlockedAchievement[] => {
const parsedUnlockedAchievements: UnlockedAchievement[] = [];
for (const achievement of Object.keys(unlockedAchievements)) {
const unlockedAchievement = unlockedAchievements[achievement];
if (unlockedAchievement?.achieved) {
parsedUnlockedAchievements.push({
name: achievement,
unlockTime: unlockedAchievement.timestamp,
});
}
}
return parsedUnlockedAchievements;
};
const goldbergUnlockedAchievements = (
unlockedAchievements: any
): UnlockedAchievement[] => {
const newUnlockedAchievements: UnlockedAchievement[] = [];
for (const achievement of Object.keys(unlockedAchievements)) {
const unlockedAchievement = unlockedAchievements[achievement];
if (unlockedAchievement?.earned) {
newUnlockedAchievements.push({
name: achievement,
unlockTime: unlockedAchievement.earned_time,
});
}
}
return newUnlockedAchievements;
};
const defaultMerge = (unlockedAchievements: any): UnlockedAchievement[] => {
const newUnlockedAchievements: UnlockedAchievement[] = [];
for (const achievement of Object.keys(unlockedAchievements)) {
const unlockedAchievement = unlockedAchievements[achievement];
if (unlockedAchievement?.Achieved) {
newUnlockedAchievements.push({
name: achievement,
unlockTime: unlockedAchievement.UnlockTime,
});
}
}
return newUnlockedAchievements;
};
const genericMerge = (unlockedAchievements: any): UnlockedAchievement[] => {
const newUnlockedAchievements: UnlockedAchievement[] = [];
for (const achievement of Object.keys(unlockedAchievements)) {
const unlockedAchievement = unlockedAchievements[achievement];
if (unlockedAchievement?.unlocked) {
newUnlockedAchievements.push({
name: achievement,
unlockTime: unlockedAchievement.time,
});
}
}
return newUnlockedAchievements;
};

View File

@ -0,0 +1,115 @@
import path from "node:path";
import fs from "node:fs";
import { app } from "electron";
import type { AchievementFile } from "@types";
import { Cracker } from "@shared";
import { Game } from "@main/entity";
//TODO: change to a automatized method
const publicDir = path.join("C:", "Users", "Public", "Documents");
const programData = path.join("C:", "ProgramData");
const appData = app.getPath("appData");
const crackers = [
Cracker.codex,
Cracker.goldberg,
Cracker.goldberg2,
Cracker.rune,
Cracker.onlineFix,
Cracker.userstats,
Cracker.rld,
];
const getPathFromCracker = (cracker: Cracker) => {
let folderPath: string;
let fileLocation: string[];
if (cracker === Cracker.onlineFix) {
folderPath = path.join(publicDir, Cracker.onlineFix);
fileLocation = ["Stats", "Achievements.ini"];
} else if (cracker === Cracker.goldberg) {
folderPath = path.join(appData, "Goldberg SteamEmu Saves");
fileLocation = ["achievements.json"];
} else if (cracker === Cracker.goldberg2) {
folderPath = path.join(appData, "GSE Saves");
fileLocation = ["achievements.json"];
} else if (cracker === Cracker.rld) {
folderPath = path.join(programData, Cracker.rld);
fileLocation = ["achievements.ini"];
} else {
folderPath = path.join(publicDir, "Steam", cracker);
fileLocation = ["achievements.ini"];
}
return { folderPath, fileLocation };
};
export const findAchievementFiles = (game: Game) => {
const achievementFiles: AchievementFile[] = [];
for (const cracker of crackers) {
const { folderPath, fileLocation } = getPathFromCracker(cracker);
const filePath = path.join(folderPath, game.objectID, ...fileLocation);
if (fs.existsSync(filePath)) {
achievementFiles.push({
type: cracker,
filePath: path.join(folderPath, game.objectID, ...fileLocation),
});
}
}
return achievementFiles;
};
export const findAchievementFileInExecutableDirectory = (
game: Game
): AchievementFile | null => {
if (!game.executablePath) {
return null;
}
const steamDataPath = path.join(
game.executablePath,
"..",
"SteamData",
"user_stats.ini"
);
return {
type: Cracker.userstats,
filePath: steamDataPath,
};
};
export const findAllAchievementFiles = () => {
const gameAchievementFiles = new Map<string, AchievementFile[]>();
for (const cracker of crackers) {
const { folderPath, fileLocation } = getPathFromCracker(cracker);
if (!fs.existsSync(folderPath)) {
return gameAchievementFiles;
}
const objectIds = fs.readdirSync(folderPath);
for (const objectId of objectIds) {
const filePath = path.join(folderPath, objectId, ...fileLocation);
if (!fs.existsSync(filePath)) continue;
const achivementFile = {
type: cracker,
filePath,
};
gameAchievementFiles.get(objectId)
? gameAchievementFiles.get(objectId)!.push(achivementFile)
: gameAchievementFiles.set(objectId, [achivementFile]);
}
}
return gameAchievementFiles;
};

View File

@ -1,138 +0,0 @@
import path from "node:path";
import fs from "node:fs";
import { app } from "electron";
import type { AchievementFile } from "@types";
import { Cracker } from "@shared";
import { Game } from "@main/entity";
//TODO: change to a automatized method
const publicDir = path.join("C:", "Users", "Public", "Documents");
const appData = app.getPath("appData");
const crackers = [
Cracker.codex,
Cracker.goldberg,
Cracker.goldberg2,
Cracker.rune,
Cracker.onlineFix,
Cracker.generic,
];
const addGame = (
achievementFiles: Map<string, AchievementFile[]>,
achievementPath: string,
objectId: string,
fileLocation: string[],
type: Cracker
) => {
const filePath = path.join(achievementPath, objectId, ...fileLocation);
if (!fs.existsSync(filePath)) return;
const achivementFile = {
type,
filePath,
};
achievementFiles.get(objectId)
? achievementFiles.get(objectId)!.push(achivementFile)
: achievementFiles.set(objectId, [achivementFile]);
};
const getObjectIdsInFolder = (path: string) => {
if (fs.existsSync(path)) {
return fs.readdirSync(path);
}
return [];
};
export const findSteamGameAchievementFiles = (game: Game) => {
const achievementFiles: AchievementFile[] = [];
for (const cracker of crackers) {
let achievementPath: string;
let fileLocation: string[];
if (cracker === Cracker.onlineFix) {
achievementPath = path.join(publicDir, Cracker.onlineFix);
fileLocation = ["Stats", "Achievements.ini"];
} else if (cracker === Cracker.goldberg) {
achievementPath = path.join(appData, "Goldberg SteamEmu Saves");
fileLocation = ["achievements.json"];
} else if (cracker === Cracker.goldberg2) {
achievementPath = path.join(appData, "GSE Saves");
fileLocation = ["achievements.json"];
} else {
achievementPath = path.join(publicDir, "Steam", cracker);
fileLocation = ["achievements.ini"];
}
const filePath = path.join(achievementPath, game.objectID, ...fileLocation);
if (fs.existsSync(filePath)) {
achievementFiles.push({
type: cracker,
filePath: path.join(achievementPath, game.objectID, ...fileLocation),
});
}
}
return achievementFiles;
};
export const findAchievementFileInExecutableDirectory = (
game: Game
): AchievementFile | null => {
if (!game.executablePath) {
return null;
}
const steamDataPath = path.join(
game.executablePath,
"..",
"SteamData",
"user_stats.ini"
);
return {
type: Cracker.generic,
filePath: steamDataPath,
};
};
export const findAllSteamGameAchievementFiles = () => {
const gameAchievementFiles = new Map<string, AchievementFile[]>();
for (const cracker of crackers) {
let achievementPath: string;
let fileLocation: string[];
if (cracker === Cracker.onlineFix) {
achievementPath = path.join(publicDir, Cracker.onlineFix);
fileLocation = ["Stats", "Achievements.ini"];
} else if (cracker === Cracker.goldberg2) {
achievementPath = path.join(appData, "GSE Saves");
fileLocation = ["achievements.json"];
} else if (cracker === Cracker.goldberg) {
achievementPath = path.join(appData, "Goldberg SteamEmu Saves");
fileLocation = ["achievements.json"];
} else {
achievementPath = path.join(publicDir, "Steam", cracker);
fileLocation = ["achievements.ini"];
}
const objectIds = getObjectIdsInFolder(achievementPath);
for (const objectId of objectIds) {
addGame(
gameAchievementFiles,
achievementPath,
objectId,
fileLocation,
cracker
);
}
}
return gameAchievementFiles;
};

View File

@ -1,60 +1,35 @@
import { Cracker } from "@shared";
import { UnlockedAchievement } from "@types";
import { existsSync, createReadStream, readFileSync } from "node:fs";
import readline from "node:readline";
export const parseAchievementFile = async (
filePath: string,
type: Cracker
): Promise<any | null> => {
if (existsSync(filePath)) {
if (type === Cracker.generic) {
return genericParse(filePath);
}
): Promise<UnlockedAchievement[]> => {
if (!existsSync(filePath)) return [];
if (filePath.endsWith(".ini")) {
return iniParse(filePath);
}
if (filePath.endsWith(".json")) {
return jsonParse(filePath);
}
if (type === Cracker.onlineFix) {
const parsed = await iniParse(filePath);
return processOnlineFix(parsed);
}
};
const genericParse = async (filePath: string) => {
try {
const file = createReadStream(filePath);
const lines = readline.createInterface({
input: file,
crlfDelay: Infinity,
});
const object: Record<string, Record<string, string | number>> = {};
for await (const line of lines) {
if (line.startsWith("###") || !line.length) continue;
if (line.startsWith("[") && line.endsWith("]")) {
continue;
}
const [name, ...value] = line.split(" = ");
const objectName = name.slice(1, -1);
object[objectName] = {};
const joinedValue = value.join("=").slice(1, -1);
for (const teste of joinedValue.split(",")) {
const [name, value] = teste.split("=");
object[objectName][name.trim()] = value;
}
}
console.log(object);
return object;
} catch {
return null;
if (type === Cracker.goldberg || type === Cracker.goldberg2) {
const parsed = await jsonParse(filePath);
return processGoldberg(parsed);
}
if (type == Cracker.userstats) {
const parsed = await iniParse(filePath);
return processUserStats(parsed);
}
if (type == Cracker.rld) {
const parsed = await iniParse(filePath);
return processRld(parsed);
}
const parsed = await iniParse(filePath);
return processDefault(parsed);
};
const iniParse = async (filePath: string) => {
@ -77,17 +52,11 @@ const iniParse = async (filePath: string) => {
object[objectName] = {};
} else {
const [name, ...value] = line.split("=");
console.log(line);
console.log(name, value);
const joinedValue = value.join("").trim();
const number = Number(joinedValue);
object[objectName][name.trim()] = isNaN(number) ? joinedValue : number;
object[objectName][name.trim()] = value.join("").trim();
}
}
console.log("Parsed ini", object);
return object;
} catch {
return null;
@ -101,3 +70,101 @@ const jsonParse = (filePath: string) => {
return null;
}
};
const processOnlineFix = (unlockedAchievements: any): UnlockedAchievement[] => {
const parsedUnlockedAchievements: UnlockedAchievement[] = [];
for (const achievement of Object.keys(unlockedAchievements)) {
const unlockedAchievement = unlockedAchievements[achievement];
if (unlockedAchievement?.achieved) {
parsedUnlockedAchievements.push({
name: achievement,
unlockTime: unlockedAchievement.timestamp,
});
}
}
return parsedUnlockedAchievements;
};
const processGoldberg = (unlockedAchievements: any): UnlockedAchievement[] => {
const newUnlockedAchievements: UnlockedAchievement[] = [];
for (const achievement of Object.keys(unlockedAchievements)) {
const unlockedAchievement = unlockedAchievements[achievement];
if (unlockedAchievement?.earned) {
newUnlockedAchievements.push({
name: achievement,
unlockTime: unlockedAchievement.earned_time,
});
}
}
return newUnlockedAchievements;
};
const processDefault = (unlockedAchievements: any): UnlockedAchievement[] => {
const newUnlockedAchievements: UnlockedAchievement[] = [];
for (const achievement of Object.keys(unlockedAchievements)) {
const unlockedAchievement = unlockedAchievements[achievement];
if (unlockedAchievement?.Achieved) {
newUnlockedAchievements.push({
name: achievement,
unlockTime: unlockedAchievement.UnlockTime,
});
}
}
return newUnlockedAchievements;
};
const processRld = (unlockedAchievements: any): UnlockedAchievement[] => {
const newUnlockedAchievements: UnlockedAchievement[] = [];
for (const achievement of Object.keys(unlockedAchievements)) {
if (achievement === "Steam") continue;
const unlockedAchievement = unlockedAchievements[achievement];
if (unlockedAchievement?.State) {
newUnlockedAchievements.push({
name: achievement,
unlockTime: new DataView(
new Uint8Array(
Buffer.from(unlockedAchievement.Time.toString(), "hex")
).buffer
).getUint32(0, true),
});
}
}
return newUnlockedAchievements;
};
const processUserStats = (unlockedAchievements: any): UnlockedAchievement[] => {
const newUnlockedAchievements: UnlockedAchievement[] = [];
const achievements = unlockedAchievements["ACHIEVEMENTS"];
if (!achievements) return [];
for (const achievement of Object.keys(achievements)) {
const unlockedAchievement = achievements[achievement];
const unlockTime = Number(
unlockedAchievement.slice(1, -1).replace("unlocked = true, time = ", "")
);
if (!isNaN(unlockTime)) {
newUnlockedAchievements.push({
name: achievement,
unlockTime: unlockTime,
});
}
}
return newUnlockedAchievements;
};

View File

@ -1,16 +1,15 @@
import { gameAchievementRepository, gameRepository } from "@main/repository";
import {
findAllSteamGameAchievementFiles,
findSteamGameAchievementFiles,
} from "./find-steam-game-achivement-files";
findAllAchievementFiles,
findAchievementFiles,
} from "./find-achivement-files";
import { parseAchievementFile } from "./parse-achievement-file";
import { checkUnlockedAchievements } from "./check-unlocked-achievements";
import { mergeAchievements } from "./merge-achievements";
import type { UnlockedAchievement } from "@types";
import { getGameAchievementData } from "./get-game-achievement-data";
export const updateAllLocalUnlockedAchievements = async () => {
const gameAchievementFilesMap = findAllSteamGameAchievementFiles();
const gameAchievementFilesMap = findAllAchievementFiles();
for (const objectId of gameAchievementFilesMap.keys()) {
const gameAchievementFiles = gameAchievementFilesMap.get(objectId)!;
@ -26,8 +25,6 @@ export const updateAllLocalUnlockedAchievements = async () => {
if (!game) continue;
console.log("Achievements files for", game.title, gameAchievementFiles);
if (!localAchievements || !localAchievements.achievements) {
await getGameAchievementData(objectId, "steam")
.then((achievements) => {
@ -46,18 +43,13 @@ export const updateAllLocalUnlockedAchievements = async () => {
const unlockedAchievements: UnlockedAchievement[] = [];
for (const achievementFile of gameAchievementFiles) {
const localAchievementFile = await parseAchievementFile(
const parsedAchievements = await parseAchievementFile(
achievementFile.filePath,
achievementFile.type
);
if (localAchievementFile) {
unlockedAchievements.push(
...checkUnlockedAchievements(
achievementFile.type,
localAchievementFile
)
);
console.log("Parsed for", game.title, parsedAchievements);
if (parsedAchievements.length) {
unlockedAchievements.push(...parsedAchievements);
}
}
@ -65,10 +57,7 @@ export const updateAllLocalUnlockedAchievements = async () => {
}
};
export const updateLocalUnlockedAchivements = async (
publishNotification: boolean,
objectId: string
) => {
export const updateLocalUnlockedAchivements = async (objectId: string) => {
const [game, localAchievements] = await Promise.all([
gameRepository.findOne({
where: { objectID: objectId, shop: "steam", isDeleted: false },
@ -80,7 +69,7 @@ export const updateLocalUnlockedAchivements = async (
if (!game) return;
const gameAchievementFiles = findSteamGameAchievementFiles(game);
const gameAchievementFiles = findAchievementFiles(game);
console.log("Achievements files for", game.title, gameAchievementFiles);
@ -107,17 +96,10 @@ export const updateLocalUnlockedAchivements = async (
achievementFile.type
);
if (localAchievementFile) {
unlockedAchievements.push(
...checkUnlockedAchievements(achievementFile.type, localAchievementFile)
);
if (localAchievementFile.length) {
unlockedAchievements.push(...localAchievementFile);
}
}
mergeAchievements(
objectId,
"steam",
unlockedAchievements,
publishNotification
);
mergeAchievements(objectId, "steam", unlockedAchievements, false);
};

View File

@ -30,5 +30,6 @@ export enum Cracker {
onlineFix = "OnlineFix",
goldberg = "Goldberg",
goldberg2 = "Goldberg2",
generic = "Generic",
userstats = "user_stats",
rld = "RLD!",
}