post_agent.rb 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. module Agents
  2. class PostAgent < Agent
  3. include WebRequestConcern
  4. can_dry_run!
  5. default_schedule "never"
  6. description <<-MD
  7. A Post Agent receives events from other agents (or runs periodically), merges those events with the [Liquid-interpolated](https://github.com/cantino/huginn/wiki/Formatting-Events-using-Liquid) contents of `payload`, and sends the results as POST (or GET) requests to a specified url. To skip merging in the incoming event, but still send the interpolated payload, set `no_merge` to `true`.
  8. The `post_url` field must specify where you would like to send requests. Please include the URI scheme (`http` or `https`).
  9. The `method` used can be any of `get`, `post`, `put`, `patch`, and `delete`.
  10. By default, non-GETs will be sent with form encoding (`application/x-www-form-urlencoded`). Change `content_type` to `json` to send JSON instead. Change `content_type` to `xml` to send XML, where the name of the root element may be specified using `xml_root`, defaulting to `post`.
  11. If `emit_events` is set to `true`, the server response will be emitted as an Event and can be fed to a WebsiteAgent for parsing (using its `data_from_event` and `type` options). No data processing
  12. will be attempted by this Agent, so the Event's "body" value will always be raw text.
  13. Other Options:
  14. * `headers` - When present, it should be a hash of headers to send with the request.
  15. * `basic_auth` - Specify HTTP basic auth parameters: `"username:password"`, or `["username", "password"]`.
  16. * `disable_ssl_verification` - Set to `true` to disable ssl verification.
  17. * `user_agent` - A custom User-Agent name (default: "Faraday v#{Faraday::VERSION}").
  18. MD
  19. event_description <<-MD
  20. Events look like this:
  21. {
  22. "status": 200,
  23. "headers": {
  24. "Content-Type": "text/html",
  25. ...
  26. },
  27. "body": "<html>Some data...</html>"
  28. }
  29. MD
  30. def default_options
  31. {
  32. 'post_url' => "http://www.example.com",
  33. 'expected_receive_period_in_days' => '1',
  34. 'content_type' => 'form',
  35. 'method' => 'post',
  36. 'payload' => {
  37. 'key' => 'value',
  38. 'something' => 'the event contained {{ somekey }}'
  39. },
  40. 'headers' => {},
  41. 'emit_events' => 'false'
  42. }
  43. end
  44. def working?
  45. last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  46. end
  47. def method
  48. (interpolated['method'].presence || 'post').to_s.downcase
  49. end
  50. def validate_options
  51. unless options['post_url'].present? && options['expected_receive_period_in_days'].present?
  52. errors.add(:base, "post_url and expected_receive_period_in_days are required fields")
  53. end
  54. if options['payload'].present? && !options['payload'].is_a?(Hash)
  55. errors.add(:base, "if provided, payload must be a hash")
  56. end
  57. if options.has_key?('emit_events') && boolify(options['emit_events']).nil?
  58. errors.add(:base, "if provided, emit_events must be true or false")
  59. end
  60. unless %w[post get put delete patch].include?(method)
  61. errors.add(:base, "method must be 'post', 'get', 'put', 'delete', or 'patch'")
  62. end
  63. if options['no_merge'].present? && !%[true false].include?(options['no_merge'].to_s)
  64. errors.add(:base, "if provided, no_merge must be 'true' or 'false'")
  65. end
  66. unless headers.is_a?(Hash)
  67. errors.add(:base, "if provided, headers must be a hash")
  68. end
  69. validate_web_request_options!
  70. end
  71. def receive(incoming_events)
  72. incoming_events.each do |event|
  73. outgoing = interpolated(event)['payload'].presence || {}
  74. if boolify(interpolated['no_merge'])
  75. handle outgoing, event.payload
  76. else
  77. handle outgoing.merge(event.payload), event.payload
  78. end
  79. end
  80. end
  81. def check
  82. handle interpolated['payload'].presence || {}
  83. end
  84. private
  85. def handle(data, payload = {})
  86. url = interpolated(payload)[:post_url]
  87. headers = headers()
  88. case method
  89. when 'get', 'delete'
  90. params, body = data, nil
  91. when 'post', 'put', 'patch'
  92. params = nil
  93. case interpolated(payload)['content_type']
  94. when 'json'
  95. headers['Content-Type'] = 'application/json; charset=utf-8'
  96. body = data.to_json
  97. when 'xml'
  98. headers['Content-Type'] = 'text/xml; charset=utf-8'
  99. body = data.to_xml(root: (interpolated(payload)[:xml_root] || 'post'))
  100. else
  101. body = data
  102. end
  103. else
  104. error "Invalid method '#{method}'"
  105. end
  106. response = faraday.run_request(method.to_sym, url, body, headers) { |request|
  107. request.params.update(params) if params
  108. }
  109. if boolify(interpolated['emit_events'])
  110. create_event payload: { body: response.body, headers: response.headers, status: response.status }
  111. end
  112. end
  113. end
  114. end