email_digest_agent.rb 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. The number of
  8. used events also relies on the `Keep events` option of the emitting Agent, meaning that if events expire before
  9. this agent is scheduled to run, they will not appear in the email.
  10. By default, the email will have a `subject` and an optional `headline` before listing the Events. If the Events'
  11. payloads contain a `message`, that will be highlighted, otherwise everything in
  12. their payloads will be shown.
  13. You can specify one or more `recipients` for the email, or skip the option in order to send the email to your
  14. account's default email address.
  15. 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']}`).
  16. You can provide a `content_type` for the email and specify `text/plain` or `text/html` to be sent.
  17. If you do not specify `content_type`, then the recipient email server will determine the correct rendering.
  18. 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.
  19. MD
  20. def default_options
  21. {
  22. 'subject' => "You have some notifications!",
  23. 'headline' => "Your notifications:",
  24. 'expected_receive_period_in_days' => "2"
  25. }
  26. end
  27. def working?
  28. received_event_without_error?
  29. end
  30. def receive(incoming_events)
  31. self.memory['events'] ||= []
  32. incoming_events.each do |event|
  33. self.memory['events'] << event.id
  34. end
  35. end
  36. def check
  37. if self.memory['events'] && self.memory['events'].length > 0
  38. payloads = received_events.reorder("events.id ASC").where(id: self.memory['events']).pluck(:payload).to_a
  39. groups = payloads.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}"
  51. rescue => e
  52. error("Error sending digest mail to #{recipient}: #{e.message}")
  53. raise
  54. end
  55. end
  56. self.memory['events'] = []
  57. end
  58. end
  59. end
  60. end