Correct rubocop offenses

This commit is contained in:
David Taylor 2017-08-01 20:53:39 +01:00
parent 4c379876b6
commit 4f9ad4efef
43 changed files with 488 additions and 514 deletions

View File

@ -6,13 +6,13 @@ class DiscourseChat::ChatController < ApplicationController
end end
def list_providers def list_providers
providers = ::DiscourseChat::Provider.enabled_providers.map {|x| { providers = ::DiscourseChat::Provider.enabled_providers.map { |x| {
name: x::PROVIDER_NAME, name: x::PROVIDER_NAME,
id: x::PROVIDER_NAME, id: x::PROVIDER_NAME,
channel_parameters: (defined? x::CHANNEL_PARAMETERS) ? x::CHANNEL_PARAMETERS : [] channel_parameters: (defined? x::CHANNEL_PARAMETERS) ? x::CHANNEL_PARAMETERS : []
}} }}
render json:providers, root: 'providers' render json: providers, root: 'providers'
end end
def test def test
@ -32,21 +32,21 @@ class DiscourseChat::ChatController < ApplicationController
provider.trigger_notification(post, channel) provider.trigger_notification(post, channel)
render json:success_json render json: success_json
rescue Discourse::InvalidParameters, ActiveRecord::RecordNotFound => e rescue Discourse::InvalidParameters, ActiveRecord::RecordNotFound => e
render json: {errors: [e.message]}, status: 422 render json: { errors: [e.message] }, status: 422
rescue DiscourseChat::ProviderError => e rescue DiscourseChat::ProviderError => e
Rails.logger.error("Test provider failed #{e.info}") Rails.logger.error("Test provider failed #{e.info}")
if e.info.key?(:error_key) and !e.info[:error_key].nil? if e.info.key?(:error_key) && !e.info[:error_key].nil?
render json: {error_key: e.info[:error_key]}, status: 422 render json: { error_key: e.info[:error_key] }, status: 422
else else
render json: {errors: [e.message]}, status: 422 render json: { errors: [e.message] }, status: 422
end end
end end
end end
def list_channels def list_channels
providers = ::DiscourseChat::Provider.enabled_providers.map {|x| x::PROVIDER_NAME} providers = ::DiscourseChat::Provider.enabled_providers.map { |x| x::PROVIDER_NAME }
requested_provider = params[:provider] requested_provider = params[:provider]
@ -61,9 +61,9 @@ class DiscourseChat::ChatController < ApplicationController
def create_channel def create_channel
begin begin
providers = ::DiscourseChat::Provider.enabled_providers.map {|x| x::PROVIDER_NAME} providers = ::DiscourseChat::Provider.enabled_providers.map { |x| x::PROVIDER_NAME }
if not defined? params[:channel] and defined? params[:channel][:provider] if (not defined? params[:channel]) && defined? params[:channel][:provider]
raise Discourse::InvalidParameters, 'Provider is not valid' raise Discourse::InvalidParameters, 'Provider is not valid'
end end
@ -73,9 +73,9 @@ class DiscourseChat::ChatController < ApplicationController
raise Discourse::InvalidParameters, 'Provider is not valid' raise Discourse::InvalidParameters, 'Provider is not valid'
end end
allowed_keys = DiscourseChat::Provider.get_by_name(requested_provider)::CHANNEL_PARAMETERS.map{|p| p[:key].to_sym} allowed_keys = DiscourseChat::Provider.get_by_name(requested_provider)::CHANNEL_PARAMETERS.map { |p| p[:key].to_sym }
hash = params.require(:channel).permit(:provider, data:allowed_keys) hash = params.require(:channel).permit(:provider, data: allowed_keys)
channel = DiscourseChat::Channel.new(hash) channel = DiscourseChat::Channel.new(hash)
@ -85,7 +85,7 @@ class DiscourseChat::ChatController < ApplicationController
render_serialized channel, DiscourseChat::ChannelSerializer, root: 'channel' render_serialized channel, DiscourseChat::ChannelSerializer, root: 'channel'
rescue Discourse::InvalidParameters => e rescue Discourse::InvalidParameters => e
render json: {errors: [e.message]}, status: 422 render json: { errors: [e.message] }, status: 422
end end
end end
@ -94,9 +94,9 @@ class DiscourseChat::ChatController < ApplicationController
channel = DiscourseChat::Channel.find(params[:id].to_i) channel = DiscourseChat::Channel.find(params[:id].to_i)
channel.error_key = nil # Reset any error on the rule channel.error_key = nil # Reset any error on the rule
allowed_keys = DiscourseChat::Provider.get_by_name(channel.provider)::CHANNEL_PARAMETERS.map{|p| p[:key].to_sym} allowed_keys = DiscourseChat::Provider.get_by_name(channel.provider)::CHANNEL_PARAMETERS.map { |p| p[:key].to_sym }
hash = params.require(:channel).permit(data:allowed_keys) hash = params.require(:channel).permit(data: allowed_keys)
if not channel.update(hash) if not channel.update(hash)
raise Discourse::InvalidParameters, 'Channel is not valid' raise Discourse::InvalidParameters, 'Channel is not valid'
@ -104,7 +104,7 @@ class DiscourseChat::ChatController < ApplicationController
render_serialized channel, DiscourseChat::ChannelSerializer, root: 'channel' render_serialized channel, DiscourseChat::ChannelSerializer, root: 'channel'
rescue Discourse::InvalidParameters => e rescue Discourse::InvalidParameters => e
render json: {errors: [e.message]}, status: 422 render json: { errors: [e.message] }, status: 422
end end
end end
@ -118,7 +118,7 @@ class DiscourseChat::ChatController < ApplicationController
def create_rule def create_rule
begin begin
hash = params.require(:rule).permit(:channel_id, :type, :filter, :group_id, :category_id, tags:[]) hash = params.require(:rule).permit(:channel_id, :type, :filter, :group_id, :category_id, tags: [])
rule = DiscourseChat::Rule.new(hash) rule = DiscourseChat::Rule.new(hash)
@ -128,14 +128,14 @@ class DiscourseChat::ChatController < ApplicationController
render_serialized rule, DiscourseChat::RuleSerializer, root: 'rule' render_serialized rule, DiscourseChat::RuleSerializer, root: 'rule'
rescue Discourse::InvalidParameters => e rescue Discourse::InvalidParameters => e
render json: {errors: [e.message]}, status: 422 render json: { errors: [e.message] }, status: 422
end end
end end
def update_rule def update_rule
begin begin
rule = DiscourseChat::Rule.find(params[:id].to_i) rule = DiscourseChat::Rule.find(params[:id].to_i)
hash = params.require(:rule).permit(:type, :filter, :group_id, :category_id, tags:[]) hash = params.require(:rule).permit(:type, :filter, :group_id, :category_id, tags: [])
if not rule.update(hash) if not rule.update(hash)
raise Discourse::InvalidParameters, 'Rule is not valid' raise Discourse::InvalidParameters, 'Rule is not valid'
@ -143,7 +143,7 @@ class DiscourseChat::ChatController < ApplicationController
render_serialized rule, DiscourseChat::RuleSerializer, root: 'rule' render_serialized rule, DiscourseChat::RuleSerializer, root: 'rule'
rescue Discourse::InvalidParameters => e rescue Discourse::InvalidParameters => e
render json: {errors: [e.message]}, status: 422 render json: { errors: [e.message] }, status: 422
end end
end end

View File

@ -8,7 +8,7 @@ class DiscourseChat::PublicController < ApplicationController
content = $redis.get(redis_key) content = $redis.get(redis_key)
if content if content
render json: {content: content} render json: { content: content }
return return
end end

View File

@ -20,7 +20,7 @@ module DiscourseChat
category = Category.find_by(slug: category_name) category = Category.find_by(slug: category_name)
unless category unless category
cat_list = (CategoryList.new(guardian).categories.map(&:slug)).join(', ') cat_list = (CategoryList.new(guardian).categories.map(&:slug)).join(', ')
return I18n.t("chat_integration.provider.#{provider}.not_found.category", name: category_name, list:cat_list) return I18n.t("chat_integration.provider.#{provider}.not_found.category", name: category_name, list: cat_list)
end end
else else
category = nil # All categories category = nil # All categories
@ -44,7 +44,7 @@ module DiscourseChat
end end
category_id = category.nil? ? nil : category.id category_id = category.nil? ? nil : category.id
case DiscourseChat::Helper.smart_create_rule(channel:channel, filter:cmd, category_id: category_id, tags:tags) case DiscourseChat::Helper.smart_create_rule(channel: channel, filter: cmd, category_id: category_id, tags: tags)
when :created when :created
return I18n.t("chat_integration.provider.#{provider}.create.created") return I18n.t("chat_integration.provider.#{provider}.create.created")
when :updated when :updated
@ -73,14 +73,14 @@ module DiscourseChat
end end
# Produce a string with a list of all rules associated with a channel # Produce a string with a list of all rules associated with a channel
def self.status_for_channel(channel) def self.status_for_channel(channel)
rules = channel.rules.order_by_precedence rules = channel.rules.order_by_precedence
provider = channel.provider provider = channel.provider
text = I18n.t("chat_integration.provider.#{provider}.status.header") + "\n" text = I18n.t("chat_integration.provider.#{provider}.status.header") + "\n"
i = 1 i = 1
rules.each do |rule| rules.each do |rule|
category_id = rule.category_id category_id = rule.category_id
case rule.type case rule.type
@ -110,28 +110,28 @@ module DiscourseChat
category: category_name category: category_name
) )
if SiteSetting.tagging_enabled and not rule.tags.nil? if SiteSetting.tagging_enabled && (not rule.tags.nil?)
text << I18n.t("chat_integration.provider.#{provider}.status.rule_string_tags_suffix", tags: rule.tags.join(', ')) text << I18n.t("chat_integration.provider.#{provider}.status.rule_string_tags_suffix", tags: rule.tags.join(', '))
end end
text << "\n" text << "\n"
i += 1 i += 1
end end
if rules.size == 0 if rules.size == 0
text << I18n.t("chat_integration.provider.#{provider}.status.no_rules") text << I18n.t("chat_integration.provider.#{provider}.status.no_rules")
end end
return text return text
end end
# Delete a rule based on its (1 based) index as seen in the # Delete a rule based on its (1 based) index as seen in the
# status_for_channel function # status_for_channel function
def self.delete_by_index(channel, index) def self.delete_by_index(channel, index)
rules = channel.rules.order_by_precedence rules = channel.rules.order_by_precedence
return false if index < 1 or index > rules.size return false if index < (1) || index > (rules.size)
return :deleted if rules[index-1].destroy return :deleted if rules[index - 1].destroy
end end
# Create a rule for a specific channel # Create a rule for a specific channel
@ -141,13 +141,13 @@ module DiscourseChat
# :updated if an existing rule has been updated # :updated if an existing rule has been updated
# :created if a new rule has been created # :created if a new rule has been created
# false if there was an error # false if there was an error
def self.smart_create_rule(channel:, filter:, category_id:nil, tags:nil) def self.smart_create_rule(channel:, filter:, category_id: nil, tags: nil)
existing_rules = DiscourseChat::Rule.with_channel(channel) existing_rules = DiscourseChat::Rule.with_channel(channel)
# Select the ones that have the same category # Select the ones that have the same category
same_category = existing_rules.select { |rule| rule.category_id == category_id } same_category = existing_rules.select { |rule| rule.category_id == category_id }
same_category_and_tags = same_category.select{ |rule| (rule.tags.nil? ? [] : rule.tags.sort) == (tags.nil? ? [] : tags.sort) } same_category_and_tags = same_category.select { |rule| (rule.tags.nil? ? [] : rule.tags.sort) == (tags.nil? ? [] : tags.sort) }
if same_category_and_tags.size > 0 if same_category_and_tags.size > 0
# These rules have exactly the same criteria as what we're trying to create # These rules have exactly the same criteria as what we're trying to create
@ -157,7 +157,7 @@ module DiscourseChat
rule.destroy rule.destroy
end end
return :updated if the_rule.update(filter:filter) # Update the filter return :updated if the_rule.update(filter: filter) # Update the filter
return false # Error, probably validation return false # Error, probably validation
end end
@ -192,11 +192,10 @@ module DiscourseChat
def self.save_transcript(transcript) def self.save_transcript(transcript)
secret = SecureRandom.hex secret = SecureRandom.hex
redis_key = "chat_integration:transcript:" + secret redis_key = "chat_integration:transcript:" + secret
$redis.set(redis_key, transcript, {:ex => 3600}) # Expire in 1 hour $redis.set(redis_key, transcript, ex: 3600) # Expire in 1 hour
return secret return secret
end end
end end
end end

View File

@ -2,12 +2,12 @@ module ::DiscourseChat
PLUGIN_NAME = "discourse-chat-integration".freeze PLUGIN_NAME = "discourse-chat-integration".freeze
class AdminEngine < ::Rails::Engine class AdminEngine < ::Rails::Engine
engine_name DiscourseChat::PLUGIN_NAME+"-admin" engine_name DiscourseChat::PLUGIN_NAME + "-admin"
isolate_namespace DiscourseChat isolate_namespace DiscourseChat
end end
class PublicEngine < ::Rails::Engine class PublicEngine < ::Rails::Engine
engine_name DiscourseChat::PLUGIN_NAME+"-public" engine_name DiscourseChat::PLUGIN_NAME + "-public"
isolate_namespace DiscourseChat isolate_namespace DiscourseChat
end end

View File

@ -31,7 +31,7 @@ class DiscourseChat::Channel < DiscourseChat::PluginModel
params = ::DiscourseChat::Provider.get_by_name(provider)::CHANNEL_PARAMETERS params = ::DiscourseChat::Provider.get_by_name(provider)::CHANNEL_PARAMETERS
unless params.map {|p| p[:key]}.sort == data.keys.sort unless params.map { |p| p[:key] }.sort == data.keys.sort
errors.add(:data, "data does not match the required structure for provider #{provider}") errors.add(:data, "data does not match the required structure for provider #{provider}")
return return
end end
@ -40,12 +40,12 @@ class DiscourseChat::Channel < DiscourseChat::PluginModel
matching_channels = DiscourseChat::Channel.where.not(id: id) matching_channels = DiscourseChat::Channel.where.not(id: id)
data.each do |key, value| data.each do |key, value|
regex_string = params.find{|p| p[:key] == key}[:regex] regex_string = params.find { |p| p[:key] == key }[:regex]
if !Regexp.new(regex_string).match(value) if !Regexp.new(regex_string).match(value)
errors.add(:data, "data.#{key} is invalid") errors.add(:data, "data.#{key} is invalid")
end end
unique = params.find{|p| p[:key] == key}[:unique] unique = params.find { |p| p[:key] == key }[:unique]
if unique if unique
check_unique = true check_unique = true
matching_channels = matching_channels.with_data_value(key, value) matching_channels = matching_channels.with_data_value(key, value)
@ -62,8 +62,8 @@ class DiscourseChat::Channel < DiscourseChat::PluginModel
DiscourseChat::Rule.with_channel_id(id).order_by_precedence DiscourseChat::Rule.with_channel_id(id).order_by_precedence
end end
scope :with_provider, ->(provider) { where("value::json->>'provider'=?", provider)} scope :with_provider, ->(provider) { where("value::json->>'provider'=?", provider) }
scope :with_data_value, ->(key, value) { where("(value::json->>'data')::json->>?=?", key.to_s, value.to_s)} scope :with_data_value, ->(key, value) { where("(value::json->>'data')::json->>?=?", key.to_s, value.to_s) }
end end

View File

