Class: Spree::Themes::ScreenshotJob

Inherits:
BaseJob
  • Object
show all
Defined in:
app/jobs/spree/themes/screenshot_job.rb

Constant Summary collapse

BASE_SCREENSHOT_API_URL =
'https://shot.screenshotapi.net/v3/screenshot'.freeze
SCREENSHOT_OUTPUT =
'image'.freeze
SCREENSHOT_FILE_TYPE =
'png'.freeze

Instance Method Summary collapse

Instance Method Details

#perform(theme_id) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'app/jobs/spree/themes/screenshot_job.rb', line 13

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