discourse/plugins/chat/lib/chat/message_rate_limiter.rb
Joffrey JAFFEUX 12a18d4d55
DEV: properly namespace chat (#20690)
This commit main goal was to comply with Zeitwerk and properly rely on autoloading. To achieve this, most resources have been namespaced under the `Chat` module.

- Given all models are now namespaced with `Chat::` and would change the stored types in DB when using polymorphism or STI (single table inheritance), this commit uses various Rails methods to ensure proper class is loaded and the stored name in DB is unchanged, eg: `Chat::Message` model will be stored as `"ChatMessage"`, and `"ChatMessage"` will correctly load `Chat::Message` model.
- Jobs are now using constants only, eg: `Jobs::Chat::Foo` and should only be enqueued this way

Notes:
- This commit also used this opportunity to limit the number of registered css files in plugin.rb
- `discourse_dev` support has been removed within this commit and will be reintroduced later

<!-- NOTE: All pull requests should have tests (rspec in Ruby, qunit in JavaScript). If your code does not include test coverage, please include an explanation of why it was omitted. -->
2023-03-17 14:24:38 +01:00

53 lines
1.3 KiB
Ruby

# frozen_string_literal: true
module Chat
class MessageRateLimiter
def self.run!(user)
instance = self.new(user)
instance.run!
end
def initialize(user)
@user = user
end
def run!
return if @user.staff?
allowed_message_count =
(
if @user.trust_level == TrustLevel[0]
SiteSetting.chat_allowed_messages_for_trust_level_0
else
SiteSetting.chat_allowed_messages_for_other_trust_levels
end
)
return if allowed_message_count.zero?
@rate_limiter =
RateLimiter.new(@user, "create_chat_message", allowed_message_count, 30.seconds)
silence_user if @rate_limiter.remaining.zero?
@rate_limiter.performed!
end
def clear!
# Used only for testing. Need to clear the rate limiter between tests.
@rate_limiter.clear! if defined?(@rate_limiter)
end
private
def silence_user
silenced_for_minutes = SiteSetting.chat_auto_silence_duration
return if silenced_for_minutes.zero?
UserSilencer.silence(
@user,
Discourse.system_user,
silenced_till: silenced_for_minutes.minutes.from_now,
reason: I18n.t("chat.errors.rate_limit_exceeded"),
)
end
end
end