discourse-chat-integration/lib/discourse_chat/provider/hipchat/hipchat_provider.rb

94 lines
2.8 KiB
Ruby
Raw Normal View History

2017-07-24 14:22:19 -04:00
module DiscourseChat
module Provider
module HipchatProvider
PROVIDER_NAME = "hipchat".freeze
PROVIDER_ENABLED_SETTING = :chat_integration_hipchat_enabled
CHANNEL_PARAMETERS = [
2017-08-01 15:53:39 -04:00
{ key: "name", regex: '^\S+' },
{ key: "webhook_url", regex: 'hipchat\.com', unique: true, hidden: true },
2017-08-16 08:51:46 -04:00
{ key: "color", regex: '^(yellow|green|red|purple|gray|random)$' }
2017-07-24 14:22:19 -04:00
]
def self.send_message(url, message)
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
2017-08-01 15:53:39 -04:00
req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
2017-07-24 14:22:19 -04:00
req.body = message.to_json
response = http.request(req)
return response
end
def self.generate_hipchat_message(post)
display_name = "@#{post.user.username}"
full_name = post.user.name || ""
if !(full_name.strip.empty?) && (full_name.strip.gsub(' ', '_').casecmp(post.user.username) != 0) && (full_name.strip.gsub(' ', '').casecmp(post.user.username) != 0)
display_name = "#{full_name} @#{post.user.username}"
end
topic = post.topic
message_text = I18n.t(
"chat_integration.provider.hipchat.message",
user: display_name,
post_url: post.full_url,
title: CGI::escapeHTML(topic.title),
)
2017-08-01 15:53:39 -04:00
icon_url =
2017-07-24 14:22:19 -04:00
if !SiteSetting.chat_integration_hipchat_icon_url.blank?
UrlHelper.absolute(SiteSetting.chat_integration_hipchat_icon_url)
elsif !SiteSetting.logo_small_url.blank?
UrlHelper.absolute(SiteSetting.logo_small_url)
end
message = {
message: message_text, # Fallback for clients that don't support the card markup
notify: true,
card: {
style: "application",
url: post.full_url,
format: "medium",
id: "discoursecard:#{post.id}",
title: topic.title,
description: post.excerpt(SiteSetting.chat_integration_hipchat_excerpt_length, text_entities: true, strip_links: true, remap_emoji: true),
icon: {
url: icon_url,
},
activity: {
2017-08-01 15:53:39 -04:00
html: message_text
2017-07-24 14:22:19 -04:00
}
}
}
return message
end
def self.trigger_notification(post, channel)
2017-08-01 15:53:39 -04:00
2017-07-24 14:22:19 -04:00
webhook_url = channel.data['webhook_url']
message = generate_hipchat_message(post)
message[:color] = channel.data['color']
response = send_message(webhook_url, message)
if not response.kind_of? Net::HTTPSuccess
error_key = nil
2017-08-01 15:53:39 -04:00
raise ::DiscourseChat::ProviderError.new info: { error_key: error_key, message: message, response_body: response.body }
2017-07-24 14:22:19 -04:00
end
end
end
end
2017-08-01 15:53:39 -04:00
end