Skip to content

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

17.2 KB
Raw Blame
import { readFile, readdir, realpath, stat } from 'node:fs/promises'
import { existsSync } from 'graceful-fs'
import { basename, join } from 'path'
import axios from 'axios'

import {
  getSideloadPreset,
  getSideloadPresetAppName,
  type MissingSideloadGame,
  type ScannedSideloadGame,
  type SideloadPreset
} from 'common/sideload_presets'
import { GameConfig } from 'backend/game_config'
import { isWindows } from 'backend/constants/environment'
import { writeConfig } from 'backend/utils'
import { logInfo, logWarning, LogPrefix } from 'backend/logger'

import { libraryStore } from './electronStores'
import { getPresetArtwork } from './presets'
import { libraryManagerMap } from '..'

import type { GameInfo } from 'common/types'

interface SideloadScanResult {
  games: ScannedSideloadGame[]
  missing: MissingSideloadGame[]
  prefix?: string
  error?: string
}

interface RegistrySection {
  name: string
  values: Record<string, string>
}

const executableExcludePattern =
  /(unins|uninstall|setup|installer|helper|cleanup|touchup|crash|report|update|patch|launcher|dxsetup|redist|vc_|eula|readme|autorun|touchup)/i

export function decodeRegistryString(value: string): string {
  let decoded = ''

  for (let index = 0; index < value.length; index++) {
    const character = value[index]
    if (character !== '\\') {
      decoded += character
      continue
    }

    const next = value[index + 1]
    if (next === undefined) {
      decoded += '\\'
      continue
    }

    switch (next) {
      case 'n':
        decoded += '\n'
        index++
        break
      case 'r':
        decoded += '\r'
        index++
        break
      case 't':
        decoded += '\t'
        index++
        break
      case '"':
        decoded += '"'
        index++
        break
      case '\\':
        decoded += '\\'
        index++
        break
      case 'x': {
        const hex = /^[0-9a-fA-F]{1,4}/.exec(value.slice(index + 2))?.[0]
        if (hex) {
          decoded += String.fromCharCode(parseInt(hex, 16))
          index += 1 + hex.length
        } else {
          decoded += '\\'
        }
        break
      }
      default:
        // Unknown escapes keep the backslash and the following character.
        decoded += character
    }
  }

  return decoded
}

/**
 * Minimal parser for Wine's .reg files. We only need section names and string
 * values; hex/dword values are intentionally ignored.
 */
export function parseWineRegistry(text: string): RegistrySection[] {
  const sections: RegistrySection[] = []
  let current: RegistrySection | undefined

  for (const line of text.split(/\r?\n/)) {
    const sectionMatch = /^\[(.+)\](?:\s+\d+)?$/.exec(line.trim())
    if (sectionMatch) {
      current = {
        name: sectionMatch[1].replace(/\\\\/g, '\\'),
        values: {}
      }
      sections.push(current)
      continue
    }

    if (!current || !line.startsWith('"')) {
      if (current && line.startsWith('@=')) {
        const raw = line.slice(2).trim()
        if (raw.startsWith('"') && raw.endsWith('"')) {
          current.values['@'] = decodeRegistryString(raw.slice(1, -1))
        }
      }
      continue
    }

    const valueMatch = /^"((?:\\.|[^"\\])+)"=(.+)$/.exec(line)
    if (!valueMatch) {
      continue
    }

    let rawValue = valueMatch[2].trim()
    if (rawValue.startsWith('"') && rawValue.endsWith('"')) {
      rawValue = rawValue.slice(1, -1)
      current.values[decodeRegistryString(valueMatch[1])] =
        decodeRegistryString(rawValue)
    }
  }

  return sections
}

async function readRegistrySections(
  prefixRoot: string
): Promise<RegistrySection[]> {
  const sections = new Map<string, RegistrySection>()

  for (const file of ['system.reg', 'user.reg']) {
    const filePath = join(prefixRoot, file)
    if (!existsSync(filePath)) {
      continue
    }
    try {
      const parsed = parseWineRegistry(await readFile(filePath, 'utf-8'))
      for (const section of parsed) {
        const existing = sections.get(section.name)
        if (existing) {
          Object.assign(existing.values, section.values)
        } else {
          sections.set(section.name, section)
        }
      }
    } catch (error) {
      logWarning(
        `Failed to read ${filePath}: ${String(error)}`,
        LogPrefix.Sideload
      )
    }
  }

  return [...sections.values()]
}

