Class: CyberarmEngine::Cache::DownloadManager

Inherits:
Object
  • Object
show all
Defined in:
lib/cyberarm_engine/cache/download_manager.rb

Defined Under Namespace

Classes: Download

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_parallel_downloads: 4) ⇒ DownloadManager

Returns a new instance of DownloadManager.



8
9
10
11
# File 'lib/cyberarm_engine/cache/download_manager.rb', line 8

def initialize(max_parallel_downloads: 4)
  @max_parallel_downloads = max_parallel_downloads
  @downloads = []
end

Instance Attribute Details

#downloadsObject (readonly)

Returns the value of attribute downloads.



6
7
8
# File 'lib/cyberarm_engine/cache/download_manager.rb', line 6

def downloads
  @downloads
end

Instance Method Details

#active_downloadsObject



38
39
40
# File 'lib/cyberarm_engine/cache/download_manager.rb', line 38

def active_downloads
  @downloads.select { |d| %i[pending downloading].include?(d.status) }
end

#download(url:, save_as: nil, &callback) ⇒ Object



13
14
15
16
17
18
# File 'lib/cyberarm_engine/cache/download_manager.rb', line 13

def download(url:, save_as: nil, &callback)
  uri = URI(url)
  save_as ||= "filename_path" # TODO: if no save_as path is provided, then get one from the Cache controller

  @downloads << Download.new(uri: uri, save_as: save_as, callback: callback)
end

#progressObject



28
29
30
31
32
33
34
35
36
# File 'lib/cyberarm_engine/cache/download_manager.rb', line 28

def progress
  remaining_bytes = @downloads.map { |d| d.remaining_bytes }.sum
  total_bytes = @downloads.map { |d| d.total_bytes }.sum

  v = 1.0 - (remaining_bytes.to_f / total_bytes)
  return 0.0 if v.nan?

  v
end

#pruneObject



51
52
53
# File 'lib/cyberarm_engine/cache/download_manager.rb', line 51

def prune
  @downloads.delete_if { |d| d.status == :finished || d.status == :failed }
end

#statusObject



20
21
22
23
24
25
26
# File 'lib/cyberarm_engine/cache/download_manager.rb', line 20

def status
  if active_downloads > 0
    :busy
  else
    :idle
  end
end

#updateObject



42
43
44
45
46
47
48
49
# File 'lib/cyberarm_engine/cache/download_manager.rb', line 42

def update
  @downloads.each do |download|
    if download.status == :pending && active_downloads.size <= @max_parallel_downloads
      download.status = :downloading
      Thread.start { download.download }
    end
  end
end