Class: SourceMonitor::Images::Processor

Inherits:
Object
  • Object
show all
Defined in:
lib/source_monitor/images/processor.rb

Overview

Orchestrates downloading images from an item’s HTML content, attaching them via ActiveStorage, and rewriting the HTML to use local blob URLs. Extracted from DownloadContentImagesJob for testability and reuse.

Constant Summary collapse

TRANSIENT_ERRORS =
[
  Timeout::Error, Errno::ETIMEDOUT,
  Faraday::TimeoutError, Faraday::ConnectionFailed,
  Net::OpenTimeout, Net::ReadTimeout
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(item) ⇒ Processor

Returns a new instance of Processor.



17
18
19
# File 'lib/source_monitor/images/processor.rb', line 17

def initialize(item)
  @item = item
end

Instance Method Details

#callObject



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
47
48
49
50
51
# File 'lib/source_monitor/images/processor.rb', line 21

def call
  return unless SourceMonitor.config.images.download_enabled?

  html = item.content
  return if html.blank?

  item_content = item.item_content || item.build_item_content

  # Skip if images already attached (idempotency)
  return if item_content.persisted? && item_content.images.attached?

  base_url = item.url
  rewriter = SourceMonitor::Images::ContentRewriter.new(html, base_url: base_url)
  image_urls = rewriter.image_urls
  return if image_urls.empty?

  # Save item_content first so we can attach blobs to it
  item_content.save! unless item_content.persisted?

  # Download images and build URL mapping
  url_mapping = download_images(item_content, image_urls)
  return if url_mapping.empty?

  # Rewrite HTML with Active Storage URLs
  rewritten_html = rewriter.rewrite do |original_url|
    url_mapping[original_url]
  end

  # Update the item content with rewritten HTML
  item.update!(content: rewritten_html)
end