-
Notifications
You must be signed in to change notification settings - Fork 87
/
background.js
276 lines (256 loc) · 8.54 KB
/
background.js
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/**
* Authors:
* Rob Wu <[email protected]>
* Peter Wu <[email protected]>
*
* Released under the terms of GPLv3+.
*/
'use strict';
/* jshint browser:true, devel:true, eqnull:true */
/* globals chrome, JXG, MarketSession, progress */
/* exported processAsset */
/**
* URL used for requesting a special download token.
*/
var API_URL = "https://android.clients.google.com/market/api/ApiRequest";
var FDFE_URL_BASE = "https://android.clients.google.com/fdfe/";
function showLastError() {
console.log("chrome.extension.lastError", chrome.extension.lastError);
}
/**
* Functions for cookie management.
*/
function setCookie(storeId, cookie, callback) {
cookie.httpOnly = true;
cookie.storeId = storeId;
chrome.cookies.set(cookie, function (data) {
if (data === null) {
showLastError();
} else if (typeof callback == "function") {
callback();
}
});
}
function setMDACookie(storeId, marketda, callback) {
setCookie(storeId, {
name: "MarketDA",
value: marketda,
url: "http://android.clients.google.com/market/",
domain: "android.clients.google.com", /* set for subdomains too */
path: "/market/"
}, callback);
}
function setAPICookie(storeId, authToken, callback) {
setCookie(storeId, {
url: API_URL,
name: "ANDROIDSECURE",
value: authToken,
}, callback);
}
function removeAPICookie(storeId, callback) {
chrome.cookies.remove({
name: "ANDROIDSECURE",
url: API_URL,
storeId: storeId
}, function(data) {
if (data === null) {
showLastError();
} else if (typeof callback == "function") {
callback();
}
});
}
/**
* Debugging utility: convert a (binary) string to a hexadecimal format.
*/
function strToHex(str) {
return str.split("").map(function (c) {
return ("0" + c.charCodeAt(0).toString(16)).substr(-2);
}).join("");
}
/**
* Try to retrieve download URL for a given base64-encoded query.
*/
function processAsset(asset_query_base64, packageName, tabId) {
if (typeof tabId !== 'number') {
throw new Error('processAsset: tabId must be a number');
}
chrome.cookies.getAllCookieStores(function(cookieStores) {
var i, cookieStore;
for (i=0; i<cookieStores.length; i++) {
cookieStore = cookieStores[i];
if (cookieStore.tabIds.indexOf(tabId) !== -1) {
_real_processAsset(asset_query_base64, packageName, cookieStore.id, tabId);
return; // Found id. Return now!
}
}
// At this point, no cookie store was found for the caller. Use default store:
console.log('Cookiestore not found for tab ' + tabId + '. Using default store');
_real_processAsset(asset_query_base64, packageName, "0");
});
}
function _real_processAsset(asset_query_base64, packageName, storeId, tabId) {
progress.downloadStarting(tabId);
var payload = "version=2&request=" + asset_query_base64;
var xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";
xhr.open("POST", API_URL);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function() {
removeAPICookie(storeId, function() {
if (xhr.status == 403) {
hasValidSession(function(isValid) {
if (isValid) {
alert("Cannot download app, maybe it is a paid one or something?");
} else {
alert("Session expired, please re-login");
openTab("options.html");
}
});
progress.downloadFailed(tabId);
return;
}
if (xhr.status != 200) {
alert("ERROR: Cannot download this app!\n" + xhr.status + " " +
xhr.statusText);
progress.downloadFailed(tabId);
return;
}
var chars = new Uint8Array(xhr.response);
/* gzipped content, try to unpack */
var data = (new JXG.Util.Unzip(chars)).unzip()[0][0];
console.log("Response: " + data);
console.log("Response (hex): " + strToHex(data));
var url, marketda;
if ((url = /https?:\/\/[^:]+/i.exec(data))) {
/* not sure if decoding is even necessary */
url = decodeURIComponent(url[0]);
/* format: "MarketDA", 0x72 ('r'), length of data, data */
if ((marketda = /MarketDA..(\d+)/.exec(data))) {
marketda = marketda[1];
var filename = packageName + ".apk";
downloadAPK(marketda, url, filename, storeId, tabId);
progress.downloadStarted(tabId);
return;
}
}
alert("ERROR: Cannot download this app!");
progress.downloadFailed(tabId);
});
};
xhr.onerror = removeAPICookie.bind(null, storeId);
setAPICookie(storeId, localStorage.getItem("authToken"), function () {
xhr.send(payload);
});
}
/**
* Tries to download an APK file given its URL and cookie.
*/
function downloadAPK(marketda, url, filename, storeId, tabId) {
if (!filename) filename = "todo-pick-a-name.apk";
setMDACookie(storeId, marketda, function() {
console.log("Trying to download " + url + " and save it as " + filename);
if (chrome.downloads) {
chrome.downloads.download({
url: url,
filename: filename
});
return;
}
chrome.tabs.sendMessage(tabId, {
action: "download",
url: url,
filename: filename
});
});
}
/**
* Determine whether a valid session is available. If the callback is called
* with "false" as first argument, then it is 100% sure that the session is
* invalid.
*/
function hasValidSession(callback) {
var authToken = localStorage.getItem("authToken");
if (authToken == null) {
callback(false);
return;
}
// TODO: restore functionality, currently (2014-02-10), the FDFE URL always
// returns 401. For now assume that a token is always valid.
if (1) {
callback(true);
return;
}
var xhr = new XMLHttpRequest();
xhr.open("GET", FDFE_URL_BASE + "delivery");
/* GoogleLogin auth=... is required, otherwise you get a 302 which is
* uncatchable */
xhr.setRequestHeader("Authorization", "GoogleLogin auth=" + authToken);
xhr.onload = function () {
console.log("xhr status " + xhr.status);
if (xhr.status == 401) {
/* 401 Unauthorized: invalid login token */
localStorage.removeItem("authToken");
callback(false);
} else {
/* assume valid session for other status codes (400, ???) */
callback(true);
}
};
xhr.onerror = function () {
console.log("Unable to test session for validity, assuming valid one");
callback(true);
};
xhr.send(null);
}
/* Try to focus existing options page or open a new tab for it */
function openTab(url) {
chrome.tabs.query({
url: url
}, function(tabs) {
if (tabs.length > 0) {
focusTab(tabs[0]);
} else {
chrome.tabs.create({
url: url,
active: true
}, focusTab);
}
function focusTab(tab) {
chrome.windows.update(tab.windowId, {
focused: true
});
}
});
}
/**
* When a tab is loaded, show the APK Downloader icon if on the market page.
*/
chrome.extension.onMessage.addListener(function (message, sender, sendResponse) {
if (message && message.action == "showIcon") {
if (message.show) {
chrome.pageAction.show(sender.tab.id);
} else {
chrome.pageAction.hide(sender.tab.id);
}
}
});
var checkMarketPage = function(details) {
var tabId = details.tabId;
chrome.tabs.sendMessage(tabId, {
action: 'checkButtonState'
});
};
var urlFilter = {
url: [{
hostEquals: "play.google.com",
pathPrefix: "/store/apps/details",
}]
};
chrome.webNavigation.onHistoryStateUpdated.addListener(checkMarketPage, urlFilter);
chrome.pageAction.onClicked.addListener(function (tab) {
var match = /play\.google\.com\/store\/apps\/details\?(?:|.*&)id=([\w\d\.\_]+)/i.exec(tab.url);
if (match) {
MarketSession.download(match[1], tab.id);
}
});