-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathuser.ts
More file actions
1387 lines (1238 loc) · 32.5 KB
/
user.ts
File metadata and controls
1387 lines (1238 loc) · 32.5 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
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 { canFunboxGetPb, checkAndUpdatePb, LbPersonalBests } from "../utils/pb";
import * as db from "../init/db";
import MonkeyError from "../utils/error";
import {
Collection,
ObjectId,
Long,
type UpdateFilter,
type Filter,
} from "mongodb";
import { flattenObjectDeep, isPlainObject, WithObjectId } from "../utils/misc";
import { getCachedConfiguration } from "../init/configuration";
import { getDayOfYear } from "date-fns";
import { UTCDate } from "@date-fns/utc";
import {
AllRewards,
Badge,
CustomTheme,
MonkeyMail,
UserInventory,
UserProfileDetails,
UserQuoteRatings,
UserStreak,
ResultFilters,
UserTag,
User,
CountByYearAndDay,
Friend,
} from "@monkeytype/schemas/users";
import {
Mode,
Mode2,
PersonalBest,
PersonalBests,
} from "@monkeytype/schemas/shared";
import { addImportantLog } from "./logs";
import { Result as ResultType } from "@monkeytype/schemas/results";
import { Configuration } from "@monkeytype/schemas/configuration";
import { isToday, isYesterday } from "@monkeytype/util/date-and-time";
import GeorgeQueue from "../queues/george-queue";
import { aggregateWithAcceptedConnections } from "./connections";
export type DBUserTag = WithObjectId<UserTag>;
export type DBUser = Omit<
User,
| "resultFilterPresets"
| "tags"
| "customThemes"
| "isPremium"
| "allTimeLbs"
| "testActivity"
> & {
_id: ObjectId;
resultFilterPresets?: WithObjectId<ResultFilters>[];
tags?: DBUserTag[];
lbPersonalBests?: LbPersonalBests;
customThemes?: WithObjectId<CustomTheme>[];
autoBanTimestamps?: number[];
inbox?: MonkeyMail[];
ips?: string[];
canReport?: boolean;
nameHistory?: string[];
lastNameChange?: number;
canManageApeKeys?: boolean;
bananas?: number;
testActivity?: CountByYearAndDay;
suspicious?: boolean;
note?: string;
};
const SECONDS_PER_HOUR = 3600;
type Result = Omit<ResultType<Mode>, "_id" | "name">;
export type DBFriend = Friend;
// Export for use in tests
export const getUsersCollection = (): Collection<DBUser> =>
db.collection<DBUser>("users");
export async function addUser(
name: string,
email: string,
uid: string,
): Promise<void> {
const newUserDocument: Partial<DBUser> = {
name,
email,
uid,
addedAt: Date.now(),
personalBests: {
time: {},
words: {},
quote: {},
zen: {},
custom: {},
},
testActivity: {},
};
const result = await getUsersCollection().updateOne(
{ uid },
{ $setOnInsert: newUserDocument },
{ upsert: true },
);
if (result.upsertedCount === 0) {
throw new MonkeyError(409, "User document already exists", "addUser");
}
}
export async function deleteUser(uid: string): Promise<void> {
await getUsersCollection().deleteOne({ uid });
}
export async function resetUser(uid: string): Promise<void> {
await getUsersCollection().updateOne(
{ uid },
{
$set: {
personalBests: {
time: {},
words: {},
quote: {},
zen: {},
custom: {},
},
lbPersonalBests: {
time: {},
},
completedTests: 0,
startedTests: 0,
timeTyping: 0,
lbMemory: {},
bananas: 0,
profileDetails: {
bio: "",
keyboard: "",
socialProfiles: {},
},
favoriteQuotes: {},
customThemes: [],
tags: [],
xp: 0,
streak: {
length: 0,
lastResultTimestamp: 0,
maxLength: 0,
},
testActivity: {},
},
$unset: {
discordAvatar: "",
discordId: "",
lbOptOut: "",
inbox: "",
},
},
);
}
export async function updateName(
uid: string,
name: string,
previousName: string,
): Promise<void> {
if (name === previousName) {
throw new MonkeyError(400, "New name is the same as the old name");
}
if (
name?.toLowerCase() !== previousName?.toLowerCase() &&
!(await isNameAvailable(name, uid))
) {
throw new MonkeyError(409, "Username already taken", name);
}
await getUsersCollection().updateOne(
{ uid },
{
$set: { name, lastNameChange: Date.now() },
$unset: { needsToChangeName: "" },
$push: { nameHistory: previousName },
},
);
}
export async function flagForNameChange(uid: string): Promise<void> {
await getUsersCollection().updateOne(
{ uid },
{ $set: { needsToChangeName: true } },
);
}
export async function clearPb(uid: string): Promise<void> {
await getUsersCollection().updateOne(
{ uid },
{
$set: {
personalBests: {
time: {},
words: {},
quote: {},
zen: {},
custom: {},
},
lbPersonalBests: {
time: {},
},
},
},
);
}
export async function optOutOfLeaderboards(uid: string): Promise<void> {
await getUsersCollection().updateOne(
{ uid },
{
$set: {
lbOptOut: true,
lbPersonalBests: {
time: {},
},
},
},
);
}
export async function updateQuoteRatings(
uid: string,
quoteRatings: UserQuoteRatings,
): Promise<boolean> {
await updateUser(
{ uid },
{ $set: { quoteRatings } },
{ stack: "update quote ratings" },
);
return true;
}
export async function updateEmail(
uid: string,
email: string,
): Promise<boolean> {
await updateUser({ uid }, { $set: { email } }, { stack: "update email" });
return true;
}
export async function getUser(uid: string, stack: string): Promise<DBUser> {
const user = await getUsersCollection().findOne({ uid });
if (!user) throw new MonkeyError(404, "User not found", stack);
return migrateUser(user);
}
/**
* Get user document only containing requested fields
* @param uid user id
* @param stack stack description used in the error
* @param fields list of fields
* @returns partial DBUser only containing requested fields
* @throws MonkeyError if user does not exist
*/
export async function getPartialUser<K extends keyof DBUser>(
uid: string,
stack: string,
fields: K[],
): Promise<Pick<DBUser, K>> {
const projection = new Map(fields.map((it) => [it, 1]));
const partialUser = await getUsersCollection().findOne(
{ uid },
{ projection },
);
if (partialUser === null) throw new MonkeyError(404, "User not found", stack);
if (fields.includes("personalBests" as K)) {
return migrateUser(partialUser);
}
return partialUser;
}
export async function findByName(name: string): Promise<DBUser | undefined> {
const found = await getUsersCollection().findOne(
{ name },
{ collation: { locale: "en", strength: 1 } },
);
return found ?? undefined;
}
export async function isNameAvailable(
name: string,
uid: string,
): Promise<boolean> {
const user = await findByName(name);
// if the user found by name is the same as the user we are checking for, then the name is available
// this means that the user can update the casing of their name without it being taken
return user === undefined || user.uid === uid;
}
export async function getUserByName(
name: string,
stack: string,
): Promise<DBUser> {
const user = await findByName(name);
if (!user) throw new MonkeyError(404, "User not found", stack);
return migrateUser(user);
}
export async function isDiscordIdAvailable(
discordId: string,
): Promise<boolean> {
const user = await getUsersCollection().findOne(
{ discordId },
{ projection: { _id: 1 } },
);
return user === null;
}
export async function addResultFilterPreset(
uid: string,
resultFilter: ResultFilters,
maxFiltersPerUser: number,
): Promise<ObjectId> {
if (maxFiltersPerUser === 0) {
throw new MonkeyError(
409,
"Maximum number of custom filters reached",
"add result filter preset",
);
}
const _id = new ObjectId();
const filter = { uid };
filter[`resultFilterPresets.${maxFiltersPerUser - 1}`] = { $exists: false };
await updateUser(
filter,
{ $push: { resultFilterPresets: { ...resultFilter, _id } } },
{
statusCode: 409,
message: "Maximum number of custom filters reached",
stack: "add result filter preset",
},
);
return _id;
}
export async function removeResultFilterPreset(
uid: string,
_id: string,
): Promise<void> {
const presetId = new ObjectId(_id);
await updateUser(
{ uid, "resultFilterPresets._id": presetId },
{ $pull: { resultFilterPresets: { _id: presetId } } },
{
statusCode: 404,
message: "Custom filter not found",
stack: "remove result filter preset",
},
);
}
export async function addTag(uid: string, name: string): Promise<DBUserTag> {
const toPush = {
_id: new ObjectId(),
name,
personalBests: {
time: {},
words: {},
quote: {},
zen: {},
custom: {},
},
};
await updateUser(
{ uid, "tags.14": { $exists: false } },
{ $push: { tags: toPush } },
{
statusCode: 400,
message: "Maximum number of tags reached",
stack: "add tag",
},
);
return toPush;
}
export async function getTags(uid: string): Promise<DBUserTag[]> {
const user = await getPartialUser(uid, "get tags", ["tags"]);
return user.tags ?? [];
}
export async function editTag(
uid: string,
_id: string,
name: string,
): Promise<void> {
const tagId = new ObjectId(_id);
await updateUser(
{ uid, "tags._id": tagId },
{ $set: { "tags.$.name": name } },
{ statusCode: 404, message: "Tag not found", stack: "edit tag" },
);
}
export async function removeTag(uid: string, _id: string): Promise<void> {
const tagId = new ObjectId(_id);
await updateUser(
{ uid, "tags._id": tagId },
{ $pull: { tags: { _id: tagId } } },
{ statusCode: 404, message: "Tag not found", stack: "remove tag" },
);
}
export async function removeTagPb(uid: string, _id: string): Promise<void> {
const tagId = new ObjectId(_id);
await updateUser(
{ uid, "tags._id": tagId },
{
$set: {
"tags.$.personalBests": {
time: {},
words: {},
quote: {},
zen: {},
custom: {},
},
},
},
{ statusCode: 404, message: "Tag not found", stack: "remove tag pb" },
);
}
export async function updateLbMemory(
uid: string,
mode: Mode,
mode2: Mode2<Mode>,
language: string,
rank: number,
): Promise<void> {
const partialUpdate = {};
partialUpdate[`lbMemory.${mode}.${mode2}.${language}`] = rank;
await updateUser(
{ uid },
{ $set: partialUpdate },
{ stack: "update lb memory" },
);
}
export async function checkIfPb(
uid: string,
user: Pick<DBUser, "personalBests" | "lbPersonalBests">,
result: Result,
): Promise<boolean> {
const { mode } = result;
if (!canFunboxGetPb(result)) return false;
if (
"stopOnLetter" in result &&
result.stopOnLetter === true &&
result.acc < 100
) {
return false;
}
if (mode === "quote") {
return false;
}
user.personalBests ??= {
time: {},
custom: {},
quote: {},
words: {},
zen: {},
};
user.lbPersonalBests ??= {
time: {},
};
const pb = checkAndUpdatePb(user.personalBests, user.lbPersonalBests, result);
if (!pb.isPb) return false;
await getUsersCollection().updateOne(
{ uid },
{ $set: { personalBests: pb.personalBests } },
);
if (pb.lbPersonalBests) {
await getUsersCollection().updateOne(
{ uid },
{ $set: { lbPersonalBests: pb.lbPersonalBests } },
);
}
return true;
}
export async function checkIfTagPb(
uid: string,
user: Pick<DBUser, "tags">,
result: Result,
): Promise<string[]> {
if (user.tags === undefined || user.tags.length === 0) {
return [];
}
const { mode, tags: resultTags } = result;
if (!canFunboxGetPb(result)) return [];
if (
"stopOnLetter" in result &&
result.stopOnLetter === true &&
result.acc < 100
) {
return [];
}
if (mode === "quote") {
return [];
}
const tagsToCheck: DBUserTag[] = [];
user.tags.forEach((userTag) => {
for (const resultTag of resultTags ?? []) {
if (resultTag === userTag._id.toHexString()) {
tagsToCheck.push(userTag);
}
}
});
const ret: string[] = [];
for (const tag of tagsToCheck) {
tag.personalBests ??= {
time: {},
words: {},
quote: {},
zen: {},
custom: {},
};
const tagpb = checkAndUpdatePb(tag.personalBests, undefined, result);
if (tagpb.isPb) {
ret.push(tag._id.toHexString());
await getUsersCollection().updateOne(
{ uid, "tags._id": new ObjectId(tag._id) },
{ $set: { "tags.$.personalBests": tagpb.personalBests } },
);
}
}
return ret;
}
export async function resetPb(uid: string): Promise<void> {
await updateUser(
{ uid },
{
$set: {
personalBests: {
time: {},
words: {},
quote: {},
zen: {},
custom: {},
},
},
},
{ stack: "reset pb" },
);
}
export async function updateLastHashes(
uid: string,
lastHashes: string[],
): Promise<void> {
await getUsersCollection().updateOne(
{ uid },
{
$set: {
lastResultHashes: lastHashes,
},
$unset: {
lastReultHashes: 1,
},
},
);
}
export async function updateTypingStats(
uid: string,
restartCount: number,
timeTyping: number,
): Promise<void> {
await getUsersCollection().updateOne(
{ uid },
{
$inc: {
startedTests: restartCount + 1,
completedTests: 1,
timeTyping,
},
},
);
}
export async function linkDiscord(
uid: string,
discordId: string,
discordAvatar?: string,
): Promise<void> {
const updates: Partial<DBUser> = { discordId };
if (discordAvatar !== undefined && discordAvatar !== null) {
updates.discordAvatar = discordAvatar;
}
await updateUser({ uid }, { $set: updates }, { stack: "link discord" });
}
export async function unlinkDiscord(uid: string): Promise<void> {
await updateUser(
{ uid },
{ $unset: { discordId: "", discordAvatar: "" } },
{ stack: "unlink discord" },
);
}
export async function incrementBananas(
uid: string,
wpm: number,
): Promise<void> {
//don't throw on missing user
await getUsersCollection().updateOne(
{
uid,
"personalBests.time.60": { $exists: true, $not: { $size: 0 } },
$expr: {
// wpm needs to be >= 75% of the the highest time 60 PB
$gte: [
wpm,
{
$multiply: [
//highest wpm with 0.75
{
$reduce: {
//find highest wpm from time 60 PBs
input: "$personalBests.time.60",
initialValue: 0,
in: {
$cond: [
{ $gte: ["$$this.wpm", "$$value"] },
"$$this.wpm",
"$$value",
],
},
},
},
0.75,
],
},
],
},
},
{ $inc: { bananas: 1 } },
);
}
export async function incrementXp(uid: string, xp: number): Promise<void> {
if (isNaN(xp)) xp = 0;
await getUsersCollection().updateOne({ uid }, { $inc: { xp: new Long(xp) } });
}
export async function incrementTestActivity(
user: DBUser,
timestamp: number,
): Promise<void> {
if (user.testActivity === undefined) {
//migration script did not run yet
return;
}
const date = new UTCDate(timestamp);
const dayOfYear = getDayOfYear(date);
const year = date.getFullYear();
if (user.testActivity[year] === undefined) {
await getUsersCollection().updateOne(
{ uid: user.uid },
{ $set: { [`testActivity.${date.getFullYear()}`]: [] } },
);
}
await getUsersCollection().updateOne(
{ uid: user.uid },
{ $inc: { [`testActivity.${date.getFullYear()}.${dayOfYear - 1}`]: 1 } },
);
}
export async function addTheme(
uid: string,
{ name, colors }: Omit<CustomTheme, "_id">,
): Promise<{ _id: ObjectId; name: string }> {
const _id = new ObjectId();
await updateUser(
{ uid, "customThemes.19": { $exists: false } },
{
$push: {
customThemes: {
_id,
name: name,
colors: colors,
},
},
},
{
statusCode: 409,
message: "Maximum number of custom themes reached",
stack: "add theme",
},
);
return {
_id,
name,
};
}
export async function removeTheme(uid: string, id: string): Promise<void> {
const themeId = new ObjectId(id);
await updateUser(
{ uid, "customThemes._id": themeId },
{ $pull: { customThemes: { _id: themeId } } },
{
statusCode: 404,
message: "Custom theme not found",
stack: "remove theme",
},
);
}
export async function editTheme(
uid: string,
id: string,
{ name, colors }: Omit<CustomTheme, "_id">,
): Promise<void> {
const themeId = new ObjectId(id);
await updateUser(
{ uid, "customThemes._id": themeId },
{
$set: {
"customThemes.$.name": name,
"customThemes.$.colors": colors,
},
},
{ statusCode: 404, message: "Custom theme not found", stack: "edit theme" },
);
}
export type DBCustomTheme = WithObjectId<CustomTheme>;
export async function getThemes(uid: string): Promise<DBCustomTheme[]> {
const user = await getPartialUser(uid, "get themes", ["customThemes"]);
return user.customThemes ?? [];
}
export async function getPersonalBests(
uid: string,
mode: string,
mode2?: string,
): Promise<PersonalBest> {
const user = await getPartialUser(uid, "get personal bests", [
"personalBests",
]);
if (mode2 !== undefined) {
// oxlint-disable-next-line no-unsafe-member-access
return user.personalBests?.[mode]?.[mode2] as PersonalBest;
}
return user.personalBests?.[mode] as PersonalBest;
}
export async function getStats(
uid: string,
): Promise<Pick<DBUser, "startedTests" | "completedTests" | "timeTyping">> {
const user = await getPartialUser(uid, "get stats", [
"startedTests",
"completedTests",
"timeTyping",
]);
return user;
}
export async function getFavoriteQuotes(
uid: string,
): Promise<NonNullable<DBUser["favoriteQuotes"]>> {
const user = await getPartialUser(uid, "get favorite quotes", [
"favoriteQuotes",
]);
return user.favoriteQuotes ?? {};
}
export async function addFavoriteQuote(
uid: string,
language: string,
quoteId: string,
maxQuotes: number,
): Promise<void> {
await updateUser(
{
uid,
$expr: {
//total amount of quotes need to be lower than maxQuotes
$lt: [
{
$reduce: {
input: { $objectToArray: "$favoriteQuotes" },
initialValue: 0,
in: { $add: ["$$value", { $size: "$$this.v" }] },
},
},
maxQuotes,
],
},
},
{
$addToSet: {
//ensure quoteId is unique in the array
[`favoriteQuotes.${language}`]: quoteId,
},
},
{
statusCode: 409,
message: "Maximum number of favorite quotes reached",
stack: "add favorite quote",
},
);
}
export async function removeFavoriteQuote(
uid: string,
language: string,
quoteId: string,
): Promise<void> {
await updateUser(
{ uid },
{ $pull: { [`favoriteQuotes.${language}`]: quoteId } },
{ stack: "remove favorite quote" },
);
}
export async function recordAutoBanEvent(
uid: string,
maxCount: number,
maxHours: number,
): Promise<boolean> {
const user = await getPartialUser(uid, "record auto ban event", [
"banned",
"autoBanTimestamps",
"discordId",
]);
let ret = false;
if (user.banned) return ret;
const autoBanTimestamps = user.autoBanTimestamps ?? [];
const now = Date.now();
//only keep events within the last maxHours
const recentAutoBanTimestamps = autoBanTimestamps.filter(
(timestamp) => timestamp >= now - maxHours * SECONDS_PER_HOUR * 1000,
);
//push new event
recentAutoBanTimestamps.push(now);
//update user, ban if needed
const updateObj: Partial<DBUser> = {
autoBanTimestamps: recentAutoBanTimestamps,
};
let banningUser = false;
if (recentAutoBanTimestamps.length > maxCount) {
updateObj.banned = true;
banningUser = true;
ret = true;
}
await getUsersCollection().updateOne({ uid }, { $set: updateObj });
void addImportantLog(
"user_auto_banned",
{ autoBanTimestamps, banningUser },
uid,
);
if (banningUser) {
const discordIdIsValid =
user.discordId !== undefined && user.discordId !== "";
if (discordIdIsValid) {
await GeorgeQueue.userBanned(user.discordId as string, true);
}
}
return ret;
}
export async function updateProfile(
uid: string,
profileDetailUpdates: Partial<UserProfileDetails>,
inventory?: UserInventory,
): Promise<void> {
let profileUpdates = flattenObjectDeep(
Object.fromEntries(
Object.entries(profileDetailUpdates).filter(
([_, value]) =>
value !== undefined &&
!(isPlainObject(value) && Object.keys(value).length === 0),
),
),
"profileDetails",
);
const updates = {
$set: {
...profileUpdates,
inventory,
},
};
if (inventory === undefined) delete updates.$set.inventory;
await getUsersCollection().updateOne(
{
uid,
},
updates,
);
}
export async function getInbox(
uid: string,
): Promise<NonNullable<DBUser["inbox"]>> {
const user = await getPartialUser(uid, "get inbox", ["inbox"]);
return user.inbox ?? [];
}
type AddToInboxBulkEntry = {
uid: string;
mail: MonkeyMail[];
};
export async function addToInboxBulk(
entries: AddToInboxBulkEntry[],
inboxConfig: Configuration["users"]["inbox"],
): Promise<void> {
const { enabled, maxMail } = inboxConfig;
if (!enabled) {
return;
}
const bulk = getUsersCollection().initializeUnorderedBulkOp();
entries.forEach((entry) => {
bulk.find({ uid: entry.uid }).updateOne({
$push: {
inbox: {
$each: entry.mail,
$position: 0, // Prepends to the inbox
$slice: maxMail, // Keeps inbox size to maxInboxSize, maxMail the oldest
},
},
});
});
await bulk.execute();
}
export async function addToInbox(
uid: string,
mail: MonkeyMail[],
inboxConfig: Configuration["users"]["inbox"],
): Promise<void> {
const { enabled, maxMail } = inboxConfig;