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
[Feat] Screenshots and scores for more stores (#6210)
Flávio Fearncc484d207fbc
diff --git a/public/locales/en/gamepage.json b/public/locales/en/gamepage.jsonindex 1278d09b9..2ded88ecd 100644--- a/public/locales/en/gamepage.json+++ b/public/locales/en/gamepage.json@@ -173,10 +173,13 @@"logoAlt": "{{title}} logo","modify": "Modify installation","neverPlayed": "Never",+ "openStorePage": "Open game page","platform": "Select Platform Version to Install","requirements": "System requirements","screenshotAlt": "{{title}} screenshot {{index}}","screenshots": "Screenshots",+ "showLess": "Show less",+ "showMore": "Show more","tabs": "Game information","totalPlayed": "Time played"},diff --git a/src/backend/storeManagers/itchio/__tests__/parse_screenshots.test.ts b/src/backend/storeManagers/itchio/__tests__/parse_screenshots.test.tsnew file mode 100644index 000000000..944d515d5--- /dev/null+++ b/src/backend/storeManagers/itchio/__tests__/parse_screenshots.test.ts@@ -0,0 +1,60 @@+import { extractItchioScreenshots } from '../parse_screenshots'++const IMG = 'https://img.itch.zone/aW1hZ2UvNTExMzA0LzI5MTIwOTQucG5n'++describe('extractItchioScreenshots', () => {+ it('reads the gallery anchors and derives the thumbnails', () => {+ const html = `+ <div class="formatted_description">+ <p>About the game</p>+ <div class="screenshot_list">+ <a href="${IMG}/original/uI3Z5J.png" data-image_lightbox="true" target="_blank">+ <img src="${IMG}/347x500/uI3Z5J.png" />+ </a>+ <a href="${IMG}2/original/wmjUTW.jpg" data-image_lightbox="true">+ <img src="${IMG}2/347x500/wmjUTW.jpg" />+ </a>+ </div>+ <p>More text</p>+ </div>+ `++ expect(extractItchioScreenshots(html)).toEqual([+ {+ full: `${IMG}/original/uI3Z5J.png`,+ thumbnail: `${IMG}/347x500/uI3Z5J.png`+ },+ {+ full: `${IMG}2/original/wmjUTW.jpg`,+ thumbnail: `${IMG}2/347x500/wmjUTW.jpg`+ }+ ])+ })++ it('returns an empty gallery when the game has no screenshots', () => {+ expect(+ extractItchioScreenshots('<div class="formatted_description">…</div>')+ ).toEqual([])+ })++ it('keeps only https images and drops duplicates', () => {+ const html = `<div class="screenshot_list">+ <a href="http://img.itch.zone/insecure.png"></a>+ <a href="https://img.itch.zone/same.png"></a>+ <a href="https://img.itch.zone/same.png"></a>+ </div>`++ expect(extractItchioScreenshots(html)).toEqual([+ { full: 'https://img.itch.zone/same.png' }+ ])+ })++ it('decodes html entities in the image urls', () => {+ const html =+ '<div class="screenshot_list"><a href="https://img.itch.zone/a.png?x=1&y=2"></a></div>'++ expect(extractItchioScreenshots(html)).toEqual([+ { full: 'https://img.itch.zone/a.png?x=1&y=2' }+ ])+ })+})diff --git a/src/backend/storeManagers/itchio/games.ts b/src/backend/storeManagers/itchio/games.tsindex bed480b04..7d013045a 100644--- a/src/backend/storeManagers/itchio/games.ts+++ b/src/backend/storeManagers/itchio/games.ts@@ -66,6 +66,7 @@ import {ItchioInstallInfo,ItchioUpload} from 'common/types/itchio'+import { getItchioScreenshots } from './screenshots'interface InstallQueueResult {id: string@@ -402,7 +403,7 @@ function getGameInfo(appName: string): GameInfo {function getExtraInfo(appName: string): Promise<ExtraInfo> {const game = getItchioLibraryGameInfo(appName)- return Promise.resolve({+ return getItchioScreenshots(game?.store_url).then((screenshots) => ({about: {description: game?.description ?? '',shortDescription: game?.description ?? ''@@ -410,8 +411,9 @@ function getExtraInfo(appName: string): Promise<ExtraInfo> {reqs: [],releaseDate: undefined,storeUrl: game?.store_url,- changelog: undefined- })+ changelog: undefined,+ screenshots+ }))}interface InstallLocationsScanResult {diff --git a/src/backend/storeManagers/itchio/parse_screenshots.ts b/src/backend/storeManagers/itchio/parse_screenshots.tsnew file mode 100644index 000000000..a0e392407--- /dev/null+++ b/src/backend/storeManagers/itchio/parse_screenshots.ts@@ -0,0 +1,50 @@+import { GameScreenshot } from 'common/types'+import { buildScreenshots } from '../storeManagerCommon/screenshots'++const THUMBNAIL_FORMAT = '347x500'+const ORIGINAL_FORMAT = 'original'++/**+ * Extracts the gallery of an itch.io game page.+ *+ * The page renders the gallery as a `screenshot_list` block whose anchors point+ * at the full size image:+ *+ * ```html+ * <div class="screenshot_list">+ * <a href="https://img.itch.zone/.../original/abc.png">+ * <img src="https://img.itch.zone/.../347x500/abc.png">+ * </a>+ * </div>+ * ```+ */+export function extractItchioScreenshots(html: string): GameScreenshot[] {+ const block = /<div class="screenshot_list"[^>]*>([\s\S]*?)<\/div>/.exec(+ html+ )?.[1]++ if (!block) {+ return []+ }++ const candidates = [...block.matchAll(/<a[^>]*\shref="([^"]+)"/g)].map(+ (match) => {+ const full = decodeHtmlEntities(match[1])+ return { full, thumbnail: toThumbnail(full) }+ }+ )++ return buildScreenshots(candidates)+}++function toThumbnail(full: string): string | undefined {+ if (!full.includes(`/${ORIGINAL_FORMAT}/`)) {+ return undefined+ }++ return full.replace(`/${ORIGINAL_FORMAT}/`, `/${THUMBNAIL_FORMAT}/`)+}++function decodeHtmlEntities(value: string): string {+ return value.replaceAll('&', '&').replaceAll(''', "'")+}diff --git a/src/backend/storeManagers/itchio/screenshots.ts b/src/backend/storeManagers/itchio/screenshots.tsnew file mode 100644index 000000000..cb898b150--- /dev/null+++ b/src/backend/storeManagers/itchio/screenshots.ts@@ -0,0 +1,47 @@+import { GameScreenshot } from 'common/types'+import { axiosClient } from 'backend/utils'+import CacheStore from 'backend/cache'+import { logWarning, LogPrefix } from 'backend/logger'+import { extractItchioScreenshots } from './parse_screenshots'++// itch.io has no public endpoint that exposes a game's gallery, so we read the+// screenshots from the game page itself. Pages are cached for a month because+// the gallery only changes when the developer uploads new images.+const screenshotsCache = new CacheStore<GameScreenshot[]>(+ 'itchio_screenshots',+ 60 * 24 * 30+)++export async function getItchioScreenshots(+ storeUrl?: string+): Promise<GameScreenshot[]> {+ if (!storeUrl) {+ return []+ }++ const cached = screenshotsCache.get(storeUrl)+ if (cached) {+ return cached+ }++ try {+ const { data } = await axiosClient.get<string>(storeUrl, {+ responseType: 'text',+ headers: { Accept: 'text/html' }+ })++ const screenshots =+ typeof data === 'string' ? extractItchioScreenshots(data) : []++ screenshotsCache.set(storeUrl, screenshots)+ return screenshots+ } catch (error) {+ // Not cached on purpose: a transient failure should be retried next time+ // the game page is opened.+ logWarning(+ [`Unable to read itch.io screenshots from ${storeUrl}`, error],+ LogPrefix.Itchio+ )+ return []+ }+}diff --git a/src/backend/storeManagers/legendary/games.ts b/src/backend/storeManagers/legendary/games.tsindex 991630bd8..001264676 100644--- a/src/backend/storeManagers/legendary/games.ts+++ b/src/backend/storeManagers/legendary/games.ts@@ -25,11 +25,14 @@ import {spawnAsync} from '../../utils'import {+ logDebug,logError,logInfo,+ logWarning,LogPrefix,createGameLogWriter} from 'backend/logger'+import { httpStatus, summarizeError } from 'backend/utils/error_summary'import {prepareLaunch,prepareWineLaunch,@@ -150,7 +153,10 @@ export default class LegendaryGame implements Game {)const res = result.data.data.Catalog as Catalog- const slugMapping = res.catalogNs.mappings.find(+ // Epic returns `null` for namespaces it does not know (DLCs, delisted+ // games, bundles), so this cannot assume the mapping list exists.+ const mappings = res.catalogNs?.mappings ?? []+ const slugMapping = mappings.find((mapping) => mapping.pageType === 'productHome')@@ -160,7 +166,10 @@ export default class LegendaryGame implements Game {return this.slugFromTitle(title)}} catch (error) {- logError(error, LogPrefix.Legendary)+ logWarning(+ `Could not resolve the Epic product slug for ${title}: ${summarizeError(error)}`,+ LogPrefix.Legendary+ )return this.slugFromTitle(title)}}@@ -200,10 +209,18 @@ export default class LegendaryGame implements Game {return null}} catch (error) {- logError(- ['Failed to get info from Epic API:', error],- LogPrefix.Legendary- )+ if (httpStatus(error) === 404) {+ // Normal for DLCs and games Epic no longer lists on the store page.+ logDebug(+ `Epic API has no content page for ${slug} (HTTP 404)`,+ LogPrefix.Legendary+ )+ } else {+ logWarning(+ `Failed to get info from Epic API for ${slug}: ${summarizeError(error)}`,+ LogPrefix.Legendary+ )+ }return null}}@@ -328,7 +345,10 @@ export default class LegendaryGame implements Game {gameInfoStore.set(namespace, extraData)return extraData} else {- logError('Error Getting Info from Epic API', LogPrefix.Legendary)+ logDebug(+ `No extra info available for ${title} from the Epic API`,+ LogPrefix.Legendary+ )return {about: {description: '',diff --git a/src/backend/storeManagers/sideload/games.ts b/src/backend/storeManagers/sideload/games.tsindex 3cf7cc218..6360ba3e2 100644--- a/src/backend/storeManagers/sideload/games.ts+++ b/src/backend/storeManagers/sideload/games.ts@@ -24,6 +24,7 @@ import { removePrefix } from 'backend/utils/uninstaller'import { removeRecentGame } from 'backend/recent_games/recent_games'import { isLinux, isMac, isWindows } from 'backend/constants/environment'import { removeNonSteamGame } from 'backend/shortcuts/nonesteamgame/nonesteamgame'+import { getSteamScreenshotsByTitle } from 'backend/storeManagers/storeManagerCommon/steam_storefront'import type LogWriter from 'backend/logger/log_writer'@@ -170,16 +171,17 @@ export default class SideloadGame implements Game {}async getExtraInfo(): Promise<ExtraInfo> {- logWarning(- `getExtraInfo not implemented on Sideload Game Manager. called for ID = ${this.id}`- )+ const title = this.getGameInfo().title ?? ''+ const screenshots = await getSteamScreenshotsByTitle(title)+return {about: {description: '',shortDescription: ''},reqs: [],- storeUrl: ''+ storeUrl: '',+ screenshots}}diff --git a/src/backend/storeManagers/storeManagerCommon/steam_storefront.ts b/src/backend/storeManagers/storeManagerCommon/steam_storefront.tsnew file mode 100644index 000000000..d05046254--- /dev/null+++ b/src/backend/storeManagers/storeManagerCommon/steam_storefront.ts@@ -0,0 +1,95 @@+import { GameScreenshot } from 'common/types'+import { axiosClient } from 'backend/utils'+import CacheStore from 'backend/cache'+import { logWarning, LogPrefix } from 'backend/logger'+import { getSteamScreenshots } from './screenshots'+import { pickBestTitleMatch } from 'backend/utils/title_match'++const STORE_SEARCH_URL = 'https://store.steampowered.com/api/storesearch/'+const APP_DETAILS_URL = 'https://store.steampowered.com/api/appdetails'++type StoreSearchResponse = {+ items?: Array<{ id?: number; name?: string }>+}++type AppDetailsResponse = Record<+ string,+ { success?: boolean; data?: { screenshots?: unknown } }+>++// The store cache is keyed by title and lives for a month: a title and its+// Steam page do not change often, and this keeps us far below the ~200+// requests / 5 minutes the public storefront tolerates.+const screenshotsCache = new CacheStore<GameScreenshot[]>(+ 'steam_storefront_screenshots',+ 60 * 24 * 30+)++async function findSteamAppId(title: string): Promise<number | undefined> {+ try {+ const { data } = await axiosClient.get<StoreSearchResponse>(+ STORE_SEARCH_URL,+ { params: { term: title, cc: 'us', l: 'english' } }+ )++ const candidates = (data.items ?? [])+ .filter(+ (item): item is { id: number; name: string } =>+ typeof item.id === 'number' && typeof item.name === 'string'+ )+ .map((item) => ({ id: item.id, name: item.name }))++ return pickBestTitleMatch(candidates, title)?.id+ } catch (error) {+ logWarning(+ [`Unable to search the Steam store for ${title}`, error],+ LogPrefix.ExtraGameInfo+ )+ return undefined+ }+}++async function getSteamStoreScreenshots(+ appId: number+): Promise<GameScreenshot[]> {+ try {+ const { data } = await axiosClient.get<AppDetailsResponse>(+ APP_DETAILS_URL,+ { params: { appids: appId, filters: 'screenshots' } }+ )++ return getSteamScreenshots(data?.[appId]?.data?.screenshots)+ } catch (error) {+ logWarning(+ [`Unable to read Steam store screenshots for ${appId}`, error],+ LogPrefix.ExtraGameInfo+ )+ return []+ }+}++/**+ * Resolves screenshots for any title through the public Steam storefront.+ * Used by stores that do not expose a gallery (ZOOM, sideloaded games).+ */+export async function getSteamScreenshotsByTitle(+ title: string+): Promise<GameScreenshot[]> {+ if (!title.trim()) {+ return []+ }++ const cached = screenshotsCache.get(title)+ if (cached) {+ return cached+ }++ const appId = await findSteamAppId(title)+ const screenshots = appId ? await getSteamStoreScreenshots(appId) : []++ if (screenshots.length > 0) {+ screenshotsCache.set(title, screenshots)+ }++ return screenshots+}diff --git a/src/backend/storeManagers/zoom/__tests__/parse_screenshots.test.ts b/src/backend/storeManagers/zoom/__tests__/parse_screenshots.test.tsnew file mode 100644index 000000000..8071a578d--- /dev/null+++ b/src/backend/storeManagers/zoom/__tests__/parse_screenshots.test.ts@@ -0,0 +1,62 @@+import { extractZoomScreenshots } from '../parse_screenshots'++describe('extractZoomScreenshots', () => {+ it('reads a screenshots array of plain urls', () => {+ const payload = {+ id: 'abc',+ title: 'Dead Synchronicity',+ screenshots: [+ 'https://cdn.zoom-platform.com/games/1/shot-1.jpg',+ 'https://cdn.zoom-platform.com/games/1/shot-2.png'+ ]+ }++ expect(extractZoomScreenshots(payload)).toEqual([+ { full: 'https://cdn.zoom-platform.com/games/1/shot-1.jpg' },+ { full: 'https://cdn.zoom-platform.com/games/1/shot-2.png' }+ ])+ })++ it('reads a gallery of objects and is case insensitive', () => {+ const payload = {+ Gallery: [+ { url: 'https://cdn.zoom-platform.com/a.webp' },+ { src: 'https://cdn.zoom-platform.com/b.jpeg' }+ ]+ }++ expect(extractZoomScreenshots(payload).map((shot) => shot.full)).toEqual([+ 'https://cdn.zoom-platform.com/a.webp',+ 'https://cdn.zoom-platform.com/b.jpeg'+ ])+ })++ it('never returns the poster, cover or logo', () => {+ const payload = {+ poster_url: 'https://cdn.zoom-platform.com/poster.jpg',+ cover: { url: 'https://cdn.zoom-platform.com/cover.jpg' },+ logo: 'https://cdn.zoom-platform.com/logo.png'+ }++ expect(extractZoomScreenshots(payload)).toEqual([])+ })++ it('ignores non https and non image urls', () => {+ const payload = {+ screenshots: [+ 'http://cdn.zoom-platform.com/insecure.jpg',+ 'https://cdn.zoom-platform.com/page.html',+ 'https://cdn.zoom-platform.com/ok.png'+ ]+ }++ expect(extractZoomScreenshots(payload)).toEqual([+ { full: 'https://cdn.zoom-platform.com/ok.png' }+ ])+ })++ it('survives unexpected payloads', () => {+ expect(extractZoomScreenshots(null)).toEqual([])+ expect(extractZoomScreenshots('nope')).toEqual([])+ })+})diff --git a/src/backend/storeManagers/zoom/games.ts b/src/backend/storeManagers/zoom/games.tsindex b93e6f796..86ed93154 100644--- a/src/backend/storeManagers/zoom/games.ts+++ b/src/backend/storeManagers/zoom/games.ts@@ -67,6 +67,7 @@ import { isLinux, isMac, isWindows } from 'backend/constants/environment'import { libraryManagerMap } from '..'import { isUmuSupported } from 'backend/utils/compatibility_layers'import { getUmuId } from 'backend/wiki_game_info/umu/utils'+import { getZoomScreenshots } from './screenshots'import type LogWriter from 'backend/logger/log_writer'import { rm, writeFile } from 'node:fs/promises'@@ -126,12 +127,15 @@ export default class ZoomGame implements Game {async getExtraInfo(): Promise<ExtraInfo> {// Zoom.py doesn't have direct equivalents for reqs, changelog, etc.// This part would need to be implemented if the Zoom API provides such data.+ const title = this.getGameInfo().title+ const screenshots = await getZoomScreenshots(this.id, title)const extra: ExtraInfo = {about: { description: '', shortDescription: '' },reqs: [],releaseDate: undefined,storeUrl: undefined,- changelog: undefined+ changelog: undefined,+ screenshots}return extra}diff --git a/src/backend/storeManagers/zoom/parse_screenshots.ts b/src/backend/storeManagers/zoom/parse_screenshots.tsnew file mode 100644index 000000000..9aaa2d695--- /dev/null+++ b/src/backend/storeManagers/zoom/parse_screenshots.ts@@ -0,0 +1,70 @@+import { GameScreenshot } from 'common/types'+import { buildScreenshots } from '../storeManagerCommon/screenshots'++const GALLERY_KEY = /screenshot|gallery|media|image/i+const EXCLUDED_KEY = /poster|cover|icon|logo|banner|thumbnail|thumb/i+const GALLERY_ITEM_KEY = /^(url|src|path|file|image|href)$/i+const IMAGE_URL = /^https:\/\/[^\s]+\.(png|jpe?g|webp|avif)(\?[^\s]*)?$/i++const MAX_DEPTH = 4++/**+ * Extracts screenshots from the ZOOM library API.+ *+ * The `/li/game/{id}` payload is not documented field by field, so instead of+ * hardcoding a shape we look for arrays of image URLs under keys that look like+ * a gallery ("screenshots", "gallery", "media", "images"), skipping the keys+ * that hold the poster/cover/logo.+ */+export function extractZoomScreenshots(payload: unknown): GameScreenshot[] {+ const urls: string[] = []++ collect(payload, '', 0, urls, false)++ return buildScreenshots(urls.map((full) => ({ full })))+}++function collect(+ value: unknown,+ key: string,+ depth: number,+ urls: string[],+ insideGallery: boolean+): void {+ if (depth > MAX_DEPTH || value === null || value === undefined) {+ return+ }++ if (typeof value === 'string') {+ const isGalleryKey =+ GALLERY_KEY.test(key) || (insideGallery && GALLERY_ITEM_KEY.test(key))+ if (isGalleryKey && !EXCLUDED_KEY.test(key) && IMAGE_URL.test(value)) {+ urls.push(value)+ }+ return+ }++ if (Array.isArray(value)) {+ for (const entry of value) {+ collect(entry, key, depth + 1, urls, insideGallery)+ }+ return+ }++ if (typeof value !== 'object') {+ return+ }++ for (const [entryKey, entryValue] of Object.entries(value)) {+ if (EXCLUDED_KEY.test(entryKey)) {+ continue+ }+ collect(+ entryValue,+ entryKey,+ depth + 1,+ urls,+ insideGallery || GALLERY_KEY.test(entryKey)+ )+ }+}diff --git a/src/backend/storeManagers/zoom/screenshots.ts b/src/backend/storeManagers/zoom/screenshots.tsnew file mode 100644index 000000000..13df3ceba--- /dev/null+++ b/src/backend/storeManagers/zoom/screenshots.ts@@ -0,0 +1,55 @@+import { GameScreenshot } from 'common/types'+import CacheStore from 'backend/cache'+import { logWarning, LogPrefix } from 'backend/logger'+import { getSteamScreenshotsByTitle } from '../storeManagerCommon/steam_storefront'+import { apiUrl } from './constants'+import { extractZoomScreenshots } from './parse_screenshots'+import { ZoomUser } from './user'++const screenshotsCache = new CacheStore<GameScreenshot[]>(+ 'zoom_screenshots',+ 60 * 24 * 30+)++async function getZoomGallery(appName: string): Promise<GameScreenshot[]> {+ try {+ const game = await ZoomUser.makeRequest<unknown>(+ `${apiUrl}/li/game/${appName}`+ )++ return extractZoomScreenshots(game)+ } catch (error) {+ logWarning(+ [`Unable to read ZOOM screenshots for ${appName}`, error],+ LogPrefix.Zoom+ )+ return []+ }+}++/**+ * Screenshots for a ZOOM Platform game.+ *+ * ZOOM's library API does not document a gallery field, so we try the single+ * game endpoint first and fall back to the Steam storefront (most ZOOM titles+ * are re-releases with a Steam page) when it comes back empty.+ */+export async function getZoomScreenshots(+ appName: string,+ title: string+): Promise<GameScreenshot[]> {+ const cached = screenshotsCache.get(appName)+ if (cached) {+ return cached+ }++ const fromZoom = await getZoomGallery(appName)+ const screenshots =+ fromZoom.length > 0 ? fromZoom : await getSteamScreenshotsByTitle(title)++ if (screenshots.length > 0) {+ screenshotsCache.set(appName, screenshots)+ }++ return screenshots+}diff --git a/src/backend/tools/index.ts b/src/backend/tools/index.tsindex 7eae15205..f98cd8dd1 100644--- a/src/backend/tools/index.ts+++ b/src/backend/tools/index.ts@@ -52,6 +52,7 @@ import {downloadFile as downloadFileInet} from '../utils/inet/downloader'import { getUmuPath, isUmuSupported } from 'backend/utils/compatibility_layers'+import { summarizeError } from 'backend/utils/error_summary'import { toolsPath, userHome } from 'backend/constants/paths'import {isIntelMac,@@ -199,7 +200,18 @@ export const DXVK = {}]- await Promise.all(tools.map(installOrUpdateTool))+ await Promise.all(+ tools.map((tool) =>+ installOrUpdateTool(tool).catch((error) => {+ // A blocked or rate limited GitHub API must not break the other+ // tools, nor surface as an unhandled rejection.+ logWarning(+ `Could not update ${tool.name}: ${summarizeError(error)}`,+ LogPrefix.ToolInstaller+ )+ })+ )+ )},installRemove: async (diff --git a/src/backend/utils/__tests__/error_summary.test.ts b/src/backend/utils/__tests__/error_summary.test.tsnew file mode 100644index 000000000..e21e94458--- /dev/null+++ b/src/backend/utils/__tests__/error_summary.test.ts@@ -0,0 +1,45 @@+import { httpStatus, summarizeError } from '../error_summary'++function axiosError(status?: number, url = 'https://example.com/api') {+ return {+ isAxiosError: true,+ message: 'Request failed with status code 403',+ code: status ? undefined : 'ECONNABORTED',+ config: { url },+ response: status ? { status } : undefined+ }+}++describe('summarizeError', () => {+ it('reports the HTTP status and the url', () => {+ expect(summarizeError(axiosError(403))).toBe(+ 'HTTP 403 (https://example.com/api)'+ )+ })++ it('reports the axios code when there is no response', () => {+ expect(summarizeError(axiosError())).toBe(+ 'ECONNABORTED (https://example.com/api)'+ )+ })++ it('falls back to the message of a regular error', () => {+ expect(summarizeError(new Error('Failed'))).toBe('Failed')+ })++ it('never throws on unexpected values', () => {+ expect(summarizeError(undefined)).toBe('unknown error')+ expect(summarizeError('oops')).toBe('oops')+ })+})++describe('httpStatus', () => {+ it('reads the status of an axios error', () => {+ expect(httpStatus(axiosError(429))).toBe(429)+ })++ it('returns nothing for other values', () => {+ expect(httpStatus(new Error('Failed'))).toBeUndefined()+ expect(httpStatus(null)).toBeUndefined()+ })+})diff --git a/src/backend/utils/__tests__/title_match.test.ts b/src/backend/utils/__tests__/title_match.test.tsnew file mode 100644index 000000000..04872b945--- /dev/null+++ b/src/backend/utils/__tests__/title_match.test.ts@@ -0,0 +1,61 @@+import { normalizeTitle, pickBestTitleMatch } from '../title_match'++describe('normalizeTitle', () => {+ it('lowercases, strips accents and punctuation', () => {+ expect(normalizeTitle('Baldur’s Gate 3™')).toBe('baldur s gate 3')+ expect(normalizeTitle('Pokémon Écarlate')).toBe('pokemon ecarlate')+ })++ it('spells & as "and"', () => {+ expect(normalizeTitle('Dead Cells & Co')).toBe('dead cells and co')+ })+})++describe('pickBestTitleMatch', () => {+ const candidates = [+ { id: 1, name: 'GRIME II' },+ { id: 2, name: 'GRIME' },+ { id: 3, name: 'Hades II' }+ ]++ it('prefers the exact title', () => {+ expect(pickBestTitleMatch(candidates, 'GRIME')?.id).toBe(2)+ })++ it('does not confuse a sequel with the original', () => {+ expect(pickBestTitleMatch(candidates, 'Hades')).toBeUndefined()+ })++ it('accepts an edition of the requested title', () => {+ const editions = [+ { id: 10, name: 'Disco Elysium - The Final Cut' },+ { id: 11, name: 'Disco Elysium: Game of the Year Edition' }+ ]++ expect(+ pickBestTitleMatch(+ [{ id: 9, name: 'Disco Elysium' }, ...editions],+ 'Disco Elysium'+ )?.id+ ).toBe(9)+ })++ it('falls back to an edition when the base game is missing', () => {+ expect(+ pickBestTitleMatch(+ [{ id: 12, name: 'Hades - Game of the Year Edition' }],+ 'Hades'+ )?.id+ ).toBe(12)+ })++ it('accepts a year suffix', () => {+ expect(+ pickBestTitleMatch([{ id: 13, name: 'Prey (2017)' }], 'Prey')?.id+ ).toBe(13)+ })++ it('returns nothing for an empty title', () => {+ expect(pickBestTitleMatch(candidates, ' ')).toBeUndefined()+ })+})diff --git a/src/backend/utils/error_summary.ts b/src/backend/utils/error_summary.tsnew file mode 100644index 000000000..efde795bc--- /dev/null+++ b/src/backend/utils/error_summary.ts@@ -0,0 +1,28 @@+import { isAxiosError } from 'axios'++export function httpStatus(error: unknown): number | undefined {+ return isAxiosError(error) ? error.response?.status : undefined+}++/**+ * One line description of an error, for logs that are expected to happen+ * (network blocks, rate limits, offline stores).+ *+ * Passing the raw error to the logger prints a full stack trace, which is+ * useful for a bug but floods the log for a known HTTP failure.+ */+export function summarizeError(error: unknown): string {+ if (!error) return 'unknown error'++ if (isAxiosError(error)) {+ const status = error.response?.status+ const url = error.config?.url+ const suffix = url ? ` (${url})` : ''++ if (status) return `HTTP ${status}${suffix}`+ return `${error.code ?? 'request failed'}${suffix}`+ }++ if (error instanceof Error) return error.message+ return String(error)+}diff --git a/src/backend/utils/title_match.ts b/src/backend/utils/title_match.tsnew file mode 100644index 000000000..7b9fe7c6d--- /dev/null+++ b/src/backend/utils/title_match.ts@@ -0,0 +1,59 @@+interface TitleCandidate {+ name: string+}++const EDITION_SUFFIX =+ /^(the )?(game of the year|goty|definitive|deluxe|ultimate|complete|enhanced|remastered|remaster|anniversary|gold|special|collectors?|digital deluxe|directors cut|final cut|legendary|premium|extended|redux)\b/++const YEAR_SUFFIX = /^\d{4}\b/++export function normalizeTitle(title: string): string {+ return title+ .normalize('NFD')+ .replace(/[\u0300-\u036f]/g, '')+ .toLowerCase()+ .replaceAll('&', ' and ')+ .replace(/[™®©]/g, '')+ .replace(/[^a-z0-9]+/g, ' ')+ .trim()+}++/**+ * Picks the candidate that matches a game title, or nothing.+ *+ * Search results are fuzzy, so we only accept an exact normalized match or a+ * title that is the requested one plus an edition marker ("Definitive Edition",+ * "GOTY", "(2020)", …). Anything else is a different game as far as we are+ * concerned: showing the score or the screenshots of "GRIME II" on "GRIME"+ * would be worse than showing none.+ */+export function pickBestTitleMatch<T extends TitleCandidate>(+ candidates: T[],+ title: string+): T | undefined {+ const wanted = normalizeTitle(title)+ if (!wanted) {+ return undefined+ }++ const normalized = candidates.map((candidate) => ({+ candidate,+ normalized: normalizeTitle(candidate.name)+ }))++ const exact = normalized.find((entry) => entry.normalized === wanted)+ if (exact) {+ return exact.candidate+ }++ const edition = normalized.find((entry) => {+ if (!entry.normalized.startsWith(`${wanted} `)) {+ return false+ }++ const remainder = entry.normalized.slice(wanted.length).trim()+ return EDITION_SUFFIX.test(remainder) || YEAR_SUFFIX.test(remainder)+ })++ return edition?.candidate+}diff --git a/src/backend/wiki_game_info/__tests__/wiki_game_info.test.ts b/src/backend/wiki_game_info/__tests__/wiki_game_info.test.tsindex 64e92fcb1..a70a41b24 100644--- a/src/backend/wiki_game_info/__tests__/wiki_game_info.test.ts+++ b/src/backend/wiki_game_info/__tests__/wiki_game_info.test.ts@@ -27,6 +27,9 @@ jest.mock('../howlongtobeat/utils', () => ({jest.mock('../umu/utils', () => ({getUmuId: jest.fn().mockResolvedValue(null)}))+jest.mock('../scores', () => ({+ getGameScores: jest.fn().mockResolvedValue({})+}))jest.mock('backend/constants/environment', () => ({isLinux: false,isMac: false@@ -56,7 +59,10 @@ describe('getWikiGameInfo cache', () => {const result = await getWikiGameInfo(makeGame('legendary'))expect(result?.pcgamingwiki).toBe(pcgwInfo)- expect(mockSet).toHaveBeenCalledWith('Minit', result)+ expect(mockSet).toHaveBeenCalledWith(+ 'Minit',+ expect.objectContaining({ pcgamingwiki: pcgwInfo })+ )})test('caches the result when the game has no PCGamingWiki page', async () => {diff --git a/src/backend/wiki_game_info/applegamingwiki/__tests__/utils.test.ts b/src/backend/wiki_game_info/applegamingwiki/__tests__/utils.test.tsindex 7b025122d..592b872df 100644--- a/src/backend/wiki_game_info/applegamingwiki/__tests__/utils.test.ts+++ b/src/backend/wiki_game_info/applegamingwiki/__tests__/utils.test.ts@@ -1,4 +1,4 @@-import { logError } from 'backend/logger'+import { logError, logWarning } from 'backend/logger'import { getInfoFromAppleGamingWiki } from '../utils'import { axiosClient } from 'backend/utils'import { AppleGamingWikiInfo } from 'common/types'@@ -85,12 +85,27 @@ describe('getInfoFromAppleGamingWiki', () => {expect(result).toBeNull()expect(logError).toBeCalledWith([- 'Was not able to get AppleGamingWiki data for The Witcher 3',+ 'Was not able to get AppleGamingWiki data for The Witcher 3: Failed',Error('Failed')],'ExtraGameInfo')})++ test('warns instead of dumping a stack when the wiki blocks us', async () => {+ jest.spyOn(axiosClient, 'get').mockRejectedValue({+ isAxiosError: true,+ response: { status: 403 },+ config: { url: 'https://www.applegamingwiki.com/w/api.php' }+ })++ expect(await getInfoFromAppleGamingWiki('Hades')).toBeNull()+ expect(logWarning).toHaveBeenCalledWith(+ 'AppleGamingWiki is refusing requests (HTTP 403); its compatibility data will be skipped',+ 'ExtraGameInfo'+ )+ expect(logError).not.toHaveBeenCalled()+ })})const testAppleGamingWikiInfo = {diff --git a/src/backend/wiki_game_info/applegamingwiki/utils.ts b/src/backend/wiki_game_info/applegamingwiki/utils.tsindex 595cd61bc..6000a69e6 100644--- a/src/backend/wiki_game_info/applegamingwiki/utils.ts+++ b/src/backend/wiki_game_info/applegamingwiki/utils.ts@@ -3,9 +3,26 @@ import {crossoverRatingRegEx,wineRatingRegEx} from './constants'-import { logError, logInfo, LogPrefix } from 'backend/logger'+import {+ logDebug,+ logError,+ logInfo,+ logWarning,+ LogPrefix+} from 'backend/logger'import { AppleGamingWikiInfo } from 'common/types'-import { axiosClient } from 'backend/utils'+import { httpStatus, summarizeError } from 'backend/utils/error_summary'+import { agwGet } from 'backend/wiki_game_info/pcgamingwiki/client'++type AppleGamingWikiSearchResponse = {+ query: { search: Array<{ pageid: string }> }+}++type AppleGamingWikiParseResponse = {+ parse: { wikitext?: { '*'?: string } }+}++const APPLE_GAMING_WIKI_API = 'https://www.applegamingwiki.com/w/api.php'export async function getInfoFromAppleGamingWiki(title: string@@ -33,17 +50,45 @@ export async function getInfoFromAppleGamingWiki(crossoverLink: wikitext?.match(crossoverLinkIDRegEx)?.[1] ?? ''}} catch (error) {- logError(- [`Was not able to get AppleGamingWiki data for ${title}`, error],+ logAppleGamingWikiFailure(title, error)+ return null+ }+}++let blockedWarningLogged = false++function logAppleGamingWikiFailure(title: string, error: unknown) {+ const status = httpStatus(error)++ if (status === 403 || status === 429) {+ if (blockedWarningLogged) {+ logDebug(+ `AppleGamingWiki still refusing ${title} (HTTP ${status})`,+ LogPrefix.ExtraGameInfo+ )+ return+ }++ blockedWarningLogged = true+ logWarning(+ `AppleGamingWiki is refusing requests (HTTP ${status}); its compatibility data will be skipped`,LogPrefix.ExtraGameInfo)- return null+ return}++ logError(+ [+ `Was not able to get AppleGamingWiki data for ${title}: ${summarizeError(error)}`,+ error+ ],+ LogPrefix.ExtraGameInfo+ )}async function getPageID(title: string): Promise<string> {- const { data } = await axiosClient.get(- `https://www.applegamingwiki.com/w/api.php?action=query&list=search&srsearch=${title.replaceAll(+ const { data } = await agwGet<AppleGamingWikiSearchResponse>(+ `${APPLE_GAMING_WIKI_API}?action=query&list=search&srsearch=${title.replaceAll(' ','%20')}&format=json`@@ -53,8 +98,8 @@ async function getPageID(title: string): Promise<string> {}async function getWikiText(id: string): Promise<string | null> {- const { data } = await axiosClient.get(- `https://www.applegamingwiki.com/w/api.php?action=parse&format=json&pageid=${id}&redirects=true&prop=wikitext`+ const { data } = await agwGet<AppleGamingWikiParseResponse>(+ `${APPLE_GAMING_WIKI_API}?action=parse&format=json&pageid=${id}&redirects=true&prop=wikitext`)if (!data.parse.wikitext || !data.parse.wikitext['*']) {diff --git a/src/backend/wiki_game_info/howlongtobeat/utils.ts b/src/backend/wiki_game_info/howlongtobeat/utils.tsindex 1dc5590ce..5ac0d9d02 100644--- a/src/backend/wiki_game_info/howlongtobeat/utils.ts+++ b/src/backend/wiki_game_info/howlongtobeat/utils.ts@@ -1,5 +1,5 @@import axios from 'axios'-import { logError, logInfo, LogPrefix } from 'backend/logger'+import { logDebug, logError, logInfo, LogPrefix } from 'backend/logger'import type { Game } from 'common/types/game_manager'export interface HeroicHowLongToBeatEntry {@@ -198,7 +198,7 @@ export async function getHowLongToBeat()}- logInfo(+ logDebug(`No HLTB ID available for ${gameInfo.title}, cannot fetch data`,LogPrefix.ExtraGameInfo)diff --git a/src/backend/wiki_game_info/metacritic/__tests__/utils.test.ts b/src/backend/wiki_game_info/metacritic/__tests__/utils.test.tsnew file mode 100644index 000000000..fbb4425cd--- /dev/null+++ b/src/backend/wiki_game_info/metacritic/__tests__/utils.test.ts@@ -0,0 +1,71 @@+import { parseMetacriticScore } from '../utils'++jest.mock('backend/cache', () => ({+ __esModule: true,+ default: class {+ get() {+ return undefined+ }+ set() {+ /* noop */+ }+ }+}))+jest.mock('backend/logger')+jest.mock('backend/utils', () => ({ axiosClient: { get: jest.fn() } }))++describe('parseMetacriticScore', () => {+ it('uses the score and slug of the exact match', () => {+ const items = [+ {+ title: 'Hades II',+ slug: 'hades-ii',+ criticScoreSummary: { score: 95 }+ },+ { title: 'Hades', slug: 'hades', criticScoreSummary: { score: 93 } }+ ]++ expect(parseMetacriticScore(items, 'Hades')).toEqual({+ score: '93',+ urlid: 'hades'+ })+ })++ it('accepts the game when it comes back with an edition suffix', () => {+ const items = [+ {+ title: 'Disco Elysium: The Final Cut',+ slug: 'disco-elysium-the-final-cut',+ criticScoreSummary: { score: 97 }+ }+ ]++ expect(parseMetacriticScore(items, 'Disco Elysium').score).toBe('97')+ })++ it('ignores games without a score', () => {+ const items = [+ { title: 'Hades', slug: 'hades', criticScoreSummary: { score: null } }+ ]++ expect(parseMetacriticScore(items, 'Hades')).toEqual({+ score: '',+ urlid: ''+ })+ })++ it('rejects a different game', () => {+ const items = [+ { title: 'Hades II', slug: 'hades-ii', criticScoreSummary: { score: 95 } }+ ]++ expect(parseMetacriticScore(items, 'Hades')).toEqual({+ score: '',+ urlid: ''+ })+ })++ it('handles an empty result list', () => {+ expect(parseMetacriticScore([], 'Hades')).toEqual({ score: '', urlid: '' })+ })+})diff --git a/src/backend/wiki_game_info/metacritic/utils.ts b/src/backend/wiki_game_info/metacritic/utils.tsnew file mode 100644index 000000000..a17c4f6f0--- /dev/null+++ b/src/backend/wiki_game_info/metacritic/utils.ts@@ -0,0 +1,91 @@+import { GameScoreInfo } from 'common/types'+import { axiosClient } from 'backend/utils'+import CacheStore from 'backend/cache'+import { logWarning, LogPrefix } from 'backend/logger'+import { pickBestTitleMatch } from 'backend/utils/title_match'++const BASE_URL = 'https://backend.metacritic.com'+// mcoTypeId=13 is Metacritic's id for games.+const GAMES_TYPE_ID = 13++type MetacriticSearchItem = {+ title?: string+ slug?: string+ criticScoreSummary?: { score?: number | null }+}++type SearchResponse = { data?: { items?: MetacriticSearchItem[] } }++const EMPTY_SCORE: GameScoreInfo = { score: '', urlid: '' }++// Scores change rarely, so a month of cache is safe and keeps the number of+// requests to a minimum.+const scoreCache = new CacheStore<GameScoreInfo>(+ 'metacritic_scores',+ 60 * 24 * 30+)++export function parseMetacriticScore(+ items: MetacriticSearchItem[],+ title: string+): GameScoreInfo {+ const candidates = items+ .filter(+ (item): item is MetacriticSearchItem & { title: string } =>+ typeof item.title === 'string'+ )+ .map((item) => ({ ...item, name: item.title }))++ const match = pickBestTitleMatch(candidates, title)+ const score = match?.criticScoreSummary?.score++ if (typeof score !== 'number') {+ return EMPTY_SCORE+ }++ return {+ score: String(score),+ urlid: match?.slug ?? ''+ }+}++/**+ * Metacritic score for a game, read from the JSON API that powers+ * metacritic.com itself.+ *+ * The endpoint is not documented and has no key, so treat it as best effort:+ * it is cached for a month and any failure simply yields an empty score.+ */+export async function getMetacriticScore(+ title: string+): Promise<GameScoreInfo> {+ if (!title.trim()) {+ return EMPTY_SCORE+ }++ const cached = scoreCache.get(title)+ if (cached) {+ return cached+ }++ try {+ const { data } = await axiosClient.get<SearchResponse>(+ `${BASE_URL}/finder/metacritic/search/${encodeURIComponent(title)}/web`,+ { params: { mcoTypeId: GAMES_TYPE_ID } }+ )++ const result = parseMetacriticScore(data?.data?.items ?? [], title)++ if (result.score) {+ scoreCache.set(title, result)+ }++ return result+ } catch (error) {+ logWarning(+ [`Unable to read the Metacritic score for ${title}`, error],+ LogPrefix.ExtraGameInfo+ )+ return EMPTY_SCORE+ }+}diff --git a/src/backend/wiki_game_info/opencritic/__tests__/utils.test.ts b/src/backend/wiki_game_info/opencritic/__tests__/utils.test.tsnew file mode 100644index 000000000..752cd16bb--- /dev/null+++ b/src/backend/wiki_game_info/opencritic/__tests__/utils.test.ts@@ -0,0 +1,79 @@+import { parseOpenCriticScore, parseSitemapIndex, slugForTitle } from '../utils'++jest.mock('backend/cache', () => ({+ __esModule: true,+ default: class {+ get() {+ return undefined+ }+ set() {+ /* noop */+ }+ }+}))+jest.mock('backend/logger')+jest.mock('backend/utils', () => ({ axiosClient: { get: jest.fn() } }))++const SITEMAP = `<?xml version="1.0" encoding="UTF-8"?>+<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">+ <url>+ <loc>https://opencritic.com/game/12081/valheim</loc>+ </url>+ <url>+ <loc>https://opencritic.com/game/12081/valheim/media</loc>+ </url>+ <url>+ <loc>https://opencritic.com/game/12081/valheim/reviews</loc>+ </url>+ <url>+ <loc>https://opencritic.com/game/27/tropico-5</loc>+ </url>+</urlset>`++const GAME_PAGE = `+ <div class="score-orb">+ <app-score-orb><div class="inner-orb"> 90 </div></app-score-orb>+ <p class="mt-2">Top Critic Average</p>+ </div>+ <div class="score-orb">+ <app-score-orb><div class="inner-orb"> 80 </div></app-score-orb>+ <p class="mt-2">Player Rating</p>+ </div>+`++describe('parseSitemapIndex', () => {+ it('keeps only the game pages', () => {+ expect(parseSitemapIndex(SITEMAP)).toEqual({+ valheim: 12081,+ 'tropico-5': 27+ })+ })++ it('ignores a payload without entries', () => {+ expect(parseSitemapIndex('<urlset></urlset>')).toEqual({})+ })+})++describe('parseOpenCriticScore', () => {+ it('reads the Top Critic Average, not the player rating', () => {+ expect(parseOpenCriticScore(GAME_PAGE, 12081, 'valheim')).toEqual({+ score: '90',+ urlid: '12081/valheim'+ })+ })++ it('returns an empty score when the game has no average yet', () => {+ expect(+ parseOpenCriticScore('<html><body>Nothing here</body></html>', 1, 'x')+ ).toEqual({ score: '', urlid: '' })+ })+})++describe('slugForTitle', () => {+ it('builds the slug used by opencritic.com', () => {+ expect(slugForTitle('The Witcher 3: Wild Hunt')).toBe(+ 'the-witcher-3-wild-hunt'+ )+ expect(slugForTitle('Pokémon Écarlate')).toBe('pokemon-ecarlate')+ })+})diff --git a/src/backend/wiki_game_info/opencritic/utils.ts b/src/backend/wiki_game_info/opencritic/utils.tsnew file mode 100644index 000000000..2dc07f662--- /dev/null+++ b/src/backend/wiki_game_info/opencritic/utils.ts@@ -0,0 +1,162 @@+import { GameScoreInfo } from 'common/types'+import { axiosClient } from 'backend/utils'+import CacheStore from 'backend/cache'+import { logWarning, LogPrefix } from 'backend/logger'+import { normalizeTitle } from 'backend/utils/title_match'++const BASE_URL = 'https://opencritic.com'+const SITEMAP_URLS = [1, 2, 3, 4, 5].map(+ (page) => `${BASE_URL}/sitemap_games_${page}.xml`+)++const EMPTY_SCORE: GameScoreInfo = { score: '', urlid: '' }++/** slug -> game id, built from the public sitemaps. */+type OpenCriticIndex = Record<string, number>++const indexCache = new CacheStore<OpenCriticIndex>(+ 'opencritic_index',+ 60 * 24 * 7+)+const scoreCache = new CacheStore<GameScoreInfo>(+ 'opencritic_scores',+ 60 * 24 * 7+)++let indexBuild: Promise<void> | null = null++export function slugForTitle(title: string): string {+ return normalizeTitle(title).replaceAll(' ', '-')+}++/**+ * Reads a `sitemap_games_N.xml` payload into `slug -> id`.+ *+ * Each game has three entries (`/game/{id}/{slug}`, `.../media` and+ * `.../reviews`); only the game page is kept.+ */+export function parseSitemapIndex(xml: string): OpenCriticIndex {+ const index: OpenCriticIndex = {}++ for (const match of xml.matchAll(+ /<loc>https:\/\/opencritic\.com\/game\/(\d+)\/([^<]+)<\/loc>/g+ )) {+ const [, id, rawSlug] = match+ if (/\/(media|reviews)$/.test(rawSlug)) {+ continue+ }+ index[rawSlug] = Number(id)+ }++ return index+}++export function parseOpenCriticScore(+ html: string,+ id: number,+ slug: string+): GameScoreInfo {+ const score =+ /<div[^>]*class="inner-orb"[^>]*>\s*(\d{1,3})\s*<\/div>[\s\S]{0,600}?Top Critic Average/.exec(+ html+ )?.[1]++ if (!score) {+ return EMPTY_SCORE+ }++ return { score, urlid: `${id}/${slug}` }+}++/**+ * OpenCritic's API is behind RapidAPI since 2026, so there is no keyless way to+ * search for a game id. The sitemaps list every game as `/game/{id}/{slug}` and+ * are public, so we index them once a week and look the slug up locally.+ */+async function buildIndex(): Promise<void> {+ const index: OpenCriticIndex = {}++ for (const url of SITEMAP_URLS) {+ const { data } = await axiosClient.get<string>(url, {+ responseType: 'text'+ })++ Object.assign(index, parseSitemapIndex(String(data)))+ }++ if (Object.keys(index).length > 0) {+ indexCache.set('index', index)+ }+}++function ensureIndex(): void {+ if (indexBuild) {+ return+ }++ indexBuild = buildIndex()+ .catch((error) => {+ logWarning(+ ['Unable to build the OpenCritic index', error],+ LogPrefix.ExtraGameInfo+ )+ })+ .finally(() => {+ indexBuild = null+ })+}++/**+ * OpenCritic score for a game.+ *+ * The index takes a while to build on a cold cache, so the first lookup kicks+ * it off in the background and reports "no score" instead of stalling the game+ * page. The next lookup (the scores are not cached together with the wiki info)+ * finds the game.+ */+export async function getOpenCriticScore(+ title: string+): Promise<GameScoreInfo> {+ if (!title.trim()) {+ return EMPTY_SCORE+ }++ const cached = scoreCache.get(title)+ if (cached) {+ return cached+ }++ const index = indexCache.get('index')+ if (!index) {+ ensureIndex()+ return EMPTY_SCORE+ }++ const slug = slugForTitle(title)+ const id = index[slug]+ if (!id) {+ return EMPTY_SCORE+ }++ try {+ // The id alone is not enough: /game/{id} returns 404, the slug is required.+ const { data } = await axiosClient.get<string>(+ `${BASE_URL}/game/${id}/${slug}`,+ { responseType: 'text', headers: { Accept: 'text/html' } }+ )++ const result = parseOpenCriticScore(String(data), id, slug)++ if (result.score) {+ scoreCache.set(title, result)+ }++ return result+ } catch (error) {+ logWarning(+ [`Unable to read the OpenCritic score for ${title}`, error],+ LogPrefix.ExtraGameInfo+ )+ return EMPTY_SCORE+ }+}diff --git a/src/backend/wiki_game_info/pcgamingwiki/__tests__/utils.test.ts b/src/backend/wiki_game_info/pcgamingwiki/__tests__/utils.test.tsindex e73248a2c..b515610a4 100644--- a/src/backend/wiki_game_info/pcgamingwiki/__tests__/utils.test.ts+++ b/src/backend/wiki_game_info/pcgamingwiki/__tests__/utils.test.ts@@ -1,4 +1,4 @@-import { logError } from 'backend/logger'+import { logDebug, logError, logWarning } from 'backend/logger'import { fetchPCGamingWikiInfo, getInfoFromPCGamingWiki } from '../utils'import { axiosClient } from 'backend/utils'@@ -29,9 +29,12 @@ describe('getInfoFromPCGamingWiki', () => {expect(result).toStrictEqual(testPCGamingWikiInfo)})- test('fetches successfully via id', async () => {+ test('resolves the GOG id through the redirect API', async () => {const mockAxios = jest.spyOn(axiosClient, 'get').mockResolvedValueOnce({- data: { cargoquery: [{ title: { pageID: 1 } }] }+ status: 302,+ headers: {+ location: 'https://www.pcgamingwiki.com/wiki/The_Witcher_3:_Wild_Hunt'+ }})mockAxios.mockResolvedValueOnce({data: {@@ -51,6 +54,37 @@ describe('getInfoFromPCGamingWiki', () => {const result = await getInfoFromPCGamingWiki('The Witcher 3', '1234')expect(result).toStrictEqual(testPCGamingWikiInfo)+ expect(mockAxios).toHaveBeenNthCalledWith(+ 1,+ expect.stringContaining('api/gog.php?page=1234'),+ expect.objectContaining({ maxRedirects: 0 })+ )+ expect(mockAxios).toHaveBeenNthCalledWith(+ 2,+ expect.stringContaining('page=The%20Witcher%203%3A%20Wild%20Hunt'),+ expect.anything()+ )+ })++ test('falls back to the title search when the GOG redirect does not resolve', async () => {+ const mockAxios = jest.spyOn(axiosClient, 'get').mockResolvedValueOnce({+ status: 200,+ headers: {}+ })+ mockAxios.mockResolvedValueOnce({+ data: { query: { search: [{ pageid: 1, title: 'Hades' }] } }+ })+ mockAxios.mockResolvedValueOnce({+ data: { parse: { wikitext: { '*': '|steam appid = 100\n' } } }+ })++ const result = await getInfoFromPCGamingWiki('Hades', '1234')+ expect(result?.steamID).toBe('100')+ expect(mockAxios).toHaveBeenNthCalledWith(+ 3,+ expect.stringContaining('pageid=1'),+ expect.anything()+ )})test('prefers exact title match over first search result', async () => {@@ -131,12 +165,35 @@ describe('getInfoFromPCGamingWiki', () => {expect(result).toBeNull()expect(logError).toBeCalledWith([- 'Was not able to get PCGamingWiki data for The Witcher 3',+ 'Was not able to get PCGamingWiki data for The Witcher 3: Failed',Error('Failed')],'ExtraGameInfo')})++ test('warns about a blocked wiki only once', async () => {+ jest.spyOn(axiosClient, 'get').mockRejectedValue({+ isAxiosError: true,+ response: { status: 403 },+ config: { url: 'https://www.pcgamingwiki.com/w/api.php' }+ })++ expect(await getInfoFromPCGamingWiki('Hades')).toBeNull()+ expect(logWarning).toHaveBeenCalledTimes(1)+ expect(logWarning).toHaveBeenCalledWith(+ 'PCGamingWiki is refusing requests (HTTP 403); its wiki data and scores will be skipped',+ 'ExtraGameInfo'+ )+ expect(logError).not.toHaveBeenCalled()++ expect(await getInfoFromPCGamingWiki('Hades II')).toBeNull()+ expect(logWarning).toHaveBeenCalledTimes(1)+ expect(logDebug).toHaveBeenCalledWith(+ 'PCGamingWiki still refusing Hades II (HTTP 403)',+ 'ExtraGameInfo'+ )+ })})describe('fetchPCGamingWikiInfo', () => {diff --git a/src/backend/wiki_game_info/pcgamingwiki/client.ts b/src/backend/wiki_game_info/pcgamingwiki/client.tsindex b5d6bfb20..9a0de13f2 100644--- a/src/backend/wiki_game_info/pcgamingwiki/client.ts+++ b/src/backend/wiki_game_info/pcgamingwiki/client.ts@@ -1,5 +1,9 @@import { app } from 'electron'-import { isAxiosError, type AxiosResponse } from 'axios'+import {+ isAxiosError,+ type AxiosRequestConfig,+ type AxiosResponse+} from 'axios'import { axiosClient } from 'backend/utils'const WEBSITE_URL = 'https://heroicgameslauncher.com'@@ -100,18 +104,26 @@ export function pcgamingWikiUserAgent(}const limiter = new RequestLimiter()+// AppleGamingWiki is a separate MediaWiki install with its own limits, but the+// same etiquette applies: identify the app and stay well below their cap.+const appleGamingWikiLimiter = new RequestLimiter()-export async function pcgwGet<T>(url: string): Promise<AxiosResponse<T>> {- await limiter.acquire()+async function throttledGet<T>(+ requestLimiter: RequestLimiter,+ url: string,+ config?: AxiosRequestConfig+): Promise<AxiosResponse<T>> {+ await requestLimiter.acquire()try {return await axiosClient.get<T>(url, {- headers: { 'User-Agent': pcgamingWikiUserAgent() }+ ...config,+ headers: { 'User-Agent': pcgamingWikiUserAgent(), ...config?.headers }})} catch (error) {if (isAxiosError(error) && error.response?.status === 429) {const now = Date.now()- limiter.blockUntil(+ requestLimiter.blockUntil(parseRetryAfter(error.response.headers['retry-after'], now) ??now + DEFAULT_RETRY_AFTER_MS)@@ -119,3 +131,17 @@ export async function pcgwGet<T>(url: string): Promise<AxiosResponse<T>> {throw error}}++export async function pcgwGet<T>(+ url: string,+ config?: AxiosRequestConfig+): Promise<AxiosResponse<T>> {+ return throttledGet<T>(limiter, url, config)+}++export async function agwGet<T>(+ url: string,+ config?: AxiosRequestConfig+): Promise<AxiosResponse<T>> {+ return throttledGet<T>(appleGamingWikiLimiter, url, config)+}diff --git a/src/backend/wiki_game_info/pcgamingwiki/utils.ts b/src/backend/wiki_game_info/pcgamingwiki/utils.tsindex 0dd76a7cd..6f4be1ce8 100644--- a/src/backend/wiki_game_info/pcgamingwiki/utils.ts+++ b/src/backend/wiki_game_info/pcgamingwiki/utils.ts@@ -9,13 +9,20 @@ import {releaseDateRegEx,steamIDRegEx} from './constants'-import { logError, logInfo, LogPrefix } from 'backend/logger'+import {+ logDebug,+ logError,+ logInfo,+ logWarning,+ LogPrefix+} from 'backend/logger'import { GameScoreInfo, PCGamingWikiInfo } from 'common/types'+import { httpStatus, summarizeError } from 'backend/utils/error_summary'import { pcgwGet } from './client'-type CargoQueryResponse = {- cargoquery: Array<{ title?: { pageID?: string } }>-}+const PCGW_BASE_URL = 'https://www.pcgamingwiki.com'+const API_URL = `${PCGW_BASE_URL}/w/api.php`+const GOG_REDIRECT_URL = `${PCGW_BASE_URL}/api/gog.php`type SearchResponse = {query: { search: Array<{ pageid: string; title?: string }> }@@ -31,6 +38,13 @@ type ParseResponse = {parse: { wikitext?: { '*'?: string } }}+/**+ * A PCGamingWiki page can be addressed either by its numeric id or by its+ * title. The GOG redirect API only gives us the title, while the search API+ * gives us the id.+ */+type PageRef = { pageId: string } | { pageTitle: string }+type PCGamingWikiResult =| { status: 'found'; info: PCGamingWikiInfo }| { status: 'notFound' }@@ -54,13 +68,13 @@ export async function fetchPCGamingWikiInfo(logInfo(`Getting PCGamingWiki data for ${title}`, LogPrefix.ExtraGameInfo)- const id = await getPageID(title, gogID)+ const page = await resolvePage(title, gogID)- if (!id) {+ if (!page) {return { status: 'notFound' }}- const wikitext = await getWikiText(id)+ const wikitext = await getWikiText(page)if (!wikitext) {return { status: 'notFound' }@@ -93,12 +107,45 @@ export async function fetchPCGamingWikiInfo(}}} catch (error) {- logError(- [`Was not able to get PCGamingWiki data for ${title}`, error],+ logPCGamingWikiFailure(title, error)+ return { status: 'failed' }+ }+}++let blockedWarningLogged = false++/**+ * Being blocked or rate limited by PCGamingWiki is an expected condition on+ * some networks and happens for every game, so a full stack trace per lookup+ * only floods the log. Warn once per session and keep the details at debug.+ */+function logPCGamingWikiFailure(title: string, error: unknown) {+ const status = httpStatus(error)++ if (status === 403 || status === 429) {+ if (blockedWarningLogged) {+ logDebug(+ `PCGamingWiki still refusing ${title} (HTTP ${status})`,+ LogPrefix.ExtraGameInfo+ )+ return+ }++ blockedWarningLogged = true+ logWarning(+ `PCGamingWiki is refusing requests (HTTP ${status}); its wiki data and scores will be skipped`,LogPrefix.ExtraGameInfo)- return { status: 'failed' }+ return}++ logError(+ [+ `Was not able to get PCGamingWiki data for ${title}: ${summarizeError(error)}`,+ error+ ],+ LogPrefix.ExtraGameInfo+ )}function getReleaseDates(wikitext: string) {@@ -110,21 +157,58 @@ function getReleaseDates(wikitext: string) {return releaseDates}-async function getPageID(title: string, id?: string): Promise<string | null> {- if (id) {- const { data } = await pcgwGet<CargoQueryResponse>(- `https://www.pcgamingwiki.com/w/api.php?action=cargoquery&tables=Infobox_game&fields=Infobox_game._pageID%3DpageID%2C&where=Infobox_game.GOGcom_ID%20HOLDS%20${id}&format=json`+async function resolvePage(+ title: string,+ gogId?: string+): Promise<PageRef | null> {+ if (gogId) {+ const pageTitle = await getPageTitleFromGogId(gogId)+ if (pageTitle) {+ return { pageTitle }+ }+ }++ const pageId = await searchPageId(title)+ return pageId ? { pageId } : null+}++/**+ * Resolves a GOG product id to a wiki page using PCGamingWiki's redirect API.+ *+ * This replaces the old `cargoquery` lookup: since the August 2026 server+ * migration the Cargo endpoint requires an authenticated bot password (and the+ * `Infobox_game` table was renamed to `Game`), so it is not usable by an+ * unauthenticated launcher anymore.+ */+async function getPageTitleFromGogId(gogId: string): Promise<string | null> {+ try {+ const { headers } = await pcgwGet<unknown>(+ `${GOG_REDIRECT_URL}?page=${encodeURIComponent(gogId)}`,+ { maxRedirects: 0, validateStatus: () => true })- const number = data.cargoquery[0]?.title?.pageID+ return pageTitleFromLocation(headers?.location)+ } catch {+ return null+ }+}++function pageTitleFromLocation(location: unknown): string | null {+ if (typeof location !== 'string') return null- if (number) {- return number- }+ const match = /\/wiki\/([^?#]+)/.exec(location)+ if (!match) return null++ try {+ return decodeURIComponent(match[1]).replaceAll('_', ' ')+ } catch {+ return null}+}+async function searchPageId(title: string): Promise<string | null> {const { data } = await pcgwGet<SearchResponse>(- `https://www.pcgamingwiki.com/w/api.php?action=query&list=search&srsearch=${title.replaceAll(+ `${API_URL}?action=query&list=search&srsearch=${title.replaceAll(' ','%20')}&format=json`@@ -141,7 +225,7 @@ async function getPageID(title: string, id?: string): Promise<string | null> {async function getImageUrl(fileName: string): Promise<string | undefined> {try {const { data } = await pcgwGet<ImageInfoResponse>(- `https://www.pcgamingwiki.com/w/api.php?action=query&format=json&prop=imageinfo&iiprop=url&titles=${encodeURIComponent(+ `${API_URL}?action=query&format=json&prop=imageinfo&iiprop=url&titles=${encodeURIComponent(`File:${fileName}`)}`)@@ -154,9 +238,14 @@ async function getImageUrl(fileName: string): Promise<string | undefined> {}}-async function getWikiText(id: string): Promise<string | null> {+async function getWikiText(page: PageRef): Promise<string | null> {+ const pageParam =+ 'pageId' in page+ ? `pageid=${page.pageId}`+ : `page=${encodeURIComponent(page.pageTitle)}`+const { data } = await pcgwGet<ParseResponse>(- `https://www.pcgamingwiki.com/w/api.php?action=parse&format=json&pageid=${id}&redirects=true&prop=wikitext`+ `${API_URL}?action=parse&format=json&${pageParam}&redirects=true&prop=wikitext`)if (!data.parse.wikitext || !data.parse.wikitext['*']) {diff --git a/src/backend/wiki_game_info/protondb/utils.ts b/src/backend/wiki_game_info/protondb/utils.tsindex 12c391074..0501951cb 100644--- a/src/backend/wiki_game_info/protondb/utils.ts+++ b/src/backend/wiki_game_info/protondb/utils.ts@@ -30,8 +30,10 @@ export async function getInfoFromProtonDB(logDebug('No response when getting ProtonDB info')return null}- const resp_str = JSON.stringify(response.data)- logDebug(`ProtonDB data for ${steamID} ${resp_str}`)+ logDebug(+ `ProtonDB tier for ${steamID}: ${response.data?.tier ?? 'unknown'}`,+ LogPrefix.ExtraGameInfo+ )if (!response.data?.tier) {logError('No tier in response, API changed?')diff --git a/src/backend/wiki_game_info/scores.ts b/src/backend/wiki_game_info/scores.tsnew file mode 100644index 000000000..4f407edfe--- /dev/null+++ b/src/backend/wiki_game_info/scores.ts@@ -0,0 +1,25 @@+import { GameScoreInfo, GameScores } from 'common/types'+import { getMetacriticScore } from './metacritic/utils'+import { getOpenCriticScore } from './opencritic/utils'++const EMPTY_SCORE: GameScoreInfo = { score: '', urlid: '' }++/**+ * Critic scores for a game, resolved outside PCGamingWiki.+ *+ * Each provider caches its own result, so opening the same game page again is+ * free. Scores are deliberately not stored together with the wiki info: that+ * cache lives for 30 days and would freeze an empty result from before the+ * providers had a chance to run.+ */+export async function getGameScores(title: string): Promise<GameScores> {+ const [metacritic, opencritic] = await Promise.all([+ getMetacriticScore(title).catch(() => EMPTY_SCORE),+ getOpenCriticScore(title).catch(() => EMPTY_SCORE)+ ])++ return {+ ...(metacritic.score ? { metacritic } : {}),+ ...(opencritic.score ? { opencritic } : {})+ }+}diff --git a/src/backend/wiki_game_info/steamdeck/utils.ts b/src/backend/wiki_game_info/steamdeck/utils.tsindex 8fa752395..9b8fd73ea 100644--- a/src/backend/wiki_game_info/steamdeck/utils.ts+++ b/src/backend/wiki_game_info/steamdeck/utils.ts@@ -29,8 +29,12 @@ export async function getSteamDeckComp(logDebug('No response when getting Steam Deck info')return null}- const resp_str = JSON.stringify(response.data)- logDebug(`SteamDeck data for ${steamID} ${resp_str}`)+ logDebug(+ `Steam Deck category for ${steamID}: ${+ response.data?.results?.resolved_category ?? 'unknown'+ }`,+ LogPrefix.ExtraGameInfo+ )if (!Number.isFinite(response.data?.results?.resolved_category)) {logError('No resolved_category in response, API changed?')diff --git a/src/backend/wiki_game_info/wiki_game_info.ts b/src/backend/wiki_game_info/wiki_game_info.tsindex e53ee6eef..0b586936e 100644--- a/src/backend/wiki_game_info/wiki_game_info.ts+++ b/src/backend/wiki_game_info/wiki_game_info.ts@@ -9,6 +9,7 @@ import { getInfoFromAppleGamingWiki } from './applegamingwiki/utils'import { getHowLongToBeat } from './howlongtobeat/utils'import { fetchPCGamingWikiInfo } from './pcgamingwiki/utils'import { getUmuId } from './umu/utils'+import { getGameScores } from './scores'import { isLinux, isMac } from 'backend/constants/environment'import type { Game } from 'common/types/game_manager'@@ -68,7 +69,9 @@ export async function getWikiGameInfo(game: Game): Promise<WikiInfo | null> {[`Using cached ExtraGameInfo data for ${title}`],LogPrefix.ExtraGameInfo)- return cachedResponse+ // 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) }}logInfo(`Getting ExtraGameInfo data for ${title}`, LogPrefix.ExtraGameInfo)@@ -78,7 +81,7 @@ export async function getWikiGameInfo(game: Game): Promise<WikiInfo | null> {if (cacheable) {wikiGameInfoStore.set(cacheKey, info)}- return info+ return { ...info, scores: await getGameScores(title) }}const [pcgwResult, gamesdb, applegamingwiki, umuId] = await Promise.all([@@ -126,7 +129,7 @@ export async function getWikiGameInfo(game: Game): Promise<WikiInfo | null> {wikiGameInfoStore.set(cacheKey, wikiGameInfo)}- return wikiGameInfo+ return { ...wikiGameInfo, scores: await getGameScores(title) }} catch (error) {logError([`Was not able to get ExtraGameInfo data for ${gameInfo.title}`, error],diff --git a/src/common/types.ts b/src/common/types.tsindex 7800a213e..9d3e7b08a 100644--- a/src/common/types.ts+++ b/src/common/types.ts@@ -865,6 +865,15 @@ export interface GameScoreInfo {score: stringurlid: string}++/**+ * Critic scores resolved from third-party providers (Metacritic, OpenCritic),+ * independently of PCGamingWiki.+ */+export interface GameScores {+ metacritic?: GameScoreInfo+ opencritic?: GameScoreInfo+}export interface PCGamingWikiInfo {steamID: stringhowLongToBeatID: string@@ -907,6 +916,7 @@ export interface WikiInfo {gamesdb: GamesDBInfo | nullsteamInfo: SteamInfo | nullumuId: string | null+ scores?: GameScores}/**diff --git a/src/frontend/components/UI/Carousel/__tests__/thumbnail.test.ts b/src/frontend/components/UI/Carousel/__tests__/thumbnail.test.tsnew file mode 100644index 000000000..6b791b70c--- /dev/null+++ b/src/frontend/components/UI/Carousel/__tests__/thumbnail.test.ts@@ -0,0 +1,31 @@+import { resolveThumbnailSource } from '../thumbnail'++const failed = (...sources: string[]) => new Set(sources)++describe('resolveThumbnailSource', () => {+ const image = {+ src: 'https://cdn.example.com/shot-full.jpg',+ thumbnail: 'https://cdn.example.com/shot-thumb.jpg'+ }++ it('uses the thumbnail when it is available', () => {+ expect(resolveThumbnailSource(image, failed())).toBe(image.thumbnail)+ })++ it('uses the full screenshot when the store sends no thumbnail', () => {+ expect(resolveThumbnailSource({ src: image.src }, failed())).toBe(image.src)+ })++ it('falls back to the full screenshot when the thumbnail failed', () => {+ expect(resolveThumbnailSource(image, failed(image.thumbnail))).toBe(+ image.src+ )+ })++ it('keeps the full screenshot when both sources failed', () => {+ // The placeholder is decided by the carousel, not here.+ expect(+ resolveThumbnailSource(image, failed(image.src, image.thumbnail))+ ).toBe(image.src)+ })+})diff --git a/src/frontend/components/UI/Carousel/index.tsx b/src/frontend/components/UI/Carousel/index.tsxindex b6f4edfa1..d9d85ca8c 100644--- a/src/frontend/components/UI/Carousel/index.tsx+++ b/src/frontend/components/UI/Carousel/index.tsx@@ -5,6 +5,7 @@ import { Pause, Play } from 'lucide-react'import Button from '../Button'import CachedImage from '../CachedImage'import Icon from '../Icon'+import { resolveThumbnailSource } from './thumbnail'import './index.css'export interface CarouselImage {@@ -185,35 +186,39 @@ const Carousel = ({{hasMany && (<div className="Carousel__thumbnails" ref={thumbnailsRef}>- {images.map((item, index) => (- <button- key={item.src}- type="button"- className={classNames('Carousel__thumbnail', {- 'Carousel__thumbnail--active': index === activeIndex- })}- aria-label={t('carousel.show', 'Show image {{index}}', {- index: index + 1- })}- aria-current={index === activeIndex ? 'true' : undefined}- onClick={() => setCurrent(index)}- >- {showsPlaceholder(item.thumbnail ?? item.src) ? (- <div className="Carousel__placeholder" aria-hidden="true">- {placeholder}- </div>- ) : (- <CachedImage- src={item.thumbnail ?? item.src}- alt=""- onError={markFailed(item.thumbnail ?? item.src)}- className={classNames('Carousel__thumbnailImage', {- 'Carousel__image--contain': item.fit === 'contain'- })}- />- )}- </button>- ))}+ {images.map((item, index) => {+ const thumbnailSrc = resolveThumbnailSource(item, failedSources)++ return (+ <button+ key={item.src}+ type="button"+ className={classNames('Carousel__thumbnail', {+ 'Carousel__thumbnail--active': index === activeIndex+ })}+ aria-label={t('carousel.show', 'Show image {{index}}', {+ index: index + 1+ })}+ aria-current={index === activeIndex ? 'true' : undefined}+ onClick={() => setCurrent(index)}+ >+ {showsPlaceholder(thumbnailSrc) ? (+ <div className="Carousel__placeholder" aria-hidden="true">+ {placeholder}+ </div>+ ) : (+ <CachedImage+ src={thumbnailSrc}+ alt=""+ onError={markFailed(thumbnailSrc)}+ className={classNames('Carousel__thumbnailImage', {+ 'Carousel__image--contain': item.fit === 'contain'+ })}+ />+ )}+ </button>+ )+ })}</div>)}</section>diff --git a/src/frontend/components/UI/Carousel/thumbnail.ts b/src/frontend/components/UI/Carousel/thumbnail.tsnew file mode 100644index 000000000..1361ce445--- /dev/null+++ b/src/frontend/components/UI/Carousel/thumbnail.ts@@ -0,0 +1,23 @@+interface ThumbnailCandidate {+ src: string+ thumbnail?: string+}++/**+ * Picks what a carousel thumbnail should render.+ *+ * Stores are inconsistent about thumbnails: some send none, some send URLs+ * that no longer resolve. In both cases the full screenshot is a better+ * fallback than the launcher logo, so only a broken full screenshot ends up+ * in the placeholder.+ */+export function resolveThumbnailSource(+ image: ThumbnailCandidate,+ failedSources: ReadonlySet<string>+): string {+ if (image.thumbnail && !failedSources.has(image.thumbnail)) {+ return image.thumbnail+ }++ return image.src+}diff --git a/src/frontend/screens/Game/GamePage/components/Description.tsx b/src/frontend/screens/Game/GamePage/components/Description.tsxindex 5b0cb5bd9..0078e94b4 100644--- a/src/frontend/screens/Game/GamePage/components/Description.tsx+++ b/src/frontend/screens/Game/GamePage/components/Description.tsx@@ -1,6 +1,10 @@-import { useContext } from 'react'+import { useContext, useEffect, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import GameContext from '../../GameContext'+import {+ DESCRIPTION_PREVIEW_LENGTH,+ truncateDescription+} from './truncate_description'const Description = () => {const { t } = useTranslation('gamepage')@@ -12,7 +16,18 @@ const Description = () => {gameInfo?.description ||t('generic.noDescription', 'No description available')- const paragraphs = description+ const isLong = description.length > DESCRIPTION_PREVIEW_LENGTH+ const [expanded, setExpanded] = useState(false)++ // A new game should always start collapsed.+ useEffect(() => setExpanded(false), [description])++ const visibleDescription = useMemo(+ () => (expanded ? description : truncateDescription(description)),+ [description, expanded]+ )++ const paragraphs = visibleDescription.split(/\n{2,}|\r\n{2,}/).map((paragraph) => paragraph.trim()).filter(Boolean)@@ -24,6 +39,18 @@ const Description = () => {<p key={paragraph}>{paragraph}</p>))}</div>+ {isLong && (+ <button+ type="button"+ className="aboutGame__toggle"+ aria-expanded={expanded}+ onClick={() => setExpanded((value) => !value)}+ >+ {expanded+ ? t('game.showLess', 'Show less')+ : t('game.showMore', 'Show more')}+ </button>+ )}</section>)}diff --git a/src/frontend/screens/Game/GamePage/components/GameMedia.tsx b/src/frontend/screens/Game/GamePage/components/GameMedia.tsxindex 35282351e..134f2c95d 100644--- a/src/frontend/screens/Game/GamePage/components/GameMedia.tsx+++ b/src/frontend/screens/Game/GamePage/components/GameMedia.tsx@@ -4,6 +4,7 @@ import { GameInfo } from 'common/types'import { Carousel, StoreBadge } from 'frontend/components/UI'import type { CarouselImage } from 'frontend/components/UI/Carousel'import HeroicIcon from 'frontend/assets/heroic-icon.svg?react'+import { createNewWindow } from 'frontend/helpers'import GameContext from '../../GameContext'interface Props {@@ -29,6 +30,8 @@ const GameMedia = ({ gameInfo }: Props) => {const cover =gameInfo.overrides?.art_cover || gameInfo.art_cover || gameExtraInfo?.coverconst logo = gameInfo.art_logo+ const storeUrl = gameExtraInfo?.storeUrl || gameInfo.store_url+ const openStorePage = t('game.openStorePage', 'Open game page')const images = useMemo<CarouselImage[]>(() => {if (screenshots?.length) {@@ -71,6 +74,20 @@ const GameMedia = ({ gameInfo }: Props) => {return artwork}, [screenshots, background, cover, logo, title, t])+ const storeBadge = storeUrl ? (+ <button+ type="button"+ className="gamePage__storeLink"+ title={openStorePage}+ aria-label={openStorePage}+ onClick={() => createNewWindow(storeUrl)}+ >+ <StoreBadge runner={runner} />+ </button>+ ) : (+ <StoreBadge runner={runner} title={STORE_NAMES[runner] ?? runner} />+ )+return (<CarouselclassName="gamePage__media"@@ -82,9 +99,7 @@ const GameMedia = ({ gameInfo }: Props) => {aria-label={t('game.heroicLogoAlt', 'Heroic Games Launcher logo')}/>}- badge={- <StoreBadge runner={runner} title={STORE_NAMES[runner] ?? runner} />- }+ badge={storeBadge}/>)}diff --git a/src/frontend/screens/Game/GamePage/components/Scores.tsx b/src/frontend/screens/Game/GamePage/components/Scores.tsxindex 13f6d7596..6061385c7 100644--- a/src/frontend/screens/Game/GamePage/components/Scores.tsx+++ b/src/frontend/screens/Game/GamePage/components/Scores.tsx@@ -18,7 +18,15 @@ const Scores = ({ gameInfo }: Props) => {const pcgamingwiki = wikiInfo?.pcgamingwikiconst applegamingwiki = wikiInfo?.applegamingwiki- const { metacritic, opencritic, igdb } = pcgamingwiki ?? {}+ const {+ metacritic: wikiMetacritic,+ opencritic: wikiOpenCritic,+ igdb+ } = pcgamingwiki ?? {}+ // Providers resolved outside PCGamingWiki win over whatever came from its+ // wikitext, which has been unreliable since the 2026 server migration.+ const metacritic = wikiInfo?.scores?.metacritic ?? wikiMetacritic+ const opencritic = wikiInfo?.scores?.opencritic ?? wikiOpenCriticconst metacriticScore = metacritic?.score || gameExtraInfo?.scoreconst title = gameInfo.overrides?.title || gameInfo.titlediff --git a/src/frontend/screens/Game/GamePage/components/__tests__/description.test.ts b/src/frontend/screens/Game/GamePage/components/__tests__/description.test.tsnew file mode 100644index 000000000..3539671a9--- /dev/null+++ b/src/frontend/screens/Game/GamePage/components/__tests__/description.test.ts@@ -0,0 +1,34 @@+import {+ DESCRIPTION_PREVIEW_LENGTH,+ truncateDescription+} from '../truncate_description'++describe('truncateDescription', () => {+ it('keeps short descriptions untouched', () => {+ expect(truncateDescription('A short description.')).toBe(+ 'A short description.'+ )+ })++ it('cuts long descriptions and marks the cut', () => {+ const text = 'word '.repeat(200).trim()+ const result = truncateDescription(text)++ expect(result.length).toBeLessThanOrEqual(DESCRIPTION_PREVIEW_LENGTH + 1)+ expect(result.endsWith('…')).toBe(true)+ })++ it('cuts at a word boundary', () => {+ const text = `${'a'.repeat(50)} ${'b'.repeat(50)} ${'c'.repeat(600)}`+ const result = truncateDescription(text, 120)++ expect(result).toBe(`${'a'.repeat(50)} ${'b'.repeat(50)}…`)+ })++ it('handles a long text without spaces', () => {+ const text = 'x'.repeat(700)+ const result = truncateDescription(text, 100)++ expect(result).toBe(`${'x'.repeat(100)}…`)+ })+})diff --git a/src/frontend/screens/Game/GamePage/components/truncate_description.ts b/src/frontend/screens/Game/GamePage/components/truncate_description.tsnew file mode 100644index 000000000..3618e591b--- /dev/null+++ b/src/frontend/screens/Game/GamePage/components/truncate_description.ts@@ -0,0 +1,23 @@+// The name cannot be `description.ts`: `Description.tsx` lives next to it and+// Windows resolves imports case-insensitively, so rollup would pick this file+// when the components barrel imports `./Description`.+export const DESCRIPTION_PREVIEW_LENGTH = 600++/**+ * Shortens a description to the preview length, cutting at a word boundary so+ * the text does not end mid word.+ */+export function truncateDescription(+ text: string,+ limit = DESCRIPTION_PREVIEW_LENGTH+): string {+ if (text.length <= limit) {+ return text+ }++ const cut = text.slice(0, limit)+ const lastSpace = cut.lastIndexOf(' ')+ const boundary = lastSpace > limit * 0.6 ? lastSpace : cut.length++ return `${cut.slice(0, boundary).trimEnd()}…`+}diff --git a/src/frontend/screens/Game/GamePage/index.css b/src/frontend/screens/Game/GamePage/index.cssindex 7eac57747..c2d824b4a 100644--- a/src/frontend/screens/Game/GamePage/index.css+++ b/src/frontend/screens/Game/GamePage/index.css@@ -114,6 +114,7 @@.gamePage__hero .aboutGame {max-width: 72ch;+ text-align: start;}.gamePage__hero .aboutGame .summary {@@ -122,6 +123,25 @@text-shadow: 0 1px 2px rgba(6, 10, 15, 0.6);}+.aboutGame__toggle {+ margin-block-start: var(--space-xs-fixed);+ padding: 0;+ border: 0;+ background: none;+ color: var(--hero-ink-soft, inherit);+ font: inherit;+ font-weight: var(--bold);+ text-decoration: underline;+ text-underline-offset: 2px;+ text-align: start;+ cursor: pointer;+}++.aboutGame__toggle:hover,+.aboutGame__toggle:focus-visible {+ opacity: 0.85;+}+.gamePage__heroMain {display: flex;flex-direction: column;@@ -246,6 +266,19 @@min-width: 0;}+.gamePage__storeLink {+ display: flex;+ padding: 0;+ border: 0;+ background: none;+ cursor: pointer;+}++.gamePage__storeLink:hover,+.gamePage__storeLink:focus-visible {+ opacity: 0.85;+}+.gamePage__infoColumns {display: grid;grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));diff --git a/src/frontend/screens/Game/GamePage/index.tsx b/src/frontend/screens/Game/GamePage/index.tsxindex aa478617b..85e56ed0f 100644--- a/src/frontend/screens/Game/GamePage/index.tsx+++ b/src/frontend/screens/Game/GamePage/index.tsx@@ -370,9 +370,18 @@ export default React.memo(function GamePage(): JSX.Element | null {useEffect(() => {window.api.getWikiGameInfo(gameInfo.title, appName, runner).then((info) => {+ // Scores come from their own providers, so keep the wiki info even when+ // PCGamingWiki/AppleGamingWiki/HowLongToBeat have nothing for the game.+ const hasScores = Boolean(+ info?.scores?.metacritic?.score || info?.scores?.opencritic?.score+ )+if (info &&- (info.applegamingwiki || info.howlongtobeat || info.pcgamingwiki)+ (info.applegamingwiki ||+ info.howlongtobeat ||+ info.pcgamingwiki ||+ hasScores)) {setWikiInfo(info)}