Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix/re implement screenshot saving (#12589)
Damian Legawiec38884d9c9f58
diff --git a/admin/app/controllers/spree/admin/themes_controller.rb b/admin/app/controllers/spree/admin/themes_controller.rbindex e952b4f3bf..5caf87d4b3 100644--- a/admin/app/controllers/spree/admin/themes_controller.rb+++ b/admin/app/controllers/spree/admin/themes_controller.rb@@ -68,7 +68,7 @@ module Spreeenddef collection- super.without_previews.order(default: :desc)+ super.without_previews.order(default: :desc).includes(screenshot_attachment: :blob)endendenddiff --git a/admin/app/views/spree/admin/dashboard/_store_preview.html.erb b/admin/app/views/spree/admin/dashboard/_store_preview.html.erbindex 3b6254ee62..8b59a47964 100644--- a/admin/app/views/spree/admin/dashboard/_store_preview.html.erb+++ b/admin/app/views/spree/admin/dashboard/_store_preview.html.erb@@ -8,12 +8,7 @@</button></div>- <%= image_tag(- current_store.default_theme.screenshot_url,- class: 'w-100 bg-light rounded',- loading: :lazy,- height: 172- ) %>+ <%= render 'spree/admin/themes/theme_preview_image', theme: current_store.default_theme, height: 172, width: 330 %><% end %><div class="card-body px-2 pt-0 pb-2">diff --git a/admin/app/views/spree/admin/dashboard/getting_started.html.erb b/admin/app/views/spree/admin/dashboard/getting_started.html.erbindex c3a160507d..53c61f9c53 100644--- a/admin/app/views/spree/admin/dashboard/getting_started.html.erb+++ b/admin/app/views/spree/admin/dashboard/getting_started.html.erb@@ -18,6 +18,5 @@<% end %></div><div class="col-lg-4">-</div></div>diff --git a/admin/app/views/spree/admin/themes/_theme.html.erb b/admin/app/views/spree/admin/themes/_theme.html.erbindex d7718b9cf8..22e0707abe 100644--- a/admin/app/views/spree/admin/themes/_theme.html.erb+++ b/admin/app/views/spree/admin/themes/_theme.html.erb@@ -1,21 +1,15 @@<tr id="<%= spree_dom_id theme %>"><td class="w-70 p-0"><%= link_to theme.ready? ? spree.edit_admin_theme_path(theme) : '#', class: 'd-flex align-items-top p-3' do %>- <% if theme.screenshot_url.present? %>- <%= image_tag(- theme.screenshot_url,- class: 'img-thumbnail',- style: 'width: 120px; height: 72px',- loading: :lazy- ) %>- <% else %>- <%= render 'spree/admin/shared/no_image', width: 120, height: 72 %>- <% end %>+ <%= render 'spree/admin/themes/theme_preview_image', theme: theme %><div class="d-flex flex-column ml-3"><strong><%= theme.name %></strong><p class="mb-0 mt-1">- <span class="text-muted">Updated: <%= local_time_ago(theme.updated_at, class: 'with-tip') %></span>+ <span class="text-muted">+ <%= Spree.t(:updated) %>:+ <%= local_time_ago(theme.updated_at, class: 'with-tip') %>+ </span></p></div><% end %>@@ -41,14 +35,14 @@<td class="w-20"><% if theme.ready? %><div class="d-flex justify-content-end w-100">- <%= link_to Spree.t(:publish), publish_admin_theme_path(theme), class: 'btn btn-sm btn-light mr-2', data: { turbo_method: :put } unless theme.default? %>+ <%= link_to Spree.t('actions.publish'), publish_admin_theme_path(theme), class: 'btn btn-sm btn-light mr-2', data: { turbo_method: :put } unless theme.default? %><div class="dropdown"><button class="btn btn-sm btn-light h-100" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><%= icon('dots', class: 'mr-0') %></button><div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton"><%= link_to_edit theme, class: 'dropdown-item' %>- <%= link_to_with_icon 'copy', Spree.t(:duplicate), clone_admin_theme_path(theme), class: 'dropdown-item', data: { turbo_method: :post } %>+ <%= link_to_with_icon 'copy', Spree.t(:clone), spree.clone_admin_theme_path(theme), class: 'dropdown-item', data: { turbo_method: :post } %><% unless theme.default? %><%= link_to_delete(theme, icon: 'trash', class: 'dropdown-item btn-danger shadow-none') if can?(:delete, theme) %><% end %>diff --git a/admin/app/views/spree/admin/themes/_theme_preview_image.html.erb b/admin/app/views/spree/admin/themes/_theme_preview_image.html.erbnew file mode 100644index 0000000000..a360b7d242--- /dev/null+++ b/admin/app/views/spree/admin/themes/_theme_preview_image.html.erb@@ -0,0 +1,24 @@+<% width ||= 120 %>+<% height ||= 72 %>++<% if theme.screenshot.attached? && theme.screenshot.variable? %>+ <%= image_tag(+ main_app.cdn_image_url(+ theme.screenshot.variant(+ spree_image_variant_options(resize_to_fill: [width * 2, height * 2])+ )+ ),+ class: 'img-thumbnail',+ style: "width: #{width}px; height: #{height}px",+ loading: :lazy+ ) %>+<% elsif theme.class.preview_image_url.present? %>+ <%= image_tag(+ theme.class.preview_image_url,+ class: 'img-thumbnail',+ style: "width: #{width}px; height: #{height}px",+ loading: :lazy+) %>+<% else %>+ <%= render 'spree/admin/shared/no_image', width: width, height: height %>+<% end %>\ No newline at end of filediff --git a/core/app/jobs/spree/themes/screenshot_job.rb b/core/app/jobs/spree/themes/screenshot_job.rbnew file mode 100644index 0000000000..558f26d9ed--- /dev/null+++ b/core/app/jobs/spree/themes/screenshot_job.rb@@ -0,0 +1,81 @@+require 'uri'+require 'net/http'++module Spree+ module Themes+ class ScreenshotJob < Spree::BaseJob+ queue_as Spree.queues.themes++ BASE_SCREENSHOT_API_URL = 'https://shot.screenshotapi.net/v3/screenshot'.freeze+ SCREENSHOT_OUTPUT = 'image'.freeze+ SCREENSHOT_FILE_TYPE = 'png'.freeze++ def perform(theme_id)+ theme = Spree::Theme.find(theme_id)++ Rails.logger.warn('Screenshot API token is missing') and return if screenshot_api_token.blank?++ return if theme.screenshot.attached?++ url = URI.encode_www_form_component("#{theme.store.url_or_custom_domain}?theme_id=#{theme_id}")+ query_params = {+ token: screenshot_api_token,+ url: url,+ output: SCREENSHOT_OUTPUT,+ file_type: SCREENSHOT_FILE_TYPE,+ retina: true,+ enable_caching: true+ }+ query = "#{BASE_SCREENSHOT_API_URL}?#{query_params.to_query}"++ # Send a GET request to the API+ uri = URI.parse(query)+ response = Net::HTTP.get_response(uri)++ case response.code+ when '301', '302'+ redirect_uri = response['location']+ redirect_uri = URI.parse(redirect_uri)+ response = Net::HTTP.get_response(redirect_uri)+ save_screenshot(theme, response)+ when '200'+ save_screenshot(theme, response)+ else+ Rails.error.report('Screenshot API returned non-200 status code')+ end+ end++ private++ def screenshot_api_token+ @screenshot_api_token ||= Spree.screenshot_api_token+ end++ def save_screenshot(theme, response)+ temp_file_path = "theme-screenshot-#{theme.id}.png"++ # Create a temporary file+ File.open(temp_file_path, "wb") do |file|+ file.write(response.body)+ end++ # Open the file for reading to attach it+ file = File.open(temp_file_path, "rb")++ # Attach the file+ theme.screenshot.attach(+ io: file,+ filename: "theme-screenshot-#{theme.id}.#{SCREENSHOT_FILE_TYPE}",+ content_type: "image/#{SCREENSHOT_FILE_TYPE}"+ )+ theme.save!++ # Close the file before attempting to delete it+ file.close++ # Remove the temporary file+ File.delete(temp_file_path) if File.exist?(temp_file_path)+ end+ end+ end+enddiff --git a/core/app/models/spree/theme.rb b/core/app/models/spree/theme.rbindex 8db20ad699..db36409b29 100644--- a/core/app/models/spree/theme.rb+++ b/core/app/models/spree/theme.rb@@ -24,6 +24,11 @@ module Spreehas_many :layout_sections, class_name: 'Spree::PageSection', dependent: :destroy, as: :pageablealias sections layout_sections+ #+ # Attachments+ #+ has_one_attached :screenshot, service: Spree.public_storage_service_name+### Callbacks@@ -38,15 +43,6 @@ module Spree#attribute :duplicating, :boolean, default: false- def screenshot_url- @screenshot_url ||= if ENV['SCREENSHOT_API_TOKEN'].present?- "https://shot.screenshotapi.net/v3/screenshot?token=#{ENV['SCREENSHOT_API_TOKEN']}&url=#{store.url_or_custom_domain}&fresh=true&output=image&file_type=png&no_cookie_banners=true&retina=true&enable_caching=true&wait_for_event=load&thumbnail_width=700"- else- # default screenshot- "https://s3.eu-central-2.wasabisys.com/w.storage.screenshotapi.net/demo_spreecommerce_org_299a49137b25.png"- end- end-## Class methods#@@ -151,6 +147,8 @@ module Spree# destroy the old theme with their other previews, etc.store.themes.find(old_theme.id).destroy++ take_screenshot # update the screenshotendend@@ -171,6 +169,14 @@ module Spreesave!end+ def take_screenshot+ return if Spree.screenshot_api_token.blank?+ return if preview? # we don't want to take screenshots of previews, they aren't surfaced in the UI+ return if screenshot.attached?++ Spree::Themes::ScreenshotJob.perform_later(id)+ end+protecteddef set_namediff --git a/core/app/models/spree/themes/default.rb b/core/app/models/spree/themes/default.rbindex 909db24533..830fde23ab 100644--- a/core/app/models/spree/themes/default.rb+++ b/core/app/models/spree/themes/default.rb@@ -4,7 +4,8 @@ module Spreedef self.metadata{authors: ['Spree Commerce'],- license: 'MIT'+ license: 'MIT',+ preview_image_url: 'https://s3.eu-central-2.wasabisys.com/w.storage.screenshotapi.net/demo_spreecommerce_org_299a49137b25.png'}enddiff --git a/core/config/locales/en.yml b/core/config/locales/en.ymlindex 2fc6071658..36d90edfdf 100644--- a/core/config/locales/en.yml+++ b/core/config/locales/en.yml@@ -1625,7 +1625,6 @@ en:prototypes: Prototypesprovider: Providerprovider_settings_warning: If you are changing the provider type, you must save first before you can edit the provider settings- publish: Publishpublished_at: Published atpurchased_quantity: Purchased Quantityqty: Qtydiff --git a/core/lib/generators/spree/install/templates/config/initializers/spree.rb b/core/lib/generators/spree/install/templates/config/initializers/spree.rbindex 7b6bd5861c..984fe4935b 100644--- a/core/lib/generators/spree/install/templates/config/initializers/spree.rb+++ b/core/lib/generators/spree/install/templates/config/initializers/spree.rb@@ -35,6 +35,9 @@ end# Spree.public_storage_service_name = :amazon_private # private assets, such as invoices, etc# end+# Enable theme preview screenshots in admin dashboard+# Spree.screenshot_api_token = <Your Screenshot API token obtained from https://screenshotapi.net/>+# Configure Spree Dependencies## Note: If a dependency is set here it will NOT be stored within the cache & database upon initialization.diff --git a/core/lib/spree/core.rb b/core/lib/spree/core.rbindex d79fb257cf..8d1c714aad 100644--- a/core/lib/spree/core.rb+++ b/core/lib/spree/core.rb@@ -40,7 +40,7 @@ module Spreemattr_accessor :base_class, :user_class, :admin_user_class,:private_storage_service_name, :public_storage_service_name,:cdn_host, :root_domain, :searcher_class, :queues,- :google_places_api_key+ :google_places_api_key, :screenshot_api_tokendef self.base_class(constantize: true)@@base_class ||= 'Spree::Base'@@ -122,6 +122,10 @@ module Spree@@google_places_api_keyend+ def self.screenshot_api_token+ @@screenshot_api_token+ end+def self.always_use_translations?Spree::Config.always_use_translationsenddiff --git a/core/spec/jobs/spree/themes/screenshot_job_spec.rb b/core/spec/jobs/spree/themes/screenshot_job_spec.rbnew file mode 100644index 0000000000..745d0485d8--- /dev/null+++ b/core/spec/jobs/spree/themes/screenshot_job_spec.rb@@ -0,0 +1,41 @@+require 'spec_helper'++RSpec.describe Spree::Themes::ScreenshotJob do+ subject { described_class.perform_now(theme.id) }++ let(:store) { @default_store }+ let(:theme) { create(:theme, store: store) }++ context 'when screenshot_api_token is not set' do+ before do+ Spree.screenshot_api_token = nil+ end++ it 'does not take a screenshot' do+ expect(Net::HTTP).not_to receive(:get_response)+ end+ end++ context 'when screenshot_api_token is set' do+ let(:file) { File.new(Spree::Core::Engine.root + 'spec/fixtures/thinking-cat.jpg') }++ before do+ Spree.screenshot_api_token = 'test_token'++ allow_any_instance_of(Spree::Store).to receive(:url_or_custom_domain).and_return('demo.spreecommerce.org')+ allow(Net::HTTP).to receive(:get_response).and_return(+ instance_double(Net::HTTPResponse, code: '200', body: file.read)+ )+ end++ it 'takes a screenshot' do+ subject++ expect(Net::HTTP).to have_received(:get_response).with(URI("https://shot.screenshotapi.net/v3/screenshot?enable_caching=true&file_type=png&output=image&retina=true&token=test_token&url=demo.spreecommerce.org%253Ftheme_id%253D#{theme.id}"))+ theme.reload++ expect(theme.screenshot.attached?).to be_truthy+ expect(theme.screenshot.filename.to_s).to eq("theme-screenshot-#{theme.id}.png")+ end+ end+enddiff --git a/core/spec/models/spree/theme_spec.rb b/core/spec/models/spree/theme_spec.rbindex 52a28f0e31..27a91232c2 100644--- a/core/spec/models/spree/theme_spec.rb+++ b/core/spec/models/spree/theme_spec.rb@@ -65,5 +65,29 @@ describe Spree::Theme, type: :model doexpect(theme_preview.page_ids).to contain_exactly(*page_ids)end++ context 'when screenshot_api_token is not set' do+ before do+ Spree.screenshot_api_token = nil+ end++ it 'does not take a screenshot' do+ expect { theme.take_screenshot }.not_to have_enqueued_job(Spree::Themes::ScreenshotJob)+ end+ end++ context 'when screenshot_api_token is set' do+ before do+ Spree.screenshot_api_token = 'test_token'+ end++ after do+ Spree.screenshot_api_token = nil+ end++ it 'takes a screenshot' do+ expect { theme.take_screenshot }.to have_enqueued_job(Spree::Themes::ScreenshotJob)+ end+ endendend