Skip to content

Instantly share code, notes, and snippets.

@willnix
Created August 6, 2011 22:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willnix/1129828 to your computer and use it in GitHub Desktop.
Save willnix/1129828 to your computer and use it in GitHub Desktop.
GMusic Download
#!/usr/bin/env python
import sys,re,time,os
import urllib,urllib2,cookielib
import xml.dom.minidom
from ID3 import *
try:
import json
except ImportError,e:
import simplejson as json
import mimetypes,random
if len(sys.argv)<3:
sys.stderr.write("%s EMAIL PASSWD [TRACKNR]\n"%sys.argv[0])
sys.exit(2)
elif len(sys.argv)>3:
_,email,passwd,tracknr=sys.argv
else:
_,email,passwd=sys.argv
tracknr = -1
urls=[
"http://music.google.com/",
"http://music.google.com/music/listen",
"http://music.google.com/music/services/loadalltracks?u=0&xt=%s",
"http://music.google.com/music/play?songid=%s&pt=e",]
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
#fetch login parameters
res=opener.open(urls[0])
html=re.sub(r"\r|\n"," ",re.sub(r"\s{2,}"," ",res.read()))
form=re.search("<form.*?</form>",html).group()
inputs="\n".join(re.findall("<input .*?/>",form))
dom=xml.dom.minidom.parseString(
re.match("<form.*?>",form).group()+inputs+"</form>")
urls.append(dom.getElementsByTagName("form")[0].getAttribute("action"))
params={}
for tag in dom.getElementsByTagName("input"):
params[tag.getAttribute("name")]=tag.getAttribute("value")
params["Email"]=email
params["Passwd"]=passwd
#login
res = opener.open(urls[-1],urllib.urlencode(params))
res = opener.open(urls[1])
xt_cookie=cj._cookies["music.google.com"]["/music"]["xt"]
xt=xt_cookie.value
res = opener.open(urls[2]%xt,urllib.urlencode({"json":"{}"}))
all_tracks = json.loads(res.read())["playlist"]
#print the entire tracklist...
if tracknr==-1:
for i in range(len(all_tracks)-1):
print "%d / %s: \"%s\""%(i,all_tracks[i]["title"],all_tracks[i]["artist"])
i += 1;
#...or download a specific track?
else:
#query the stream url
res = opener.open(urls[3]%all_tracks[int(tracknr)]["id"])
track_url = json.loads(res.read())["url"]
local_file = open("./"+all_tracks[int(tracknr)]["name"]+".mp3", 'w')
remote_file = opener.open(track_url)
local_file.write(remote_file.read())
remote_file.close()
local_file.close()
#tag the new file
local_file = ID3("./"+all_tracks[int(tracknr)]["name"]+".mp3")
local_file['TITLE'] = all_tracks[int(tracknr)]["name"]
local_file['ARTIST'] = all_tracks[int(tracknr)]["artist"]
local_file['ALBUM'] = all_tracks[int(tracknr)]["album"]
local_file['TRACK'] = int(all_tracks[int(tracknr)]["track"])
local_file.write()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment