This repository was archived by the owner on Oct 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathmain.js
2253 lines (1946 loc) · 76.2 KB
/
main.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
require('source-map-support/register');
module.exports = /******/ (function(modules) {
// webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {}; // The require function
/******/
/******/ /******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if (installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/
} // Create a new module (and put it into the cache)
/******/ /******/ var module = (installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {},
/******/
}); // Execute the module function
/******/
/******/ /******/ modules[moduleId].call(
module.exports,
module,
module.exports,
__webpack_require__
); // Flag the module as loaded
/******/
/******/ /******/ module.l = true; // Return the exports of the module
/******/
/******/ /******/ return module.exports;
/******/
} // expose the modules object (__webpack_modules__)
/******/
/******/
/******/ /******/ __webpack_require__.m = modules; // expose the module cache
/******/
/******/ /******/ __webpack_require__.c = installedModules; // define getter function for harmony exports
/******/
/******/ /******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if (!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter,
/******/
});
/******/
}
/******/
}; // getDefaultExport function for compatibility with non-harmony modules
/******/
/******/ /******/ __webpack_require__.n = function(module) {
/******/ var getter =
module && module.__esModule
? /******/ function getDefault() {
return module['default'];
}
: /******/ function getModuleExports() {
return module;
};
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/
}; // Object.prototype.hasOwnProperty.call
/******/
/******/ /******/ __webpack_require__.o = function(object, property) {
return Object.prototype.hasOwnProperty.call(object, property);
}; // __webpack_public_path__
/******/
/******/ /******/ __webpack_require__.p = '/'; // Load entry module and return exports
/******/
/******/ /******/ return __webpack_require__((__webpack_require__.s = 5));
/******/
})(
/************************************************************************/
/******/ [
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends =
Object.assign ||
function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
/**
* Database setup is done here
*/
var fs = __webpack_require__(13);
var path = __webpack_require__(14);
var IS_PROD = !process.env.FORCE_DEV && 'development' === 'production';
var DEFAULT_CONFIG = {
db: 'spectrum',
};
var PRODUCTION_CONFIG = {
password: process.env.COMPOSE_RETHINKDB_PASSWORD,
host: process.env.COMPOSE_RETHINKDB_URL,
port: process.env.COMPOSE_RETHINKDB_PORT,
ssl: {
ca: IS_PROD && __webpack_require__(15),
},
};
var config = IS_PROD
? _extends({}, DEFAULT_CONFIG, PRODUCTION_CONFIG)
: _extends({}, DEFAULT_CONFIG);
var r = __webpack_require__(16)(config);
module.exports = { db: r };
// /**
// * Database setup is done here
// */
// const fs = require('fs');
// const path = require('path');
// const IS_PROD = !process.env.FORCE_DEV && process.env.NODE_ENV === 'production';
//
// const DEFAULT_CONFIG = {
// db: 'spectrum',
// };
//
// // COMPOSE_RETHINKDB_URL="aws-us-east-1-portal.6.dblayer.com"
// // COMPOSE_RETHINKDB_PORT=19241
// // COMPOSE_RETHINKDB_PASSWORD="12460d0b-b1dc-4505-9cd5-7a96e58ad825"
//
// const PRODUCTION_CONFIG = {
// password: "12460d0b-b1dc-4505-9cd5-7a96e58ad825",
// host: "aws-us-east-1-portal.6.dblayer.com" ,
// port: 19241,
// ssl: {
// ca: !IS_PROD && require('raw-loader!../../cacert'),
// },
// };
//
// const config = !IS_PROD
// ? {
// ...DEFAULT_CONFIG,
// ...PRODUCTION_CONFIG,
// }
// : {
// ...DEFAULT_CONFIG,
// };
//
// var r = require('rethinkdbdash')(config);
//
// module.exports = { db: r };
/***/
},
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var Queue = __webpack_require__(11);
var Raven = __webpack_require__(3);
if (false) {
Raven.config(
'https://3bd8523edd5d43d7998f9b85562d6924:[email protected]/154812',
{
environment: process.env.NODE_ENV,
}
).install();
}
var redis = false
? {
port: process.env.COMPOSE_REDIS_PORT,
host: process.env.COMPOSE_REDIS_URL,
password: process.env.COMPOSE_REDIS_PASSWORD,
}
: undefined; // Use the local instance of Redis in development by not passing any connection string
// Leave the options undefined if we're using the default redis connection
var options = redis && { redis: redis };
function createQueue(name /*: string */) {
var queue = new Queue(name, options);
queue.on('stalled', function(job) {
var message = 'Job#' + job.id + ' stalled, processing again.';
if (true) {
console.error(message);
return;
}
// In production log stalled job to Sentry
Raven.captureException(new Error(message));
});
return new Queue(name, options);
}
module.exports = createQueue;
/***/
},
/* 2 */
/***/ function(module, exports) {
module.exports = require('debug');
/***/
},
/* 3 */
/***/ function(module, exports) {
module.exports = require('raven');
/***/
},
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
// counts for processing
// the thread must have at least # total messages
var MIN_TOTAL_MESSAGE_COUNT = (exports.MIN_TOTAL_MESSAGE_COUNT = 1);
// # of the total messages must have been sent in the past week
var MIN_NEW_MESSAGE_COUNT = (exports.MIN_NEW_MESSAGE_COUNT = 1);
// # only show the top # threads per channel
var MAX_THREAD_COUNT_PER_CHANNEL = (exports.MAX_THREAD_COUNT_PER_CHANNEL = 10);
// don't send the digest if the email will have less than # total threads to show
var MIN_THREADS_REQUIRED_FOR_DIGEST = (exports.MIN_THREADS_REQUIRED_FOR_DIGEST = 1);
// cap the digest at # threads
var MAX_THREAD_COUNT_PER_DIGEST = (exports.MAX_THREAD_COUNT_PER_DIGEST = 10);
// upsell communities to join if the user has joined less than # communities
var COMMUNITY_UPSELL_THRESHOLD = (exports.COMMUNITY_UPSELL_THRESHOLD = 5);
// generate a score for each thread based on the total number of messages and number of new messages
// new messages rank higher in order to devalue old threads that have a large amount of old messages (like pinned posts)
// the end weekly digest will have threads sorted by the weight of (TOTAL * WEIGHT) + (NEW * WEIGHT)
var TOTAL_MESSAGE_COUNT_WEIGHT = (exports.TOTAL_MESSAGE_COUNT_WEIGHT = 0.1);
var NEW_MESSAGE_COUNT_WEIGHT = (exports.NEW_MESSAGE_COUNT_WEIGHT = 1.5);
/*
Example weighting:
A thread with 150 messages, where 5 are new this week: 22.5
A thread with 10 total messages, where all 10 are new this week: 16
A thread with 25 total messages, where 10 are old and 15 are new this week: 25
*/
// queues
var SEND_WEEKLY_DIGEST_EMAIL = (exports.SEND_WEEKLY_DIGEST_EMAIL =
'send weekly digest email');
/***/
},
/* 5 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(6);
/***/
},
/* 6 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _sendWeeklyDigestEmail = __webpack_require__(7);
var _sendWeeklyDigestEmail2 = _interopRequireDefault(
_sendWeeklyDigestEmail
);
var _constants = __webpack_require__(4);
var _jobs = __webpack_require__(22);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true,
});
} else {
obj[key] = value;
}
return obj;
}
var debug = __webpack_require__(2)('hermes');
var createWorker = __webpack_require__(26);
var PORT = process.env.PORT || 3004;
console.log('\n✉️ Chronos, the cron job worker, is starting...');
debug('Logging with debug enabled!');
console.log('');
var server = createWorker(
_defineProperty(
{},
_constants.SEND_WEEKLY_DIGEST_EMAIL,
_sendWeeklyDigestEmail2.default
)
);
console.log(_jobs.weeklyDigest);
console.log(
'\uD83D\uDDC4 Crons open for business ' +
(('development' === 'production' &&
'at ' +
process.env.COMPOSE_REDIS_URL +
':' +
process.env.COMPOSE_REDIS_PORT) ||
'locally')
);
server.listen(PORT, 'localhost', function() {
console.log(
'\uD83D\uDC89 Healthcheck server running at ' +
server.address().address +
':' +
server.address().port
);
});
/***/
},
/* 7 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
var _regenerator = __webpack_require__(8);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _extends =
Object.assign ||
function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var _lodash = __webpack_require__(10);
var _lodash2 = _interopRequireDefault(_lodash);
var _createQueue = __webpack_require__(1);
var _createQueue2 = _interopRequireDefault(_createQueue);
var _constants = __webpack_require__(4);
var _thread = __webpack_require__(12);
var _usersSettings = __webpack_require__(17);
var _usersChannels = __webpack_require__(18);
var _usersCommunities = __webpack_require__(19);
var _message = __webpack_require__(20);
var _community = __webpack_require__(21);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _toConsumableArray(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
} else {
return Array.from(arr);
}
}
function _objectWithoutProperties(obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
}
function _asyncToGenerator(fn) {
return function() {
var gen = fn.apply(this, arguments);
return new Promise(function(resolve, reject) {
function step(key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(
function(value) {
step('next', value);
},
function(err) {
step('throw', err);
}
);
}
}
return step('next');
});
};
}
var debug = __webpack_require__(2)(
'chronos:queue:send-weekly-digest-email'
);
// $FlowFixMe
var sendWeeklyDigestEmailQueue = (0, _createQueue2.default)(
_constants.SEND_WEEKLY_DIGEST_EMAIL
);
exports.default = function(job) {
debug('\nnew job: ' + job.id);
debug('\nprocessing weekly digest');
/*
1. Get all threads in the database that were active in the last week. For each thread, construct a new object containing the thread data and the message count from the server
*/
var allActiveThreadsThisWeek = (function() {
var _ref = _asyncToGenerator(
_regenerator2.default.mark(function _callee2() {
var threadIds,
messageCountPromises,
messageCounts,
filteredTopThreads;
return _regenerator2.default.wrap(
function _callee2$(_context2) {
while (1) {
switch ((_context2.prev = _context2.next)) {
case 0:
_context2.next = 2;
return (0, _thread.getActiveThreadsInPastWeek)();
case 2:
threadIds = _context2.sent;
debug('\n ⚙️ Fetched all active threads this week');
// if no threadIds, escape
if (!(!threadIds || threadIds.length === 0)) {
_context2.next = 7;
break;
}
debug('\n ❌ No active threads found');
return _context2.abrupt('return');
case 7:
// for each thread that was active in the last week, return a new array containing a record for each thread with the thread data and the message count
messageCountPromises = threadIds.map(
(function() {
var _ref3 = _asyncToGenerator(
_regenerator2.default.mark(function _callee(
_ref2
) {
var communityId = _ref2.communityId,
channelId = _ref2.channelId,
id = _ref2.id,
content = _ref2.content,
thread = _objectWithoutProperties(_ref2, [
'communityId',
'channelId',
'id',
'content',
]);
return _regenerator2.default.wrap(
function _callee$(_context) {
while (1) {
switch ((_context.prev = _context.next)) {
case 0:
_context.t0 = communityId;
_context.t1 = channelId;
_context.t2 = id;
_context.t3 = content.title;
_context.next = 6;
return (0,
_message.getNewMessageCount)(id);
case 6:
_context.t4 = _context.sent;
_context.next = 9;
return (0,
_message.getTotalMessageCount)(id);
case 9:
_context.t5 = _context.sent;
return _context.abrupt('return', {
communityId: _context.t0,
channelId: _context.t1,
id: _context.t2,
title: _context.t3,
newMessageCount: _context.t4,
totalMessageCount: _context.t5,
});
case 11:
case 'end':
return _context.stop();
}
}
},
_callee,
undefined
);
})
);
return function(_x) {
return _ref3.apply(this, arguments);
};
})()
);
// promise all the active threads and message counts
_context2.next = 10;
return Promise.all(messageCountPromises);
case 10:
messageCounts = _context2.sent;
debug('\n ⚙️ Fetched message counts for threads');
// remove any threads where the total message count is less than 10
filteredTopThreads = messageCounts
.filter(function(thread) {
return (
thread.totalMessageCount >=
_constants.MIN_TOTAL_MESSAGE_COUNT
);
})
.filter(function(thread) {
return (
thread.newMessageCount >=
_constants.MIN_NEW_MESSAGE_COUNT
);
});
debug('\n ⚙️ Filtered threads with enough messages');
// returns an array of threads that are active in the last week and have the minimum required message count to be considered valuable
return _context2.abrupt('return', filteredTopThreads);
case 15:
case 'end':
return _context2.stop();
}
}
},
_callee2,
undefined
);
})
);
return function allActiveThreadsThisWeek() {
return _ref.apply(this, arguments);
};
})();
/*
2. Given an array of all the active threads this week that contain the minimum message count required, we now aggregate them by the channel where they were posted.
The return value from this function is an object with keys representing channelIds and values representing an array of threads
*/
var activeThreadsByChannel = (function() {
var _ref4 = _asyncToGenerator(
_regenerator2.default.mark(function _callee4() {
var topThreads,
obj,
getCommunity,
topThreadsWithCommunityDataPromises,
threadsWithCommunityData,
finalThreads,
finishedTopThreads;
return _regenerator2.default.wrap(
function _callee4$(_context4) {
while (1) {
switch ((_context4.prev = _context4.next)) {
case 0:
_context4.next = 2;
return allActiveThreadsThisWeek();
case 2:
topThreads = _context4.sent;
if (!(!topThreads || topThreads.length === 0)) {
_context4.next = 6;
break;
}
debug('\n ❌ No topThreads found');
return _context4.abrupt('return');
case 6:
// create an empty object for the final output
obj = {};
getCommunity = function getCommunity(id) {
return (0, _community.getCommunityById)(id);
};
// for each thread, get the community data that we'll need when rendering an email
topThreadsWithCommunityDataPromises = topThreads.map(
(function() {
var _ref5 = _asyncToGenerator(
_regenerator2.default.mark(function _callee3(
thread
) {
var community, obj;
return _regenerator2.default.wrap(
function _callee3$(_context3) {
while (1) {
switch ((_context3.prev =
_context3.next)) {
case 0:
_context3.next = 2;
return getCommunity(
thread.communityId
);
case 2:
community = _context3.sent;
// this is the final data we'll send to the email for each thread
obj = {
community: {
name: community.name,
slug: community.slug,
profilePhoto:
community.profilePhoto,
},
channelId: thread.channelId,
title: thread.title,
threadId: thread.id,
newMessageCount:
thread.newMessageCount,
totalMessageCount:
thread.totalMessageCount,
};
return _context3.abrupt(
'return',
obj
);
case 5:
case 'end':
return _context3.stop();
}
}
},
_callee3,
undefined
);
})
);
return function(_x2) {
return _ref5.apply(this, arguments);
};
})()
);
_context4.next = 11;
return Promise.all(topThreadsWithCommunityDataPromises);
case 11:
threadsWithCommunityData = _context4.sent;
// for each of the active threads this week, determine if that that thread has been categorized yet into the new object. If so, push that thread into the array, otherwise create a new key/value pair in the object for the channel + thread
finalThreads = threadsWithCommunityData.map(function(
thread
) {
return obj[thread.channelId]
? (obj[
thread.channelId
] = [].concat(
_toConsumableArray(obj[thread.channelId]),
[_extends({}, thread)]
))
: (obj[thread.channelId] = [_extends({}, thread)]);
});
_context4.next = 15;
return Promise.all(finalThreads);
case 15:
finishedTopThreads = _context4.sent;
debug('\n ⚙️ Organized top threads by channel');
// return the final object containing keys for channelIds, and arrays of threads for values
return _context4.abrupt('return', obj);
case 18:
case 'end':
return _context4.stop();
}
}
},
_callee4,
undefined
);
})
);
return function activeThreadsByChannel() {
return _ref4.apply(this, arguments);
};
})();
/*
3. In this step we process and aggregate user settings, users channels, and the thread data fetched above
a. first, get all the userIds of people who have opted to receive a weekly digest
b. for each person, get an array of channelIds where that user is a member
c. determine if there is any overlap between the user's channels and the active threads from the past week. Note: this filters out people who are members of inactive communities, even if they are opted in to receive a weekly digest
*/
var eligibleUsersForWeeklyDigest = (function() {
var _ref6 = _asyncToGenerator(
_regenerator2.default.mark(function _callee6() {
var users,
channelConnectionPromises,
usersWithChannels,
threadData,
threadChannelKeys,
getIntersectingChannels,
rawThreadsForUsersEmail,
eligibleUsersForWeeklyDigest;
return _regenerator2.default.wrap(
function _callee6$(_context6) {
while (1) {
switch ((_context6.prev = _context6.next)) {
case 0:
_context6.next = 2;
return (0, _usersSettings.getUsersForWeeklyDigest)();
case 2:
users = _context6.sent;
debug(
'\n ⚙️ Fetched users who want to receive a weekly digest'
);
// for each user who wants a weekly digest, fetch an array of channelIds where they are a member
channelConnectionPromises = users.map(
(function() {
var _ref8 = _asyncToGenerator(
_regenerator2.default.mark(function _callee5(
_ref7
) {
var email = _ref7.email,
firstName = _ref7.firstName,
userId = _ref7.userId,
user = _objectWithoutProperties(_ref7, [
'email',
'firstName',
'userId',
]);
return _regenerator2.default.wrap(
function _callee5$(_context5) {
while (1) {
switch ((_context5.prev =
_context5.next)) {
case 0:
_context5.t0 = email;
_context5.t1 = firstName || null;
_context5.t2 = userId;
_context5.next = 5;
return (0,
_usersChannels.getUsersChannelsEligibleForWeeklyDigest)(
userId
);
case 5:
_context5.t3 = _context5.sent;
return _context5.abrupt('return', {
email: _context5.t0,
name: _context5.t1,
userId: _context5.t2,
channels: _context5.t3,
});
case 7:
case 'end':
return _context5.stop();
}
}
},
_callee5,
undefined
);
})
);
return function(_x3) {
return _ref8.apply(this, arguments);
};
})()
);
// fetch all usersChannels
_context6.next = 7;
return Promise.all(channelConnectionPromises);
case 7:
usersWithChannels = _context6.sent;
debug('\n ⚙️ Fetched users eligible channels');
// get all the threads, organized by channel, in scope
_context6.next = 11;
return activeThreadsByChannel();
case 11:
threadData = _context6.sent;
if (threadData) {
_context6.next = 15;
break;
}
debug('\n ❌ No threadData found');
return _context6.abrupt('return');
case 15:
// get an array of all channels where there are active threads this week
threadChannelKeys = Object.keys(threadData);
// for each user, determine the overlapping channels where they are a member and where active threads occurred this week
getIntersectingChannels = usersWithChannels.map(
function(e) {
return _extends({}, e, {
channels: (0, _lodash2.default)(
e.channels,
threadChannelKeys
),
});
}
);
debug(
'\n ⚙️ Filtered intersecting channels between the user and the top threads this week'
);
// based on the intersecting channels, get the threads that could appear in the user's weekly digest
rawThreadsForUsersEmail = getIntersectingChannels.map(
function(e) {
var arr = [];
e.channels.map(function(c) {
return arr.push.apply(
arr,
_toConsumableArray(threadData[c])
);
});
return _extends({}, e, {
threads: [].concat(arr),
});
}
);
debug(
'\n ⚙️ Fetched all the possible threads this user could receive in a weekly digest'
);
// if no rawThreadsForUsersEmail, escape
if (
!(
!rawThreadsForUsersEmail ||
rawThreadsForUsersEmail.length === 0
)
) {
_context6.next = 23;
break;
}
debug('\n ❌ No rawThreads found');
return _context6.abrupt('return');
case 23:
// we don't want to send a weekly digest to someone with only one thread for that week - so in this step we filter out any results where the thread count is less than the miminimum acceptable threshhold
eligibleUsersForWeeklyDigest = rawThreadsForUsersEmail
.filter(function(user) {
return (
user.threads.length >
_constants.MIN_THREADS_REQUIRED_FOR_DIGEST
);
})
// and finally, sort the user's threads in descending order by message count
.map(function(_ref9) {
var channels = _ref9.channels,
user = _objectWithoutProperties(_ref9, [
'channels',
]);
// for each thread, assign a score based on the total message count and new message count
var threadsWithScores = user.threads.map(function(
thread
) {
return _extends({}, thread, {
score:
thread.newMessageCount *
_constants.NEW_MESSAGE_COUNT_WEIGHT +
thread.totalMessageCount *
_constants.TOTAL_MESSAGE_COUNT_WEIGHT,
});
});
return _extends({}, user, {
threads: threadsWithScores
.sort(function(a, b) {
return b.score - a.score;
})
.slice(
0,
_constants.MAX_THREAD_COUNT_PER_DIGEST
),
});
});
debug(
'\n ⚙️ Filtered users who have enough threads to qualify for a weekly digest'
);
/*
The result of our operations so far has given us an array with the following shape:
[
{
userId: ID,
email: String,
name?: String // returns null if user doesn't have a first name
threads: [{ thread1 }, { thread2}, ... ]
}
...
]
Where a thread contains the following information:
{
communityId: ID,
channelId: ID,
id: ID,
title: String,
messageCount: Number
}
*/
return _context6.abrupt(
'return',
eligibleUsersForWeeklyDigest
);
case 26:
case 'end':
return _context6.stop();
}
}
},
_callee6,
undefined
);
})