Skip to content

Commit

Permalink
Merge pull request #948 from hydralauncher/feat/search-games-from-api
Browse files Browse the repository at this point in the history
feat: search games from api
  • Loading branch information
zamitto authored Sep 12, 2024
2 parents 262e95e + ad3c2df commit 87cacdf
Show file tree
Hide file tree
Showing 10 changed files with 142 additions and 80 deletions.
3 changes: 2 additions & 1 deletion src/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"featured": "Featured",
"trending": "Trending",
"surprise_me": "Surprise me",
"no_results": "No results found"
"no_results": "No results found",
"start_typing": "Starting typing to search..."
},
"sidebar": {
"catalogue": "Catalogue",
Expand Down
3 changes: 2 additions & 1 deletion src/locales/pt-BR/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"featured": "Destaques",
"trending": "Populares",
"surprise_me": "Surpreenda-me",
"no_results": "Nenhum resultado encontrado"
"no_results": "Nenhum resultado encontrado",
"start_typing": "Comece a digitar para pesquisar…"
},
"sidebar": {
"catalogue": "Catálogo",
Expand Down
3 changes: 2 additions & 1 deletion src/locales/pt-PT/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"featured": "Destaques",
"trending": "Populares",
"surprise_me": "Surpreende-me",
"no_results": "Nenhum resultado encontrado"
"no_results": "Nenhum resultado encontrado",
"start_typing": "Comece a digitar para pesquisar…"
},
"sidebar": {
"catalogue": "Catálogo",
Expand Down
12 changes: 4 additions & 8 deletions src/main/events/catalogue/get-random-game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { shuffle } from "lodash-es";
import { getSteam250List } from "@main/services";

import { registerEvent } from "../register-event";
import { searchSteamGames } from "../helpers/search-games";
import { getSteamGameById } from "../helpers/search-games";
import type { Steam250Game } from "@types";

const state = { games: Array<Steam250Game>(), index: 0 };
Expand All @@ -12,14 +12,10 @@ const filterGames = async (games: Steam250Game[]) => {
const results: Steam250Game[] = [];

for (const game of games) {
const catalogue = await searchSteamGames({ query: game.title });
const steamGame = await getSteamGameById(game.objectID);

if (catalogue.length) {
const [steamGame] = catalogue;

if (steamGame.repacks.length) {
results.push(game);
}
if (steamGame?.repacks.length) {
results.push(game);
}
}

Expand Down
19 changes: 17 additions & 2 deletions src/main/events/catalogue/search-games.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,25 @@
import { registerEvent } from "../register-event";
import { searchSteamGames } from "../helpers/search-games";
import { convertSteamGameToCatalogueEntry } from "../helpers/search-games";
import { CatalogueEntry } from "@types";
import { HydraApi, RepacksManager } from "@main/services";

const searchGamesEvent = async (
_event: Electron.IpcMainInvokeEvent,
query: string
): Promise<CatalogueEntry[]> => searchSteamGames({ query, limit: 12 });
): Promise<CatalogueEntry[]> => {
const games = await HydraApi.get<
{ objectId: string; title: string; shop: string }[]
>("/games/search", { title: query, take: 12, skip: 0 }, { needsAuth: false });

const steamGames = games.map((game) => {
return convertSteamGameToCatalogueEntry({
id: Number(game.objectId),
name: game.title,
clientIcon: null,
});
});

return RepacksManager.findRepacksForCatalogueEntries(steamGames);
};

registerEvent("searchGames", searchGamesEvent);
33 changes: 14 additions & 19 deletions src/main/events/helpers/search-games.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import { orderBy } from "lodash-es";
import flexSearch from "flexsearch";

import type { GameShop, CatalogueEntry, SteamGame } from "@types";

import { getSteamAppAsset } from "@main/helpers";
Expand All @@ -23,20 +20,18 @@ export const convertSteamGameToCatalogueEntry = (
repacks: [],
});

export const searchSteamGames = async (
options: flexSearch.SearchOptions
): Promise<CatalogueEntry[]> => {
const steamGames = (await steamGamesWorker.run(options, {
name: "search",
})) as SteamGame[];

const result = RepacksManager.findRepacksForCatalogueEntries(
steamGames.map((game) => convertSteamGameToCatalogueEntry(game))
);

return orderBy(
result,
[({ repacks }) => repacks.length, "repacks"],
["desc"]
);
export const getSteamGameById = async (
objectId: string
): Promise<CatalogueEntry | null> => {
const steamGame = await steamGamesWorker.run(Number(objectId), {
name: "getById",
});

if (!steamGame) return null;

const catalogueEntry = convertSteamGameToCatalogueEntry(steamGame);

const result = RepacksManager.findRepacksForCatalogueEntry(catalogueEntry);

return result;
};
60 changes: 45 additions & 15 deletions src/main/services/hydra-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import { clearGamesRemoteIds } from "./library-sync/clear-games-remote-id";
import { logger } from "./logger";
import { UserNotLoggedInError } from "@shared";

interface HydraApiOptions {
needsAuth: boolean;
}

export class HydraApi {
private static instance: AxiosInstance;

Expand Down Expand Up @@ -204,50 +208,76 @@ export class HydraApi {
throw err;
};

static async get<T = any>(url: string, params?: any) {
if (!this.isLoggedIn()) throw new UserNotLoggedInError();
static async get<T = any>(
url: string,
params?: any,
options?: HydraApiOptions
) {
if (!options || options.needsAuth) {
if (!this.isLoggedIn()) throw new UserNotLoggedInError();
await this.revalidateAccessTokenIfExpired();
}

await this.revalidateAccessTokenIfExpired();
return this.instance
.get<T>(url, { params, ...this.getAxiosConfig() })
.then((response) => response.data)
.catch(this.handleUnauthorizedError);
}

static async post<T = any>(url: string, data?: any) {
if (!this.isLoggedIn()) throw new UserNotLoggedInError();
static async post<T = any>(
url: string,
data?: any,
options?: HydraApiOptions
) {
if (!options || options.needsAuth) {
if (!this.isLoggedIn()) throw new UserNotLoggedInError();
await this.revalidateAccessTokenIfExpired();
}

await this.revalidateAccessTokenIfExpired();
return this.instance
.post<T>(url, data, this.getAxiosConfig())
.then((response) => response.data)
.catch(this.handleUnauthorizedError);
}

static async put<T = any>(url: string, data?: any) {
if (!this.isLoggedIn()) throw new UserNotLoggedInError();
static async put<T = any>(
url: string,
data?: any,
options?: HydraApiOptions
) {
if (!options || options.needsAuth) {
if (!this.isLoggedIn()) throw new UserNotLoggedInError();
await this.revalidateAccessTokenIfExpired();
}

await this.revalidateAccessTokenIfExpired();
return this.instance
.put<T>(url, data, this.getAxiosConfig())
.then((response) => response.data)
.catch(this.handleUnauthorizedError);
}

static async patch<T = any>(url: string, data?: any) {
if (!this.isLoggedIn()) throw new UserNotLoggedInError();
static async patch<T = any>(
url: string,
data?: any,
options?: HydraApiOptions
) {
if (!options || options.needsAuth) {
if (!this.isLoggedIn()) throw new UserNotLoggedInError();
await this.revalidateAccessTokenIfExpired();
}

await this.revalidateAccessTokenIfExpired();
return this.instance
.patch<T>(url, data, this.getAxiosConfig())
.then((response) => response.data)
.catch(this.handleUnauthorizedError);
}

static async delete<T = any>(url: string) {
if (!this.isLoggedIn()) throw new UserNotLoggedInError();
static async delete<T = any>(url: string, options?: HydraApiOptions) {
if (!options || options.needsAuth) {
if (!this.isLoggedIn()) throw new UserNotLoggedInError();
await this.revalidateAccessTokenIfExpired();
}

await this.revalidateAccessTokenIfExpired();
return this.instance
.delete<T>(url, this.getAxiosConfig())
.then((response) => response.data)
Expand Down
5 changes: 5 additions & 0 deletions src/main/services/repacks-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ export class RepacksManager {
.map((index) => this.repacks[index]);
}

public static findRepacksForCatalogueEntry(entry: CatalogueEntry) {
const repacks = this.search({ query: formatName(entry.title) });
return { ...entry, repacks };
}

public static findRepacksForCatalogueEntries(entries: CatalogueEntry[]) {
return entries.map((entry) => {
const repacks = this.search({ query: formatName(entry.title) });
Expand Down
23 changes: 1 addition & 22 deletions src/main/workers/steam-games.worker.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,15 @@
import { SteamGame } from "@types";
import { orderBy, slice } from "lodash-es";
import flexSearch from "flexsearch";
import { slice } from "lodash-es";
import fs from "node:fs";

import { formatName } from "@shared";
import { workerData } from "node:worker_threads";

const steamGamesIndex = new flexSearch.Index({
tokenize: "reverse",
});

const { steamGamesPath } = workerData;

const data = fs.readFileSync(steamGamesPath, "utf-8");

const steamGames = JSON.parse(data) as SteamGame[];

for (let i = 0; i < steamGames.length; i++) {
const steamGame = steamGames[i];

const formattedName = formatName(steamGame.name);

steamGamesIndex.add(i, formattedName);
}

export const search = (options: flexSearch.SearchOptions) => {
const results = steamGamesIndex.search(options);
const games = results.map((index) => steamGames[index]);

return orderBy(games, ["name"], ["asc"]);
};

export const getById = (id: number) =>
steamGames.find((game) => game.id === id);

Expand Down
61 changes: 50 additions & 11 deletions src/renderer/src/pages/home/search-results.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type { CatalogueEntry } from "@types";
import type { DebouncedFunc } from "lodash";
import { debounce } from "lodash";

import { InboxIcon } from "@primer/octicons-react";
import { InboxIcon, SearchIcon } from "@primer/octicons-react";
import { clearSearch } from "@renderer/features";
import { useAppDispatch } from "@renderer/hooks";
import { useEffect, useRef, useState } from "react";
Expand All @@ -25,8 +25,10 @@ export function SearchResults() {

const [searchResults, setSearchResults] = useState<CatalogueEntry[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [showTypingMessage, setShowTypingMessage] = useState(false);

const debouncedFunc = useRef<DebouncedFunc<() => void> | null>(null);
const abortControllerRef = useRef<AbortController | null>(null);

const navigate = useNavigate();

Expand All @@ -38,21 +40,64 @@ export function SearchResults() {
useEffect(() => {
setIsLoading(true);
if (debouncedFunc.current) debouncedFunc.current.cancel();
if (abortControllerRef.current) abortControllerRef.current.abort();

const abortController = new AbortController();
abortControllerRef.current = abortController;

debouncedFunc.current = debounce(() => {
const query = searchParams.get("query") ?? "";

if (query.length < 3) {
setIsLoading(false);
setShowTypingMessage(true);
setSearchResults([]);
return;
}

setShowTypingMessage(false);
window.electron
.searchGames(searchParams.get("query") ?? "")
.searchGames(query)
.then((results) => {
if (abortController.signal.aborted) return;

setSearchResults(results);
setIsLoading(false);
})
.finally(() => {
.catch(() => {
setIsLoading(false);
});
}, 300);
}, 500);

debouncedFunc.current();
}, [searchParams, dispatch]);

const noResultsContent = () => {
if (isLoading) return null;

if (showTypingMessage) {
return (
<div className={styles.noResults}>
<SearchIcon size={56} />

<p>{t("start_typing")}</p>
</div>
);
}

if (searchResults.length === 0) {
return (
<div className={styles.noResults}>
<InboxIcon size={56} />

<p>{t("no_results")}</p>
</div>
);
}

return null;
};

return (
<SkeletonTheme baseColor={vars.color.background} highlightColor="#444">
<section className={styles.content}>
Expand All @@ -75,13 +120,7 @@ export function SearchResults() {
)}
</section>

{!isLoading && searchResults.length === 0 && (
<div className={styles.noResults}>
<InboxIcon size={56} />

<p>{t("no_results")}</p>
</div>
)}
{noResultsContent()}
</section>
</SkeletonTheme>
);
Expand Down

0 comments on commit 87cacdf

Please sign in to comment.