Class: LeechtopDownloader::FileManager

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/leechtop_downloader/file_manager.rb

Overview

FileManager handles the physical saving of files using Metric/UTC standards.

Class Method Summary collapse

Class Method Details

.find_unique_filename(base, ext, dir, orig) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
# File 'lib/leechtop_downloader/file_manager.rb', line 54

def self.find_unique_filename(base, ext, dir, orig)
  counter = 1
  loop do
    name = "#{base}_#{counter}#{ext}"
    unless File.exist?(File.join(dir, name))
      puts "Warning: File '#{orig}' already exists. Saving as '#{name}'"
      return name
    end
    counter += 1
  end
end

.resolve_filename(original_filename, directory) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/leechtop_downloader/file_manager.rb', line 39

def self.resolve_filename(original_filename, directory)
  return original_filename unless File.exist?(File.join(directory, original_filename))

  ext = File.extname(original_filename)
  base = File.basename(original_filename, ext)
  find_unique_filename(base, ext, directory, original_filename)
end

.save_stream(io, filename, destination = '.') ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/leechtop_downloader/file_manager.rb', line 19

def self.save_stream(io, filename, destination = '.')
  # Enforcement of UTC and Metric standards
  FileUtils.mkdir_p(destination)
  resolved_filename = resolve_filename(filename, destination)
  filepath = File.join(destination, resolved_filename)

  bytes_written = write_stream(io, filepath)

  # Enforce UTC timestamps on the generated file
  utc_now = Time.now.utc
  File.utime(utc_now, utc_now, filepath)

  [bytes_written, resolved_filename]
end

.write_stream(io, filepath) ⇒ Object



71
72
73
74
75
76
77
78
79
80
# File 'lib/leechtop_downloader/file_manager.rb', line 71

def self.write_stream(io, filepath)
  bytes_written = 0
  File.open(filepath, 'wb') do |file|
    while (chunk = io.read(8192)) # 8 KB metric chunking
      file.write(chunk)
      bytes_written += chunk.bytesize
    end
  end
  bytes_written
end