1 # == Schema Information
 
   3 # Table name: user_blocks
 
   5 #  id             :integer          not null, primary key
 
   6 #  user_id        :bigint           not null
 
   7 #  creator_id     :bigint           not null
 
   8 #  reason         :text             not null
 
   9 #  ends_at        :datetime         not null
 
  10 #  needs_view     :boolean          default(FALSE), not null
 
  12 #  created_at     :datetime
 
  13 #  updated_at     :datetime
 
  14 #  reason_format  :enum             default("markdown"), not null
 
  15 #  deactivates_at :datetime
 
  19 #  index_user_blocks_on_creator_id_and_id  (creator_id,id)
 
  20 #  index_user_blocks_on_user_id            (user_id)
 
  24 #  user_blocks_moderator_id_fkey  (creator_id => users.id)
 
  25 #  user_blocks_revoker_id_fkey    (revoker_id => users.id)
 
  26 #  user_blocks_user_id_fkey       (user_id => users.id)
 
  29 class UserBlock < ApplicationRecord
 
  30   validate :moderator_permissions
 
  31   validates :reason, :characters => true, :length => { :maximum => 10000 }
 
  32   validates :deactivates_at, :comparison => { :greater_than_or_equal_to => :ends_at }, :unless => -> { needs_view }
 
  33   validates :deactivates_at, :absence => true, :if => -> { needs_view }
 
  35   belongs_to :user, :class_name => "User"
 
  36   belongs_to :creator, :class_name => "User"
 
  37   belongs_to :revoker, :class_name => "User", :optional => true
 
  39   PERIODS = Settings.user_block_periods
 
  42   # scope to match active blocks
 
  44     where("needs_view or ends_at > ?", Time.now.utc)
 
  48   # return a renderable version of the reason text.
 
  50     RichText.new(self[:reason_format], self[:reason])
 
  54   # returns true if the block is currently active (i.e: the user can't
 
  57     needs_view || ends_at > Time.now.utc
 
  61   # returns true if the block is a "zero hour" block
 
  63     # if the times differ more than 1 minute we probably have more important issues
 
  64     needs_view && (ends_at.to_i - updated_at.to_i) < 60
 
  68   # revokes the block, allowing the user to use the API again. the argument
 
  69   # is the user object who is revoking the ban.
 
  72       :ends_at => Time.now.utc,
 
  73       :deactivates_at => Time.now.utc,
 
  74       :revoker_id => revoker.id,
 
  82   # validate that only moderators are allowed to change the
 
  83   # block. this should be caught and dealt with in the controller,
 
  84   # but i've also included it here just in case.
 
  85   def moderator_permissions
 
  86     errors.add(:base, I18n.t("user_blocks.model.non_moderator_update")) if creator_id_changed? && !creator.moderator?
 
  87     errors.add(:base, I18n.t("user_blocks.model.non_moderator_revoke")) if revoker_id_changed? && !revoker_id.nil? && !revoker.moderator?