Sha256: 48b3a6a6662ca1c1200cc38803fe3066ed4f799982c2516309f20d0f2a106adc

Contents?: true

Size: 984 Bytes

Versions: 20

Compression:

Stored size: 984 Bytes

Contents

module JsChat
  module Errors
    class Flooding < JsChat::Error ; end
    class StillFlooding < Exception ; end
  end

  module FloodProtection 
    def seen!
      @activity_log ||= []
      @activity_log << Time.now.utc
      @activity_log.shift if @activity_log.size > 50
      remove_old_activity_logs
      detect_flooding

      if flooding?
        if @still_flooding
          raise JsChat::Errors::StillFlooding
        else
          @still_flooding = true
          raise JsChat::Errors::Flooding.new(:flooding, 'Please wait a few seconds before responding')
        end
      elsif @still_flooding
        @still_flooding = false
      end
    end

    def detect_flooding
      @flooding = @activity_log.size > 10 and @activity_log.sort.inject { |i, sum| sum.to_i - i.to_i } - @activity_log.first.to_i < 0.5
    end

    def flooding?
      @flooding
    end

    def remove_old_activity_logs
      @activity_log.delete_if { |l| l + 5 < Time.now.utc }
    end
  end
end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
jschat-0.3.7 lib/jschat/flood_protection.rb
jschat-0.3.6 lib/jschat/flood_protection.rb
jschat-0.3.5 lib/jschat/flood_protection.rb
jschat-0.3.3 lib/jschat/flood_protection.rb
jschat-0.3.2 lib/jschat/flood_protection.rb
jschat-0.3.1 lib/jschat/flood_protection.rb
jschat-0.3.0 lib/jschat/flood_protection.rb
jschat-0.2.9 lib/jschat/flood_protection.rb
jschat-0.2.8 lib/jschat/flood_protection.rb
jschat-0.2.7 lib/jschat/flood_protection.rb
jschat-0.2.6 lib/jschat/flood_protection.rb
jschat-0.2.5 lib/jschat/flood_protection.rb
jschat-0.2.4 lib/jschat/flood_protection.rb
jschat-0.2.3 lib/jschat/flood_protection.rb
jschat-0.2.2 lib/jschat/flood_protection.rb
jschat-0.2.1 lib/jschat/flood_protection.rb
jschat-0.2.0 lib/jschat/flood_protection.rb
jschat-0.1.5 lib/jschat/flood_protection.rb
jschat-0.1.2 lib/jschat/flood_protection.rb
jschat-0.1.1 lib/jschat/flood_protection.rb