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
def list_providers
providers = ::DiscourseChat::Provider.enabled_providers.map {|x| {
name: x::PROVIDER_NAME,
id: x::PROVIDER_NAME,
providers = ::DiscourseChat::Provider.enabled_providers.map { |x| {
name: x::PROVIDER_NAME,
id: x::PROVIDER_NAME,
channel_parameters: (defined? x::CHANNEL_PARAMETERS) ? x::CHANNEL_PARAMETERS : []
}}
render json:providers, root: 'providers'
render json: providers, root: 'providers'
end
def test
@ -32,21 +32,21 @@ class DiscourseChat::ChatController < ApplicationController
provider.trigger_notification(post, channel)
render json:success_json
render json: success_json
rescue Discourse::InvalidParameters, ActiveRecord::RecordNotFound => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
rescue DiscourseChat::ProviderError => e
Rails.logger.error("Test provider failed #{e.info}")
if e.info.key?(:error_key) and !e.info[:error_key].nil?
render json: {error_key: e.info[:error_key]}, status: 422
else
render json: {errors: [e.message]}, status: 422
if e.info.key?(:error_key) && !e.info[:error_key].nil?
render json: { error_key: e.info[:error_key] }, status: 422
else
render json: { errors: [e.message] }, status: 422
end
end
end
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]
@ -61,9 +61,9 @@ class DiscourseChat::ChatController < ApplicationController
def create_channel
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'
end
@ -73,19 +73,19 @@ class DiscourseChat::ChatController < ApplicationController
raise Discourse::InvalidParameters, 'Provider is not valid'
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)
if not channel.save(hash)
raise Discourse::InvalidParameters, 'Channel is not valid'
end
render_serialized channel, DiscourseChat::ChannelSerializer, root: 'channel'
rescue Discourse::InvalidParameters => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
end
end
@ -94,17 +94,17 @@ class DiscourseChat::ChatController < ApplicationController
channel = DiscourseChat::Channel.find(params[:id].to_i)
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)
raise Discourse::InvalidParameters, 'Channel is not valid'
end
render_serialized channel, DiscourseChat::ChannelSerializer, root: 'channel'
rescue Discourse::InvalidParameters => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
end
end
@ -118,32 +118,32 @@ class DiscourseChat::ChatController < ApplicationController
def create_rule
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)
if not rule.save(hash)
raise Discourse::InvalidParameters, 'Rule is not valid'
end
render_serialized rule, DiscourseChat::RuleSerializer, root: 'rule'
rescue Discourse::InvalidParameters => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
end
end
def update_rule
begin
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)
raise Discourse::InvalidParameters, 'Rule is not valid'
end
render_serialized rule, DiscourseChat::RuleSerializer, root: 'rule'
rescue Discourse::InvalidParameters => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
end
end
@ -154,4 +154,4 @@ class DiscourseChat::ChatController < ApplicationController
render json: success_json
end
end
end

View File

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

View File

@ -1,6 +1,6 @@
module DiscourseChat
module Helper
def self.process_command(channel, tokens)
guardian = DiscourseChat::Manager.guardian
@ -16,11 +16,11 @@ module DiscourseChat
# If the first token in the command is a tag, this rule applies to all categories
category_name = tokens[0].start_with?('tag:') ? nil : tokens.shift
if category_name
if category_name
category = Category.find_by(slug: category_name)
unless category
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
else
category = nil # All categories
@ -33,7 +33,7 @@ module DiscourseChat
if token.start_with?('tag:')
tag_name = token.sub(/^tag:/, '')
else
return error_text # Abort and send help text
return error_text # Abort and send help text
end
tag = Tag.find_by(name: tag_name)
@ -44,7 +44,7 @@ module DiscourseChat
end
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
return I18n.t("chat_integration.provider.#{provider}.create.created")
when :updated
@ -73,14 +73,14 @@ module DiscourseChat
end
# Produce a string with a list of all rules associated with a channel
def self.status_for_channel(channel)
rules = channel.rules.order_by_precedence
def self.status_for_channel(channel)
rules = channel.rules.order_by_precedence
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
rules.each do |rule|
i = 1
rules.each do |rule|
category_id = rule.category_id
case rule.type
@ -110,60 +110,60 @@ module DiscourseChat
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(', '))
end
text << "\n"
i += 1
end
i += 1
end
if rules.size == 0
text << I18n.t("chat_integration.provider.#{provider}.status.no_rules")
end
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
def self.delete_by_index(channel, index)
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
# Create a rule for a specific channel
# Designed to be used by provider's "Slash commands"
# Will intelligently adjust existing rules to avoid duplicates
# Designed to be used by provider's "Slash commands"
# Will intelligently adjust existing rules to avoid duplicates
# Returns
# :updated if an existing rule has been updated
# :created if a new rule has been created
# 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)
# Select the ones that have the same category
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
the_rule = same_category_and_tags.shift # Take out the first one
same_category_and_tags.each do |rule| # Destroy all the others - they're duplicates
rule.destroy
rule.destroy
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
end
same_category_and_filters = same_category.select { |rule| rule.filter == filter }
if same_category_and_filters.size > 0
if same_category_and_filters.size > 0
# These rules are exactly the same, except for tags. Let's combine the tags together
tags = [] if tags.nil?
same_category_and_filters.each do |rule|
@ -172,7 +172,7 @@ module DiscourseChat
the_rule = same_category_and_filters.shift # Take out the first one
if the_rule.update(tags: tags) # Update the tags
if the_rule.update(tags: tags) # Update the tags
same_category_and_filters.each do |rule| # Destroy all the others - they're duplicates
rule.destroy
end
@ -192,11 +192,10 @@ module DiscourseChat
def self.save_transcript(transcript)
secret = SecureRandom.hex
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
end
end
end

View File

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

View File

@ -7,4 +7,4 @@ module Jobs
::DiscourseChat::Manager.trigger_notifications(args[:post_id])
end
end
end
end

View File

@ -31,7 +31,7 @@ class DiscourseChat::Channel < DiscourseChat::PluginModel
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}")
return
end
@ -40,18 +40,18 @@ class DiscourseChat::Channel < DiscourseChat::PluginModel
matching_channels = DiscourseChat::Channel.where.not(id: id)
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)
errors.add(:data, "data.#{key} is invalid")
end
unique = params.find{|p| p[:key] == key}[:unique]
unique = params.find { |p| p[:key] == key }[:unique]
if unique
check_unique = true
matching_channels = matching_channels.with_data_value(key, value)
end
end
if check_unique && matching_channels.exists?
errors.add(:data, "matches an existing channel")
end
@ -62,8 +62,8 @@ class DiscourseChat::Channel < DiscourseChat::PluginModel
DiscourseChat::Rule.with_channel_id(id).order_by_precedence
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,18 +6,18 @@ class DiscourseChat::PluginModel < PluginStoreRow
def init_plugin_model
self.type_name ||= 'JSON'
self.plugin_name ||= PLUGIN_NAME
self.plugin_name ||= PLUGIN_NAME
end
# 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(plugin_name: self::PLUGIN_NAME)
.where("key like?", "#{self::KEY_PREFIX}%")
.where(plugin_name: self::PLUGIN_NAME)
.where("key like?", "#{self::KEY_PREFIX}%")
end
before_save :set_key
private
private
def set_key
self.key ||= self.class.alloc_key
end

View File

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

