Class: XiamiRadio::Downloader
- Inherits:
-
Object
- Object
- XiamiRadio::Downloader
- Defined in:
- lib/xiami_radio/downloader.rb
Instance Attribute Summary collapse
-
#file ⇒ Object
readonly
Returns the value of attribute file.
-
#progress ⇒ Object
readonly
Returns the value of attribute progress.
-
#total ⇒ Object
readonly
Returns the value of attribute total.
-
#track ⇒ Object
readonly
Returns the value of attribute track.
Class Method Summary collapse
Instance Method Summary collapse
- #filename ⇒ Object
-
#initialize(track) ⇒ Downloader
constructor
A new instance of Downloader.
- #start ⇒ Object
- #stop ⇒ Object
Constructor Details
#initialize(track) ⇒ Downloader
Returns a new instance of Downloader.
15 16 17 18 |
# File 'lib/xiami_radio/downloader.rb', line 15 def initialize(track) @track = track @uri = URI @track.location end |
Instance Attribute Details
#file ⇒ Object (readonly)
Returns the value of attribute file.
13 14 15 |
# File 'lib/xiami_radio/downloader.rb', line 13 def file @file end |
#progress ⇒ Object (readonly)
Returns the value of attribute progress.
13 14 15 |
# File 'lib/xiami_radio/downloader.rb', line 13 def progress @progress end |
#total ⇒ Object (readonly)
Returns the value of attribute total.
13 14 15 |
# File 'lib/xiami_radio/downloader.rb', line 13 def total @total end |
#track ⇒ Object (readonly)
Returns the value of attribute track.
13 14 15 |
# File 'lib/xiami_radio/downloader.rb', line 13 def track @track end |
Class Method Details
.circulator ⇒ Object
6 7 8 9 10 |
# File 'lib/xiami_radio/downloader.rb', line 6 def circulator @circulator ||= Queue.new %w(甲 乙).map(&@circulator.method(:push)) if @circulator.empty? @circulator end |
Instance Method Details
#filename ⇒ Object
20 21 22 |
# File 'lib/xiami_radio/downloader.rb', line 20 def filename File.join XiamiRadio::TMP_DIR, self.class.circulator.pop(true) end |
#start ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/xiami_radio/downloader.rb', line 28 def start @thread = Thread.start do Net::HTTP.get_response @uri do |res| if res.code == '302' @uri = URI res.header['Location'] start else @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 end sleep 0.1 until @progress.to_i > 0 end |
#stop ⇒ Object
48 49 50 51 52 |
# File 'lib/xiami_radio/downloader.rb', line 48 def stop @thread&.exit @thread = nil File.delete(@file) end |