inline_images.rb 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. class Sequencer
  3. class Unit
  4. module Import
  5. module Common
  6. module Ticket
  7. module Article
  8. class InlineImages < Sequencer::Unit::Base
  9. include ::Sequencer::Unit::Import::Common::Mapping::Mixin::ProvideMapped
  10. uses :mapped
  11. def process
  12. return if !contains_inline_image?(mapped[:body])
  13. provide_mapped do
  14. {
  15. body: replaced_inline_images,
  16. }
  17. end
  18. end
  19. def self.inline_data(image_url)
  20. clean_image_url = image_url.gsub(%r{^cid:}, '')
  21. return if !%r{^(http|https)://.+?$}.match?(clean_image_url)
  22. @cache ||= {}
  23. return @cache[clean_image_url] if @cache[clean_image_url]
  24. image_data = download(clean_image_url)
  25. return if image_data.blank?
  26. @cache[clean_image_url] = "data:image/png;base64,#{Base64.strict_encode64(image_data)}"
  27. @cache[clean_image_url]
  28. end
  29. def self.download(image_url)
  30. logger.debug { "Downloading inline image from #{image_url}" }
  31. response = UserAgent.get(
  32. image_url,
  33. {},
  34. {
  35. open_timeout: 20,
  36. read_timeout: 240,
  37. verify_ssl: true,
  38. },
  39. )
  40. return response.body if response.success?
  41. logger.error response.error
  42. nil
  43. end
  44. private
  45. def contains_inline_image?(string)
  46. return false if string.blank?
  47. string.include?(inline_image_url_prefix)
  48. end
  49. def replaced_inline_images
  50. body_html = Nokogiri::HTML(mapped[:body])
  51. body_html.css('img').each do |node|
  52. next if !contains_inline_image?(node['src'])
  53. node.attributes['src'].value = self.class.inline_data(node['src'])
  54. end
  55. body_html.to_html
  56. end
  57. def inline_image_url_prefix
  58. raise NotImplementedError
  59. end
  60. end
  61. end
  62. end
  63. end
  64. end
  65. end
  66. end