Class: Soundcloud9000::DownloadThread

Inherits:
Object
  • Object
show all
Defined in:
lib/soundcloud9000/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/soundcloud9000/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/soundcloud9000/download_thread.rb', line 6

def events
  @events
end

#fileObject (readonly)

Returns the value of attribute file.



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

def file
  @file
end

#progressObject (readonly)

Returns the value of attribute progress.



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

def progress
  @progress
end

#totalObject (readonly)

Returns the value of attribute total.



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

def total
  @total
end

#urlObject (readonly)

Returns the value of attribute url.



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

def url
  @url
end

Instance Method Details

#log(s) ⇒ Object



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

def log(s)
  Soundcloud9000::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
46
47
48
49
# File 'lib/soundcloud9000/download_thread.rb', line 20

def start!
  Thread.start do
    begin
      log :start

      http = Net::HTTP.new(url.host, url.port)
      http.use_ssl = true

      http.request(Net::HTTP::Get.new(url.request_uri)) 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 StandardError => e
      log e.message
    end
  end

  sleep 0.1 while @total.nil?
  sleep 0.1

  self
end