feat: refactor

This commit is contained in:
Zamitto 2024-10-20 21:29:17 -03:00
parent 33e91e2007
commit 36e6a8cef7
37 changed files with 151 additions and 254 deletions

View File

@ -1,4 +1,4 @@
import { AppUpdaterEvent } from "@types";
import type { AppUpdaterEvent } from "@types";
import { registerEvent } from "../register-event";
import updater, { UpdateInfo } from "electron-updater";
import { WindowManager } from "@main/services";

View File

@ -1,147 +0,0 @@
import type {
AchievementData,
GameShop,
RemoteUnlockedAchievement,
UnlockedAchievement,
UserAchievement,
} from "@types";
import { registerEvent } from "../register-event";
import {
gameAchievementRepository,
userPreferencesRepository,
} from "@main/repository";
import { getGameAchievementData } from "@main/services/achievements/get-game-achievement-data";
import { HydraApi } from "@main/services";
const getAchievementLocalUser = async (shop: string, objectId: string) => {
const cachedAchievements = await gameAchievementRepository.findOne({
where: { objectId, shop },
});
const achievementsData = await getGameAchievementData(objectId, shop);
const unlockedAchievements = JSON.parse(
cachedAchievements?.unlockedAchievements || "[]"
) as UnlockedAchievement[];
return achievementsData
.map((achievementData) => {
const unlockedAchiementData = unlockedAchievements.find(
(localAchievement) => {
return (
localAchievement.name.toUpperCase() ==
achievementData.name.toUpperCase()
);
}
);
const icongray = achievementData.icongray.endsWith("/")
? achievementData.icon
: achievementData.icongray;
if (unlockedAchiementData) {
return {
...achievementData,
unlocked: true,
unlockTime: unlockedAchiementData.unlockTime,
};
}
return {
...achievementData,
unlocked: false,
unlockTime: null,
icongray: icongray,
} as UserAchievement;
})
.sort((a, b) => {
if (a.unlocked && !b.unlocked) return -1;
if (!a.unlocked && b.unlocked) return 1;
if (a.unlocked && b.unlocked) {
return b.unlockTime! - a.unlockTime!;
}
return Number(a.hidden) - Number(b.hidden);
});
};
const getAchievementsRemoteUser = async (
shop: string,
objectId: string,
userId: string
) => {
const userPreferences = await userPreferencesRepository.findOne({
where: { id: 1 },
});
const achievementsData: AchievementData[] = await getGameAchievementData(
objectId,
shop
);
const unlockedAchievements = await HydraApi.get<RemoteUnlockedAchievement[]>(
`/users/${userId}/games/achievements`,
{ shop, objectId, language: userPreferences?.language || "en" }
);
return achievementsData
.map((achievementData) => {
const unlockedAchiementData = unlockedAchievements.find(
(localAchievement) => {
return (
localAchievement.name.toUpperCase() ==
achievementData.name.toUpperCase()
);
}
);
const icongray = achievementData.icongray.endsWith("/")
? achievementData.icon
: achievementData.icongray;
if (unlockedAchiementData) {
return {
...achievementData,
unlocked: true,
unlockTime: unlockedAchiementData.unlockTime,
};
}
return {
...achievementData,
unlocked: false,
unlockTime: null,
icongray: icongray,
} as UserAchievement;
})
.sort((a, b) => {
if (a.unlocked && !b.unlocked) return -1;
if (!a.unlocked && b.unlocked) return 1;
if (a.unlocked && b.unlocked) {
return b.unlockTime! - a.unlockTime!;
}
return Number(a.hidden) - Number(b.hidden);
});
};
export const getGameAchievements = async (
objectId: string,
shop: GameShop,
userId?: string
): Promise<UserAchievement[]> => {
if (!userId) {
return getAchievementLocalUser(shop, objectId);
}
return getAchievementsRemoteUser(shop, objectId, userId);
};
const getGameAchievementsEvent = async (
_event: Electron.IpcMainInvokeEvent,
objectId: string,
shop: GameShop,
userId?: string
): Promise<UserAchievement[]> => {
return getGameAchievements(objectId, shop, userId);
};
registerEvent("getGameAchievements", getGameAchievementsEvent);

View File

