2013-06-10 13:17:09 -04:00
|
|
|
# GroupMessage sends a private message to a group.
|
|
|
|
# It will also avoid sending the same message repeatedly, which can happen with
|
|
|
|
# notifications to moderators when spam is detected.
|
|
|
|
#
|
|
|
|
# Options:
|
|
|
|
#
|
|
|
|
# user: (User) If the message is about a user, pass the user object.
|
|
|
|
# limit_once_per: (seconds) Limit sending the given type of message once every X seconds.
|
|
|
|
# The default is 24 hours. Set to false to always send the message.
|
|
|
|
|
|
|
|
require_dependency 'post_creator'
|
|
|
|
require_dependency 'topic_subtype'
|
|
|
|
require_dependency 'discourse'
|
|
|
|
|
|
|
|
class GroupMessage
|
|
|
|
|
|
|
|
include Rails.application.routes.url_helpers
|
|
|
|
|
2017-07-27 21:20:09 -04:00
|
|
|
def self.create(group_name, message_type, opts = {})
|
2013-06-10 13:17:09 -04:00
|
|
|
GroupMessage.new(group_name, message_type, opts).create
|
|
|
|
end
|
|
|
|
|
2017-07-27 21:20:09 -04:00
|
|
|
def initialize(group_name, message_type, opts = {})
|
2013-06-10 13:17:09 -04:00
|
|
|
@group_name = group_name
|
|
|
|
@message_type = message_type
|
|
|
|
@opts = opts
|
|
|
|
end
|
|
|
|
|
|
|
|
def create
|
|
|
|
unless sent_recently?
|
2014-06-30 09:21:26 -04:00
|
|
|
post = PostCreator.create(
|
|
|
|
Discourse.system_user,
|
|
|
|
target_group_names: [@group_name],
|
|
|
|
archetype: Archetype.private_message,
|
|
|
|
subtype: TopicSubtype.system_message,
|
|
|
|
title: I18n.t("system_messages.#{@message_type}.subject_template", message_params),
|
|
|
|
raw: I18n.t("system_messages.#{@message_type}.text_body_template", message_params)
|
|
|
|
)
|
2013-06-10 13:17:09 -04:00
|
|
|
remember_message_sent
|
|
|
|
post
|
|
|
|
else
|
|
|
|
false
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def message_params
|
2013-08-26 16:15:59 -04:00
|
|
|
@message_params ||= begin
|
2014-06-30 09:21:26 -04:00
|
|
|
h = { base_url: Discourse.base_url }.merge(@opts[:message_params] || {})
|
2013-08-26 16:15:59 -04:00
|
|
|
if @opts[:user]
|
2017-07-27 21:20:09 -04:00
|
|
|
h.merge!(username: @opts[:user].username,
|
|
|
|
user_url: user_path(@opts[:user].username))
|
2013-08-26 16:15:59 -04:00
|
|
|
end
|
|
|
|
h
|
|
|
|
end
|
2013-06-10 13:17:09 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def sent_recently?
|
|
|
|
return false if @opts[:limit_once_per] == false
|
|
|
|
$redis.get(sent_recently_key).present?
|
|
|
|
end
|
|
|
|
|
|
|
|
# default is to send no more than once every 24 hours (24 * 60 * 60 = 86,400 seconds)
|
|
|
|
def remember_message_sent
|
|
|
|
$redis.setex(sent_recently_key, @opts[:limit_once_per].try(:to_i) || 86_400, 1) unless @opts[:limit_once_per] == false
|
|
|
|
end
|
|
|
|
|
2014-02-18 00:09:24 -05:00
|
|
|
def sent_recently_key
|
|
|
|
"grpmsg:#{@group_name}:#{@message_type}:#{@opts[:user] ? @opts[:user].username : ''}"
|
|
|
|
end
|
2013-06-10 13:17:09 -04:00
|
|
|
end
|