http_client.rb 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. require 'uri'
  3. class GitLab
  4. class HttpClient
  5. attr_reader :api_token, :endpoint, :verify_ssl
  6. def initialize(endpoint, api_token, verify_ssl: true)
  7. raise __('Invalid GitLab configuration (missing endpoint or api_token).') if api_token.blank? || endpoint.blank? || endpoint.exclude?('/graphql') || endpoint.scan(URI::DEFAULT_PARSER.make_regexp).blank?
  8. @api_token = api_token
  9. @endpoint = endpoint
  10. @verify_ssl = verify_ssl
  11. end
  12. # returns path of the subfolder of the endpoint if exists
  13. def endpoint_path
  14. path = URI.parse(endpoint).path
  15. return if path.blank?
  16. return if path == '/api/graphql'
  17. if path.start_with?('/')
  18. path = path[1..]
  19. end
  20. path.sub('api/graphql', '')
  21. end
  22. def perform(payload)
  23. response = UserAgent.post(
  24. endpoint,
  25. payload,
  26. {
  27. headers: headers,
  28. json: true,
  29. open_timeout: 6,
  30. read_timeout: 16,
  31. log: {
  32. facility: 'GitLab',
  33. },
  34. verify_ssl: verify_ssl,
  35. },
  36. )
  37. if !response.success?
  38. Rails.logger.error response.error
  39. raise __('GitLab request failed. Please have a look at the log file for details.')
  40. end
  41. response.data
  42. end
  43. def perform_rest_get_request(variables)
  44. uri = URI.parse(endpoint)
  45. return if uri.blank? || variables.blank?
  46. response = UserAgent.get(
  47. "#{uri.scheme}://#{uri.host}/api/v4/projects/#{ERB::Util.url_encode(variables[:fullpath])}/issues/#{variables[:issue_id]}",
  48. {},
  49. {
  50. headers: headers,
  51. json: true,
  52. open_timeout: 6,
  53. read_timeout: 16,
  54. log: {
  55. facility: 'GitLab',
  56. },
  57. verify_ssl: verify_ssl,
  58. },
  59. )
  60. if !response.success?
  61. Rails.logger.error response.error
  62. return
  63. end
  64. JSON.parse(response.body)
  65. end
  66. private
  67. def headers
  68. {
  69. 'PRIVATE-TOKEN': @api_token
  70. }
  71. end
  72. end
  73. end