Source

gSharkDown / lib / groove.py

Full commit
#!/usr/bin/env python
import httplib
import StringIO
import hashlib
import uuid
import random
import string
import sys
import gzip

if sys.version_info[1] >= 6:
    import json

_useragent = \
"""Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"""
_referer = "http://grooveshark.com/JSQueue.swf?20111111.111"
_token = None

h = {}
h["country"] = {}
h["country"]["CC1"] = "0"
h["country"]["CC2"] = "0"
h["country"]["CC3"] = "0"
h["country"]["CC4"] = "0"
h["country"]["ID"] = "1"
h["privacy"] = 0
h["session"] = None
h["uuid"] = str.upper(str(uuid.uuid4()))

entrystring = \
"""A Grooveshark song downloader in python
by George Stephanos <gaf.stephanos@gmail.com>
"""


def prepToken(method, sectoken):
    """
    Method to create the tocken for the request.
    """
    rnd = (''.join(random.choice(string.hexdigits) for x in range(6))).lower()
    hashs = hashlib.sha1(
        method + ":" + _token + sectoken + rnd).hexdigest()
    ret = rnd + hashs
    return ret


def getToken():
    """
    Gets a token from the grooveshark.com service
    """
    global h, _token
    p = {}
    p["parameters"] = {}
    p["parameters"]["secretKey"] = hashlib.md5(h["session"]).hexdigest()
    p["method"] = "getCommunicationToken"
    p["header"] = h
    p["header"]["client"] = "htmlshark"
    p["header"]["clientRevision"] = "20110606"
    conn = httplib.HTTPSConnection("grooveshark.com")
    conn.request("POST", "/more.php",
                 json.JSONEncoder().encode(p),
                 {"User-Agent": _useragent,
                  "Referer": _referer,
                  "Content-Type": "",
                  "Accept-Encoding": "gzip",
                  "Cookie": "PHPSESSID=" + h["session"]})
    resp = conn.getresponse().read()
    gzipfile = gzip.GzipFile(fileobj = (StringIO.StringIO(resp)))
    _token = json.JSONDecoder().decode(gzipfile.read())["result"]


def getSearchResultsEx(query, type = "Songs"):
    """
    Method to get the search results from the gs service
    and returns them as dictionary.
    """
    p = {}
    p["parameters"] = {}
    p["parameters"]["type"] = type
    p["parameters"]["query"] = query
    p["header"] = h
    p["header"]["client"] = "htmlshark"
    p["header"]["clientRevision"] = "20110906"
    p["header"]["token"] = prepToken("getSearchResultsEx", ":backToTheScienceLab:")
    p["method"] = "getSearchResultsEx"
    conn = httplib.HTTPConnection("grooveshark.com")
    conn.request("POST", "/more.php?" + p["method"],
                 json.JSONEncoder().encode(p),
                 {"User-Agent": _useragent,
                  "Referer": "http://grooveshark.com/",
                  "Content-Type": "application/json",
                  "Accept-Encoding": "gzip",
                  "Cookie": "PHPSESSID=" + h["session"]})
    resp = conn.getresponse().read()
    gzipfile = gzip.GzipFile(fileobj = (StringIO.StringIO(resp)))
    j = json.JSONDecoder().decode(gzipfile.read())
    try:
        return j['result']['result']['Songs']
    except:
        return j['result']['result']


def getStreamKeyFromSongIDEx(id):
    """
    Gets the stream URL for Song ID
    """
    p = {}
    p["parameters"] = {}
    p["parameters"]["mobile"] = "false"
    p["parameters"]["prefetch"] = "false"
    p["parameters"]["songIDs"] = id
    p["parameters"]["country"] = h["country"]
    p["header"] = h
    p["header"]["client"] = "jsqueue"
    p["header"]["clientRevision"] = "20110606.04"
    p["header"]["token"] = prepToken("getStreamKeysFromSongIDs", ":bewareOfBearsharktopus:")
    p["method"] = "getStreamKeysFromSongIDs"
    conn = httplib.HTTPConnection("grooveshark.com")
    conn.request("POST", "/more.php?" + p["method"],
                 json.JSONEncoder().encode(p),
                 {"User-Agent": _useragent,
                  "Referer": _referer,
                  "Content-Type": "",
                  "Accept-Encoding": "gzip",
                  "Cookie": "PHPSESSID=" + h["session"]})
    resp = conn.getresponse().read()
    gzipfile = gzip.GzipFile(fileobj = (StringIO.StringIO(resp)))
    j = json.JSONDecoder().decode(gzipfile.read())
    return j


def header_cb(buf):
    global h
    if "PHPSESSID" in buf:
        buf = buf.split(' ')
        h["session"] = buf[1][10:-1]


def init():
    conn = httplib.HTTPConnection("grooveshark.com")
    conn.request("HEAD", "", headers = {"User-Agent": _useragent})
    res = conn.getresponse()
    cookie = res.getheader("set-cookie").split(";")
    h["session"] = cookie[0][10:]