account_alias.rb 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. normalizes :acct, with: ->(acct) { acct.strip.delete_prefix('@') }
  22. def pretty_acct
  23. username, domain = acct.split('@', 2)
  24. domain.nil? ? username : "#{username}@#{Addressable::IDNA.to_unicode(domain)}"
  25. end
  26. private
  27. def set_uri
  28. target_account = ResolveAccountService.new.call(acct)
  29. self.uri = ActivityPub::TagManager.instance.uri_for(target_account) unless target_account.nil?
  30. rescue Webfinger::Error, HTTP::Error, OpenSSL::SSL::SSLError, Mastodon::Error
  31. # Validation will take care of it
  32. end
  33. def add_to_account
  34. account.update(also_known_as: account.also_known_as + [uri])
  35. end
  36. def remove_from_account
  37. account.update(also_known_as: account.also_known_as.reject { |x| x == uri })
  38. end
  39. def validate_target_account
  40. if uri.blank?
  41. errors.add(:acct, I18n.t('migrations.errors.not_found'))
  42. elsif ActivityPub::TagManager.instance.uri_for(account) == uri
  43. errors.add(:acct, I18n.t('migrations.errors.move_to_self'))
  44. end
  45. end
  46. end