email_digest_agent.rb 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. module Agents
  2. class EmailDigestAgent < Agent
  3. include EmailConcern
  4. default_schedule "5am"
  5. cannot_create_events!
  6. description <<-MD
  7. The Email Digest Agent collects any Events sent to it and sends them all via email when scheduled.
  8. By default, the will have a `subject` and an optional `headline` before listing the Events. If the Events'
  9. payloads contain a `message`, that will be highlighted, otherwise everything in
  10. their payloads will be shown.
  11. You can specify one or more `recipients` for the email, or skip the option in order to send the email to your
  12. account's default email address.
  13. You can provide a `from` address for the email, or leave it blank to default to the value of `EMAIL_FROM_ADDRESS` (`#{ENV['EMAIL_FROM_ADDRESS']}`).
  14. You can provide a `content_type` for the email and specify `text/plain` or `text/html` to be sent.
  15. If you do not specify `content_type`, then the recipient email server will determine the correct rendering.
  16. Set `expected_receive_period_in_days` to the maximum amount of time that you'd expect to pass between Events being received by this Agent.
  17. MD
  18. def default_options
  19. {
  20. 'subject' => "You have some notifications!",
  21. 'headline' => "Your notifications:",
  22. 'expected_receive_period_in_days' => "2"
  23. }
  24. end
  25. def receive(incoming_events)
  26. incoming_events.each do |event|
  27. self.memory['queue'] ||= []
  28. self.memory['queue'] << event.payload
  29. self.memory['events'] ||= []
  30. self.memory['events'] << event.id
  31. end
  32. end
  33. def check
  34. if self.memory['queue'] && self.memory['queue'].length > 0
  35. ids = self.memory['events'].join(",")
  36. groups = self.memory['queue'].map { |payload| present(payload) }
  37. recipients.each do |recipient|
  38. log "Sending digest mail to #{recipient} with events [#{ids}]"
  39. SystemMailer.send_message(
  40. to: recipient,
  41. from: interpolated['from'],
  42. subject: interpolated['subject'],
  43. headline: interpolated['headline'],
  44. content_type: interpolated['content_type'],
  45. groups: groups
  46. ).deliver_later
  47. end
  48. self.memory['queue'] = []
  49. self.memory['events'] = []
  50. end
  51. end
  52. end
  53. end