forked from kulpae/cloudruby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsoundcloud.rb
More file actions
83 lines (74 loc) · 2.1 KB
/
soundcloud.rb
File metadata and controls
83 lines (74 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
require 'cgi'
require 'open-uri'
require 'json'
class SoundCloud
include Observable
LIMIT = 100
def initialize(client_id)
@cid = client_id
@playlist_pos = -1
end
def load_playlist(search = nil, offset = 0)
search = "" unless search && !search.empty?
if search =~ /\s*http(s)?:\/\/(www.)?soundcloud.com.*/
url = "http://api.soundcloud.com/resolve.json?url=%s&client_id=%s" % [CGI.escape(search), @cid]
else
url = "http://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"] = stream_url t
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
def shufflePlaylist
return unless @tracks.respond_to? "shuffle!"
@tracks.shuffle!
changed
notify_observers :state => :shuffle, :tracks => @tracks
end
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
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
private
def stream_url(track)
"#{track["stream_url"]}?client_id=%s" % [@cid] if track && track["stream_url"]
end
end