@ -6,14 +6,14 @@ class DiscourseChat::PluginModel < PluginStoreRow
def init_plugin_model def init_plugin_model
self.type_name ||= 'JSON' self.type_name ||= 'JSON'
self.plugin_name ||= PLUGIN_NAME self.plugin_name ||= PLUGIN_NAME
end end
# Restrict the scope to JSON PluginStoreRows which are for this plugin, and this model # Restrict the scope to JSON PluginStoreRows which are for this plugin, and this model
def self.default_scope def self.default_scope
where(type_name: 'JSON') where(type_name: 'JSON')
.where(plugin_name: self::PLUGIN_NAME) .where(plugin_name: self::PLUGIN_NAME)
.where("key like?", "#{self::KEY_PREFIX}%") .where("key like?", "#{self::KEY_PREFIX}%")
end end
before_save :set_key before_save :set_key

View File

@ -7,15 +7,15 @@ class DiscourseChat::Rule < DiscourseChat::PluginModel
after_initialize :init_filter after_initialize :init_filter
def init_filter def init_filter
self.filter ||= 'watch' self.filter ||= 'watch'
self.type ||= 'normal' self.type ||= 'normal'
end end
validates :filter, :inclusion => { :in => %w(watch follow mute), validates :filter, inclusion: { in: %w(watch follow mute),
:message => "%{value} is not a valid filter" } message: "%{value} is not a valid filter" }
validates :type, :inclusion => { :in => %w(normal group_message group_mention), validates :type, inclusion: { in: %w(normal group_message group_mention),
:message => "%{value} is not a valid filter" } message: "%{value} is not a valid filter" }
validate :channel_valid?, :category_valid?, :group_valid?, :tags_valid? validate :channel_valid?, :category_valid?, :group_valid?, :tags_valid?
@ -34,7 +34,7 @@ class DiscourseChat::Rule < DiscourseChat::PluginModel
return unless type == 'normal' return unless type == 'normal'
# Validate category # Validate category
if not (category_id.nil? or Category.where(id: category_id).exists?) if not (category_id.nil? || Category.where(id: category_id).exists?)
errors.add(:category_id, "#{category_id} is not a valid category id") errors.add(:category_id, "#{category_id} is not a valid category id")
end end
end end
@ -64,7 +64,7 @@ class DiscourseChat::Rule < DiscourseChat::PluginModel
# We never want an empty array, set it to nil instead # We never want an empty array, set it to nil instead
def tags=(array) def tags=(array)
if array.nil? or array.empty? if array.nil? || array.empty?
super(nil) super(nil)
else else
super(array) super(array)
@ -74,7 +74,7 @@ class DiscourseChat::Rule < DiscourseChat::PluginModel
# These are only allowed to be integers # These are only allowed to be integers
%w(channel_id category_id group_id).each do |name| %w(channel_id category_id group_id).each do |name|
define_method "#{name}=" do |val| define_method "#{name}=" do |val|
if val.nil? or val.blank? if val.nil? || val.blank?
super(nil) super(nil)
else else
super(val.to_i) super(val.to_i)
@ -86,21 +86,21 @@ class DiscourseChat::Rule < DiscourseChat::PluginModel
# Mock foreign key # Mock foreign key
# Could return nil # Could return nil
def channel def channel
DiscourseChat::Channel.find_by(id:channel_id) DiscourseChat::Channel.find_by(id: channel_id)
end end
def channel=(val) def channel=(val)
self.channel_id = val.id self.channel_id = val.id
end end
scope :with_type, ->(type) { where("value::json->>'type'=?", type.to_s)} scope :with_type, ->(type) { where("value::json->>'type'=?", type.to_s) }
scope :with_channel, ->(channel) { with_channel_id(channel.id) } scope :with_channel, ->(channel) { with_channel_id(channel.id) }
scope :with_channel_id, ->(channel_id) { where("value::json->>'channel_id'=?", channel_id.to_s)} scope :with_channel_id, ->(channel_id) { where("value::json->>'channel_id'=?", channel_id.to_s) }
scope :with_category_id, ->(category_id) { category_id.nil? ? where("(value::json->'category_id') IS NULL OR json_typeof(value::json->'category_id')='null'") : where("value::json->>'category_id'=?", category_id.to_s)} scope :with_category_id, ->(category_id) { category_id.nil? ? where("(value::json->'category_id') IS NULL OR json_typeof(value::json->'category_id')='null'") : where("value::json->>'category_id'=?", category_id.to_s) }
scope :with_group_ids, ->(group_id) { where("value::json->>'group_id' IN (?)", group_id.map(&:to_s))} scope :with_group_ids, ->(group_id) { where("value::json->>'group_id' IN (?)", group_id.map(&:to_s)) }
scope :order_by_precedence, ->{ order("CASE scope :order_by_precedence, -> { order("CASE
WHEN value::json->>'type' = 'group_mention' THEN 1 WHEN value::json->>'type' = 'group_mention' THEN 1
WHEN value::json->>'type' = 'group_message' THEN 2 WHEN value::json->>'type' = 'group_message' THEN 2
ELSE 3 ELSE 3

View File

@ -5,7 +5,7 @@ class DiscourseChat::ChannelSerializer < ApplicationSerializer
def rules def rules
object.rules.order_by_precedence.map do |rule| object.rules.order_by_precedence.map do |rule|
DiscourseChat::RuleSerializer.new(rule, root:false) DiscourseChat::RuleSerializer.new(rule, root: false)
end end
end end
end end

View File

@ -3,7 +3,7 @@ class DiscourseChat::RuleSerializer < ApplicationSerializer
def group_name def group_name
if object.group_id if object.group_id
groups = Group.where(id:object.group_id) groups = Group.where(id: object.group_id)
if groups.exists? if groups.exists?
return groups.first.name return groups.first.name
else else

View File

@ -46,14 +46,14 @@ module DiscourseChat
if SiteSetting.tagging_enabled if SiteSetting.tagging_enabled
topic_tags = topic.tags.present? ? topic.tags.pluck(:name) : [] topic_tags = topic.tags.present? ? topic.tags.pluck(:name) : []
matching_rules = matching_rules.select do |rule| matching_rules = matching_rules.select do |rule|
next true if rule.tags.nil? or rule.tags.empty? # Filter has no tags specified next true if rule.tags.nil? || rule.tags.empty? # Filter has no tags specified
any_tags_match = !((rule.tags & topic_tags).empty?) any_tags_match = !((rule.tags & topic_tags).empty?)
next any_tags_match # If any tags match, keep this filter, otherwise throw away next any_tags_match # If any tags match, keep this filter, otherwise throw away
end end
end end
# Sort by order of precedence (mute always wins; watch beats follow) # Sort by order of precedence (mute always wins; watch beats follow)
precedence = { 'mute' => 0, 'watch' => 1, 'follow' => 2} precedence = { 'mute' => 0, 'watch' => 1, 'follow' => 2 }
sort_func = proc { |a, b| precedence[a.filter] <=> precedence[b.filter] } sort_func = proc { |a, b| precedence[a.filter] <=> precedence[b.filter] }
matching_rules = matching_rules.sort(&sort_func) matching_rules = matching_rules.sort(&sort_func)
@ -84,10 +84,10 @@ module DiscourseChat
provider.trigger_notification(post, channel) provider.trigger_notification(post, channel)
channel.update_attribute('error_key', nil) if channel.error_key channel.update_attribute('error_key', nil) if channel.error_key
rescue => e rescue => e
if e.class == DiscourseChat::ProviderError and e.info.key?(:error_key) and !e.info[:error_key].nil? if e.class == (DiscourseChat::ProviderError) && e.info.key?(:error_key) && !e.info[:error_key].nil?
channel.update_attribute('error_key', e.info[:error_key]) channel.update_attribute('error_key', e.info[:error_key])
else else
channel.update_attribute('error_key','chat_integration.channel_exception') channel.update_attribute('error_key', 'chat_integration.channel_exception')
end end
# Log the error # Log the error
@ -104,6 +104,5 @@ module DiscourseChat
end end
end end
end end

View File

@ -22,15 +22,15 @@ module DiscourseChat
end end
def self.provider_names def self.provider_names
self.providers.map {|x| x::PROVIDER_NAME} self.providers.map { |x| x::PROVIDER_NAME }
end end
def self.enabled_provider_names def self.enabled_provider_names
self.enabled_providers.map {|x| x::PROVIDER_NAME} self.enabled_providers.map { |x| x::PROVIDER_NAME }
end end
def self.get_by_name(name) def self.get_by_name(name)
self.providers.find{|p| p::PROVIDER_NAME == name} self.providers.find { |p| p::PROVIDER_NAME == name }
end end
def self.is_enabled(provider) def self.is_enabled(provider)
@ -42,7 +42,7 @@ module DiscourseChat
end end
class HookEngine < ::Rails::Engine class HookEngine < ::Rails::Engine
engine_name DiscourseChat::PLUGIN_NAME+"-hooks" engine_name DiscourseChat::PLUGIN_NAME + "-hooks"
isolate_namespace DiscourseChat::Provider isolate_namespace DiscourseChat::Provider
end end
@ -71,11 +71,11 @@ module DiscourseChat
engines = [] engines = []
DiscourseChat::Provider.providers.each do |provider| DiscourseChat::Provider.providers.each do |provider|
engine = provider.constants.select do |constant| engine = provider.constants.select do |constant|
constant.to_s =~ /Engine$/ and not constant.to_s == "HookEngine" constant.to_s =~ (/Engine$/) && (not constant.to_s == "HookEngine")
end.map(&provider.method(:const_get)).first end.map(&provider.method(:const_get)).first
if engine if engine
engines.push({engine: engine, name: provider::PROVIDER_NAME}) engines.push(engine: engine, name: provider::PROVIDER_NAME)
end end
end end

View File

@ -4,8 +4,8 @@ module DiscourseChat
PROVIDER_NAME = "discord".freeze PROVIDER_NAME = "discord".freeze
PROVIDER_ENABLED_SETTING = :chat_integration_discord_enabled PROVIDER_ENABLED_SETTING = :chat_integration_discord_enabled
CHANNEL_PARAMETERS = [ CHANNEL_PARAMETERS = [
{key: "name", regex: '^\S+'}, { key: "name", regex: '^\S+' },
{key: "webhook_url", regex: '^https:\/\/discordapp\.com\/api\/webhooks\/', unique: true, hidden: true} { key: "webhook_url", regex: '^https:\/\/discordapp\.com\/api\/webhooks\/', unique: true, hidden: true }
] ]
def self.send_message(url, message) def self.send_message(url, message)
@ -14,7 +14,7 @@ module DiscourseChat
uri = URI(url) uri = URI(url)
req = Net::HTTP::Post.new(uri, 'Content-Type' =>'application/json') req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
req.body = message.to_json req.body = message.to_json
response = http.request(req) response = http.request(req)
@ -36,13 +36,13 @@ module DiscourseChat
end end
message = { message = {
embeds:[{ embeds: [{
title: post.topic.title, title: post.topic.title,
description: post.excerpt(SiteSetting.chat_integration_discord_excerpt_length, text_entities: true, strip_links: true, remap_emoji: true), description: post.excerpt(SiteSetting.chat_integration_discord_excerpt_length, text_entities: true, strip_links: true, remap_emoji: true),
url: post.full_url, url: post.full_url,
author:{ author: {
name: display_name, name: display_name,
url: Discourse.base_url+"/u/"+post.user.username, url: Discourse.base_url + "/u/" + post.user.username,
icon_url: ensure_protocol(post.user.small_avatar_url) icon_url: ensure_protocol(post.user.small_avatar_url)
} }
}] }]
@ -53,7 +53,7 @@ module DiscourseChat
def self.trigger_notification(post, channel) def self.trigger_notification(post, channel)
# Adding ?wait=true means that we actually get a success/failure response, rather than returning asynchronously # Adding ?wait=true means that we actually get a success/failure response, rather than returning asynchronously
webhook_url = channel.data['webhook_url']+'?wait=true' webhook_url = channel.data['webhook_url'] + '?wait=true'
message = generate_discord_message(post) message = generate_discord_message(post)
@ -61,7 +61,7 @@ module DiscourseChat
if not response.kind_of? Net::HTTPSuccess if not response.kind_of? Net::HTTPSuccess
error_key = nil error_key = nil
raise ::DiscourseChat::ProviderError.new info: {error_key: error_key, message: message, response_body:response.body} raise ::DiscourseChat::ProviderError.new info: { error_key: error_key, message: message, response_body: response.body }
end end
end end

View File

@ -4,9 +4,9 @@ module DiscourseChat
PROVIDER_NAME = "hipchat".freeze PROVIDER_NAME = "hipchat".freeze
PROVIDER_ENABLED_SETTING = :chat_integration_hipchat_enabled PROVIDER_ENABLED_SETTING = :chat_integration_hipchat_enabled
CHANNEL_PARAMETERS = [ CHANNEL_PARAMETERS = [
{key: "name", regex: '^\S+'}, { key: "name", regex: '^\S+' },
{key: "webhook_url", regex: 'hipchat\.com', unique: true, hidden:true}, { key: "webhook_url", regex: 'hipchat\.com', unique: true, hidden: true },
{key: "color", regex: '(yellow|green|red|purple|gray|random)'} { key: "color", regex: '(yellow|green|red|purple|gray|random)' }
] ]
def self.send_message(url, message) def self.send_message(url, message)
@ -15,7 +15,7 @@ module DiscourseChat
http = Net::HTTP.new(uri.host, uri.port) http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true http.use_ssl = true
req = Net::HTTP::Post.new(uri, 'Content-Type' =>'application/json') req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
req.body = message.to_json req.body = message.to_json
response = http.request(req) response = http.request(req)
@ -83,7 +83,7 @@ module DiscourseChat
if not response.kind_of? Net::HTTPSuccess if not response.kind_of? Net::HTTPSuccess
error_key = nil error_key = nil
raise ::DiscourseChat::ProviderError.new info: {error_key: error_key, message: message, response_body:response.body} raise ::DiscourseChat::ProviderError.new info: { error_key: error_key, message: message, response_body: response.body }
end end
end end

View File

@ -4,8 +4,8 @@ module DiscourseChat
PROVIDER_NAME = "matrix".freeze PROVIDER_NAME = "matrix".freeze
PROVIDER_ENABLED_SETTING = :chat_integration_matrix_enabled PROVIDER_ENABLED_SETTING = :chat_integration_matrix_enabled
CHANNEL_PARAMETERS = [ CHANNEL_PARAMETERS = [
{key: "name", regex: '^\S+'}, { key: "name", regex: '^\S+' },
{key: "room_id", regex: '^\!\S+:\S+$', unique: true, hidden:true} { key: "room_id", regex: '^\!\S+:\S+$', unique: true, hidden: true }
] ]
def self.send_message(room_id, message) def self.send_message(room_id, message)
@ -13,18 +13,16 @@ module DiscourseChat
event_type = 'm.room.message' event_type = 'm.room.message'
uid = Time.now.to_i uid = Time.now.to_i
url_params = URI.encode_www_form({ url_params = URI.encode_www_form(access_token: SiteSetting.chat_integration_matrix_access_token)
access_token: SiteSetting.chat_integration_matrix_access_token
})
url = "#{homeserver}/_matrix/client/r0/rooms/#{CGI::escape(room_id)}/send/#{event_type}/#{uid}" url = "#{homeserver}/_matrix/client/r0/rooms/#{CGI::escape(room_id)}/send/#{event_type}/#{uid}"
uri = URI([url,url_params].join('?')) uri = URI([url, url_params].join('?'))
http = Net::HTTP.new(uri.host, uri.port) http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true http.use_ssl = true
req = Net::HTTP::Put.new(uri, 'Content-Type' =>'application/json') req = Net::HTTP::Put.new(uri, 'Content-Type' => 'application/json')
req.body = message.to_json req.body = message.to_json
response = http.request(req) response = http.request(req)
@ -42,18 +40,14 @@ module DiscourseChat
message = { message = {
msgtype: 'm.notice', msgtype: 'm.notice',
body: I18n.t('chat_integration.provider.matrix.text_message', { body: I18n.t('chat_integration.provider.matrix.text_message', user: display_name,
user: display_name, post_url: post.full_url,
post_url: post.full_url, title: post.topic.title),
title: post.topic.title
}),
format: 'org.matrix.custom.html', format: 'org.matrix.custom.html',
formatted_body: I18n.t('chat_integration.provider.matrix.formatted_message', { formatted_body: I18n.t('chat_integration.provider.matrix.formatted_message', user: display_name,
user: display_name, post_url: post.full_url,
post_url: post.full_url, title: post.topic.title,
title: post.topic.title, excerpt: post.excerpt(SiteSetting.chat_integration_discord_excerpt_length, text_entities: true, strip_links: true, remap_emoji: true))
excerpt: post.excerpt(SiteSetting.chat_integration_discord_excerpt_length, text_entities: true, strip_links: true, remap_emoji: true),
})
} }
@ -75,7 +69,7 @@ module DiscourseChat
error_key = 'chat_integration.provider.matrix.errors.unknown_room' error_key = 'chat_integration.provider.matrix.errors.unknown_room'
end end
ensure ensure
raise ::DiscourseChat::ProviderError.new info: {error_key: error_key, message: message, response_body:response.body} raise ::DiscourseChat::ProviderError.new info: { error_key: error_key, message: message, response_body: response.body }
end end
end end

View File

@ -36,10 +36,10 @@ module DiscourseChat::Provider::MattermostProvider
provider = DiscourseChat::Provider::MattermostProvider::PROVIDER_NAME provider = DiscourseChat::Provider::MattermostProvider::PROVIDER_NAME
channel = DiscourseChat::Channel.with_provider(provider).with_data_value('identifier',channel_id).first channel = DiscourseChat::Channel.with_provider(provider).with_data_value('identifier', channel_id).first
# Create channel if doesn't exist # Create channel if doesn't exist
channel ||= DiscourseChat::Channel.create!(provider:provider, data:{identifier: channel_id}) channel ||= DiscourseChat::Channel.create!(provider: provider, data: { identifier: channel_id })
return ::DiscourseChat::Helper.process_command(channel, tokens) return ::DiscourseChat::Helper.process_command(channel, tokens)
@ -57,7 +57,7 @@ module DiscourseChat::Provider::MattermostProvider
end end
class MattermostEngine < ::Rails::Engine class MattermostEngine < ::Rails::Engine
engine_name DiscourseChat::PLUGIN_NAME+"-mattermost" engine_name DiscourseChat::PLUGIN_NAME + "-mattermost"
isolate_namespace DiscourseChat::Provider::MattermostProvider isolate_namespace DiscourseChat::Provider::MattermostProvider
end end
@ -66,6 +66,3 @@ module DiscourseChat::Provider::MattermostProvider
end end
end end

View File

@ -4,7 +4,7 @@ module DiscourseChat
PROVIDER_NAME = "mattermost".freeze PROVIDER_NAME = "mattermost".freeze
PROVIDER_ENABLED_SETTING = :chat_integration_mattermost_enabled PROVIDER_ENABLED_SETTING = :chat_integration_mattermost_enabled
CHANNEL_PARAMETERS = [ CHANNEL_PARAMETERS = [
{key: "identifier", regex: '^[@#]\S*$', unique: true} { key: "identifier", regex: '^[@#]\S*$', unique: true }
] ]
def self.send_via_webhook(message) def self.send_via_webhook(message)
@ -13,7 +13,7 @@ module DiscourseChat
http = Net::HTTP.new(uri.host, uri.port) http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = (uri.scheme == 'https') http.use_ssl = (uri.scheme == 'https')
req = Net::HTTP::Post.new(uri, 'Content-Type' =>'application/json') req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
req.body = message.to_json req.body = message.to_json
response = http.request(req) response = http.request(req)
@ -23,7 +23,7 @@ module DiscourseChat
else else
error_key = nil error_key = nil
end end
raise ::DiscourseChat::ProviderError.new info: {error_key: error_key, request: req.body, response_code:response.code, response_body:response.body} raise ::DiscourseChat::ProviderError.new info: { error_key: error_key, request: req.body, response_code: response.code, response_body: response.body }
end end
end end
@ -40,7 +40,7 @@ module DiscourseChat
category = '' category = ''
if topic.category if topic.category
category = (topic.category.parent_category) ? "[#{topic.category.parent_category.name}/#{topic.category.name}]": "[#{topic.category.name}]" category = (topic.category.parent_category) ? "[#{topic.category.parent_category.name}/#{topic.category.name}]" : "[#{topic.category.name}]"
end end
icon_url = icon_url =
@ -63,7 +63,7 @@ module DiscourseChat
author_icon: post.user.small_avatar_url, author_icon: post.user.small_avatar_url,
color: topic.category ? "##{topic.category.color}" : nil, color: topic.category ? "##{topic.category.color}" : nil,
text: post.excerpt(SiteSetting.chat_integration_mattermost_excerpt_length, text_entities: true, strip_links: true, remap_emoji: true), text: post.excerpt(SiteSetting.chat_integration_mattermost_excerpt_length, text_entities: true, strip_links: true, remap_emoji: true),
title: "#{topic.title} #{(category == '[uncategorized]')? '' : category} #{topic.tags.present? ? topic.tags.map(&:name).join(', ') : ''}", title: "#{topic.title} #{(category == '[uncategorized]') ? '' : category} #{topic.tags.present? ? topic.tags.map(&:name).join(', ') : ''}",
title_link: post.full_url, title_link: post.full_url,
thumb_url: post.full_url, thumb_url: post.full_url,
} }

View File

@ -33,10 +33,10 @@ module DiscourseChat::Provider::SlackProvider
provider = DiscourseChat::Provider::SlackProvider::PROVIDER_NAME provider = DiscourseChat::Provider::SlackProvider::PROVIDER_NAME
channel = DiscourseChat::Channel.with_provider(provider).with_data_value('identifier',channel_id).first channel = DiscourseChat::Channel.with_provider(provider).with_data_value('identifier', channel_id).first
# Create channel if doesn't exist # Create channel if doesn't exist
channel ||= DiscourseChat::Channel.create!(provider:provider, data:{identifier: channel_id}) channel ||= DiscourseChat::Channel.create!(provider: provider, data: { identifier: channel_id })
if tokens[0] == 'post' if tokens[0] == 'post'
return process_post_request(channel, tokens, params[:channel_id]) return process_post_request(channel, tokens, params[:channel_id])
@ -68,7 +68,7 @@ module DiscourseChat::Provider::SlackProvider
# Load the user data (we need this to change user IDs into usernames) # Load the user data (we need this to change user IDs into usernames)
req = Net::HTTP::Post.new(URI('https://slack.com/api/users.list')) req = Net::HTTP::Post.new(URI('https://slack.com/api/users.list'))
req.set_form_data({token: SiteSetting.chat_integration_slack_access_token}) req.set_form_data(token: SiteSetting.chat_integration_slack_access_token)
response = http.request(req) response = http.request(req)
return error_text unless response.kind_of? Net::HTTPSuccess return error_text unless response.kind_of? Net::HTTPSuccess
json = JSON.parse(response.body) json = JSON.parse(response.body)
@ -91,7 +91,7 @@ module DiscourseChat::Provider::SlackProvider
return error_text unless json['ok'] return error_text unless json['ok']
first_post_link = "https://slack.com/archives/#{slack_channel_id}/p" first_post_link = "https://slack.com/archives/#{slack_channel_id}/p"
first_post_link += json["messages"].reverse.first["ts"].gsub('.','') first_post_link += json["messages"].reverse.first["ts"].gsub('.', '')
post_content = "" post_content = ""
@ -106,7 +106,7 @@ module DiscourseChat::Provider::SlackProvider
username = "" username = ""
if user_id = message["user"] if user_id = message["user"]
user = users.find{|u| u["id"] == user_id} user = users.find { |u| u["id"] == user_id }
users_in_transcript << user users_in_transcript << user
username = user["name"] username = user["name"]
elsif message.key?("username") elsif message.key?("username")
@ -128,7 +128,7 @@ module DiscourseChat::Provider::SlackProvider
text.gsub!(/<(.*?)>/) do |match| text.gsub!(/<(.*?)>/) do |match|
group = $1 group = $1
parts = group.split('|') parts = group.split('|')
link = parts[0].start_with?('@','#','!') ? '' : parts[0] link = parts[0].start_with?('@', '#', '!') ? '' : parts[0]
text = parts.length > 1 ? parts[1] : parts[0] text = parts.length > 1 ? parts[1] : parts[0]
"[#{text}](#{link})" "[#{text}](#{link})"
end end
@ -176,7 +176,7 @@ module DiscourseChat::Provider::SlackProvider
end end
class SlackEngine < ::Rails::Engine class SlackEngine < ::Rails::Engine
engine_name DiscourseChat::PLUGIN_NAME+"-slack" engine_name DiscourseChat::PLUGIN_NAME + "-slack"
isolate_namespace DiscourseChat::Provider::SlackProvider isolate_namespace DiscourseChat::Provider::SlackProvider
end end
@ -185,6 +185,3 @@ module DiscourseChat::Provider::SlackProvider
end end
end end

View File

@ -1,16 +1,16 @@
class ChatIntegrationSlackEnabledSettingValidator class ChatIntegrationSlackEnabledSettingValidator
def initialize(opts={}) def initialize(opts = {})
@opts = opts @opts = opts
end end
def valid_value?(val) def valid_value?(val)
return true if val == 'f' or val == false return true if val == ('f') || val == (false)
return false if SiteSetting.chat_integration_slack_outbound_webhook_url.blank? && SiteSetting.chat_integration_slack_access_token.blank? return false if SiteSetting.chat_integration_slack_outbound_webhook_url.blank? && SiteSetting.chat_integration_slack_access_token.blank?
true true
end end
def error_message def error_message
I18n.t('site_settings.errors.chat_integration_slack_api_configs_are_empty') I18n.t('site_settings.errors.chat_integration_slack_api_configs_are_empty')
end end
end end

View File

@ -4,7 +4,7 @@ module DiscourseChat::Provider::SlackProvider
PROVIDER_ENABLED_SETTING = :chat_integration_slack_enabled PROVIDER_ENABLED_SETTING = :chat_integration_slack_enabled
CHANNEL_PARAMETERS = [ CHANNEL_PARAMETERS = [
{key: "identifier", regex: '^[@#]\S*$', unique: true} { key: "identifier", regex: '^[@#]\S*$', unique: true }
] ]
def self.excerpt(post, max_length = SiteSetting.chat_integration_slack_excerpt_length) def self.excerpt(post, max_length = SiteSetting.chat_integration_slack_excerpt_length)
@ -28,7 +28,7 @@ module DiscourseChat::Provider::SlackProvider
category = '' category = ''
if topic.category if topic.category
category = (topic.category.parent_category) ? "[#{topic.category.parent_category.name}/#{topic.category.name}]": "[#{topic.category.name}]" category = (topic.category.parent_category) ? "[#{topic.category.parent_category.name}/#{topic.category.name}]" : "[#{topic.category.name}]"
end end
icon_url = icon_url =
@ -56,8 +56,8 @@ module DiscourseChat::Provider::SlackProvider
record = DiscourseChat.pstore_get("topic_#{post.topic.id}_#{channel}") record = DiscourseChat.pstore_get("topic_#{post.topic.id}_#{channel}")
if (SiteSetting.chat_integration_slack_access_token.empty? || post.is_first_post? || record.blank? || (record.present? && ((Time.now.to_i - record[:ts].split('.')[0].to_i)/ 60) >= 5 )) if (SiteSetting.chat_integration_slack_access_token.empty? || post.is_first_post? || record.blank? || (record.present? && ((Time.now.to_i - record[:ts].split('.')[0].to_i) / 60) >= 5))
summary[:title] = "#{topic.title} #{(category == '[uncategorized]')? '' : category} #{topic.tags.present? ? topic.tags.map(&:name).join(', ') : ''}" summary[:title] = "#{topic.title} #{(category == '[uncategorized]') ? '' : category} #{topic.tags.present? ? topic.tags.map(&:name).join(', ') : ''}"
summary[:title_link] = post.full_url summary[:title_link] = post.full_url
summary[:thumb_url] = post.full_url summary[:thumb_url] = post.full_url
end end
@ -67,14 +67,14 @@ module DiscourseChat::Provider::SlackProvider
end end
def self.send_via_api(post, channel, message) def self.send_via_api(post, channel, message)
http = Net::HTTP.new("slack.com", 443) http = Net::HTTP.new("slack.com", 443)
http.use_ssl = true http.use_ssl = true
response = nil response = nil
uri = "" uri = ""
record = DiscourseChat.pstore_get("slack_topic_#{post.topic.id}_#{channel}") record = DiscourseChat.pstore_get("slack_topic_#{post.topic.id}_#{channel}")
if (record.present? && ((Time.now.to_i - record[:ts].split('.')[0].to_i)/ 60) < 5 && record[:message][:attachments].length < 5) if (record.present? && ((Time.now.to_i - record[:ts].split('.')[0].to_i) / 60) < 5 && record[:message][:attachments].length < 5)
attachments = record[:message][:attachments] attachments = record[:message][:attachments]
attachments.concat message[:attachments] attachments.concat message[:attachments]
@ -99,54 +99,53 @@ module DiscourseChat::Provider::SlackProvider
response = http.request(Net::HTTP::Post.new(uri)) response = http.request(Net::HTTP::Post.new(uri))
unless response.kind_of? Net::HTTPSuccess unless response.kind_of? Net::HTTPSuccess
raise ::DiscourseChat::ProviderError.new info: {request: uri, response_code:response.code, response_body:response.body} raise ::DiscourseChat::ProviderError.new info: { request: uri, response_code: response.code, response_body: response.body }
end end
json = JSON.parse(response.body) json = JSON.parse(response.body)
unless json["ok"] == true unless json["ok"] == true
if json.key?("error") and (json["error"] == 'channel_not_found' or json["error"] == 'is_archived') if json.key?("error") && (json["error"] == ('channel_not_found') || json["error"] == ('is_archived'))
error_key = 'chat_integration.provider.slack.errors.channel_not_found' error_key = 'chat_integration.provider.slack.errors.channel_not_found'
else else
error_key = json.to_s error_key = json.to_s
end end
raise ::DiscourseChat::ProviderError.new info: {error_key: error_key, request: uri, response_code:response.code, response_body:response.body} raise ::DiscourseChat::ProviderError.new info: { error_key: error_key, request: uri, response_code: response.code, response_body: response.body }
end end
DiscourseChat.pstore_set("slack_topic_#{post.topic.id}_#{channel}", JSON.parse(response.body) ) DiscourseChat.pstore_set("slack_topic_#{post.topic.id}_#{channel}", JSON.parse(response.body))
response response
end end
def self.send_via_webhook(message) def self.send_via_webhook(message)
http = Net::HTTP.new("hooks.slack.com", 443) http = Net::HTTP.new("hooks.slack.com", 443)
http.use_ssl = true http.use_ssl = true
req = Net::HTTP::Post.new(URI(SiteSetting.chat_integration_slack_outbound_webhook_url), 'Content-Type' =>'application/json') req = Net::HTTP::Post.new(URI(SiteSetting.chat_integration_slack_outbound_webhook_url), 'Content-Type' => 'application/json')
req.body = message.to_json req.body = message.to_json
response = http.request(req) response = http.request(req)
unless response.kind_of? Net::HTTPSuccess unless response.kind_of? Net::HTTPSuccess
if response.code.to_s == '403' if response.code.to_s == '403'
error_key = 'chat_integration.provider.slack.errors.action_prohibited' error_key = 'chat_integration.provider.slack.errors.action_prohibited'
elsif response.body == 'channel_not_found' or response.body == 'channel_is_archived' elsif response.body == ('channel_not_found') || response.body == ('channel_is_archived')
error_key = 'chat_integration.provider.slack.errors.channel_not_found' error_key = 'chat_integration.provider.slack.errors.channel_not_found'
else else
error_key = nil error_key = nil
end end
raise ::DiscourseChat::ProviderError.new info: {error_key: error_key, request: req.body, response_code:response.code, response_body:response.body} raise ::DiscourseChat::ProviderError.new info: { error_key: error_key, request: req.body, response_code: response.code, response_body: response.body }
end end
end end
def self.trigger_notification(post, channel) def self.trigger_notification(post, channel)
channel_id = channel.data['identifier'] channel_id = channel.data['identifier']
message = slack_message(post, channel_id) message = slack_message(post, channel_id)
if SiteSetting.chat_integration_slack_access_token.empty? if SiteSetting.chat_integration_slack_access_token.empty?
self.send_via_webhook(message) self.send_via_webhook(message)
else else
self.send_via_api(post, channel_id, message) self.send_via_api(post, channel_id, message)
end end
end end
end end

View File

@ -27,7 +27,7 @@ module DiscourseChat::Provider::TelegramProvider
DiscourseChat::Provider::TelegramProvider.sendMessage(message) DiscourseChat::Provider::TelegramProvider.sendMessage(message)
elsif params.key?('channel_post') and params['channel_post']['text'].include? '/getchatid' elsif params.key?('channel_post') && params['channel_post']['text'].include?('/getchatid')
chat_id = params['channel_post']['chat']['id'] chat_id = params['channel_post']['chat']['id']
message_text = I18n.t( message_text = I18n.t(
@ -46,7 +46,7 @@ module DiscourseChat::Provider::TelegramProvider
DiscourseChat::Provider::TelegramProvider.sendMessage(message) DiscourseChat::Provider::TelegramProvider.sendMessage(message)
end end
# Always give telegram a success message, otherwise we'll stop receiving webhooks # Always give telegram a success message, otherwise we'll stop receiving webhooks
data = { data = {
success: true success: true
} }
@ -58,7 +58,7 @@ module DiscourseChat::Provider::TelegramProvider
provider = DiscourseChat::Provider::TelegramProvider::PROVIDER_NAME provider = DiscourseChat::Provider::TelegramProvider::PROVIDER_NAME
channel = DiscourseChat::Channel.with_provider(provider).with_data_value('chat_id',chat_id).first channel = DiscourseChat::Channel.with_provider(provider).with_data_value('chat_id', chat_id).first
if channel.nil? if channel.nil?
return I18n.t( return I18n.t(
@ -97,11 +97,11 @@ module DiscourseChat::Provider::TelegramProvider
end end
class TelegramEngine < ::Rails::Engine class TelegramEngine < ::Rails::Engine
engine_name DiscourseChat::PLUGIN_NAME+"-telegram" engine_name DiscourseChat::PLUGIN_NAME + "-telegram"
isolate_namespace DiscourseChat::Provider::TelegramProvider isolate_namespace DiscourseChat::Provider::TelegramProvider
end end
TelegramEngine.routes.draw do TelegramEngine.routes.draw do
post "command/:token" => "telegram_command#command" post "command/:token" => "telegram_command#command"
end end
end end

View File

@ -1,8 +1,8 @@
DiscourseEvent.on(:site_setting_saved) do |sitesetting| DiscourseEvent.on(:site_setting_saved) do |sitesetting|
isEnabledSetting = sitesetting.name == 'chat_integration_telegram_enabled' isEnabledSetting = sitesetting.name == 'chat_integration_telegram_enabled'
isAccessToken = sitesetting.name == 'chat_integration_telegram_access_token' isAccessToken = sitesetting.name == 'chat_integration_telegram_access_token'
if (isEnabledSetting or isAccessToken) if (isEnabledSetting || isAccessToken)
enabled = isEnabledSetting ? sitesetting.value == 't' : SiteSetting.chat_integration_telegram_enabled enabled = isEnabledSetting ? sitesetting.value == 't' : SiteSetting.chat_integration_telegram_enabled
if enabled if enabled
Scheduler::Defer.later("Setup Telegram Webhook") do Scheduler::Defer.later("Setup Telegram Webhook") do

View File

@ -4,8 +4,8 @@ module DiscourseChat
PROVIDER_NAME = "telegram".freeze PROVIDER_NAME = "telegram".freeze
PROVIDER_ENABLED_SETTING = :chat_integration_telegram_enabled PROVIDER_ENABLED_SETTING = :chat_integration_telegram_enabled
CHANNEL_PARAMETERS = [ CHANNEL_PARAMETERS = [
{key: "name", regex: '^\S+'}, { key: "name", regex: '^\S+' },
{key: "chat_id", regex: '^(-?[0-9]+|@\S+)$', unique: true} { key: "chat_id", regex: '^(-?[0-9]+|@\S+)$', unique: true }
] ]
def self.setup_webhook def self.setup_webhook
@ -13,7 +13,7 @@ module DiscourseChat
SiteSetting.chat_integration_telegram_secret = newSecret SiteSetting.chat_integration_telegram_secret = newSecret
message = { message = {
url: Discourse.base_url+'/chat-integration/telegram/command/'+newSecret, url: Discourse.base_url + '/chat-integration/telegram/command/' + newSecret,
} }
response = self.do_api_request('setWebhook', message) response = self.do_api_request('setWebhook', message)
@ -21,7 +21,7 @@ module DiscourseChat
if not response['ok'] == true if not response['ok'] == true
# If setting up webhook failed, disable provider # If setting up webhook failed, disable provider
SiteSetting.chat_integration_telegram_enabled = false SiteSetting.chat_integration_telegram_enabled = false
Rails.logger.error("Failed to setup telegram webhook. Message data= "+message.to_json+ " response="+response.to_json) Rails.logger.error("Failed to setup telegram webhook. Message data= " + message.to_json + " response=" + response.to_json)
end end
end end
@ -38,7 +38,7 @@ module DiscourseChat
uri = URI("https://api.telegram.org/bot#{access_token}/#{methodName}") uri = URI("https://api.telegram.org/bot#{access_token}/#{methodName}")
req = Net::HTTP::Post.new(uri, 'Content-Type' =>'application/json') req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
req.body = message.to_json req.body = message.to_json
response = http.request(req) response = http.request(req)
@ -59,7 +59,7 @@ module DiscourseChat
category = '' category = ''
if topic.category if topic.category
category = (topic.category.parent_category) ? "[#{topic.category.parent_category.name}/#{topic.category.name}]": "[#{topic.category.name}]" category = (topic.category.parent_category) ? "[#{topic.category.parent_category.name}/#{topic.category.name}]" : "[#{topic.category.name}]"
end end
tags = '' tags = ''
@ -96,7 +96,7 @@ module DiscourseChat
elsif response['description'].include? 'Forbidden' elsif response['description'].include? 'Forbidden'
error_key = 'chat_integration.provider.telegram.errors.forbidden' error_key = 'chat_integration.provider.telegram.errors.forbidden'
end end
raise ::DiscourseChat::ProviderError.new info: {error_key: error_key, message: message, response_body:response} raise ::DiscourseChat::ProviderError.new info: { error_key: error_key, message: message, response_body: response }
end end
end end

View File

@ -8,7 +8,7 @@ describe 'Chat Controller', type: :request do
let(:category) { Fabricate(:category) } let(:category) { Fabricate(:category) }
let(:category2) { Fabricate(:category) } let(:category2) { Fabricate(:category) }
let(:tag) { Fabricate(:tag) } let(:tag) { Fabricate(:tag) }
let(:channel) { DiscourseChat::Channel.create(provider:'dummy') } let(:channel) { DiscourseChat::Channel.create(provider: 'dummy') }
include_context "dummy provider" include_context "dummy provider"
include_context "validated dummy provider" include_context "validated dummy provider"
@ -49,9 +49,9 @@ describe 'Chat Controller', type: :request do
expect(json['providers'].size).to eq(2) expect(json['providers'].size).to eq(2)
expect(json['providers'].find{|h| h['name']=='dummy'}).to eq('name'=> 'dummy', expect(json['providers'].find { |h| h['name'] == 'dummy' }).to eq('name' => 'dummy',
'id'=> 'dummy', 'id' => 'dummy',
'channel_parameters'=> [] 'channel_parameters' => []
) )
end end
end end
@ -90,9 +90,9 @@ describe 'Chat Controller', type: :request do
end end
it 'should return the right response' do it 'should return the right response' do
rule = DiscourseChat::Rule.create(channel: channel, filter:'follow', category_id:category.id, tags:[tag.name]) rule = DiscourseChat::Rule.create(channel: channel, filter: 'follow', category_id: category.id, tags: [tag.name])
get '/admin/plugins/chat/channels.json', provider:'dummy' get '/admin/plugins/chat/channels.json', provider: 'dummy'
expect(response).to be_success expect(response).to be_success
@ -105,12 +105,12 @@ describe 'Chat Controller', type: :request do
"provider" => 'dummy', "provider" => 'dummy',
"data" => {}, "data" => {},
"error_key" => nil, "error_key" => nil,
"rules" => [{"id" => rule.id, "type" => 'normal', "group_name" => nil, "group_id" => nil, "filter" => "follow", "channel_id" => channel.id, "category_id" => category.id, "tags" => [tag.name]}] "rules" => [{ "id" => rule.id, "type" => 'normal', "group_name" => nil, "group_id" => nil, "filter" => "follow", "channel_id" => channel.id, "category_id" => category.id, "tags" => [tag.name] }]
) )
end end
it 'should fail for invalid provider' do it 'should fail for invalid provider' do
get '/admin/plugins/chat/channels.json', provider:'someprovider' get '/admin/plugins/chat/channels.json', provider: 'someprovider'
expect(response).not_to be_success expect(response).not_to be_success
end end
@ -129,7 +129,7 @@ describe 'Chat Controller', type: :request do
it 'should be able to add a new channel' do it 'should be able to add a new channel' do
post '/admin/plugins/chat/channels.json', post '/admin/plugins/chat/channels.json',
channel:{ channel: {
provider: 'dummy', provider: 'dummy',
data: {} data: {}
} }
@ -143,9 +143,9 @@ describe 'Chat Controller', type: :request do
it 'should fail for invalid params' do it 'should fail for invalid params' do
post '/admin/plugins/chat/channels.json', post '/admin/plugins/chat/channels.json',
channel:{ channel: {
provider: 'dummy2', provider: 'dummy2',
data: {val: 'something with whitespace'} data: { val: 'something with whitespace' }
} }
expect(response).not_to be_success expect(response).not_to be_success
@ -155,7 +155,7 @@ describe 'Chat Controller', type: :request do
end end
describe 'updating a channel' do describe 'updating a channel' do
let(:channel){DiscourseChat::Channel.create(provider:'dummy2', data:{val:"something"})} let(:channel) { DiscourseChat::Channel.create(provider: 'dummy2', data: { val: "something" }) }
include_examples 'admin constraints', 'put', "/admin/plugins/chat/channels/1.json" include_examples 'admin constraints', 'put', "/admin/plugins/chat/channels/1.json"
@ -167,20 +167,20 @@ describe 'Chat Controller', type: :request do
it 'should be able update a channel' do it 'should be able update a channel' do
put "/admin/plugins/chat/channels/#{channel.id}.json", put "/admin/plugins/chat/channels/#{channel.id}.json",
channel:{ channel: {
data: {val: "something-else"} data: { val: "something-else" }
} }
expect(response).to be_success expect(response).to be_success
channel = DiscourseChat::Channel.all.first channel = DiscourseChat::Channel.all.first
expect(channel.data).to eq({"val" => "something-else"}) expect(channel.data).to eq("val" => "something-else")
end end
it 'should fail for invalid params' do it 'should fail for invalid params' do
put "/admin/plugins/chat/channels/#{channel.id}.json", put "/admin/plugins/chat/channels/#{channel.id}.json",
channel:{ channel: {
data: {val: "something with whitespace"} data: { val: "something with whitespace" }
} }
expect(response).not_to be_success expect(response).not_to be_success
@ -190,7 +190,7 @@ describe 'Chat Controller', type: :request do
end end
describe 'deleting a channel' do describe 'deleting a channel' do
let(:channel){DiscourseChat::Channel.create(provider:'dummy', data:{})} let(:channel) { DiscourseChat::Channel.create(provider: 'dummy', data: {}) }
include_examples 'admin constraints', 'delete', "/admin/plugins/chat/channels/1.json" include_examples 'admin constraints', 'delete', "/admin/plugins/chat/channels/1.json"
@ -221,7 +221,7 @@ describe 'Chat Controller', type: :request do
it 'should be able to add a new rule' do it 'should be able to add a new rule' do
post '/admin/plugins/chat/rules.json', post '/admin/plugins/chat/rules.json',
rule:{ rule: {
channel_id: channel.id, channel_id: channel.id,
category_id: category.id, category_id: category.id,
filter: 'watch', filter: 'watch',
@ -241,7 +241,7 @@ describe 'Chat Controller', type: :request do
it 'should fail for invalid params' do it 'should fail for invalid params' do
post '/admin/plugins/chat/rules.json', post '/admin/plugins/chat/rules.json',
rule:{ rule: {
channel_id: channel.id, channel_id: channel.id,
category_id: category.id, category_id: category.id,
filter: 'watch', filter: 'watch',
@ -255,7 +255,7 @@ describe 'Chat Controller', type: :request do
end end
describe 'updating a rule' do describe 'updating a rule' do
let(:rule){DiscourseChat::Rule.create(channel: channel, filter:'follow', category_id:category.id, tags:[tag.name])} let(:rule) { DiscourseChat::Rule.create(channel: channel, filter: 'follow', category_id: category.id, tags: [tag.name]) }
include_examples 'admin constraints', 'put', "/admin/plugins/chat/rules/1.json" include_examples 'admin constraints', 'put', "/admin/plugins/chat/rules/1.json"
@ -267,7 +267,7 @@ describe 'Chat Controller', type: :request do
it 'should be able update a rule' do it 'should be able update a rule' do
put "/admin/plugins/chat/rules/#{rule.id}.json", put "/admin/plugins/chat/rules/#{rule.id}.json",
rule:{ rule: {
channel_id: channel.id, channel_id: channel.id,
category_id: category2.id, category_id: category2.id,
filter: rule.filter, filter: rule.filter,
@ -282,7 +282,7 @@ describe 'Chat Controller', type: :request do
it 'should fail for invalid params' do it 'should fail for invalid params' do
put "/admin/plugins/chat/rules/#{rule.id}.json", put "/admin/plugins/chat/rules/#{rule.id}.json",
rule:{ rule: {
channel_id: channel.id, channel_id: channel.id,
category_id: category.id, category_id: category.id,
filter: 'watch', filter: 'watch',
@ -296,7 +296,7 @@ describe 'Chat Controller', type: :request do
end end
describe 'deleting a rule' do describe 'deleting a rule' do
let(:rule){DiscourseChat::Rule.create(channel_id: channel.id, filter:'follow', category_id:category.id, tags:[tag.name])} let(:rule) { DiscourseChat::Rule.create(channel_id: channel.id, filter: 'follow', category_id: category.id, tags: [tag.name]) }
include_examples 'admin constraints', 'delete', "/admin/plugins/chat/rules/1.json" include_examples 'admin constraints', 'delete', "/admin/plugins/chat/rules/1.json"

View File

@ -21,7 +21,7 @@ RSpec.shared_context "dummy provider" do
end end
def self.sent_to_channel_ids def self.sent_to_channel_ids
@@sent_messages.map{|x| x[:channel].id} @@sent_messages.map { |x| x[:channel].id }
end end
def self.set_raise_exception(bool) def self.set_raise_exception(bool)
@ -34,7 +34,7 @@ RSpec.shared_context "dummy provider" do
::DiscourseChat::Provider.send(:remove_const, :DummyProvider) ::DiscourseChat::Provider.send(:remove_const, :DummyProvider)
end end
let(:provider){::DiscourseChat::Provider::DummyProvider} let(:provider) { ::DiscourseChat::Provider::DummyProvider }
end end
RSpec.shared_context "validated dummy provider" do RSpec.shared_context "validated dummy provider" do
@ -43,7 +43,7 @@ RSpec.shared_context "validated dummy provider" do
PROVIDER_NAME = "dummy2".freeze PROVIDER_NAME = "dummy2".freeze
PROVIDER_ENABLED_SETTING = :chat_integration_enabled # Tie to main plugin enabled setting PROVIDER_ENABLED_SETTING = :chat_integration_enabled # Tie to main plugin enabled setting
CHANNEL_PARAMETERS = [ CHANNEL_PARAMETERS = [
{key: "val", regex: '^\S+$', unique: true} { key: "val", regex: '^\S+$', unique: true }
] ]
@@sent_messages = [] @@sent_messages = []

View File

@ -4,55 +4,55 @@ require_relative '../dummy_provider'
RSpec.describe DiscourseChat::Manager do RSpec.describe DiscourseChat::Manager do
include_context "dummy provider" include_context "dummy provider"
let(:chan1){DiscourseChat::Channel.create!(provider:'dummy')} let(:chan1) { DiscourseChat::Channel.create!(provider: 'dummy') }
let(:chan2){DiscourseChat::Channel.create!(provider:'dummy')} let(:chan2) { DiscourseChat::Channel.create!(provider: 'dummy') }
let(:category) {Fabricate(:category)} let(:category) { Fabricate(:category) }
let(:category) {Fabricate(:category)} let(:category) { Fabricate(:category) }
let(:tag1){Fabricate(:tag)} let(:tag1) { Fabricate(:tag) }
let(:tag2){Fabricate(:tag)} let(:tag2) { Fabricate(:tag) }
let(:tag3){Fabricate(:tag)} let(:tag3) { Fabricate(:tag) }
describe '.process_command' do describe '.process_command' do
describe 'add new rule' do describe 'add new rule' do
# Not testing how filters are merged here, that's done in .smart_create_rule # Not testing how filters are merged here, that's done in .smart_create_rule
# We just want to make sure the commands are being interpretted correctly # We just want to make sure the commands are being interpretted correctly
it 'should add a new rule correctly' do it 'should add a new rule correctly' do
response = DiscourseChat::Helper.process_command(chan1, ['watch',category.slug]) response = DiscourseChat::Helper.process_command(chan1, ['watch', category.slug])
expect(response).to eq(I18n.t("chat_integration.provider.dummy.create.created")) expect(response).to eq(I18n.t("chat_integration.provider.dummy.create.created"))
rule = DiscourseChat::Rule.all.first rule = DiscourseChat::Rule.all.first
expect(rule.channel).to eq(chan1) expect(rule.channel).to eq(chan1)
expect(rule.filter).to eq('watch') expect(rule.filter).to eq('watch')
expect(rule.category_id).to eq(category.id) expect(rule.category_id).to eq(category.id)
expect(rule.tags).to eq(nil) expect(rule.tags).to eq(nil)
end end
it 'should work with all three filter types' do it 'should work with all three filter types' do
response = DiscourseChat::Helper.process_command(chan1, ['watch',category.slug]) response = DiscourseChat::Helper.process_command(chan1, ['watch', category.slug])
rule = DiscourseChat::Rule.all.first rule = DiscourseChat::Rule.all.first
expect(rule.filter).to eq('watch') expect(rule.filter).to eq('watch')
response = DiscourseChat::Helper.process_command(chan1, ['follow',category.slug]) response = DiscourseChat::Helper.process_command(chan1, ['follow', category.slug])
rule = DiscourseChat::Rule.all.first rule = DiscourseChat::Rule.all.first
expect(rule.filter).to eq('follow') expect(rule.filter).to eq('follow')
response = DiscourseChat::Helper.process_command(chan1, ['mute',category.slug]) response = DiscourseChat::Helper.process_command(chan1, ['mute', category.slug])
rule = DiscourseChat::Rule.all.first rule = DiscourseChat::Rule.all.first
expect(rule.filter).to eq('mute') expect(rule.filter).to eq('mute')
end end
it 'errors on incorrect categories' do it 'errors on incorrect categories' do
response = DiscourseChat::Helper.process_command(chan1, ['watch','blah']) response = DiscourseChat::Helper.process_command(chan1, ['watch', 'blah'])
expect(response).to eq(I18n.t("chat_integration.provider.dummy.not_found.category", name:'blah', list:'uncategorized')) expect(response).to eq(I18n.t("chat_integration.provider.dummy.not_found.category", name: 'blah', list: 'uncategorized'))
end end
context 'with tags enabled' do context 'with tags enabled' do
@ -61,7 +61,7 @@ RSpec.describe DiscourseChat::Manager do
end end
it 'should add a new tag rule correctly' do it 'should add a new tag rule correctly' do
response = DiscourseChat::Helper.process_command(chan1, ['watch',"tag:#{tag1.name}"]) response = DiscourseChat::Helper.process_command(chan1, ['watch', "tag:#{tag1.name}"])
expect(response).to eq(I18n.t("chat_integration.provider.dummy.create.created")) expect(response).to eq(I18n.t("chat_integration.provider.dummy.create.created"))
@ -74,7 +74,7 @@ RSpec.describe DiscourseChat::Manager do
it 'should work with a category and multiple tags' do it 'should work with a category and multiple tags' do
response = DiscourseChat::Helper.process_command(chan1, ['watch',category.slug, "tag:#{tag1.name}", "tag:#{tag2.name}"]) response = DiscourseChat::Helper.process_command(chan1, ['watch', category.slug, "tag:#{tag1.name}", "tag:#{tag2.name}"])
expect(response).to eq(I18n.t("chat_integration.provider.dummy.create.created")) expect(response).to eq(I18n.t("chat_integration.provider.dummy.create.created"))
@ -86,23 +86,23 @@ RSpec.describe DiscourseChat::Manager do
end end
it 'errors on incorrect tags' do it 'errors on incorrect tags' do
response = DiscourseChat::Helper.process_command(chan1, ['watch',category.slug, "tag:blah"]) response = DiscourseChat::Helper.process_command(chan1, ['watch', category.slug, "tag:blah"])
expect(response).to eq(I18n.t("chat_integration.provider.dummy.not_found.tag", name:"blah")) expect(response).to eq(I18n.t("chat_integration.provider.dummy.not_found.tag", name: "blah"))
end end
end end
end end
describe 'remove rule' do describe 'remove rule' do
it 'removes the rule' do it 'removes the rule' do
rule1 = DiscourseChat::Rule.create(channel: chan1, rule1 = DiscourseChat::Rule.create(channel: chan1,
filter: 'watch', filter: 'watch',
category_id: category.id, category_id: category.id,
tags: [tag1.name, tag2.name] tags: [tag1.name, tag2.name]
) )
expect(DiscourseChat::Rule.all.size).to eq(1) expect(DiscourseChat::Rule.all.size).to eq(1)
response = DiscourseChat::Helper.process_command(chan1, ['remove','1']) response = DiscourseChat::Helper.process_command(chan1, ['remove', '1'])
expect(response).to eq(I18n.t("chat_integration.provider.dummy.delete.success")) expect(response).to eq(I18n.t("chat_integration.provider.dummy.delete.success"))
@ -110,7 +110,7 @@ RSpec.describe DiscourseChat::Manager do
end end
it 'errors correctly' do it 'errors correctly' do
response = DiscourseChat::Helper.process_command(chan1, ['remove','1']) response = DiscourseChat::Helper.process_command(chan1, ['remove', '1'])
expect(response).to eq(I18n.t("chat_integration.provider.dummy.delete.error")) expect(response).to eq(I18n.t("chat_integration.provider.dummy.delete.error"))
end end
end end
@ -152,13 +152,13 @@ RSpec.describe DiscourseChat::Manager do
end end
context 'with some rules' do context 'with some rules' do
let(:group){Fabricate(:group)} let(:group) { Fabricate(:group) }
before do before do
DiscourseChat::Rule.create!(channel: chan1, filter:'watch', category_id:category.id, tags:nil) DiscourseChat::Rule.create!(channel: chan1, filter: 'watch', category_id: category.id, tags: nil)
DiscourseChat::Rule.create!(channel: chan1, filter:'mute', category_id:nil, tags:nil) DiscourseChat::Rule.create!(channel: chan1, filter: 'mute', category_id: nil, tags: nil)
DiscourseChat::Rule.create!(channel: chan1, filter:'follow', category_id:nil, tags:[tag1.name]) DiscourseChat::Rule.create!(channel: chan1, filter: 'follow', category_id: nil, tags: [tag1.name])
DiscourseChat::Rule.create!(channel: chan1, filter:'watch', type: 'group_message', group_id:group.id) DiscourseChat::Rule.create!(channel: chan1, filter: 'watch', type: 'group_message', group_id: group.id)
DiscourseChat::Rule.create!(channel: chan2, filter:'watch', category_id:1, tags:nil) DiscourseChat::Rule.create!(channel: chan2, filter: 'watch', category_id: 1, tags: nil)
end end
it 'displays the correct rules' do it 'displays the correct rules' do
@ -180,32 +180,32 @@ RSpec.describe DiscourseChat::Manager do
end end
describe '.delete_by_index' do describe '.delete_by_index' do
let(:category2) {Fabricate(:category)} let(:category2) { Fabricate(:category) }
let(:category3) {Fabricate(:category)} let(:category3) { Fabricate(:category) }
it 'deletes the correct rule' do it 'deletes the correct rule' do
# Three identical rules, with different filters # Three identical rules, with different filters
# Status will be sorted by precedence # Status will be sorted by precedence
# be in this order # be in this order
rule1 = DiscourseChat::Rule.create(channel: chan1, rule1 = DiscourseChat::Rule.create(channel: chan1,
filter: 'mute', filter: 'mute',
category_id: category.id, category_id: category.id,
tags: [tag1.name, tag2.name] tags: [tag1.name, tag2.name]
) )
rule2 = DiscourseChat::Rule.create(channel: chan1, rule2 = DiscourseChat::Rule.create(channel: chan1,
filter: 'watch', filter: 'watch',
category_id: category2.id, category_id: category2.id,
tags: [tag1.name, tag2.name] tags: [tag1.name, tag2.name]
) )
rule3 = DiscourseChat::Rule.create(channel: chan1, rule3 = DiscourseChat::Rule.create(channel: chan1,
filter: 'follow', filter: 'follow',
category_id: category3.id, category_id: category3.id,
tags: [tag1.name, tag2.name] tags: [tag1.name, tag2.name]
) )
expect(DiscourseChat::Rule.all.size).to eq(3) expect(DiscourseChat::Rule.all.size).to eq(3)
expect(DiscourseChat::Helper.delete_by_index(chan1,2)).to eq(:deleted) expect(DiscourseChat::Helper.delete_by_index(chan1, 2)).to eq(:deleted)
expect(DiscourseChat::Rule.all.size).to eq(2) expect(DiscourseChat::Rule.all.size).to eq(2)
expect(DiscourseChat::Rule.all.map(&:category_id)).to contain_exactly(category.id, category3.id) expect(DiscourseChat::Rule.all.map(&:category_id)).to contain_exactly(category.id, category3.id)
@ -213,19 +213,18 @@ RSpec.describe DiscourseChat::Manager do
it 'fails gracefully for out of range indexes' do it 'fails gracefully for out of range indexes' do
rule1 = DiscourseChat::Rule.create(channel: chan1, rule1 = DiscourseChat::Rule.create(channel: chan1,
filter: 'watch', filter: 'watch',
category_id: category.id, category_id: category.id,
tags: [tag1.name, tag2.name] tags: [tag1.name, tag2.name]
) )
expect(DiscourseChat::Helper.delete_by_index(chan1,-1)).to eq(false) expect(DiscourseChat::Helper.delete_by_index(chan1, -1)).to eq(false)
expect(DiscourseChat::Helper.delete_by_index(chan1,0)).to eq(false) expect(DiscourseChat::Helper.delete_by_index(chan1, 0)).to eq(false)
expect(DiscourseChat::Helper.delete_by_index(chan1,2)).to eq(false) expect(DiscourseChat::Helper.delete_by_index(chan1, 2)).to eq(false)
expect(DiscourseChat::Helper.delete_by_index(chan1,1)).to eq(:deleted) expect(DiscourseChat::Helper.delete_by_index(chan1, 1)).to eq(:deleted)
end end
end end
describe '.smart_create_rule' do describe '.smart_create_rule' do
@ -246,10 +245,10 @@ RSpec.describe DiscourseChat::Manager do
end end
it 'updates a rule when it has the same category and tags' do it 'updates a rule when it has the same category and tags' do
existing = DiscourseChat::Rule.create!(channel:chan1, existing = DiscourseChat::Rule.create!(channel: chan1,
filter: 'watch', filter: 'watch',
category_id: category.id, category_id: category.id,
tags: [tag2.name, tag1.name] tags: [tag2.name, tag1.name]
) )
val = DiscourseChat::Helper.smart_create_rule(channel: chan1, val = DiscourseChat::Helper.smart_create_rule(channel: chan1,
@ -313,8 +312,8 @@ RSpec.describe DiscourseChat::Manager do
ttl = $redis.pttl("chat_integration:transcript:#{key}") ttl = $redis.pttl("chat_integration:transcript:#{key}")
# Slight hack since freeze_time doens't work on redis # Slight hack since freeze_time doens't work on redis
expect($redis.pttl("chat_integration:transcript:#{key}")).to be <= (3601*1000) expect($redis.pttl("chat_integration:transcript:#{key}")).to be <= (3601 * 1000)
expect($redis.pttl("chat_integration:transcript:#{key}")).to be >= (3599*1000) expect($redis.pttl("chat_integration:transcript:#{key}")).to be >= (3599 * 1000)
end end
end end

View File

@ -8,7 +8,7 @@ RSpec.describe DiscourseChat::Provider::DiscordProvider do
SiteSetting.chat_integration_discord_enabled = true SiteSetting.chat_integration_discord_enabled = true
end end
let(:chan1){DiscourseChat::Channel.create!(provider:'discord', data:{name: "Awesome Channel", webhook_url: 'https://discordapp.com/api/webhooks/1234/abcd'})} let(:chan1) { DiscourseChat::Channel.create!(provider: 'discord', data: { name: "Awesome Channel", webhook_url: 'https://discordapp.com/api/webhooks/1234/abcd' }) }
it 'sends a webhook request' do it 'sends a webhook request' do
stub1 = stub_request(:post, 'https://discordapp.com/api/webhooks/1234/abcd?wait=true').to_return(status: 200) stub1 = stub_request(:post, 'https://discordapp.com/api/webhooks/1234/abcd?wait=true').to_return(status: 200)
@ -18,8 +18,8 @@ RSpec.describe DiscourseChat::Provider::DiscordProvider do
it 'includes the protocol in the avatar URL' do it 'includes the protocol in the avatar URL' do
stub1 = stub_request(:post, 'https://discordapp.com/api/webhooks/1234/abcd?wait=true') stub1 = stub_request(:post, 'https://discordapp.com/api/webhooks/1234/abcd?wait=true')
.with(body: hash_including({embeds:[hash_including({author:hash_including({url:/^https?:\/\//})})]})) .with(body: hash_including(embeds: [hash_including(author: hash_including(url: /^https?:\/\//))]))
.to_return(status: 200) .to_return(status: 200)
described_class.trigger_notification(post, chan1) described_class.trigger_notification(post, chan1)
expect(stub1).to have_been_requested.once expect(stub1).to have_been_requested.once
end end
@ -27,7 +27,7 @@ RSpec.describe DiscourseChat::Provider::DiscordProvider do
it 'handles errors correctly' do it 'handles errors correctly' do
stub1 = stub_request(:post, "https://discordapp.com/api/webhooks/1234/abcd?wait=true").to_return(status: 400) stub1 = stub_request(:post, "https://discordapp.com/api/webhooks/1234/abcd?wait=true").to_return(status: 400)
expect(stub1).to have_been_requested.times(0) expect(stub1).to have_been_requested.times(0)
expect{described_class.trigger_notification(post, chan1)}.to raise_exception(::DiscourseChat::ProviderError) expect { described_class.trigger_notification(post, chan1) }.to raise_exception(::DiscourseChat::ProviderError)
expect(stub1).to have_been_requested.once expect(stub1).to have_been_requested.once
end end

View File

@ -8,7 +8,7 @@ RSpec.describe DiscourseChat::Provider::HipchatProvider do
SiteSetting.chat_integration_hipchat_enabled = true SiteSetting.chat_integration_hipchat_enabled = true
end end
let(:chan1){DiscourseChat::Channel.create!(provider:'hipchat', data:{name: "Awesome Channel", webhook_url: 'https://blah.hipchat.com/abcd', color: "red"})} let(:chan1) { DiscourseChat::Channel.create!(provider: 'hipchat', data: { name: "Awesome Channel", webhook_url: 'https://blah.hipchat.com/abcd', color: "red" }) }
it 'sends a webhook request' do it 'sends a webhook request' do
stub1 = stub_request(:post, 'https://blah.hipchat.com/abcd').to_return(status: 200) stub1 = stub_request(:post, 'https://blah.hipchat.com/abcd').to_return(status: 200)
@ -19,7 +19,7 @@ RSpec.describe DiscourseChat::Provider::HipchatProvider do
it 'handles errors correctly' do it 'handles errors correctly' do
stub1 = stub_request(:post, "https://blah.hipchat.com/abcd").to_return(status: 400) stub1 = stub_request(:post, "https://blah.hipchat.com/abcd").to_return(status: 400)
expect(stub1).to have_been_requested.times(0) expect(stub1).to have_been_requested.times(0)
expect{described_class.trigger_notification(post, chan1)}.to raise_exception(::DiscourseChat::ProviderError) expect { described_class.trigger_notification(post, chan1) }.to raise_exception(::DiscourseChat::ProviderError)
expect(stub1).to have_been_requested.once expect(stub1).to have_been_requested.once
end end

View File

@ -9,7 +9,7 @@ RSpec.describe DiscourseChat::Provider::MatrixProvider do
SiteSetting.chat_integration_matrix_access_token = 'abcd' SiteSetting.chat_integration_matrix_access_token = 'abcd'
end end
let(:chan1){DiscourseChat::Channel.create!(provider:'matrix', data:{name: "Awesome Channel", room_id: '!blah:matrix.org'})} let(:chan1) { DiscourseChat::Channel.create!(provider: 'matrix', data: { name: "Awesome Channel", room_id: '!blah:matrix.org' }) }
it 'sends the message' do it 'sends the message' do
stub1 = stub_request(:put, %r{https://matrix.org/_matrix/client/r0/rooms/!blah:matrix.org/send/m.room.message/*}).to_return(status: 200) stub1 = stub_request(:put, %r{https://matrix.org/_matrix/client/r0/rooms/!blah:matrix.org/send/m.room.message/*}).to_return(status: 200)
@ -18,9 +18,9 @@ RSpec.describe DiscourseChat::Provider::MatrixProvider do
end end
it 'handles errors correctly' do it 'handles errors correctly' do
stub1 = stub_request(:put, %r{https://matrix.org/_matrix/client/r0/rooms/!blah:matrix.org/send/m.room.message/*}).to_return(status: 400, body:'{"errmsg":"M_UNKNOWN"}') stub1 = stub_request(:put, %r{https://matrix.org/_matrix/client/r0/rooms/!blah:matrix.org/send/m.room.message/*}).to_return(status: 400, body: '{"errmsg":"M_UNKNOWN"}')
expect(stub1).to have_been_requested.times(0) expect(stub1).to have_been_requested.times(0)
expect{described_class.trigger_notification(post, chan1)}.to raise_exception(::DiscourseChat::ProviderError) expect { described_class.trigger_notification(post, chan1) }.to raise_exception(::DiscourseChat::ProviderError)
expect(stub1).to have_been_requested.once expect(stub1).to have_been_requested.once
end end

View File

@ -4,7 +4,7 @@ describe 'Mattermost Command Controller', type: :request do
let(:category) { Fabricate(:category) } let(:category) { Fabricate(:category) }
let(:tag) { Fabricate(:tag) } let(:tag) { Fabricate(:tag) }
let(:tag2) { Fabricate(:tag) } let(:tag2) { Fabricate(:tag) }
let!(:chan1){DiscourseChat::Channel.create!(provider:'mattermost', data:{identifier: '#welcome'})} let!(:chan1) { DiscourseChat::Channel.create!(provider: 'mattermost', data: { identifier: '#welcome' }) }
describe 'with plugin disabled' do describe 'with plugin disabled' do
it 'should return a 404' do it 'should return a 404' do
@ -99,7 +99,7 @@ describe 'Mattermost Command Controller', type: :request do
expect(json["text"]).to eq(I18n.t("chat_integration.provider.mattermost.create.created")) expect(json["text"]).to eq(I18n.t("chat_integration.provider.mattermost.create.created"))
chan = DiscourseChat::Channel.with_provider('mattermost').with_data_value('identifier','#general').first chan = DiscourseChat::Channel.with_provider('mattermost').with_data_value('identifier', '#general').first
expect(chan.provider).to eq('mattermost') expect(chan.provider).to eq('mattermost')
rule = chan.rules.first rule = chan.rules.first

View File

@ -9,7 +9,7 @@ RSpec.describe DiscourseChat::Provider::MattermostProvider do
SiteSetting.chat_integration_mattermost_webhook_url = "https://mattermost.blah/hook/abcd" SiteSetting.chat_integration_mattermost_webhook_url = "https://mattermost.blah/hook/abcd"
end end
let(:chan1){DiscourseChat::Channel.create!(provider:'mattermost', data:{identifier: "#awesomechannel"})} let(:chan1) { DiscourseChat::Channel.create!(provider: 'mattermost', data: { identifier: "#awesomechannel" }) }
it 'sends a webhook request' do it 'sends a webhook request' do
stub1 = stub_request(:post, 'https://mattermost.blah/hook/abcd').to_return(status: 200) stub1 = stub_request(:post, 'https://mattermost.blah/hook/abcd').to_return(status: 200)
@ -20,7 +20,7 @@ RSpec.describe DiscourseChat::Provider::MattermostProvider do
it 'handles errors correctly' do it 'handles errors correctly' do
stub1 = stub_request(:post, "https://mattermost.blah/hook/abcd").to_return(status: 500, body: "error") stub1 = stub_request(:post, "https://mattermost.blah/hook/abcd").to_return(status: 500, body: "error")
expect(stub1).to have_been_requested.times(0) expect(stub1).to have_been_requested.times(0)
expect{described_class.trigger_notification(post, chan1)}.to raise_exception(::DiscourseChat::ProviderError) expect { described_class.trigger_notification(post, chan1) }.to raise_exception(::DiscourseChat::ProviderError)
expect(stub1).to have_been_requested.once expect(stub1).to have_been_requested.once
end end

View File

@ -4,7 +4,7 @@ describe 'Slack Command Controller', type: :request do
let(:category) { Fabricate(:category) } let(:category) { Fabricate(:category) }
let(:tag) { Fabricate(:tag) } let(:tag) { Fabricate(:tag) }
let(:tag2) { Fabricate(:tag) } let(:tag2) { Fabricate(:tag) }
let!(:chan1){DiscourseChat::Channel.create!(provider:'slack', data:{identifier: '#welcome'})} let!(:chan1) { DiscourseChat::Channel.create!(provider: 'slack', data: { identifier: '#welcome' }) }
describe 'with plugin disabled' do describe 'with plugin disabled' do
it 'should return a 404' do it 'should return a 404' do
@ -99,7 +99,7 @@ describe 'Slack Command Controller', type: :request do
expect(json["text"]).to eq(I18n.t("chat_integration.provider.slack.create.created")) expect(json["text"]).to eq(I18n.t("chat_integration.provider.slack.create.created"))
chan = DiscourseChat::Channel.with_provider('slack').with_data_value('identifier','#general').first chan = DiscourseChat::Channel.with_provider('slack').with_data_value('identifier', '#general').first
expect(chan.provider).to eq('slack') expect(chan.provider).to eq('slack')
rule = chan.rules.first rule = chan.rules.first
@ -122,7 +122,7 @@ describe 'Slack Command Controller', type: :request do
post "/chat-integration/slack/command.json", post "/chat-integration/slack/command.json",
text: "post 2", text: "post 2",
channel_name: 'general', channel_name: 'general',
channel_id:'C6029G78F', channel_id: 'C6029G78F',
token: token token: token
json = JSON.parse(response.body) json = JSON.parse(response.body)
@ -136,7 +136,7 @@ describe 'Slack Command Controller', type: :request do
post "/chat-integration/slack/command.json", post "/chat-integration/slack/command.json",
text: "post 2", text: "post 2",
channel_name: 'general', channel_name: 'general',
channel_id:'C6029G78F', channel_id: 'C6029G78F',
token: token token: token
json = JSON.parse(response.body) json = JSON.parse(response.body)
@ -150,7 +150,7 @@ describe 'Slack Command Controller', type: :request do
post "/chat-integration/slack/command.json", post "/chat-integration/slack/command.json",
text: "post 2", text: "post 2",
channel_name: 'general', channel_name: 'general',
channel_id:'C6029G78F', channel_id: 'C6029G78F',
token: token token: token
json = JSON.parse(response.body) json = JSON.parse(response.body)

View File

@ -57,7 +57,7 @@ RSpec.describe DiscourseChat::Provider::SlackProvider do
SiteSetting.chat_integration_slack_enabled = true SiteSetting.chat_integration_slack_enabled = true
end end
let(:chan1){DiscourseChat::Channel.create!(provider:'slack', data:{identifier: '#general'})} let(:chan1) { DiscourseChat::Channel.create!(provider: 'slack', data: { identifier: '#general' }) }
it 'sends a webhook request' do it 'sends a webhook request' do
stub1 = stub_request(:post, SiteSetting.chat_integration_slack_outbound_webhook_url).to_return(body: "success") stub1 = stub_request(:post, SiteSetting.chat_integration_slack_outbound_webhook_url).to_return(body: "success")
@ -68,7 +68,7 @@ RSpec.describe DiscourseChat::Provider::SlackProvider do
it 'handles errors correctly' do it 'handles errors correctly' do
stub1 = stub_request(:post, SiteSetting.chat_integration_slack_outbound_webhook_url).to_return(status: 400, body: "error") stub1 = stub_request(:post, SiteSetting.chat_integration_slack_outbound_webhook_url).to_return(status: 400, body: "error")
expect(stub1).to have_been_requested.times(0) expect(stub1).to have_been_requested.times(0)
expect{described_class.trigger_notification(post, chan1)}.to raise_exception(::DiscourseChat::ProviderError) expect { described_class.trigger_notification(post, chan1) }.to raise_exception(::DiscourseChat::ProviderError)
expect(stub1).to have_been_requested.once expect(stub1).to have_been_requested.once
end end
@ -76,8 +76,8 @@ RSpec.describe DiscourseChat::Provider::SlackProvider do
before do before do
SiteSetting.chat_integration_slack_access_token = "magic" SiteSetting.chat_integration_slack_access_token = "magic"
@stub1 = stub_request(:post, SiteSetting.chat_integration_slack_outbound_webhook_url).to_return(body: "success") @stub1 = stub_request(:post, SiteSetting.chat_integration_slack_outbound_webhook_url).to_return(body: "success")
@stub2 = stub_request(:post, %r{https://slack.com/api/chat.postMessage}).to_return(body: "{\"ok\":true, \"ts\": \"#{Time.now.to_i}.012345\", \"message\": {\"attachments\": [], \"username\":\"blah\", \"text\":\"blah2\"} }", headers: {'Content-Type' => 'application/json'}) @stub2 = stub_request(:post, %r{https://slack.com/api/chat.postMessage}).to_return(body: "{\"ok\":true, \"ts\": \"#{Time.now.to_i}.012345\", \"message\": {\"attachments\": [], \"username\":\"blah\", \"text\":\"blah2\"} }", headers: { 'Content-Type' => 'application/json' })
@stub3 = stub_request(:post, %r{https://slack.com/api/chat.update}).to_return(body: '{"ok":true, "ts": "some_message_id"}', headers: {'Content-Type' => 'application/json'}) @stub3 = stub_request(:post, %r{https://slack.com/api/chat.update}).to_return(body: '{"ok":true, "ts": "some_message_id"}', headers: { 'Content-Type' => 'application/json' })
end end
it 'sends an api request' do it 'sends an api request' do
@ -89,13 +89,13 @@ RSpec.describe DiscourseChat::Provider::SlackProvider do
end end
it 'handles errors correctly' do it 'handles errors correctly' do
@stub2 = stub_request(:post, %r{https://slack.com/api/chat.postMessage}).to_return(body: "{\"ok\":false }", headers: {'Content-Type' => 'application/json'}) @stub2 = stub_request(:post, %r{https://slack.com/api/chat.postMessage}).to_return(body: "{\"ok\":false }", headers: { 'Content-Type' => 'application/json' })
expect{described_class.trigger_notification(post, chan1)}.to raise_exception(::DiscourseChat::ProviderError) expect { described_class.trigger_notification(post, chan1) }.to raise_exception(::DiscourseChat::ProviderError)
expect(@stub2).to have_been_requested.once expect(@stub2).to have_been_requested.once
end end
it 'correctly merges replies' do it 'correctly merges replies' do
second_post = Fabricate(:post, topic: post.topic, post_number:2) second_post = Fabricate(:post, topic: post.topic, post_number: 2)
expect(@stub2).to have_been_requested.times(0) expect(@stub2).to have_been_requested.times(0)
expect(@stub3).to have_been_requested.times(0) expect(@stub3).to have_been_requested.times(0)

View File

@ -2,7 +2,7 @@ require 'rails_helper'
describe 'Telegram Command Controller', type: :request do describe 'Telegram Command Controller', type: :request do
let(:category) { Fabricate(:category) } let(:category) { Fabricate(:category) }
let!(:chan1){DiscourseChat::Channel.create!(provider:'telegram', data:{name: 'Amazing Channel', chat_id:'123'})} let!(:chan1) { DiscourseChat::Channel.create!(provider: 'telegram', data: { name: 'Amazing Channel', chat_id: '123' }) }
describe 'with plugin disabled' do describe 'with plugin disabled' do
it 'should return a 404' do it 'should return a 404' do
@ -31,12 +31,12 @@ describe 'Telegram Command Controller', type: :request do
SiteSetting.chat_integration_telegram_enabled = true SiteSetting.chat_integration_telegram_enabled = true
end end
let!(:stub){stub_request(:post, 'https://api.telegram.org/botTOKEN/sendMessage').to_return(body: "{\"ok\":true}")} let!(:stub) { stub_request(:post, 'https://api.telegram.org/botTOKEN/sendMessage').to_return(body: "{\"ok\":true}") }
describe 'when forum is private' do describe 'when forum is private' do
it 'should not redirect to login page' do it 'should not redirect to login page' do
SiteSetting.login_required = true SiteSetting.login_required = true
post '/chat-integration/telegram/command/shhh.json', message: {chat: {id:123}, text: '/help' } post '/chat-integration/telegram/command/shhh.json', message: { chat: { id: 123 }, text: '/help' }
expect(response.status).to eq(200) expect(response.status).to eq(200)
end end
@ -44,7 +44,7 @@ describe 'Telegram Command Controller', type: :request do
describe 'when the token is invalid' do describe 'when the token is invalid' do
it 'should raise the right error' do it 'should raise the right error' do
post '/chat-integration/telegram/command/blah.json', message: {chat: {id:123}, text: '/help' } post '/chat-integration/telegram/command/blah.json', message: { chat: { id: 123 }, text: '/help' }
expect(response.status).to eq(403) expect(response.status).to eq(403)
end end
end end
@ -52,7 +52,7 @@ describe 'Telegram Command Controller', type: :request do
describe 'when token has not been set' do describe 'when token has not been set' do
it 'should raise the right error' do it 'should raise the right error' do
SiteSetting.chat_integration_telegram_access_token = "" SiteSetting.chat_integration_telegram_access_token = ""
post '/chat-integration/telegram/command/blah.json', message: {chat: {id:123}, text: '/help' } post '/chat-integration/telegram/command/blah.json', message: { chat: { id: 123 }, text: '/help' }
expect(response.status).to eq(403) expect(response.status).to eq(403)
end end
@ -68,7 +68,7 @@ describe 'Telegram Command Controller', type: :request do
describe 'add new rule' do describe 'add new rule' do
it 'should add a new rule correctly' do it 'should add a new rule correctly' do
post '/chat-integration/telegram/command/shhh.json', message: {chat: {id:123}, text: "/watch #{category.slug}" } post '/chat-integration/telegram/command/shhh.json', message: { chat: { id: 123 }, text: "/watch #{category.slug}" }
expect(response.status).to eq(200) expect(response.status).to eq(200)
expect(stub).to have_been_requested.once expect(stub).to have_been_requested.once
@ -81,7 +81,7 @@ describe 'Telegram Command Controller', type: :request do
end end
it 'should add a new rule correctly using group chat syntax' do it 'should add a new rule correctly using group chat syntax' do
post '/chat-integration/telegram/command/shhh.json', message: {chat: {id:123}, text: "/watch@my-awesome-bot #{category.slug}" } post '/chat-integration/telegram/command/shhh.json', message: { chat: { id: 123 }, text: "/watch@my-awesome-bot #{category.slug}" }
expect(response.status).to eq(200) expect(response.status).to eq(200)
expect(stub).to have_been_requested.once expect(stub).to have_been_requested.once
@ -95,7 +95,7 @@ describe 'Telegram Command Controller', type: :request do
context 'from an unknown channel' do context 'from an unknown channel' do
it 'does nothing' do it 'does nothing' do
post '/chat-integration/telegram/command/shhh.json', message: {chat: {id:456}, text: "/watch #{category.slug}" } post '/chat-integration/telegram/command/shhh.json', message: { chat: { id: 456 }, text: "/watch #{category.slug}" }
expect(DiscourseChat::Rule.all.size).to eq(0) expect(DiscourseChat::Rule.all.size).to eq(0)
expect(DiscourseChat::Channel.all.size).to eq(1) expect(DiscourseChat::Channel.all.size).to eq(1)
end end
@ -103,12 +103,12 @@ describe 'Telegram Command Controller', type: :request do
end end
it "should respond only to a specific command in a broadcast channel" do it "should respond only to a specific command in a broadcast channel" do
post '/chat-integration/telegram/command/shhh.json', channel_post: {chat: {id:123}, text: "something" } post '/chat-integration/telegram/command/shhh.json', channel_post: { chat: { id: 123 }, text: "something" }
expect(response.status).to eq(200) expect(response.status).to eq(200)
expect(stub).to have_been_requested.times(0) expect(stub).to have_been_requested.times(0)
post '/chat-integration/telegram/command/shhh.json', channel_post: {chat: {id:123}, text: "/getchatid" } post '/chat-integration/telegram/command/shhh.json', channel_post: { chat: { id: 123 }, text: "/getchatid" }
expect(response.status).to eq(200) expect(response.status).to eq(200)
expect(stub).to have_been_requested.times(1) expect(stub).to have_been_requested.times(1)

View File

@ -10,7 +10,7 @@ RSpec.describe DiscourseChat::Provider::TelegramProvider do
SiteSetting.chat_integration_telegram_enabled = true SiteSetting.chat_integration_telegram_enabled = true
end end
let(:chan1){DiscourseChat::Channel.create!(provider:'telegram', data:{name: "Awesome Channel", chat_id: '123'})} let(:chan1) { DiscourseChat::Channel.create!(provider: 'telegram', data: { name: "Awesome Channel", chat_id: '123' }) }
it 'sends a webhook request' do it 'sends a webhook request' do
stub1 = stub_request(:post, 'https://api.telegram.org/botTOKEN/sendMessage').to_return(body: "{\"ok\":true}") stub1 = stub_request(:post, 'https://api.telegram.org/botTOKEN/sendMessage').to_return(body: "{\"ok\":true}")
@ -21,7 +21,7 @@ RSpec.describe DiscourseChat::Provider::TelegramProvider do
it 'handles errors correctly' do it 'handles errors correctly' do
stub1 = stub_request(:post, 'https://api.telegram.org/botTOKEN/sendMessage').to_return(body: "{\"ok\":false, \"description\":\"chat not found\"}") stub1 = stub_request(:post, 'https://api.telegram.org/botTOKEN/sendMessage').to_return(body: "{\"ok\":false, \"description\":\"chat not found\"}")
expect(stub1).to have_been_requested.times(0) expect(stub1).to have_been_requested.times(0)
expect{described_class.trigger_notification(post, chan1)}.to raise_exception(::DiscourseChat::ProviderError) expect { described_class.trigger_notification(post, chan1) }.to raise_exception(::DiscourseChat::ProviderError)
expect(stub1).to have_been_requested.once expect(stub1).to have_been_requested.once
end end

View File

@ -5,13 +5,10 @@ RSpec.describe DiscourseChat::Channel do
include_context "dummy provider" include_context "dummy provider"
include_context "validated dummy provider" include_context "validated dummy provider"
it 'should save and load successfully' do it 'should save and load successfully' do
expect(DiscourseChat::Channel.all.length).to eq(0) expect(DiscourseChat::Channel.all.length).to eq(0)
chan = DiscourseChat::Channel.create({ chan = DiscourseChat::Channel.create(provider: "dummy")
provider:"dummy",
})
expect(DiscourseChat::Channel.all.length).to eq(1) expect(DiscourseChat::Channel.all.length).to eq(1)
@ -22,15 +19,15 @@ RSpec.describe DiscourseChat::Channel do
end end
it 'should edit successfully' do it 'should edit successfully' do
channel = DiscourseChat::Channel.create!(provider:"dummy2", data:{val:"hello"}) channel = DiscourseChat::Channel.create!(provider: "dummy2", data: { val: "hello" })
expect(channel.valid?).to eq(true) expect(channel.valid?).to eq(true)
channel.save! channel.save!
end end
it 'can be filtered by provider' do it 'can be filtered by provider' do
channel1 = DiscourseChat::Channel.create!(provider:'dummy') channel1 = DiscourseChat::Channel.create!(provider: 'dummy')
channel2 = DiscourseChat::Channel.create!(provider:'dummy2', data:{val:"blah"}) channel2 = DiscourseChat::Channel.create!(provider: 'dummy2', data: { val: "blah" })
channel3 = DiscourseChat::Channel.create!(provider:'dummy2', data:{val:"blah2"}) channel3 = DiscourseChat::Channel.create!(provider: 'dummy2', data: { val: "blah2" })
expect(DiscourseChat::Channel.all.length).to eq(3) expect(DiscourseChat::Channel.all.length).to eq(3)
@ -39,19 +36,19 @@ RSpec.describe DiscourseChat::Channel do
end end
it 'can be filtered by data value' do it 'can be filtered by data value' do
channel2 = DiscourseChat::Channel.create!(provider:'dummy2', data:{val:"foo"}) channel2 = DiscourseChat::Channel.create!(provider: 'dummy2', data: { val: "foo" })
channel3 = DiscourseChat::Channel.create!(provider:'dummy2', data:{val:"blah"}) channel3 = DiscourseChat::Channel.create!(provider: 'dummy2', data: { val: "blah" })
expect(DiscourseChat::Channel.all.length).to eq(2) expect(DiscourseChat::Channel.all.length).to eq(2)
for_provider = DiscourseChat::Channel.with_provider('dummy2') for_provider = DiscourseChat::Channel.with_provider('dummy2')
expect(for_provider.length).to eq(2) expect(for_provider.length).to eq(2)
expect(DiscourseChat::Channel.with_provider('dummy2').with_data_value('val','blah').length).to eq(1) expect(DiscourseChat::Channel.with_provider('dummy2').with_data_value('val', 'blah').length).to eq(1)
end end
it 'can find its own rules' do it 'can find its own rules' do
channel = DiscourseChat::Channel.create({provider:'dummy'}) channel = DiscourseChat::Channel.create(provider: 'dummy')
expect(channel.rules.size).to eq(0) expect(channel.rules.size).to eq(0)
DiscourseChat::Rule.create(channel: channel) DiscourseChat::Rule.create(channel: channel)
DiscourseChat::Rule.create(channel: channel) DiscourseChat::Rule.create(channel: channel)
@ -59,7 +56,7 @@ RSpec.describe DiscourseChat::Channel do
end end
it 'destroys its rules on destroy' do it 'destroys its rules on destroy' do
channel = DiscourseChat::Channel.create({provider:'dummy'}) channel = DiscourseChat::Channel.create(provider: 'dummy')
expect(channel.rules.size).to eq(0) expect(channel.rules.size).to eq(0)
rule1 = DiscourseChat::Rule.create(channel: channel) rule1 = DiscourseChat::Rule.create(channel: channel)
rule2 = DiscourseChat::Rule.create(channel: channel) rule2 = DiscourseChat::Rule.create(channel: channel)
@ -72,40 +69,39 @@ RSpec.describe DiscourseChat::Channel do
describe 'validations' do describe 'validations' do
it 'validates provider correctly' do it 'validates provider correctly' do
channel = DiscourseChat::Channel.create!(provider:"dummy") channel = DiscourseChat::Channel.create!(provider: "dummy")
expect(channel.valid?).to eq(true) expect(channel.valid?).to eq(true)
channel.provider = 'somerandomprovider' channel.provider = 'somerandomprovider'
expect(channel.valid?).to eq(false) expect(channel.valid?).to eq(false)
end end
it 'succeeds with valid data' do it 'succeeds with valid data' do
channel2 = DiscourseChat::Channel.new(provider:"dummy2", data:{val:"hello"}) channel2 = DiscourseChat::Channel.new(provider: "dummy2", data: { val: "hello" })
expect(channel2.valid?).to eq(true) expect(channel2.valid?).to eq(true)
end end
it 'disallows invalid data' do it 'disallows invalid data' do
channel2 = DiscourseChat::Channel.new(provider:"dummy2", data:{val:' '}) channel2 = DiscourseChat::Channel.new(provider: "dummy2", data: { val: ' ' })
expect(channel2.valid?).to eq(false) expect(channel2.valid?).to eq(false)
end end
it 'disallows unknown keys' do it 'disallows unknown keys' do
channel2 = DiscourseChat::Channel.new(provider:"dummy2", data:{val:"hello", unknown:"world"}) channel2 = DiscourseChat::Channel.new(provider: "dummy2", data: { val: "hello", unknown: "world" })
expect(channel2.valid?).to eq(false) expect(channel2.valid?).to eq(false)
end end
it 'requires all keys' do it 'requires all keys' do
channel2 = DiscourseChat::Channel.new(provider:"dummy2", data:{}) channel2 = DiscourseChat::Channel.new(provider: "dummy2", data: {})
expect(channel2.valid?).to eq(false) expect(channel2.valid?).to eq(false)
end end
it 'disallows duplicate channels' do it 'disallows duplicate channels' do
channel1 = DiscourseChat::Channel.create(provider:"dummy2", data:{val:"hello"}) channel1 = DiscourseChat::Channel.create(provider: "dummy2", data: { val: "hello" })
channel2 = DiscourseChat::Channel.new(provider:"dummy2", data:{val:"hello"}) channel2 = DiscourseChat::Channel.new(provider: "dummy2", data: { val: "hello" })
expect(channel2.valid?).to eq(false) expect(channel2.valid?).to eq(false)
channel2.data[:val] = "hello2" channel2.data[:val] = "hello2"
expect(channel2.valid?).to eq(true) expect(channel2.valid?).to eq(true)
end end
end end
end end

View File

@ -4,36 +4,34 @@ require_relative '../dummy_provider'
RSpec.describe DiscourseChat::Rule do RSpec.describe DiscourseChat::Rule do
include_context "dummy provider" include_context "dummy provider"
let(:tag1){Fabricate(:tag)} let(:tag1) { Fabricate(:tag) }
let(:tag2){Fabricate(:tag)} let(:tag2) { Fabricate(:tag) }
let(:channel){DiscourseChat::Channel.create(provider:'dummy')} let(:channel) { DiscourseChat::Channel.create(provider: 'dummy') }
let(:category) {Fabricate(:category)} let(:category) { Fabricate(:category) }
let(:group) {Fabricate(:group)} let(:group) { Fabricate(:group) }
describe '.alloc_key' do describe '.alloc_key' do
it 'should return sequential numbers' do it 'should return sequential numbers' do
expect( DiscourseChat::Rule.create(channel: channel).key ).to eq("rule:1") expect(DiscourseChat::Rule.create(channel: channel).key).to eq("rule:1")
expect( DiscourseChat::Rule.create(channel: channel).key ).to eq("rule:2") expect(DiscourseChat::Rule.create(channel: channel).key).to eq("rule:2")
expect( DiscourseChat::Rule.create(channel: channel).key ).to eq("rule:3") expect(DiscourseChat::Rule.create(channel: channel).key).to eq("rule:3")
end end
end end
it 'should convert between channel and channel_id successfully' do it 'should convert between channel and channel_id successfully' do
rule = DiscourseChat::Rule.create(channel: channel) rule = DiscourseChat::Rule.create(channel: channel)
expect( rule.channel_id ).to eq(channel.id) expect(rule.channel_id).to eq(channel.id)
expect( rule.channel.id ).to eq(channel.id) expect(rule.channel.id).to eq(channel.id)
end end
it 'should save and load successfully' do it 'should save and load successfully' do
expect(DiscourseChat::Rule.all.length).to eq(0) expect(DiscourseChat::Rule.all.length).to eq(0)
rule = DiscourseChat::Rule.create({ rule = DiscourseChat::Rule.create(channel: channel,
channel: channel, category_id: category.id,
category_id: category.id, tags: [tag1.name, tag2.name],
tags: [tag1.name, tag2.name], filter: 'watch')
filter: 'watch'
})
expect(DiscourseChat::Rule.all.length).to eq(1) expect(DiscourseChat::Rule.all.length).to eq(1)
@ -41,18 +39,16 @@ RSpec.describe DiscourseChat::Rule do
expect(loadedRule.channel.id).to eq(channel.id) expect(loadedRule.channel.id).to eq(channel.id)
expect(loadedRule.category_id).to eq(category.id) expect(loadedRule.category_id).to eq(category.id)
expect(loadedRule.tags).to contain_exactly(tag1.name,tag2.name) expect(loadedRule.tags).to contain_exactly(tag1.name, tag2.name)
expect(loadedRule.filter).to eq('watch') expect(loadedRule.filter).to eq('watch')
end end
describe 'general operations' do describe 'general operations' do
before do before do
rule = DiscourseChat::Rule.create({ rule = DiscourseChat::Rule.create(channel: channel,
channel: channel, category_id: category.id,
category_id: category.id, tags: [tag1.name, tag2.name])
tags: [tag1.name, tag2.name]
})
end end
it 'can be modified' do it 'can be modified' do
@ -66,7 +62,7 @@ RSpec.describe DiscourseChat::Rule do
end end
it 'can be deleted' do it 'can be deleted' do
DiscourseChat::Rule.new(channel:channel).save! DiscourseChat::Rule.new(channel: channel).save!
expect(DiscourseChat::Rule.all.length).to eq(2) expect(DiscourseChat::Rule.all.length).to eq(2)
rule = DiscourseChat::Rule.all.first rule = DiscourseChat::Rule.all.first
@ -76,10 +72,10 @@ RSpec.describe DiscourseChat::Rule do
end end
it 'can delete all' do it 'can delete all' do
DiscourseChat::Rule.create({channel:channel}) DiscourseChat::Rule.create(channel: channel)
DiscourseChat::Rule.create({channel:channel}) DiscourseChat::Rule.create(channel: channel)
DiscourseChat::Rule.create({channel:channel}) DiscourseChat::Rule.create(channel: channel)
DiscourseChat::Rule.create({channel:channel}) DiscourseChat::Rule.create(channel: channel)
expect(DiscourseChat::Rule.all.length).to eq(5) expect(DiscourseChat::Rule.all.length).to eq(5)
@ -89,13 +85,13 @@ RSpec.describe DiscourseChat::Rule do
end end
it 'can be filtered by channel' do it 'can be filtered by channel' do
channel2 = DiscourseChat::Channel.create(provider:'dummy') channel2 = DiscourseChat::Channel.create(provider: 'dummy')
channel3 = DiscourseChat::Channel.create(provider:'dummy') channel3 = DiscourseChat::Channel.create(provider: 'dummy')
rule2 = DiscourseChat::Rule.create(channel:channel) rule2 = DiscourseChat::Rule.create(channel: channel)
rule3 = DiscourseChat::Rule.create(channel:channel) rule3 = DiscourseChat::Rule.create(channel: channel)
rule4 = DiscourseChat::Rule.create(channel:channel2) rule4 = DiscourseChat::Rule.create(channel: channel2)
rule5 = DiscourseChat::Rule.create(channel:channel3) rule5 = DiscourseChat::Rule.create(channel: channel3)
expect(DiscourseChat::Rule.all.length).to eq(5) expect(DiscourseChat::Rule.all.length).to eq(5)
@ -104,8 +100,8 @@ RSpec.describe DiscourseChat::Rule do
end end
it 'can be filtered by category' do it 'can be filtered by category' do
rule2 = DiscourseChat::Rule.create(channel:channel, category_id: category.id) rule2 = DiscourseChat::Rule.create(channel: channel, category_id: category.id)
rule3 = DiscourseChat::Rule.create(channel:channel, category_id: nil) rule3 = DiscourseChat::Rule.create(channel: channel, category_id: nil)
expect(DiscourseChat::Rule.all.length).to eq(3) expect(DiscourseChat::Rule.all.length).to eq(3)
@ -116,13 +112,13 @@ RSpec.describe DiscourseChat::Rule do
it 'can be filtered by group' do it 'can be filtered by group' do
group1 = Fabricate(:group) group1 = Fabricate(:group)
group2 = Fabricate(:group) group2 = Fabricate(:group)
rule2 = DiscourseChat::Rule.create!(channel:channel, type:'group_message', group_id: group1.id) rule2 = DiscourseChat::Rule.create!(channel: channel, type: 'group_message', group_id: group1.id)
rule3 = DiscourseChat::Rule.create!(channel:channel, type:'group_message', group_id: group2.id) rule3 = DiscourseChat::Rule.create!(channel: channel, type: 'group_message', group_id: group2.id)
expect(DiscourseChat::Rule.all.length).to eq(3) expect(DiscourseChat::Rule.all.length).to eq(3)
expect(DiscourseChat::Rule.with_category_id(category.id).length).to eq(1) expect(DiscourseChat::Rule.with_category_id(category.id).length).to eq(1)
expect(DiscourseChat::Rule.with_group_ids([group1.id,group2.id]).length).to eq(2) expect(DiscourseChat::Rule.with_group_ids([group1.id, group2.id]).length).to eq(2)
expect(DiscourseChat::Rule.with_group_ids([group1.id]).length).to eq(1) expect(DiscourseChat::Rule.with_group_ids([group1.id]).length).to eq(1)
expect(DiscourseChat::Rule.with_group_ids([group2.id]).length).to eq(1) expect(DiscourseChat::Rule.with_group_ids([group2.id]).length).to eq(1)
end end
@ -141,9 +137,9 @@ RSpec.describe DiscourseChat::Rule do
end end
it 'can be sorted by precedence' do it 'can be sorted by precedence' do
rule2 = DiscourseChat::Rule.create(channel:channel, filter:'mute') rule2 = DiscourseChat::Rule.create(channel: channel, filter: 'mute')
rule3 = DiscourseChat::Rule.create(channel:channel, filter:'follow') rule3 = DiscourseChat::Rule.create(channel: channel, filter: 'follow')
rule4 = DiscourseChat::Rule.create(channel:channel, filter:'mute') rule4 = DiscourseChat::Rule.create(channel: channel, filter: 'mute')
expect(DiscourseChat::Rule.all.length).to eq(4) expect(DiscourseChat::Rule.all.length).to eq(4)
@ -154,11 +150,9 @@ RSpec.describe DiscourseChat::Rule do
describe 'validations' do describe 'validations' do
let(:rule) do let(:rule) do
DiscourseChat::Rule.create({ DiscourseChat::Rule.create(filter: 'watch',
filter: 'watch', channel: channel,
channel: channel, category_id: category.id)
category_id: category.id,
})
end end
it 'validates channel correctly' do it 'validates channel correctly' do

View File

@ -4,29 +4,29 @@ require_relative '../dummy_provider'
RSpec.describe DiscourseChat::Manager do RSpec.describe DiscourseChat::Manager do
let(:manager) {::DiscourseChat::Manager} let(:manager) { ::DiscourseChat::Manager }
let(:category) {Fabricate(:category)} let(:category) { Fabricate(:category) }
let(:group) {Fabricate(:group)} let(:group) { Fabricate(:group) }
let(:topic){Fabricate(:topic, category_id: category.id )} let(:topic) { Fabricate(:topic, category_id: category.id) }
let(:first_post) {Fabricate(:post, topic: topic)} let(:first_post) { Fabricate(:post, topic: topic) }
let(:second_post) {Fabricate(:post, topic: topic, post_number:2)} let(:second_post) { Fabricate(:post, topic: topic, post_number: 2) }
describe '.trigger_notifications' do describe '.trigger_notifications' do
include_context "dummy provider" include_context "dummy provider"
let(:chan1){DiscourseChat::Channel.create!(provider:'dummy')} let(:chan1) { DiscourseChat::Channel.create!(provider: 'dummy') }
let(:chan2){DiscourseChat::Channel.create!(provider:'dummy')} let(:chan2) { DiscourseChat::Channel.create!(provider: 'dummy') }
let(:chan3){DiscourseChat::Channel.create!(provider:'dummy')} let(:chan3) { DiscourseChat::Channel.create!(provider: 'dummy') }
before do before do
SiteSetting.chat_integration_enabled = true SiteSetting.chat_integration_enabled = true
end end
it "should fail gracefully when a provider throws an exception" do it "should fail gracefully when a provider throws an exception" do
DiscourseChat::Rule.create!(channel: chan1, filter: 'watch', category_id:category.id ) DiscourseChat::Rule.create!(channel: chan1, filter: 'watch', category_id: category.id)
# Triggering a ProviderError should set the error_key to the error message # Triggering a ProviderError should set the error_key to the error message
provider.set_raise_exception(DiscourseChat::ProviderError.new info: {error_key:"hello"}) provider.set_raise_exception(DiscourseChat::ProviderError.new info: { error_key: "hello" })
manager.trigger_notifications(first_post.id) manager.trigger_notifications(first_post.id)
expect(provider.sent_to_channel_ids).to contain_exactly() expect(provider.sent_to_channel_ids).to contain_exactly()
expect(DiscourseChat::Channel.all.first.error_key).to eq('hello') expect(DiscourseChat::Channel.all.first.error_key).to eq('hello')
@ -45,7 +45,7 @@ RSpec.describe DiscourseChat::Manager do
it "should not send notifications when provider is disabled" do it "should not send notifications when provider is disabled" do
SiteSetting.chat_integration_enabled = false SiteSetting.chat_integration_enabled = false
DiscourseChat::Rule.create!(channel: chan1, filter: 'watch', category_id:category.id ) DiscourseChat::Rule.create!(channel: chan1, filter: 'watch', category_id: category.id)
manager.trigger_notifications(first_post.id) manager.trigger_notifications(first_post.id)
@ -53,9 +53,9 @@ RSpec.describe DiscourseChat::Manager do
end end
it "should send a notification to watched and following channels for new topic" do it "should send a notification to watched and following channels for new topic" do
DiscourseChat::Rule.create!(channel: chan1, filter: 'watch', category_id:category.id ) DiscourseChat::Rule.create!(channel: chan1, filter: 'watch', category_id: category.id)
DiscourseChat::Rule.create!(channel: chan2, filter: 'follow', category_id:category.id ) DiscourseChat::Rule.create!(channel: chan2, filter: 'follow', category_id: category.id)
DiscourseChat::Rule.create!(channel: chan3, filter: 'mute', category_id:category.id ) DiscourseChat::Rule.create!(channel: chan3, filter: 'mute', category_id: category.id)
manager.trigger_notifications(first_post.id) manager.trigger_notifications(first_post.id)
@ -63,9 +63,9 @@ RSpec.describe DiscourseChat::Manager do
end end
it "should send a notification only to watched for reply" do it "should send a notification only to watched for reply" do
DiscourseChat::Rule.create!(channel: chan1, filter: 'watch', category_id:category.id ) DiscourseChat::Rule.create!(channel: chan1, filter: 'watch', category_id: category.id)
DiscourseChat::Rule.create!(channel: chan2, filter: 'follow', category_id:category.id ) DiscourseChat::Rule.create!(channel: chan2, filter: 'follow', category_id: category.id)
DiscourseChat::Rule.create!(channel: chan3, filter: 'mute', category_id:category.id ) DiscourseChat::Rule.create!(channel: chan3, filter: 'mute', category_id: category.id)
manager.trigger_notifications(second_post.id) manager.trigger_notifications(second_post.id)
@ -73,7 +73,7 @@ RSpec.describe DiscourseChat::Manager do
end end
it "should respect wildcard category settings" do it "should respect wildcard category settings" do
DiscourseChat::Rule.create!(channel: chan1, filter: 'watch', category_id: nil ) DiscourseChat::Rule.create!(channel: chan1, filter: 'watch', category_id: nil)
manager.trigger_notifications(first_post.id) manager.trigger_notifications(first_post.id)
@ -81,8 +81,8 @@ RSpec.describe DiscourseChat::Manager do
end end
it "should respect mute over watch" do it "should respect mute over watch" do
DiscourseChat::Rule.create!(channel: chan1, filter: 'watch', category_id: nil ) # Wildcard watch DiscourseChat::Rule.create!(channel: chan1, filter: 'watch', category_id: nil) # Wildcard watch
DiscourseChat::Rule.create!(channel: chan1, filter: 'mute', category_id: category.id ) # Specific mute DiscourseChat::Rule.create!(channel: chan1, filter: 'mute', category_id: category.id) # Specific mute
manager.trigger_notifications(first_post.id) manager.trigger_notifications(first_post.id)
@ -90,8 +90,8 @@ RSpec.describe DiscourseChat::Manager do
end end
it "should respect watch over follow" do it "should respect watch over follow" do
DiscourseChat::Rule.create!(channel: chan1, filter: 'follow', category_id: nil ) # Wildcard watch DiscourseChat::Rule.create!(channel: chan1, filter: 'follow', category_id: nil) # Wildcard watch
DiscourseChat::Rule.create!(channel: chan1, filter: 'watch', category_id: category.id ) # Specific watch DiscourseChat::Rule.create!(channel: chan1, filter: 'watch', category_id: category.id) # Specific watch
manager.trigger_notifications(second_post.id) manager.trigger_notifications(second_post.id)
@ -99,7 +99,7 @@ RSpec.describe DiscourseChat::Manager do
end end
it "should not notify about private messages" do it "should not notify about private messages" do
DiscourseChat::Rule.create!(channel: chan1, filter: 'follow', category_id: nil ) # Wildcard watch DiscourseChat::Rule.create!(channel: chan1, filter: 'follow', category_id: nil) # Wildcard watch
private_post = Fabricate(:private_message_post) private_post = Fabricate(:private_message_post)
@ -109,8 +109,8 @@ RSpec.describe DiscourseChat::Manager do
end end
it "should work for group pms" do it "should work for group pms" do
DiscourseChat::Rule.create!(channel: chan1, filter: 'watch' ) # Wildcard watch DiscourseChat::Rule.create!(channel: chan1, filter: 'watch') # Wildcard watch
DiscourseChat::Rule.create!(channel: chan2, type: 'group_message', filter: 'watch', group_id: group.id ) # Group watch DiscourseChat::Rule.create!(channel: chan2, type: 'group_message', filter: 'watch', group_id: group.id) # Group watch
private_post = Fabricate(:private_message_post) private_post = Fabricate(:private_message_post)
private_post.topic.invite_group(Fabricate(:user), group) private_post.topic.invite_group(Fabricate(:user), group)
@ -122,8 +122,8 @@ RSpec.describe DiscourseChat::Manager do
it "should work for pms with multiple groups" do it "should work for pms with multiple groups" do
group2 = Fabricate(:group) group2 = Fabricate(:group)
DiscourseChat::Rule.create!(channel: chan1, type: 'group_message', filter: 'watch', group_id: group.id ) DiscourseChat::Rule.create!(channel: chan1, type: 'group_message', filter: 'watch', group_id: group.id)
DiscourseChat::Rule.create!(channel: chan2, type: 'group_message', filter: 'watch', group_id: group2.id ) DiscourseChat::Rule.create!(channel: chan2, type: 'group_message', filter: 'watch', group_id: group2.id)
private_post = Fabricate(:private_message_post) private_post = Fabricate(:private_message_post)
private_post.topic.invite_group(Fabricate(:user), group) private_post.topic.invite_group(Fabricate(:user), group)
@ -146,7 +146,7 @@ RSpec.describe DiscourseChat::Manager do
end end
it "should not notify about posts the chat_user cannot see" do it "should not notify about posts the chat_user cannot see" do
DiscourseChat::Rule.create!(channel: chan1, filter: 'follow', category_id: nil ) # Wildcard watch DiscourseChat::Rule.create!(channel: chan1, filter: 'follow', category_id: nil) # Wildcard watch
# Create a group & user # Create a group & user
group = Fabricate(:group, name: "friends") group = Fabricate(:group, name: "friends")
@ -180,16 +180,16 @@ RSpec.describe DiscourseChat::Manager do
end end
describe 'with tags enabled' do describe 'with tags enabled' do
let(:tag){Fabricate(:tag, name:'gsoc')} let(:tag) { Fabricate(:tag, name: 'gsoc') }
let(:tagged_topic){Fabricate(:topic, category_id: category.id, tags: [tag])} let(:tagged_topic) { Fabricate(:topic, category_id: category.id, tags: [tag]) }
let(:tagged_first_post) {Fabricate(:post, topic: tagged_topic)} let(:tagged_first_post) { Fabricate(:post, topic: tagged_topic) }
before(:each) do before(:each) do
SiteSetting.tagging_enabled = true SiteSetting.tagging_enabled = true
end end
it 'should still work for rules without any tags specified' do it 'should still work for rules without any tags specified' do
DiscourseChat::Rule.create!(channel: chan1, filter: 'follow', category_id: nil ) # Wildcard watch DiscourseChat::Rule.create!(channel: chan1, filter: 'follow', category_id: nil) # Wildcard watch
manager.trigger_notifications(first_post.id) manager.trigger_notifications(first_post.id)
manager.trigger_notifications(tagged_first_post.id) manager.trigger_notifications(tagged_first_post.id)
@ -198,7 +198,7 @@ RSpec.describe DiscourseChat::Manager do
end end
it 'should only match tagged topics when rule has tags' do it 'should only match tagged topics when rule has tags' do
DiscourseChat::Rule.create!(channel: chan1, filter: 'follow', category_id: category.id, tags:[tag.name] ) DiscourseChat::Rule.create!(channel: chan1, filter: 'follow', category_id: category.id, tags: [tag.name])
manager.trigger_notifications(first_post.id) manager.trigger_notifications(first_post.id)
manager.trigger_notifications(tagged_first_post.id) manager.trigger_notifications(tagged_first_post.id)