PageRenderTime 45ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/groove.py

https://bitbucket.org/vkolev/gsharkdown/
Python | 244 lines | 230 code | 8 blank | 6 comment | 4 complexity | 9b3a9e95b6844b8fc98c96f152be061e MD5 | raw file
Possible License(s): GPL-3.0
  1. import httplib
  2. import StringIO
  3. import hashlib
  4. import uuid
  5. import random
  6. import string
  7. import sys
  8. import gzip
  9. import pycurl
  10. import ipycurl
  11. import threading
  12. import time
  13. import gobject
  14. from enviroment import env
  15. if sys.version_info[1] >= 6:
  16. import json
  17. def dummy(error = None):
  18. pass
  19. _referer = "http://grooveshark.com/JSQueue.swf?20130520"
  20. _token = None
  21. _isInitialized = False
  22. _initializingLock = threading.Lock()
  23. _onInitError = dummy
  24. _onInitStart = dummy
  25. _onInitFinish = dummy
  26. _initFailed = False
  27. h = {}
  28. h["country"] = {}
  29. h["country"]["CC1"] = "72057594037927940"
  30. h["country"]["CC2"] = "0"
  31. h["country"]["CC3"] = "0"
  32. h["country"]["IPR"] = "1"
  33. h["country"]["CC4"] = "0"
  34. h["country"]["ID"] = "57"
  35. h["privacy"] = 0
  36. h["session"] = None
  37. h["uuid"] = str.upper(str(uuid.uuid4()))
  38. entrystring = \
  39. """A Grooveshark song downloader in python
  40. by George Stephanos <gaf.stephanos@gmail.com>
  41. """
  42. def createCurl(url = None):
  43. """
  44. Create a configurated cURL object
  45. """
  46. c = ipycurl.Curl(url)
  47. c.setopt(pycurl.USERAGENT, env().USER_AGENT)
  48. c.set_option(pycurl.FAILONERROR, True)
  49. c.setopt(pycurl.COOKIEFILE, env().get_config_directory() + "/cookie.txt")
  50. c.setopt(pycurl.COOKIEJAR, env().get_config_directory() + "/cookie.txt")
  51. c.set_timeout(50)
  52. proxy = env().get_proxy()
  53. if proxy != None:
  54. c.setopt(pycurl.PROXY, proxy["host"])
  55. c.setopt(pycurl.PROXYPORT, int(proxy["port"]))
  56. if proxy["user"] != None:
  57. c.setopt(pycurl.PROXYUSERPWD, proxy["user"] + ":" + proxy["pass"])
  58. else:
  59. c.setopt(pycurl.PROXY, "")
  60. return c
  61. def prepToken(method, sectoken):
  62. """
  63. Method to create the tocken for the request.
  64. """
  65. rnd = (''.join(random.choice(string.hexdigits) for x in range(6))).lower()
  66. hashs = hashlib.sha1(
  67. method + ":" + _token + sectoken + rnd).hexdigest()
  68. ret = rnd + hashs
  69. return ret
  70. def getToken():
  71. """
  72. Gets a token from the grooveshark.com service
  73. """
  74. global h, _token
  75. p = {}
  76. p["parameters"] = {}
  77. p["parameters"]["secretKey"] = hashlib.md5(h["session"]).hexdigest()
  78. p["method"] = "getCommunicationToken"
  79. p["header"] = h
  80. p["header"]["client"] = "htmlshark"
  81. p["header"]["clientRevision"] = "20130520"
  82. conn = createCurl("https://grooveshark.com/more.php?" + p["method"])
  83. conn.setopt(pycurl.POST, True)
  84. conn.setopt(pycurl.POSTFIELDS, json.JSONEncoder().encode(p))
  85. conn.setopt(pycurl.HTTPHEADER, [
  86. "Referer: " + _referer,
  87. "Accept-Encoding: gzip",
  88. "Content-Type: application/json"
  89. ])
  90. resp = conn.perform()
  91. conn.close()
  92. gzipfile = gzip.GzipFile(fileobj = (StringIO.StringIO(resp)))
  93. _token = json.JSONDecoder().decode(gzipfile.read())["result"]
  94. def getSearchResultsEx(query, _type = "Songs"):
  95. """
  96. Method to get the search results from the gs service
  97. and returns them as dictionary.
  98. """
  99. init()
  100. p = {}
  101. p["parameters"] = {}
  102. p["parameters"]["type"] = _type
  103. p["parameters"]["query"] = query
  104. p["header"] = h
  105. p["header"]["client"] = "htmlshark"
  106. p["header"]["clientRevision"] = "20130520"
  107. p["header"]["token"] = prepToken("getResultsFromSearch", ":nuggetsOfBaller:")
  108. p["method"] = "getResultsFromSearch"
  109. conn = createCurl("https://grooveshark.com/more.php?" + p["method"])
  110. conn.setopt(pycurl.POST, True)
  111. conn.setopt(pycurl.POSTFIELDS, json.JSONEncoder().encode(p))
  112. conn.setopt(pycurl.HTTPHEADER, [
  113. "Referer: http://grooveshark.com/",
  114. "Accept-Encoding: gzip",
  115. "Content-Type: application/json"
  116. ])
  117. resp = conn.perform()
  118. conn.close()
  119. gzipfile = gzip.GzipFile(fileobj = (StringIO.StringIO(resp)))
  120. j = json.JSONDecoder().decode(gzipfile.read())
  121. result = j['result']['result']
  122. if hasattr(result, 'Songs'):
  123. return result['Songs']
  124. else:
  125. return result
  126. def getStreamKeyFromSongIDEx(_id):
  127. """
  128. Gets the stream URL for Song ID
  129. """
  130. init()
  131. p = {}
  132. p["parameters"] = {}
  133. p["parameters"]["mobile"] = "false"
  134. p["parameters"]["prefetch"] = "false"
  135. p["parameters"]["songIDs"] = _id
  136. p["parameters"]["country"] = h["country"]
  137. p["header"] = h
  138. p["header"]["client"] = "jsqueue"
  139. p["header"]["clientRevision"] = "20130520"
  140. p["header"]["token"] = prepToken("getStreamKeysFromSongIDs", ":chickenFingers:")
  141. p["method"] = "getStreamKeysFromSongIDs"
  142. conn = createCurl("https://grooveshark.com/more.php?" + p["method"])
  143. conn.setopt(pycurl.POST, True)
  144. conn.setopt(pycurl.POSTFIELDS, json.JSONEncoder().encode(p))
  145. conn.setopt(pycurl.HTTPHEADER, [
  146. "Referer: " + _referer,
  147. "Accept-Encoding: gzip",
  148. "Content-Type: application/json"
  149. ])
  150. resp = conn.perform()
  151. conn.close()
  152. gzipfile = gzip.GzipFile(fileobj = (StringIO.StringIO(resp)))
  153. j = json.JSONDecoder().decode(gzipfile.read())
  154. if len(j["result"][str(_id)]) == 0:
  155. raise Exception("The song streaming key is empty")
  156. return j
  157. def init():
  158. global _isInitialized, _initFailed
  159. _initializingLock.acquire()
  160. if isInitialized():
  161. _initializingLock.release()
  162. if _initFailed == True:
  163. raise Exception(_("Grooveshark is not initialized"))
  164. return
  165. print "[Initializing Grooveshark]"
  166. gobject.idle_add(_onInitStart)
  167. while True:
  168. try:
  169. conn = createCurl("http://grooveshark.com/")
  170. conn.perform()
  171. cookielist = conn.get_info(pycurl.INFO_COOKIELIST)
  172. for cookie in cookielist:
  173. cookie = cookie.split("\t")
  174. if cookie[5] == "PHPSESSID":
  175. h["session"] = cookie[6]
  176. conn.close()
  177. getToken()
  178. print "[Grooveshark initialized]"
  179. break
  180. except Exception as e:
  181. if e.args[0] == 11004:
  182. time.sleep(1)
  183. else:
  184. print "[Grooveshark initialized failed]"
  185. _initFailed = True
  186. gobject.idle_add(_onInitError, e.__str__())
  187. break
  188. _isInitialized = True
  189. _initializingLock.release()
  190. gobject.idle_add(_onInitFinish)
  191. if _initFailed == True:
  192. raise Exception(_("Grooveshark is not initialized"))
  193. def onInitError(callback):
  194. global _onInitError
  195. _onInitError = callback
  196. def onInitStart(callback):
  197. global _onInitStart
  198. _onInitStart = callback
  199. def onInitFinish(callback):
  200. global _onInitFinish
  201. _onInitFinish = callback
  202. def isInitialized():
  203. return _isInitialized
  204. def getSession():
  205. return h["session"]