adioso_agent.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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/)
  8. for a `username` and `password`.
  9. MD
  10. event_description <<-MD
  11. If flights are present then events look like:
  12. {
  13. "cost": 75.23,
  14. "date": "June 25, 2013",
  15. "route": "New York to Chicago"
  16. }
  17. otherwise
  18. {
  19. "nonetodest": "No flights found to the specified destination"
  20. }
  21. MD
  22. def default_options
  23. {
  24. 'start_date' => Date.today.httpdate[0..15],
  25. 'end_date' => Date.today.plus_with_duration(100).httpdate[0..15],
  26. 'from' => "New York",
  27. 'to' => "Chicago",
  28. 'username' => "xx",
  29. 'password' => "xx",
  30. 'expected_update_period_in_days' => "1"
  31. }
  32. end
  33. def working?
  34. event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
  35. end
  36. def validate_options
  37. unless %w[start_date end_date from to username password expected_update_period_in_days].all? { |field| options[field].present? }
  38. errors.add(:base, "All fields are required")
  39. end
  40. end
  41. def date_to_unix_epoch(date)
  42. date.to_time.to_i
  43. end
  44. def check
  45. auth_options = {:basic_auth => {:username =>interpolated[:username], :password=>interpolated['password']}}
  46. parse_response = HTTParty.get "http://api.adioso.com/v2/search/parse?q=#{URI.encode(interpolated['from'])}+to+#{URI.encode(interpolated['to'])}", auth_options
  47. fare_request = parse_response["search_url"].gsub /(end=)(\d*)([^\d]*)(\d*)/, "\\1#{date_to_unix_epoch(interpolated['end_date'])}\\3#{date_to_unix_epoch(interpolated['start_date'])}"
  48. fare = HTTParty.get fare_request, auth_options
  49. if fare["warnings"]
  50. create_event :payload => fare["warnings"]
  51. else
  52. event = fare["results"].min {|a,b| a["cost"] <=> b["cost"]}
  53. event["date"] = Time.at(event["date"]).to_date.httpdate[0..15]
  54. event["route"] = "#{interpolated['from']} to #{interpolated['to']}"
  55. create_event :payload => event
  56. end
  57. end
  58. end
  59. end