2021-12-22 16:03:36 +01:00
|
|
|
module DownloadManager
|
|
|
|
class ParallelDownloadQueue
|
|
|
|
DOWNLOAD_MAX_PARALLEL = ENV.fetch('DOWNLOAD_MAX_PARALLEL') { 10 }
|
|
|
|
|
|
|
|
attr_accessor :attachments,
|
|
|
|
:destination,
|
|
|
|
:on_error
|
|
|
|
|
|
|
|
def initialize(attachments, destination)
|
|
|
|
@attachments = attachments
|
|
|
|
@destination = destination
|
|
|
|
end
|
|
|
|
|
|
|
|
def download_all
|
2022-01-04 16:15:28 +01:00
|
|
|
hydra = Typhoeus::Hydra.new(max_concurrency: DOWNLOAD_MAX_PARALLEL)
|
2021-12-22 16:03:36 +01:00
|
|
|
|
2022-01-04 16:15:28 +01:00
|
|
|
attachments.map do |attachment, path|
|
|
|
|
begin
|
2022-01-06 15:42:56 +01:00
|
|
|
download_one(attachment: attachment,
|
|
|
|
path_in_download_dir: path,
|
|
|
|
http_client: hydra)
|
2022-01-04 16:15:28 +01:00
|
|
|
rescue => e
|
|
|
|
on_error.call(attachment, path, e)
|
2021-12-22 16:03:36 +01:00
|
|
|
end
|
|
|
|
end
|
2022-01-04 16:15:28 +01:00
|
|
|
hydra.run
|
2021-12-22 16:03:36 +01:00
|
|
|
end
|
|
|
|
|
2022-01-04 16:15:28 +01:00
|
|
|
# rubocop:disable Style/AutoResourceCleanup
|
|
|
|
# can't be used with typhoeus, otherwise block is closed before the request is run by hydra
|
2021-12-22 16:03:36 +01:00
|
|
|
def download_one(attachment:, path_in_download_dir:, http_client:)
|
|
|
|
attachment_path = File.join(destination, path_in_download_dir)
|
|
|
|
attachment_dir = File.dirname(attachment_path)
|
|
|
|
|
|
|
|
FileUtils.mkdir_p(attachment_dir) if !Dir.exist?(attachment_dir) # defensive, do not write in undefined dir
|
|
|
|
if attachment.is_a?(PiecesJustificativesService::FakeAttachment)
|
2022-01-04 16:15:28 +01:00
|
|
|
File.write(attachment_path, attachment.file.read, mode: 'wb')
|
2021-12-22 16:03:36 +01:00
|
|
|
else
|
2022-01-04 16:15:28 +01:00
|
|
|
request = Typhoeus::Request.new(attachment.url)
|
|
|
|
fd = File.open(attachment_path, mode: 'wb')
|
|
|
|
request.on_body do |chunk|
|
|
|
|
fd.write(chunk)
|
|
|
|
end
|
|
|
|
request.on_complete do |response|
|
|
|
|
fd.close
|
|
|
|
unless response.success?
|
2022-01-06 15:42:56 +01:00
|
|
|
File.delete(attachment_path) if File.exist?(attachment_path) # -> case of retries failed, must cleanup partialy downloaded file
|
|
|
|
on_error.call(attachment, path_in_download_dir, response.code)
|
2021-12-22 16:03:36 +01:00
|
|
|
end
|
|
|
|
end
|
2022-01-04 16:15:28 +01:00
|
|
|
http_client.queue(request)
|
2021-12-22 16:03:36 +01:00
|
|
|
end
|
|
|
|
end
|
2022-01-04 16:15:28 +01:00
|
|
|
# rubocop:enable Style/AutoResourceCleanup
|
2021-12-22 16:03:36 +01:00
|
|
|
end
|
|
|
|
end
|