slack.rb 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class Transaction::Slack
  3. =begin
  4. backend = Transaction::Slack.new(
  5. object: 'Ticket',
  6. type: 'update',
  7. object_id: 123,
  8. interface_handle: 'application_server', # application_server|websocket|scheduler
  9. changes: {
  10. 'attribute1' => [before, now],
  11. 'attribute2' => [before, now],
  12. },
  13. created_at: Time.zone.now,
  14. user_id: 123,
  15. )
  16. backend.perform
  17. =end
  18. def initialize(item, params = {})
  19. @item = item
  20. @params = params
  21. end
  22. def perform
  23. # return if we run import mode
  24. return if Setting.get('import_mode')
  25. return if @item[:object] != 'Ticket'
  26. return if !Setting.get('slack_integration')
  27. config = Setting.get('slack_config')
  28. return if !config
  29. return if !config['items']
  30. ticket = Ticket.find_by(id: @item[:object_id])
  31. return if !ticket
  32. if @item[:article_id]
  33. article = Ticket::Article.find(@item[:article_id])
  34. # ignore notifications
  35. sender = Ticket::Article::Sender.lookup(id: article.sender_id)
  36. if sender&.name == 'System'
  37. return if @item[:changes].blank?
  38. article = nil
  39. end
  40. end
  41. # ignore if no changes has been done
  42. changes = human_changes(ticket)
  43. return if @item[:type] == 'update' && !article && changes.blank?
  44. # get user based notification template
  45. # if create, send create message / block update messages
  46. template = nil
  47. sent_value = nil
  48. if @item[:type] == 'create'
  49. template = 'ticket_create'
  50. elsif @item[:type] == 'update'
  51. template = 'ticket_update'
  52. elsif @item[:type] == 'reminder_reached'
  53. template = 'ticket_reminder_reached'
  54. sent_value = ticket.pending_time
  55. elsif @item[:type] == 'escalation'
  56. template = 'ticket_escalation'
  57. sent_value = ticket.escalation_at
  58. elsif @item[:type] == 'escalation_warning'
  59. template = 'ticket_escalation_warning'
  60. sent_value = ticket.escalation_at
  61. else
  62. raise "unknown type for notification #{@item[:type]}"
  63. end
  64. user = User.find(1)
  65. current_user = User.lookup(id: @item[:user_id])
  66. if !current_user
  67. current_user = User.lookup(id: 1)
  68. end
  69. result = NotificationFactory::Slack.template(
  70. template: template,
  71. locale: user.locale,
  72. timezone: Setting.get('timezone_default'),
  73. objects: {
  74. ticket: ticket,
  75. article: article,
  76. current_user: current_user,
  77. changes: changes,
  78. },
  79. )
  80. # good, warning, danger
  81. color = '#000000'
  82. ticket_state_type = ticket.state.state_type.name
  83. if ticket.escalation_at && ticket.escalation_at < Time.zone.now
  84. color = '#f35912'
  85. elsif ticket_state_type == 'pending reminder'
  86. if ticket.pending_time && ticket.pending_time < Time.zone.now
  87. color = '#faab00'
  88. end
  89. elsif ticket_state_type.match?(/^(new|open)$/)
  90. color = '#faab00'
  91. elsif ticket_state_type == 'closed'
  92. color = '#38ad69'
  93. end
  94. config['items'].each do |local_config|
  95. next if local_config['webhook'].blank?
  96. # check if reminder_reached/escalation/escalation_warning is already sent today
  97. md5_webhook = Digest::MD5.hexdigest(local_config['webhook'])
  98. cache_key = "slack::backend::#{@item[:type]}::#{ticket.id}::#{md5_webhook}"
  99. if sent_value
  100. value = Cache.get(cache_key)
  101. if value == sent_value
  102. Rails.logger.debug { "did not send webhook, already sent (#{@item[:type]}/#{ticket.id}/#{local_config['webhook']})" }
  103. next
  104. end
  105. Cache.write(
  106. cache_key,
  107. sent_value,
  108. {
  109. expires_in: 24.hours
  110. },
  111. )
  112. end
  113. # check action
  114. if local_config['types'].class == Array
  115. hit = false
  116. local_config['types'].each do |type|
  117. next if type.to_s != @item[:type].to_s
  118. hit = true
  119. break
  120. end
  121. next if !hit
  122. elsif local_config['types']
  123. next if local_config['types'].to_s != @item[:type].to_s
  124. end
  125. # check group
  126. if local_config['group_ids'].class == Array
  127. hit = false
  128. local_config['group_ids'].each do |group_id|
  129. next if group_id.to_s != ticket.group_id.to_s
  130. hit = true
  131. break
  132. end
  133. next if !hit
  134. elsif local_config['group_ids']
  135. next if local_config['group_ids'].to_s != ticket.group_id.to_s
  136. end
  137. logo_url = 'https://zammad.com/assets/images/logo-200x200.png'
  138. if local_config['logo_url'].present?
  139. logo_url = local_config['logo_url']
  140. end
  141. Rails.logger.debug { "sent webhook (#{@item[:type]}/#{ticket.id}/#{local_config['webhook']})" }
  142. notifier = Slack::Notifier.new(
  143. local_config['webhook'],
  144. channel: local_config['channel'],
  145. username: local_config['username'],
  146. icon_url: logo_url,
  147. mrkdwn: true,
  148. http_client: Transaction::Slack::Client,
  149. )
  150. if local_config['expand']
  151. body = "#{result[:subject]}\n#{result[:body]}"
  152. result = notifier.ping body
  153. else
  154. attachment = {
  155. text: result[:body],
  156. mrkdwn_in: ['text'],
  157. color: color,
  158. }
  159. result = notifier.ping result[:subject],
  160. attachments: [attachment]
  161. end
  162. if !result.empty? && !result[0].success?
  163. if sent_value
  164. Cache.delete(cache_key)
  165. end
  166. Rails.logger.error "Unable to post webhook: #{local_config['webhook']}: #{result.inspect}"
  167. next
  168. end
  169. Rails.logger.debug { "sent webhook (#{@item[:type]}/#{ticket.id}/#{local_config['webhook']})" }
  170. end
  171. end
  172. def human_changes(record)
  173. return {} if !@item[:changes]
  174. user = User.find(1)
  175. locale = user.preferences[:locale] || Setting.get('locale_default') || 'en-us'
  176. # only show allowed attributes
  177. attribute_list = ObjectManager::Attribute.by_object_as_hash('Ticket', user)
  178. #puts "AL #{attribute_list.inspect}"
  179. user_related_changes = {}
  180. @item[:changes].each do |key, value|
  181. # if no config exists, use all attributes
  182. if attribute_list.blank?
  183. user_related_changes[key] = value
  184. # if config exists, just use existing attributes for user
  185. elsif attribute_list[key.to_s]
  186. user_related_changes[key] = value
  187. end
  188. end
  189. changes = {}
  190. user_related_changes.each do |key, value|
  191. # get attribute name
  192. attribute_name = key.to_s
  193. object_manager_attribute = attribute_list[attribute_name]
  194. if attribute_name[-3, 3] == '_id'
  195. attribute_name = attribute_name[ 0, attribute_name.length - 3 ].to_s
  196. end
  197. # add item to changes hash
  198. if key.to_s == attribute_name
  199. changes[attribute_name] = value
  200. end
  201. # if changed item is an _id field/reference, look up the real values
  202. value_id = []
  203. value_str = [ value[0], value[1] ]
  204. if key.to_s[-3, 3] == '_id'
  205. value_id[0] = value[0]
  206. value_id[1] = value[1]
  207. if record.respond_to?(attribute_name) && record.send(attribute_name)
  208. relation_class = record.send(attribute_name).class
  209. if relation_class && value_id[0]
  210. relation_model = relation_class.lookup(id: value_id[0])
  211. if relation_model
  212. if relation_model['name']
  213. value_str[0] = relation_model['name']
  214. elsif relation_model.respond_to?('fullname')
  215. value_str[0] = relation_model.send('fullname')
  216. end
  217. end
  218. end
  219. if relation_class && value_id[1]
  220. relation_model = relation_class.lookup(id: value_id[1])
  221. if relation_model
  222. if relation_model['name']
  223. value_str[1] = relation_model['name']
  224. elsif relation_model.respond_to?('fullname')
  225. value_str[1] = relation_model.send('fullname')
  226. end
  227. end
  228. end
  229. end
  230. end
  231. # check if we have a dedicated display name for it
  232. display = attribute_name
  233. if object_manager_attribute && object_manager_attribute[:display]
  234. # delete old key
  235. changes.delete(display)
  236. # set new key
  237. display = object_manager_attribute[:display].to_s
  238. end
  239. changes[display] = if object_manager_attribute && object_manager_attribute[:translate]
  240. from = Translation.translate(locale, value_str[0])
  241. to = Translation.translate(locale, value_str[1])
  242. [from, to]
  243. else
  244. [value_str[0].to_s, value_str[1].to_s]
  245. end
  246. end
  247. changes
  248. end
  249. class Transaction::Slack::Client
  250. def self.post(uri, params = {})
  251. UserAgent.post(
  252. uri.to_s,
  253. params,
  254. {
  255. open_timeout: 4,
  256. read_timeout: 10,
  257. total_timeout: 20,
  258. log: {
  259. facility: 'slack_webhook',
  260. }
  261. },
  262. )
  263. end
  264. end
  265. end