-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathandroidmarket.py
220 lines (195 loc) · 8.01 KB
/
androidmarket.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import base64
import gzip
import pprint
import StringIO
import urllib
import urllib2
from google.protobuf import descriptor
from google.protobuf.internal.containers import RepeatedCompositeFieldContainer
import market_proto
class LoginError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class RequestError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class MarketSession(object):
SERVICE = "android";
URL_LOGIN = "https://www.google.com/accounts/ClientLogin"
ACCOUNT_TYPE_GOOGLE = "GOOGLE"
ACCOUNT_TYPE_HOSTED = "HOSTED"
ACCOUNT_TYPE_HOSTED_OR_GOOGLE = "HOSTED_OR_GOOGLE"
PROTOCOL_VERSION = 2
authSubToken = None
context = None
def __init__(self):
self.context = market_proto.RequestContext()
self.context.isSecure = 0
self.context.version = 1002012
self.context.androidId = "0123456789123456" # change me :(
self.context.userLanguage = "en"
self.context.userCountry = "US"
self.context.deviceAndSdkVersion = "crespo:10"
self.setOperatorTMobile()
def _toDict(self, protoObj):
iterable = False
if isinstance(protoObj, RepeatedCompositeFieldContainer):
iterable = True
else:
protoObj = [protoObj]
retlist = []
for po in protoObj:
msg = dict()
for fielddesc, value in po.ListFields():
#print value, type(value), getattr(value, '__iter__', False)
if fielddesc.type == descriptor.FieldDescriptor.TYPE_GROUP or isinstance(value, RepeatedCompositeFieldContainer):
msg[fielddesc.name.lower()] = self._toDict(value)
else:
msg[fielddesc.name.lower()] = value
retlist.append(msg)
if not iterable:
if len(retlist) > 0:
return retlist[0]
else:
return None
return retlist
def setOperatorSimple(self, alpha, numeric):
self.setOperator(alpha, alpha, numeric, numeric);
def setOperatorTMobile(self):
self.setOperatorSimple("T-Mobile", "310260")
def setOperatorSFR(self):
self.setOperatorSimple("F SFR", "20810")
def setOperatorO2(self):
self.setOperatorSimple("o2 - de", "26207")
def setOperatorSimyo(self):
self.setOperator("E-Plus", "simyo", "26203", "26203")
def setOperatorSunrise(self):
self.setOperatorSimple("sunrise", "22802")
def setOperator(self, alpha, simAlpha, numeric, simNumeric):
self.context.operatorAlpha = alpha
self.context.simOperatorAlpha = simAlpha
self.context.operatorNumeric = numeric
self.context.simOperatorNumeric = simNumeric
def setAuthSubToken(self, authSubToken):
self.context.authSubToken = authSubToken
self.authSubToken = authSubToken
def login(self, email, password, accountType = ACCOUNT_TYPE_HOSTED_OR_GOOGLE):
params = {"Email": email, "Passwd": password, "service": self.SERVICE,
"accountType": accountType}
try:
data = urllib2.urlopen(self.URL_LOGIN, urllib.urlencode(params)).read()
data = data.split()
params = {}
for d in data:
k, v = d.split("=")
params[k.strip().lower()] = v.strip()
if "auth" in params:
self.setAuthSubToken(params["auth"])
else:
raise LoginError("Auth token not found.")
except urllib2.HTTPError, e:
if e.code == 403:
data = e.fp.read().split()
params = {}
for d in data:
k, v = d.split("=", 1)
params[k.strip().lower()] = v.strip()
if "error" in params:
raise LoginError(params["error"])
else:
raise LoginError("Login failed.")
else:
raise e
def execute(self, request):
request.context.CopyFrom(self.context)
try:
headers = {"Cookie": "ANDROID="+self.authSubToken,
"User-Agent": "Android-Market/2 (sapphire PLAT-RC33); gzip",
"Content-Type": "application/x-www-form-urlencoded",
"Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7"}
data = request.SerializeToString()
data = "version=%d&request=%s" % (self.PROTOCOL_VERSION, base64.urlsafe_b64encode(data))
if self.context.isSecure == 1 or self.context.isSecure == True:
http = "https://"
else:
http = "http://"
request = urllib2.Request(http + "android.clients.google.com/market/api/ApiRequest",
data, headers)
data = urllib2.urlopen(request).read()
data = StringIO.StringIO(data)
gzipper = gzip.GzipFile(fileobj=data)
data = gzipper.read()
response = market_proto.Response()
response.ParseFromString(data)
return response
except Exception, e:
raise RequestError(e)
def searchApp(self, query, startIndex = 0, entriesCount = 10, extendedInfo = True):
appsreq = market_proto.AppsRequest()
appsreq.query = query
appsreq.startIndex = startIndex
appsreq.entriesCount = entriesCount
appsreq.withExtendedInfo = extendedInfo
request = market_proto.Request()
request.requestgroup.add(appsRequest = appsreq)
response = self.execute(request)
retlist = []
for rg in response.responsegroup:
if rg.HasField("appsResponse"):
for app in rg.appsResponse.app:
retlist.append(self._toDict(app))
return retlist
def getComments(self, appid, startIndex = 0, entriesCount = 10):
req = market_proto.CommentsRequest()
req.appId = appid
req.startIndex = startIndex
req.entriesCount = entriesCount
request = market_proto.Request()
request.requestgroup.add(commentsRequest = req)
response = self.execute(request)
retlist = []
for rg in response.responsegroup:
if rg.HasField("commentsResponse"):
for comment in rg.commentsResponse.comments:
retlist.append(self._toDict(comment))
return retlist
def getImage(self, appid, imageid = "0", imagetype = market_proto.GetImageRequest.SCREENSHOT):
req = market_proto.GetImageRequest()
req.appId = appid
req.imageId = imageid
req.imageUsage = imagetype
request = market_proto.Request()
request.requestgroup.add(imageRequest = req)
response = self.execute(request)
for rg in response.responsegroup:
if rg.HasField("imageResponse"):
return rg.imageResponse.imageData
def getCategories(self):
req = market_proto.CategoriesRequest()
request = market_proto.Request()
request.requestgroup.add(categoriesRequest = req)
response = self.execute(request)
retlist = []
for rg in response.responsegroup:
if rg.HasField("categoriesResponse"):
for cat in rg.categoriesResponse.categories:
retlist.append(self._toDict(cat))
return retlist
def getSubCategories(self, apptype):
req = market_proto.SubCategoriesRequest()
req.appType = apptype
request = market_proto.Request()
request.requestgroup.add(subCategoriesRequest = req)
response = self.execute(request)
retlist = []
for rg in response.responsegroup:
if rg.HasField("subCategoriesResponse"):
for cat in rg.subCategoriesResponse.category:
retlist.append(self._toDict(cat))
return retlist
if __name__ == "__main__":
print "No command line interface available, yet."