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.

53 lines
1.3 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,
  5. :lease_seconds, :domain
  6. def call(account, callback, secret, lease_seconds, verified_domain = nil)
  7. @account = account
  8. @callback = Addressable::URI.parse(callback).normalize.to_s
  9. @secret = secret
  10. @lease_seconds = lease_seconds
  11. @domain = verified_domain
  12. process_subscribe
  13. end
  14. private
  15. def process_subscribe
  16. if account.nil?
  17. ['Invalid topic URL', 422]
  18. elsif !valid_callback?
  19. ['Invalid callback URL', 422]
  20. elsif blocked_domain?
  21. ['Callback URL not allowed', 403]
  22. else
  23. confirm_subscription
  24. ['', 202]
  25. end
  26. end
  27. def confirm_subscription
  28. subscription = locate_subscription
  29. Pubsubhubbub::ConfirmationWorker.perform_async(subscription.id, 'subscribe', secret, lease_seconds)
  30. end
  31. def valid_callback?
  32. callback.present? && callback =~ URL_PATTERN
  33. end
  34. def blocked_domain?
  35. DomainBlock.blocked? Addressable::URI.parse(callback).host
  36. end
  37. def locate_subscription
  38. subscription = Subscription.find_or_initialize_by(account: account, callback_url: callback)
  39. subscription.domain = domain
  40. subscription.save!
  41. subscription
  42. end
  43. end