wunderlist_agent.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. module Agents
  2. class WunderlistAgent < Agent
  3. include FormConfigurable
  4. include Oauthable
  5. include WebRequestConcern
  6. valid_oauth_providers :wunderlist
  7. cannot_be_scheduled!
  8. no_bulk_receive!
  9. gem_dependency_check { Devise.omniauth_providers.include?(:wunderlist) }
  10. description <<-MD
  11. The WunderlistAgent creates new Wunderlist tasks based on the incoming event.
  12. #{'## Include the `omniauth-wunderlist` gem in your `Gemfile` and set `WUNDERLIST_OAUTH_KEY` and `WUNDERLIST_OAUTH_SECRET` in your environment to use this Agent' if dependencies_missing?}
  13. To be able to use this Agent you need to authenticate with Wunderlist in the [Services](/services) section first.
  14. MD
  15. def default_options
  16. {
  17. 'list_id' => '',
  18. 'title' => '{{title}}'
  19. }
  20. end
  21. form_configurable :list_id, roles: :completable
  22. form_configurable :title
  23. def complete_list_id
  24. response = request_guard do
  25. HTTParty.get lists_url, request_options
  26. end
  27. response.map { |p| {text: "#{p['title']} (#{p['id']})", id: p['id']}}
  28. end
  29. def validate_options
  30. errors.add(:base, "you need to specify the list you want to add tasks to") unless options['list_id'].present?
  31. errors.add(:base, "you need to specify the title of the task to create") unless options['title'].present?
  32. end
  33. def working?
  34. !recent_error_logs?
  35. end
  36. def receive(incoming_events)
  37. incoming_events.each do |event|
  38. mo = interpolated(event)
  39. title = mo[:title][0..244]
  40. log("Creating new task '#{title}' on list #{mo[:list_id]}", inbound_event: event)
  41. request_guard do
  42. HTTParty.post tasks_url, request_options.merge(body: {title: title, list_id: mo[:list_id].to_i}.to_json)
  43. end
  44. end
  45. end
  46. private
  47. def request_guard(&blk)
  48. response = yield
  49. error("Error during http request: #{response.body}") if response.code > 400
  50. response
  51. end
  52. def lists_url
  53. "https://a.wunderlist.com/api/v1/lists"
  54. end
  55. def tasks_url
  56. "https://a.wunderlist.com/api/v1/tasks"
  57. end
  58. def request_options
  59. {:headers => {'Content-Type' => 'application/json',
  60. 'User-Agent' => user_agent,
  61. 'X-Access-Token' => service.token,
  62. 'X-Client-ID' => ENV["WUNDERLIST_OAUTH_KEY"] }}
  63. end
  64. end
  65. end