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.

63 lines
1.9 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: custom_filters
  5. #
  6. # id :bigint(8) not null, primary key
  7. # account_id :bigint(8)
  8. # expires_at :datetime
  9. # phrase :text default(""), not null
  10. # context :string default([]), not null, is an Array
  11. # whole_word :boolean default(TRUE), not null
  12. # irreversible :boolean default(FALSE), not null
  13. # created_at :datetime not null
  14. # updated_at :datetime not null
  15. #
  16. class CustomFilter < ApplicationRecord
  17. VALID_CONTEXTS = %w(
  18. home
  19. notifications
  20. public
  21. thread
  22. ).freeze
  23. include Expireable
  24. belongs_to :account
  25. validates :phrase, :context, presence: true
  26. validate :context_must_be_valid
  27. validate :irreversible_must_be_within_context
  28. scope :active_irreversible, -> { where(irreversible: true).where(Arel.sql('expires_at IS NULL OR expires_at > NOW()')) }
  29. before_validation :clean_up_contexts
  30. after_commit :remove_cache
  31. def expires_in
  32. return @expires_in if defined?(@expires_in)
  33. return nil if expires_at.nil?
  34. [30.minutes, 1.hour, 6.hours, 12.hours, 1.day, 1.week].find { |expires_in| expires_in.from_now >= expires_at }
  35. end
  36. private
  37. def clean_up_contexts
  38. self.context = Array(context).map(&:strip).map(&:presence).compact
  39. end
  40. def remove_cache
  41. Rails.cache.delete("filters:#{account_id}")
  42. Redis.current.publish("timeline:#{account_id}", Oj.dump(event: :filters_changed))
  43. end
  44. def context_must_be_valid
  45. errors.add(:context, I18n.t('filters.errors.invalid_context')) if context.empty? || context.any? { |c| !VALID_CONTEXTS.include?(c) }
  46. end
  47. def irreversible_must_be_within_context
  48. errors.add(:irreversible, I18n.t('filters.errors.invalid_irreversible')) if irreversible? && !context.include?('home') && !context.include?('notifications')
  49. end
  50. end