function getRegistryRoot(prefix: string): string | undefined {
  if (existsSync(join(prefix, 'system.reg'))) {
    return prefix
  }
  const protonRoot = join(prefix, 'pfx')
  if (existsSync(join(protonRoot, 'system.reg'))) {
    return protonRoot
  }
  return undefined
}

function registryPathToLocal(
  prefixRoot: string,
  windowsPath: string | undefined
): string | undefined {
  if (!windowsPath) {
    return undefined
  }
  const normalized = windowsPath.replaceAll('\\', '/')
  const match = /^([a-zA-Z]):\/(.*)$/.exec(normalized)
  if (!match) {
    return undefined
  }
  const parts = match[2].split('/').filter(Boolean)
  const drive = match[1].toLowerCase()

  if (drive === 'c') {
    return join(prefixRoot, 'drive_c', ...parts)
  }

  // Other drives are exposed by Wine as dosdevices/<letter>: symlinks.
  const driveRoot = join(prefixRoot, 'dosdevices', `${drive}:`)
  if (!existsSync(driveRoot)) {
    return undefined
  }
  return join(driveRoot, ...parts)
}

function stripTrademarks(value: string): string {
  return value
    .replace(/[™®]/g, '')
    .replace(/\((tm|r)\)/gi, '')
    .replace(/\s+/g, ' ')
    .trim()
}

async function findExecutableInDirectory(
  directory: string,
  depth = 4
): Promise<string | undefined> {
  let best: { path: string; size: number } | undefined
  const visited = new Set<string>()

  const walk = async (current: string, remaining: number) => {
    let realPath: string
    try {
      realPath = await realpath(current)
    } catch {
      return
    }
    if (visited.has(realPath)) {
      return
    }
    visited.add(realPath)

    let entries
    try {
      entries = await readdir(current, { withFileTypes: true })
    } catch {
      return
    }

    for (const entry of entries) {
      const entryPath = join(current, entry.name)
      let isDirectory = entry.isDirectory()
      if (!isDirectory && entry.isSymbolicLink()) {
        try {
          isDirectory = (await stat(entryPath)).isDirectory()
        } catch {
          isDirectory = false
        }
      }

      if (isDirectory) {
        if (remaining > 0 && entry.name !== '__Installer') {
          await walk(entryPath, remaining - 1)
        }
        continue
      }
      if (
        !/\.exe$/i.test(entry.name) ||
        executableExcludePattern.test(entry.name)
      ) {
        continue
      }
      try {
        const size = (await stat(entryPath)).size
        if (!best || size > best.size) {
          best = { path: entryPath, size }
        }
      } catch {
        // ignore unreadable files
      }
    }
  }

  await walk(directory, depth)
  return best?.path
}

function getDisplayIconExecutable(
  prefixRoot: string,
  displayIcon: string | undefined
): string | undefined {
  if (!displayIcon) {
    return undefined
  }
  const cleanPath = displayIcon
    .replace(/^"|"$/g, '')
    .replace(/,\s*\d+$/, '')
    .trim()
  if (!/\.exe$/i.test(cleanPath)) {
    return undefined
  }
  const localPath = registryPathToLocal(prefixRoot, cleanPath)
  return localPath && existsSync(localPath) ? localPath : undefined
}

function scanUbisoft(
  prefixRoot: string,
  sections: RegistrySection[]
): ScannedSideloadGame[] {
  const games: ScannedSideloadGame[] = []
  const seen = new Set<string>()

  for (const section of sections) {
    const match =
      /^Software\\(?:Wow6432Node\\)?Ubisoft\\Launcher\\Installs\\([^\\]+)$/i.exec(
        section.name
      )
    if (!match) {
      continue
    }

    const gameId = match[1]
    if (seen.has(gameId)) {
      continue
    }

    const installDir = registryPathToLocal(
      prefixRoot,
      section.values['InstallDir']
    )
    if (!installDir || !existsSync(installDir)) {
      continue
    }

    seen.add(gameId)
    const title = basename(installDir.replace(/[\\/]+$/, ''))
    games.push({
      id: gameId,
      source: 'ubisoft',
      title,
      installDir,
      launchUrl: `uplay://launch/${gameId}/0`,
      added: false
    })
  }

  return games
}

