|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# == Schema Information |
| 4 | +# |
| 5 | +# Table name: account_migrations |
| 6 | +# |
| 7 | +# id :bigint(8) not null, primary key |
| 8 | +# account_id :bigint(8) |
| 9 | +# acct :string default(""), not null |
| 10 | +# followers_count :bigint(8) default(0), not null |
| 11 | +# target_account_id :bigint(8) |
| 12 | +# created_at :datetime not null |
| 13 | +# updated_at :datetime not null |
| 14 | +# |
| 15 | + |
| 16 | +class AccountMigration < ApplicationRecord |
| 17 | + COOLDOWN_PERIOD = 30.days.freeze |
| 18 | + |
| 19 | + belongs_to :account |
| 20 | + belongs_to :target_account, class_name: 'Account' |
| 21 | + |
| 22 | + before_validation :set_target_account |
| 23 | + before_validation :set_followers_count |
| 24 | + |
| 25 | + validates :acct, presence: true, domain: { acct: true } |
| 26 | + validate :validate_migration_cooldown |
| 27 | + validate :validate_target_account |
| 28 | + |
| 29 | + scope :within_cooldown, ->(now = Time.now.utc) { where(arel_table[:created_at].gteq(now - COOLDOWN_PERIOD)) } |
| 30 | + |
| 31 | + attr_accessor :current_password, :current_username |
| 32 | + |
| 33 | + def save_with_challenge(current_user) |
| 34 | + if current_user.encrypted_password.present? |
| 35 | + errors.add(:current_password, :invalid) unless current_user.valid_password?(current_password) |
| 36 | + else |
| 37 | + errors.add(:current_username, :invalid) unless account.username == current_username |
| 38 | + end |
| 39 | + |
| 40 | + return false unless errors.empty? |
| 41 | + |
| 42 | + save |
| 43 | + end |
| 44 | + |
| 45 | + def cooldown_at |
| 46 | + created_at + COOLDOWN_PERIOD |
| 47 | + end |
| 48 | + |
| 49 | + private |
| 50 | + |
| 51 | + def set_target_account |
| 52 | + self.target_account = ResolveAccountService.new.call(acct) |
| 53 | + rescue Goldfinger::Error, HTTP::Error, OpenSSL::SSL::SSLError, Mastodon::Error |
| 54 | + # Validation will take care of it |
| 55 | + end |
| 56 | + |
| 57 | + def set_followers_count |
| 58 | + self.followers_count = account.followers_count |
| 59 | + end |
| 60 | + |
| 61 | + def validate_target_account |
| 62 | + if target_account.nil? |
| 63 | + errors.add(:acct, I18n.t('migrations.errors.not_found')) |
| 64 | + else |
| 65 | + errors.add(:acct, I18n.t('migrations.errors.missing_also_known_as')) unless target_account.also_known_as.include?(ActivityPub::TagManager.instance.uri_for(account)) |
| 66 | + errors.add(:acct, I18n.t('migrations.errors.already_moved')) if account.moved_to_account_id.present? && account.moved_to_account_id == target_account.id |
| 67 | + errors.add(:acct, I18n.t('migrations.errors.move_to_self')) if account.id == target_account.id |
| 68 | + end |
| 69 | + end |
| 70 | + |
| 71 | + def validate_migration_cooldown |
| 72 | + errors.add(:base, I18n.t('migrations.errors.on_cooldown')) if account.migrations.within_cooldown.exists? |
| 73 | + end |
| 74 | +end |
0 commit comments