slack.rb 8.8 KB

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