1
0

account_alias.rb 1.5 KB

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