Skip to content

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

12.9 KB
Raw Blame
import './index.css'

import { useContext, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import classNames from 'classnames'

import {
  Modal,
  ModalContent,
  ModalFooter,
  ModalHeader
} from 'frontend/components/UI/Modal'
import { Button } from 'frontend/components/UI'
import ContextProvider from 'frontend/state/ContextProvider'

import type {
  HeroicApplyResult,
  HeroicBackupStageId,
  HeroicBackupValidationReport,
  PerGamePathOverride
} from 'common/types/importExport'
import type { Runner } from 'common/types'

import {
  StepCredentials,
  StepDone,
  StepGlobalSettings,
  StepLibrarySystem,
  StepPerGame,
  StepPickFile,
  StepSummary
} from './steps'
import type { PathChoice } from './shared'

type WizardStep = 0 | 1 | 2 | 3 | 4 | 5 | 6

const DEFAULT_CREDENTIALS: Partial<Record<Runner, boolean>> = {
  legendary: true,
  gog: true,
  nile: true,
  zoom: true,
  itchio: true
}

interface Props {
  open: boolean
  onClose: () => void
}

export default function ImportExportWizard({ open, onClose }: Props) {
  const { t } = useTranslation()
  const { platform } = useContext(ContextProvider)

  const stepTitles = [
    t('import-export.steps.pick-file', 'Pick a backup file'),
    t('import-export.steps.summary', 'Summary'),
    t('import-export.steps.global-settings', 'Global settings'),
    t('import-export.steps.per-game', 'Per-game settings'),
    t('import-export.steps.credentials', 'Store logins'),
    t('import-export.steps.library-system', 'Library & system'),
    t('import-export.steps.done', 'Done')
  ]

  const [step, setStep] = useState<WizardStep>(0)
  const [filePath, setFilePath] = useState('')
  const [validation, setValidation] =
    useState<HeroicBackupValidationReport | null>(null)
  const [validating, setValidating] = useState(false)
  const [validateError, setValidateError] = useState<string | null>(null)

  const [overwriteGlobal, setOverwriteGlobal] = useState(false)
  const [includeGlobal, setIncludeGlobal] = useState(true)
  const [includeCategories, setIncludeCategories] = useState(true)
  const [includePlaytime, setIncludePlaytime] = useState(true)
  const [includedApps, setIncludedApps] = useState<Set<string>>(new Set())
  const [appFilter, setAppFilter] = useState('')
  const [includedCredentials, setIncludedCredentials] =
    useState<Partial<Record<Runner, boolean>>>(DEFAULT_CREDENTIALS)
  const [pathChoices, setPathChoices] = useState<Record<string, PathChoice>>({})
  const [includedWineVersions, setIncludedWineVersions] = useState<Set<string>>(
    new Set()
  )
  const [downloadMissingGames, setDownloadMissingGames] = useState(true)

  const [applying, setApplying] = useState(false)
  const [applyResult, setApplyResult] = useState<HeroicApplyResult | null>(null)
  const [wineBusy, setWineBusy] = useState(false)

  const sessionRef = useRef(0)

  useEffect(() => {
    if (!open) {
      sessionRef.current += 1
      setStep(0)
      setFilePath('')
      setValidation(null)
      setValidateError(null)
      setApplyResult(null)
      setAppFilter('')
      setPathChoices({})
      setOverwriteGlobal(false)
      setIncludeGlobal(true)
      setIncludeCategories(true)
      setIncludePlaytime(true)
      setIncludedCredentials(DEFAULT_CREDENTIALS)
      setDownloadMissingGames(true)
    }
  }, [open])

  useEffect(() => {
    if (!validation) return
    setIncludedApps(new Set(validation.perGameAppNames))

    const creds: Partial<Record<Runner, boolean>> = {}
    for (const cred of validation.credentials) {
      creds[cred.runner] = cred.present
    }
    setIncludedCredentials(creds)

    const initial: Record<string, PathChoice> = {}
    for (const issue of validation.pathIssues) {
      initial[issue.appName] = {
        installAction: issue.installPathIssue ? 'download' : 'ignore',
        prefixAction: 'ignore'
      }
    }
    setPathChoices(initial)

    setIncludedWineVersions(
      new Set(
        validation.missingWineVersions
          .filter((v) => v.downloadable)
          .map((v) => v.version ?? v.displayName)
      )
    )
  }, [validation])

  const includedStages: HeroicBackupStageId[] = useMemo(() => {
    if (!validation) return []
    return validation.manifest.stages.filter((s) => {
      if (s === 'globalSettings') return includeGlobal
      if (s === 'categories') return includeCategories
      if (s === 'playtime') return includePlaytime
      if (s === 'credentials') {
        return Object.values(includedCredentials).some(Boolean)
      }
      if (s === 'perGameSettings') return includedApps.size > 0
      return true
    })
  }, [
    validation,
    includeGlobal,
    includeCategories,
    includePlaytime,
    includedApps,
    includedCredentials
  ])

  async function pickBackupFile(path: string) {
    setFilePath(path)
    await runValidation(path)
  }

  async function runValidation(path: string) {
    const session = sessionRef.current
    setValidating(true)
    setValidateError(null)
    try {
      const report = await window.api.validateHeroicBackup(path)
      if (session !== sessionRef.current) return
      if (report.ok) {
        setValidation(report)
        setStep(1)
      } else {
        setValidation(null)
        setValidateError(
          report.errors.join(' — ') ||
            t(
              'import-export.invalid-backup',
              'This file is not a valid Heroic backup.'
            )
        )
      }
    } catch (err) {
      if (session !== sessionRef.current) return
      setValidateError(String(err))
    } finally {
      if (session === sessionRef.current) setValidating(false)
    }
  }

  function toggleApp(appName: string) {
    setIncludedApps((prev) => {
      const next = new Set(prev)
      if (next.has(appName)) next.delete(appName)
      else next.add(appName)
      return next
    })
  }

  function setAllApps(include: boolean) {
    if (!validation) return
    setIncludedApps(include ? new Set(validation.perGameAppNames) : new Set())
  }

  function stepIsReachable(target: WizardStep): boolean {
    if (applying) return target === step
    if (step === 6 && applyResult?.ok !== false) return target === step
    if (!validation) return target === 0
    return target <= step
  }

  function goToStep(target: WizardStep) {
    if (stepIsReachable(target)) setStep(target)
  }

  function nextStep() {
    setStep((s) => Math.min(6, s + 1) as WizardStep)
  }

  function prevStep() {
    setStep((s) => Math.max(0, s - 1) as WizardStep)
  }

  async function applyBackup() {
    if (!validation) return
    setApplying(true)
    try {
      const overrides: PerGamePathOverride[] = []
      for (const issue of validation.pathIssues) {
        const choice = pathChoices[issue.appName]
        if (!choice) continue
        const o: PerGamePathOverride = { appName: issue.appName }
        if (choice.installAction === 'browse' && choice.installOverride)
          o.installPath = choice.installOverride
        if (choice.installAction === 'skip') o.skipInstallPath = true
        if (choice.installAction === 'download' && downloadMissingGames)
          o.installAfterImport = true
        if (choice.prefixAction === 'browse' && choice.prefixOverride)
          o.prefixPath = choice.prefixOverride
        if (choice.prefixAction === 'default-prefix') o.useDefaultPrefix = true
        if (Object.keys(o).length > 1) overrides.push(o)
      }

      const result = await window.api.applyHeroicBackup({
        sourcePath: filePath,
        stages: includedStages,
        overwriteGlobalSettings: overwriteGlobal,
        includedAppNames: Array.from(includedApps),
        includedCredentials,
        perGameOverrides: overrides,
        includedWineVersions: Array.from(includedWineVersions)
      })
      setApplyResult(result)
      setStep(6)
    } catch (err) {
      setApplyResult({
        ok: false,
        stages: [],
        gamesQueuedForDownload: [],
        wineVersionsQueuedForDownload: [],
        warnings: [],
        errors: [String(err)]
      })
      setStep(6)
    } finally {
      setApplying(false)
    }
  }

  if (!open) return null

  const guardedClose = () => {
    if (wineBusy || applying) return
    onClose()
  }

  return (
    <Modal
      className="ImportExportWizard"
      size="lg"
      onClose={guardedClose}
      showCloseButton={!wineBusy && !applying}
      disableBackdropClose
    >
      <ModalHeader>
        {t('import-export.wizard-title', 'Import Heroic backup')}
      </ModalHeader>

      <div className="ImportExportWizard__stepper" role="tablist">
        {stepTitles.map((title, idx) => (
          <button
            key={idx}
            type="button"
            role="tab"
            aria-selected={idx === step}
            className={classNames('ImportExportWizard__stepperItem', {
              'is-active': idx === step,
              'is-done': idx < step,
              'is-disabled': !stepIsReachable(idx as WizardStep)
            })}
            onClick={() => goToStep(idx as WizardStep)}
            disabled={!stepIsReachable(idx as WizardStep)}
          >
            <span className="ImportExportWizard__stepperNumber">{idx + 1}</span>
            <span className="ImportExportWizard__stepperLabel">{title}</span>
          </button>
        ))}
      </div>

      <ModalContent className="ImportExportWizard__body">
        <div key={step} className="ImportExportWizard__stepContent fadeIn">
          {step === 0 && (
            <StepPickFile
              filePath={filePath}
              onPick={(path) => {
                void pickBackupFile(path)
              }}
              validating={validating}
              error={validateError}
            />
          )}
          {step === 1 && validation && (
            <StepSummary validation={validation} currentPlatform={platform} />
          )}
          {step === 2 && validation && (
            <StepGlobalSettings
              validation={validation}
              includeGlobal={includeGlobal}
              setIncludeGlobal={setIncludeGlobal}
              overwriteGlobal={overwriteGlobal}
              setOverwriteGlobal={setOverwriteGlobal}
              includeCategories={includeCategories}
              setIncludeCategories={setIncludeCategories}
              includePlaytime={includePlaytime}
              setIncludePlaytime={setIncludePlaytime}
            />
          )}
          {step === 3 && validation && (
            <StepPerGame
              validation={validation}
              includedApps={includedApps}
              toggleApp={toggleApp}
              setAllApps={setAllApps}
              appFilter={appFilter}
              setAppFilter={setAppFilter}
            />
          )}
          {step === 4 && validation && (
            <StepCredentials
              validation={validation}
              included={includedCredentials}
              setIncluded={setIncludedCredentials}
            />
          )}
          {step === 5 && validation && (
            <StepLibrarySystem
              validation={validation}
              pathChoices={pathChoices}
              setPathChoices={setPathChoices}
              includedWineVersions={includedWineVersions}
              setIncludedWineVersions={setIncludedWineVersions}
              downloadMissingGames={downloadMissingGames}
              setDownloadMissingGames={setDownloadMissingGames}
            />
          )}
          {step === 6 && (
            <StepDone
              applyResult={applyResult}
              applying={applying}
              rollbackHintPath={applyResult?.rollbackPath}
              onWineBusyChange={setWineBusy}
            />
          )}
        </div>
      </ModalContent>

      <ModalFooter>
        <div className="ImportExportWizard__footer">
          <Button
            variant="secondary"
            onClick={prevStep}
            disabled={
              step === 0 ||
              applying ||
              (step === 6 && applyResult?.ok !== false)
            }
          >
            {t('import-export.back', 'Back')}
          </Button>
          {step < 5 && (
            <Button
              variant="primary"
              disabled={!validation || validating}
              onClick={nextStep}
            >
              {t('import-export.next', 'Next')}
            </Button>
          )}
          {step === 5 && (
            <Button variant="primary" onClick={applyBackup} disabled={applying}>
              {applying
                ? t('import-export.applying', 'Applying...')
                : t('import-export.apply', 'Apply backup')}
            </Button>
          )}
          {step === 6 && (
            <Button
              variant="primary"
              onClick={onClose}
              disabled={wineBusy}
              title={
                wineBusy
                  ? t(
                      'import-export.step7.wine-busy-hint',
                      'Wait until Wine / Proton finishes installing'
                    )
                  : undefined
              }
            >
              {t('import-export.close', 'Close')}
            </Button>
          )}
        </div>
      </ModalFooter>
    </Modal>
  )
}