You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.4 KiB

  1. # frozen_string_literal: true
  2. class Pubsubhubbub::SubscribeService < BaseService
  3. URL_PATTERN = /\A#{URI.regexp(%w(http https))}\z/
  4. attr_reader :account, :callback, :secret, :lease_seconds
  5. def call(account, callback, secret, lease_seconds)
  6. @account = account
  7. @callback = Addressable::URI.parse(callback).normalize.to_s
  8. @secret = secret
  9. @lease_seconds = lease_seconds
  10. process_subscribe
  11. end
  12. private
  13. def process_subscribe
  14. case subscribe_status
  15. when :invalid_topic
  16. ['Invalid topic URL', 422]
  17. when :invalid_callback
  18. ['Invalid callback URL', 422]
  19. when :callback_not_allowed
  20. ['Callback URL not allowed', 403]
  21. when :valid
  22. confirm_subscription
  23. ['', 202]
  24. end
  25. end
  26. def subscribe_status
  27. if account.nil?
  28. :invalid_topic
  29. elsif !valid_callback?
  30. :invalid_callback
  31. elsif blocked_domain?
  32. :callback_not_allowed
  33. else
  34. :valid
  35. end
  36. end
  37. def confirm_subscription
  38. subscription = locate_subscription
  39. Pubsubhubbub::ConfirmationWorker.perform_async(subscription.id, 'subscribe', secret, lease_seconds)
  40. end
  41. def valid_callback?
  42. callback.present? && callback =~ URL_PATTERN
  43. end
  44. def blocked_domain?
  45. DomainBlock.blocked? Addressable::URI.parse(callback).host
  46. end
  47. def locate_subscription
  48. Subscription.where(account: account, callback_url: callback).first_or_create!(account: account, callback_url: callback)
  49. end
  50. end