diff --git a/app/services/image_importer.rb b/app/services/image_importer.rb index 40fd7680d4..9cef10548a 100644 --- a/app/services/image_importer.rb +++ b/app/services/image_importer.rb @@ -1,15 +1,23 @@ # frozen_string_literal: true +require "private_address_check" +require "private_address_check/tcpsocket_ext" + class ImageImporter def import(url, product) valid_url = URI.parse(url) - file = File.open(valid_url.to_s) filename = File.basename(valid_url.path) + metadata = { custom: { origin: url } } - Spree::Image.create( - attachment: { io: file, filename: }, - viewable_id: product.id, - viewable_type: Spree::Product, - ) + image = Spree::Image.create do |img| + PrivateAddressCheck.only_public_connections do + img.attachment.attach(io: valid_url.open, filename:, metadata:) + end + end + product.image = image if image + 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 diff --git a/spec/services/image_importer_spec.rb b/spec/services/image_importer_spec.rb index df526750ca..67fa4793d2 100644 --- a/spec/services/image_importer_spec.rb +++ b/spec/services/image_importer_spec.rb @@ -3,19 +3,19 @@ require 'spec_helper' RSpec.describe ImageImporter do - let(:url) { Rails.root.join("spec/fixtures/files/logo.png").to_s } + let(:ofn_url) { "https://s3.amazonaws.com/ofn_production/eofop2en1y6tu9fr1x9b0wzwgs5r" } let(:product) { create(:product) } describe "#import" do - it "downloads and attaches to the product" do + it "downloads from the Internet", :vcr do expect { - subject.import(url, product) + subject.import(ofn_url, product) }.to change { Spree::Image.count }.by(1) expect(product.image).not_to be_nil - expect(product.reload.image.attachment_blob.byte_size).to eq 6274 + expect(product.reload.image.attachment_blob.byte_size).to eq 12_926 end end end