trigger_webhook_job.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class TriggerWebhookJob < ApplicationJob
  3. USER_ATTRIBUTE_FILTER = %w[
  4. last_login
  5. login_failed
  6. password
  7. preferences
  8. group_ids
  9. groups
  10. authorization_ids
  11. authorizations
  12. ].freeze
  13. attr_reader :ticket, :trigger, :article
  14. retry_on TriggerWebhookJob::RequestError, attempts: 5, wait: lambda { |executions|
  15. executions * 10.seconds
  16. }
  17. discard_on(ActiveJob::DeserializationError) do |_job, e|
  18. Rails.logger.info 'Trigger, Ticket or Article may got removed before TriggerWebhookJob could be executed. Discarding job. See exception for further details.'
  19. Rails.logger.info e
  20. end
  21. def perform(trigger, ticket, article)
  22. @trigger = trigger
  23. @ticket = ticket
  24. @article = article
  25. return if abort?
  26. return if request.success?
  27. raise TriggerWebhookJob::RequestError
  28. end
  29. private
  30. def abort?
  31. if webhook_id.blank?
  32. log_wrong_trigger_config
  33. return true
  34. elsif webhook.blank?
  35. log_not_existing_webhook
  36. return true
  37. end
  38. false
  39. end
  40. def webhook_id
  41. @webhook_id ||= trigger.perform.dig('notification.webhook', 'webhook_id')
  42. end
  43. def webhook
  44. @webhook ||= begin
  45. Webhook.find_by(
  46. id: webhook_id,
  47. active: true
  48. )
  49. end
  50. end
  51. def log_wrong_trigger_config
  52. Rails.logger.error "Can't find webhook_id for Trigger '#{trigger.name}' with ID #{trigger.id}"
  53. end
  54. def log_not_existing_webhook
  55. Rails.logger.error "Can't find Webhook for ID #{webhook_id} configured in Trigger '#{trigger.name}' with ID #{trigger.id}"
  56. end
  57. def request
  58. UserAgent.post(
  59. webhook.endpoint,
  60. payload,
  61. {
  62. json: true,
  63. jsonParseDisable: true,
  64. open_timeout: 4,
  65. read_timeout: 30,
  66. total_timeout: 60,
  67. headers: headers,
  68. signature_token: webhook.signature_token,
  69. verify_ssl: webhook.ssl_verify,
  70. log: {
  71. facility: 'webhook',
  72. },
  73. },
  74. )
  75. end
  76. def headers
  77. {
  78. 'X-Zammad-Trigger' => trigger.name,
  79. 'X-Zammad-Delivery' => job_id
  80. }
  81. end
  82. def payload
  83. {
  84. ticket: TriggerWebhookJob::RecordPayload.generate(ticket),
  85. article: TriggerWebhookJob::RecordPayload.generate(article),
  86. }
  87. end
  88. end