wunderlist_agent.rb 2.3 KB

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