async function scanEA(
  prefixRoot: string,
  sections: RegistrySection[]
): Promise<ScannedSideloadGame[]> {
  const games: ScannedSideloadGame[] = []
  const seen = new Set<string>()

  for (const section of sections) {
    const isUninstallSection =
      /^Software\\(?:Wow6432Node\\)?Microsoft\\Windows\\CurrentVersion\\Uninstall\\[^\\]+$/i.test(
        section.name
      )
    if (!isUninstallSection) {
      continue
    }

    const displayName = stripTrademarks(section.values['DisplayName'] ?? '')
    const publisher = section.values['Publisher'] ?? ''
    const installDir = registryPathToLocal(
      prefixRoot,
      section.values['InstallLocation']
    )

    if (
      !displayName ||
      !installDir ||
      !existsSync(installDir) ||
      !/electronic arts/i.test(publisher) ||
      /ea app|origin|visual c|directx|redistributable|touchup|cleanup|error reporter/i.test(
        displayName
      ) ||
      /EA Desktop[\\/]?/i.test(installDir)
    ) {
      continue
    }

    const executable =
      (await findExecutableInDirectory(installDir)) ??
      getDisplayIconExecutable(prefixRoot, section.values['DisplayIcon'])
    if (!executable) {
      continue
    }

    const key = (installDir + '|' + executable).toLowerCase()
    if (seen.has(key)) {
      continue
    }
    seen.add(key)

    games.push({
      id: section.name.split('\\').at(-1) ?? displayName,
      source: 'ea',
      title: displayName,
      installDir,
      executable,
      added: false
    })
  }

  return games
}

