digest_email_agent.rb 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. module Agents
  2. class DigestEmailAgent < Agent
  3. MAIN_KEYS = %w[title message text main value].map(&:to_sym)
  4. default_schedule "5am"
  5. cannot_create_events!
  6. description <<-MD
  7. The DigestEmailAgent collects any Events sent to it and sends them all via email when run.
  8. The email will be sent to your account's address and will have a `subject` and an optional `headline` before
  9. listing the Events. If the Events' payloads contain a `:message`, that will be highlighted, otherwise everything in
  10. their payloads will be shown.
  11. 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.
  12. MD
  13. def default_options
  14. {
  15. :subject => "You have some notifications!",
  16. :headline => "Your notifications:",
  17. :expected_receive_period_in_days => "2"
  18. }
  19. end
  20. def working?
  21. last_receive_at && last_receive_at > options[:expected_receive_period_in_days].to_i.days.ago && !recent_error_logs?
  22. end
  23. def validate_options
  24. errors.add(:base, "subject and expected_receive_period_in_days are required") unless options[:subject].present? && options[:expected_receive_period_in_days].present?
  25. end
  26. def receive(incoming_events)
  27. incoming_events.each do |event|
  28. self.memory[:queue] ||= []
  29. self.memory[:queue] << event.payload
  30. end
  31. end
  32. def check
  33. if self.memory[:queue] && self.memory[:queue].length > 0
  34. groups = self.memory[:queue].map { |payload| present(payload) }
  35. log "Sending digest mail to #{user.email}"
  36. SystemMailer.delay.send_message(:to => user.email, :subject => options[:subject], :headline => options[:headline], :groups => groups)
  37. self.memory[:queue] = []
  38. end
  39. end
  40. def present(payload)
  41. if payload.is_a?(Hash)
  42. payload = ActiveSupport::HashWithIndifferentAccess.new(payload)
  43. MAIN_KEYS.each do |key|
  44. return { :title => payload[key].to_s, :entries => present_hash(payload, key) } if payload.has_key?(key)
  45. end
  46. { :title => "Event", :entries => present_hash(payload) }
  47. else
  48. { :title => payload.to_s, :entries => [] }
  49. end
  50. end
  51. def present_hash(hash, skip_key = nil)
  52. hash.to_a.sort_by {|a| a.first.to_s }.map { |k, v| "#{k}: #{v}" unless k.to_s == skip_key.to_s }.compact
  53. end
  54. end
  55. end