post_agent.rb 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. module Agents
  2. class PostAgent < Agent
  3. include WebRequestConcern
  4. include FileHandling
  5. consumes_file_pointer!
  6. MIME_RE = /\A\w+\/.+\z/
  7. can_dry_run!
  8. no_bulk_receive!
  9. default_schedule "never"
  10. description do
  11. <<-MD
  12. 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`.
  13. The `post_url` field must specify where you would like to send requests. Please include the URI scheme (`http` or `https`).
  14. The `method` used can be any of `get`, `post`, `put`, `patch`, and `delete`.
  15. By default, non-GETs will be sent with form encoding (`application/x-www-form-urlencoded`).
  16. Change `content_type` to `json` to send JSON instead.
  17. Change `content_type` to `xml` to send XML, where the name of the root element may be specified using `xml_root`, defaulting to `post`.
  18. When `content_type` contains a [MIME](https://en.wikipedia.org/wiki/Media_type) type, and `payload` is a string, its interpolated value will be sent as a string in the HTTP request's body and the request's `Content-Type` HTTP header will be set to `content_type`. When `payload` is a string `no_merge` has to be set to `true`.
  19. 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
  20. will be attempted by this Agent, so the Event's "body" value will always be raw text.
  21. The Event will also have a "headers" hash and a "status" integer value.
  22. Set `event_headers_style` to one of the following values to normalize the keys of "headers" for downstream agents' convenience:
  23. * `capitalized` (default) - Header names are capitalized; e.g. "Content-Type"
  24. * `downcased` - Header names are downcased; e.g. "content-type"
  25. * `snakecased` - Header names are snakecased; e.g. "content_type"
  26. * `raw` - Backward compatibility option to leave them unmodified from what the underlying HTTP library returns.
  27. Other Options:
  28. * `headers` - When present, it should be a hash of headers to send with the request.
  29. * `basic_auth` - Specify HTTP basic auth parameters: `"username:password"`, or `["username", "password"]`.
  30. * `disable_ssl_verification` - Set to `true` to disable ssl verification.
  31. * `user_agent` - A custom User-Agent name (default: "Faraday v#{Faraday::VERSION}").
  32. #{receiving_file_handling_agent_description}
  33. When receiving a `file_pointer` the request will be sent with multipart encoding (`multipart/form-data`) and `content_type` is ignored. `upload_key` can be used to specify the parameter in which the file will be sent, it defaults to `file`.
  34. MD
  35. end
  36. event_description <<-MD
  37. Events look like this:
  38. {
  39. "status": 200,
  40. "headers": {
  41. "Content-Type": "text/html",
  42. ...
  43. },
  44. "body": "<html>Some data...</html>"
  45. }
  46. MD
  47. def default_options
  48. {
  49. 'post_url' => "http://www.example.com",
  50. 'expected_receive_period_in_days' => '1',
  51. 'content_type' => 'form',
  52. 'method' => 'post',
  53. 'payload' => {
  54. 'key' => 'value',
  55. 'something' => 'the event contained {{ somekey }}'
  56. },
  57. 'headers' => {},
  58. 'emit_events' => 'false',
  59. 'no_merge' => 'false'
  60. }
  61. end
  62. def working?
  63. last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  64. end
  65. def method
  66. (interpolated['method'].presence || 'post').to_s.downcase
  67. end
  68. def validate_options
  69. unless options['post_url'].present? && options['expected_receive_period_in_days'].present?
  70. errors.add(:base, "post_url and expected_receive_period_in_days are required fields")
  71. end
  72. if options['payload'].present? && %w[get delete].include?(method) && !options['payload'].is_a?(Hash)
  73. errors.add(:base, "if provided, payload must be a hash")
  74. end
  75. if options['payload'].present? && %w[post put patch].include?(method)
  76. if !options['payload'].is_a?(Hash) && options['content_type'] !~ MIME_RE
  77. errors.add(:base, "if provided, payload must be a hash")
  78. end
  79. if options['content_type'] =~ MIME_RE && options['payload'].is_a?(String) && boolify(options['no_merge']) != true
  80. errors.add(:base, "when the payload is a string, `no_merge` has to be set to `true`")
  81. end
  82. end
  83. if options.has_key?('emit_events') && boolify(options['emit_events']).nil?
  84. errors.add(:base, "if provided, emit_events must be true or false")
  85. end
  86. begin
  87. normalize_response_headers({})
  88. rescue ArgumentError => e
  89. errors.add(:base, e.message)
  90. end
  91. unless %w[post get put delete patch].include?(method)
  92. errors.add(:base, "method must be 'post', 'get', 'put', 'delete', or 'patch'")
  93. end
  94. if options['no_merge'].present? && !%[true false].include?(options['no_merge'].to_s)
  95. errors.add(:base, "if provided, no_merge must be 'true' or 'false'")
  96. end
  97. unless headers.is_a?(Hash)
  98. errors.add(:base, "if provided, headers must be a hash")
  99. end
  100. validate_web_request_options!
  101. end
  102. def receive(incoming_events)
  103. incoming_events.each do |event|
  104. interpolate_with(event) do
  105. outgoing = interpolated['payload'].presence || {}
  106. if boolify(interpolated['no_merge'])
  107. handle outgoing, event, headers(interpolated[:headers])
  108. else
  109. handle outgoing.merge(event.payload), event, headers(interpolated[:headers])
  110. end
  111. end
  112. end
  113. end
  114. def check
  115. handle interpolated['payload'].presence || {}, headers
  116. end
  117. private
  118. def normalize_response_headers(headers)
  119. case interpolated['event_headers_style']
  120. when nil, '', 'capitalized'
  121. normalize = ->name {
  122. name.gsub(/(?:\A|(?<=-))([[:alpha:]])|([[:alpha:]]+)/) {
  123. $1 ? $1.upcase : $2.downcase
  124. }
  125. }
  126. when 'downcased'
  127. normalize = :downcase.to_proc
  128. when 'snakecased', nil
  129. normalize = ->name { name.tr('A-Z-', 'a-z_') }
  130. when 'raw'
  131. normalize = ->name { name } # :itself.to_proc in Ruby >= 2.2
  132. else
  133. raise ArgumentError, "if provided, event_headers_style must be 'capitalized', 'downcased', 'snakecased' or 'raw'"
  134. end
  135. headers.each_with_object({}) { |(key, value), hash|
  136. hash[normalize[key]] = value
  137. }
  138. end
  139. def handle(data, event = Event.new, headers)
  140. url = interpolated(event.payload)[:post_url]
  141. case method
  142. when 'get', 'delete'
  143. params, body = data, nil
  144. when 'post', 'put', 'patch'
  145. params = nil
  146. content_type =
  147. if has_file_pointer?(event)
  148. data[interpolated(event.payload)['upload_key'].presence || 'file'] = get_upload_io(event)
  149. nil
  150. else
  151. interpolated(event.payload)['content_type']
  152. end
  153. case content_type
  154. when 'json'
  155. headers['Content-Type'] = 'application/json; charset=utf-8'
  156. body = data.to_json
  157. when 'xml'
  158. headers['Content-Type'] = 'text/xml; charset=utf-8'
  159. body = data.to_xml(root: (interpolated(event.payload)[:xml_root] || 'post'))
  160. when MIME_RE
  161. headers['Content-Type'] = content_type
  162. body = data.to_s
  163. else
  164. body = data
  165. end
  166. else
  167. error "Invalid method '#{method}'"
  168. end
  169. response = faraday.run_request(method.to_sym, url, body, headers) { |request|
  170. request.params.update(params) if params
  171. }
  172. if boolify(interpolated['emit_events'])
  173. create_event payload: {
  174. body: response.body,
  175. headers: normalize_response_headers(response.headers),
  176. status: response.status
  177. }
  178. end
  179. end
  180. end
  181. end