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.

64 lines
1.5 KiB

  1. # frozen_string_literal: true
  2. module AccountFinderConcern
  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. Account.find(-99)
  13. rescue ActiveRecord::RecordNotFound
  14. Account.create!(id: -99, actor_type: 'Application', locked: true, username: Rails.configuration.x.local_domain)
  15. end
  16. def find_local(username)
  17. find_remote(username, nil)
  18. end
  19. def find_remote(username, domain)
  20. AccountFinder.new(username, domain).account
  21. end
  22. end
  23. class AccountFinder
  24. attr_reader :username, :domain
  25. def initialize(username, domain)
  26. @username = username
  27. @domain = domain
  28. end
  29. def account
  30. scoped_accounts.order(id: :asc).take
  31. end
  32. private
  33. def scoped_accounts
  34. Account.unscoped.tap do |scope|
  35. scope.merge! with_usernames
  36. scope.merge! matching_username
  37. scope.merge! matching_domain
  38. end
  39. end
  40. def with_usernames
  41. Account.where.not(Account.arel_table[:username].lower.eq '')
  42. end
  43. def matching_username
  44. Account.where(Account.arel_table[:username].lower.eq username.to_s.downcase)
  45. end
  46. def matching_domain
  47. Account.where(Account.arel_table[:domain].lower.eq(domain.nil? ? nil : domain.to_s.downcase))
  48. end
  49. end
  50. end