jabber_agent.rb 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. module Agents
  2. class JabberAgent < Agent
  3. cannot_be_scheduled!
  4. cannot_create_events!
  5. description <<-MD
  6. The JabberAgent will send any events it receives to your Jabber/XMPP IM account.
  7. Specify the `jabber_server` and `jabber_port` for your Jabber server.
  8. The `message` is sent from `jabber_sender` to `jaber_receiver`. This message
  9. can contain any keys found in the source's payload, escaped using double curly braces.
  10. ex: `"News Story: <$.title>: <$.url>"`
  11. MD
  12. def default_options
  13. {
  14. 'jabber_server' => '127.0.0.1',
  15. 'jabber_port' => '5222',
  16. 'jabber_sender' => 'huginn@localhost',
  17. 'jabber_receiver' => 'muninn@localhost',
  18. 'jabber_password' => '',
  19. 'message' => 'It will be <$.temp> out tomorrow',
  20. 'expected_receive_period_in_days' => "2"
  21. }
  22. end
  23. def working?
  24. last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  25. end
  26. def receive(incoming_events)
  27. incoming_events.each do |event|
  28. log "Sending IM to #{options['jabber_receiver']} with event #{event.id}"
  29. deliver body(event)
  30. end
  31. end
  32. def validate_options
  33. errors.add(:base, "server and username is required") unless credentials_present?
  34. end
  35. def deliver(text)
  36. client.send Jabber::Message::new(options['jabber_receiver'], text).set_type(:chat)
  37. end
  38. private
  39. def client
  40. Jabber::Client.new(Jabber::JID::new(options['jabber_sender'])).tap do |sender|
  41. sender.connect(options['jabber_server'], (options['jabber_port'] || '5222'))
  42. sender.auth(options['jabber_password'])
  43. end
  44. end
  45. def credentials_present?
  46. options['jabber_server'].present? && options['jabber_sender'].present? && options['jabber_receiver'].present?
  47. end
  48. def body(event)
  49. Utils.interpolate_jsonpaths(options['message'], event.payload)
  50. end
  51. end
  52. end