-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathgames.ts
2200 lines (1909 loc) · 58.3 KB
/
games.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
InstallArgs,
InstalledInfo,
GameInfo,
ExtraInfo,
ExecResult,
GameSettings,
PlatformConfig,
LicenseConfigValidateResult,
ChannelReleaseMeta,
SiweValues,
UpdateArgs
} from '../../../common/types'
import { generateID } from '@valist/sdk'
import { hpLibraryStore } from './electronStore'
import { sendFrontendMessage, getMainWindow } from 'backend/main_window'
import {
LogPrefix,
logDebug,
logError,
logInfo,
logWarning
} from 'backend/logger/logger'
import {
ExtractZipService,
ExtractZipProgressResponse
} from 'backend/services/ExtractZipService'
import {
existsSync,
mkdirSync,
rmSync,
readdirSync,
readFileSync,
statSync
} from 'graceful-fs'
import {
isMac,
isWindows,
isLinux,
getValidateLicenseKeysApiUrl,
ipdtPatcher,
toolsPath,
ipdtManifestsPath
} from 'backend/constants'
import {
downloadFile,
spawnAsync,
killPattern,
shutdownWine,
getExecutableAndArgs,
calculateProgress,
calculateEta,
getFileSize,
getPlatformName
} from 'backend/utils'
import { notify, showDialogBoxModalAuto } from 'backend/dialog/dialog'
import path, { dirname, join } from 'path'
import {
callAbortController,
createAbortController,
deleteAbortController
} from 'backend/utils/aborthandler/aborthandler'
import {
getIPDTManifestUrl,
handleArchAndPlatform,
handlePlatformReversed,
runModPatcher,
sanitizeVersion,
safeRemoveDirectory
} from './utils'
import { getSettings as getSettingsSideload } from 'backend/storeManagers/sideload/games'
import {
addShortcuts as addShortcutsUtil,
removeShortcuts as removeShortcutsUtil
} from '../../shortcuts/shortcuts/shortcuts'
import { InstallResult, RemoveArgs } from 'common/types/game_manager'
import { GOGCloudSavesLocation } from 'common/types/gog'
import {
getGameProcessName,
launchGame
} from 'backend/storeManagers/storeManagerCommon/games'
import { PlatformsMetaInterface } from '@valist/sdk/dist/typesShared'
import { Channel } from '@valist/sdk/dist/typesApi'
import { DownloadItem, dialog } from 'electron'
import { waitForItemToDownload } from 'backend/utils/downloadFile/download_file'
import {
cancelQueueExtraction,
getFirstQueueElement,
updateQueueElementParam
} from 'backend/downloadmanager/downloadqueue'
import { captureException } from '@sentry/electron'
import Store from 'electron-store'
import i18next from 'i18next'
import { DEV_PORTAL_URL } from 'common/constants'
import getPartitionCookies from 'backend/utils/get_partition_cookies'
import { prepareBaseGameForModding } from 'backend/ipcHandlers/mods'
import { runWineCommandOnGame } from 'backend/utils/compatibility_layers'
import { chmod, writeFile } from 'fs/promises'
import { trackEvent } from 'backend/metrics/metrics'
import { getFlag } from 'backend/flags/flags'
import { ipfsGateway } from 'backend/vite_constants'
import { GlobalConfig } from 'backend/config'
import { PatchingError } from './types'
import { SiweMessage } from 'siwe'
interface ProgressDownloadingItem {
DownloadItem: DownloadItem
platformInfo?: PlatformConfig
destinationPath: string
gameInfo: GameInfo
installVersion: string
appPlatform: InstalledInfo['platform']
channelName: string | undefined
}
const inProgressDownloadsMap: Map<string, ProgressDownloadingItem> = new Map()
export const inProgressExtractionsMap: Map<string, ExtractZipService> =
new Map()
export async function getSettings(appName: string): Promise<GameSettings> {
return getSettingsSideload(appName)
}
export const isGameAvailable = async (appName: string) => {
const hpGameInfo = getGameInfo(appName)
if (hpGameInfo && hpGameInfo.install.platform === 'web') {
return true
}
if (hpGameInfo.install && hpGameInfo.install.executable) {
let { executable } = getExecutableAndArgs(hpGameInfo.install.executable)
const { targetExe } = await getSettings(appName)
if (targetExe) {
executable = targetExe
}
// on linux and mac replace backslashes with forward slashes on executable
if (!isWindows) {
executable = executable.replace(/\\/g, '/')
}
return existsSync(executable)
}
return false
}
export function isNative(appName: string): boolean {
const {
install: { platform }
} = getGameInfo(appName)
if (platform) {
if (platform === 'web') {
return true
}
if (isWindows) {
return true
}
const genericPlatform = handlePlatformReversed(platform).toLowerCase()
if (isMac && genericPlatform === 'mac') {
return true
}
if (isLinux && genericPlatform === 'linux') {
return true
}
}
return false
}
export async function stop(appName: string): Promise<void> {
const gameInfo = getGameInfo(appName)
const {
install: { executable = undefined }
} = gameInfo
if (executable) {
if (!isNative(appName)) {
const gameSettings = await getSettings(appName)
shutdownWine(gameSettings)
}
}
const gameProcessName = getGameProcessName(gameInfo)
if (gameProcessName) {
killPattern(gameProcessName)
if (!isNative(appName)) {
const gameSettings = await getSettings(appName)
shutdownWine(gameSettings)
}
}
}
export async function pause(appName: string): Promise<void> {
const dl = inProgressDownloadsMap.get(appName)
if (!dl?.DownloadItem) {
throw `Tried to pause download for ${appName} that is not in progress!`
}
dl.DownloadItem.pause()
}
// check for valid json file inside the folder before importing
// if none was found, check the first folder inside the folder
// return the path to the folder with a valid json file
// if none was found return empty string
// this is necessary because we do not know which folder the user has selected, the main folder or the game folder
const getValidGameFolderPath = (
appName: string,
folderPath: string
): string => {
const subFolders = readdirSync(folderPath)
if (subFolders.includes(`${appName}.json`)) {
return folderPath
}
// in case the selected folder is a dev folder with multiple games
for (const subFolder of subFolders) {
// check if it is a folder or a file, if it is a file, skip it
const subFolderStats = statSync(path.join(folderPath, subFolder))
if (subFolderStats.isDirectory()) {
if (getValidGameFolderPath(appName, path.join(folderPath, subFolder))) {
return path.join(folderPath, subFolder)
}
}
}
return ''
}
type HyperPlayManifest = {
manifest: InstalledInfo
}
/**
*
* @param appName
* @param pathName exe file full path
* @param platform
* @returns
*/
export async function importGame(
appName: string,
pathName: string
): Promise<ExecResult> {
pathName = getValidGameFolderPath(appName, pathName)
if (!pathName) {
logError(
'Not a valid game folder, import not possible',
LogPrefix.HyperPlay
)
showDialogBoxModalAuto({
title: i18next.t('importGameErrorTitle', 'Import Game Error'),
message: i18next.t(
'importGameErrorMessage',
'Not a valid game folder, importing game is not possible'
),
type: 'ERROR'
})
throw Error('Not a valid game folder, import not possible')
}
// read the json file and get the game info
const installInfo: HyperPlayManifest = JSON.parse(
readFileSync(path.join(pathName, `${appName}.json`), 'utf8')
)
const currentLibrary = hpLibraryStore.get('games', [])
const gameInLibrary = currentLibrary.find((val) => {
return val.app_name === appName
})
if (gameInLibrary === undefined) {
logInfo('Cannot find game in library so cannot import', LogPrefix.HyperPlay)
return { stderr: '', stdout: '' }
}
const gameInfo = getGameInfo(appName)
const channel = gameInfo.channels![
installInfo.manifest.channelName!
] as Channel
// Accessing the platform data with type assertion
const platformKey = installInfo.manifest
.platform as keyof PlatformsMetaInterface
const platformData = channel.release_meta.platforms[platformKey]
if (!platformData || !platformData.executable) {
logError(
`Platform data not found for ${appName} in importGame`,
LogPrefix.HyperPlay
)
return { stderr: '', stdout: '' }
}
const mainExe = platformData.executable
const executable = path.join(pathName, mainExe)
if (!existsSync(executable)) {
logError(`Executable ${executable} does not exist!`, LogPrefix.HyperPlay)
showDialogBoxModalAuto({
title: i18next.t('importGameErrorTitle', 'Import Game Error'),
message: i18next.t(
'importGameErrorMessageExecutable',
'Game Executable not found, importing game is not possible'
),
type: 'ERROR'
})
throw Error(`Executable ${executable} does not exist!`)
}
gameInLibrary.install = {
install_path: pathName,
executable,
install_size: installInfo.manifest.install_size ?? '0',
is_dlc: false,
version: installInfo.manifest.version,
platform: installInfo.manifest.platform,
channelName: installInfo.manifest.channelName
}
gameInLibrary.is_installed = true
hpLibraryStore.set('games', currentLibrary)
sendFrontendMessage('refreshLibrary', 'hyperplay')
// delete current manifest file
rmSync(path.join(pathName, `${appName}.json`))
writeManifestFile(appName, gameInLibrary.install)
return { stderr: '', stdout: '' }
}
type DistArgs = {
gamePath: string
appName: string
}
// for Windows games only
const installDistributables = async ({ gamePath, appName }: DistArgs) => {
sendFrontendMessage('gameStatusUpdate', {
appName,
status: 'distributables',
runner: 'hyperplay',
folder: gamePath
})
const possibleFolders = ['dist', 'redist', 'Dist', 'Redist']
let executables: string[] = []
for (const folder of possibleFolders) {
executables = executables.concat(
await findFolderAndExecutables(gamePath, folder)
)
}
for await (const executable of executables) {
logInfo(`Installing distributable ${executable}`, LogPrefix.HyperPlay)
// Not windows
if (!isWindows && !isNative(appName)) {
return runWineCommandOnGame('hyperplay', appName, {
commandParts: [executable, '/quiet'],
protonVerb: 'run',
startFolder: dirname(executable)
})
}
// Windows
return spawnAsync(executable, ['/quiet'])
}
return
}
const findFolderAndExecutables = async (
basePath: string,
folderName: string
): Promise<string[]> => {
let executables: string[] = []
if (!existsSync(basePath)) {
return executables
}
const entries = readdirSync(basePath, { withFileTypes: true })
for (const entry of entries) {
const entryPath = path.join(basePath, entry.name)
if (entry.isDirectory()) {
if (entry.name === folderName) {
executables = executables.concat(await findExecutables(entryPath))
} else {
executables = executables.concat(
await findFolderAndExecutables(entryPath, folderName)
)
}
}
}
return executables
}
const findExecutables = async (folderPath: string): Promise<string[]> => {
let executables: string[] = []
const files = readdirSync(folderPath, { withFileTypes: true })
logInfo(`Searching for executables in ${folderPath}`, LogPrefix.HyperPlay)
for (const file of files) {
if (file.isDirectory()) {
const subFolderExecutables = await findExecutables(
path.join(folderPath, file.name)
)
executables = executables.concat(subFolderExecutables)
} else if (file.name.endsWith('.exe')) {
logInfo(`Found distributable ${file.name}`, LogPrefix.HyperPlay)
executables.push(path.join(folderPath, file.name))
}
}
return executables
}
export async function cleanUpDownload(appName: string, directory: string) {
inProgressDownloadsMap.delete(appName)
inProgressExtractionsMap.delete(appName)
deleteAbortController(appName)
await safeRemoveDirectory(directory)
}
function getDownloadUrl(platformInfo: PlatformConfig, appName: string) {
const is_ci =
process.env.CI &&
process.env.MOCK_DOWNLOAD_URL &&
process.env.CI === 'e2e' &&
process.env.APP_NAME_TO_MOCK &&
process.env.APP_NAME_TO_MOCK === appName
const downloadUrl = is_ci
? process.env.MOCK_DOWNLOAD_URL
: platformInfo.external_url
return downloadUrl
}
async function downloadGame(
appName: string,
directory: string,
fileName: string,
platformInfo: PlatformConfig,
destinationPath: string,
gameInfo: GameInfo,
installVersion: string,
appPlatform: InstalledInfo['platform'],
channelName?: string
): Promise<void> {
if (await resumeIfPaused(appName)) {
return
}
/* eslint-disable-next-line no-async-promise-executor */
return new Promise(async (res, rej) => {
let downloadStarted = false
logInfo(
`Downloading zip file to directory ${directory} filename ${fileName}`,
LogPrefix.HyperPlay
)
// we might need a helper function to deal with the different platforms
const window = getMainWindow()
if (!window || !platformInfo.external_url) {
throw new Error('DownloadUrl not found')
}
const downloadUrl = getDownloadUrl(platformInfo, appName)
if (!downloadUrl) {
throw `Download url is invalid. Value: ${downloadUrl}`
}
logInfo(`Downloading from ${downloadUrl}`, LogPrefix.HyperPlay)
function handleProgess(
downloadedBytes: number,
downloadSpeed: number,
diskWriteSpeed: number,
progress: number
) {
const currentProgress = calculateProgress(
downloadedBytes,
Number.parseInt(platformInfo.downloadSize ?? '0'),
downloadSpeed,
diskWriteSpeed,
progress
)
if (downloadedBytes > 0 && !downloadStarted) {
downloadStarted = true
sendFrontendMessage('gameStatusUpdate', {
appName,
status: 'installing',
runner: 'hyperplay',
folder: destinationPath
})
}
window?.webContents.send(`progressUpdate-${appName}`, {
appName,
status: 'installing',
runner: 'hyperplay',
folder: destinationPath,
progress: {
folder: destinationPath,
...currentProgress
}
})
}
function onCompleted() {
res()
}
async function onCancel() {
try {
await cleanUpDownload(appName, directory)
} catch (err) {
rej(err)
}
rej()
}
const item = await downloadFile(
downloadUrl,
directory,
fileName,
createAbortController(appName),
handleProgess,
onCompleted,
onCancel
)
inProgressDownloadsMap.set(appName, {
DownloadItem: item,
appPlatform,
gameInfo,
destinationPath,
platformInfo,
installVersion,
channelName
})
})
}
function sanitizeFileName(filename: string) {
return filename.replace(/[/\\?%*:|"<>]/g, '-')
}
function getZipFileName(
appName: string,
platformInfo: PlatformConfig,
destinationPath: string
): { directory: string; filename: string } {
const zipName = encodeURI(platformInfo.name)
const tempfolder = path.join(destinationPath, '.temp', appName)
if (!existsSync(tempfolder)) {
mkdirSync(tempfolder, { recursive: true })
}
return { directory: tempfolder, filename: zipName }
}
export async function validateAccessCode({
accessCode,
channelId,
licenseConfigId
}: {
accessCode: string
channelId?: number
licenseConfigId?: number
}) {
const validateUrl = getValidateLicenseKeysApiUrl()
/* eslint-disable-next-line */
const request: Record<string, any> = {
code: accessCode
}
if (channelId !== undefined) {
request.channel_id = channelId
}
if (licenseConfigId !== undefined) {
request.license_config_id = licenseConfigId
}
const cookieString = await getPartitionCookies({
partition: 'persist:auth',
url: DEV_PORTAL_URL
})
const validateResult = await fetch(validateUrl, {
method: 'POST',
headers: {
Cookie: cookieString
},
body: JSON.stringify(request)
})
const result: LicenseConfigValidateResult = await validateResult.json()
return result
}
async function getAccessCodeGatedPlatforms(
accessCode: string,
channelId: number,
appName: string
): Promise<PlatformsMetaInterface> {
const validateResult = await validateAccessCode({ accessCode, channelId })
if (validateResult.valid !== true)
throw `Access code ${accessCode} is not valid for channel id ${channelId}!`
//set platform info
logInfo(
'Updating platform info with access code gated platform info in HyperPlay Game Manager',
LogPrefix.HyperPlay
)
if (validateResult.platforms === undefined)
throw 'Access code gated platforms returned by the validate url were undefined'
// update local game info access key code cache
// this will be needed for updating the game
const hpGames = hpLibraryStore.get('games', [])
const newHpGames = hpGames.map((val) => {
if (val.app_name === appName) {
if (val.accessCodesCache === undefined) val.accessCodesCache = {}
val.accessCodesCache[channelId] = accessCode
}
return val
})
hpLibraryStore.set('games', newHpGames)
return validateResult.platforms
}
async function getTokenGatedPlatforms(
channel_id: number,
siweValues: SiweValues
): Promise<PlatformsMetaInterface> {
const { address, message, signature } = siweValues
const request = {
message,
signature,
address,
channel_id
}
const validateUrl = `${DEV_PORTAL_URL}api/v1/license_contracts/validate`
const validateResponse = await fetch(validateUrl, {
method: 'POST',
body: JSON.stringify(request)
})
if (!validateResponse.ok) {
throw `Could not validate access ${await validateResponse.text()}`
}
const validateResult: LicenseConfigValidateResult =
await validateResponse.json()
if (validateResult.valid !== true)
throw `Address code ${address} is not valid for channel id ${channel_id}!`
if (validateResult.platforms === undefined)
throw 'Token gated platforms returned by the validate url were undefined'
return validateResult.platforms
}
function updateInstalledInfo(appName: string, installedInfo: InstalledInfo) {
const currentLibrary = hpLibraryStore.get('games', []) as GameInfo[]
const gameIndex = currentLibrary.findIndex(
(value) => value.app_name === appName
)
currentLibrary[gameIndex].install = installedInfo
currentLibrary[gameIndex].is_installed = true
hpLibraryStore.set('games', currentLibrary)
writeManifestFile(appName, installedInfo)
}
export function getDestinationPath(gameInfo: GameInfo, dirpath: string) {
if (
gameInfo.account_name === undefined ||
gameInfo.project_name === undefined
) {
throw `Account or project name is undefined for ${gameInfo.app_name}`
}
const accountFolderName = sanitizeFileName(gameInfo.account_name)
const projectFolderName = sanitizeFileName(gameInfo.project_name)
return path.join(dirpath, accountFolderName, projectFolderName)
}
function getReleaseMeta(
gameInfo: GameInfo,
channelName: string | undefined
): [ChannelReleaseMeta, Channel] {
const { channels } = gameInfo
if (
channelName === undefined ||
channels === undefined ||
!Object.hasOwn(channels, channelName)
) {
throw `Channel name not found for ${gameInfo.app_name}`
}
const selectedChannel = channels[channelName]
const releaseMeta = selectedChannel.release_meta
if (!releaseMeta) {
throw `Release meta not found for ${gameInfo.app_name}`
}
return [releaseMeta, selectedChannel]
}
async function resumeIfPaused(
appName: string
): Promise<InstallResult | boolean> {
const isPaused = inProgressDownloadsMap.has(appName)
if (isPaused) {
const item = inProgressDownloadsMap.get(appName)
if (!item?.DownloadItem) {
return false
}
item.DownloadItem.resume()
if (await waitForItemToDownload(item.DownloadItem)) {
await extract(appName, {
appPlatform: item.appPlatform,
gameInfo: item.gameInfo,
destinationPath: item.destinationPath,
platformInfo: item.platformInfo,
installVersion: item.installVersion,
channelName: item.channelName
})
return true
}
return false
}
return isPaused
}
export async function cancelExtraction(appName: string) {
logInfo(
`cancelExtraction: Extraction will be canceled and downloaded zip will be removed`,
LogPrefix.HyperPlay
)
try {
process.noAsar = false
const extractZipService = inProgressExtractionsMap.get(appName)
if (extractZipService) {
extractZipService.cancel()
}
} catch (error: unknown) {
logInfo(
`cancelExtraction: Error while canceling the operation ${
(error as Error).message
} `,
LogPrefix.HyperPlay
)
}
}
export function gameIsAccessCodeGated(appName: string): boolean {
const gameInfo = getGameInfo(appName)
const [, installedChannel] = getReleaseMeta(
gameInfo,
gameInfo.install.channelName
)
return installedChannel.license_config.access_codes
}
export async function install(
appName: string,
{
path: dirpath,
platformToInstall,
channelName,
accessCode,
updateOnly = false,
siweValues,
modOptions
}: InstallArgs
): Promise<InstallResult> {
if (await resumeIfPaused(appName)) {
return { status: 'done' }
}
let { directory, fileName } = { directory: '', fileName: '' }
try {
const gameInfo = getGameInfo(appName)
const { title, account_name } = gameInfo
const isMarketWars = account_name === 'marketwars'
if (isMarketWars && modOptions?.zipFilePath) {
try {
await prepareBaseGameForModding({
appName,
zipFile: modOptions.zipFilePath,
installPath: dirpath
})
} catch (error) {
callAbortController(appName)
return { status: 'error' }
}
}
const destinationPath = updateOnly
? dirpath
: getDestinationPath(gameInfo, dirpath)
const [releaseMeta, selectedChannel] = getReleaseMeta(gameInfo, channelName)
const releaseVersion: string = sanitizeVersion(releaseMeta.name)
const gameInfoVersion = gameInfo.version
? sanitizeVersion(gameInfo.version)
: ''
const installVersion = releaseVersion ?? gameInfoVersion ?? '0'
if (platformToInstall === 'Browser') {
const browserGameInstalledInfo: InstalledInfo = {
appName,
install_path: destinationPath,
executable: '',
install_size: '0',
is_dlc: false,
version: installVersion,
platform: 'web',
channelName
}
updateInstalledInfo(appName, browserGameInstalledInfo)
return { status: 'done' }
}
const window = getMainWindow()
if (!window) return { status: 'error', error: 'Window undefined' }
const appPlatform = handleArchAndPlatform(platformToInstall, releaseMeta)
let platformInfo = releaseMeta.platforms[appPlatform]
if (!platformInfo) {
return {
status: 'error',
error: `Platform info not found for ${appName}`
}
}
if (selectedChannel.license_config.tokens) {
if (!siweValues?.address) throw 'No address found'
const gatedPlatforms = await getTokenGatedPlatforms(
selectedChannel.channel_id,
siweValues
)
platformInfo = gatedPlatforms[appPlatform] ?? platformInfo
} else if (selectedChannel.license_config.access_codes) {
// get presigned platform info if code gated
if (accessCode === undefined)
throw 'Access code was undefined for an access code gated channel'
const gatedPlatforms = await getAccessCodeGatedPlatforms(
accessCode,
selectedChannel.channel_id,
appName
)
platformInfo = gatedPlatforms[appPlatform] ?? platformInfo
}
if (!existsSync(dirpath)) {
mkdirSync(dirpath, { recursive: true })
}
logInfo(`Installing ${title} to ${dirpath}...`, LogPrefix.HyperPlay)
const zipPathInfo = getZipFileName(appName, platformInfo, destinationPath)
directory = zipPathInfo.directory
fileName = zipPathInfo.filename
// download the zip file
if (!existsSync(destinationPath)) {
mkdirSync(destinationPath, { recursive: true })
}
// Reset the download progress
window.webContents.send(`progressUpdate-${appName}`, {
appName,
runner: 'hyperplay',
folder: destinationPath,
status: 'done',
progress: {
folder: destinationPath,
percent: 0,
diskSpeed: 0,
downSpeed: 0,
bytes: 0,
eta: null
}
})
await downloadGame(
appName,
directory,
fileName,
platformInfo,
destinationPath,
gameInfo,
installVersion,
appPlatform,
channelName
)
if (!platformInfo.executable) {
return {
status: 'error',
error: 'Executable not found during install in HyperPlay game manager'
}
}
await extract(appName, {
appPlatform,
gameInfo,
destinationPath,
platformInfo,
installVersion,
channelName
})
if (isMarketWars) {
try {
await runModPatcher(appName)
} catch (error) {
return { status: 'error' }
}
}
if (platformToInstall === 'Windows') {
logInfo(`Looking for distributables for ${appName}`, LogPrefix.HyperPlay)
await installDistributables({
gamePath: destinationPath,
appName
})
}
return { status: 'done' }
} catch (error) {
process.noAsar = false
logInfo(
`Error while downloading and extracting game: ${error}`,
LogPrefix.HyperPlay
)
if (!`${error}`.includes('Download stopped or paused')) {
callAbortController(appName)
return {
status: 'abort'
}
}
return {
status: 'error',
error: `${error}`
}
}
}
interface Extract {
platformInfo?: PlatformConfig
destinationPath: string
gameInfo: GameInfo
installVersion: string
appPlatform: InstalledInfo['platform']
channelName: string | undefined
}
export async function extract(
appName: string,
{
platformInfo,
destinationPath,