View File

@ -2,4 +2,4 @@ Discourse::Application.routes.append do
mount ::DiscourseChat::AdminEngine, at: '/admin/plugins/chat', constraints: AdminConstraint.new
mount ::DiscourseChat::PublicEngine, at: '/chat-transcript/', as: 'chat-transcript'
mount ::DiscourseChat::Provider::HookEngine, at: '/chat-integration/'
end
end

View File

@ -5,7 +5,7 @@ module DiscourseChat
get "" => "chat#respond"
get '/providers' => "chat#list_providers"
post '/test' => "chat#test"
get '/channels' => "chat#list_channels"
post '/channels' => "chat#create_channel"
put '/channels/:id' => "chat#update_channel"
@ -21,4 +21,4 @@ module DiscourseChat
PublicEngine.routes.draw do
get '/:secret' => "public#post_transcript"
end
end
end

View File

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

View File

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

View File

@ -11,7 +11,7 @@ module DiscourseChat
post = Post.find_by(id: post_id)
# Abort if the chat_user doesn't have permission to see the post
return if !guardian.can_see?(post)
return if !guardian.can_see?(post)
# Abort if the post is blank, or is non-regular (e.g. a "topic closed" notification)
return if post.blank? || post.post_type != Post.types[:regular]
@ -46,14 +46,14 @@ module DiscourseChat
if SiteSetting.tagging_enabled
topic_tags = topic.tags.present? ? topic.tags.pluck(:name) : []
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?)
next any_tags_match # If any tags match, keep this filter, otherwise throw away
end
end
# 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] }
matching_rules = matching_rules.sort(&sort_func)
@ -84,10 +84,10 @@ module DiscourseChat
provider.trigger_notification(post, channel)
channel.update_attribute('error_key', nil) if channel.error_key
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])
else
channel.update_attribute('error_key','chat_integration.channel_exception')
channel.update_attribute('error_key', 'chat_integration.channel_exception')
end
# Log the error
@ -99,11 +99,10 @@ module DiscourseChat
error_info: e.class == DiscourseChat::ProviderError ? e.info : nil }
)
end
end
end
end
end
end

View File

@ -22,19 +22,19 @@ module DiscourseChat
end
def self.provider_names
self.providers.map {|x| x::PROVIDER_NAME}
self.providers.map { |x| x::PROVIDER_NAME }
end
def self.enabled_provider_names
self.enabled_providers.map {|x| x::PROVIDER_NAME}
self.enabled_providers.map { |x| x::PROVIDER_NAME }
end
def self.get_by_name(name)
self.providers.find{|p| p::PROVIDER_NAME == name}
self.providers.find { |p| p::PROVIDER_NAME == name }
end
def self.is_enabled(provider)
if defined? provider::PROVIDER_ENABLED_SETTING
if defined? provider::PROVIDER_ENABLED_SETTING
SiteSetting.send(provider::PROVIDER_ENABLED_SETTING)
else
false
@ -42,7 +42,7 @@ module DiscourseChat
end
class HookEngine < ::Rails::Engine
engine_name DiscourseChat::PLUGIN_NAME+"-hooks"
engine_name DiscourseChat::PLUGIN_NAME + "-hooks"
isolate_namespace DiscourseChat::Provider
end
@ -62,7 +62,7 @@ module DiscourseChat
end
def respond
render
render
end
end
@ -71,12 +71,12 @@ module DiscourseChat
engines = []
DiscourseChat::Provider.providers.each do |provider|
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
if engine
engines.push({engine: engine, name: provider::PROVIDER_NAME})
end
engines.push(engine: engine, name: provider::PROVIDER_NAME)
end
end
DiscourseChat::Provider::HookEngine.routes.draw do

View File

@ -4,8 +4,8 @@ module DiscourseChat
PROVIDER_NAME = "discord".freeze
PROVIDER_ENABLED_SETTING = :chat_integration_discord_enabled
CHANNEL_PARAMETERS = [
{key: "name", regex: '^\S+'},
{key: "webhook_url", regex: '^https:\/\/discordapp\.com\/api\/webhooks\/', unique: true, hidden: true}
{ key: "name", regex: '^\S+' },
{ key: "webhook_url", regex: '^https:\/\/discordapp\.com\/api\/webhooks\/', unique: true, hidden: true }
]
def self.send_message(url, message)
@ -14,7 +14,7 @@ module DiscourseChat
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
response = http.request(req)
@ -36,13 +36,13 @@ module DiscourseChat
end
message = {
embeds:[{
embeds: [{
title: post.topic.title,
description: post.excerpt(SiteSetting.chat_integration_discord_excerpt_length, text_entities: true, strip_links: true, remap_emoji: true),
url: post.full_url,
author:{
author: {
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)
}
}]
@ -53,7 +53,7 @@ module DiscourseChat
def self.trigger_notification(post, channel)
# 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)
@ -61,11 +61,11 @@ module DiscourseChat
if not response.kind_of? Net::HTTPSuccess
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
end
end

View File

@ -4,9 +4,9 @@ module DiscourseChat
PROVIDER_NAME = "hipchat".freeze
PROVIDER_ENABLED_SETTING = :chat_integration_hipchat_enabled
CHANNEL_PARAMETERS = [
{key: "name", regex: '^\S+'},
{key: "webhook_url", regex: 'hipchat\.com', unique: true, hidden:true},
{key: "color", regex: '(yellow|green|red|purple|gray|random)'}
{ key: "name", regex: '^\S+' },
{ key: "webhook_url", regex: 'hipchat\.com', unique: true, hidden: true },
{ key: "color", regex: '(yellow|green|red|purple|gray|random)' }
]
def self.send_message(url, message)
@ -15,7 +15,7 @@ module DiscourseChat
http = Net::HTTP.new(uri.host, uri.port)
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
response = http.request(req)
@ -40,7 +40,7 @@ module DiscourseChat
title: CGI::escapeHTML(topic.title),
)
icon_url =
icon_url =
if !SiteSetting.chat_integration_hipchat_icon_url.blank?
UrlHelper.absolute(SiteSetting.chat_integration_hipchat_icon_url)
elsif !SiteSetting.logo_small_url.blank?
@ -62,7 +62,7 @@ module DiscourseChat
url: icon_url,
},
activity: {
html: message_text
html: message_text
}
}
@ -72,7 +72,7 @@ module DiscourseChat
end
def self.trigger_notification(post, channel)
webhook_url = channel.data['webhook_url']
message = generate_hipchat_message(post)
@ -83,11 +83,11 @@ module DiscourseChat
if not response.kind_of? Net::HTTPSuccess
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
end
end

View File

