Class: SoundCloud

Inherits:
Object
  • Object
show all
Includes:
Observable
Defined in:
lib/soundcloud.rb

Constant Summary collapse

LIMIT =
100

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client_id, params = {}) ⇒ SoundCloud

Returns a new instance of SoundCloud.



16
17
18
19
20
21
22
23
# File 'lib/soundcloud.rb', line 16

def initialize client_id, params = {}
  params.each { |key, value| send "#{key}=", value }
  @cid = client_id
  @playlist_pos = -1
  @download_queue = []
  @dthread = Thread.new do downloader end
  @dthread.run
end

Instance Attribute Details

#loggerObject

Returns the value of attribute logger.



14
15
16
# File 'lib/soundcloud.rb', line 14

def logger
  @logger
end

Instance Method Details

#download(target_dir) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/soundcloud.rb', line 89

def download(target_dir)
  return @error unless @tracks
  return if @tracks.empty?
  if @tracks.is_a? Hash
    t = @tracks
  else 
    t = @tracks[@playlist_pos]
  end
  unless t["download"].nil? || t["download"].size == 0
    filename = "#{t["permalink"]}.#{t["original_format"]}"
    path = File.join(target_dir, filename)
    pair = [path, t['download']]
    @logger.debug {"download queued: #{pair}"}
    @download_queue << pair unless @download_queue.include? pair

    changed
    notify_observers :state => :download, :count => @download_queue.size
  else
    changed
    notify_observers :state => :status, :type => "Download", :value => "Not granted by content owner"
  end
end

#downloaderObject

download thread



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/soundcloud.rb', line 113

def downloader
  loop do
    while d = @download_queue.shift
      path = d[0]
      uri = d[1]
      size = @download_queue.size
      changed
      notify_observers :state => :download, :name => path, :count => size
      begin
        path = File.expand_path path
        File.open(path, "wb") do |file|
          cl = HTTPClient.new
          cl.redirect_uri_callback = ->(uri, res) {
            res.header['location'][0]
          }
          cl.get_content(uri) do |chunk|
            file.write(chunk)
          end
        end
      rescue Exception => e
        @logger.error {"Download error: #{e}"}
        changed
        notify_observers :state => :error, :error => e
      end
    end
    sleep 5
  end
rescue => e
  changed
  @logger.error {"Downloader thread: #{e}"}
  notify_observers :state => "error", :error => e
end

#load_playlist(search = nil, offset = 0) ⇒ Object



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
50
# File 'lib/soundcloud.rb', line 25

def load_playlist(search = nil, offset = 0)
  search = "" unless search && !search.empty?
  if search =~ /\s*http(s)?:\/\/(www.)?soundcloud.com.*/
    url = "https://api.soundcloud.com/resolve.json?url=%s&client_id=%s" % [CGI.escape(search), @cid]
  else
    url = "https://api.soundcloud.com/tracks.json?client_id=%s&filter=streamable&limit=%d&offset=%d&q=%s" \
      % [@cid, LIMIT, offset, CGI.escape(search)]
  end
  c = open(url) do |io|
    io.readlines
  end.join
  @tracks = JSON.parse c
  @tracks = [@tracks] if @tracks.is_a? Hash
  @tracks.map! do |t|
    t["mpg123url"] = client_url t['stream_url']
    t["download"] = client_url t['download_url']
    t["duration"] = t["duration"].nil? ? 0 : t["duration"].to_i/1000
    t["bpm"] = t["bpm"].nil? ? 0 : t["bpm"].to_i
    t[:error] = "Not streamable" if t["stream_url"].nil?
    t
  end
  changed
  notify_observers :state =>:load, :tracks => @tracks
  rescue => e
    @error = {:error => e}
end

#nextTrackObject



59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/soundcloud.rb', line 59

def nextTrack
  return @error unless @tracks
  return if @tracks.empty? || @tracks.nil?
  if @tracks.is_a? Hash
    t = @tracks
  else 
    @playlist_pos += 1
    @playlist_pos -= @tracks.size if @playlist_pos >= @tracks.size
    t = @tracks[@playlist_pos]
    changed
    notify_observers :state => :next, :position => @playlist_pos
  end
  t
end

#prevTrackObject



74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/soundcloud.rb', line 74

def prevTrack
  return @error unless @tracks
  return if @tracks.empty?
  if @tracks.is_a? Hash
    t = @tracks
  else 
    @playlist_pos -= 1
    @playlist_pos += @tracks.size if @playlist_pos < 0
    t = @tracks[@playlist_pos]
    changed
    notify_observers :state => :previous, :position => @playlist_pos
  end
  t
end

#shufflePlaylistObject



52
53
54
55
56
57
# File 'lib/soundcloud.rb', line 52

def shufflePlaylist
  return unless @tracks.respond_to? "shuffle!"
  @tracks.shuffle!
  changed
  notify_observers :state => :shuffle, :tracks => @tracks
end