finder_concern.rb 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # frozen_string_literal: true
  2. module Account::FinderConcern
  3. extend ActiveSupport::Concern
  4. class_methods do
  5. def find_local!(username)
  6. find_local(username) || raise(ActiveRecord::RecordNotFound)
  7. end
  8. def find_remote!(username, domain)
  9. find_remote(username, domain) || raise(ActiveRecord::RecordNotFound)
  10. end
  11. def representative
  12. actor = Account.find(-99).tap(&:ensure_keys!)
  13. actor.update!(username: 'mastodon.internal') if actor.username.include?(':')
  14. actor
  15. rescue ActiveRecord::RecordNotFound
  16. Account.create!(id: -99, actor_type: 'Application', locked: true, username: 'mastodon.internal')
  17. end
  18. def find_local(username)
  19. find_remote(username, nil)
  20. end
  21. def find_remote(username, domain)
  22. AccountFinder.new(username, domain).account
  23. end
  24. end
  25. class AccountFinder
  26. attr_reader :username, :domain
  27. def initialize(username, domain)
  28. @username = username
  29. @domain = domain
  30. end
  31. def account
  32. scoped_accounts.order(id: :asc).take
  33. end
  34. private
  35. def scoped_accounts
  36. Account.unscoped.tap do |scope|
  37. scope.merge! with_usernames
  38. scope.merge! matching_username
  39. scope.merge! matching_domain
  40. end
  41. end
  42. def with_usernames
  43. Account.where.not(Account.arel_table[:username].lower.eq '')
  44. end
  45. def matching_username
  46. Account.where(Account.arel_table[:username].lower.eq username.to_s.downcase)
  47. end
  48. def matching_domain
  49. Account.where(Account.arel_table[:domain].lower.eq(domain.nil? ? nil : domain.to_s.downcase))
  50. end
  51. end
  52. end