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.

78 lines
2.4 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
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. # @return [Account]
  7. def call(uri)
  8. username, domain = uri.split('@')
  9. return Account.find_local(username) if TagManager.instance.local_domain?(domain)
  10. return nil if DomainBlock.blocked?(domain)
  11. account = Account.find_remote(username, domain)
  12. return account unless account.nil?
  13. Rails.logger.debug "Creating new remote account for #{uri}"
  14. account = Account.new(username: username, domain: domain)
  15. data = Goldfinger.finger("acct:#{uri}")
  16. account.remote_url = data.link('http://schemas.google.com/g/2010#updates-from').href
  17. account.salmon_url = data.link('salmon').href
  18. account.url = data.link('http://webfinger.net/rel/profile-page').href
  19. account.public_key = magic_key_to_pem(data.link('magic-public-key').href)
  20. account.private_key = nil
  21. feed = get_feed(account.remote_url)
  22. hubs = feed.xpath('//xmlns:link[@rel="hub"]')
  23. if hubs.empty? || hubs.first.attribute('href').nil?
  24. raise Goldfinger::Error, 'No PubSubHubbub hubs found'
  25. end
  26. if feed.at_xpath('/xmlns:feed/xmlns:author/xmlns:uri').nil?
  27. raise Goldfinger::Error, 'No author URI found'
  28. end
  29. account.uri = feed.at_xpath('/xmlns:feed/xmlns:author/xmlns:uri').content
  30. account.hub_url = hubs.first.attribute('href').value
  31. get_profile(feed, account)
  32. account.save!
  33. return account
  34. end
  35. private
  36. def get_feed(url)
  37. response = http_client.get(Addressable::URI.parse(url))
  38. Nokogiri::XML(response)
  39. end
  40. def get_profile(xml, account)
  41. author = xml.at_xpath('/xmlns:feed/xmlns:author')
  42. update_remote_profile_service.call(author, account)
  43. end
  44. def magic_key_to_pem(magic_key)
  45. _, modulus, exponent = magic_key.split('.')
  46. modulus, exponent = [modulus, exponent].map { |n| Base64.urlsafe_decode64(n).bytes.inject(0) { |a, e| (a << 8) | e } }
  47. key = OpenSSL::PKey::RSA.new
  48. key.n = modulus
  49. key.e = exponent
  50. key.to_pem
  51. end
  52. def update_remote_profile_service
  53. @update_remote_profile_service ||= UpdateRemoteProfileService.new
  54. end
  55. def http_client
  56. HTTP.timeout(:per_operation, write: 20, connect: 20, read: 50)
  57. end
  58. end