attachments.rb 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Sequencer::Unit::Import::Kayako::Post::Attachments < Sequencer::Unit::Base
  3. include ::Sequencer::Unit::Import::Kayako::Requester
  4. prepend ::Sequencer::Unit::Import::Common::Model::Mixin::Skip::Action
  5. optional :action
  6. skip_action :skipped, :failed
  7. uses :resource, :instance, :model_class, :dry_run
  8. def self.mutex
  9. @mutex ||= Mutex.new
  10. end
  11. def process
  12. return if skip?
  13. download_threads.each(&:join)
  14. end
  15. private
  16. def local_attachments
  17. @local_attachments ||= instance.attachments&.filter { |attachment| attachment.preferences&.dig('Content-Disposition') != 'inline' }
  18. end
  19. def skip?
  20. ensure_common_ground
  21. attachments_equal?
  22. end
  23. def ensure_common_ground
  24. return if attachments_equal?
  25. local_attachments.each(&:delete)
  26. end
  27. def attachments_equal?
  28. resource['attachments'].count == local_attachments.count
  29. end
  30. def download_threads
  31. resource['attachments'].map do |attachment|
  32. Thread.new do
  33. sync(attachment)
  34. end
  35. end
  36. end
  37. def sync(attachment)
  38. logger.debug { "Downloading attachment #{attachment}" }
  39. response = request(
  40. api_path: attachment['url_download'].gsub("#{Setting.get('import_kayako_endpoint')}/", ''),
  41. )
  42. return if dry_run
  43. store_attachment(attachment, response)
  44. rescue => e
  45. logger.error(e)
  46. end
  47. def store_attachment(attachment, response)
  48. self.class.mutex.synchronize do
  49. ::Store.create!(
  50. object: model_class.name,
  51. o_id: instance.id,
  52. data: response.body,
  53. filename: attachment['name'],
  54. preferences: {
  55. 'Content-Type' => attachment['type']
  56. },
  57. created_by_id: 1
  58. )
  59. end
  60. end
  61. end