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.

85 lines
2.5 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. class FollowRemoteAccountService < BaseService
  2. # Find or create a local account for a remote user.
  3. # When creating, look up the user's webfinger and fetch all
  4. # important information from their feed
  5. # @param [String] uri User URI in the form of username@domain
  6. # @param [Boolean] subscribe Whether to initiate a PubSubHubbub subscription
  7. # @return [Account]
  8. def call(uri, subscribe = true)
  9. username, domain = uri.split('@')
  10. return Account.find_local(username) if domain == Rails.configuration.x.local_domain
  11. account = Account.find_by(username: username, domain: domain)
  12. if account.nil?
  13. account = Account.new(username: username, domain: domain)
  14. elsif account.subscribed?
  15. return account
  16. end
  17. data = Goldfinger.finger("acct:#{uri}")
  18. account.remote_url = data.link('http://schemas.google.com/g/2010#updates-from').href
  19. account.salmon_url = data.link('salmon').href
  20. account.url = data.link('http://webfinger.net/rel/profile-page').href
  21. account.public_key = magic_key_to_pem(data.link('magic-public-key').href)
  22. account.private_key = nil
  23. feed = get_feed(account.remote_url)
  24. hubs = feed.xpath('//xmlns:link[@rel="hub"]')
  25. return nil if hubs.empty? || hubs.first.attribute('href').nil? || feed.at_xpath('/xmlns:feed/xmlns:author/xmlns:uri').nil?
  26. account.uri = feed.at_xpath('/xmlns:feed/xmlns:author/xmlns:uri').content
  27. account.hub_url = hubs.first.attribute('href').value
  28. get_profile(feed, account)
  29. account.save!
  30. if subscribe
  31. account.secret = SecureRandom.hex
  32. account.verify_token = SecureRandom.hex
  33. subscription = account.subscription(api_subscription_url(account.id))
  34. subscription.subscribe
  35. account.save!
  36. end
  37. return account
  38. rescue Goldfinger::Error, HTTP::Error
  39. nil
  40. end
  41. private
  42. def get_feed(url)
  43. response = http_client.get(Addressable::URI.parse(url))
  44. Nokogiri::XML(response)
  45. end
  46. def get_profile(xml, account)
  47. author = xml.at_xpath('/xmlns:feed/xmlns:author')
  48. update_remote_profile_service.(author, account)
  49. end
  50. def magic_key_to_pem(magic_key)
  51. _, modulus, exponent = magic_key.split('.')
  52. modulus, exponent = [modulus, exponent].map { |n| Base64.urlsafe_decode64(n).bytes.inject(0) { |num, byte| (num << 8) | byte } }
  53. key = OpenSSL::PKey::RSA.new
  54. key.n = modulus
  55. key.e = exponent
  56. key.to_pem
  57. end
  58. def update_remote_profile_service
  59. @update_remote_profile_service ||= UpdateRemoteProfileService.new
  60. end
  61. def http_client
  62. HTTP
  63. end
  64. end