@ -1,8 +1,6 @@
import type { GameShop } from "@types";
import type { GameShop, GameStats } from "@types";
import { registerEvent } from "../register-event";
import { HydraApi } from "@main/services";
import type { GameStats } from "@types";
const getGameStats = async (
_event: Electron.IpcMainInvokeEvent,

View File

@ -1,7 +1,7 @@
import { registerEvent } from "../register-event";
import { HydraApi } from "@main/services";
import { userPreferencesRepository } from "@main/repository";
import { TrendingGame } from "@types";
import type { TrendingGame } from "@types";
const getTrendingGames = async (_event: Electron.IpcMainInvokeEvent) => {
const userPreferences = await userPreferencesRepository.findOne({

View File

@ -1,6 +1,6 @@
import { registerEvent } from "../register-event";
import { convertSteamGameToCatalogueEntry } from "../helpers/search-games";
import { CatalogueEntry } from "@types";
import type { CatalogueEntry } from "@types";
import { HydraApi } from "@main/services";
const searchGamesEvent = async (

View File

@ -1,5 +1,5 @@
import { registerEvent } from "../register-event";
import { GameShop } from "@types";
import type { GameShop } from "@types";
import { Ludusavi } from "@main/services";
import path from "node:path";
import { backupsPath } from "@main/constants";

View File

@ -4,7 +4,7 @@ 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 type { GameShop } from "@types";
import axios from "axios";
import os from "node:os";
import { backupsPath } from "@main/constants";

View File

@ -9,7 +9,6 @@ import "./catalogue/get-random-game";
import "./catalogue/search-games";
import "./catalogue/get-game-stats";
import "./catalogue/get-trending-games";
import "./catalogue/get-game-achievements";
import "./hardware/get-disk-free-space";
import "./library/add-game-to-library";
import "./library/create-game-shortcut";
@ -50,6 +49,7 @@ import "./user/unblock-user";
import "./user/get-user-friends";
import "./user/get-user-stats";
import "./user/report-user";
import "./user/get-unlocked-achievements";
import "./user/get-compared-unlocked-achievements";
import "./profile/get-friend-requests";
import "./profile/get-me";

View File

@ -1,6 +1,6 @@
import { registerEvent } from "../register-event";
import { HydraApi } from "@main/services";
import { FriendRequest } from "@types";
import type { FriendRequest } from "@types";
const getFriendRequests = async (
_event: Electron.IpcMainInvokeEvent

View File

@ -1,7 +1,7 @@
import { registerEvent } from "../register-event";
import * as Sentry from "@sentry/electron/main";
import { HydraApi, logger } from "@main/services";
import { ProfileVisibility, UserDetails } from "@types";
import type { ProfileVisibility, UserDetails } from "@types";
import {
userAuthRepository,
userSubscriptionRepository,

View File

@ -1,7 +1,7 @@
import { registerEvent } from "../register-event";
import { HydraApi } from "@main/services";
import { UserNotLoggedInError } from "@shared";
import { FriendRequestSync } from "@types";
import type { FriendRequestSync } from "@types";
const syncFriendRequests = async (_event: Electron.IpcMainInvokeEvent) => {
return HydraApi.get<FriendRequestSync>(`/profile/friend-requests/sync`).catch(

View File

@ -1,6 +1,6 @@
import { registerEvent } from "../register-event";
import { HydraApi } from "@main/services";
import { FriendRequestAction } from "@types";
import type { FriendRequestAction } from "@types";
const updateFriendRequest = async (
_event: Electron.IpcMainInvokeEvent,

View File

@ -1,7 +1,7 @@
import { registerEvent } from "../register-event";
import { HydraApi } from "@main/services";
import { UserNotLoggedInError } from "@shared";
import { UserBlocks } from "@types";
import type { UserBlocks } from "@types";
export const getBlockedUsers = async (
_event: Electron.IpcMainInvokeEvent,

View File

@ -0,0 +1,68 @@
import type { GameShop, UnlockedAchievement, UserAchievement } from "@types";
import { registerEvent } from "../register-event";
import { gameAchievementRepository } from "@main/repository";
import { getGameAchievementData } from "@main/services/achievements/get-game-achievement-data";
export const getUnlockedAchievements = async (
objectId: string,
shop: GameShop
): Promise<UserAchievement[]> => {
const cachedAchievements = await gameAchievementRepository.findOne({
where: { objectId, shop },
});
const achievementsData = await getGameAchievementData(objectId, shop);
const unlockedAchievements = JSON.parse(
cachedAchievements?.unlockedAchievements || "[]"
) as UnlockedAchievement[];
return achievementsData
.map((achievementData) => {
const unlockedAchiementData = unlockedAchievements.find(
(localAchievement) => {
return (
localAchievement.name.toUpperCase() ==
achievementData.name.toUpperCase()
);
}
);
const icongray = achievementData.icongray.endsWith("/")
? achievementData.icon
: achievementData.icongray;
if (unlockedAchiementData) {
return {
...achievementData,
unlocked: true,
unlockTime: unlockedAchiementData.unlockTime,
};
}
return {
...achievementData,
unlocked: false,
unlockTime: null,
icongray: icongray,
} as UserAchievement;
})
.sort((a, b) => {
if (a.unlocked && !b.unlocked) return -1;
if (!a.unlocked && b.unlocked) return 1;
if (a.unlocked && b.unlocked) {
return b.unlockTime! - a.unlockTime!;
}
return Number(a.hidden) - Number(b.hidden);
});
};
const getGameAchievementsEvent = async (
_event: Electron.IpcMainInvokeEvent,
objectId: string,
shop: GameShop
): Promise<UserAchievement[]> => {
return getUnlockedAchievements(objectId, shop);
};
registerEvent("getUnlockedAchievements", getGameAchievementsEvent);

View File

@ -1,7 +1,7 @@
import { userAuthRepository } from "@main/repository";
import { registerEvent } from "../register-event";
import { HydraApi } from "@main/services";
import { UserFriends } from "@types";
import type { UserFriends } from "@types";
export const getUserFriends = async (
userId: string,

View File

@ -16,7 +16,7 @@ import { IsNull, Not } from "typeorm";
const fileStats: Map<string, number> = new Map();
const fltFiles: Map<string, Set<string>> = new Map();
const watchAchiievementsWindows = async () => {
const watchAchievementsWindows = async () => {
const games = await gameRepository.find({
where: {
isDeleted: false,
@ -53,12 +53,17 @@ const watchAchievementsWithWine = async () => {
if (games.length === 0) return;
// const user = app.getPath("home").split("/").pop()
// for (const game of games) {
// }
// TODO: watch achievements with wine
};
export const watchAchievements = async () => {
if (process.platform === "win32") {
return watchAchiievementsWindows();
return watchAchievementsWindows();
}
watchAchievementsWithWine();
@ -101,10 +106,9 @@ const compareFltFolder = async (game: Game, file: AchievementFile) => {
}
};
const compareFile = async (game: Game, file: AchievementFile) => {
const compareFile = (game: Game, file: AchievementFile) => {
if (file.type === Cracker.flt) {
await compareFltFolder(game, file);
return;
return compareFltFolder(game, file);
}
try {
@ -121,8 +125,7 @@ const compareFile = async (game: Game, file: AchievementFile) => {
currentStat.mtimeMs
);
await processAchievementFileDiff(game, file);
return;
return processAchievementFileDiff(game, file);
}
}
@ -136,8 +139,9 @@ const compareFile = async (game: Game, file: AchievementFile) => {
previousStat,
currentStat.mtimeMs
);
await processAchievementFileDiff(game, file);
return processAchievementFileDiff(game, file);
} catch (err) {
fileStats.set(file.filePath, -1);
return;
}
};

View File

@ -3,13 +3,13 @@ import {
userPreferencesRepository,
} from "@main/repository";
import { HydraApi } from "../hydra-api";
import { AchievementData } from "@types";
import type { AchievementData, GameShop } from "@types";
import { UserNotLoggedInError } from "@shared";
import { logger } from "../logger";
export const getGameAchievementData = async (
objectId: string,
shop: string
shop: GameShop
) => {
const userPreferences = await userPreferencesRepository.findOne({
where: { id: 1 },

View File

@ -6,11 +6,11 @@ import {
import type { AchievementData, GameShop, UnlockedAchievement } from "@types";
import { WindowManager } from "../window-manager";
import { HydraApi } from "../hydra-api";
import { getGameAchievements } from "@main/events/catalogue/get-game-achievements";
import { getUnlockedAchievements } from "@main/events/user/get-unlocked-achievements";
const saveAchievementsOnLocal = async (
objectId: string,
shop: string,
shop: GameShop,
achievements: any[]
) => {
return gameAchievementRepository
@ -23,7 +23,7 @@ const saveAchievementsOnLocal = async (
["objectId", "shop"]
)
.then(() => {
return getGameAchievements(objectId, shop as GameShop)
return getUnlockedAchievements(objectId, shop)
.then((achievements) => {
WindowManager.mainWindow?.webContents.send(
`on-update-achievements-${objectId}-${shop}`,
@ -36,12 +36,12 @@ const saveAchievementsOnLocal = async (
export const mergeAchievements = async (
objectId: string,
shop: string,
shop: GameShop,
achievements: UnlockedAchievement[],
publishNotification: boolean
) => {
const game = await gameRepository.findOne({
where: { objectID: objectId, shop: shop as GameShop },
where: { objectID: objectId, shop: shop },
});
if (!game) return;

View File

@ -7,7 +7,7 @@ import {
startTorrentClient as startRPCClient,
} from "./torrent-client";
import { gameRepository } from "@main/repository";
import { DownloadProgress } from "@types";
import type { DownloadProgress } from "@types";
import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity";
import { calculateETA } from "./helpers";
import axios from "axios";

View File

@ -1,4 +1,4 @@
import { SteamGame } from "@types";
import type { SteamGame } from "@types";
import { slice } from "lodash-es";
import fs from "node:fs";

View File

@ -51,8 +51,6 @@ contextBridge.exposeInMainWorld("electron", {
getGameStats: (objectId: string, shop: GameShop) =>
ipcRenderer.invoke("getGameStats", objectId, shop),
getTrendingGames: () => ipcRenderer.invoke("getTrendingGames"),
getGameAchievements: (objectId: string, shop: GameShop, userId?: string) =>
ipcRenderer.invoke("getGameAchievements", objectId, shop, userId),
onAchievementUnlocked: (
cb: (
objectId: string,
@ -270,6 +268,8 @@ contextBridge.exposeInMainWorld("electron", {
shop,
userId
),
getUnlockedAchievements: (objectId: string, shop: GameShop) =>
ipcRenderer.invoke("getUnlockedAchievements", objectId, shop),
/* Auth */
signOut: () => ipcRenderer.invoke("signOut"),

View File

@ -3,7 +3,7 @@ import { useEffect, useState } from "react";
import { SyncIcon } from "@primer/octicons-react";
import { Link } from "../link/link";
import * as styles from "./header.css";
import { AppUpdaterEvent } from "@types";
import type { AppUpdaterEvent } from "@types";
export const releasesPageUrl =
"https://github.com/hydralauncher/hydra/releases/latest";

View File

@ -1,7 +1,7 @@
import { useNavigate } from "react-router-dom";
import * as styles from "./hero.css";
import { useEffect, useState } from "react";
import { TrendingGame } from "@types";
import type { TrendingGame } from "@types";
import { useTranslation } from "react-i18next";
import Skeleton from "react-loading-skeleton";

View File

@ -155,14 +155,15 @@ export function GameDetailsContextProvider({
setStats(result);
});
window.electron
.getGameAchievements(objectId, shop as GameShop)
.then((achievements) => {
if (abortController.signal.aborted) return;
if (!userDetails) return;
setAchievements(achievements);
})
.catch(() => {});
if (userDetails) {
window.electron
.getUnlockedAchievements(objectId, shop as GameShop)
.then((achievements) => {
if (abortController.signal.aborted) return;
setAchievements(achievements);
})
.catch(() => {});
}
updateGame();
}, [

View File

@ -66,11 +66,6 @@ declare global {
searchGameRepacks: (query: string) => Promise<GameRepack[]>;
getGameStats: (objectId: string, shop: GameShop) => Promise<GameStats>;
getTrendingGames: () => Promise<TrendingGame[]>;
getGameAchievements: (
objectId: string,
shop: GameShop,
userId?: string
) => Promise<UserAchievement[]>;
onAchievementUnlocked: (
cb: (
objectId: string,
@ -208,6 +203,10 @@ declare global {
shop: GameShop,
userId: string
) => Promise<ComparedAchievements>;
getUnlockedAchievements: (
objectId: string,
shop: GameShop
) => Promise<UserAchievement[]>;
/* Profile */
getMe: () => Promise<UserDetails | null>;

View File

@ -1,5 +1,5 @@
import { PayloadAction, createSlice } from "@reduxjs/toolkit";
import { GameRunning } from "@types";
import type { GameRunning } from "@types";
export interface GameRunningState {
gameRunning: GameRunning | null;

View File

@ -11,14 +11,14 @@ import {
import { LockIcon, PersonIcon, TrophyIcon } from "@primer/octicons-react";
import { SPACING_UNIT, vars } from "@renderer/theme.css";
import { gameDetailsContext } from "@renderer/context";
import { ComparedAchievements, UserAchievement } from "@types";
import type { ComparedAchievements, UserAchievement } from "@types";
import { average } from "color.js";
import Color from "color";
import { Link } from "@renderer/components";
import { ComparedAchievementList } from "./compared-achievement-list";
interface UserInfo {
userId: string;
id: string;
displayName: string;
profileImageUrl: string | null;
totalAchievementCount: number;
@ -43,7 +43,9 @@ function AchievementSummary({ user, isComparison }: AchievementSummaryProps) {
const { t } = useTranslation("achievement");
const { userDetails, hasActiveSubscription } = useUserDetails();
const getProfileImage = (user: UserInfo) => {
const getProfileImage = (
user: Pick<UserInfo, "profileImageUrl" | "displayName">
) => {
return (
<div className={styles.profileAvatar}>
{user.profileImageUrl ? (
@ -59,11 +61,7 @@ function AchievementSummary({ user, isComparison }: AchievementSummaryProps) {
);
};
if (
isComparison &&
userDetails?.id == user.userId &&
!hasActiveSubscription
) {
if (isComparison && userDetails?.id == user.id && !hasActiveSubscription) {
return (
<div
style={{
@ -213,11 +211,8 @@ export function AchievementsContent({
const dispatch = useAppDispatch();
const { userDetails, hasActiveSubscription } = useUserDetails();
useEffect(() => {
if (gameTitle) {
dispatch(setHeaderTitle(gameTitle));
}
dispatch(setHeaderTitle(gameTitle));
}, [dispatch, gameTitle]);
const handleHeroLoad = async () => {
@ -247,16 +242,15 @@ export function AchievementsContent({
};
const getProfileImage = (
profileImageUrl: string | null,
displayName: string
user: Pick<UserInfo, "profileImageUrl" | "displayName">
) => {
return (
<div className={styles.profileAvatarSmall}>
{profileImageUrl ? (
{user.profileImageUrl ? (
<img
className={styles.profileAvatarSmall}
src={profileImageUrl}
alt={displayName}
src={user.profileImageUrl}
alt={user.displayName}
/>
) : (
<PersonIcon size={24} />
@ -315,7 +309,6 @@ export function AchievementsContent({
<AchievementSummary
user={{
...userDetails,
userId: userDetails.id,
totalAchievementCount: comparedAchievements
? comparedAchievements.owner.totalAchievementCount
: achievements!.length,
@ -346,36 +339,21 @@ export function AchievementsContent({
<div></div>
{hasActiveSubscription && (
<div style={{ display: "flex", justifyContent: "center" }}>
{getProfileImage(
userDetails.profileImageUrl,
userDetails.displayName
)}
{getProfileImage({ ...userDetails })}
</div>
)}
<div style={{ display: "flex", justifyContent: "center" }}>
{getProfileImage(
otherUser.profileImageUrl,
otherUser.displayName
)}
{getProfileImage(otherUser)}
</div>
</div>
</div>
)}
<div
style={{
display: "flex",
flexDirection: "row",
width: "100%",
backgroundColor: vars.color.background,
}}
>
{otherUser ? (
<ComparedAchievementList achievements={comparedAchievements!} />
) : (
<AchievementList achievements={achievements!} />
)}
</div>
{otherUser ? (
<ComparedAchievementList achievements={comparedAchievements!} />
) : (
<AchievementList achievements={achievements!} />
)}
</section>
</div>
);

View File

@ -4,7 +4,7 @@ import * as styles from "./achievements.css";
export function AchievementsSkeleton() {
return (
<div className={styles.container}>
<div className={styles.heroImage}>
<div className={styles.hero}>
<Skeleton className={styles.heroImageSkeleton} />
</div>
<div className={styles.heroPanelSkeleton}></div>

View File

@ -3,8 +3,8 @@ import { style } from "@vanilla-extract/css";
import { recipe } from "@vanilla-extract/recipes";
export const HERO_HEIGHT = 150;
export const LOGO_HEIGHT = 100;
export const LOGO_MAX_WIDTH = 200;
const LOGO_HEIGHT = 100;
const LOGO_MAX_WIDTH = 200;
export const wrapper = style({
display: "flex",
@ -104,6 +104,7 @@ export const list = style({
gap: `${SPACING_UNIT * 2}px`,
padding: `${SPACING_UNIT * 2}px`,
width: "100%",
backgroundColor: vars.color.background,
});
export const listItem = style({
@ -162,12 +163,7 @@ export const heroLogoBackdrop = style({
});
export const heroImageSkeleton = style({
height: "300px",
"@media": {
"(min-width: 1250px)": {
height: "350px",
},
},
height: "150px",
});
export const heroPanelSkeleton = style({

View File

@ -52,7 +52,7 @@ export default function Achievements() {
if (!otherUserId || !comparedAchievements) return null;
return {
userId: otherUserId,
id: otherUserId,
displayName: comparedAchievements.target.displayName,
profileImageUrl: comparedAchievements.target.profileImageUrl,
totalAchievementCount: comparedAchievements.target.totalAchievementCount,

View File

@ -7,7 +7,7 @@ import { BinaryNotFoundModal } from "../shared-modals/binary-not-found-modal";
import * as styles from "./downloads.css";
import { DeleteGameModal } from "./delete-game-modal";
import { DownloadGroup } from "./download-group";
import { LibraryGame } from "@types";
import type { LibraryGame } from "@types";
import { orderBy } from "lodash-es";
import { ArrowDownIcon } from "@primer/octicons-react";

View File

@ -1,7 +1,7 @@
import { useEffect, useState } from "react";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import { GameRepack, GameShop, Steam250Game } from "@types";
import type { GameRepack, GameShop, Steam250Game } from "@types";
import { Button, ConfirmationModal } from "@renderer/components";
import { buildGameDetailsPath } from "@renderer/helpers";

View File

@ -1,7 +1,7 @@
import { useTranslation } from "react-i18next";
import { Button, Modal } from "@renderer/components";
import * as styles from "./remove-from-library-modal.css";
import { Game } from "@types";
import type { Game } from "@types";
interface RemoveGameFromLibraryModalProps {
visible: boolean;

View File

@ -14,7 +14,7 @@ import { LockedProfile } from "./locked-profile";
import { ReportProfile } from "../report-profile/report-profile";
import { FriendsBox } from "./friends-box";
import { RecentGamesBox } from "./recent-games-box";
import { UserGame } from "@types";
import type { UserGame } from "@types";
import {
buildGameAchievementPath,
buildGameDetailsPath,

View File

@ -9,7 +9,7 @@ import { useForm } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { downloadSourcesTable } from "@renderer/dexie";
import { DownloadSourceValidationResult } from "@types";
import type { DownloadSourceValidationResult } from "@types";
import { downloadSourcesWorker } from "@renderer/workers";
interface AddDownloadSourceModalProps {

View File

@ -1,5 +1,5 @@
import { SPACING_UNIT, vars } from "@renderer/theme.css";
import { UserFriend } from "@types";
import type { UserFriend } from "@types";
import { useEffect, useRef, useState } from "react";
import { UserFriendItem } from "./user-friend-item";
import { useNavigate } from "react-router-dom";

View File

@ -1,6 +1,6 @@
import { repacksTable } from "@renderer/dexie";
import { formatName } from "@shared";
import { GameRepack } from "@types";
import type { GameRepack } from "@types";
import flexSearch from "flexsearch";
interface SerializedGameRepack extends Omit<GameRepack, "uris"> {