mirror of
https://github.com/openfoodfoundation/openfoodnetwork
synced 2026-01-24 20:36:49 +00:00
Importer goal is to dl a file over https instead of local file
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user