about summary refs log tree commit diff
path: root/app/validators/follow_limit_validator.rb
blob: c619cb9a3327ae4d068a248c0c27c472ca6875be (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
# frozen_string_literal: true

class FollowLimitValidator < ActiveModel::Validator
  LIMIT = ENV.fetch('MAX_FOLLOWS_THRESHOLD', 7_500).to_i
  RATIO = ENV.fetch('MAX_FOLLOWS_RATIO', 1.1).to_f

  def validate(follow)
    return if follow.account.nil? || !follow.account.local?

    follow.errors.add(:base, I18n.t('users.follow_limit_reached', limit: self.class.limit_for_account(follow.account))) if limit_reached?(follow.account)
  end

  class << self
    def limit_for_account(account)
      if account.following_count < LIMIT
        LIMIT
      else
        [(account.followers_count * RATIO).round, LIMIT].max
      end
    end
  end

  private

  def limit_reached?(account)
    account.following_count >= self.class.limit_for_account(account)
  end
end