adioso_agent.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. module Agents
  2. class AdiosoAgent < Agent
  3. cannot_receive_events!
  4. default_schedule "every_1d"
  5. description <<~MD
  6. The Adioso Agent will tell you the minimum airline prices between a pair of cities, and within a certain period of time.
  7. The currency is USD. Please make sure that the difference between `start_date` and `end_date` is less than 150 days. You will need to contact [Adioso](http://adioso.com/) for a `username` and `password`.
  8. MD
  9. event_description <<~MD
  10. If flights are present then events look like:
  11. {
  12. "cost": 75.23,
  13. "date": "June 25, 2013",
  14. "route": "New York to Chicago"
  15. }
  16. otherwise
  17. {
  18. "nonetodest": "No flights found to the specified destination"
  19. }
  20. MD
  21. def default_options
  22. {
  23. 'start_date' => Date.today.httpdate[0..15],
  24. 'end_date' => Date.today.plus_with_duration(100).httpdate[0..15],
  25. 'from' => "New York",
  26. 'to' => "Chicago",
  27. 'username' => "xx",
  28. 'password' => "xx",
  29. 'expected_update_period_in_days' => "1"
  30. }
  31. end
  32. def working?
  33. event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
  34. end
  35. def validate_options
  36. unless %w[
  37. start_date end_date from to username password expected_update_period_in_days
  38. ].all? { |field| options[field].present? }
  39. errors.add(:base, "All fields are required")
  40. end
  41. end
  42. def date_to_unix_epoch(date)
  43. date.to_time.to_i
  44. end
  45. def check
  46. auth_options = {
  47. basic_auth: {
  48. username: interpolated[:username],
  49. password: interpolated[:password]
  50. }
  51. }
  52. parse_response = HTTParty.get(
  53. "http://api.adioso.com/v2/search/parse?#{{ q: "#{interpolated[:from]} to #{interpolated[:to]}" }.to_query}",
  54. auth_options
  55. )
  56. fare_request = parse_response["search_url"].gsub(
  57. /(end=)(\d*)([^\d]*)(\d*)/,
  58. "\\1#{date_to_unix_epoch(interpolated['end_date'])}\\3#{date_to_unix_epoch(interpolated['start_date'])}"
  59. )
  60. fare = HTTParty.get fare_request, auth_options
  61. if fare["warnings"]
  62. create_event payload: fare["warnings"]
  63. else
  64. event = fare["results"].min_by { |x| x["cost"] }
  65. event["date"] = Time.at(event["date"]).to_date.httpdate[0..15]
  66. event["route"] = "#{interpolated['from']} to #{interpolated['to']}"
  67. create_event payload: event
  68. end
  69. end
  70. end
  71. end