-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
531 lines (468 loc) · 13.5 KB
/
index.mjs
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
//import { readFileSync } from "fs";
import Promise from "bluebird";
import _ from "lodash";
import debug from "debug";
import Jobs from "@oada/jobs";
import tree from "./tree.js";
//import jsonpointer from "jsonpointer";
import template from "./email_templates/index.js";
import { v4 as uuidv4 } from "uuid";
import emailParser from "email-addresses";
import config from "./config.js";
import moment from "moment";
//import Worker from "@oada/rules-worker";
//const { RulesWorker } = Worker;
const { Service } = Jobs;
const TN = "trellis-notifications";
let OADA = null;
const error = debug(`${TN}:error`);
const warn = debug(`${TN}:warn`);
const info = debug(`${TN}:info`);
const trace = debug(`${TN}:trace`);
const TOKEN = config.get('token');
let DOMAIN = config.get('domain') || '';
let DAILY_DIGEST_TIME = config.get("dailyDigestTime") || 8;
const MS_IN_A_DAY = 86400000;
if (DOMAIN.match(/^http/)) DOMAIN = DOMAIN.replace(/^https:\/\//, '')
if (DOMAIN === 'localhost' || DOMAIN === 'proxy') {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0
}
const SKIN = config.get('skin') || 'default';
const service = new Service(TN, DOMAIN, TOKEN, 1, {
finishReporters: [
{
type: 'slack',
status: 'failure',
posturl: config.get('slackposturl')
}
]
}); // 1 concurrent job
const DocType = {
AUDIT: "audit",
COI: "coi",
CERT: "cert",
LOG: "log",
ALL: "all"
};
Object.freeze(DocType);
const Frequency = {
DAILYFEED: "daily-feed",
LIVEFEED: "live-feed"
};
Object.freeze(Frequency);
let notifications = {};
let dailyNotifications = {};
const doctypes = [DocType.AUDIT, DocType.CERT, DocType.COI, DocType.LOG];
let now = new Date();
let msTill1700 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), DAILY_DIGEST_TIME, 0, 0, 0) - now;
if (msTill1700 < 0) {
msTill1700 += MS_IN_A_DAY;
}
setTimeout(setDailyDigestTimer, msTill1700);
async function setDailyDigestTimer() {
try {
await dailyDigest();
setInterval(dailyDigest, MS_IN_A_DAY);
} catch (error) {
trace("Error: dailyDigest() ", e);
};
}//end setDailyDigestTimer
/**
* get Daily Digest Path
*/
function getDailyDigestPath() {
let _date = moment().format('YYYY-MM-DD');
let _path = `/bookmarks/services/${TN}/notifications/day-index/${_date}/daily-digest-queue`;
return _path;
}//end getDailyDigestPath
/**
* get Daily Digest Queue
* @param oada
*/
async function getDailyDigestQueue(oada) {
let _path = getDailyDigestPath();
return oada
.get({ path: _path })
.then(r => r.data)
.catch(e => {
throw new Error("Failed to get daily digest queue, error " + e);
});
}//end getDailyDigestQueue
/**
* Updating daily digest after processing daily digest
* @param oada
* @param _content
*/
async function updateDailyDigestQueue(oada, _content) {
let _path = getDailyDigestPath();
return oada.put({
path: _path,
data: _content
}).catch(e => {
throw new Error("--> updateDailyDigest(): Failed to update daily digest " + e);
});
}//end updateDailyDigestQueue
/**
* Flushing daily notifications hash table after processing the queue
*/
function flushDailyNotifications() {
dailyNotifications = {};
}//end flushDailyNotifications()
let _counter = 0;
/**
* Daily Digest Main Function
*/
async function dailyDigest() {
let _path = getDailyDigestPath();
let _result = {};
if (OADA !== null) {
try {
let _dailyDigest = await getDailyDigestQueue(OADA);
if (_dailyDigest && (!_dailyDigest.hasOwnProperty("processed") || !_dailyDigest.processed)) {
let _dailyDigestHT = _dailyDigest["notificationsHT"];
for (let _email of Object.keys(_dailyDigestHT)) {
let _userToken = "";
let _docType = "";
if (_dailyDigestHT[_email].notifications.length >= 2) {
_docType = DocType.ALL;
} else {
_docType = _dailyDigestHT[_email].notifications[0].docType;
}//if
for (let _notification in _dailyDigestHT[_email].notifications) {
_userToken = _dailyDigestHT[_email].notifications[0].userToken;
} //for #2
await createEmailJob(OADA, _docType, _email, _email, _userToken);
}//for
_result = {
counter: _counter++,
processed: true,
path: _path
};
await OADA.put({
path: _path,
data: _result
}).catch(e => {
throw new Error("Failed to put resource for daily digest " + e);
});
flushDailyNotifications();
}//if
} catch (error) {
throw new Error("--> dailyDigest(): Error when getting the daily digest queue");
};
}//if
}//end daily digest
/**
* Generates a token
*/
function generateToken() {
return uuidv4().replace(/-/g, '');
}//end generateToken
// 5 min timeout
Promise.each(doctypes, async doctype => {
trace("creating jobs for document type ", doctype);
service.on(`${doctype}-changed`, config.get('timeout'), newJob);
});
async function newJob(job, { jobId, log, oada }) {
/*
trace('Linking job under src/_meta until oada-jobs can do that natively')
//debugging
//
await oada.put({
path: `${job.config.src}/_meta/services/${TN}/jobs`,
data: {
[jobId]: { _ref: `resources/${jobId}` }
}
})
*/
OADA = oada;
// Find the net destination path, taking into consideration chroot
const c = job.config;
const _userEndpoint = c.userEndpoint;
const _emailsEndpoint = c.emailsEndpoint;
const _doctype = c.doctype;
let _destinationPath = c.chroot;
let _tnUserEndpoint = "";
let _emailsToNotify = "";
let _prefix = "/bookmarks/trellisfw/";
_tnUserEndpoint = _prefix + _destinationPath + '/' + _userEndpoint;
_emailsToNotify = _prefix + _destinationPath + "/" + _emailsEndpoint;
let _notificationsConfig = _prefix + _destinationPath;
trace('Final destinationPath = ', _destinationPath);
const _emails = await oada
.get({ path: _emailsToNotify })
.then(r => r.data)
.catch(e => {
throw new Error("Failed to retrieve emails to notify, error " + e);
});
//notify according to rules/config
let _config = await notifyUser({
oada, _tnUserEndpoint, _emailsToNotify,
_notificationsConfig, _emails, job
});
return _config;
}//end newJob
/**
* Inserts into the daily digest endpoint in the notifications service
* keeps track of the notifications that are need to send at the end of the day
* @param notifications --> object with configuration for notifications
*/
async function insertDailyDigestQueue(oada, notifications, _userToken) {
let _entries = Object.entries(notifications);
let _result = {};
for (const [email, notification] of _entries) {
if (notification.config.frequency === Frequency.DAILYFEED) {
let _userNotifications = [];
if (dailyNotifications[email]) {
//copying previous array of notifications
_userNotifications = dailyNotifications[email].notifications;
} else {
//initialize the hash table entry
dailyNotifications[email] = {};
dailyNotifications[email].notifications = [];
dailyNotifications[email].id = email;
dailyNotifications[email].processed = false;
}// if
_result[email] = {};
let _userNotification = {
docType: notification.config.docType,
userToken: _userToken
};
//let _userNotifications = [];
_userNotifications.push(_userNotification);
_result[email] = {
id: email,
notifications: _userNotifications,
processed: false
};
dailyNotifications[email].notifications = _userNotifications;
}//if
}//for
let _path = getDailyDigestPath();
let _notificationsHT = {
notificationsHT: _result
};
await oada.put({
path: _path,
data: _notificationsHT
});
return _result;
}//end insertDailyDigestQueue
/**
* Generates the subject to be sent by the notification service
* @param docType -> type of document
*/
function getSubject(docType) {
let _subject = "New FSQA audit available";
switch (docType) {
case DocType.CERT:
_subject = "New FSQA certificate available";
break;
case DocType.COI:
_subject = "New certificate of insurance available";
break;
case DocType.LOG:
_subject = "New letter of guarantee available";
break;
case DocType.AUDIT:
_subject = "New FSQA audit available";
break;
case DocType.ALL:
_subject = "Daily digest - new documents available";
break;
default:
throw new Error("Document type not recognized");
}//switch
return _subject;
}//end getSubject
/**
* Gets temporal authorization
* @param oada --> oada client
* @param job --> job configuration
* @param _userToken --> user generated token
*/
async function getAuthorization(oada, job, _userToken) {
const _data = {
clientId: "SERVICE-CLIENT-TRELLIS-NOTIFICATIONS",
user: { _id: job.config.user.id },
token: _userToken,
scope: ["all:all"],
createTime: Date.now(),
expiresIn: 90 * 24 * 3600 * 1000
};
const _auth = await oada.
post({
path: "/authorizations",
data: _data,
headers: { "content-type": "application/vnd.oada.authorization.1+json" }
})
.then(r => r.data)
.catch(e => {
info('FAILED to post to /authorizations user ', job.config.user.id, ', error ', e);
throw e;
});
return _auth;
}// end getAuthorization
/**
* Gets the Notification Config Data from endpoint (required)
* @param oada --> oada client
* @param _notificationsConfig --> path to the configuration for notifications
*/
async function getNotificationConfigData(oada, _notificationsConfig) {
return await oada
.get({ path: _notificationsConfig })
.then(r => r.data)
.catch(e => {
throw new Error("Failed to retrieve notifications config, error " + e);
});
}//end getNotificationConfigData
/**
* Creates a job for email notifications
* @param oada
* @param _docType
* @param _to
* @param _emails
*/
async function createEmailJob(oada, _docType, _to, _emails, _userToken) {
let _subject = getSubject(_docType);
let _link = `https://trellisfw.github.io/conductor?d=${DOMAIN}&t=${_userToken}&s=${SKIN}`;
let _resourceData = {
service: "abalonemail",
type: "email",
config: {
multiple: false,
to: _to,
from: "[email protected]",
subject: `[Trellis Notification] - [${_subject}]`,
templateData: {
recipients: _emails,
link: _link
},
html: template.html,
attachments: template.attachments
}
};
const _jobkey = await oada
.post({
path: "/resources",
data: _resourceData
})
.then(r => r.headers["content-location"].replace(/^\/resources\//, ''))
.catch(e => {
throw new Error("Failed to create resource, error " + e);
});
// Link into abalonemail queue
await oada.put({
path: `/bookmarks/services/abalonemail/jobs`,
data: { [_jobkey]: { _id: `resources/${_jobkey}` } },
tree
});
return _jobkey;
}//end createEmailJob
/**
* Populates the values for all notifications in the config
* @param _to
* @param _notificationsConfigData
*/
function populateNotifications(_to, _notificationsConfigData, _docType) {
let _emailsConfig = _notificationsConfigData["notifications-config"];
let _configTemplate = {
id: "",
type: "email",
frequency: "",
docType: _docType
};
if (_to) {
_to.forEach(function (item) {
let _template = _.cloneDeep(_configTemplate);
_template.id = item.email;
if (_emailsConfig[item.email] && _emailsConfig[item.email].frequency) {
_template.frequency = _emailsConfig[item.email].frequency;
} else {
_template.frequency = Frequency.LIVEFEED;
}
notifications[item.email] = {};
notifications[item.email].config = {};
notifications[item.email].config = _template;
});
}
}//end populateNotifications
/**
* Parses the emails to notify
* @param _emails
*/
function parseEmails(_emails) {
return emailParser.parseAddressList(_emails).map(({ name, address }) =>
({
name: name || undefined,
email: address
}));
}//end parseEmails
/**
* Gets the LIVEFEED Emails from notifications
*/
function getLiveFeedEmails() {
let _entries = Object.entries(notifications);
let _counter = 0;
let _result = "";
let _emails = "";
for (const [email, notification] of _entries) {
if (notification.config.frequency === Frequency.LIVEFEED) {
_result += email + ",";
_counter++;
}//if
}//for
if (_counter > 0) {
_emails = _result.substring(0, _result.length - 1);
}
return _emails;
}//end getLiveFeedEmails
/**
* notifyUser: notifies user according to rules
* @param param0
*/
async function notifyUser({ oada, _tnUserEndpoint, _emailsToNotify,
_notificationsConfig, _emails, job }) {
trace('--> notify User ', job.config.doctype);
let _tradingPartnerId = job.config.chroot.replace(/^.*trading-partners\/([^\/]+)(\/.*)$/, '$1');
const _docType = job.config.doctype;
const _userToken = generateToken();
const _auth = await getAuthorization(oada, job, _userToken);
const _notificationsConfigData = await getNotificationConfigData(oada, _notificationsConfig);
let _to = parseEmails(_emails);
populateNotifications(_to, _notificationsConfigData, _docType);
let _list = await insertDailyDigestQueue(oada, notifications, _userToken);
let _liveFeedEmails = getLiveFeedEmails();
let _jobkey = await createEmailJob(oada, _docType, _liveFeedEmails, _emails, _userToken);
let _config = {
result: "success",
destinationPath: _tnUserEndpoint,
tnUserEndpoint: _tnUserEndpoint,
emailsToNotify: _emailsToNotify,
emails: _emails,
liveFeeEmails: _liveFeedEmails,
tradingPartnerId: _tradingPartnerId,
jobkey: _jobkey,
notifications: notifications,
dailyDigest: _list
};
return _config;
}//end notifyUser
service.start().catch(e => console.error('Service threw uncaught error: ', e))
/*
*TODO: define a set of actions related to trellis-notifications
*
*/
/*
new RulesWorker({
name: "trellis-notifications",
conn: service.getClient(DOMAIN).clone(TOKEN),
actions: [
{
name: "notify-fsqa-emails",
service: "trellis-notifications",
type: "application/json",
description: "send a notification",
notifyUser
}
]
});*/