-
Notifications
You must be signed in to change notification settings - Fork 96
/
api.js
716 lines (641 loc) · 30.8 KB
/
api.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
/*!
* Copyright 2014 Apereo Foundation (AF) Licensed under the
* Educational Community License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
var _ = require('underscore');
var crypto = require('crypto');
var events = require('events');
var fs = require('fs');
var htmlToText = require('nodemailer-html-to-text').htmlToText;
var juice = require('juice');
var MailParser = require('mailparser').MailParser;
var nodemailer = require('nodemailer');
var path = require('path');
var redback = require('redback');
var stubTransport = require('nodemailer-stub-transport');
var sendmailTransport = require('nodemailer-sendmail-transport');
var util = require('util');
var ContentUtil = require('oae-content/lib/internal/util');
var Context = require('oae-context').Context;
var EmailConfig = require('oae-config').config('oae-email');
var IO = require('oae-util/lib/io');
var Locking = require('oae-util/lib/locking');
var log = require('oae-logger').logger('oae-email');
var OaeModules = require('oae-util/lib/modules');
var Redis = require('oae-util/lib/redis');
var Sanitization = require('oae-util/lib/sanitization');
var Telemetry = require('oae-telemetry').telemetry('oae-email');
var TenantsAPI = require('oae-tenants');
var UIAPI = require('oae-ui');
var Validator = require('oae-util/lib/validator').Validator;
var EmailRateLimiter = null;
// A cache of email templates
var templates = {};
/*!
* Whether or not the server is in debug mode. If true, no emails will ever be sent, instead the email
* data will be logged. This is equivalent to "disabling" emails.
*/
var debug = true;
// The cached connection pool with the configured mail values. This can be smtp, sendmail, ..
var emailTransport = null;
// The interval in which the same email can't be sent out multiple times
var deduplicationInterval = null;
// The configuration for e-mail throttling
var throttleConfig = {
'timespan': null,
'count': null
};
/**
* ## EmailAPI
*
* ### Events
*
* * `debugSent(message)` - If `debug` is enabled, this event is fired and indicates an email was sent from the system. The `message` object, which is a https://www.npmjs.org/package/mailparser object is provided
*
* ### Templates
*
* All emails that are sent are based on an internationalizable template. To load a new template for the system, you must
* create a directory in your OAE module called `emailTemplates`. The directory structure looks like this (using oae-content
* as an example):
*
* * oae-content/ (module directory)
* ** emailTemplates/ (directory that is scanned by oae-email)
* *** default/ (the default templates, chosen if there is no locale)
* **** templateId.meta.json.jst (the "meta" template for template with id "templateId")
* **** templateId.html.jst (the "html" template for template with id "templateId")
* **** templateId.txt.jst (the "text" template for template with id "templateId")
* *** en_CA/ (the en_CA locale templates, used if the receiving user has locale en_CA)
* **** templateId.meta.json.jst
* **** templateId.html.jst
* **** templateId.txt.jst
*
* **The 'default' locale:** The default locale is chosen if the user's locale does not have a template provided for it.
* **The 'meta.json' template:** This template should produce a JSON object that specifies email metadata. This template **must** exist, and should at least provide the "subject" of the email.
* **The 'html' template:** This template provides an HTML-formatted version of the email content. One of HTML and TXT templates must be provided.
* **The 'txt' template:** This template provides a plain-text version of the email content. If this is not provided, the HTML version will be converted to plain-text in replacement. One of HTML and TXT must be provided.
*
* ### JST Files
*
* All templates: meta.json.jst, html.jst and txt.jst are JavaScriptTemplates, and are compiled and rendered using UnderscoreJS:
* http://underscorejs.org/#template
*/
var EmailAPI = module.exports = new events.EventEmitter();
/**
* Initialize the email module.
*
* @param {Object} emailSystemConfig The `email` config object from the system `config.js`. Refer to that file for the configuration options
* @param {Function} callback Standard callback function
* @param {Object} callback.err An error that occurred, if any
*/
var init = module.exports.init = function(emailSystemConfig, callback) {
emailSystemConfig = emailSystemConfig || {};
// Email configuration
debug = (emailSystemConfig.debug !== false);
deduplicationInterval = emailSystemConfig.deduplicationInterval || (7 * 24 * 60 * 60);
emailSystemConfig.throttling = emailSystemConfig.throttling || {};
throttleConfig.count = emailSystemConfig.throttling.count || 10;
throttleConfig.timespan = emailSystemConfig.throttling.timespan || 2 * 60;
// Create the Redback rate limiter for emails
var EmailRedback = redback.use(Redis.getClient(), {'namespace': 'oae-email:redback'});
/*!
* For robust unit tests, any provided timespan needs to cover at least 2 buckets so that when
* we do a count on the rate, we don't risk rolling over to a new interval and miss the emails
* we just sent, resetting the frequency to 0 and intermittently failing the test. Therefore
* we set the bucket interval to be (timespan / 2).
*
* Additionally, when a bucket is incremented in redback, the following 2 buckets are cleared.
* Therefore in order to ensure we don't roll over to a new bucket while incrementing and risking
* our previous bucket getting cleared, we must ensure we have at least 5 buckets so that the
* clearing of the "next 2" buckets does not impact the counting of the "previous 2". (e.g., if
* the current time bucket is 2, redback will clear buckets 3 and 4 while we count back from 0,
* 1 and 2).
*/
var bucketInterval = Math.ceil(throttleConfig.timespan / 2);
EmailRateLimiter = EmailRedback.createRateLimit('email', {
// The rate limiter seems to need at least 5 buckets to work, so lets give it exactly 5 (there are exactly bucket_span / bucket_interval buckets)
'bucket_span': bucketInterval * 5,
'bucket_interval': bucketInterval,
'subject_expiry': throttleConfig.timespan
});
// If there was an existing email transport, we close it.
if (emailTransport) {
emailTransport.close();
emailTransport = null;
}
// Open an email transport
if (debug) {
emailTransport = nodemailer.createTransport(stubTransport());
} else {
if (emailSystemConfig.transport === 'SMTP') {
log().info({'data': emailSystemConfig.smtpTransport}, 'Configuring SMTP email transport.');
emailTransport = nodemailer.createTransport(emailSystemConfig.smtpTransport);
} else if (emailSystemConfig.transport === 'sendmail') {
log().info({'data': emailSystemConfig.sendmailTransport}, 'Configuring Sendmail email transport.');
emailTransport = nodemailer.createTransport(sendmailTransport(emailSystemConfig.sendmailTransport.path));
} else {
log().error({
'err': new Error('Attempted to initialize Email API with invalid mail transport'),
'transport': emailTransport
}, 'Attempted to initialize Email API with invalid mail transport');
return callback({'code': 400, 'msg': 'Misconfigured mail transport'});
}
}
// Add a plugin to include a text version on html only emails
emailTransport.use('compile', htmlToText());
return refreshTemplates(callback);
};
/**
* Refresh the email templates used for sending emails.
*
* @param {Function} callback Standard callback function
* @param {Object} callback.err An error that occurred, if any
*/
var refreshTemplates = module.exports.refreshTemplates = function(callback) {
// Get all the registered OAE modules so we can scan each one for a mail template
var modules = OaeModules.getAvailableModules();
_getTemplatesForModules(__dirname + '/../..', modules, function(err, _templates) {
if (err) {
return callback(err);
}
templates = _templates;
return callback();
});
};
/**
* Send a templated email to a user.
*
* # Hash identity
*
* A hash identity can be provided that is used for the message id. This ID will be used to determine
* if the email has already been sent. This is to avoid situations where an application bug can result
* in emails being sent out repeatedly.
*
* If no hash is provided in the `opts.hash` parameter, then one will be generated based on the contents
* of the message. If the message body is not identical each time the same message is generated, it is
* recommended to provide a hash string that more accurately describes the identity of the message.
*
* For more information on how to configure suppression of duplicate messages and email throttling, see
* the appropriate configuration properties in `config.email` of `config.js`.
*
* @param {String} templateModule The module that provides the template (e.g., 'oae-email')
* @param {String} templateId The id of the template
* @param {User} toUser The user that will be receiving the email. This is accessible in the email templates (e.g., `<%= user.displayName %>`)
* @param {String} toUser.email The email address of the user. If this is not available an error with code 400 is returned and no email is sent
* @param {Object} [data] An object that represents the data of the email. This will be accessible in the email templates (e.g., `<%= data.activity['displayName'] %>`)
* @param {Object} [opts] Additional options
* @param {String} [opts.hash] See method summary for more information
* @param {Function} [callback] Invoked when the email has been sent
* @param {Object} [callback.err] An error that occurred, if any
*/
var sendEmail = module.exports.sendEmail = function(templateModule, templateId, toUser, data, opts, callback) {
data = data || {};
opts = opts || {};
callback = callback || function(err) {
if (err && err.code === 400) {
log().error({'err': err}, 'Failed to deliver due to validation error');
}
};
var validator = new Validator();
validator.check(templateModule, {'code': 400, 'msg': 'Must specify a template module'}).notEmpty();
validator.check(templateId, {'code': 400, 'msg': 'Must specify a template id'}).notEmpty();
validator.check(null, {'code': 400, 'msg': 'Must specify a user when sending an email'}).isObject(toUser);
// Only validate the user email if it was a valid object
if (toUser) {
validator.check(toUser.email, {'code': 400, 'msg': 'User must have a valid email address to receive email'}).isEmail();
}
if (validator.hasErrors()) {
return callback(validator.getFirstError());
}
log().trace({
'templateModule': templateModule,
'templateId': templateId,
'toUser': toUser,
'data': data,
'opts': opts
}, 'Preparing template for mail to be sent.');
var metaTemplate = _getTemplate(templateModule, templateId, 'meta.json');
var htmlTemplate = _getTemplate(templateModule, templateId, 'html');
var txtTemplate = _getTemplate(templateModule, templateId, 'txt');
var sharedLogic = _getTemplate(templateModule, templateId, 'shared');
// Verify the user templates have enough data to send an email
if (!metaTemplate) {
var noMetaTemplateErr = {'code': 500, 'msg': 'No email metadata template existed for user'};
log().error({
'err': new Error(noMetaTemplateErr.msg),
'templateModule': templateModule,
'templateId': templateId,
'toUser': {
'id': toUser.id,
'locale': toUser.locale
}
}, noMetaTemplateErr.msg);
return callback(noMetaTemplateErr);
} else if (!htmlTemplate && !txtTemplate) {
var noContentTemplateErr = {'code': 500, 'msg': 'No email content (text or html) template existed for user'};
log().error({
'err': new Error(noContentTemplateErr.msg),
'templateModule': templateModule,
'templateId': templateId,
'toUser': {
'id': toUser.id,
'locale': toUser.locale
}
}, noContentTemplateErr.msg);
return callback(noContentTemplateErr);
}
var renderedTemplates = {};
var templateCtx = _.extend({}, data, {'user': toUser, 'shared': sharedLogic});
var metaContent = null;
var htmlContent = null;
var txtContent = null;
var metaRendered = _renderTemplate(metaTemplate, templateCtx, toUser.locale);
try {
// Try and parse the meta template into JSON
metaContent = JSON.parse(metaRendered);
} catch (metaErr) {
log().error({
'err': metaErr,
'templateModule': templateModule,
'templateId': templateId,
'rendered': metaRendered,
'toUser': {
'id': toUser.id,
'locale': toUser.locale
}
}, 'Error parsing email metadata template for user');
return callback({'code': 500, 'msg': 'Error parsing email metadata template for user'});
}
// Try and render the html template
if (htmlTemplate) {
try {
htmlContent = _renderTemplate(htmlTemplate, templateCtx, toUser.locale);
} catch (htmlErr) {
log().warn({
'err': htmlErr,
'templateModule': templateModule,
'templateId': templateId,
'toUser': {
'id': toUser.id,
'locale': toUser.locale
}
}, 'Failed to parse email html template for user');
}
}
// Try and render the text template
if (txtTemplate) {
try {
txtContent = _renderTemplate(txtTemplate, templateCtx, toUser.locale);
} catch (txtErr) {
log().warn({
'err': txtErr,
'templateModule': templateModule,
'templateId': templateId,
'toUser': {
'id': toUser.id,
'locale': toUser.locale
}
}, 'Failed to parse email html template for user');
}
}
if (htmlContent || txtContent) {
// If one of HTML or TXT templates managed to render, we will send the email with the content we have
renderedTemplates['meta.json'] = metaContent;
renderedTemplates['html'] = htmlContent;
renderedTemplates['txt'] = txtContent;
} else {
return callback({'code': 500, 'msg': 'Could not parse a suitable content template for user'});
}
// If the `from` header is not set, we generate an intelligent `from` header based on the tenant host
var tenant = TenantsAPI.getTenant(toUser.tenant.alias);
var from = EmailConfig.getValue(tenant.alias, 'general', 'from') || util.format('"Apereo OAE" <noreply@%s>', tenant.host);
// Build the email object that will be sent through nodemailer. The 'from' property can be overridden by
// the meta.json, then we further override that with some hard values
var emailInfo = _.extend({'from': from}, renderedTemplates['meta.json'], {
'to': toUser.email
});
if (renderedTemplates['txt']) {
emailInfo.text = renderedTemplates['txt'];
}
if (renderedTemplates['html']) {
emailInfo.html = renderedTemplates['html'];
}
// Ensure the hash is set and is a valid hex string
opts.hash = _generateMessageHash(emailInfo, opts);
// Set the Message-Id header based on the message hash. We apply the
// tenant host as the FQDN as it improves the spam score by providing
// a source location of the message. We also add the userid of the user
// we sent the message to, so we can determine what user a message was
// sent to in Sendgrid
emailInfo.messageId = util.format('%s.%s@%s', opts.hash, toUser.id.replace(/:/g, '-'), tenant.host);
// If we're not sending out HTML, we can send out the email now
if (!emailInfo.html) {
return _sendEmail(emailInfo, opts, callback);
}
// If we're sending HTML, we should inline all the CSS
_inlineCSS(emailInfo.html, function(err, inlinedHtml) {
if (err) {
log().error({'err': err, 'emailInfo': emailInfo}, 'Unable to inline CSS');
return callback(err);
}
emailInfo.html = inlinedHtml;
return _sendEmail(emailInfo, opts, callback);
});
};
/**
* Sends an email if it hasn't been sent before
*
* @param {Object} emailInfo A NodeMailer email info object containing the header and body information for an email
* @param {Object} opts Additional options
* @param {String} [opts.hash] If specified, it will be used to identify this email
* @param {String} [opts.locale] The locale in which this email is being sent
* @param {Function} callback Standard callback function
* @param {Object} callback.err An error that occurred, if any
* @api private
*/
var _sendEmail = function(emailInfo, opts, callback) {
if (emailInfo.subject) {
emailInfo.subject = UIAPI.translate(emailInfo.subject, opts.locale);
}
// We lock the mail for a sufficiently long time
var lockKey = util.format('oae-email-locking:%s', emailInfo.messageId);
Locking.acquire(lockKey, deduplicationInterval, function(err, token) {
if (err) {
log().error({'err': err, 'emailInfo': emailInfo}, 'Unable to lock email id');
return callback(err);
} else if (!token) {
Telemetry.incr('lock.fail');
log().error({'emailInfo': emailInfo}, 'A lock was already in place for this message id. A duplicate email is being delivered');
return callback({'code': 403, 'msg': 'This email has already been sent out'});
}
// Ensure we're not sending out too many emails to a single user within the last timespan
EmailRateLimiter.count(emailInfo.to, throttleConfig.timespan, function(err, count) {
if (err) {
log().error({'err': err}, 'Failed to perform email throttle check');
return callback({'code': 500, 'msg': 'Failed to perform email throttle check'});
} else if (count > (throttleConfig.count - 1)) {
Telemetry.incr('throttled');
log().warn({'to': emailInfo.to}, 'Throttling in effect');
return callback({'code': 403, 'msg': 'Throttling in effect'});
}
// We will proceed to send an email, so add it to the rate-limit counts
EmailRateLimiter.add(emailInfo.to, function(err) {
if (err) {
log().warn({'err': err, 'to': emailInfo.to}, 'An unexpected error occurred trying to increment email rate-limit counts');
}
// We got a lock and aren't throttled, send our mail
emailTransport.sendMail(emailInfo, function(err, info) {
if (err) {
log().error({'err': err, 'to': emailInfo.to, 'subject': emailInfo.subject}, 'Error sending email to recipient');
return callback(err);
}
// If we're debugging we log the mail that would have been sent
if (debug) {
log().info({'to': emailInfo.to, 'subject': emailInfo.subject}, 'Sending email');
// Parse the email so our unit tests can inspect the result
var mailparser = new MailParser();
mailparser.on('end', function(email_object){
EmailAPI.emit('debugSent', email_object);
return callback();
});
mailparser.write(info.response);
mailparser.end();
} else {
return callback();
}
});
});
});
});
};
/**
* If there is an html body present in the `emailInfo`, inline the CSS properties into the style attribute of each element.
*
* @param {Object} html The HTML that contains the CSS that should be inlined
* @param {Function} callback Standard callback function
* @param {Object} callback.err An error that occurred, if any
* @param {Object} callback.inlinedHtml The resulting inlined HTML
* @api private
*/
var _inlineCSS = function(html, callback) {
juice.juiceContent(html, {'url': 'http://'}, callback);
};
/**
* Get the templates for a list of modules.
*
* @param {String} basedir The base directory where the module folders are located
* @param {String[]} modules The list of modules for which to retrieve templates
* @param {Function} callback Standard callback function
* @param {Object} callback.err An error that occurred, if any
* @param {Object} callback.templates An object keyed by module whose value are the templates
* @api private
*/
var _getTemplatesForModules = function(basedir, modules, callback, _templates) {
_templates = _templates || {};
if (_.isEmpty(modules)) {
return callback(null, _templates);
}
// Get the email templates for the next module
var module = modules.pop();
_getTemplatesForModule(basedir, module, function(err, templatesForModule) {
if (err) {
return callback(err);
}
_templates[module] = templatesForModule;
return _getTemplatesForModules(basedir, modules, callback, _templates);
});
};
/**
* Get the templates for a module
*
* @param {String} basedir The base directory where the module folders are located
* @param {String} module The module for which to retrieve the templates
* @param {Function} callback Standard callback function
* @param {Object} callback.err An error that occurred, if any
* @param {Object} callback.templates The retrieved templates keyed by their id
* @api private
*/
var _getTemplatesForModule = function(basedir, module, callback) {
// Get all the email templates for this module
var emailTemplatesPath = _templatesPath(basedir, module);
IO.getFileListForFolder(emailTemplatesPath, function(err, files) {
if (err) {
return callback(err);
} else if (_.isEmpty(files)) {
return callback();
}
// Identify a valid template by the existence of a *.meta.json.jst file
var templateIds = {};
_.each(files, function(file) {
var re = /^(.*)\.meta\.json\.jst$/;
if (re.test(file)) {
templateIds[file.replace(re, '$1')] = true;
}
});
templateIds = _.keys(templateIds);
if (_.isEmpty(templateIds)) {
return callback();
}
return _getTemplatesForTemplateIds(basedir, module, templateIds, callback);
});
};
/**
* Get the templates for a list of template ids. The templates that need to be retrieved are the meta.json, txt
* and html templates for each email template id.
*
* @param {String} basedir The base directory where the locale folders are located
* @param {String} module The module for which to retrieve the templates
* @param {String[]} templateIds The ids of the templates to retrieve
* @param {Function} callback Standard callback function
* @param {Object} callback.err An error that occurred, if any
* @param {Object} callback.templates The retrieved templates keyed by their id
* @api private
*/
var _getTemplatesForTemplateIds = function(basedir, module, templateIds, callback, _templates) {
_templates = _templates || {};
if (_.isEmpty(templateIds)) {
return callback(null, _templates);
}
var templateId = templateIds.pop();
var templateMetaPath = _templatesPath(basedir, module, templateId + '.meta.json.jst');
var templateHtmlPath = _templatesPath(basedir, module, templateId + '.html.jst');
var templateTxtPath = _templatesPath(basedir, module, templateId + '.txt.jst');
// Get each template individually
_getTemplateContents(templateMetaPath, function(err, metaTemplate) {
if (err) {
return callback(err);
}
_getTemplateContents(templateHtmlPath, function(err, htmlTemplate) {
if (err) {
return callback(err);
}
_getTemplateContents(templateTxtPath, function(err, txtTemplate) {
if (err) {
return callback(err);
}
var sharedLogic = {};
try {
var templateSharedPath = _templatesPath(basedir, module, templateId + '.shared');
sharedLogic = require(templateSharedPath);
} catch (err) {}
// Attach the templates to the given object of templates
_templates[templateId] = {
'meta.json': metaTemplate,
'html': htmlTemplate,
'txt': txtTemplate,
'shared': sharedLogic
};
return _getTemplatesForTemplateIds(basedir, module, templateIds, callback, _templates);
});
});
});
};
/**
* Get the template at the given path.
*
* @param {String} templatePath The path to the template file to be retrieved
* @param {Function} callback Standard callback function
* @param {Object} callback.err An error that occurred, if any
* @param {Function} callback.template The templates content
* @api private
*/
var _getTemplateContents = function(templatePath, callback) {
fs.exists(templatePath, function(exists) {
if (!exists) {
return callback();
}
fs.readFile(templatePath, 'utf8', function(err, templateContent) {
if (err) {
return callback(err);
}
if (templateContent) {
return callback(null, templateContent);
} else {
return callback({'code': 500, 'msg': 'Template file ' + templatePath + ' had no content'});
}
});
});
};
/**
* Get the path for a template file or directory.
*
* @param {String} basedir The base directory for the templates
* @param {String} module The module for the templates
* @param {String} [locale] The locale for the templates
* @param {String} [template] The full filename for the template (e.g., meta.json.jst)
* @return {String} Returns the path where the locales, template files or specific template file should be found
* @api private
*/
var _templatesPath = function(basedir, module, template) {
var templatePath = util.format('%s/%s/emailTemplates', basedir, module);
if (template) {
templatePath += '/' + template;
}
return templatePath;
};
/**
* Fetch the appropriate template file (either override or base) for the given module, template id and
* template type from the `templates` object. If no template can be found, `null` will be returned.
*
* @param {String} templateModule The module to which the template belongs
* @param {String} templateId The id of the template
* @param {String} templateType The type of template to fetch (i.e., one of 'html', 'txt' or 'meta.json')
* @return {String} The template content that can be used to render the template. If `null`, there was no suitable template for the given criteria.
* @api private
*/
var _getTemplate = function(templateModule, templateId, templateType) {
var template =
templates &&
templates[templateModule] &&
templates[templateModule][templateId] &&
templates[templateModule][templateId][templateType];
return template;
};
/**
* Render an underscore.js template and internationalize the output
*
* @param {String} templateContent The underscore.js template that should be rendered
* @param {Object} data The data that should be fed to the template
* @param {String} locale The locale in which the output should be translated
* @return {String} The rendered content
* @api private
*/
var _renderTemplate = function(templateContent, data, locale) {
return UIAPI.renderTemplate(templateContent, data, locale);
};
/**
* Given email headers and `sendEmail` options, generate a message hash for the message
* that is a valid hexadecimal string
*
* @param {Object} emailInfo The NodeMailer email info object that contains the message headers
* @param {String} [emailInfo.to] The "To" header of the message
* @param {String} [emailInfo.subject] The subject of the message
* @param {String} [emailInfo.txt] The plain text body of the message
* @param {String} [emailInfo.html] The rich HTML body of the message
* @param {Object} opts The options used when invoking `EmailAPI.sendEmail`
* @param {String} [opts.hash] The hash that was specified as an identity of the message, if any
* @return {String} A unique hexidecimal string based either on the specified hash or message content
* @api private
*/
var _generateMessageHash = function(emailInfo, opts) {
var md5sum = crypto.createHash('md5');
if (opts.hash) {
md5sum.update(opts.hash.toString());
// If no unique hash was specified by the user, we will generate one based on the mail data that is available
} else {
md5sum.update(emailInfo['to'] || '');
md5sum.update(emailInfo['subject'] || '');
md5sum.update(emailInfo['txt'] || '');
md5sum.update(emailInfo['html'] || '');
}
return md5sum.digest('hex');
};