-
-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathdatabaseHandler.ts
More file actions
441 lines (387 loc) · 12.8 KB
/
Copy pathdatabaseHandler.ts
File metadata and controls
441 lines (387 loc) · 12.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
/*
* 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 { join } from "path"
import type { ContractSession, GameVersion, UserProfile } from "./types/types"
import { deserializeSession, serializeSession } from "./contracts/sessions"
import { castUserProfile } from "./utils"
import { log, LogLevel } from "./loggingInterop"
import { mkdir, readdir, unlink } from "fs/promises"
import type * as nodeFs from "node:fs/promises"
import * as atomically from "atomically"
import { existsSync } from "fs"
// unlink, mkdir, readdir from node:fs/promises
type NodeUnlinkMkdirReaddir = Pick<
typeof nodeFs,
"unlink" | "mkdir" | "readdir"
>
type AtomicReadWrite = Pick<typeof atomically, "readFile" | "writeFile">
// custom exists function because node doesn't have an async version of existsSync
type ExistsPromise = {
exists: (path: string) => Promise<boolean>
}
/**
* The fs implementation that this system uses.
*/
export type DataStorageFs = NodeUnlinkMkdirReaddir &
ExistsPromise &
AtomicReadWrite
/**
* Handles the dispatching of user data in a way that avoids FS operations unless absolutely needed.
*/
class AsyncUserDataGuard {
/** @internal */
readonly userData: Map<string, UserProfile> = new Map()
/** @internal */
readonly dirtyProfiles: Set<string> = new Set()
/**
* Internal list of background tasks that have been scheduled.
* The key is the versioned user ID.
* @internal
*/
readonly tasks: Map<string, NodeJS.Timeout> = new Map()
/** If true, none of the background tasks will attempt to write. */
#paused = false
/**
* Get the fs implementation to use for file read/writes.
* Mainly for test purposes, but could also be used by plugins to make it use a real database.
*/
getFs(): DataStorageFs {
return {
writeFile: atomically.writeFile,
readFile: atomically.readFile,
unlink,
mkdir,
readdir,
exists(path) {
// node's fs doesn't have a promise version of exists
return Promise.resolve(existsSync(path))
},
}
}
/**
* Get a loaded user's profile.
* @param id The target user ID.
* @returns The profile, or undefined if they're not loaded.
* Profiles are loaded when they perform the auth handshake via the game.
*/
getProfile(id: string): UserProfile | undefined {
return this.userData.get(id)
}
addLoadedProfile(id: string, profile: UserProfile): void {
if (!this.userData.has(id) && !this.tasks.has(id)) {
const interval = setInterval(() => {
if (!this.dirtyProfiles.has(id) || this.#paused) {
return
}
this.save(id)
}, 3000)
this.tasks.set(id, interval.unref())
}
this.userData.set(id, profile)
// just in case
this.dirtyProfiles.delete(id)
}
/**
* Saves any modifications to a given profile, called by a background scheduled task.
* @param id The user ID.
*/
save(id: string) {
this.dirtyProfiles.delete(id)
this.write(id)
.then(() => undefined)
.catch((e) => {
log(LogLevel.ERROR, `Failed to write user profile ${id}: ${e}`)
})
}
markDirty(id: string): void {
this.dirtyProfiles.add(id)
}
/** @internal */
async write(versionedId: string): Promise<void> {
let path
const [id, gameVersion] = versionedId.split(".")
if (["scpc", "h1", "h2"].includes(gameVersion)) {
path = join("userdata", gameVersion, "users", `${id}.json`)
} else {
path = join("userdata", "users", `${id}.json`)
}
await this.getFs().writeFile(
path,
JSON.stringify(this.getProfile(versionedId)),
)
}
/**
* Immediately write all loaded profiles to the disk, even if no changes are pending.
*/
async forceFlush() {
const taskKeys = this.tasks.keys()
this.#paused = true
for (const id of taskKeys) {
this.dirtyProfiles.delete(id)
await this.write(id)
}
this.#paused = false
}
/**
* Unload all profiles without saving.
*/
unloadAll() {
for (const id of this.tasks.keys()) {
clearInterval(this.tasks.get(id))
this.dirtyProfiles.delete(id)
this.userData.delete(id)
}
}
}
/**
* If you are touching this, you better know what you're doing.
*/
export const asyncGuard = new AsyncUserDataGuard()
/**
* Gets a user's profile data.
*
* @param userId The user's ID.
* @param gameVersion The game's version.
* @returns The user's profile, OR UNDEFINED if not loaded.
*/
export function getUserData(
userId: string,
gameVersion: GameVersion,
): UserProfile {
// TODO: consumers could have undefined returned - this function needs undefined
// as part of it's signature, but that requires a lot of changes.
const data = asyncGuard.getProfile(`${userId}.${gameVersion}`)!
// NOTE: ProfileLevel always starts at 1
if (data?.Extensions?.progression?.PlayerProfileXP?.ProfileLevel === 0) {
data.Extensions.progression.PlayerProfileXP.ProfileLevel = 1
}
return data
}
/**
* Attempts to load a user's profile if it hasn't been loaded yet.
*
* @param userId The user's ID.
* @param gameVersion The game's version.
*/
export async function cheapLoadUserData(
userId: string,
gameVersion: GameVersion,
): Promise<void> {
if (!userId || !gameVersion) {
return
}
const userProfile = asyncGuard.getProfile(`${userId}.${gameVersion}`)
if (userProfile) {
return
}
try {
await loadUserData(userId, gameVersion)
} catch (e) {
log(LogLevel.DEBUG, "Unable to load profile information.")
log(LogLevel.DEBUG, e)
}
}
/**
* Loads a user's profile data.
*
* @param userId The user's ID.
* @param gameVersion The game's version.
* @returns The raw JSON data.
*/
export async function loadUserData(
userId: string,
gameVersion: GameVersion,
): Promise<UserProfile> {
let path
if (["scpc", "h1", "h2"].includes(gameVersion)) {
path = join("userdata", gameVersion, "users", `${userId}.json`)
} else {
path = join("userdata", "users", `${userId}.json`)
}
const userProfile = castUserProfile(
JSON.parse((await asyncGuard.getFs().readFile(path)).toString()),
gameVersion,
path,
)
asyncGuard.addLoadedProfile(`${userId}.${gameVersion}`, userProfile)
return userProfile
}
/**
* Marks a user's profile as dirty.
* Dirty profiles are automatically saved by a background thread every 3 seconds.
*
* @param userId The user's ID.
* @param gameVersion The game's version.
*/
export function writeUserData(userId: string, gameVersion: GameVersion): void {
asyncGuard.markDirty(`${userId}.${gameVersion}`)
}
/**
* Writes a previously-non existent user profile.
* This is used for creating new profiles.
*
* @param userId The user's ID.
* @param userProfile
* @param gameVersion The game's version.
*/
export function writeNewUserData(
userId: string,
userProfile: UserProfile,
gameVersion: GameVersion,
): void {
asyncGuard.addLoadedProfile(`${userId}.${gameVersion}`, userProfile)
asyncGuard.markDirty(`${userId}.${gameVersion}`)
}
/**
* Gets the value of an external provider binding.
*
* @param userId The user's ID.
* @param externalFolder The folder where this provider's users are stored.
* @param gameVersion The game's version.
*/
export async function getExternalUserData(
userId: string,
externalFolder: string,
gameVersion: GameVersion,
): Promise<string> {
const fs = asyncGuard.getFs()
if (["scpc", "h1", "h2"].includes(gameVersion)) {
return (
await fs.readFile(
join("userdata", gameVersion, externalFolder, `${userId}.json`),
)
).toString()
}
return (
await fs.readFile(join("userdata", externalFolder, `${userId}.json`))
).toString()
}
/**
* Writes the value of an external provider binding.
*
* @param userId The user's ID.
* @param externalFolder The folder where this provider's users are stored.
* @param userData The data to write to the binding.
* @param gameVersion The game's version.
*/
export async function writeExternalUserData(
userId: string,
externalFolder: string,
userData: string,
gameVersion: GameVersion,
): Promise<void> {
const fs = asyncGuard.getFs()
if (["scpc", "h1", "h2"].includes(gameVersion)) {
return await fs.writeFile(
join("userdata", gameVersion, externalFolder, `${userId}.json`),
userData,
)
}
return await fs.writeFile(
join("userdata", externalFolder, `${userId}.json`),
userData,
)
}
/**
* Reads a contract session from the contractSessions folder.
*
* @param identifier The identifier for the saved session, in the format of token_sessionID.
* @returns The contract session.
*/
export async function getContractSession(
identifier: string,
): Promise<ContractSession> {
const fs = asyncGuard.getFs()
const files = await fs.readdir("contractSessions")
const filtered = files.filter((fn) => fn.endsWith(`_${identifier}.json`))
if (filtered.length === 0) {
throw new Error(`No session saved with identifier ${identifier}`)
}
// The filtered files have the same identifier, they are just stored at different slots
// So we can read any of them, and it will be the same.
return deserializeSession(
JSON.parse(
(
await fs.readFile(join("contractSessions", filtered[0]))
).toString(),
),
)
}
/**
* Writes a contract session to the contractsSessions folder.
*
* @param identifier The identifier for the saved session, in the format of slot_token_sessionID.
* @param session The contract session.
*/
export async function writeContractSession(
identifier: string,
session: ContractSession,
): Promise<void> {
const fs = asyncGuard.getFs()
return await fs.writeFile(
join("contractSessions", `${identifier}.json`),
JSON.stringify(serializeSession(session)),
)
}
/**
* Deletes a saved contract session from the contractsSessions folder.
*
* @param fileName The identifier for the saved session, in the format of slot_token_sessionID.
* @throws ENOENT if the file is not found.
*/
export async function deleteContractSession(fileName: string): Promise<void> {
const fs = asyncGuard.getFs()
return await fs.unlink(join("contractSessions", `${fileName}.json`))
}
/**
* Sets up the required file structure for the server.
*
* @param joinFunc The path join function to use, defaulting to Node's. You may need to specify it if working in a VFS.
*/
export async function setupFileStructure(joinFunc = join) {
const fs = asyncGuard.getFs()
for (const dir of [
"contractSessions",
"plugins",
"userdata",
"contracts",
joinFunc("userdata", "epicids"),
joinFunc("userdata", "steamids"),
joinFunc("userdata", "appleids"),
joinFunc("userdata", "users"),
joinFunc("userdata", "h1", "steamids"),
joinFunc("userdata", "h1", "epicids"),
joinFunc("userdata", "h1", "users"),
joinFunc("userdata", "h2", "steamids"),
joinFunc("userdata", "h2", "users"),
joinFunc("userdata", "scpc", "users"),
joinFunc("userdata", "scpc", "steamids"),
joinFunc("images", "actors"),
joinFunc("images", "contracts"),
joinFunc("images", "contracts", "elusive"),
joinFunc("images", "contracts", "escalation"),
joinFunc("images", "contracts", "featured"),
joinFunc("images", "unlockables_override"),
]) {
if (await fs.exists(dir)) {
continue
}
log(LogLevel.DEBUG, `Creating missing directory ${dir}`)
await fs.mkdir(dir, { recursive: true })
}
}