class XiamiRadio::Downloader
Attributes
file[R]
track[R]
Public Class Methods
circulator()
click to toggle source
# File lib/xiami_radio/downloader.rb, line 6 def circulator @circulator ||= Queue.new %w(甲 乙).map(&@circulator.method(:push)) if @circulator.empty? @circulator end
new(track)
click to toggle source
# File lib/xiami_radio/downloader.rb, line 15 def initialize(track) @track = track end
Public Instance Methods
filename()
click to toggle source
# File lib/xiami_radio/downloader.rb, line 19 def filename File.join XiamiRadio::TMP_DIR, self.class.circulator.pop(true) end
progress()
click to toggle source
# File lib/xiami_radio/downloader.rb, line 23 def progress @progress.nil? ? 0.00 : (@progress.to_f / @total.to_f).round(2) end
start()
click to toggle source
# File lib/xiami_radio/downloader.rb, line 27 def start @thread ||= Thread.start { request URI(@track.location) } end
stop()
click to toggle source
# File lib/xiami_radio/downloader.rb, line 31 def stop @thread&.exit @thread = nil File.delete(@file) if @file end
Private Instance Methods
request(uri)
click to toggle source
# File lib/xiami_radio/downloader.rb, line 39 def request(uri) Net::HTTP.get_response uri do |res| if res.code == '302' request URI(res.header['Location']) else XiamiRadio.logger.info "#{@track.title} download start" @progress, @total = 0, res.header['Content-Length'].to_i @file = File.open(filename, 'w') res.read_body do |chunk| @file << chunk @progress += chunk.size @file.close unless @progress < @total end end end XiamiRadio.logger.info "#{@track.title} download completed" end