@ -4,8 +4,8 @@ module DiscourseChat
PROVIDER_NAME = "matrix".freeze
PROVIDER_ENABLED_SETTING = :chat_integration_matrix_enabled
CHANNEL_PARAMETERS = [
{key: "name", regex: '^\S+'},
{key: "room_id", regex: '^\!\S+:\S+$', unique: true, hidden:true}
{ key: "name", regex: '^\S+' },
{ key: "room_id", regex: '^\!\S+:\S+$', unique: true, hidden: true }
]
def self.send_message(room_id, message)
@ -13,18 +13,16 @@ module DiscourseChat
event_type = 'm.room.message'
uid = Time.now.to_i
url_params = URI.encode_www_form({
access_token: SiteSetting.chat_integration_matrix_access_token
})
url_params = URI.encode_www_form(access_token: SiteSetting.chat_integration_matrix_access_token)
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.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
response = http.request(req)
@ -42,18 +40,14 @@ module DiscourseChat
message = {
msgtype: 'm.notice',
body: I18n.t('chat_integration.provider.matrix.text_message', {
user: display_name,
post_url: post.full_url,
title: post.topic.title
}),
body: I18n.t('chat_integration.provider.matrix.text_message', user: display_name,
post_url: post.full_url,
title: post.topic.title),
format: 'org.matrix.custom.html',
formatted_body: I18n.t('chat_integration.provider.matrix.formatted_message', {
user: display_name,
post_url: post.full_url,
title: post.topic.title,
excerpt: post.excerpt(SiteSetting.chat_integration_discord_excerpt_length, text_entities: true, strip_links: true, remap_emoji: true),
})
formatted_body: I18n.t('chat_integration.provider.matrix.formatted_message', user: display_name,
post_url: post.full_url,
title: post.topic.title,
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'
end
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
@ -83,4 +77,4 @@ module DiscourseChat
end
end
end
end

View File

@ -12,10 +12,10 @@ module DiscourseChat::Provider::MattermostProvider
def command
text = process_command(params)
render json: {
render json: {
response_type: 'ephemeral',
text: text
text: text
}
end
@ -36,13 +36,13 @@ module DiscourseChat::Provider::MattermostProvider
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
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)
end
def mattermost_token_valid?
@ -57,7 +57,7 @@ module DiscourseChat::Provider::MattermostProvider
end
class MattermostEngine < ::Rails::Engine
engine_name DiscourseChat::PLUGIN_NAME+"-mattermost"
engine_name DiscourseChat::PLUGIN_NAME + "-mattermost"
isolate_namespace DiscourseChat::Provider::MattermostProvider
end
@ -66,6 +66,3 @@ module DiscourseChat::Provider::MattermostProvider
end
end

View File

@ -4,7 +4,7 @@ module DiscourseChat
PROVIDER_NAME = "mattermost".freeze
PROVIDER_ENABLED_SETTING = :chat_integration_mattermost_enabled
CHANNEL_PARAMETERS = [
{key: "identifier", regex: '^[@#]\S*$', unique: true}
{ key: "identifier", regex: '^[@#]\S*$', unique: true }
]
def self.send_via_webhook(message)
@ -13,7 +13,7 @@ module DiscourseChat
http = Net::HTTP.new(uri.host, uri.port)
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
response = http.request(req)
@ -23,9 +23,9 @@ module DiscourseChat
else
error_key = nil
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
def self.mattermost_message(post, channel)
@ -40,7 +40,7 @@ module DiscourseChat
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
icon_url =
@ -63,7 +63,7 @@ module DiscourseChat
author_icon: post.user.small_avatar_url,
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),
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,
thumb_url: post.full_url,
}
@ -75,7 +75,7 @@ module DiscourseChat
def self.trigger_notification(post, channel)
channel_id = channel.data['identifier']
message = mattermost_message(post, channel_id)
self.send_via_webhook(message)
end
@ -83,4 +83,4 @@ module DiscourseChat
end
end
require_relative "mattermost_command_controller.rb"
require_relative "mattermost_command_controller.rb"

View File

@ -33,17 +33,17 @@ module DiscourseChat::Provider::SlackProvider
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
channel ||= DiscourseChat::Channel.create!(provider:provider, data:{identifier: channel_id})
channel ||= DiscourseChat::Channel.create!(provider: provider, data: { identifier: channel_id })
if tokens[0] == 'post'
return process_post_request(channel, tokens, params[:channel_id])
end
return ::DiscourseChat::Helper.process_command(channel, tokens)
end
def process_post_request(channel, tokens, slack_channel_id)
@ -68,7 +68,7 @@ module DiscourseChat::Provider::SlackProvider
# 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.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)
return error_text unless response.kind_of? Net::HTTPSuccess
json = JSON.parse(response.body)
@ -91,7 +91,7 @@ module DiscourseChat::Provider::SlackProvider
return error_text unless json['ok']
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 = ""
@ -106,7 +106,7 @@ module DiscourseChat::Provider::SlackProvider
username = ""
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
username = user["name"]
elsif message.key?("username")
@ -121,14 +121,14 @@ module DiscourseChat::Provider::SlackProvider
post_content << "![#{username}] " if message["user"]
post_content << "**@#{username}:** "
end
text = message["text"]
# Format links (don't worry about special cases @ # !)
text.gsub!(/<(.*?)>/) do |match|
group = $1
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}](#{link})"
end
@ -176,7 +176,7 @@ module DiscourseChat::Provider::SlackProvider
end
class SlackEngine < ::Rails::Engine
engine_name DiscourseChat::PLUGIN_NAME+"-slack"
engine_name DiscourseChat::PLUGIN_NAME + "-slack"
isolate_namespace DiscourseChat::Provider::SlackProvider
end
@ -185,6 +185,3 @@ module DiscourseChat::Provider::SlackProvider
end
end

View File

@ -1,16 +1,16 @@
class ChatIntegrationSlackEnabledSettingValidator
def initialize(opts={})
def initialize(opts = {})
@opts = opts
end
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?
true
end
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

View File

@ -4,7 +4,7 @@ module DiscourseChat::Provider::SlackProvider
PROVIDER_ENABLED_SETTING = :chat_integration_slack_enabled
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)
@ -28,7 +28,7 @@ module DiscourseChat::Provider::SlackProvider
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
icon_url =
@ -56,8 +56,8 @@ module DiscourseChat::Provider::SlackProvider
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 ))
summary[:title] = "#{topic.title} #{(category == '[uncategorized]')? '' : category} #{topic.tags.present? ? topic.tags.map(&:name).join(', ') : ''}"
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_link] = post.full_url
summary[:thumb_url] = post.full_url
end
@ -67,14 +67,14 @@ module DiscourseChat::Provider::SlackProvider
end
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
response = nil
response = nil
uri = ""
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.concat message[:attachments]
@ -98,55 +98,54 @@ module DiscourseChat::Provider::SlackProvider
response = http.request(Net::HTTP::Post.new(uri))
unless response.kind_of? Net::HTTPSuccess
raise ::DiscourseChat::ProviderError.new info: {request: uri, response_code:response.code, response_body:response.body}
unless response.kind_of? Net::HTTPSuccess
raise ::DiscourseChat::ProviderError.new info: { request: uri, response_code: response.code, response_body: response.body }
end
json = JSON.parse(response.body)
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'
else
error_key = json.to_s
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
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
end
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
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
response = http.request(req)
unless response.kind_of? Net::HTTPSuccess
if response.code.to_s == '403'
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'
else
error_key = nil
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
def self.trigger_notification(post, channel)
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?
self.send_via_webhook(message)
else
self.send_via_api(post, channel_id, message)
end
if SiteSetting.chat_integration_slack_access_token.empty?
self.send_via_webhook(message)
else
self.send_via_api(post, channel_id, message)
end
end
end

View File

