email.js 2.0 KB

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