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.

35 lines
1.1 KiB

  1. # frozen_string_literal: true
  2. class SubscribeService < BaseService
  3. def call(account)
  4. account.secret = SecureRandom.hex
  5. subscription = account.subscription(api_subscription_url(account.id))
  6. response = subscription.subscribe
  7. if response_failed_permanently?(response)
  8. # An error in the 4xx range (except for 429, which is rate limiting)
  9. # means we're not allowed to subscribe. Fail and move on
  10. account.secret = ''
  11. account.save!
  12. elsif response_successful?(response)
  13. # Anything in the 2xx range means the subscription will be confirmed
  14. # asynchronously, we've done what we needed to do
  15. account.save!
  16. else
  17. # What's left is the 5xx range and 429, which means we need to retry
  18. # at a later time. Fail loudly!
  19. raise "Subscription attempt failed for #{account.acct} (#{account.hub_url}): HTTP #{response.code}"
  20. end
  21. end
  22. private
  23. def response_failed_permanently?(response)
  24. response.code > 299 && response.code < 500 && response.code != 429
  25. end
  26. def response_successful?(response)
  27. response.code > 199 && response.code < 300
  28. end
  29. end