boxcar_agent.rb 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. module Agents
  2. class BoxcarAgent < Agent
  3. cannot_be_scheduled!
  4. cannot_create_events!
  5. API_URL = 'https://new.boxcar.io/api/notifications'
  6. description <<-MD
  7. The Boxcar agent sends push notifications to iPhone.
  8. To be able to use the Boxcar end-user API, you need your `Access Token`.
  9. The access token is available on general "Settings" screen of Boxcar iOS
  10. app or from Boxcar Web Inbox settings page.
  11. Please provide your access token in the `user_credentials` option. If
  12. you'd like to use a credential, set the `user_credentials` option to `{%
  13. credential CREDENTIAL_NAME %}`.
  14. Options:
  15. * `user_credentials` - Boxcar access token.
  16. * `title` - Title of the message.
  17. * `body` - Body of the message.
  18. * `source_name` - Name of the source of the message. Set to `Huginn` by default.
  19. * `icon_url` - URL to the icon.
  20. * `sound` - Sound to be played for the notification. Set to 'bird-1' by default.
  21. MD
  22. def default_options
  23. {
  24. 'user_credentials' => '',
  25. 'title' => "{{title}}",
  26. 'body' => "{{body}}",
  27. 'source_name' => "Huginn",
  28. 'icon_url' => "",
  29. 'sound' => "bird-1"
  30. }
  31. end
  32. def working?
  33. received_event_without_error?
  34. end
  35. def strip(string)
  36. (string || '').strip
  37. end
  38. def validate_options
  39. errors.add(:base, "you need to specify a boxcar api key") if options['user_credentials'].blank?
  40. end
  41. def receive(incoming_events)
  42. incoming_events.each do |event|
  43. payload_interpolated = interpolated(event)
  44. user_credentials = payload_interpolated['user_credentials']
  45. post_params = {
  46. 'user_credentials' => user_credentials,
  47. 'notification' => {
  48. 'title' => strip(payload_interpolated['title']),
  49. 'long_message' => strip(payload_interpolated['body']),
  50. 'source_name' => payload_interpolated['source_name'],
  51. 'sound' => payload_interpolated['sound'],
  52. 'icon_url' => payload_interpolated['icon_url']
  53. }
  54. }
  55. send_notification(post_params)
  56. end
  57. end
  58. def send_notification(post_params)
  59. response = HTTParty.post(API_URL, :query => post_params)
  60. raise StandardError, response['error']['message'] if response['error'].present?
  61. if response['Response'].present? && response['Response'] == "Not authorized"
  62. raise StandardError, response['Response']
  63. end
  64. if !response['id'].present?
  65. raise StandardError, "Invalid response from Boxcar: #{response}"
  66. end
  67. end
  68. end
  69. end