email.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { ReactiveCache } from '/imports/reactiveCache';
  2. import { TAPi18n } from '/imports/i18n';
  3. //var nodemailer = require('nodemailer');
  4. import EmailLocalization from '../lib/emailLocalization';
  5. // buffer each user's email text in a queue, then flush them in single email
  6. Meteor.startup(() => {
  7. Notifications.subscribe('email', (user, title, description, params) => {
  8. // add quote to make titles easier to read in email text
  9. const quoteParams = _.clone(params);
  10. ['card', 'list', 'oldList', 'board', 'comment'].forEach(key => {
  11. if (quoteParams[key]) quoteParams[key] = `"${params[key]}"`;
  12. });
  13. ['timeValue', 'timeOldValue'].forEach(key => {
  14. quoteParams[key] = quoteParams[key] ? `${params[key]}` : '';
  15. });
  16. // Get user's preferred language
  17. const lan = user.getLanguage();
  18. const subject = TAPi18n.__(title, params, lan); // the original function has a fault, i believe the title should be used according to original author
  19. const existing = user.getEmailBuffer().length > 0;
  20. const htmlEnabled =
  21. Meteor.settings.public &&
  22. Meteor.settings.public.RICHER_CARD_COMMENT_EDITOR !== false;
  23. const text = `${existing ? `\n${subject}\n` : ''}${
  24. params.user
  25. } ${TAPi18n.__(description, quoteParams, lan)}\n${params.url}`;
  26. user.addEmailBuffer(htmlEnabled ? text.replace(/\n/g, '<br/>') : text);
  27. // unlike setTimeout(func, delay, args),
  28. // Meteor.setTimeout(func, delay) does not accept args :-(
  29. // so we pass userId with closure
  30. const userId = user._id;
  31. Meteor.setTimeout(() => {
  32. const user = ReactiveCache.getUser(userId);
  33. // for each user, in the timed period, only the first call will get the cached content,
  34. // other calls will get nothing
  35. const texts = user.getEmailBuffer();
  36. if (texts.length === 0) return;
  37. // merge the cached content into single email and flush
  38. const html = texts.join('<br/>\n\n');
  39. user.clearEmailBuffer();
  40. try {
  41. // Use EmailLocalization utility to ensure the correct language is used
  42. EmailLocalization.sendEmail({
  43. to: user.emails[0].address.toLowerCase(),
  44. from: Accounts.emailTemplates.from,
  45. subject,
  46. html,
  47. language: user.getLanguage(),
  48. userId: user._id
  49. });
  50. } catch (e) {
  51. return;
  52. }
  53. }, process.env.EMAIL_NOTIFICATION_TIMEOUT || 30000);
  54. });
  55. });