apply_zendesk_configuration.rb 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Service::System::Import::ApplyZendeskConfiguration < Service::System::Import::ApplyConfigurationBase
  3. def execute
  4. super
  5. Setting.set('import_zendesk_endpoint', @endpoint)
  6. Setting.set('import_zendesk_endpoint_username', @username)
  7. Setting.set('import_zendesk_endpoint_key', @secret)
  8. Setting.set('import_backend', 'zendesk')
  9. end
  10. private
  11. def build_endpoint
  12. "#{@url}/api/v2".gsub(%r{([^:])//+}, '\\1/')
  13. end
  14. def reachable!
  15. response = request("#{@endpoint}/users/me", verify_ssl: @tls_verify)
  16. return if response.header&.fetch('x-zendesk-api-version', nil).present?
  17. message = response.error.to_s.presence || __('The hostname could not be found.')
  18. raise_unreachable_error(message) if !response.success?
  19. end
  20. def accessible!
  21. result = check_accessibility { Sequencer.process('Import::Zendesk::ConnectionTest') }
  22. raise InaccessibleError, __('The provided credentials are invalid.') if !result[:connected]
  23. end
  24. def check_accessibility(&)
  25. Setting.set('import_zendesk_endpoint', @endpoint)
  26. Setting.set('import_zendesk_endpoint_username', @username)
  27. Setting.set('import_zendesk_endpoint_key', @secret)
  28. result = yield
  29. Setting.set('import_zendesk_endpoint', nil)
  30. Setting.set('import_zendesk_endpoint_username', nil)
  31. Setting.set('import_zendesk_endpoint_key', nil)
  32. result
  33. end
  34. def raise_unreachable_error(message)
  35. messages = {
  36. 'No such file' => __('The hostname could not be found.'),
  37. 'getaddrinfo: nodename nor servname provided, or not known' => __('The hostname could not be found.'),
  38. '503 Service Temporarily Unavailable' => __('The hostname could not be found.'),
  39. 'No route to host' => __('There is no route to this host.'),
  40. 'Connection refused' => __('The connection was refused.'),
  41. }
  42. human_message = messages.find { |key, _| message.match?(%r{#{Regexp.escape(key)}}i) }&.last
  43. raise UnreachableError, human_message.presence || message
  44. end
  45. end