attachments.rb 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. attachment: true,
  42. )
  43. return if dry_run
  44. store_attachment(attachment, response)
  45. rescue => e
  46. logger.error(e)
  47. end
  48. def store_attachment(attachment, response)
  49. self.class.mutex.synchronize do
  50. ::Store.create!(
  51. object: model_class.name,
  52. o_id: instance.id,
  53. data: response.body,
  54. filename: attachment['name'],
  55. preferences: {
  56. 'Content-Type' => attachment['type']
  57. },
  58. created_by_id: 1
  59. )
  60. end
  61. end
  62. end