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.

73 lines
2.3 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: domain_blocks
  5. #
  6. # id :bigint(8) not null, primary key
  7. # domain :string default(""), not null
  8. # created_at :datetime not null
  9. # updated_at :datetime not null
  10. # severity :integer default("silence")
  11. # reject_media :boolean default(FALSE), not null
  12. # reject_reports :boolean default(FALSE), not null
  13. # private_comment :text
  14. # public_comment :text
  15. #
  16. class DomainBlock < ApplicationRecord
  17. include DomainNormalizable
  18. enum severity: [:silence, :suspend, :noop]
  19. validates :domain, presence: true, uniqueness: true, domain: true
  20. has_many :accounts, foreign_key: :domain, primary_key: :domain
  21. delegate :count, to: :accounts, prefix: true
  22. scope :matches_domain, ->(value) { where(arel_table[:domain].matches("%#{value}%")) }
  23. scope :with_user_facing_limitations, -> { where(severity: [:silence, :suspend]).or(where(reject_media: true)) }
  24. scope :by_severity, -> { order(Arel.sql('(CASE severity WHEN 0 THEN 1 WHEN 1 THEN 2 WHEN 2 THEN 0 END), reject_media, domain')) }
  25. class << self
  26. def suspend?(domain)
  27. !!rule_for(domain)&.suspend?
  28. end
  29. def silence?(domain)
  30. !!rule_for(domain)&.silence?
  31. end
  32. def reject_media?(domain)
  33. !!rule_for(domain)&.reject_media?
  34. end
  35. def reject_reports?(domain)
  36. !!rule_for(domain)&.reject_reports?
  37. end
  38. alias blocked? suspend?
  39. def rule_for(domain)
  40. return if domain.blank?
  41. uri = Addressable::URI.new.tap { |u| u.host = domain.gsub(/[\/]/, '') }
  42. segments = uri.normalized_host.split('.')
  43. variants = segments.map.with_index { |_, i| segments[i..-1].join('.') }
  44. where(domain: variants).order(Arel.sql('char_length(domain) desc')).first
  45. end
  46. end
  47. def stricter_than?(other_block)
  48. return true if suspend?
  49. return false if other_block.suspend? && (silence? || noop?)
  50. return false if other_block.silence? && noop?
  51. (reject_media || !other_block.reject_media) && (reject_reports || !other_block.reject_reports)
  52. end
  53. def affected_accounts_count
  54. scope = suspend? ? accounts.where(suspended_at: created_at) : accounts.where(silenced_at: created_at)
  55. scope.count
  56. end
  57. end