slack.rb 8.3 KB

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