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.

60 lines
1.6 KiB

8 years ago
  1. class FollowRemoteUserService
  2. include GrapeRouteHelpers::NamedRouteMatcher
  3. def call(user)
  4. username, domain = user.split('@')
  5. account = Account.where(username: username, domain: domain).first
  6. return account unless account.nil?
  7. account = Account.new(username: username, domain: domain)
  8. data = Goldfinger.finger("acct:#{user}")
  9. account.remote_url = data.link('http://schemas.google.com/g/2010#updates-from').href
  10. account.salmon_url = data.link('salmon').href
  11. account.public_key = magic_key_to_pem(data.link('magic-public-key').href)
  12. account.private_key = nil
  13. account.secret = SecureRandom.hex
  14. account.verify_token = SecureRandom.hex
  15. feed = get_feed(account.remote_url)
  16. hubs = feed.xpath('//xmlns:link[@rel="hub"]')
  17. return false if hubs.empty? || hubs.first.attribute('href').nil?
  18. account.hub_url = hubs.first.attribute('href').value
  19. account.save!
  20. subscription = account.subscription(subscription_url(account))
  21. subscription.subscribe
  22. rescue Goldfinger::Error, HTTP::Error => e
  23. false
  24. end
  25. private
  26. def get_feed(url)
  27. response = http_client.get(Addressable::URI.parse(url))
  28. Nokogiri::XML(response)
  29. end
  30. def magic_key_to_pem(magic_key)
  31. _, modulus, exponent = magic_key.split('.')
  32. modulus, exponent = [modulus, exponent].map { |n| Base64.urlsafe_decode64(n).bytes.inject(0) { |num, byte| (num << 8) | byte } }
  33. key = OpenSSL::PKey::RSA.new
  34. key.n = modulus
  35. key.d = exponent
  36. key.to_pem
  37. end
  38. def http_client
  39. HTTP
  40. end
  41. def subscription_url(account)
  42. "https://649841dc.ngrok.io/api#{subscriptions_path(id: account.id)}"
  43. end
  44. end