闭社主体 forked from https://github.com/tootsuite/mastodon
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.

79 lines
2.2 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
  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.url = data.link('http://webfinger.net/rel/profile-page').href
  15. account.public_key = magic_key_to_pem(data.link('magic-public-key').href)
  16. account.private_key = nil
  17. account.secret = SecureRandom.hex
  18. account.verify_token = SecureRandom.hex
  19. feed = get_feed(account.remote_url)
  20. hubs = feed.xpath('//xmlns:link[@rel="hub"]')
  21. return nil if hubs.empty? || hubs.first.attribute('href').nil? || feed.at_xpath('/xmlns:feed/xmlns:author/xmlns:uri').nil?
  22. account.uri = feed.at_xpath('/xmlns:feed/xmlns:author/xmlns:uri').content
  23. account.hub_url = hubs.first.attribute('href').value
  24. get_profile(feed, account)
  25. account.save!
  26. subscription = account.subscription(subscription_url(account))
  27. subscription.subscribe
  28. return account
  29. rescue Goldfinger::Error, HTTP::Error => e
  30. nil
  31. end
  32. private
  33. def get_feed(url)
  34. response = http_client.get(Addressable::URI.parse(url))
  35. Nokogiri::XML(response)
  36. end
  37. def get_profile(xml, account)
  38. author = xml.at_xpath('/xmlns:feed/xmlns:author')
  39. if author.at_xpath('./poco:displayName').nil?
  40. account.display_name = account.username
  41. else
  42. account.display_name = author.at_xpath('./poco:displayName').content
  43. end
  44. unless author.at_xpath('./poco:note').nil?
  45. account.note = author.at_xpath('./poco:note').content
  46. end
  47. end
  48. def magic_key_to_pem(magic_key)
  49. _, modulus, exponent = magic_key.split('.')
  50. modulus, exponent = [modulus, exponent].map { |n| Base64.urlsafe_decode64(n).bytes.inject(0) { |num, byte| (num << 8) | byte } }
  51. key = OpenSSL::PKey::RSA.new
  52. key.n = modulus
  53. key.e = exponent
  54. key.to_pem
  55. end
  56. def http_client
  57. HTTP
  58. end
  59. end