A games launcher for GOG, Amazon and Epic Games for Linux, Windows and macOS.
TypeScript amazon-primeelectronepic-games-launcherepic-games-storeepic-storegaminggoggog-galaxyheroic-games-launcherlinuxplay-gamesprotonsteamwine
[Fix] Address the review comments from #6210 (#6215)
Flávio Fearnfeb653a10d84
diff --git a/src/backend/storeManagers/itchio/games.ts b/src/backend/storeManagers/itchio/games.tsindex 7d013045a..dd99f2ec9 100644--- a/src/backend/storeManagers/itchio/games.ts+++ b/src/backend/storeManagers/itchio/games.ts@@ -67,6 +67,12 @@ import {ItchioUpload} from 'common/types/itchio'import { getItchioScreenshots } from './screenshots'+import { withTimeout } from 'backend/utils/with_timeout'++// The description comes from the library and should show right away. The+// gallery needs an extra request to the game page, so wait only a moment for+// it and let the fetch finish in the background (it caches the result).+const SCREENSHOTS_TIMEOUT_MS = 1200interface InstallQueueResult {id: string@@ -401,9 +407,15 @@ function getGameInfo(appName: string): GameInfo {}}-function getExtraInfo(appName: string): Promise<ExtraInfo> {+async function getExtraInfo(appName: string): Promise<ExtraInfo> {const game = getItchioLibraryGameInfo(appName)- return getItchioScreenshots(game?.store_url).then((screenshots) => ({+ const screenshots = await withTimeout(+ getItchioScreenshots(game?.store_url),+ SCREENSHOTS_TIMEOUT_MS,+ []+ )++ return {about: {description: game?.description ?? '',shortDescription: game?.description ?? ''@@ -413,7 +425,7 @@ function getExtraInfo(appName: string): Promise<ExtraInfo> {storeUrl: game?.store_url,changelog: undefined,screenshots- }))+ }}interface InstallLocationsScanResult {diff --git a/src/backend/utils/__tests__/with_timeout.test.ts b/src/backend/utils/__tests__/with_timeout.test.tsnew file mode 100644index 000000000..5e23ebf68--- /dev/null+++ b/src/backend/utils/__tests__/with_timeout.test.ts@@ -0,0 +1,21 @@+import { withTimeout } from '../with_timeout'++describe('withTimeout', () => {+ it('returns the value when the promise is fast enough', async () => {+ await expect(+ withTimeout(Promise.resolve('done'), 100, 'fallback')+ ).resolves.toBe('done')+ })++ it('returns the fallback when the promise takes too long', async () => {+ await expect(+ withTimeout(new Promise(() => undefined), 20, 'fallback')+ ).resolves.toBe('fallback')+ })++ it('returns the fallback when the promise rejects', async () => {+ await expect(+ withTimeout(Promise.reject(new Error('nope')), 100, 'fallback')+ ).resolves.toBe('fallback')+ })+})diff --git a/src/backend/utils/with_timeout.ts b/src/backend/utils/with_timeout.tsnew file mode 100644index 000000000..0499d719f--- /dev/null+++ b/src/backend/utils/with_timeout.ts@@ -0,0 +1,24 @@+/**+ * Resolves with the result of `promise`, or with `fallback` if it takes longer+ * than `ms`. The original promise keeps running in the background, so any work+ * it does (like caching its result) is not lost.+ */+export function withTimeout<T>(+ promise: Promise<T>,+ ms: number,+ fallback: T+): Promise<T> {+ return new Promise<T>((resolve) => {+ const timer = setTimeout(() => resolve(fallback), ms)+ promise.then(+ (value) => {+ clearTimeout(timer)+ resolve(value)+ },+ () => {+ clearTimeout(timer)+ resolve(fallback)+ }+ )+ })+}diff --git a/src/backend/wiki_game_info/metacritic/utils.ts b/src/backend/wiki_game_info/metacritic/utils.tsindex a17c4f6f0..b0e562e5d 100644--- a/src/backend/wiki_game_info/metacritic/utils.ts+++ b/src/backend/wiki_game_info/metacritic/utils.ts@@ -24,6 +24,9 @@ const scoreCache = new CacheStore<GameScoreInfo>('metacritic_scores',60 * 24 * 30)+// Games without a Metacritic page would otherwise be looked up on every game+// page open, since there is no score to cache.+const missCache = new CacheStore<true>('metacritic_misses', 60 * 24)export function parseMetacriticScore(items: MetacriticSearchItem[],@@ -68,6 +71,10 @@ export async function getMetacriticScore(return cached}+ if (missCache.get(title)) {+ return EMPTY_SCORE+ }+try {const { data } = await axiosClient.get<SearchResponse>(`${BASE_URL}/finder/metacritic/search/${encodeURIComponent(title)}/web`,@@ -78,6 +85,8 @@ export async function getMetacriticScore(if (result.score) {scoreCache.set(title, result)+ } else {+ missCache.set(title, true)}return resultdiff --git a/src/backend/wiki_game_info/opencritic/__tests__/utils.test.ts b/src/backend/wiki_game_info/opencritic/__tests__/utils.test.tsindex 752cd16bb..6d6c037f3 100644--- a/src/backend/wiki_game_info/opencritic/__tests__/utils.test.ts+++ b/src/backend/wiki_game_info/opencritic/__tests__/utils.test.ts@@ -76,4 +76,11 @@ describe('slugForTitle', () => {)expect(slugForTitle('Pokémon Écarlate')).toBe('pokemon-ecarlate')})++ it('drops apostrophes instead of splitting the word', () => {+ expect(slugForTitle("Baldur's Gate 3")).toBe('baldurs-gate-3')+ expect(slugForTitle('Death Stranding Director’s Cut')).toBe(+ 'death-stranding-directors-cut'+ )+ })})diff --git a/src/backend/wiki_game_info/opencritic/utils.ts b/src/backend/wiki_game_info/opencritic/utils.tsindex 2dc07f662..2e98114af 100644--- a/src/backend/wiki_game_info/opencritic/utils.ts+++ b/src/backend/wiki_game_info/opencritic/utils.ts@@ -25,8 +25,15 @@ const scoreCache = new CacheStore<GameScoreInfo>(let indexBuild: Promise<void> | null = null+/**+ * OpenCritic builds its slugs by dropping apostrophes instead of replacing them+ * with a space, so `Baldur's Gate 3` is `baldurs-gate-3`. Normalizing first+ * would produce `baldur-s-gate-3` and the lookup would miss.+ */export function slugForTitle(title: string): string {- return normalizeTitle(title).replaceAll(' ', '-')+ const withoutApostrophes = title.replaceAll(/['‘’ʼ`´]/g, '')++ return normalizeTitle(withoutApostrophes).replaceAll(' ', '-')}/**diff --git a/src/backend/wiki_game_info/scores.ts b/src/backend/wiki_game_info/scores.tsindex 4f407edfe..be8d14cfb 100644--- a/src/backend/wiki_game_info/scores.ts+++ b/src/backend/wiki_game_info/scores.ts@@ -1,8 +1,11 @@import { GameScoreInfo, GameScores } from 'common/types'import { getMetacriticScore } from './metacritic/utils'import { getOpenCriticScore } from './opencritic/utils'+import { withTimeout } from 'backend/utils/with_timeout'const EMPTY_SCORE: GameScoreInfo = { score: '', urlid: '' }+// One slow provider must not hold back the other one (nor the game page).+const PROVIDER_TIMEOUT_MS = 8000/*** Critic scores for a game, resolved outside PCGamingWiki.@@ -14,8 +17,8 @@ const EMPTY_SCORE: GameScoreInfo = { score: '', urlid: '' }*/export async function getGameScores(title: string): Promise<GameScores> {const [metacritic, opencritic] = await Promise.all([- getMetacriticScore(title).catch(() => EMPTY_SCORE),- getOpenCriticScore(title).catch(() => EMPTY_SCORE)+ withTimeout(getMetacriticScore(title), PROVIDER_TIMEOUT_MS, EMPTY_SCORE),+ withTimeout(getOpenCriticScore(title), PROVIDER_TIMEOUT_MS, EMPTY_SCORE)])return {diff --git a/src/backend/wiki_game_info/wiki_game_info.ts b/src/backend/wiki_game_info/wiki_game_info.tsindex 0b586936e..c506215ea 100644--- a/src/backend/wiki_game_info/wiki_game_info.ts+++ b/src/backend/wiki_game_info/wiki_game_info.ts@@ -58,6 +58,10 @@ export async function getWikiGameInfo(game: Game): Promise<WikiInfo | null> {try {const title = removeSpecialcharacters(gameInfo.title)+ // Scores have their own providers and cache, so start them right away and+ // only await them at the end. Otherwise a slow Metacritic lookup delays the+ // whole wiki info (HowLongToBeat, compatibility, genres, ...).+ const scoresPromise = getGameScores(title)// Steam titles can collide across appsconst cacheKey = runner === 'steam' ? `steam:${appName}` : title@@ -71,7 +75,7 @@ export async function getWikiGameInfo(game: Game): Promise<WikiInfo | null> {)// Scores are resolved on every read: they have their own cache and must// not be frozen by the 30 day wiki cache.- return { ...cachedResponse, scores: await getGameScores(title) }+ return { ...cachedResponse, scores: await scoresPromise }}logInfo(`Getting ExtraGameInfo data for ${title}`, LogPrefix.ExtraGameInfo)@@ -81,7 +85,7 @@ export async function getWikiGameInfo(game: Game): Promise<WikiInfo | null> {if (cacheable) {wikiGameInfoStore.set(cacheKey, info)}- return { ...info, scores: await getGameScores(title) }+ return { ...info, scores: await scoresPromise }}const [pcgwResult, gamesdb, applegamingwiki, umuId] = await Promise.all([@@ -129,7 +133,7 @@ export async function getWikiGameInfo(game: Game): Promise<WikiInfo | null> {wikiGameInfoStore.set(cacheKey, wikiGameInfo)}- return { ...wikiGameInfo, scores: await getGameScores(title) }+ return { ...wikiGameInfo, scores: await scoresPromise }} catch (error) {logError([`Was not able to get ExtraGameInfo data for ${gameInfo.title}`, error],