052028f1 |
1 | import socket, hmac, urllib, urllib2, pprint, md5, re, sha, time, random, os, pickle, uuid, tempfile, pprint |
1413d357 |
2 | |
44dcc6f4 |
3 | SESSION_EXPIRY = 518400 # 6 days in seconds |
4 | |
1413d357 |
5 | # GrooveAPI constants |
6842a53b |
6 | THUMB_URL = 'http://beta.grooveshark.com/static/amazonart/m' |
1413d357 |
7 | SONG_LIMIT = 25 |
8 | ALBUM_LIMIT = 15 |
9 | ARTIST_LIMIT = 15 |
7ce01be6 |
10 | SONG_SUFFIX = '.mp3' |
1413d357 |
11 | |
12 | # GrooveSong constants |
13 | DOMAIN = "grooveshark.com" |
14 | HOME_URL = "http://listen." + DOMAIN |
1413d357 |
15 | API_URL = "http://cowbell." + DOMAIN + "/more.php" |
16 | SERVICE_URL = "http://cowbell." + DOMAIN + "/service.php" |
44dcc6f4 |
17 | TOKEN_URL = "http://cowbell." + DOMAIN + "/more.php" |
1413d357 |
18 | |
44dcc6f4 |
19 | CLIENT_NAME = "gslite" |
20 | CLIENT_VERSION = "20101012.37" |
1413d357 |
21 | HEADERS = {"Content-Type": "application/json", |
22 | "User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 (.NET CLR 3.5.30729)", |
23 | "Referer": "http://listen.grooveshark.com/main.swf?cowbell=fe87233106a6cef919a1294fb2c3c05f"} |
24 | |
44dcc6f4 |
25 | RE_SESSION = re.compile('"sessionID":"\s*?([A-z0-9]+)"') |
1413d357 |
26 | RANDOM_CHARS = "1234567890abcdef" |
27 | |
28 | # Get a song |
29 | class GrooveSong: |
30 | |
7ce01be6 |
31 | def __init__(self): |
1413d357 |
32 | |
33 | import simplejson |
34 | self.simplejson = simplejson |
7ce01be6 |
35 | |
36 | self.cacheDir = os.path.join(tempfile.gettempdir(), 'groovesong') |
44dcc6f4 |
37 | self._lastSessionTime = 0 |
1413d357 |
38 | self.uuid = self._getUUID() |
44dcc6f4 |
39 | |
40 | self._getSavedSession() |
41 | # session ids last 1 week |
42 | if self.sessionID == '' or time.time() - self._lastSessionTime >= SESSION_EXPIRY: |
43 | self.sessionID = self._getSession(HOME_URL) |
44 | if self.sessionID == '': |
45 | raise StandardError('Failed to get session id') |
46 | else: |
47 | print "New GrooveSong session id: " + self.sessionID |
48 | self._setSavedSession() |
1413d357 |
49 | |
50 | # The actual call to the API |
51 | def _callRemote(self, method, params, type="default"): |
52 | postData = { |
53 | "header": { |
54 | "client": CLIENT_NAME, |
55 | "clientRevision": CLIENT_VERSION, |
56 | "uuid": self.uuid, |
57 | "session": self.sessionID}, |
58 | "country": {"IPR":"1021", "ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"}, |
59 | "privacy": 1, |
60 | "parameters": params, |
61 | "method": method} |
62 | |
63 | token = self._getMethodToken(method) |
64 | if token == None: |
65 | raise StandardError("Cannot get token") |
66 | |
67 | postData["header"]["token"] = token |
68 | if type == "service": |
69 | url = SERVICE_URL + "?" + method |
70 | else: |
71 | url = API_URL + "?" + method |
72 | |
73 | postData = self.simplejson.dumps(postData) |
74 | print "GrooveSong URL: " + url |
75 | request = urllib2.Request(url, postData, HEADERS) |
76 | |
77 | response = urllib2.urlopen(request).read() |
78 | try: |
79 | response = self.simplejson.loads(response) |
80 | print "GrooveSong Response..." |
81 | pprint.pprint(response) |
82 | except: |
83 | raise StandardError("API error: " + response) |
84 | try: |
85 | response["fault"] |
86 | except KeyError: |
87 | return response |
88 | else: |
89 | raise StandardError("API error: " + response["fault"]["message"]) |
90 | |
91 | # Generate a random uuid |
92 | def _getUUID(self): |
93 | return str(uuid.uuid4()) |
94 | |
95 | # Make a token ready for a request header |
96 | def _getMethodToken(self, method): |
7ce01be6 |
97 | self._token = self._getCommunicationToken() |
98 | if self._token == None: |
99 | return None |
1413d357 |
100 | |
101 | randomChars = "" |
102 | while 6 > len(randomChars): |
103 | randomChars = randomChars + random.choice(RANDOM_CHARS) |
104 | |
7ce01be6 |
105 | token = sha.new(method + ":" + self._token + ":quitStealinMahShit:" + randomChars).hexdigest() |
106 | |
1413d357 |
107 | return randomChars + token |
108 | |
109 | # Generate a communication token |
110 | def _getCommunicationToken(self): |
111 | params = {"secretKey": self._getSecretKey(self.sessionID)} |
112 | postData = { |
113 | "header": { |
114 | "client": CLIENT_NAME, |
115 | "clientRevision": CLIENT_VERSION, |
116 | "uuid": self.uuid, |
117 | "session": self.sessionID}, |
118 | "country": {"IPR":"1021", "ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"}, |
119 | "privacy": 1, |
120 | "parameters": params, |
121 | "method": "getCommunicationToken"} |
122 | |
123 | postData = self.simplejson.dumps(postData) |
124 | request = urllib2.Request(TOKEN_URL, postData, HEADERS) |
125 | response = urllib2.urlopen(request).read() |
126 | try: |
127 | response = self.simplejson.loads(response) |
128 | except: |
129 | raise StandardError("API error: " + response) |
130 | try: |
131 | response["fault"] |
132 | except KeyError: |
133 | return response["result"] |
134 | else: |
135 | return None |
136 | |
137 | # Generate a secret key from a sessionID |
138 | def _getSecretKey(self, sessionID): |
7ce01be6 |
139 | return md5.new(sessionID).hexdigest() |
1413d357 |
140 | |
141 | # Get a session id from some HTML |
142 | def _getSession(self, html): |
143 | html = urllib2.urlopen(HOME_URL).read() |
144 | session = RE_SESSION.search(html) |
145 | if session: |
44dcc6f4 |
146 | self._lastSessionTime = time.time() |
1413d357 |
147 | return session.group(1) |
148 | else: |
149 | return None |
44dcc6f4 |
150 | |
151 | def _getSavedSession(self): |
152 | path = os.path.join(self.cacheDir, 'session.dmp') |
153 | try: |
154 | f = open(path, 'rb') |
155 | session = pickle.load(f) |
156 | self.sessionID = session['sessionID'] |
157 | self._lastSessionTime = session['lastSessionTime'] |
44dcc6f4 |
158 | f.close() |
159 | except: |
160 | self.sessionID = '' |
161 | self._lastSessionTime = 0 |
44dcc6f4 |
162 | pass |
163 | |
164 | def _setSavedSession(self): |
165 | try: |
166 | # Create the 'data' directory if it doesn't exist. |
167 | if not os.path.exists(self.cacheDir): |
168 | os.makedirs(self.cacheDir) |
169 | path = os.path.join(self.cacheDir, 'session.dmp') |
170 | f = open(path, 'wb') |
7ce01be6 |
171 | session = {'sessionID' : self.sessionID, 'lastSessionTime' : self._lastSessionTime} |
44dcc6f4 |
172 | pickle.dump(session, f, protocol=pickle.HIGHEST_PROTOCOL) |
173 | f.close() |
174 | except: |
175 | print "An error occurred during save session" |
176 | pass |
1413d357 |
177 | |
178 | # Gets a stream key and host to get song content |
179 | def _getStreamDetails(self, songID): |
180 | params = { |
181 | "songID": songID, |
182 | "prefetch": False, |
183 | "mobile": False, |
184 | "country": {"IPR":"1021","ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"} |
185 | } |
186 | response = self._callRemote("getStreamKeyFromSongIDEx", params) |
7ce01be6 |
187 | try: |
188 | self._lastStreamKey = response["result"]["streamKey"] |
189 | self._lastStreamServer = response["result"]["ip"] |
190 | self._lastStreamServerID = response["result"]["streamServerID"] |
191 | return True |
192 | except: |
193 | return False |
1413d357 |
194 | |
195 | # Tells Grooveshark you have downloaded a song |
196 | def _markSongDownloaded(self, songID): |
197 | params = { |
198 | "streamKey": self._lastStreamKey, |
199 | "streamServerID": self._lastStreamServerID, |
200 | "songID": songID} |
201 | self._callRemote("markSongDownloaded", params) |
202 | |
cbb0985e |
203 | # Get the song URL |
1413d357 |
204 | def getSongURL(self, songID): |
cbb0985e |
205 | if self._getStreamDetails(songID) == True: |
206 | postData = {"streamKey": self._lastStreamKey} |
207 | postData = urllib.urlencode(postData) |
208 | return "http://" + self._lastStreamServer + "/stream.php?" + str(postData) |
209 | else: |
210 | return '' |
1413d357 |
211 | |
052028f1 |
212 | class GrooveAPIv1: |
213 | |
214 | def __init__(self, sessionID = 0): |
215 | import simplejson |
216 | self.simplejson = simplejson |
217 | timeout = 40 |
218 | socket.setdefaulttimeout(timeout) |
219 | self.loggedIn = 0 |
220 | self.userId = 0 |
221 | self.sessionID = sessionID |
222 | |
223 | def callRemote(self, method, params={}): |
224 | data = {'header': {'sessionID': self.sessionID}, 'method': method, 'parameters': params} |
225 | data = self.simplejson.dumps(data) |
226 | req = urllib2.Request("http://api.grooveshark.com/ws/1.0/?json") |
227 | req.add_header('Host', 'api.grooveshark.com') |
228 | req.add_header('Content-type', 'text/json') |
229 | req.add_header('Content-length', str(len(data))) |
230 | req.add_data(data) |
231 | response = urllib2.urlopen(req) |
232 | result = response.read() |
233 | response.close() |
234 | try: |
235 | result = self.simplejson.loads(result) |
236 | if 'fault' in result: |
237 | if result['fault']['code'] == 8: #Session ID has expired. Get a new and try again if possible. |
238 | print 'GrooveShark: SessionID expired' |
239 | return [] |
240 | return result |
241 | except: |
242 | return [] |
243 | |
244 | def login(self, username, password): |
245 | if self.loggedIn == 1: |
246 | return self.userId |
247 | token = md5.new(username.lower() + md5.new(password).hexdigest()).hexdigest() |
248 | result = self.callRemote("session.loginExt", {"username": username, "token": token}) |
249 | if 'result' in result: |
250 | if 'userID' in result['result']: |
251 | self.loggedIn = 1 |
252 | self.userId = result['result']['userID'] |
253 | return result['result']['userID'] |
254 | else: |
255 | return 0 |
256 | |
257 | def unfavorite(self, songID): |
258 | return self.callRemote("song.unfavorite", {"songID": songID}) |
259 | |
260 | def playlistCreate(self, name, about): |
261 | if self.loggedIn == 1: |
262 | result = self.callRemote("playlist.create", {"name": name, "about": about}) |
263 | if 'result' in result: |
264 | return result['result']['playlistID'] |
265 | else: |
266 | return 0 |
267 | else: |
268 | return 0 |
269 | |
270 | def playlistCreateUnique(self, name, songIds): |
271 | if self.loggedIn == 1: |
272 | result = self.callRemote("playlist.createunique", {"name": name, "songIDs": songIds}) |
273 | if 'result' in result: |
274 | return result['result']['playlistID'] |
275 | else: |
276 | return 0 |
277 | else: |
278 | return 0 |
279 | |
052028f1 |
280 | def playlistDelete(self, playlistId): |
281 | if self.loggedIn == 1: |
282 | result = self.callRemote("playlist.delete", {"playlistID": playlistId}) |
283 | if 'fault' in result: |
284 | return 0 |
285 | else: |
286 | return 1 |
287 | else: |
288 | return 0 |
289 | |
290 | def playlistRename(self, playlistId, name): |
291 | if self.loggedIn == 1: |
292 | result = self.callRemote("playlist.rename", {"playlistID": playlistId, "name": name}) |
293 | if 'fault' in result: |
294 | return 0 |
295 | else: |
296 | return 1 |
297 | else: |
298 | return 0 |
299 | |
300 | def playlistClearSongs(self, playlistId): |
301 | if self.loggedIn == 1: |
302 | return self.callRemote("playlist.clearSongs", {"playlistID": playlistId}) |
303 | |
304 | def playlistAddSong(self, playlistId, songId, position): |
305 | if self.loggedIn == 1: |
306 | result = self.callRemote("playlist.addSong", {"playlistID": playlistId, "songID": songId, "position": position}) |
307 | if 'fault' in result: |
308 | return 0 |
309 | else: |
310 | return 1 |
311 | else: |
312 | return 0 |
313 | |
314 | def playlistDeleteSong(self, playlistId, position): |
315 | if self.loggedIn == 1: |
316 | result = self.callRemote("playlist.removeSong", {"playlistID": playlistId, "position": position}) |
317 | if 'fault' in result: |
318 | return 0 |
319 | else: |
320 | return 1 |
321 | else: |
322 | return 0 |
323 | |
324 | def playlistReplace(self, playlistId, songIds): |
325 | if self.loggedIn == 1: |
326 | result = self.callRemote("playlist.replace", {"playlistID": playlistId, "songIDs": songIds}) |
327 | if 'fault' in result: |
328 | return 0 |
329 | else: |
330 | return 1 |
331 | else: |
332 | return 0 |
333 | |
334 | def artistGetSimilar(self, artistId, limit): |
335 | items = self.callRemote("artist.getSimilar", {"artistID": artistId, "limit": limit}) |
336 | if 'result' in items: |
337 | i = 0 |
338 | list = [] |
339 | artists = items['result']['artists'] |
340 | while(i < len(artists)): |
341 | s = artists[i] |
342 | list.append([s['artistName'].encode('ascii', 'ignore'),\ |
343 | s['artistID']]) |
344 | i = i + 1 |
345 | return list |
346 | else: |
347 | return [] |
348 | |
1413d357 |
349 | # Main API |
350 | class GrooveAPI: |
351 | |
352 | sessionID = '' |
353 | userID = 0 |
354 | host = 'api.grooveshark.com' |
0e7dbdf7 |
355 | lastSessionTime = 0 |
1413d357 |
356 | |
357 | # Constructor |
7ce01be6 |
358 | def __init__(self): |
359 | |
1413d357 |
360 | import simplejson |
361 | self.simplejson = simplejson |
362 | socket.setdefaulttimeout(40) |
7ce01be6 |
363 | |
364 | self.cacheDir = os.path.join(tempfile.gettempdir(), 'grooveapi') |
365 | if os.path.isdir(self.cacheDir) == False: |
366 | os.makedirs(self.cacheDir) |
367 | print "Made " + self.cacheDir |
368 | |
44dcc6f4 |
369 | self._getSavedSession() |
0e7dbdf7 |
370 | # session ids last 1 week |
44dcc6f4 |
371 | if self.sessionID == '' or time.time()- self.lastSessionTime >= SESSION_EXPIRY: |
1413d357 |
372 | self.sessionID = self._getSessionID() |
373 | if self.sessionID == '': |
374 | raise StandardError('Failed to get session id') |
375 | else: |
44dcc6f4 |
376 | print "New GrooveAPI session id: " + self.sessionID |
377 | self._setSavedSession() |
0e7dbdf7 |
378 | |
1413d357 |
379 | # Sort keys |
380 | def _keySort(self, d): |
381 | return [(k,d[k]) for k in sorted(d.keys())] |
382 | |
383 | # Make a message sig |
384 | def _createMessageSig(self, method, params, secret): |
385 | args = self._keySort(params); |
386 | data = ''; |
387 | for arg in args: |
388 | data += str(arg[0]) |
389 | data += str(arg[1]) |
390 | data = method + data |
391 | |
392 | h = hmac.new(secret, data) |
393 | return h.hexdigest() |
394 | |
395 | # The actual call to the API |
396 | def _callRemote(self, method, params = {}): |
397 | url = 'http://%s/ws/2.1/?method=%s&%s&wsKey=wordpress&sig=%s&format=json' % (self.host, method, urllib.urlencode(params), self._createMessageSig(method, params, 'd6c59291620c6eaa5bf94da08fae0ecc')) |
398 | print url |
399 | req = urllib2.Request(url) |
400 | response = urllib2.urlopen(req) |
401 | result = response.read() |
7ce01be6 |
402 | print "Response..." |
1413d357 |
403 | pprint.pprint(result) |
404 | response.close() |
405 | try: |
406 | result = self.simplejson.loads(result) |
407 | return result |
408 | except: |
409 | return [] |
410 | |
411 | # Get a session id |
412 | def _getSessionID(self): |
413 | params = {} |
414 | result = self._callRemote('startSession', params) |
0e7dbdf7 |
415 | self.lastSessionTime = time.time() |
1413d357 |
416 | return result['result']['sessionID'] |
417 | |
44dcc6f4 |
418 | def _getSavedSession(self): |
7ce01be6 |
419 | path = os.path.join(self.cacheDir, 'session.dmp') |
1413d357 |
420 | try: |
421 | f = open(path, 'rb') |
0e7dbdf7 |
422 | session = pickle.load(f) |
423 | self.sessionID = session['sessionID'] |
424 | self.lastSessionTime = session['lastSessionTime'] |
44dcc6f4 |
425 | self.userID = session['userID'] |
1413d357 |
426 | f.close() |
427 | except: |
0e7dbdf7 |
428 | self.sessionID = '' |
429 | self.lastSessionTime = 0 |
44dcc6f4 |
430 | self.userID = 0 |
1413d357 |
431 | pass |
1413d357 |
432 | |
44dcc6f4 |
433 | def _setSavedSession(self): |
1413d357 |
434 | try: |
7ce01be6 |
435 | # Create the directory if it doesn't exist. |
436 | if not os.path.exists(self.cacheDir): |
437 | os.makedirs(self.cacheDir) |
438 | path = os.path.join(self.cacheDir, 'session.dmp') |
1413d357 |
439 | f = open(path, 'wb') |
44dcc6f4 |
440 | session = { 'sessionID' : self.sessionID, 'lastSessionTime' : self.lastSessionTime, 'userID': self.userID} |
0e7dbdf7 |
441 | pickle.dump(session, f, protocol=pickle.HIGHEST_PROTOCOL) |
1413d357 |
442 | f.close() |
443 | except: |
44dcc6f4 |
444 | print "An error occurred during save session" |
1413d357 |
445 | pass |
446 | |
447 | # Make user authentication token |
448 | def _getUserToken(self, username, password): |
449 | return md5.new(username.lower() + md5.new(password).hexdigest()).hexdigest() |
450 | |
451 | # Authenticates the user for current API session |
452 | def _authenticateUser(self, username, token): |
453 | params = {'sessionID': self.sessionID, 'username': username, 'token': token} |
454 | result = self._callRemote('authenticateUser', params) |
455 | return result['result']['UserID'] |
456 | |
457 | # Login |
458 | def login(self, username, password): |
44dcc6f4 |
459 | if self.userID <= 0: |
460 | # Check cache |
461 | self._getSavedSession() |
462 | if self.userID <= 0: |
463 | token = self._getUserToken(username, password) |
464 | self.userID = self._authenticateUser(username, token) |
465 | if self.userID > 0: |
466 | self._setSavedSession() |
1413d357 |
467 | return self.userID |
468 | |
469 | # Logs the user out |
470 | def logout(self): |
44dcc6f4 |
471 | result = self._callRemote('logout', {'sessionID' : self.sessionID}) |
472 | if 'result' in result and result['result']['success'] == True: |
473 | self.userID = 0 |
474 | self._setSavedSession() |
475 | return True |
476 | return False |
1413d357 |
477 | |
1413d357 |
478 | # Search for albums |
479 | def getArtistSearchResults(self, query, limit=ARTIST_LIMIT): |
480 | result = self._callRemote('getArtistSearchResults', {'query' : query,'limit' : limit}) |
481 | if 'result' in result: |
482 | return self._parseArtists(result) |
483 | else: |
484 | return [] |
485 | |
486 | # Search for albums |
487 | def getAlbumSearchResults(self, query, limit=ALBUM_LIMIT): |
488 | result = self._callRemote('getAlbumSearchResults', {'query' : query,'limit' : limit}) |
489 | if 'result' in result: |
490 | return self._parseAlbums(result) |
491 | else: |
492 | return [] |
493 | |
494 | # Search for songs |
495 | def getSongSearchResults(self, query, limit=SONG_LIMIT): |
496 | result = self._callRemote('getSongSearchResultsEx', {'query' : query, 'limit' : limit}) |
497 | if 'result' in result: |
498 | return self._parseSongs(result) |
499 | else: |
500 | return [] |
7ce01be6 |
501 | |
502 | # Get artists albums |
503 | def getArtistAlbums(self, artistID, limit=ALBUM_LIMIT): |
504 | result = self._callRemote('getArtistAlbums', {'artistID' : artistID}) |
505 | if 'result' in result: |
506 | return self._parseAlbums(result, limit) |
507 | else: |
508 | return [] |
509 | |
510 | # Get album songs |
511 | def getAlbumSongs(self, albumID, limit=SONG_LIMIT): |
512 | result = self._callRemote('getAlbumSongsEx', {'albumID' : albumID, 'limit' : limit}) |
513 | if 'result' in result: |
514 | return self._parseSongs(result) |
515 | else: |
516 | return [] |
97289139 |
517 | |
518 | # Get artist's popular songs |
519 | def getArtistPopularSongs(self, artistID, limit = SONG_LIMIT): |
520 | result = self._callRemote('getArtistPopularSongs', {'artistID' : artistID}) |
521 | if 'result' in result: |
522 | return self._parseSongs(result, limit) |
523 | else: |
524 | return [] |
525 | |
1413d357 |
526 | # Gets the popular songs |
527 | def getPopularSongsToday(self, limit=SONG_LIMIT): |
528 | result = self._callRemote('getPopularSongsToday', {'limit' : limit}) |
529 | if 'result' in result: |
7ce01be6 |
530 | # Note limit is broken in the Grooveshark getPopularSongsToday method |
531 | return self._parseSongs(result, limit) |
1413d357 |
532 | else: |
533 | return [] |
534 | |
535 | # Gets the favorite songs of the logged-in user |
536 | def getUserFavoriteSongs(self): |
537 | if (self.userID == 0): |
538 | return []; |
539 | result = self._callRemote('getUserFavoriteSongs', {'sessionID' : self.sessionID}) |
540 | if 'result' in result: |
541 | return self._parseSongs(result) |
542 | else: |
543 | return [] |
544 | |
40ac5d22 |
545 | # Add song to user favorites |
546 | def addUserFavoriteSong(self, songID): |
547 | if (self.userID == 0): |
548 | return False; |
549 | result = self._callRemote('addUserFavoriteSong', {'sessionID' : self.sessionID, 'songID' : songID}) |
550 | return result['result']['success'] |
7ce01be6 |
551 | |
1413d357 |
552 | # Get the url to link to a song on Grooveshark |
553 | def getSongURLFromSongID(self, songID): |
7ce01be6 |
554 | song = GrooveSong() |
cbb0985e |
555 | url = song.getSongURL(songID) |
556 | print "Got song URL " + url |
557 | return url |
1413d357 |
558 | |
559 | # Get the url to link to a song on Grooveshark |
560 | def getSongInfo(self, songID): |
561 | result = self._callRemote('getSongInfoEx', {'songID' : songID}) |
562 | if 'result' in result and 'SongID' in result['result']: |
563 | info = result['result'] |
564 | if 'CoverArtFilename' in info and info['CoverArtFilename'] != None: |
565 | info['CoverArtFilename'] = THUMB_URL+info['CoverArtFilename'].encode('ascii', 'ignore') |
566 | else: |
7ce01be6 |
567 | info['CoverArtFilename'] = 'None' |
1413d357 |
568 | return info |
569 | else: |
7ce01be6 |
570 | return 'None' |
1413d357 |
571 | |
572 | # Gets the playlists of the logged-in user |
573 | def getUserPlaylists(self): |
574 | if (self.userID == 0): |
575 | return []; |
576 | result = self._callRemote('getUserPlaylists', {'sessionID' : self.sessionID}) |
577 | if 'result' in result: |
578 | return self._parsePlaylists(result) |
579 | else: |
580 | return [] |
86f629ea |
581 | |
582 | # Get userid from name |
583 | def _getUserIDFromUsername(self, username): |
584 | result = self._callRemote('getUserIDFromUsername', {'username' : username}) |
585 | if 'result' in result and result['result']['UserID'] > 0: |
586 | return result['result']['UserID'] |
587 | else: |
588 | return 0 |
589 | |
590 | # Gets the playlists of the logged-in user |
591 | def getUserPlaylistsEx(self, username): |
592 | userID = self._getUserIDFromUsername(username) |
593 | if (userID > 0): |
594 | result = self._callRemote('getUserPlaylistsEx', {'userID' : userID}) |
595 | if 'result' in result and result['result']['playlists'] != None: |
596 | playlists = result['result']['playlists'] |
597 | return self._parsePlaylists(playlists) |
598 | else: |
599 | return [] |
1413d357 |
600 | |
601 | # Creates a playlist with songs |
602 | def createPlaylist(self, name, songIDs): |
603 | result = self._callRemote('createPlaylist', {'name' : name, 'songIDs' : songIDs, 'sessionID' : self.sessionID}) |
40ac5d22 |
604 | if 'result' in result and result['result']['success'] == True: |
7ce01be6 |
605 | return result['result']['playlistID'] |
1413d357 |
606 | elif 'errors' in result: |
607 | return 0 |
608 | |
609 | # Sets the songs for a playlist |
610 | def setPlaylistSongs(self, playlistID, songIDs): |
611 | result = self._callRemote('setPlaylistSongs', {'playlistID' : playlistID, 'songIDs' : songIDs, 'sessionID' : self.sessionID}) |
40ac5d22 |
612 | if 'result' in result and result['result']['success'] == True: |
7ce01be6 |
613 | return True |
1413d357 |
614 | else: |
7ce01be6 |
615 | return False |
1413d357 |
616 | |
617 | # Gets the songs of a playlist |
618 | def getPlaylistSongs(self, playlistID): |
619 | result = self._callRemote('getPlaylistSongs', {'playlistID' : playlistID}); |
620 | if 'result' in result: |
621 | return self._parseSongs(result) |
622 | else: |
623 | return [] |
7ce01be6 |
624 | |
625 | # Check the service |
626 | def pingService(self,): |
627 | result = self._callRemote('pingService', {}); |
628 | if 'result' in result and result['result'] != '': |
629 | return True |
630 | else: |
631 | return False |
1413d357 |
632 | |
633 | # Extract song data |
7ce01be6 |
634 | def _parseSongs(self, items, limit=0): |
1413d357 |
635 | if 'result' in items: |
636 | i = 0 |
637 | list = [] |
97289139 |
638 | index = '' |
639 | l = -1 |
640 | try: |
641 | if 'songs' in items['result'][0]: |
642 | l = len(items['result'][0]['songs']) |
643 | index = 'songs[]' |
644 | except: pass |
645 | try: |
646 | if l < 0 and 'songs' in items['result']: |
647 | l = len(items['result']['songs']) |
648 | index = 'songs' |
649 | except: pass |
650 | try: |
651 | if l < 0 and 'song' in items['result']: |
652 | l = 1 |
653 | index = 'song' |
654 | except: pass |
655 | try: |
656 | if l < 0: |
657 | l = len(items['result']) |
658 | except: pass |
659 | |
7ce01be6 |
660 | if limit > 0 and l > limit: |
661 | l = limit |
1413d357 |
662 | while(i < l): |
97289139 |
663 | if index == 'songs[]': |
664 | s = items['result'][0]['songs'][i] |
665 | elif index == 'songs': |
1413d357 |
666 | s = items['result'][index][i] |
667 | elif index == 'song': |
668 | s = items['result'][index] |
669 | else: |
670 | s = items['result'][i] |
671 | if 'CoverArtFilename' not in s: |
672 | info = self.getSongInfo(s['SongID']) |
673 | coverart = info['CoverArtFilename'] |
674 | elif s['CoverArtFilename'] != None: |
675 | coverart = THUMB_URL+s['CoverArtFilename'].encode('ascii', 'ignore') |
676 | else: |
7ce01be6 |
677 | coverart = 'None' |
1413d357 |
678 | list.append([s['SongName'].encode('ascii', 'ignore'),\ |
679 | s['SongID'],\ |
680 | s['AlbumName'].encode('ascii', 'ignore'),\ |
681 | s['AlbumID'],\ |
682 | s['ArtistName'].encode('ascii', 'ignore'),\ |
683 | s['ArtistID'],\ |
684 | coverart]) |
685 | i = i + 1 |
686 | return list |
687 | else: |
688 | return [] |
689 | |
690 | # Extract artist data |
691 | def _parseArtists(self, items): |
692 | if 'result' in items: |
693 | i = 0 |
694 | list = [] |
695 | artists = items['result']['artists'] |
696 | while(i < len(artists)): |
697 | s = artists[i] |
698 | list.append([s['ArtistName'].encode('ascii', 'ignore'),\ |
699 | s['ArtistID']]) |
700 | i = i + 1 |
701 | return list |
702 | else: |
703 | return [] |
704 | |
705 | # Extract album data |
7ce01be6 |
706 | def _parseAlbums(self, items, limit=0): |
1413d357 |
707 | if 'result' in items: |
708 | i = 0 |
709 | list = [] |
7ce01be6 |
710 | try: |
711 | albums = items['result']['albums'] |
712 | except: |
713 | res = items['result'][0] |
714 | albums = res['albums'] |
715 | l = len(albums) |
716 | if limit > 0 and l > limit: |
717 | l = limit |
718 | while(i < l): |
1413d357 |
719 | s = albums[i] |
720 | if 'CoverArtFilename' in s and s['CoverArtFilename'] != None: |
721 | coverart = THUMB_URL+s['CoverArtFilename'].encode('ascii', 'ignore') |
722 | else: |
7ce01be6 |
723 | coverart = 'None' |
1413d357 |
724 | list.append([s['ArtistName'].encode('ascii', 'ignore'),\ |
725 | s['ArtistID'],\ |
726 | s['AlbumName'].encode('ascii', 'ignore'),\ |
727 | s['AlbumID'],\ |
728 | coverart]) |
729 | i = i + 1 |
730 | return list |
731 | else: |
732 | return [] |
733 | |
734 | def _parsePlaylists(self, items): |
86f629ea |
735 | i = 0 |
736 | list = [] |
1413d357 |
737 | if 'result' in items: |
1413d357 |
738 | playlists = items['result'] |
86f629ea |
739 | elif len(items) > 0: |
740 | playlists = items |
1413d357 |
741 | else: |
742 | return [] |
86f629ea |
743 | |
744 | while (i < len(playlists)): |
745 | s = playlists[i] |
746 | list.append([s['Name'].encode('ascii', 'ignore'), s['PlaylistID']]) |
747 | i = i + 1 |
748 | return list |
1413d357 |
749 | |
750 | # Test |
7ce01be6 |
751 | #import sys |
752 | #res = [] |
753 | #groovesharkApi = GrooveAPI() |
754 | #res = groovesharkApi.pingService() |
44dcc6f4 |
755 | #res = groovesharkApi.login(sys.argv[1], sys.argv[2]) |
e6f8730b |
756 | #songIDs = "[23404546,23401810,23401157]" |
757 | #res = groovesharkApi.createPlaylist("Test", songIDs) |
758 | #res = groovesharkApi.setPlaylistSongs('42873478', songIDs) |
759 | #pprint.pprint(res) |
760 | #res = groovesharkApi.getPlaylistSongs('42873478') |
1413d357 |
761 | #res = groovesharkApi.getSongSearchResults('jimmy jazz', 3) |
7ce01be6 |
762 | #res = groovesharkApi.getPopularSongsToday(3) |
763 | #res = groovesharkApi.getSongURLFromSongID('26579347') |
1413d357 |
764 | #res = groovesharkApi.getAlbumSearchResults('london calling', 3) |
7ce01be6 |
765 | #res = groovesharkApi.getArtistAlbums('52283') |
1413d357 |
766 | #res = groovesharkApi.getArtistSearchResults('the clash', 3) |
767 | #res = groovesharkApi.getUserFavoriteSongs() |
44dcc6f4 |
768 | #res = groovesharkApi.getUserPlaylists() |
40ac5d22 |
769 | #res = groovesharkApi.getSongInfo('27425375') |
1413d357 |
770 | #res = groovesharkApi.getPlaylistSongs(40902662) |
40ac5d22 |
771 | #res = groovesharkApi.addUserFavoriteSong('27425375') |
44dcc6f4 |
772 | #res = groovesharkApi.logout() |
86f629ea |
773 | #res = groovesharkApi.getUserPlaylistsEx('stephendenham') |
97289139 |
774 | #res = groovesharkApi.getArtistPopularSongs('3707') |
7ce01be6 |
775 | # |
776 | #pprint.pprint(res) |