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. # We're not allowed to subscribe. Fail and move on.
  9. account.secret = ''
  10. account.save!
  11. elsif response_successful?(response)
  12. # The subscription will be confirmed asynchronously.
  13. account.save!
  14. else
  15. # The response was either a 429 rate limit, or a 5xx error.
  16. # We need to retry at a later time. Fail loudly!
  17. raise "Subscription attempt failed for #{account.acct} (#{account.hub_url}): HTTP #{response.code}"
  18. end
  19. end
  20. private
  21. # Any response in the 3xx or 4xx range, except for 429 (rate limit)
  22. def response_failed_permanently?(response)
  23. (response.status.redirect? || response.status.client_error?) && !response.status.too_many_requests?
  24. end
  25. # Any response in the 2xx range
  26. def response_successful?(response)
  27. response.status.success?
  28. end
  29. end