Class: Soundcloud2000::DownloadThread

Inherits:
Object
  • Object
show all
Defined in:
lib/soundcloud2000/download_thread.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, filename) ⇒ DownloadThread

Returns a new instance of DownloadThread.



8
9
10
11
12
13
14
# File 'lib/soundcloud2000/download_thread.rb', line 8

def initialize(url, filename)
  @events = Events.new
  @url = URI.parse(url)
  @file = File.open(filename, "w")
  @progress = 0
  start!
end

Instance Attribute Details

#eventsObject (readonly)

Returns the value of attribute events.



6
7
8
# File 'lib/soundcloud2000/download_thread.rb', line 6

def events
  @events
end

#fileObject (readonly)

Returns the value of attribute file.



6
7
8
# File 'lib/soundcloud2000/download_thread.rb', line 6

def file
  @file
end

#progressObject (readonly)

Returns the value of attribute progress.



6
7
8
# File 'lib/soundcloud2000/download_thread.rb', line 6

def progress
  @progress
end

#totalObject (readonly)

Returns the value of attribute total.



6
7
8
# File 'lib/soundcloud2000/download_thread.rb', line 6

def total
  @total
end

#urlObject (readonly)

Returns the value of attribute url.



6
7
8
# File 'lib/soundcloud2000/download_thread.rb', line 6

def url
  @url
end

Instance Method Details

#log(s) ⇒ Object



16
17
18
# File 'lib/soundcloud2000/download_thread.rb', line 16

def log(s)
  Soundcloud2000::Application.logger.debug("DownloadThread #{s}")
end

#start!Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/soundcloud2000/download_thread.rb', line 20

def start!
  Thread.start do
    begin
      log :start
      Net::HTTP.get_response(url) do |res|
        log "response: #{res.code}"
        raise res.body if res.code != '200'

        @total = res.header['Content-Length'].to_i

        res.read_body do |chunk|
          @progress += chunk.size
          @file << chunk
          @file.close if @progress == @total
        end
      end
    rescue => e
      log e.message
    end
  end

  sleep 0.1 while @total.nil?
  sleep 0.1

  self
end