growl_agent.rb 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. require 'ruby-growl'
  2. module Agents
  3. class GrowlAgent < Agent
  4. attr_reader :growler
  5. cannot_be_scheduled!
  6. cannot_create_events!
  7. description <<-MD
  8. The GrowlAgent sends any events it receives to a Growl GNTP server immediately.
  9. 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.
  10. 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.
  11. MD
  12. def default_options
  13. {
  14. 'growl_server' => 'localhost',
  15. 'growl_password' => '',
  16. 'growl_app_name' => 'HuginnGrowl',
  17. 'growl_notification_name' => 'Notification',
  18. 'expected_receive_period_in_days' => "2"
  19. }
  20. end
  21. def working?
  22. last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  23. end
  24. def validate_options
  25. unless options['growl_server'].present? && options['expected_receive_period_in_days'].present?
  26. errors.add(:base, "growl_server and expected_receive_period_in_days are required fields")
  27. end
  28. end
  29. def register_growl
  30. @growler = Growl.new interpolated['growl_server'], interpolated['growl_app_name'], "GNTP"
  31. @growler.password = interpolated['growl_password']
  32. @growler.add_notification interpolated['growl_notification_name']
  33. end
  34. def notify_growl(subject, message)
  35. @growler.notify(interpolated['growl_notification_name'], subject, message)
  36. end
  37. def receive(incoming_events)
  38. register_growl
  39. incoming_events.each do |event|
  40. message = (event.payload['message'] || event.payload['text']).to_s
  41. subject = event.payload['subject'].to_s
  42. if message.present? && subject.present?
  43. log "Sending Growl notification '#{subject}': '#{message}' to #{interpolated(event.payload)['growl_server']} with event #{event.id}"
  44. notify_growl(subject,message)
  45. else
  46. log "Event #{event.id} not sent, message and subject expected"
  47. end
  48. end
  49. end
  50. end
  51. end