email_digest_agent.rb 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 working?
  26. received_event_without_error?
  27. end
  28. def receive(incoming_events)
  29. incoming_events.each do |event|
  30. self.memory['queue'] ||= []
  31. self.memory['queue'] << event.payload
  32. self.memory['events'] ||= []
  33. self.memory['events'] << event.id
  34. end
  35. end
  36. def check
  37. if self.memory['queue'] && self.memory['queue'].length > 0
  38. ids = self.memory['events'].join(",")
  39. groups = self.memory['queue'].map { |payload| present(payload) }
  40. recipients.each do |recipient|
  41. begin
  42. SystemMailer.send_message(
  43. to: recipient,
  44. from: interpolated['from'],
  45. subject: interpolated['subject'],
  46. headline: interpolated['headline'],
  47. content_type: interpolated['content_type'],
  48. groups: groups
  49. ).deliver_now
  50. log "Sent digest mail to #{recipient} with events [#{ids}]"
  51. rescue => e
  52. error("Error sending digest mail to #{recipient} with events [#{ids}]: #{e.message}")
  53. raise
  54. end
  55. end
  56. self.memory['queue'] = []
  57. self.memory['events'] = []
  58. end
  59. end
  60. end
  61. end