Class: SourceMonitor::Images::Downloader

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

Defined Under Namespace

Classes: Result

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, settings: nil) ⇒ Downloader

Returns a new instance of Downloader.



13
14
15
16
# File 'lib/source_monitor/images/downloader.rb', line 13

def initialize(url, settings: nil)
  @url = url
  @settings = settings || SourceMonitor.config.images
end

Instance Attribute Details

#settingsObject (readonly)

Returns the value of attribute settings.



11
12
13
# File 'lib/source_monitor/images/downloader.rb', line 11

def settings
  @settings
end

#urlObject (readonly)

Returns the value of attribute url.



11
12
13
# File 'lib/source_monitor/images/downloader.rb', line 11

def url
  @url
end

Instance Method Details

#callObject

Downloads the image and returns a Result, or nil if download fails or the image does not meet validation criteria.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/source_monitor/images/downloader.rb', line 20

def call
  response = fetch_image
  return unless response

  content_type = response.headers["content-type"]&.split(";")&.first&.strip&.downcase
  return unless allowed_content_type?(content_type)

  body = response.body
  return unless body && body.bytesize > 0
  return if body.bytesize > settings.max_download_size

  filename = derive_filename(url, content_type)

  Result.new(
    io: StringIO.new(body),
    filename: filename,
    content_type: content_type,
    byte_size: body.bytesize
  )
rescue Faraday::Error, URI::InvalidURIError, Timeout::Error
  nil
end