闭社主体 forked from https://github.com/tootsuite/mastodon
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.4 KiB

  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. COOLDOWN_PERIOD = 30.days.freeze
  16. belongs_to :account
  17. belongs_to :target_account, class_name: 'Account'
  18. before_validation :set_target_account
  19. before_validation :set_followers_count
  20. validates :acct, presence: true, domain: { acct: true }
  21. validate :validate_migration_cooldown
  22. validate :validate_target_account
  23. scope :within_cooldown, ->(now = Time.now.utc) { where(arel_table[:created_at].gteq(now - COOLDOWN_PERIOD)) }
  24. attr_accessor :current_password, :current_username
  25. def save_with_challenge(current_user)
  26. if current_user.encrypted_password.present?
  27. errors.add(:current_password, :invalid) unless current_user.valid_password?(current_password)
  28. else
  29. errors.add(:current_username, :invalid) unless account.username == current_username
  30. end
  31. return false unless errors.empty?
  32. save
  33. end
  34. def cooldown_at
  35. created_at + COOLDOWN_PERIOD
  36. end
  37. def acct=(val)
  38. super(val.to_s.strip.gsub(/\A@/, ''))
  39. end
  40. private
  41. def set_target_account
  42. self.target_account = ResolveAccountService.new.call(acct)
  43. rescue Goldfinger::Error, HTTP::Error, OpenSSL::SSL::SSLError, Mastodon::Error
  44. # Validation will take care of it
  45. end
  46. def set_followers_count
  47. self.followers_count = account.followers_count
  48. end
  49. def validate_target_account
  50. if target_account.nil?
  51. errors.add(:acct, I18n.t('migrations.errors.not_found'))
  52. else
  53. errors.add(:acct, I18n.t('migrations.errors.missing_also_known_as')) unless target_account.also_known_as.include?(ActivityPub::TagManager.instance.uri_for(account))
  54. errors.add(:acct, I18n.t('migrations.errors.already_moved')) if account.moved_to_account_id.present? && account.moved_to_account_id == target_account.id
  55. errors.add(:acct, I18n.t('migrations.errors.move_to_self')) if account.id == target_account.id
  56. end
  57. end
  58. def validate_migration_cooldown
  59. errors.add(:base, I18n.t('migrations.errors.on_cooldown')) if account.migrations.within_cooldown.exists?
  60. end
  61. end