generic.rb 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class Sequencer::Unit::Import::Kayako::SubSequence::Generic < Sequencer::Unit::Base
  3. uses :dry_run, :import_job, :field_map, :id_map, :default_language
  4. attr_accessor :iteration, :result
  5. EXPECTING = %i[action response].freeze
  6. def process
  7. loop.each_with_index do |_, iteration|
  8. @iteration = iteration
  9. @result = ::Sequencer.process(sequence_name,
  10. parameters: sequence_params,
  11. expecting: self.class.const_get(:EXPECTING))
  12. break if iteration_should_stop?
  13. end
  14. end
  15. def sequence_params
  16. {
  17. request_params: request_params,
  18. import_job: import_job,
  19. dry_run: dry_run,
  20. object: object,
  21. default_language: default_language,
  22. field_map: field_map,
  23. id_map: id_map,
  24. }
  25. end
  26. def request_params
  27. return {} if iteration.zero?
  28. if cursor_pagination?
  29. return cursor_pagination
  30. end
  31. offset_pagination
  32. end
  33. def object
  34. @object ||= self.class.name.demodulize.singularize
  35. end
  36. def sequence_name
  37. raise NotImplementedError
  38. end
  39. private
  40. def offset_pagination
  41. {
  42. offset: offset,
  43. }
  44. end
  45. def offset
  46. iteration * 100
  47. end
  48. def cursor_pagination?
  49. return if result.nil?
  50. @cursor_pagination ||= result[:response].header['link'].include?('after_id')
  51. end
  52. def cursor_pagination
  53. {
  54. after_id: cursor_after_id
  55. }
  56. end
  57. def cursor_after_id
  58. unescaped_header_next_link.match(%r{after_id=(\d+)})[1]
  59. end
  60. def unescaped_header_next_link
  61. CGI.unescape(CGI.unescape(result[:response].header['link']))
  62. end
  63. def iteration_should_stop?
  64. return true if result[:action] == :failed
  65. return true if result[:response].header['link'].blank? || result[:response].header['link'].exclude?('rel="next"')
  66. false
  67. end
  68. end