about summary refs log tree commit diff
path: root/app/models/account_alias.rb
blob: 3d0b5d188fd2b8ec594ca0d48cc0a6d167b3d725 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# frozen_string_literal: true

# == Schema Information
#
# Table name: account_aliases
#
#  id         :bigint(8)        not null, primary key
#  account_id :bigint(8)
#  acct       :string           default(""), not null
#  uri        :string           default(""), not null
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class AccountAlias < ApplicationRecord
  belongs_to :account

  validates :acct, presence: true, domain: { acct: true }
  validates :uri, presence: true
  validates :uri, uniqueness: { scope: :account_id }
  validate :validate_target_account

  before_validation :set_uri
  after_create :add_to_account
  after_destroy :remove_from_account

  def acct=(val)
    val = val.to_s.strip
    super(val.start_with?('@') ? val[1..-1] : val)
  end

  private

  def set_uri
    target_account = ResolveAccountService.new.call(acct)
    self.uri       = ActivityPub::TagManager.instance.uri_for(target_account) unless target_account.nil?
  rescue Goldfinger::Error, HTTP::Error, OpenSSL::SSL::SSLError, Mastodon::Error
    # Validation will take care of it
  end

  def add_to_account
    account.update(also_known_as: account.also_known_as + [uri])
  end

  def remove_from_account
    account.update(also_known_as: account.also_known_as.reject { |x| x == uri })
  end

  def validate_target_account
    if uri.nil?
      errors.add(:acct, I18n.t('migrations.errors.not_found'))
    elsif ActivityPub::TagManager.instance.uri_for(account) == uri
      errors.add(:acct, I18n.t('migrations.errors.move_to_self'))
    end
  end
end