Class: XiamiRadio::Downloader

Inherits:
Object
  • Object
show all
Defined in:
lib/xiami_radio/downloader.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

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

#fileObject (readonly)

Returns the value of attribute file.



13
14
15
# File 'lib/xiami_radio/downloader.rb', line 13

def file
  @file
end

#progressObject (readonly)

Returns the value of attribute progress.



13
14
15
# File 'lib/xiami_radio/downloader.rb', line 13

def progress
  @progress
end

#totalObject (readonly)

Returns the value of attribute total.



13
14
15
# File 'lib/xiami_radio/downloader.rb', line 13

def total
  @total
end

#trackObject (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

.circulatorObject



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

#filenameObject



20
21
22
# File 'lib/xiami_radio/downloader.rb', line 20

def filename
  File.join XiamiRadio::TMP_DIR, self.class.circulator.pop(true)
end

#startObject



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

#stopObject



48
49
50
51
52
# File 'lib/xiami_radio/downloader.rb', line 48

def stop
  @thread&.exit
  @thread = nil
  File.delete(@file)
end