Skip to content

A games launcher for GOG, Amazon and Epic Games for Linux, Windows and macOS.

1.8 KB
Raw Blame
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)
    )
  }
}