account_migration.rb 2.6 KB

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