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.

69 lines
2.0 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. #
  14. class DomainBlock < ApplicationRecord
  15. include DomainNormalizable
  16. enum severity: [:silence, :suspend, :noop]
  17. validates :domain, presence: true, uniqueness: true
  18. has_many :accounts, foreign_key: :domain, primary_key: :domain
  19. delegate :count, to: :accounts, prefix: true
  20. scope :matches_domain, ->(value) { where(arel_table[:domain].matches("%#{value}%")) }
  21. class << self
  22. def suspend?(domain)
  23. !!rule_for(domain)&.suspend?
  24. end
  25. def silence?(domain)
  26. !!rule_for(domain)&.silence?
  27. end
  28. def reject_media?(domain)
  29. !!rule_for(domain)&.reject_media?
  30. end
  31. def reject_reports?(domain)
  32. !!rule_for(domain)&.reject_reports?
  33. end
  34. alias blocked? suspend?
  35. def rule_for(domain)
  36. return if domain.blank?
  37. uri = Addressable::URI.new.tap { |u| u.host = domain.gsub(/[\/]/, '') }
  38. segments = uri.normalized_host.split('.')
  39. variants = segments.map.with_index { |_, i| segments[i..-1].join('.') }
  40. where(domain: variants[0..-2]).order(Arel.sql('char_length(domain) desc')).first
  41. end
  42. end
  43. def stricter_than?(other_block)
  44. return true if suspend?
  45. return false if other_block.suspend? && (silence? || noop?)
  46. return false if other_block.silence? && noop?
  47. (reject_media || !other_block.reject_media) && (reject_reports || !other_block.reject_reports)
  48. end
  49. def affected_accounts_count
  50. scope = suspend? ? accounts.where(suspended_at: created_at) : accounts.where(silenced_at: created_at)
  51. scope.count
  52. end
  53. end