2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2013-02-06 03:16:51 +08:00
|
|
|
class RateLimiter
|
|
|
|
|
2013-02-26 00:42:20 +08:00
|
|
|
# A rate limit has been exceeded.
|
2015-03-23 09:20:50 +08:00
|
|
|
class LimitExceeded < StandardError
|
2017-12-04 18:44:16 +08:00
|
|
|
attr_reader :type, :available_in
|
2015-09-25 00:25:09 +08:00
|
|
|
|
2015-09-25 01:52:32 +08:00
|
|
|
def initialize(available_in, type = nil)
|
2013-02-06 03:16:51 +08:00
|
|
|
@available_in = available_in
|
2015-09-25 01:52:32 +08:00
|
|
|
@type = type
|
2013-02-06 03:16:51 +08:00
|
|
|
end
|
2015-09-25 00:25:09 +08:00
|
|
|
|
|
|
|
def description
|
2018-06-19 07:48:03 +08:00
|
|
|
time_left =
|
|
|
|
if @available_in <= 3
|
|
|
|
I18n.t("rate_limiter.short_time")
|
|
|
|
elsif @available_in < 1.minute.to_i
|
|
|
|
I18n.t("rate_limiter.seconds", count: @available_in)
|
|
|
|
elsif @available_in < 1.hour.to_i
|
|
|
|
I18n.t("rate_limiter.minutes", count: (@available_in / 1.minute.to_i))
|
|
|
|
else
|
|
|
|
I18n.t("rate_limiter.hours", count: (@available_in / 1.hour.to_i))
|
|
|
|
end
|
2015-09-25 01:52:32 +08:00
|
|
|
|
|
|
|
if @type.present?
|
2016-03-07 23:56:17 +08:00
|
|
|
type_key = @type.tr("-", "_")
|
2015-09-25 01:52:32 +08:00
|
|
|
msg = I18n.t("rate_limiter.by_type.#{type_key}", time_left: time_left, default: "")
|
|
|
|
return msg if msg.present?
|
|
|
|
end
|
|
|
|
|
2015-09-25 00:25:09 +08:00
|
|
|
I18n.t("rate_limiter.too_many_requests", time_left: time_left)
|
|
|
|
end
|
2013-02-06 03:16:51 +08:00
|
|
|
end
|
|
|
|
|
2013-02-26 00:42:20 +08:00
|
|
|
end
|