Files
openfoodnetwork/engines/dfc_provider/app/services/image_builder.rb
2025-03-04 20:02:03 +01:00

36 lines
1005 B
Ruby

# frozen_string_literal: true
require "private_address_check"
require "private_address_check/tcpsocket_ext"
class ImageBuilder < DfcBuilder
def self.apply(image_url, spree_product)
return if image_url.blank?
return if image_url == current_image_url(spree_product)
image = ImageBuilder.import(image_url)
spree_product.image = image if image
end
def self.current_image_url(spree_product)
spree_product.image&.attachment&.blob&.custom_metadata&.fetch("origin", nil)
end
def self.import(image_link)
url = URI.parse(image_link)
filename = File.basename(image_link)
metadata = { custom: { origin: image_link } }
Spree::Image.new.tap do |image|
PrivateAddressCheck.only_public_connections do
image.attachment.attach(io: url.open, filename:, metadata:)
end
end
rescue StandardError
# Any URL parsing or network error shouldn't impact the product import
# at all. Maybe we'll add UX for error handling later.
nil
end
end