Nessuna descrizione http://j1x-huginn.herokuapp.com

webhook_agent.rb 2.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. module Agents
  2. class WebhookAgent < Agent
  3. cannot_be_scheduled!
  4. cannot_receive_events!
  5. description do <<-MD
  6. The Webhook Agent will create events by receiving webhooks from any source. In order to create events with this agent, make a POST request to:
  7. ```
  8. https://#{ENV['DOMAIN']}/users/#{user.id}/web_requests/#{id || ':id'}/#{options['secret'] || ':secret'}
  9. ```
  10. #{'The placeholder symbols above will be replaced by their values once the agent is saved.' unless id}
  11. Options:
  12. * `secret` - A token that the host will provide for authentication.
  13. * `expected_receive_period_in_days` - How often you expect to receive
  14. events this way. Used to determine if the agent is working.
  15. * `payload_path` - JSONPath of the attribute in the POST body to be
  16. used as the Event payload. Set to `.` to return the entire message.
  17. If `payload_path` points to an array, Events will be created for each element.
  18. * `verbs` - Comma-separated list of http verbs your agent will accept.
  19. For example, "post,get" will enable POST and GET requests. Defaults
  20. to "post".
  21. * `response` - The response message to the request. Defaults to 'Event Created'.
  22. MD
  23. end
  24. event_description do
  25. <<-MD
  26. The event payload is based on the value of the `payload_path` option,
  27. which is set to `#{interpolated['payload_path']}`.
  28. MD
  29. end
  30. def default_options
  31. { "secret" => "supersecretstring",
  32. "expected_receive_period_in_days" => 1,
  33. "payload_path" => "some_key"
  34. }
  35. end
  36. def receive_web_request(params, method, format)
  37. # check the secret
  38. secret = params.delete('secret')
  39. return ["Not Authorized", 401] unless secret == interpolated['secret']
  40. #check the verbs
  41. verbs = (interpolated['verbs'] || 'post').split(/,/).map { |x| x.strip.downcase }.select { |x| x.present? }
  42. return ["Please use #{verbs.join('/').upcase} requests only", 401] unless verbs.include?(method)
  43. [payload_for(params)].flatten.each do |payload|
  44. create_event(payload: payload)
  45. end
  46. [response_message, 201]
  47. end
  48. def working?
  49. event_created_within?(interpolated['expected_receive_period_in_days']) && !recent_error_logs?
  50. end
  51. def validate_options
  52. unless options['secret'].present?
  53. errors.add(:base, "Must specify a secret for 'Authenticating' requests")
  54. end
  55. end
  56. def payload_for(params)
  57. Utils.value_at(params, interpolated['payload_path']) || {}
  58. end
  59. def response_message
  60. interpolated['response'] || 'Event Created'
  61. end
  62. end
  63. end