-
Notifications
You must be signed in to change notification settings - Fork 4k
/
group.js
1638 lines (1409 loc) · 53.8 KB
/
group.js
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 moment from 'moment';
import mongoose from 'mongoose';
import {
model as User,
nameFields,
} from './user';
import shared from '../../common';
import _ from 'lodash';
import { model as Challenge} from './challenge';
import {
chatModel as Chat,
setUserStyles,
messageDefaults,
} from './message';
import * as Tasks from './task';
import validator from 'validator';
import { removeFromArray } from '../libs/collectionManipulators';
import payments from '../libs/payments/payments';
import {
groupChatReceivedWebhook,
questActivityWebhook,
} from '../libs/webhook';
import {
InternalServerError,
BadRequest,
NotAuthorized,
} from '../libs/errors';
import baseModel from '../libs/baseModel';
import { sendTxn as sendTxnEmail } from '../libs/email';
import nconf from 'nconf';
import { sendNotification as sendPushNotification } from '../libs/pushNotifications';
import {
syncableAttrs,
} from '../libs/taskManager';
import {
schema as SubscriptionPlanSchema,
} from './subscriptionPlan';
import amazonPayments from '../libs/payments/amazon';
import stripePayments from '../libs/payments/stripe';
import { getGroupChat, translateMessage } from '../libs/chat/group-chat';
import { model as UserNotification } from './userNotification';
import { sendChatPushNotifications } from '../libs/chat';
const questScrolls = shared.content.quests;
const questSeriesAchievements = shared.content.questSeriesAchievements;
const Schema = mongoose.Schema;
export const INVITES_LIMIT = 100; // must not be greater than MAX_EMAIL_INVITES_BY_USER
export const TAVERN_ID = shared.TAVERN_ID;
const NO_CHAT_NOTIFICATIONS = [TAVERN_ID];
const LARGE_GROUP_COUNT_MESSAGE_CUTOFF = shared.constants.LARGE_GROUP_COUNT_MESSAGE_CUTOFF;
const MAX_SUMMARY_SIZE_FOR_GUILDS = shared.constants.MAX_SUMMARY_SIZE_FOR_GUILDS;
const GUILDS_PER_PAGE = shared.constants.GUILDS_PER_PAGE;
const CHAT_FLAG_LIMIT_FOR_HIDING = shared.constants.CHAT_FLAG_LIMIT_FOR_HIDING;
const CRON_SAFE_MODE = nconf.get('CRON_SAFE_MODE') === 'true';
const CRON_SEMI_SAFE_MODE = nconf.get('CRON_SEMI_SAFE_MODE') === 'true';
const MAX_UPDATE_RETRIES = 5;
/*
# Spam constants to limit people from sending too many messages too quickly
# SPAM_MESSAGE_LIMIT - The amount of messages that can be sent in a time window
# SPAM_WINDOW_LENGTH - The window length for spam protection in milliseconds
# SPAM_MIN_EXEMPT_CONTRIB_LEVEL - Anyone at or above this level is exempt
*/
export const SPAM_MESSAGE_LIMIT = 2;
export const SPAM_WINDOW_LENGTH = 60000; // 1 minute
export const SPAM_MIN_EXEMPT_CONTRIB_LEVEL = 4;
export const MAX_CHAT_COUNT = 200;
export const MAX_SUBBED_GROUP_CHAT_COUNT = 400;
export let schema = new Schema({
name: {$type: String, required: true},
summary: {$type: String, maxlength: MAX_SUMMARY_SIZE_FOR_GUILDS},
description: String,
leader: {$type: String, ref: 'User', validate: [v => validator.isUUID(v), 'Invalid uuid.'], required: true},
type: {$type: String, enum: ['guild', 'party'], required: true},
privacy: {$type: String, enum: ['private', 'public'], default: 'private', required: true},
chat: Array, // Used for backward compatibility, but messages aren't stored here
leaderOnly: { // restrict group actions to leader (members can't do them)
challenges: {$type: Boolean, default: false, required: true},
// invites: {$type: Boolean, default: false, required: true},
// Some group plans prevent members from getting gems
getGems: {$type: Boolean, default: false},
},
memberCount: {$type: Number, default: 1},
challengeCount: {$type: Number, default: 0},
balance: {$type: Number, default: 0},
logo: String,
leaderMessage: String,
quest: {
key: String,
active: {$type: Boolean, default: false},
leader: {$type: String, ref: 'User'},
progress: {
hp: Number,
collect: {$type: Schema.Types.Mixed, default: () => {
return {};
}}, // {feather: 5, ingot: 3}
rage: Number, // limit break / "energy stored in shell", for explosion-attacks
},
// Shows boolean for each party-member who has accepted the quest. Eg {UUID: true, UUID: false}. Once all users click
// 'Accept', the quest begins. If a false user waits too long, probably a good sign to prod them or boot them.
// TODO when booting user, remove from .joined and check again if we can now start the quest
members: {$type: Schema.Types.Mixed, default: () => {
return {};
}},
extra: {$type: Schema.Types.Mixed, default: () => {
return {};
}},
},
tasksOrder: {
habits: [{$type: String, ref: 'Task'}],
dailys: [{$type: String, ref: 'Task'}],
todos: [{$type: String, ref: 'Task'}],
rewards: [{$type: String, ref: 'Task'}],
},
purchased: {
plan: {$type: SubscriptionPlanSchema, default: () => {
return {};
}},
},
managers: {$type: Schema.Types.Mixed, default: () => {
return {};
}},
categories: [{
slug: {$type: String},
name: {$type: String},
}],
}, {
strict: true,
minimize: false, // So empty objects are returned
typeKey: '$type', // So that we can use fields named `type`
});
schema.plugin(baseModel, {
noSet: ['_id', 'balance', 'quest', 'memberCount', 'chat', 'challengeCount', 'tasksOrder', 'purchased', 'managers'],
private: ['purchased.plan'],
toJSONTransform (plainObj, originalDoc) {
if (plainObj.purchased) plainObj.purchased.active = originalDoc.isSubscribed();
},
});
schema.pre('init', function ensureSummaryIsFetched (group) {
// The Vue website makes the summary be mandatory for all new groups, but the
// Angular website did not, and the API does not yet for backwards-compatibilty.
// When any guild without a summary is fetched from the database, this code
// supplies the name as the summary. This can be removed when all guilds have
// a summary and the API makes it mandatory (a breaking change!)
// NOTE: the Tavern and parties do NOT need summaries so ensure they don't break
// if we remove this code.
if (!group.summary) {
group.summary = group.name ? group.name.substring(0, MAX_SUMMARY_SIZE_FOR_GUILDS) : ' ';
}
});
// A list of additional fields that cannot be updated (but can be set on creation)
let noUpdate = ['privacy', 'type'];
schema.statics.sanitizeUpdate = function sanitizeUpdate (updateObj) {
return this.sanitize(updateObj, noUpdate);
};
// Basic fields to fetch for populating a group info
export let basicFields = 'name type privacy leader summary categories';
schema.pre('remove', true, async function preRemoveGroup (next, done) {
next();
try {
await this.removeGroupInvitations();
done();
} catch (err) {
done(err);
}
});
// return clean updates for each user in a party without resetting their progress
function _cleanQuestParty (merge) {
let updates = {
$set: {
'party.quest.key': null,
'party.quest.completed': null,
'party.quest.RSVPNeeded': false,
},
};
if (merge) _.merge(updates, merge);
return updates;
}
// return a clean user.quest of a particular user while keeping his progress
function _cleanQuestUser (userProgress) {
if (!userProgress) {
userProgress = {
up: 0,
down: 0,
collect: {},
collectedItems: 0,
};
} else {
userProgress = userProgress.toObject();
}
let clean = {
key: null,
progress: userProgress,
completed: null,
RSVPNeeded: false,
};
return clean;
}
schema.statics.getGroup = async function getGroup (options = {}) {
let {user, groupId, fields, optionalMembership = false, populateLeader = false, requireMembership = false} = options;
let query;
let isUserParty = groupId === 'party' || user.party._id === groupId;
let isUserGuild = user.guilds.indexOf(groupId) !== -1;
let isTavern = ['habitrpg', TAVERN_ID].indexOf(groupId) !== -1;
// When requireMembership is true check that user is member even in public guild
if (requireMembership && !isUserParty && !isUserGuild && !isTavern) {
return null;
}
// When optionalMembership is true it's not required for the user to be a member of the group
if (isUserParty) {
query = {type: 'party', _id: user.party._id};
} else if (isTavern) {
query = {_id: TAVERN_ID};
} else if (optionalMembership === true) {
query = {_id: groupId};
} else if (isUserGuild) {
query = {type: 'guild', _id: groupId};
} else {
query = {type: 'guild', privacy: 'public', _id: groupId};
}
let mQuery = this.findOne(query);
if (fields) mQuery.select(fields);
if (populateLeader === true) mQuery.populate('leader', nameFields);
let group = await mQuery.exec();
if (!group) {
if (groupId === user.party._id) {
// reset party object to default state
user.party = {};
} else {
removeFromArray(user.guilds, groupId);
}
await user.save();
}
return group;
};
export const VALID_QUERY_TYPES = ['party', 'guilds', 'privateGuilds', 'publicGuilds', 'tavern'];
schema.statics.getGroups = async function getGroups (options = {}) {
let {
user, types, groupFields = basicFields,
sort = '-memberCount', populateLeader = false,
paginate = false, page = 0, // optional pagination for public guilds
filters = {},
} = options;
let queries = [];
// Throw error if an invalid type is supplied
let areValidTypes = types.every(type => VALID_QUERY_TYPES.indexOf(type) !== -1);
if (!areValidTypes) throw new BadRequest(shared.i18n.t('groupTypesRequired'));
types.forEach(type => {
switch (type) {
case 'party': {
queries.push(this.getGroup({user, groupId: 'party', fields: groupFields, populateLeader}));
break;
}
case 'guilds': {
let query = {
type: 'guild',
_id: {$in: user.guilds},
};
_.assign(query, filters);
let userGuildsQuery = this.find(query).select(groupFields);
if (populateLeader === true) userGuildsQuery.populate('leader', nameFields);
userGuildsQuery.sort(sort).exec();
queries.push(userGuildsQuery);
break;
}
case 'privateGuilds': {
let query = {
type: 'guild',
privacy: 'private',
_id: {$in: user.guilds},
};
_.assign(query, filters);
let privateGuildsQuery = this.find(query).select(groupFields);
if (populateLeader === true) privateGuildsQuery.populate('leader', nameFields);
privateGuildsQuery.sort(sort).exec();
queries.push(privateGuildsQuery);
break;
}
// NOTE: when returning publicGuilds we use `.lean()` so all mongoose methods won't be available.
// Docs are going to be plain javascript objects
case 'publicGuilds': {
let query = {
type: 'guild',
privacy: 'public',
};
_.assign(query, filters);
let publicGuildsQuery = this.find(query).select(groupFields);
if (populateLeader === true) publicGuildsQuery.populate('leader', nameFields);
if (paginate === true) publicGuildsQuery.limit(GUILDS_PER_PAGE).skip(page * GUILDS_PER_PAGE);
publicGuildsQuery.sort(sort).lean().exec();
queries.push(publicGuildsQuery);
break;
}
case 'tavern': {
if (types.indexOf('publicGuilds') === -1) {
queries.push(this.getGroup({user, groupId: TAVERN_ID, fields: groupFields}));
}
break;
}
}
});
let groupsArray = _.reduce(await Promise.all(queries), (previousValue, currentValue) => {
if (_.isEmpty(currentValue)) return previousValue; // don't add anything to the results if the query returned null or an empty array
return previousValue.concat(Array.isArray(currentValue) ? currentValue : [currentValue]); // otherwise concat the new results to the previousValue
}, []);
return groupsArray;
};
// When converting to json remove chat messages with more than 1 flag and remove all flags info
// unless the user is an admin or said chat is posted by that user
// Not putting into toJSON because there we can't access user
// It also removes the _meta field that can be stored inside a chat message
schema.statics.toJSONCleanChat = async function groupToJSONCleanChat (group, user) {
// @TODO: Adding this here for support the old chat, but we should depreciate accessing chat like this
// Also only return chat if requested, eventually we don't want to return chat here
if (group && group.chat) {
await getGroupChat(group);
}
const groupToJson = group.toJSON();
const userLang = user.preferences.language;
groupToJson.chat = groupToJson.chat
.map(chatMsg => {
// Translate system messages
if (!_.isEmpty(chatMsg.info)) {
chatMsg.text = translateMessage(userLang, chatMsg.info);
}
// Convert to timestamps because Android expects it
// old chats are saved with a numeric timestamp
// new chats use `Date` which then has to be converted to the numeric timestamp
if (chatMsg.timestamp && chatMsg.timestamp.getTime) {
chatMsg.timestamp = chatMsg.timestamp.getTime();
}
if (!user.contributor.admin) {
// Flags are hidden to non admins
chatMsg.flags = {};
if (chatMsg._meta) chatMsg._meta = undefined;
// Messages with too many flags are hidden to non-admins and non-authors
if (user._id !== chatMsg.uuid && chatMsg.flagCount >= CHAT_FLAG_LIMIT_FOR_HIDING) return undefined;
}
return chatMsg;
})
// Used to filter for undefined chat messages that should not be shown to non-admins
.filter(chatMsg => chatMsg !== undefined);
return groupToJson;
};
function getInviteError (uuids, emails, usernames) {
const uuidsIsArray = Array.isArray(uuids);
const emailsIsArray = Array.isArray(emails);
const usernamesIsArray = Array.isArray(usernames);
const emptyEmails = emailsIsArray && emails.length < 1;
const emptyUuids = uuidsIsArray && uuids.length < 1;
const emptyUsernames = usernamesIsArray && usernames.length < 1;
let errorString;
if (!uuids && !emails && !usernames) {
errorString = 'canOnlyInviteEmailUuid';
} else if (uuids && !uuidsIsArray) {
errorString = 'uuidsMustBeAnArray';
} else if (emails && !emailsIsArray) {
errorString = 'emailsMustBeAnArray';
} else if (usernames && !usernamesIsArray) {
errorString = 'usernamesMustBeAnArray';
} else if ((!emails || emptyEmails) && (!uuids || emptyUuids) && (!usernames || emptyUsernames)) {
errorString = 'inviteMustNotBeEmpty';
}
return errorString;
}
function getInviteCount (uuids, emails) {
let totalInvites = 0;
if (uuids) {
totalInvites += uuids.length;
}
if (emails) {
totalInvites += emails.length;
}
return totalInvites;
}
/**
* Checks invitation uuids and emails for possible errors.
*
* @param uuids An array of User IDs
* @param emails An array of emails
* @param res Express res object for use with translations
* @throws BadRequest An error describing the issue with the invitations
*/
schema.statics.validateInvitations = async function getInvitationError (invites, res, group = null) {
const {
uuids,
emails,
usernames,
} = invites;
const errorString = getInviteError(uuids, emails, usernames);
if (errorString) throw new BadRequest(res.t(errorString));
const totalInvites = getInviteCount(uuids, emails);
if (totalInvites > INVITES_LIMIT) {
throw new BadRequest(res.t('canOnlyInviteMaxInvites', {maxInvites: INVITES_LIMIT}));
}
// If party, check the limit of members
if (group && group.type === 'party') {
let memberCount = 0;
// Counting the members that already joined the party
memberCount += group.memberCount;
// Count how many invitations currently exist in the party
let query = {};
query['invitations.party.id'] = group._id;
// @TODO invitations are now stored like this: `'invitations.parties': []`
let groupInvites = await User.count(query).exec();
memberCount += groupInvites;
// Counting the members that are going to be invited by email and uuids
memberCount += totalInvites;
if (memberCount > shared.constants.PARTY_LIMIT_MEMBERS) {
throw new BadRequest(res.t('partyExceedsMembersLimit', {maxMembersParty: shared.constants.PARTY_LIMIT_MEMBERS}));
}
}
};
schema.methods.getParticipatingQuestMembers = function getParticipatingQuestMembers () {
return Object.keys(this.quest.members).filter(member => this.quest.members[member]);
};
schema.methods.removeGroupInvitations = async function removeGroupInvitations () {
let group = this;
let usersToRemoveInvitationsFrom = await User.find({
[`invitations.${group.type}${group.type === 'guild' ? 's' : ''}.id`]: group._id,
}).exec();
let userUpdates = usersToRemoveInvitationsFrom.map(user => {
if (group.type === 'party') {
removeFromArray(user.invitations.parties, { id: group._id });
user.invitations.party = user.invitations.parties.length > 0 ? user.invitations.parties[user.invitations.parties.length - 1] : {};
this.markModified('invitations.party');
} else {
removeFromArray(user.invitations.guilds, { id: group._id });
}
return user.save();
});
return Promise.all(userUpdates);
};
// Return true if user is a member of the group
schema.methods.isMember = function isGroupMember (user) {
if (this._id === TAVERN_ID) {
return true; // everyone is considered part of the tavern
} else if (this.type === 'party') {
return user.party._id === this._id ? true : false;
} else { // guilds
return user.guilds.indexOf(this._id) !== -1;
}
};
schema.methods.getMemberCount = async function getMemberCount () {
let query = { guilds: this._id };
if (this.type === 'party') {
query = { 'party._id': this._id };
}
return await User.count(query).exec();
};
schema.methods.sendChat = function sendChat (options = {}) {
const {message, user, metaData, client, flagCount = 0, info = {}, translate, mentions, mentionedMembers} = options;
let newMessage = messageDefaults(message, user, client, flagCount, info);
let newChatMessage = new Chat();
newChatMessage = Object.assign(newChatMessage, newMessage);
newChatMessage.groupId = this._id;
if (user) setUserStyles(newChatMessage, user);
// Optional data stored in the chat message but not returned
// to the users that can be stored for debugging purposes
if (metaData) {
newChatMessage._meta = metaData;
}
// Activate the webhook for receiving group chat messages before
// newChatMessage is possibly returned
this.sendGroupChatReceivedWebhooks(newChatMessage);
// do not send notifications for:
// - groups that never send notifications (e.g., Tavern)
// - groups with very many users
// - messages that have already been flagged to hide them
if (NO_CHAT_NOTIFICATIONS.indexOf(this._id) !== -1 || this.memberCount > LARGE_GROUP_COUNT_MESSAGE_CUTOFF || newChatMessage.flagCount >= CHAT_FLAG_LIMIT_FOR_HIDING) {
return newChatMessage;
}
// Kick off chat notifications in the background.
const query = {};
if (this.type === 'party') {
query['party._id'] = this._id;
} else {
query.guilds = this._id;
}
query._id = { $ne: user ? user._id : ''};
// First remove the old notification (if it exists)
const lastSeenUpdateRemoveOld = {
$pull: {
notifications: { type: 'NEW_CHAT_MESSAGE', 'data.group.id': this._id },
},
};
// Then add the new notification
const lastSeenUpdateAddNew = {
$set: { // old notification, supported until mobile is updated and we release api v4
[`newMessages.${this._id}`]: {name: this.name, value: true},
},
$push: {
notifications: new UserNotification({
type: 'NEW_CHAT_MESSAGE',
data: { group: { id: this._id, name: this.name } },
}).toObject(),
},
};
User.update(query, lastSeenUpdateRemoveOld, {multi: true}).exec().then(() => {
User.update(query, lastSeenUpdateAddNew, {multi: true}).exec();
});
if (this.type === 'party' && user) {
sendChatPushNotifications(user, this, newChatMessage, mentions, translate);
}
if (mentionedMembers) {
mentionedMembers.forEach((member) => {
if (member._id === user._id) return;
const pushNotifPrefs = member.preferences.pushNotifications;
if (this.type === 'party') {
if (pushNotifPrefs.mentionParty !== true || !this.isMember(member)) {
return;
}
} else if (this.isMember(member)) {
if (pushNotifPrefs.mentionJoinedGuild !== true) {
return;
}
} else {
if (this.privacy !== 'public') {
return;
}
if (pushNotifPrefs.mentionUnjoinedGuild !== true) {
return;
}
}
sendPushNotification(member, {identifier: 'chatMention', title: `${user.profile.name} mentioned you in ${this.name}`, message});
});
}
return newChatMessage;
};
schema.methods.startQuest = async function startQuest (user) {
// not using i18n strings because these errors are meant for devs who forgot to pass some parameters
if (this.type !== 'party') throw new InternalServerError('Must be a party to use this method');
if (!this.quest.key) throw new InternalServerError('Party does not have a pending quest');
if (this.quest.active) throw new InternalServerError('Quest is already active');
let userIsParticipating = this.quest.members[user._id];
let quest = questScrolls[this.quest.key];
let collected = {};
if (quest.collect) {
collected = _.transform(quest.collect, (result, n, itemToCollect) => {
result[itemToCollect] = 0;
});
}
this.markModified('quest');
this.quest.active = true;
if (quest.boss) {
this.quest.progress.hp = quest.boss.hp;
if (quest.boss.rage) this.quest.progress.rage = 0;
} else if (quest.collect) {
this.quest.progress.collect = collected;
}
let nonMembers = Object.keys(_.pickBy(this.quest.members, (member) => {
return !member;
}));
// Changes quest.members to only include participating members
this.quest.members = _.pickBy(this.quest.members, _.identity);
let nonUserQuestMembers = _.keys(this.quest.members);
removeFromArray(nonUserQuestMembers, user._id);
// remove any users from quest.members who aren't in the party
// and get the data necessary to send webhooks
const members = [];
await User.find({
_id: {$in: Object.keys(this.quest.members)},
})
.select('party.quest party._id items.quests auth preferences.emailNotifications preferences.pushNotifications preferences.language pushDevices profile.name webhooks')
.lean()
.exec()
.then(partyMembers => {
partyMembers.forEach(member => {
if (!member.party || member.party._id !== this._id) {
delete this.quest.members[member._id];
} else {
members.push(member);
}
});
});
if (userIsParticipating) {
user.party.quest.key = this.quest.key;
user.party.quest.progress.down = 0;
user.party.quest.completed = null;
user.markModified('party.quest');
}
const promises = [];
// Remove the quest from the quest leader items (if they are the current user)
if (this.quest.leader === user._id) {
user.items.quests[this.quest.key] -= 1;
user.markModified('items.quests');
promises.push(user.save());
} else { // another user is starting the quest, update the leader separately
promises.push(User.update({_id: this.quest.leader}, {
$inc: {
[`items.quests.${this.quest.key}`]: -1,
},
}).exec());
}
// update the remaining users
promises.push(User.update({
_id: { $in: nonUserQuestMembers },
}, {
$set: {
'party.quest.key': this.quest.key,
'party.quest.progress.down': 0,
'party.quest.completed': null,
},
}, { multi: true }).exec());
await Promise.all(promises);
// update the users who are not participating
// Do not block updates
User.update({
_id: { $in: nonMembers },
}, _cleanQuestParty(),
{ multi: true }).exec();
const newMessage = this.sendChat({
message: `\`${shared.i18n.t('chatQuestStarted', {questName: quest.text('en')}, 'en')}\``,
metaData: {
participatingMembers: this.getParticipatingQuestMembers().join(', '),
},
info: {
type: 'quest_start',
quest: quest.key,
},
});
await newMessage.save();
const membersToEmail = [];
// send notifications and webhooks in the background without blocking
members.forEach(member => {
if (member._id !== user._id) {
// send push notifications and filter users that disabled emails
if (member.preferences.emailNotifications.questStarted !== false) {
membersToEmail.push(member);
}
// send push notifications and filter users that disabled emails
if (member.preferences.pushNotifications.questStarted !== false) {
const memberLang = member.preferences.language;
sendPushNotification(member, {
title: quest.text(memberLang),
message: shared.i18n.t('questStarted', memberLang),
identifier: 'questStarted',
});
}
}
// Send webhooks
questActivityWebhook.send(member, {
type: 'questStarted',
group: this,
quest,
});
});
// Send emails in bulk
sendTxnEmail(membersToEmail, 'quest-started', [
{ name: 'PARTY_URL', content: '/party' },
]);
};
schema.methods.sendGroupChatReceivedWebhooks = function sendGroupChatReceivedWebhooks (chat) {
let query = {
webhooks: {
$elemMatch: {
type: 'groupChatReceived',
'options.groupId': this._id,
},
},
};
if (this.type === 'party') {
query['party._id'] = this._id;
} else {
query.guilds = this._id;
}
User.find(query).select({webhooks: 1}).lean().exec().then((users) => {
users.forEach((user) => {
groupChatReceivedWebhook.send(user, {
group: this,
chat,
});
});
});
};
schema.statics.cleanQuestParty = _cleanQuestParty;
schema.statics.cleanQuestUser = _cleanQuestUser;
// returns a clean object for group.quest
schema.statics.cleanGroupQuest = function cleanGroupQuest () {
return {
key: null,
active: false,
leader: null,
progress: {
collect: {},
},
members: {},
};
};
function _getUserUpdateForQuestReward (itemToAward, allAwardedItems) {
let updates = {
$set: {},
$inc: {},
};
let dropK = itemToAward.key;
switch (itemToAward.type) {
case 'gear': {
// TODO This means they can lose their new gear on death, is that what we want?
updates.$set[`items.gear.owned.${dropK}`] = true;
break;
}
case 'eggs':
case 'food':
case 'hatchingPotions':
case 'quests': {
updates.$inc[`items.${itemToAward.type}.${dropK}`] = _.filter(allAwardedItems, {type: itemToAward.type, key: itemToAward.key}).length;
break;
}
case 'pets': {
updates.$set[`items.pets.${dropK}`] = 5;
break;
}
case 'mounts': {
updates.$set[`items.mounts.${dropK}`] = true;
break;
}
}
updates = _.omitBy(updates, _.isEmpty);
return updates;
}
async function _updateUserWithRetries (userId, updates, numTry = 1, query = {}) {
query._id = userId;
try {
return await User.update(query, updates).exec();
} catch (err) {
if (numTry < MAX_UPDATE_RETRIES) {
return _updateUserWithRetries(userId, updates, ++numTry, query);
} else {
throw err;
}
}
}
// Participants: Grant rewards & achievements, finish quest.
// Changes the group object update members
schema.methods.finishQuest = async function finishQuest (quest) {
let questK = quest.key;
let updates = {
$inc: {
[`achievements.quests.${questK}`]: 1,
'stats.gp': Number(quest.drop.gp),
'stats.exp': Number(quest.drop.exp),
},
$set: {},
};
if (this._id === TAVERN_ID) {
updates.$set['party.quest.completed'] = questK; // Just show the notif
} else {
_.merge(updates, _cleanQuestParty({$set: {'party.quest.completed': questK}})); // clear quest progress
}
_.each(_.reject(quest.drop.items, 'onlyOwner'), (item) => {
_.merge(updates, _getUserUpdateForQuestReward(item, quest.drop.items));
});
let questOwnerUpdates = {};
let questLeader = this.quest.leader;
_.each(_.filter(quest.drop.items, 'onlyOwner'), (item) => {
_.merge(questOwnerUpdates, _getUserUpdateForQuestReward(item, quest.drop.items));
});
_.merge(questOwnerUpdates, updates);
let participants = this._id === TAVERN_ID ? {} : this.getParticipatingQuestMembers();
this.quest = {};
this.markModified('quest');
if (this._id === TAVERN_ID) {
return await User.update({}, updates, {multi: true}).exec();
}
let promises = participants.map(userId => {
if (userId === questLeader) {
return _updateUserWithRetries(userId, questOwnerUpdates);
} else {
return _updateUserWithRetries(userId, updates);
}
});
// Send webhooks in background
// @TODO move the find users part to a worker as well, not just the http request
User.find({
_id: {$in: participants},
webhooks: {
$elemMatch: {
type: 'questActivity',
'options.questFinished': true,
},
},
})
.select('_id webhooks')
.lean()
.exec()
.then(participantsWithWebhook => {
participantsWithWebhook.forEach(participantWithWebhook => {
// Send webhooks
questActivityWebhook.send(participantWithWebhook, {
type: 'questFinished',
group: this,
quest,
});
});
});
_.forEach(questSeriesAchievements, (questList, achievement) => {
if (questList.includes(questK)) {
let questAchievementQuery = {};
questAchievementQuery[`achievements.${achievement}`] = {$ne: true};
_.forEach(questList, (questName) => {
if (questName !== questK) {
questAchievementQuery[`achievements.quests.${questName}`] = {$gt: 0};
}
});
let questAchievementUpdate = {$set: {}, $push: {}};
questAchievementUpdate.$set[`achievements.${achievement}`] = true;
const achievementTitleCase = `${achievement.slice(0, 1).toUpperCase()}${achievement.slice(1, achievement.length)}`;
const achievementSnakeCase = `ACHIEVEMENT_${_.snakeCase(achievement).toUpperCase()}`;
questAchievementUpdate.$push = {
notifications: new UserNotification({
type: achievementSnakeCase,
data: {
achievement,
message: `${shared.i18n.t('modalAchievement')} ${shared.i18n.t(`achievement${achievementTitleCase}`)}`,
modalText: shared.i18n.t(`achievement${achievementTitleCase}ModalText`),
},
}).toObject(),
};
promises.push(participants.map(userId => {
return _updateUserWithRetries(userId, questAchievementUpdate, null, questAchievementQuery);
}));
}
});
await Promise.all(promises);
};
function _isOnQuest (user, progress, group) {
return group && progress && group.quest && group.quest.active && group.quest.members[user._id] === true;
}
schema.methods._processBossQuest = async function processBossQuest (options) {
let {
user,
progress,
} = options;
let group = this;
let quest = questScrolls[group.quest.key];
let down = progress.down * quest.boss.str; // multiply by boss strength
// Everyone takes damage
let updates = {
$inc: {'stats.hp': down},
};
const promises = [];
group.quest.progress.hp -= progress.up;
if (CRON_SAFE_MODE || CRON_SEMI_SAFE_MODE) {
const groupMessage = group.sendChat({
message: `\`${shared.i18n.t('chatBossDontAttack', {bossName: quest.boss.name('en')}, 'en')}\``,
info: {
type: 'boss_dont_attack',
user: user.profile.name,
quest: group.quest.key,
userDamage: progress.up.toFixed(1),
},
});
promises.push(groupMessage.save());
} else {
const groupMessage = group.sendChat({
message: `\`${shared.i18n.t('chatBossDamage', {username: user.profile.name, bossName: quest.boss.name('en'), userDamage: progress.up.toFixed(1), bossDamage: Math.abs(down).toFixed(1)}, user.preferences.language)}\``,
info: {
type: 'boss_damage',
user: user.profile.name,
quest: group.quest.key,
userDamage: progress.up.toFixed(1),
bossDamage: Math.abs(down).toFixed(1),
},
});
promises.push(groupMessage.save());
}
// If boss has Rage, increment Rage as well
if (quest.boss.rage) {
group.quest.progress.rage += Math.abs(down);
if (group.quest.progress.rage >= quest.boss.rage.value) {
const rageMessage = group.sendChat({
message: quest.boss.rage.effect('en'),
info: {
type: 'boss_rage',
quest: quest.key,
},
});
promises.push(rageMessage.save());