@ -27,7 +27,7 @@ module DiscourseChat::Provider::TelegramProvider
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']
message_text = I18n.t(
@ -46,7 +46,7 @@ module DiscourseChat::Provider::TelegramProvider
DiscourseChat::Provider::TelegramProvider.sendMessage(message)
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 = {
success: true
}
@ -58,7 +58,7 @@ module DiscourseChat::Provider::TelegramProvider
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?
return I18n.t(
@ -67,7 +67,7 @@ module DiscourseChat::Provider::TelegramProvider
chat_id: chat_id,
)
end
# If slash commands disabled, send a generic message
if !SiteSetting.chat_integration_telegram_enable_slash_commands
return I18n.t(
@ -97,11 +97,11 @@ module DiscourseChat::Provider::TelegramProvider
end
class TelegramEngine < ::Rails::Engine
engine_name DiscourseChat::PLUGIN_NAME+"-telegram"
engine_name DiscourseChat::PLUGIN_NAME + "-telegram"
isolate_namespace DiscourseChat::Provider::TelegramProvider
end
TelegramEngine.routes.draw do
post "command/:token" => "telegram_command#command"
post "command/:token" => "telegram_command#command"
end
end
end

View File

@ -1,8 +1,8 @@
DiscourseEvent.on(:site_setting_saved) do |sitesetting|
isEnabledSetting = sitesetting.name == 'chat_integration_telegram_enabled'
isAccessToken = sitesetting.name == 'chat_integration_telegram_access_token'
isEnabledSetting = sitesetting.name == 'chat_integration_telegram_enabled'
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
if enabled
Scheduler::Defer.later("Setup Telegram Webhook") do
@ -10,4 +10,4 @@ DiscourseEvent.on(:site_setting_saved) do |sitesetting|
end
end
end
end
end

View File

@ -4,16 +4,16 @@ module DiscourseChat
PROVIDER_NAME = "telegram".freeze
PROVIDER_ENABLED_SETTING = :chat_integration_telegram_enabled
CHANNEL_PARAMETERS = [
{key: "name", regex: '^\S+'},
{key: "chat_id", regex: '^(-?[0-9]+|@\S+)$', unique: true}
{ key: "name", regex: '^\S+' },
{ key: "chat_id", regex: '^(-?[0-9]+|@\S+)$', unique: true }
]
def self.setup_webhook
def self.setup_webhook
newSecret = SecureRandom.hex
SiteSetting.chat_integration_telegram_secret = newSecret
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)
@ -21,7 +21,7 @@ module DiscourseChat
if not response['ok'] == true
# If setting up webhook failed, disable provider
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
@ -38,7 +38,7 @@ module DiscourseChat
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
response = http.request(req)
@ -59,7 +59,7 @@ module DiscourseChat
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
tags = ''
@ -96,7 +96,7 @@ module DiscourseChat
elsif response['description'].include? 'Forbidden'
error_key = 'chat_integration.provider.telegram.errors.forbidden'
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
@ -106,4 +106,4 @@ module DiscourseChat
end
require_relative "telegram_command_controller.rb"
require_relative "telegram_initializer.rb"
require_relative "telegram_initializer.rb"

View File

@ -14,8 +14,8 @@ require_relative "lib/discourse_chat/provider/slack/slack_enabled_setting_valida
after_initialize do
require_relative "app/initializers/discourse_chat"
DiscourseEvent.on(:post_created) do |post|
DiscourseEvent.on(:post_created) do |post|
if SiteSetting.chat_integration_enabled?
# This will run for every post, even PMs. Don't worry, they're filtered out later.
time = SiteSetting.chat_integration_delay_seconds.seconds

View File

@ -8,7 +8,7 @@ describe 'Chat Controller', type: :request do
let(:category) { Fabricate(:category) }
let(:category2) { Fabricate(:category) }
let(:tag) { Fabricate(:tag) }
let(:channel) { DiscourseChat::Channel.create(provider:'dummy') }
let(:channel) { DiscourseChat::Channel.create(provider: 'dummy') }
include_context "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'].find{|h| h['name']=='dummy'}).to eq('name'=> 'dummy',
'id'=> 'dummy',
'channel_parameters'=> []
expect(json['providers'].find { |h| h['name'] == 'dummy' }).to eq('name' => 'dummy',
'id' => 'dummy',
'channel_parameters' => []
)
end
end
@ -90,9 +90,9 @@ describe 'Chat Controller', type: :request do
end
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
@ -105,12 +105,12 @@ describe 'Chat Controller', type: :request do
"provider" => 'dummy',
"data" => {},
"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
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
end
@ -129,7 +129,7 @@ describe 'Chat Controller', type: :request do
it 'should be able to add a new channel' do
post '/admin/plugins/chat/channels.json',
channel:{
channel: {
provider: 'dummy',
data: {}
}
@ -143,9 +143,9 @@ describe 'Chat Controller', type: :request do
it 'should fail for invalid params' do
post '/admin/plugins/chat/channels.json',
channel:{
channel: {
provider: 'dummy2',
data: {val: 'something with whitespace'}
data: { val: 'something with whitespace' }
}
expect(response).not_to be_success
@ -155,8 +155,8 @@ describe 'Chat Controller', type: :request do
end
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"
context 'as an admin' do
@ -167,20 +167,20 @@ describe 'Chat Controller', type: :request do
it 'should be able update a channel' do
put "/admin/plugins/chat/channels/#{channel.id}.json",
channel:{
data: {val: "something-else"}
channel: {
data: { val: "something-else" }
}
expect(response).to be_success
channel = DiscourseChat::Channel.all.first
expect(channel.data).to eq({"val" => "something-else"})
expect(channel.data).to eq("val" => "something-else")
end
it 'should fail for invalid params' do
put "/admin/plugins/chat/channels/#{channel.id}.json",
channel:{
data: {val: "something with whitespace"}
channel: {
data: { val: "something with whitespace" }
}
expect(response).not_to be_success
@ -190,8 +190,8 @@ describe 'Chat Controller', type: :request do
end
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"
context 'as an admin' do
@ -221,7 +221,7 @@ describe 'Chat Controller', type: :request do
it 'should be able to add a new rule' do
post '/admin/plugins/chat/rules.json',
rule:{
rule: {
channel_id: channel.id,
category_id: category.id,
filter: 'watch',
@ -241,7 +241,7 @@ describe 'Chat Controller', type: :request do
it 'should fail for invalid params' do
post '/admin/plugins/chat/rules.json',
rule:{
rule: {
channel_id: channel.id,
category_id: category.id,
filter: 'watch',
@ -255,8 +255,8 @@ describe 'Chat Controller', type: :request do
end
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"
context 'as an admin' do
@ -267,7 +267,7 @@ describe 'Chat Controller', type: :request do
it 'should be able update a rule' do
put "/admin/plugins/chat/rules/#{rule.id}.json",
rule:{
rule: {
channel_id: channel.id,
category_id: category2.id,
filter: rule.filter,
@ -282,7 +282,7 @@ describe 'Chat Controller', type: :request do
it 'should fail for invalid params' do
put "/admin/plugins/chat/rules/#{rule.id}.json",
rule:{
rule: {
channel_id: channel.id,
category_id: category.id,
filter: 'watch',
@ -296,8 +296,8 @@ describe 'Chat Controller', type: :request do
end
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"
context 'as an admin' do

View File

@ -1,13 +1,13 @@
require 'rails_helper'
describe 'Public Controller', type: :request do
before do
SiteSetting.chat_integration_enabled = true
end
describe 'loading a transcript' do
it 'should be able to load a transcript' do
key = DiscourseChat::Helper.save_transcript("Some content here")
@ -24,7 +24,7 @@ describe 'Public Controller', type: :request do
expect(response).not_to be_success
end
end
end

View File

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

View File

@ -4,64 +4,64 @@ require_relative '../dummy_provider'
RSpec.describe DiscourseChat::Manager do
include_context "dummy provider"
let(:chan1){DiscourseChat::Channel.create!(provider:'dummy')}
let(:chan2){DiscourseChat::Channel.create!(provider:'dummy')}
let(:chan1) { 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(:tag1){Fabricate(:tag)}
let(:tag2){Fabricate(:tag)}
let(:tag3){Fabricate(:tag)}
let(:category) { Fabricate(:category) }
let(:tag1) { Fabricate(:tag) }
let(:tag2) { Fabricate(:tag) }
let(:tag3) { Fabricate(:tag) }
describe '.process_command' do
describe 'add new rule' do
# 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
# 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
it 'should add a new rule correctly' do
response = DiscourseChat::Helper.process_command(chan1, ['watch',category.slug])
expect(response).to eq(I18n.t("chat_integration.provider.dummy.create.created"))
it 'should add a new rule correctly' do
response = DiscourseChat::Helper.process_command(chan1, ['watch', category.slug])
rule = DiscourseChat::Rule.all.first
expect(rule.channel).to eq(chan1)
expect(rule.filter).to eq('watch')
expect(rule.category_id).to eq(category.id)
expect(rule.tags).to eq(nil)
end
expect(response).to eq(I18n.t("chat_integration.provider.dummy.create.created"))
rule = DiscourseChat::Rule.all.first
expect(rule.channel).to eq(chan1)
expect(rule.filter).to eq('watch')
expect(rule.category_id).to eq(category.id)
expect(rule.tags).to eq(nil)
end
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
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
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
expect(rule.filter).to eq('mute')
end
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
context 'with tags enabled' do
before do
SiteSetting.tagging_enabled = true
end
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"))
@ -73,9 +73,9 @@ RSpec.describe DiscourseChat::Manager do
end
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"))
rule = DiscourseChat::Rule.all.first
@ -86,23 +86,23 @@ RSpec.describe DiscourseChat::Manager do
end
it 'errors on incorrect tags' do
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"))
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"))
end
end
end
end
describe 'remove rule' do
it 'removes the rule' do
rule1 = DiscourseChat::Rule.create(channel: chan1,
filter: 'watch',
category_id: category.id,
tags: [tag1.name, tag2.name]
filter: 'watch',
category_id: category.id,
tags: [tag1.name, tag2.name]
)
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"))
@ -110,8 +110,8 @@ RSpec.describe DiscourseChat::Manager do
end
it 'errors correctly' do
response = DiscourseChat::Helper.process_command(chan1, ['remove','1'])
expect(response).to eq(I18n.t("chat_integration.provider.dummy.delete.error"))
response = DiscourseChat::Helper.process_command(chan1, ['remove', '1'])
expect(response).to eq(I18n.t("chat_integration.provider.dummy.delete.error"))
end
end
@ -138,7 +138,7 @@ RSpec.describe DiscourseChat::Manager do
end
describe '.status_for_channel' do
context 'with no rules' do
it 'includes the heading' do
string = DiscourseChat::Helper.status_for_channel(chan1)
@ -152,13 +152,13 @@ RSpec.describe DiscourseChat::Manager do
end
context 'with some rules' do
let(:group){Fabricate(:group)}
let(:group) { Fabricate(:group) }
before do
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:'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: chan2, filter:'watch', category_id:1, 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: '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: chan2, filter: 'watch', category_id: 1, tags: nil)
end
it 'displays the correct rules' do
@ -180,32 +180,32 @@ RSpec.describe DiscourseChat::Manager do
end
describe '.delete_by_index' do
let(:category2) {Fabricate(:category)}
let(:category3) {Fabricate(:category)}
let(:category2) { Fabricate(:category) }
let(:category3) { Fabricate(:category) }
it 'deletes the correct rule' do
# Three identical rules, with different filters
# Three identical rules, with different filters
# Status will be sorted by precedence
# be in this order
rule1 = DiscourseChat::Rule.create(channel: chan1,
filter: 'mute',
category_id: category.id,
tags: [tag1.name, tag2.name]
filter: 'mute',
category_id: category.id,
tags: [tag1.name, tag2.name]
)
rule2 = DiscourseChat::Rule.create(channel: chan1,
filter: 'watch',
category_id: category2.id,
tags: [tag1.name, tag2.name]
filter: 'watch',
category_id: category2.id,
tags: [tag1.name, tag2.name]
)
rule3 = DiscourseChat::Rule.create(channel: chan1,
filter: 'follow',
category_id: category3.id,
tags: [tag1.name, tag2.name]
filter: 'follow',
category_id: category3.id,
tags: [tag1.name, tag2.name]
)
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.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
rule1 = DiscourseChat::Rule.create(channel: chan1,
filter: 'watch',
category_id: category.id,
tags: [tag1.name, tag2.name]
filter: 'watch',
category_id: category.id,
tags: [tag1.name, tag2.name]
)
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,2)).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, 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
describe '.smart_create_rule' do
@ -246,10 +245,10 @@ RSpec.describe DiscourseChat::Manager do
end
it 'updates a rule when it has the same category and tags' do
existing = DiscourseChat::Rule.create!(channel:chan1,
filter: 'watch',
category_id: category.id,
tags: [tag2.name, tag1.name]
existing = DiscourseChat::Rule.create!(channel: chan1,
filter: 'watch',
category_id: category.id,
tags: [tag2.name, tag1.name]
)
val = DiscourseChat::Helper.smart_create_rule(channel: chan1,
@ -309,13 +308,13 @@ RSpec.describe DiscourseChat::Manager do
key = DiscourseChat::Helper.save_transcript("Some content here")
expect($redis.get("chat_integration:transcript:#{key}")).to eq("Some content here")
ttl = $redis.pttl("chat_integration:transcript:#{key}")
# 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 >= (3599*1000)
expect($redis.pttl("chat_integration:transcript:#{key}")).to be <= (3601 * 1000)
expect($redis.pttl("chat_integration:transcript:#{key}")).to be >= (3599 * 1000)
end
end
end
end

View File

@ -17,7 +17,7 @@ RSpec.describe PostCreator do
it 'should schedule a chat notification job' do
freeze_time
post = PostCreator.new(topic.user,
raw: 'Some post content',
topic_id: topic.id
@ -29,7 +29,7 @@ RSpec.describe PostCreator do
.to eq((Time.zone.now + SiteSetting.chat_integration_delay_seconds.seconds).to_f)
expect(job['args'].first['post_id']).to eq(post.id)
end
end

View File

@ -8,7 +8,7 @@ RSpec.describe DiscourseChat::Provider::DiscordProvider do
SiteSetting.chat_integration_discord_enabled = true
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
stub1 = stub_request(:post, 'https://discordapp.com/api/webhooks/1234/abcd?wait=true').to_return(status: 200)
@ -18,16 +18,16 @@ RSpec.describe DiscourseChat::Provider::DiscordProvider do
it 'includes the protocol in the avatar URL' do
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?:\/\//})})]}))
.to_return(status: 200)
.with(body: hash_including(embeds: [hash_including(author: hash_including(url: /^https?:\/\//))]))
.to_return(status: 200)
described_class.trigger_notification(post, chan1)
expect(stub1).to have_been_requested.once
expect(stub1).to have_been_requested.once
end
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)
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
end

View File

@ -8,7 +8,7 @@ RSpec.describe DiscourseChat::Provider::HipchatProvider do
SiteSetting.chat_integration_hipchat_enabled = true
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
stub1 = stub_request(:post, 'https://blah.hipchat.com/abcd').to_return(status: 200)
@ -16,10 +16,10 @@ RSpec.describe DiscourseChat::Provider::HipchatProvider do
expect(stub1).to have_been_requested.once
end
it 'handles errors correctly' do
it 'handles errors correctly' do
stub1 = stub_request(:post, "https://blah.hipchat.com/abcd").to_return(status: 400)
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
end

View File

@ -9,7 +9,7 @@ RSpec.describe DiscourseChat::Provider::MatrixProvider do
SiteSetting.chat_integration_matrix_access_token = 'abcd'
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
stub1 = stub_request(:put, %r{https://matrix.org/_matrix/client/r0/rooms/!blah:matrix.org/send/m.room.message/*}).to_return(status: 200)
@ -17,10 +17,10 @@ RSpec.describe DiscourseChat::Provider::MatrixProvider do
expect(stub1).to have_been_requested.once
end
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"}')
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"}')
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
end

View File

@ -4,7 +4,7 @@ describe 'Mattermost Command Controller', type: :request do
let(:category) { Fabricate(:category) }
let(:tag) { 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
it 'should return a 404' do
@ -24,7 +24,7 @@ describe 'Mattermost Command Controller', type: :request do
expect(response.status).to eq(404)
end
end
describe 'slash commands endpoint' do
before do
SiteSetting.chat_integration_enabled = true
@ -70,7 +70,7 @@ describe 'Mattermost Command Controller', type: :request do
end
describe 'add new rule' do
it 'should add a new rule correctly' do
post "/chat-integration/mattermost/command.json",
text: "watch #{category.slug}",
@ -99,7 +99,7 @@ describe 'Mattermost Command Controller', type: :request do
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')
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"
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
stub1 = stub_request(:post, 'https://mattermost.blah/hook/abcd').to_return(status: 200)
@ -17,10 +17,10 @@ RSpec.describe DiscourseChat::Provider::MattermostProvider do
expect(stub1).to have_been_requested.once
end
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")
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
end

View File

@ -4,7 +4,7 @@ describe 'Slack Command Controller', type: :request do
let(:category) { Fabricate(:category) }
let(:tag) { 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
it 'should return a 404' do
@ -24,7 +24,7 @@ describe 'Slack Command Controller', type: :request do
expect(response.status).to eq(404)
end
end
describe 'slash commands endpoint' do
before do
SiteSetting.chat_integration_enabled = true
@ -70,7 +70,7 @@ describe 'Slack Command Controller', type: :request do
end
describe 'add new rule' do
it 'should add a new rule correctly' do
post "/chat-integration/slack/command.json",
text: "watch #{category.slug}",
@ -99,7 +99,7 @@ describe 'Slack Command Controller', type: :request do
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')
rule = chan.rules.first
@ -118,11 +118,11 @@ describe 'Slack Command Controller', type: :request do
it 'generates a transcript properly' do
stub1 = stub_request(:post, "https://slack.com/api/users.list").to_return(body: '{"ok":true,"members":[{"id":"U5Z773QLS","name":"david","profile":{"icon_24":"https://example.com/avatar"}}]}')
stub2 = stub_request(:post, "https://slack.com/api/channels.history").to_return(body: '{"ok":true,"messages":[{"type":"message","user":"U5Z773QLS","text":"And this is a slack message with an attachment: <https:\/\/meta.discourse.org>","attachments":[{"title":"Discourse Meta","title_link":"https:\/\/meta.discourse.org","text":"Discussion about the next-generation open source Discourse forum software","fallback":"Discourse Meta","thumb_url":"https:\/\/discourse-meta.s3-us-west-1.amazonaws.com\/original\/3X\/c\/b\/cb4bec8901221d4a646e45e1fa03db3a65e17f59.png","from_url":"https:\/\/meta.discourse.org","thumb_width":350,"thumb_height":349,"service_icon":"https:\/\/discourse-meta.s3-us-west-1.amazonaws.com\/original\/3X\/c\/b\/cb4bec8901221d4a646e45e1fa03db3a65e17f59.png","service_name":"meta.discourse.org","id":1}],"ts":"1500910064.045243"},{"type":"message","user":"U5Z773QLS","text":"Hello world, this is a slack message","ts":"1500910051.036792"}],"has_more":true}')
post "/chat-integration/slack/command.json",
text: "post 2",
channel_name: 'general',
channel_id:'C6029G78F',
channel_id: 'C6029G78F',
token: token
json = JSON.parse(response.body)
@ -136,7 +136,7 @@ describe 'Slack Command Controller', type: :request do
post "/chat-integration/slack/command.json",
text: "post 2",
channel_name: 'general',
channel_id:'C6029G78F',
channel_id: 'C6029G78F',
token: token
json = JSON.parse(response.body)
@ -146,11 +146,11 @@ describe 'Slack Command Controller', type: :request do
it 'errors correctly if there is no api key' do
SiteSetting.chat_integration_slack_access_token = ''
post "/chat-integration/slack/command.json",
text: "post 2",
channel_name: 'general',
channel_id:'C6029G78F',
channel_id: 'C6029G78F',
token: token
json = JSON.parse(response.body)

View File

@ -57,7 +57,7 @@ RSpec.describe DiscourseChat::Provider::SlackProvider do
SiteSetting.chat_integration_slack_enabled = true
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
stub1 = stub_request(:post, SiteSetting.chat_integration_slack_outbound_webhook_url).to_return(body: "success")
@ -65,10 +65,10 @@ RSpec.describe DiscourseChat::Provider::SlackProvider do
expect(stub1).to have_been_requested.once
end
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")
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
end
@ -76,29 +76,29 @@ RSpec.describe DiscourseChat::Provider::SlackProvider do
before do
SiteSetting.chat_integration_slack_access_token = "magic"
@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'})
@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'})
@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' })
end
it 'sends an api request' do
expect(@stub2).to have_been_requested.times(0)
described_class.trigger_notification(post, chan1)
expect(@stub1).to have_been_requested.times(0)
expect(@stub2).to have_been_requested.once
end
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'})
expect{described_class.trigger_notification(post, chan1)}.to raise_exception(::DiscourseChat::ProviderError)
@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(@stub2).to have_been_requested.once
end
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(@stub3).to have_been_requested.times(0)
described_class.trigger_notification(post, chan1)
described_class.trigger_notification(second_post, chan1)
expect(@stub1).to have_been_requested.times(0)

View File

@ -2,7 +2,7 @@ require 'rails_helper'
describe 'Telegram Command Controller', type: :request do
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
it 'should return a 404' do
@ -31,12 +31,12 @@ describe 'Telegram Command Controller', type: :request do
SiteSetting.chat_integration_telegram_enabled = true
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
it 'should not redirect to login page' do
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)
end
@ -44,15 +44,15 @@ describe 'Telegram Command Controller', type: :request do
describe 'when the token is invalid' do
it 'should raise the right error' do
post '/chat-integration/telegram/command/blah.json', message: {chat: {id:123}, text: '/help' }
expect(response.status).to eq(403)
post '/chat-integration/telegram/command/blah.json', message: { chat: { id: 123 }, text: '/help' }
expect(response.status).to eq(403)
end
end
describe 'when token has not been set' do
it 'should raise the right error' do
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)
end
@ -68,7 +68,7 @@ describe 'Telegram Command Controller', type: :request do
describe 'add new rule' 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(stub).to have_been_requested.once
@ -81,7 +81,7 @@ describe 'Telegram Command Controller', type: :request do
end
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(stub).to have_been_requested.once
@ -95,7 +95,7 @@ describe 'Telegram Command Controller', type: :request do
context 'from an unknown channel' 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::Channel.all.size).to eq(1)
end
@ -103,16 +103,16 @@ describe 'Telegram Command Controller', type: :request do
end
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(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(stub).to have_been_requested.times(1)
end
end
end
end
end

View File

@ -10,7 +10,7 @@ RSpec.describe DiscourseChat::Provider::TelegramProvider do
SiteSetting.chat_integration_telegram_enabled = true
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
stub1 = stub_request(:post, 'https://api.telegram.org/botTOKEN/sendMessage').to_return(body: "{\"ok\":true}")
@ -18,10 +18,10 @@ RSpec.describe DiscourseChat::Provider::TelegramProvider do
expect(stub1).to have_been_requested.once
end
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\"}")
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
end

View File

@ -5,32 +5,29 @@ RSpec.describe DiscourseChat::Channel do
include_context "dummy provider"
include_context "validated dummy provider"
it 'should save and load successfully' do
expect(DiscourseChat::Channel.all.length).to eq(0)
chan = DiscourseChat::Channel.create({
provider:"dummy",
})
chan = DiscourseChat::Channel.create(provider: "dummy")
expect(DiscourseChat::Channel.all.length).to eq(1)
loadedChan = DiscourseChat::Channel.find(chan.id)
expect(loadedChan.provider).to eq('dummy')
end
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)
channel.save!
end
it 'can be filtered by provider' do
channel1 = DiscourseChat::Channel.create!(provider:'dummy')
channel2 = DiscourseChat::Channel.create!(provider:'dummy2', data:{val:"blah"})
channel3 = DiscourseChat::Channel.create!(provider:'dummy2', data:{val:"blah2"})
channel1 = DiscourseChat::Channel.create!(provider: 'dummy')
channel2 = DiscourseChat::Channel.create!(provider: 'dummy2', data: { val: "blah" })
channel3 = DiscourseChat::Channel.create!(provider: 'dummy2', data: { val: "blah2" })
expect(DiscourseChat::Channel.all.length).to eq(3)
@ -39,19 +36,19 @@ RSpec.describe DiscourseChat::Channel do
end
it 'can be filtered by data value' do
channel2 = DiscourseChat::Channel.create!(provider:'dummy2', data:{val:"foo"})
channel3 = DiscourseChat::Channel.create!(provider:'dummy2', data:{val:"blah"})
channel2 = DiscourseChat::Channel.create!(provider: 'dummy2', data: { val: "foo" })
channel3 = DiscourseChat::Channel.create!(provider: 'dummy2', data: { val: "blah" })
expect(DiscourseChat::Channel.all.length).to eq(2)
for_provider = DiscourseChat::Channel.with_provider('dummy2')
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
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)
DiscourseChat::Rule.create(channel: channel)
DiscourseChat::Rule.create(channel: channel)
@ -59,7 +56,7 @@ RSpec.describe DiscourseChat::Channel do
end
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)
rule1 = DiscourseChat::Rule.create(channel: channel)
rule2 = DiscourseChat::Rule.create(channel: channel)
@ -72,40 +69,39 @@ RSpec.describe DiscourseChat::Channel do
describe 'validations' do
it 'validates provider correctly' do
channel = DiscourseChat::Channel.create!(provider:"dummy")
channel = DiscourseChat::Channel.create!(provider: "dummy")
expect(channel.valid?).to eq(true)
channel.provider = 'somerandomprovider'
expect(channel.valid?).to eq(false)
end
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)
end
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)
end
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)
end
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)
end
it 'disallows duplicate channels' do
channel1 = DiscourseChat::Channel.create(provider:"dummy2", data:{val:"hello"})
channel2 = DiscourseChat::Channel.new(provider:"dummy2", data:{val:"hello"})
channel1 = DiscourseChat::Channel.create(provider: "dummy2", data: { val: "hello" })
channel2 = DiscourseChat::Channel.new(provider: "dummy2", data: { val: "hello" })
expect(channel2.valid?).to eq(false)
channel2.data[:val] = "hello2"
expect(channel2.valid?).to eq(true)
end
end
end
end

View File

@ -4,36 +4,34 @@ require_relative '../dummy_provider'
RSpec.describe DiscourseChat::Rule do
include_context "dummy provider"
let(:tag1){Fabricate(:tag)}
let(:tag2){Fabricate(:tag)}
let(:tag1) { Fabricate(:tag) }
let(:tag2) { Fabricate(:tag) }
let(:channel){DiscourseChat::Channel.create(provider:'dummy')}
let(:category) {Fabricate(:category)}
let(:group) {Fabricate(:group)}
let(:channel) { DiscourseChat::Channel.create(provider: 'dummy') }
let(:category) { Fabricate(:category) }
let(:group) { Fabricate(:group) }
describe '.alloc_key' 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:2")
expect( DiscourseChat::Rule.create(channel: channel).key ).to eq("rule:3")
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:2")
expect(DiscourseChat::Rule.create(channel: channel).key).to eq("rule:3")
end
end
it 'should convert between channel and channel_id successfully' do
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
it 'should save and load successfully' do
expect(DiscourseChat::Rule.all.length).to eq(0)
rule = DiscourseChat::Rule.create({
channel: channel,
category_id: category.id,
tags: [tag1.name, tag2.name],
filter: 'watch'
})
rule = DiscourseChat::Rule.create(channel: channel,
category_id: category.id,
tags: [tag1.name, tag2.name],
filter: 'watch')
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.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')
end
describe 'general operations' do
before do
rule = DiscourseChat::Rule.create({
channel: channel,
category_id: category.id,
tags: [tag1.name, tag2.name]
})
rule = DiscourseChat::Rule.create(channel: channel,
category_id: category.id,
tags: [tag1.name, tag2.name])
end
it 'can be modified' do
@ -66,7 +62,7 @@ RSpec.describe DiscourseChat::Rule do
end
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)
rule = DiscourseChat::Rule.all.first
@ -76,11 +72,11 @@ RSpec.describe DiscourseChat::Rule do
end
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)
DiscourseChat::Rule.destroy_all
@ -89,14 +85,14 @@ RSpec.describe DiscourseChat::Rule do
end
it 'can be filtered by channel' do
channel2 = DiscourseChat::Channel.create(provider:'dummy')
channel3 = DiscourseChat::Channel.create(provider:'dummy')
channel2 = DiscourseChat::Channel.create(provider: 'dummy')
channel3 = DiscourseChat::Channel.create(provider: 'dummy')
rule2 = DiscourseChat::Rule.create(channel: channel)
rule3 = DiscourseChat::Rule.create(channel: channel)
rule4 = DiscourseChat::Rule.create(channel: channel2)
rule5 = DiscourseChat::Rule.create(channel: channel3)
rule2 = DiscourseChat::Rule.create(channel:channel)
rule3 = DiscourseChat::Rule.create(channel:channel)
rule4 = DiscourseChat::Rule.create(channel:channel2)
rule5 = DiscourseChat::Rule.create(channel:channel3)
expect(DiscourseChat::Rule.all.length).to eq(5)
expect(DiscourseChat::Rule.with_channel(channel).length).to eq(3)
@ -104,8 +100,8 @@ RSpec.describe DiscourseChat::Rule do
end
it 'can be filtered by category' do
rule2 = DiscourseChat::Rule.create(channel:channel, category_id: category.id)
rule3 = DiscourseChat::Rule.create(channel:channel, category_id: nil)
rule2 = DiscourseChat::Rule.create(channel: channel, category_id: category.id)
rule3 = DiscourseChat::Rule.create(channel: channel, category_id: nil)
expect(DiscourseChat::Rule.all.length).to eq(3)
@ -116,13 +112,13 @@ RSpec.describe DiscourseChat::Rule do
it 'can be filtered by group' do
group1 = Fabricate(:group)
group2 = Fabricate(:group)
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)
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)
expect(DiscourseChat::Rule.all.length).to eq(3)
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([group2.id]).length).to eq(1)
end
@ -141,9 +137,9 @@ RSpec.describe DiscourseChat::Rule do
end
it 'can be sorted by precedence' do
rule2 = DiscourseChat::Rule.create(channel:channel, filter:'mute')
rule3 = DiscourseChat::Rule.create(channel:channel, filter:'follow')
rule4 = DiscourseChat::Rule.create(channel:channel, filter:'mute')
rule2 = DiscourseChat::Rule.create(channel: channel, filter: 'mute')
rule3 = DiscourseChat::Rule.create(channel: channel, filter: 'follow')
rule4 = DiscourseChat::Rule.create(channel: channel, filter: 'mute')
expect(DiscourseChat::Rule.all.length).to eq(4)
@ -152,13 +148,11 @@ RSpec.describe DiscourseChat::Rule do
end
describe 'validations' do
let(:rule) do
DiscourseChat::Rule.create({
filter: 'watch',
channel: channel,
category_id: category.id,
})
DiscourseChat::Rule.create(filter: 'watch',
channel: channel,
category_id: category.id)
end
it 'validates channel correctly' do
@ -223,4 +217,4 @@ RSpec.describe DiscourseChat::Rule do
end
end
end
end

View File

@ -4,29 +4,29 @@ require_relative '../dummy_provider'
RSpec.describe DiscourseChat::Manager do
let(:manager) {::DiscourseChat::Manager}
let(:category) {Fabricate(:category)}
let(:group) {Fabricate(:group)}
let(:topic){Fabricate(:topic, category_id: category.id )}
let(:first_post) {Fabricate(:post, topic: topic)}
let(:second_post) {Fabricate(:post, topic: topic, post_number:2)}
let(:manager) { ::DiscourseChat::Manager }
let(:category) { Fabricate(:category) }
let(:group) { Fabricate(:group) }
let(:topic) { Fabricate(:topic, category_id: category.id) }
let(:first_post) { Fabricate(:post, topic: topic) }
let(:second_post) { Fabricate(:post, topic: topic, post_number: 2) }
describe '.trigger_notifications' do
include_context "dummy provider"
let(:chan1){DiscourseChat::Channel.create!(provider:'dummy')}
let(:chan2){DiscourseChat::Channel.create!(provider:'dummy')}
let(:chan3){DiscourseChat::Channel.create!(provider:'dummy')}
let(:chan1) { DiscourseChat::Channel.create!(provider: 'dummy') }
let(:chan2) { DiscourseChat::Channel.create!(provider: 'dummy') }
let(:chan3) { DiscourseChat::Channel.create!(provider: 'dummy') }
before do
SiteSetting.chat_integration_enabled = true
end
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
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)
expect(provider.sent_to_channel_ids).to contain_exactly()
expect(DiscourseChat::Channel.all.first.error_key).to eq('hello')
@ -40,12 +40,12 @@ RSpec.describe DiscourseChat::Manager do
provider.set_raise_exception(nil)
manager.trigger_notifications(first_post.id)
expect(DiscourseChat::Channel.all.first.error_key.nil?).to be true
expect(DiscourseChat::Channel.all.first.error_key.nil?).to be true
end
it "should not send notifications when provider is disabled" do
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)
@ -53,9 +53,9 @@ RSpec.describe DiscourseChat::Manager do
end
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: chan2, filter: 'follow', category_id:category.id )
DiscourseChat::Rule.create!(channel: chan3, filter: 'mute', 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: chan3, filter: 'mute', category_id: category.id)
manager.trigger_notifications(first_post.id)
@ -63,9 +63,9 @@ RSpec.describe DiscourseChat::Manager do
end
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: chan2, filter: 'follow', category_id:category.id )
DiscourseChat::Rule.create!(channel: chan3, filter: 'mute', 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: chan3, filter: 'mute', category_id: category.id)
manager.trigger_notifications(second_post.id)
@ -73,7 +73,7 @@ RSpec.describe DiscourseChat::Manager do
end
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)
@ -81,8 +81,8 @@ RSpec.describe DiscourseChat::Manager do
end
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: 'mute', category_id: category.id ) # Specific mute
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
manager.trigger_notifications(first_post.id)
@ -90,8 +90,8 @@ RSpec.describe DiscourseChat::Manager do
end
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: 'watch', category_id: category.id ) # Specific 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
manager.trigger_notifications(second_post.id)
@ -99,8 +99,8 @@ RSpec.describe DiscourseChat::Manager do
end
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)
manager.trigger_notifications(private_post.id)
@ -109,9 +109,9 @@ RSpec.describe DiscourseChat::Manager do
end
it "should work for group pms" do
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: chan1, filter: 'watch') # Wildcard 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.topic.invite_group(Fabricate(:user), group)
@ -122,8 +122,8 @@ RSpec.describe DiscourseChat::Manager do
it "should work for pms with multiple groups" do
group2 = Fabricate(:group)
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: chan1, type: 'group_message', filter: 'watch', group_id: group.id)
DiscourseChat::Rule.create!(channel: chan2, type: 'group_message', filter: 'watch', group_id: group2.id)
private_post = Fabricate(:private_message_post)
private_post.topic.invite_group(Fabricate(:user), group)
@ -146,7 +146,7 @@ RSpec.describe DiscourseChat::Manager do
end
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
group = Fabricate(:group, name: "friends")
@ -180,16 +180,16 @@ RSpec.describe DiscourseChat::Manager do
end
describe 'with tags enabled' do
let(:tag){Fabricate(:tag, name:'gsoc')}
let(:tagged_topic){Fabricate(:topic, category_id: category.id, tags: [tag])}
let(:tagged_first_post) {Fabricate(:post, topic: tagged_topic)}
let(:tag) { Fabricate(:tag, name: 'gsoc') }
let(:tagged_topic) { Fabricate(:topic, category_id: category.id, tags: [tag]) }
let(:tagged_first_post) { Fabricate(:post, topic: tagged_topic) }
before(:each) do
SiteSetting.tagging_enabled = true
end
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(tagged_first_post.id)
@ -198,7 +198,7 @@ RSpec.describe DiscourseChat::Manager do
end
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(tagged_first_post.id)
@ -209,4 +209,4 @@ RSpec.describe DiscourseChat::Manager do
end
end
end
end