1
0

user_location_agent.rb 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. require 'securerandom'
  2. module Agents
  3. class UserLocationAgent < Agent
  4. cannot_be_scheduled!
  5. description do
  6. <<-MD
  7. The UserLocationAgent creates events based on WebHook POSTS that contain a `latitude` and `longitude`. You can use the POSTLocation iOS app to post your location.
  8. Your POST path will be `https://#{ENV['DOMAIN']}/users/#{user.id}/update_location/:secret` where `:secret` is specified in your options.
  9. MD
  10. end
  11. event_description <<-MD
  12. Assuming you're using the iOS application, events look like this:
  13. {
  14. "latitude": "37.12345",
  15. "longitude": "-122.12345",
  16. "timestamp": "123456789.0",
  17. "altitude": "22.0",
  18. "horizontal_accuracy": "5.0",
  19. "vertical_accuracy": "3.0",
  20. "speed": "0.52595",
  21. "course": "72.0703",
  22. "device_token": "..."
  23. }
  24. MD
  25. def working?
  26. event_created_within?(2) && !recent_error_logs?
  27. end
  28. def default_options
  29. { 'secret' => SecureRandom.hex(7) }
  30. end
  31. def validate_options
  32. errors.add(:base, "secret is required and must be longer than 4 characters") unless options['secret'].present? && options['secret'].length > 4
  33. end
  34. def receive(incoming_events)
  35. incoming_events.each do |event|
  36. interpolate_with(event) do
  37. handle_payload event.payload
  38. end
  39. end
  40. end
  41. def receive_web_request(params, method, format)
  42. params = params.symbolize_keys
  43. if method != 'post'
  44. return ['Not Found', 404]
  45. end
  46. if interpolated['secret'] != params[:secret]
  47. return ['Not Authorized', 401]
  48. end
  49. handle_payload params.except(:secret)
  50. return ['ok', 200]
  51. end
  52. private
  53. def handle_payload(payload)
  54. location = Location.new(payload)
  55. if location.present?
  56. create_event payload: payload, location: location
  57. end
  58. end
  59. end
  60. end