account_alias.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: account_aliases
  5. #
  6. # id :bigint(8) not null, primary key
  7. # account_id :bigint(8)
  8. # acct :string default(""), not null
  9. # uri :string default(""), not null
  10. # created_at :datetime not null
  11. # updated_at :datetime not null
  12. #
  13. class AccountAlias < ApplicationRecord
  14. belongs_to :account
  15. validates :acct, presence: true, domain: { acct: true }
  16. validates :uri, uniqueness: { scope: :account_id }
  17. validate :validate_target_account
  18. before_validation :set_uri
  19. after_create :add_to_account
  20. after_destroy :remove_from_account
  21. def acct=(val)
  22. val = val.to_s.strip
  23. super(val.start_with?('@') ? val[1..] : val)
  24. end
  25. def pretty_acct
  26. username, domain = acct.split('@', 2)
  27. domain.nil? ? username : "#{username}@#{Addressable::IDNA.to_unicode(domain)}"
  28. end
  29. private
  30. def set_uri
  31. target_account = ResolveAccountService.new.call(acct)
  32. self.uri = ActivityPub::TagManager.instance.uri_for(target_account) unless target_account.nil?
  33. rescue Webfinger::Error, HTTP::Error, OpenSSL::SSL::SSLError, Mastodon::Error
  34. # Validation will take care of it
  35. end
  36. def add_to_account
  37. account.update(also_known_as: account.also_known_as + [uri])
  38. end
  39. def remove_from_account
  40. account.update(also_known_as: account.also_known_as.reject { |x| x == uri })
  41. end
  42. def validate_target_account
  43. if uri.blank?
  44. errors.add(:acct, I18n.t('migrations.errors.not_found'))
  45. elsif ActivityPub::TagManager.instance.uri_for(account) == uri
  46. errors.add(:acct, I18n.t('migrations.errors.move_to_self'))
  47. end
  48. end
  49. end