async function scanBattleNet(
  prefixRoot: string,
  sections: RegistrySection[]
): Promise<ScannedSideloadGame[]> {
  const games: ScannedSideloadGame[] = []
  const seen = new Set<string>()
  const hasBattlenetProtocol = sections.some((section) =>
    /^Software\\Classes\\battlenet$/i.test(section.name)
  )

  for (const section of sections) {
    const isUninstallSection =
      /^Software\\(?:Wow6432Node\\)?Microsoft\\Windows\\CurrentVersion\\Uninstall\\[^\\]+$/i.test(
        section.name
      )
    if (!isUninstallSection) {
      continue
    }

    const uninstallString = section.values['UninstallString'] ?? ''
    if (!/Blizzard Uninstaller\.exe/i.test(uninstallString)) {
      continue
    }
    const uid = /--uid=([^\s"]+)/i.exec(uninstallString)?.[1]
    if (!uid || uid.toLowerCase() === 'battle.net') {
      continue
    }
    if (seen.has(uid)) {
      continue
    }

    const installDir = registryPathToLocal(
      prefixRoot,
      section.values['InstallLocation']
    )
    if (!installDir || !existsSync(installDir)) {
      continue
    }

    const executable =
      getDisplayIconExecutable(prefixRoot, section.values['DisplayIcon']) ??
      (await findExecutableInDirectory(installDir))
    if (!executable) {
      continue
    }

    seen.add(uid)
    games.push({
      id: uid,
      source: 'battlenet',
      title: stripTrademarks(section.values['DisplayName'] ?? uid),
      installDir,
      executable,
      launchUrl: hasBattlenetProtocol ? `battlenet://${uid}` : undefined,
      added: false
    })
  }

  return games
}

export async function scanGamesForPreset(
  preset: SideloadPreset,
  prefixRoot: string,
  sections: RegistrySection[]
): Promise<ScannedSideloadGame[]> {
  switch (preset.id) {
    case 'ubisoft-connect':
      return scanUbisoft(prefixRoot, sections)
    case 'ea-app':
      return scanEA(prefixRoot, sections)
    case 'battlenet':
      return scanBattleNet(prefixRoot, sections)
    default:
      return []
  }
}

function markAlreadyAdded(
  preset: SideloadPreset,
  games: ScannedSideloadGame[]
): ScannedSideloadGame[] {
  const library = libraryStore.get('games', [])

  return games.map((game) => {
    const added = library.some((entry) => {
      if (entry.sourcePresetId === preset.id && entry.storeGameId === game.id) {
        return true
      }
      if (game.launchUrl && entry.launchUrl === game.launchUrl) {
        return true
      }
      if (
        game.executable &&
        entry.install?.executable &&
        entry.install.executable === game.executable
      ) {
        return true
      }
      return false
    })

    return { ...game, added }
  })
}

function getMissingGames(
  preset: SideloadPreset,
  games: ScannedSideloadGame[]
): MissingSideloadGame[] {
  const detected = new Set(games.map((game) => game.id))

  return libraryStore
    .get('games', [])
    .filter((entry) => {
      if (entry.sourcePresetId !== preset.id || !entry.storeGameId) {
        return false
      }
      if (detected.has(entry.storeGameId)) {
        return false
      }
      // Some stores leave an empty install folder behind after uninstalling.
      // Treat the entry as missing when either its executable or its folder
      // is gone.
      const executableMissing = Boolean(
        entry.install?.executable && !existsSync(entry.install.executable)
      )
      const folderMissing = !entry.folder_name || !existsSync(entry.folder_name)
      return executableMissing || folderMissing
    })
    .map((entry) => ({
      appName: entry.app_name,
      title: entry.title,
      storeGameId: entry.storeGameId
    }))
    .sort((a, b) => a.title.localeCompare(b.title))
}

export async function scanPresetGames(
  presetId: string
): Promise<SideloadScanResult> {
  const preset = getSideloadPreset(presetId)
  if (!preset?.launcher) {
    return { games: [], missing: [], error: 'not-a-launcher-preset' }
  }
  if (isWindows) {
    return { games: [], missing: [], error: 'unsupported-platform' }
  }

  const appName = getSideloadPresetAppName(preset)
  const gameConfig = GameConfig.get(appName)
  const settings = gameConfig.config ?? (await gameConfig.getSettings())
  const prefix = settings?.winePrefix
  if (!prefix || prefix === '...' || !existsSync(prefix)) {
    return { games: [], missing: [], error: 'prefix-not-found' }
  }

  const registryRoot = getRegistryRoot(prefix)
  if (!registryRoot) {
    return { games: [], missing: [], error: 'registry-not-found', prefix }
  }

  const games = markAlreadyAdded(
    preset,
    await scanGamesForPreset(
      preset,
      registryRoot,
      await readRegistrySections(registryRoot)
    )
  ).sort((a, b) => a.title.localeCompare(b.title))

  const missing = getMissingGames(preset, games)

  logInfo(
    `Scanned ${games.length} game(s) in ${preset.title} prefix` +
      (missing.length ? `, ${missing.length} missing` : ''),
    LogPrefix.Sideload
  )
  return { games, missing, prefix }
}

async function getBottlesArtwork(title: string): Promise<string | undefined> {
  try {
    const response = await axios.get(
      `https://steamgrid.usebottles.com/api/search/${encodeURIComponent(title)}`,
      { timeout: 5000 }
    )
    const artwork =
      typeof response.data === 'string' ? response.data.trim() : ''
    return artwork.startsWith('http') ? artwork : undefined
  } catch (error) {
    logWarning(
      `Could not fetch Bottles artwork for "${title}": ${String(error)}`,
      LogPrefix.Sideload
    )
    return undefined
  }
}

function scannedAppName(preset: SideloadPreset, game: ScannedSideloadGame) {
  const suffix = game.id
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .slice(0, 40)
  return `preset-${preset.id}-${suffix}`
}

export async function addScannedGames(
  presetId: string,
  gameIds: string[]
): Promise<{ added: string[]; error?: string }> {
  const preset = getSideloadPreset(presetId)
  if (!preset?.launcher) {
    return { added: [], error: 'not-a-launcher-preset' }
  }

  const scan = await scanPresetGames(presetId)
  if (scan.error) {
    return { added: [], error: scan.error }
  }

  const selected = scan.games.filter(
    (game) => !game.added && gameIds.includes(game.id)
  )
  if (!selected.length) {
    return { added: [] }
  }

  const launcherAppName = getSideloadPresetAppName(preset)
  const launcherSettings = await GameConfig.get(launcherAppName).getSettings()
  const artwork = getPresetArtwork(presetId)
  const scannedArtwork = await Promise.all(
    selected.map((game) => getBottlesArtwork(game.title))
  )
  const added: string[] = []

  for (const [index, game] of selected.entries()) {
    const gameArtwork = scannedArtwork[index] ?? artwork.square
    const appName = scannedAppName(preset, game)
    const gameInfo: GameInfo = {
      runner: 'sideload',
      app_name: appName,
      title: game.title,
      install: {
        executable: game.executable,
        platform: 'Windows',
        is_dlc: false
      },
      folder_name: game.installDir,
      art_cover: scannedArtwork[index] ?? artwork.hero,
      art_square: gameArtwork,
      is_installed: true,
      canRunOffline: false,
      launchUrl: game.launchUrl,
      sourcePresetId: preset.id,
      storeGameId: game.id
    }

    libraryManagerMap['sideload'].addNewApp(gameInfo)

    await writeConfig(appName, {
      winePrefix: launcherSettings.winePrefix,
      wineVersion: launcherSettings.wineVersion,
      wineCrossoverBottle: launcherSettings.wineCrossoverBottle
    })

    added.push(appName)
  }

  logInfo(
    `Added ${added.length} scanned ${preset.title} game(s)`,
    LogPrefix.Sideload
  )
  return { added }
}