email_digest_agent.rb 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. 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.
  15. MD
  16. def default_options
  17. {
  18. 'subject' => "You have some notifications!",
  19. 'headline' => "Your notifications:",
  20. 'expected_receive_period_in_days' => "2"
  21. }
  22. end
  23. def receive(incoming_events)
  24. incoming_events.each do |event|
  25. self.memory['queue'] ||= []
  26. self.memory['queue'] << event.payload
  27. self.memory['events'] ||= []
  28. self.memory['events'] << event.id
  29. end
  30. end
  31. def check
  32. if self.memory['queue'] && self.memory['queue'].length > 0
  33. ids = self.memory['events'].join(",")
  34. groups = self.memory['queue'].map { |payload| present(payload) }
  35. recipients.each do |recipient|
  36. log "Sending digest mail to #{recipient} with events [#{ids}]"
  37. SystemMailer.send_message(
  38. to: recipient,
  39. from: interpolated['from'],
  40. subject: interpolated['subject'],
  41. headline: interpolated['headline'],
  42. groups: groups
  43. ).deliver_later
  44. end
  45. self.memory['queue'] = []
  46. self.memory['events'] = []
  47. end
  48. end
  49. end
  50. end