growl_agent.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. module Agents
  2. class GrowlAgent < Agent
  3. attr_reader :growler
  4. cannot_be_scheduled!
  5. cannot_create_events!
  6. gem_dependency_check { defined?(Growl) }
  7. description <<-MD
  8. #{'## Include `ruby-growl` in your Gemfile to use this Agent!' if dependencies_missing?}
  9. The GrowlAgent sends any events it receives to a Growl GNTP server immediately.
  10. It is assumed that events have a `message` or `text` key, which will hold the body of the growl notification, and a `subject` key, which will have the headline of the Growl notification. You can use Event Formatting Agent if your event does not provide these keys.
  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. 'growl_server' => 'localhost',
  16. 'growl_password' => '',
  17. 'growl_app_name' => 'HuginnGrowl',
  18. 'growl_notification_name' => 'Notification',
  19. 'expected_receive_period_in_days' => "2"
  20. }
  21. end
  22. def working?
  23. last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  24. end
  25. def validate_options
  26. unless options['growl_server'].present? && options['expected_receive_period_in_days'].present?
  27. errors.add(:base, "growl_server and expected_receive_period_in_days are required fields")
  28. end
  29. end
  30. def register_growl
  31. @growler = Growl.new interpolated['growl_server'], interpolated['growl_app_name'], "GNTP"
  32. @growler.password = interpolated['growl_password']
  33. @growler.add_notification interpolated['growl_notification_name']
  34. end
  35. def notify_growl(subject, message)
  36. @growler.notify(interpolated['growl_notification_name'], subject, message)
  37. end
  38. def receive(incoming_events)
  39. register_growl
  40. incoming_events.each do |event|
  41. message = (event.payload['message'] || event.payload['text']).to_s
  42. subject = event.payload['subject'].to_s
  43. if message.present? && subject.present?
  44. log "Sending Growl notification '#{subject}': '#{message}' to #{interpolated(event)['growl_server']} with event #{event.id}"
  45. notify_growl(subject,message)
  46. else
  47. log "Event #{event.id} not sent, message and subject expected"
  48. end
  49. end
  50. end
  51. end
  52. end