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.1 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
  2. include ApplicationHelper
  3. def call(uri)
  4. username, domain = uri.split('@')
  5. account = Account.where(username: username, domain: domain).first
  6. if account.nil?
  7. account = Account.new(username: username, domain: domain)
  8. elsif account.subscribed?
  9. return account
  10. end
  11. data = Goldfinger.finger("acct:#{uri}")
  12. account.remote_url = data.link('http://schemas.google.com/g/2010#updates-from').href
  13. account.salmon_url = data.link('salmon').href
  14. account.public_key = magic_key_to_pem(data.link('magic-public-key').href)
  15. account.private_key = nil
  16. account.secret = SecureRandom.hex
  17. account.verify_token = SecureRandom.hex
  18. feed = get_feed(account.remote_url)
  19. hubs = feed.xpath('//xmlns:link[@rel="hub"]')
  20. return nil if hubs.empty? || hubs.first.attribute('href').nil? || feed.at_xpath('/xmlns:feed/xmlns:author/xmlns:uri').nil?
  21. account.uri = feed.at_xpath('/xmlns:feed/xmlns:author/xmlns:uri').content
  22. account.hub_url = hubs.first.attribute('href').value
  23. get_profile(feed, account)
  24. account.save!
  25. subscription = account.subscription(subscription_url(account))
  26. subscription.subscribe
  27. return account
  28. rescue Goldfinger::Error, HTTP::Error => e
  29. nil
  30. end
  31. private
  32. def get_feed(url)
  33. response = http_client.get(Addressable::URI.parse(url))
  34. Nokogiri::XML(response)
  35. end
  36. def get_profile(xml, account)
  37. author = xml.at_xpath('/xmlns:feed/xmlns:author')
  38. if author.at_xpath('./poco:displayName').nil?
  39. account.display_name = account.username
  40. else
  41. account.display_name = author.at_xpath('./poco:displayName').content
  42. end
  43. unless author.at_xpath('./poco:note').nil?
  44. account.note = author.at_xpath('./poco:note').content
  45. end
  46. end
  47. def magic_key_to_pem(magic_key)
  48. _, modulus, exponent = magic_key.split('.')
  49. modulus, exponent = [modulus, exponent].map { |n| Base64.urlsafe_decode64(n).bytes.inject(0) { |num, byte| (num << 8) | byte } }
  50. key = OpenSSL::PKey::RSA.new
  51. key.n = modulus
  52. key.e = exponent
  53. key.to_pem
  54. end
  55. def http_client
  56. HTTP
  57. end
  58. end