forked from thepeacockproject/Peacock
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.ts
More file actions
862 lines (752 loc) · 27.8 KB
/
utils.ts
File metadata and controls
862 lines (752 loc) · 27.8 KB
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
/*
* The Peacock Project - a HITMAN server replacement.
* Copyright (C) 2021-2026 The Peacock Project Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { decode } from "jsonwebtoken"
import type { NextFunction, Response } from "express"
import type {
GameVersion,
MissionManifestObjective,
OfficialSublocation,
PeacockLocationsData,
RepositoryId,
RequestWithJwt,
ServerVersion,
Unlockable,
UserProfile,
} from "./types/types"
import { AxiosError } from "axios"
import { log, LogLevel } from "./loggingInterop"
import { writeFileSync } from "fs"
import { getFlag } from "./flags"
import { getConfig, getVersionedConfig } from "./configSwizzleManager"
import { compare } from "semver"
import assert from "assert"
import { getUnlockableById } from "./inventory"
/**
* True if the server is being run by the launcher, false otherwise.
*/
export const IS_LAUNCHER = process.env.IS_PEACOCK_LAUNCHER === "true"
export const ServerVer: ServerVersion = {
_Major: 8,
_Minor: 23,
_Build: 0,
_Revision: 0,
}
export const PEACOCKVERSTRING = HUMAN_VERSION
export const uuidRegex =
/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/
export const contractTypes = ["featured", "usercreated"]
/**
* A list of game versions, except scpc.
*/
export const versions: Exclude<GameVersion, "scpc">[] = ["h1", "h2", "h3"]
export const contractCreationTutorialId = "d7e2607c-6916-48e2-9588-976c7d8998bb"
/**
* The latest profile version, this should be changed in conjunction with the updating mechanism.
*
* See docs/USER_PROFILES.md for more.
*/
export const LATEST_PROFILE_VERSION = 2
export async function checkForUpdates(): Promise<void> {
if (getFlag("updateChecking") === false) {
return
}
try {
type VersionCheckResponse = { id: string; channel: string }
const res = await fetch(
"https://backend.rdil.rocks/peacock/latest-version/data",
)
const data = (await res.json()) as VersionCheckResponse
const current = compare(PEACOCKVERSTRING, data.id)
const isNewer = current === 1
if (isNewer) {
log(
LogLevel.INFO,
`You're ahead of the latest release! The latest version of Peacock (${data.id}) is older than this build.`,
"updates",
)
} else if (current === 0) {
log(LogLevel.DEBUG, "Peacock is up to date.", "updates")
} else {
log(
LogLevel.WARN,
`Peacock is out-of-date! Check the Discord for the latest release.`,
"updates",
)
}
} catch {
log(LogLevel.WARN, "Failed to check for updates!", "updates")
}
}
export * from "semver"
export function getRemoteService(gameVersion: GameVersion): string | undefined {
switch (gameVersion) {
case "h3":
return "hm3-service"
case "h2":
return "pc2-service"
default:
return "pc-service"
}
}
/**
* Middleware that validates the authentication token sent by the client.
*
* @param req The express request object.
* @param res The express response object.
* @param next The express next function.
*/
export function extractToken(
req: RequestWithJwt,
res?: Response,
next?: NextFunction,
): void {
const header = req.header("Authorization")
const auth = header ? header.split(" ") : []
if (auth.length === 2 && auth[0].toLowerCase() === "bearer") {
// @ts-expect-error Type overlap
req.jwt = <string>decode(auth[1])
if (!uuidRegex.test(req.jwt.unique_name)) {
res?.status(424).send("profile appears to be corrupted")
return
}
next?.()
return
}
req.shouldCease = true
next?.("router")
}
export const DEFAULT_MASTERY_MAXLEVEL = 20
export const XP_PER_LEVEL = 6000
export function getMaxProfileLevel(gameVersion: GameVersion): number {
if (gameVersion === "h3") {
return 12500
}
return 5000
}
/**
* Calculates the level for the given XP based on xpPerLevel (defaults to XP_PER_LEVEL).
* Minimum level returned is 1.
*/
export function levelForXp(xp: number, xpPerLevel = XP_PER_LEVEL): number {
return Math.max(1, Math.floor(xp / xpPerLevel) + 1)
}
/**
* Calculates the required XP for the given level based on xpPerLevel (defaults to XP_PER_LEVEL).
* Minimum XP returned is 0.
*/
export function xpRequiredForLevel(
level: number,
xpPerLevel = XP_PER_LEVEL,
): number {
return Math.max(0, (level - 1) * xpPerLevel)
}
export const EVERGREEN_LEVEL_INFO: number[] = [
0, 5000, 10000, 17000, 24000, 31000, 38000, 45000, 52000, 61000, 70000,
79000, 88000, 97000, 106000, 115000, 124000, 133000, 142000, 154000, 166000,
178000, 190000, 202000, 214000, 226000, 238000, 250000, 262000, 280000,
298000, 316000, 334000, 352000, 370000, 388000, 406000, 424000, 442000,
468000, 494000, 520000, 546000, 572000, 598000, 624000, 650000, 676000,
702000, 736000, 770000, 804000, 838000, 872000, 906000, 940000, 974000,
1008000, 1042000, 1082000, 1122000, 1162000, 1202000, 1242000, 1282000,
1322000, 1362000, 1402000, 1442000, 1492000, 1542000, 1592000, 1642000,
1692000, 1742000, 1792000, 1842000, 1892000, 1942000, 2002000, 2062000,
2122000, 2182000, 2242000, 2302000, 2362000, 2422000, 2482000, 2542000,
2692000, 2842000, 2992000, 3142000, 3292000, 3442000, 3592000, 3742000,
3892000, 4042000, 4192000,
]
export function evergreenLevelForXp(xp: number): number {
for (let i = 1; i < EVERGREEN_LEVEL_INFO.length; i++) {
if (xp < EVERGREEN_LEVEL_INFO[i]) {
return i
}
}
return EVERGREEN_LEVEL_INFO.length
}
/**
* Get the amount of XP needed to reach a mastery level in Evergreen.
*
* @param level
* @returns The XP, as a number.
*/
export function xpRequiredForEvergreenLevel(level: number): number {
return EVERGREEN_LEVEL_INFO[level - 1]
}
export const SNIPER_LEVEL_INFO: number[] = [
0, 50000, 150000, 500000, 1000000, 1700000, 2500000, 3500000, 5000000,
7000000, 9500000, 12500000, 16000000, 20000000, 25000000, 31000000,
38000000, 47000000, 58000000, 70000000,
]
export function sniperLevelForXp(xp: number): number {
for (let i = 1; i < SNIPER_LEVEL_INFO.length; i++) {
if (xp < SNIPER_LEVEL_INFO[i]) {
return i
}
}
return SNIPER_LEVEL_INFO.length
}
/**
* Get the amount of XP needed to reach a mastery level in sniper missions.
*
* @param level
* @returns The XP, as a number.
*/
export function xpRequiredForSniperLevel(level: number): number {
return SNIPER_LEVEL_INFO[level - 1]
}
/**
* Clamps the given value between a minimum and maximum value.
*/
export function clampValue(value: number, min: number, max: number) {
return Math.max(min, Math.min(value, max))
}
/**
* Updates a user profile depending on the current version (if any).
*
* @param profile The user profile to update
* @param gameVersion The game version
*/
function updateUserProfile(
profile: UserProfile,
gameVersion: GameVersion,
): void {
/**
* This switch is structured such that the current profile version will return.
* thus stopping the function.
*
* As the version number is incremented, the previous version should be added
* as a case to update it to the newest version.
*/
switch (profile.Version) {
case LATEST_PROFILE_VERSION:
// This profile updated to the latest version, we're done.
return
case 1: {
/* ////// VERSION 2 ////// */
const sublocations = profile.Extensions.progression.PlayerProfileXP
.Sublocations as unknown as OfficialSublocation[]
profile.Extensions.progression.PlayerProfileXP.Sublocations =
Object.fromEntries(
sublocations.map((value) => [
value.Location,
{
Xp: value.Xp,
ActionXp: value.ActionXp,
},
]),
)
profile.Extensions.LastOfficialSync = null
profile.Version = 2
return updateUserProfile(profile, gameVersion)
}
default: {
// Check that the profile version is indeed undefined. If it isn't,
// we've forgotten to add a version to the switch.
if (profile.Version !== undefined) {
log(
LogLevel.ERROR,
`Unhandled profile version ${profile.Version}`,
)
return
}
/* ////// VERSION 1 ////// */
// Profile has no version, update it to version 1, then re-run
// the function to update it to subsequent versions.
const sniperLocs = {
LOCATION_PARENT_AUSTRIA: [
"FIREARMS_SC_HERO_SNIPER_HM",
"FIREARMS_SC_HERO_SNIPER_KNIGHT",
"FIREARMS_SC_HERO_SNIPER_STONE",
],
LOCATION_PARENT_SALTY: [
"FIREARMS_SC_SEAGULL_HM",
"FIREARMS_SC_SEAGULL_KNIGHT",
"FIREARMS_SC_SEAGULL_STONE",
],
LOCATION_PARENT_CAGED: [
"FIREARMS_SC_FALCON_HM",
"FIREARMS_SC_FALCON_KNIGHT",
"FIREARMS_SC_FALCON_STONE",
],
}
// We need this to ensure all locations are added.
const allLocs = Object.keys(
getVersionedConfig<PeacockLocationsData>(
"LocationsData",
gameVersion,
false,
).parents,
).map((key) => key.toLocaleLowerCase())
profile.Extensions.progression.Locations = allLocs.reduce(
(obj, key) => {
const newKey = key.toLocaleUpperCase()
const curData =
profile.Extensions.progression.Locations[key]
if (gameVersion === "h1") {
// No sniper locations, but we add normal and pro1
// @ts-expect-error I know what I'm doing.
obj[newKey] = {
// Data from previous profiles only contains normal and is the default.
normal: {
Xp: curData.Xp ?? 0,
Level: curData.Level ?? 1,
PreviouslySeenXp: curData.PreviouslySeenXp ?? 0,
},
pro1: {
Xp: 0,
Level: 1,
PreviouslySeenXp: 0,
},
}
} else {
// We need to update sniper locations.
// @ts-expect-error I know what I'm doing.
obj[newKey] = sniperLocs[newKey]
? // @ts-expect-error I know what I'm doing.
sniperLocs[newKey].reduce((obj, uId) => {
obj[uId] = {
Xp: 0,
Level: 1,
PreviouslySeenXp: 0,
}
return obj
}, {})
: {
Xp: curData.Xp ?? 0,
Level: curData.Level ?? 1,
PreviouslySeenXp:
curData.PreviouslySeenXp ?? 0,
}
}
return obj
},
{},
)
// @ts-expect-error Legacy property.
delete profile.Extensions.progression["Unlockables"]
profile.Version = 1
return updateUserProfile(profile, gameVersion)
}
}
}
/**
* Returns whether a location is a sniper location. Works for both parent and child locations.
*
* @param location The location ID string.
* @returns A boolean denoting the result.
*/
export function isSniperLocation(location: string): boolean {
return (
location.includes("AUSTRIA") ||
location.includes("SALTY") ||
location.includes("CAGED")
)
}
export function castUserProfile(
profile: UserProfile,
gameVersion: GameVersion,
path?: string,
): UserProfile {
const j = fastClone(profile)
if (!j.Extensions || Object.keys(j.Extensions).length === 0) {
log(LogLevel.DEBUG, "No extensions - skipping validation")
return j
}
let dirty = false
for (const item of [
"PeacockEscalations",
"PeacockFavoriteContracts",
"PeacockPlayedContracts",
"PeacockCompletedEscalations",
"CPD",
]) {
if (!Object.hasOwn(j.Extensions, item)) {
log(LogLevel.DEBUG, `Err missing property ${item}`)
log(
LogLevel.WARN,
`A requested user profile is missing some vital data.`,
)
log(
LogLevel.WARN,
`Attempting to repair the profile automatically...`,
)
if (item === "PeacockEscalations") {
j.Extensions.PeacockEscalations = {}
}
if (item === "PeacockCompletedEscalations") {
j.Extensions.PeacockCompletedEscalations = []
}
if (item === "PeacockFavoriteContracts") {
j.Extensions.PeacockFavoriteContracts = []
}
if (item === "CPD") {
j.Extensions.CPD = {}
}
if (item === "PeacockPlayedContracts") {
j.Extensions.PeacockPlayedContracts = {}
}
dirty = true
}
}
// Fix Extensions.gamepersistentdata.HitsFilterType.
// None of the old profiles should have "MyPlaylist".
if (j.Extensions.gamepersistentdata.HitsFilterType["MyPlaylist"]) {
j.Extensions.gamepersistentdata.HitsFilterType = {
MyHistory: "all",
MyContracts: "all",
MyPlaylist: "all",
}
}
if (j.Extensions?.gamepersistentdata?.PersistentBool) {
switch (getFlag("mapDiscoveryState")) {
case "REVEALED":
{
const areas = Object.keys(getConfig("AreaMap", false))
for (const area of areas) {
j.Extensions.gamepersistentdata.PersistentBool[area] =
true
}
}
break
case "CLOUDED":
j.Extensions.gamepersistentdata.PersistentBool = {
__Full:
j.Extensions.gamepersistentdata.PersistentBool
?.__Full ?? {},
}
break
}
}
if (j.Version !== LATEST_PROFILE_VERSION) {
// This profile is not the latest version. We must update it.
log(LogLevel.DEBUG, `Profile is outdated, updating...`)
updateUserProfile(j, gameVersion)
dirty = true
}
if (dirty) {
writeFileSync(path ?? `userdata/users/${j.Id}.json`, JSON.stringify(j))
log(LogLevel.INFO, "Profile successfully repaired!")
}
return j
}
export const defaultSuits = {
LOCATION_PARENT_ICA_FACILITY: "TOKEN_OUTFIT_GREENLAND_HERO_TRAININGSUIT",
LOCATION_PARENT_PARIS: "TOKEN_OUTFIT_PARIS_HERO_PARISSUIT",
LOCATION_PARENT_COASTALTOWN: "TOKEN_OUTFIT_SAPIENZA_HERO_SAPIENZASUIT",
LOCATION_COASTALTOWN_MOVIESET:
"TOKEN_OUTFIT_SAPIENZA_HERO_SAPIENZASUIT_NOGLASSES",
LOCATION_COASTALTOWN_EBOLA:
"TOKEN_OUTFIT_SAPIENZA_HERO_SAPIENZASUIT_NOGLASSES",
LOCATION_PARENT_MARRAKECH: "TOKEN_OUTFIT_MARRAKESH_HERO_MARRAKESHSUIT",
LOCATION_PARENT_BANGKOK: "TOKEN_OUTFIT_BANGKOK_HERO_BANGKOKSUIT",
LOCATION_PARENT_COLORADO: "TOKEN_OUTFIT_COLORADO_HERO_COLORADOSUIT",
LOCATION_PARENT_HOKKAIDO: "TOKEN_OUTFIT_HOKKAIDO_HERO_HOKKAIDOSUIT",
LOCATION_PARENT_NEWZEALAND: "TOKEN_OUTFIT_NEWZEALAND_HERO_NEWZEALANDSUIT",
LOCATION_PARENT_MIAMI: "TOKEN_OUTFIT_MIAMI_HERO_MIAMISUIT",
LOCATION_PARENT_COLOMBIA: "TOKEN_OUTFIT_COLOMBIA_HERO_COLOMBIASUIT",
LOCATION_PARENT_MUMBAI: "TOKEN_OUTFIT_MUMBAI_HERO_MUMBAISUIT",
LOCATION_PARENT_NORTHAMERICA:
"TOKEN_OUTFIT_NORTHAMERICA_HERO_NORTHAMERICASUIT",
LOCATION_PARENT_NORTHSEA: "TOKEN_OUTFIT_NORTHSEA_HERO_NORTHSEASUIT",
LOCATION_PARENT_GREEDY: "TOKEN_OUTFIT_GREEDY_HERO_GREEDYSUIT",
LOCATION_PARENT_OPULENT: "TOKEN_OUTFIT_OPULENT_HERO_OPULENTSUIT",
LOCATION_PARENT_GOLDEN: "TOKEN_OUTFIT_HERO_GECKO_SUIT",
LOCATION_PARENT_ANCESTRAL: "TOKEN_OUTFIT_ANCESTRAL_HERO_ANCESTRALSUIT",
LOCATION_ANCESTRAL_SMOOTHSNAKE:
"TOKEN_OUTFIT_ANCESTRAL_HERO_SMOOTHSNAKESUIT",
LOCATION_PARENT_EDGY: "TOKEN_OUTFIT_EDGY_HERO_EDGYSUIT",
LOCATION_PARENT_WET: "TOKEN_OUTFIT_WET_HERO_WETSUIT",
LOCATION_PARENT_ELEGANT: "TOKEN_OUTFIT_ELEGANT_HERO_LLAMASUIT",
LOCATION_PARENT_TRAPPED: "TOKEN_OUTFIT_TRAPPED_WOLVERINE_SUIT",
LOCATION_PARENT_ROCKY: "TOKEN_OUTFIT_HERO_DUGONG_SUIT",
}
/**
* Default suits that are attainable via challenges or mastery in this version.
*
* NOTE: Currently this is hardcoded. To allow for flexibility and extensibility, this should be generated in real-time
* using the Drops of challenges and masteries. However, that would require looping through all challenges and masteries
* for all default suits, which is slow. This is a trade-off (but also allows plugins to alter it if they really want to).
*
* @param gameVersion The game version.
* @returns The default suits that are attainable via challenges or mastery.
*/
export function attainableDefaults(gameVersion: GameVersion): string[] {
switch (gameVersion) {
case "h3":
return [
"TOKEN_OUTFIT_GREENLAND_HERO_TRAININGSUIT",
"TOKEN_OUTFIT_HOKKAIDO_HERO_HOKKAIDOSUIT",
"TOKEN_OUTFIT_OPULENT_HERO_OPULENTSUIT",
"TOKEN_OUTFIT_HERO_DUGONG_SUIT",
]
default:
return []
}
}
/**
* Gets the default suit for a given sub-location and parent location.
* Priority is given to the sub-location, then the parent location, then 47's signature suit.
*
* @param subLocation The sub-location.
* @param gameVersion The game version.
* @param suitOverride A default suit override for this contract.
* @returns The default suit for the given sub-location and parent location.
*/
export function getDefaultSuitFor(
subLocation: Unlockable,
gameVersion: GameVersion,
suitOverride?: string | undefined,
): string {
type Cast = keyof typeof defaultSuits
return suitOverride && getUnlockableById(suitOverride, gameVersion)
? suitOverride
: defaultSuits[subLocation.Id as Cast] ||
defaultSuits[subLocation.Properties.ParentLocation as Cast] ||
"TOKEN_OUTFIT_HITMANSUIT"
}
export const nilUuid = "00000000-0000-0000-0000-000000000000"
export const hitmapsUrl = "https://backend.rdil.rocks/partners/hitmaps/contract"
export const vrTutorialId = "47fdffe9-c453-45ad-ad96-ac6f63494c40"
export function isObjectiveActive(
objective: MissionManifestObjective,
doneObjectives: Set<RepositoryId>,
): boolean {
if (objective.Activation !== undefined) {
if (Array.isArray(objective.Activation.$eq)) {
return (
objective.Activation.$eq[1] === "Completed" &&
doneObjectives.has(
(<string>objective.Activation.$eq[0]).substring(1),
)
)
}
}
return false
}
export const jokes = [
"STILL... we are close now, 47.",
"James Batty, the plaintiff, wants Janus to stop his annual landing of a helicopter, near the local creek.",
"Searching for local masons in your area...",
"I wonder what kind of curry currymaker makes",
"Listening for uncommon guard voice lines...",
"Mistah Jason Portman, please come to the hospital entrance. A doctor will escort you to your checkup. That was for: mistah Jason Portman.",
"Nakamura-San, please come to the operating theatre. Stat.",
"Ugh, my knee is so sore.",
"Mister Prichard I presume? Hi, I'm Chen Ting. Pleasure to meet you.",
"Find your inner... zen",
"I love those little drones when they scoot around like that.",
"Welcome, welcome! Hello! Good to see you. So lovely to see so many familiar faces here today.",
"hi so i own hitman 1 and 2 i got hitman 1 and 2 on disc hitman 1 def edition and hitman 2 gold disc both on ps4 and when i got hitman 2 i downloaded the best legesy pack and all of my saves are on hitman 2 but i got rid of that game will i need both of them to get all the levels onto hitman 3 and im staying on ps4",
"The weather is always nice in Paris.",
"Have you seen a girl around? Short hair, with a bright green bag?",
"The show is just about to start.",
"Entering the Ether lab requires a uniform and a keycard... luckily, it seems both are within reach.",
"Welcome to Bangkok, 47. The target has been in residence at the hotel for almost a month and security is tight, with several other high-profile guests also at the hotel. Good Hunting.",
]
/**
* The current game difficulty.
*/
export const gameDifficulty = {
/**
* The game isn't on a set difficulty (missions with no difficulties data?).
*/
unset: 0,
/**
* Casual mode.
*/
casual: 1,
/**
* Alias for {@link casual}.
*/
easy: 1,
/**
* Professional (normal) mode.
*/
normal: 2,
/**
* Master mode.
*/
master: 4,
/**
* Alias for {@link master}.
*/
hard: 4,
} as const
export function difficultyToString(difficulty: number): string {
switch (difficulty) {
case 1:
return "casual"
case 2:
return "normal"
case 4:
return "master"
case 0:
default:
return "unset"
}
}
/**
* Handle an {@link AxiosError} from axios.
*
* @see https://axios-http.com/docs/handling_errors
* @param error The error from axios.
*/
export function handleAxiosError(error: AxiosError): void {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
log(LogLevel.DEBUG, `Request error: code ${error.response.status}`)
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of http.ClientRequest
log(LogLevel.DEBUG, `Request error: bad fetch`)
} else {
// Something happened in setting up the request that triggered an Error
log(LogLevel.DEBUG, `Request error: something went wrong`)
}
}
export function unlockOrderComparer(a: Unlockable, b: Unlockable): number {
return (
(a?.Properties?.UnlockOrder ?? Number.POSITIVE_INFINITY) -
(b?.Properties?.UnlockOrder ?? Number.POSITIVE_INFINITY) || 0
)
}
export function unlockLevelComparer(a: Unlockable, b: Unlockable): number {
return (
(a?.Properties?.UnlockLevel
? parseInt(a?.Properties?.UnlockLevel)
: Number.POSITIVE_INFINITY) -
(b?.Properties?.UnlockLevel
? parseInt(b?.Properties?.UnlockLevel)
: Number.POSITIVE_INFINITY) || 0
)
}
/**
* Converts a contract's public ID as a long-form number into the version with dashes.
*
* @param publicId The ID without dashes.
* @returns The ID with dashes.
*/
export function addDashesToPublicId(publicId: string): string {
if (publicId.includes("-")) {
// this work is already done
return publicId
}
let id = publicId
id = id.slice(0, 1) + "-" + id.slice(1)
id = id.slice(0, 4) + "-" + id.slice(4)
id = id.slice(0, 12) + "-" + id.slice(12)
return id
}
/**
* A fast implementation of deep object cloning.
*
* @param item The item to clone.
* @returns The new item.
*/
export function fastClone<T>(item: T): T {
return structuredClone(item)
}
/**
* Returns if the specified repository ID is a suit.
*
* @param repoId The repository ID.
* @returns If the repository ID points to a suit.
*/
export function isSuit(repoId: string): boolean {
const suitsToTypeMap: Record<string, string> = {}
const unlockablesFiltered = getConfig<readonly Unlockable[]>(
"allunlockables",
false,
).filter((unlockable) => unlockable.Type === "disguise")
for (const u of unlockablesFiltered) {
if (u.Subtype && u.Properties.RepositoryId) {
suitsToTypeMap[u.Properties.RepositoryId] = u.Subtype
}
}
return suitsToTypeMap[repoId]
? suitsToTypeMap[repoId] !== "disguise"
: false
}
type SublocationMap = {
[parentId: string]: string[]
}
export function getSublocations(gameVersion: GameVersion): SublocationMap {
const sublocations: SublocationMap = {}
const locations = getVersionedConfig<PeacockLocationsData>(
"LocationsData",
gameVersion,
false,
)
for (const child of Object.values(locations.children)) {
if (!child.Properties.ParentLocation) continue
sublocations[child.Properties.ParentLocation] ??= []
sublocations[child.Properties.ParentLocation].push(child.Id)
}
return sublocations
}
export function isTrueForEveryElement<Type>(
iter: Iterable<Type>,
test: (elem: Type) => boolean,
): boolean {
for (const element of iter) {
if (!test(element)) {
return false
}
}
return true
}
const SERVER_VERSION_REGEX = /^(?<major>\d+)_(?<minor>\d+)_(?<build>\d+)$/
const RESOURCES_VERSION_REGEX = /^(?<major>\d+)_(?<minor>\d+)$/
export function extractServerVersion(
serverVersion: string | undefined,
): ServerVersion | undefined {
if (!serverVersion) return
const versionParts = SERVER_VERSION_REGEX.exec(serverVersion)
if (versionParts?.groups) {
return {
_Major: parseInt(versionParts.groups.major, 10),
_Minor: parseInt(versionParts.groups.minor, 10),
_Build: parseInt(versionParts.groups.build, 10),
_Revision: 0,
}
}
}
// TODO: use me for validation on resources!!
export function extractResourcesVersion(
resourcesServerVersion: string | undefined,
): ServerVersion | undefined {
if (!resourcesServerVersion) return
const versionParts = RESOURCES_VERSION_REGEX.exec(resourcesServerVersion)
if (versionParts?.groups) {
return {
_Major: parseInt(versionParts.groups.major, 10),
_Minor: parseInt(versionParts.groups.minor, 10),
_Build: 0,
_Revision: 0,
}
}
}
export function parsePageNumber(page: unknown): number {
page ||= 0
if (typeof page === "string") {
page = parseInt(page, 10)
}
assert.equal(typeof page, "number")
page = Math.max(page as number, 0)
return page as number
}