/
google.py
163 lines (135 loc) · 3.74 KB
/
google.py
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import certifi
import gpsoauth
import urllib
import urllib2
import json
import uuid
import sys
SJ_DOMAIN = "mclients.googleapis.com"
SJ_URL = "/sj/v1.11"
def encode(values):
try:
for k, v in values.iteritems():
values[k] = unicode(v).encode("utf-8")
except Exception:
pass
return urllib.urlencode(values)
class Mobileclient(object):
def __init__(self):
self._auth = None
def login(self, username, password):
android_id = "asdkfjaj"
try:
res = gpsoauth.perform_master_login(username, password, android_id)
except:
print "Developer might have forgotten to include cacert.pem. Please let him know!"
raw_input("Press enter to exit")
sys.exit()
if "Token" not in res:
return False
self._master_token = res['Token']
res = gpsoauth.perform_oauth(
username, self._master_token, android_id,
service='sj', app='com.google.android.music',
client_sig='38918a453d07199354f8b19af05ec6562ced5788')
if 'Auth' not in res:
return False
self._auth = res["Auth"]
self.is_authenticated = True
return True
def search_all_access(self, search_query, max_results=1):
params = {"q": search_query, "max_items": max_results}
query = encode(params)
url = "/query?{0}".format(query)
data = self._http_get(url)
return data
def find_best_track(self, search_query):
data = self.search_all_access(search_query)
if "entries" not in data:
return None
for entry in data["entries"]:
if entry["type"] == "1":
return entry["track"]
return None
def create_playlist(self, name, public=False):
mutations = build_create_playlist(name, public)
data = self._pl_http_post("/playlistbatch?alt=json", {
"mutations": mutations,
})
return data["mutate_response"][0]["id"] # playlist_id
def add_songs_to_playlist(self, playlist_id, track_ids):
mutations = build_add_tracks(playlist_id, track_ids)
self._pl_http_post("/plentriesbatch?alt=json", {
"mutations": mutations,
})
def _http_get(self, url):
headers = {
"Authorization": "GoogleLogin auth={0}".format(self._auth),
"Content-type": "application/json",
}
req = urllib2.Request("https://" + SJ_DOMAIN + SJ_URL + url, headers=headers)
res = urllib2.urlopen(req)
body = res.read()
data = json.loads(body)
return data
def _pl_http_post(self, url, data):
data = json.dumps(data)
headers = {
"Authorization": "GoogleLogin auth={0}".format(self._auth),
"Content-type": "application/json",
}
req = urllib2.Request("https://" + SJ_DOMAIN + SJ_URL + url, data=data, headers=headers)
res = urllib2.urlopen(req)
body = res.read()
data = json.loads(body)
return data
def build_add_tracks(playlist_id, track_ids):
mutations = []
prev_id = ""
cur_id = str(uuid.uuid4())
next_id = str(uuid.uuid4())
for i, track_id in enumerate(track_ids):
details = {
"create": {
"clientId": cur_id,
"creationTimestamp": -1,
"deleted": False,
"lastModifiedTimestamp": "0",
"playlistId": playlist_id,
"source": 1,
"trackId": track_id,
}
}
if track_id.startswith("T"):
details["create"]["source"] = 2 # AA track
if i > 0:
details["create"]["precedingEntryId"] = prev_id
if i < len(track_ids) - 1:
details["create"]["followingEntryId"] = next_id
mutations.append(details)
prev_id = cur_id
cur_id = next_id
next_id = str(uuid.uuid4())
return mutations
def build_create_playlist(name, public):
return [{
"create": {
"creationTimestamp": "-1",
"deleted": False,
"lastModifiedTimestamp": 0,
"name": name,
"type": "USER_GENERATED",
"accessControlled": public,
}
}]
def parse_auth_response(s):
# SID=DQAAAGgA...7Zg8CTN
# LSID=DQAAAGsA...lk8BBbG
# Auth=DQAAAGgA...dk3fA5N
res = {}
for line in s.split("\n"):
if not line:
continue
k, v = line.split("=", 1)
res[k] = v
return res