Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: assets/js/Synchronizer.jsm

Issue 8482109: ABP/Android JavaScript code (Closed)
Patch Set: ABP/Android JavaScript code Created Nov. 12, 2012, 9:32 a.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 /*
2 * This Source Code is subject to the terms of the Mozilla Public License
3 * version 2.0 (the "License"). You can obtain a copy of the License at
4 * http://mozilla.org/MPL/2.0/.
5 */
6
7 //
8 // This file has been generated automatically from Adblock Plus source code
9 //
10
11 (function (_patchFunc5) {
12 const MILLISECONDS_IN_SECOND = 1000;
13 const SECONDS_IN_MINUTE = 60;
14 const SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTE;
15 const SECONDS_IN_DAY = 24 * SECONDS_IN_HOUR;
16 const INITIAL_DELAY = 6 * SECONDS_IN_MINUTE;
17 const CHECK_INTERVAL = SECONDS_IN_HOUR;
18 const MIN_EXPIRATION_INTERVAL = 1 * SECONDS_IN_DAY;
19 const MAX_EXPIRATION_INTERVAL = 14 * SECONDS_IN_DAY;
20 const MAX_ABSENSE_INTERVAL = 1 * SECONDS_IN_DAY;
21 var XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttpreq uest;1", "nsIJSXMLHttpRequest");
22 var timer = null;
23 var executing = {
24 __proto__: null
25 };
26 var Synchronizer = {
27 startup: function () {
28 var callback = function () {
29 timer.delay = CHECK_INTERVAL * MILLISECONDS_IN_SECOND;
30 checkSubscriptions();
31 }
32 ;
33 timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
34 timer.initWithCallback(callback, INITIAL_DELAY * MILLISECONDS_IN_SECOND, C i.nsITimer.TYPE_REPEATING_SLACK);
35 }
36 ,
37 isExecuting: function (url) {
38 return url in executing;
39 }
40 ,
41 execute: function (subscription, manual, forceDownload) {
42 Utils.runAsync(this.executeInternal, this, subscription, manual, forceDown load);
43 }
44 ,
45 executeInternal: function (subscription, manual, forceDownload) {
46 var url = subscription.url;
47 if (url in executing)
48 return ;
49 var newURL = subscription.nextURL;
50 var hadTemporaryRedirect = false;
51 subscription.nextURL = null;
52 var curVersion = Utils.addonVersion;
53 var loadFrom = newURL;
54 var isBaseLocation = true;
55 if (!loadFrom)
56 loadFrom = url;
57 if (loadFrom == url) {
58 if (subscription.alternativeLocations) {
59 var options = [[1, url]];
60 var totalWeight = 1;
61 for (var _loopIndex0 = 0;
62 _loopIndex0 < subscription.alternativeLocations.split(",").length; ++ _loopIndex0) {
63 var alternative = subscription.alternativeLocations.split(",")[_loop Index0];
64 if (!/^https?:\/\//.test(alternative))
65 continue;
66 var weight = 1;
67 var weightingRegExp = /;q=([\d\.]+)$/;
68 if (weightingRegExp.test(alternative)) {
69 weight = parseFloat(RegExp["$1"]);
70 if (isNaN(weight) || !isFinite(weight) || weight < 0)
71 weight = 1;
72 if (weight > 10)
73 weight = 10;
74 alternative = alternative.replace(weightingRegExp, "");
75 }
76 options.push([weight, alternative]);
77 totalWeight += weight;
78 }
79 var choice = Math.random() * totalWeight;
80 for (var _loopIndex1 = 0;
81 _loopIndex1 < options.length; ++ _loopIndex1) {
82 var weight = options[_loopIndex1][0];
83 var alternative = options[_loopIndex1][1];
84 choice -= weight;
85 if (choice < 0) {
86 loadFrom = alternative;
87 break;
88 }
89 }
90 isBaseLocation = (loadFrom == url);
91 }
92 }
93 else {
94 forceDownload = true;
95 }
96 loadFrom = loadFrom.replace(/%VERSION%/, "ABP" + curVersion);
97 var request = null;
98 function errorCallback(error) {
99 var channelStatus = -1;
100 try {
101 channelStatus = request.channel.status;
102 }
103 catch (e){}
104 var responseStatus = "";
105 try {
106 responseStatus = request.channel.QueryInterface(Ci.nsIHttpChannel).res ponseStatus;
107 }
108 catch (e){}
109 setError(subscription, error, channelStatus, responseStatus, loadFrom, i sBaseLocation, manual);
110 }
111 try {
112 request = new XMLHttpRequest();
113 request.mozBackgroundRequest = true;
114 request.open("GET", loadFrom);
115 }
116 catch (e){
117 errorCallback("synchronize_invalid_url");
118 return ;
119 }
120 try {
121 request.overrideMimeType("text/plain");
122 request.channel.loadFlags = request.channel.loadFlags | request.channel. INHIBIT_CACHING | request.channel.VALIDATE_ALWAYS;
123 if (request.channel instanceof Ci.nsIHttpChannel)
124 request.channel.redirectionLimit = 5;
125 var oldNotifications = request.channel.notificationCallbacks;
126 var oldEventSink = null;
127 request.channel.notificationCallbacks = {
128 QueryInterface: XPCOMUtils.generateQI([Ci.nsIInterfaceRequestor, Ci.ns IChannelEventSink]),
129 getInterface: function (iid) {
130 if (iid.equals(Ci.nsIChannelEventSink)) {
131 try {
132 oldEventSink = oldNotifications.QueryInterface(iid);
133 }
134 catch (e){}
135 return this;
136 }
137 if (oldNotifications)
138 return oldNotifications.QueryInterface(iid);
139 else
140 throw Cr.NS_ERROR_NO_INTERFACE;
141 }
142 ,
143 onChannelRedirect: function (oldChannel, newChannel, flags) {
144 if (isBaseLocation && !hadTemporaryRedirect && oldChannel instanceof Ci.nsIHttpChannel) {
145 try {
146 subscription.alternativeLocations = oldChannel.getResponseHeader ("X-Alternative-Locations");
147 }
148 catch (e){
149 subscription.alternativeLocations = null;
150 }
151 }
152 if (flags & Ci.nsIChannelEventSink.REDIRECT_TEMPORARY)
153 hadTemporaryRedirect = true;
154 else
155 if (!hadTemporaryRedirect)
156 newURL = newChannel.URI.spec;
157 if (oldEventSink)
158 oldEventSink.onChannelRedirect(oldChannel, newChannel, flags);
159 }
160 ,
161 asyncOnChannelRedirect: function (oldChannel, newChannel, flags, callb ack) {
162 this.onChannelRedirect(oldChannel, newChannel, flags);
163 callback.onRedirectVerifyCallback(Cr.NS_OK);
164 }
165
166 };
167 }
168 catch (e){
169 Cu.reportError(e);
170 }
171 if (subscription.lastModified && !forceDownload)
172 request.setRequestHeader("If-Modified-Since", subscription.lastModified) ;
173 request.addEventListener("error", function (ev) {
174 delete executing[url];
175 try {
176 request.channel.notificationCallbacks = null;
177 }
178 catch (e){}
179 errorCallback("synchronize_connection_error");
180 }
181 , false);
182 request.addEventListener("load", function (ev) {
183 delete executing[url];
184 try {
185 request.channel.notificationCallbacks = null;
186 }
187 catch (e){}
188 if (request.status && request.status != 200 && request.status != 304) {
189 errorCallback("synchronize_connection_error");
190 return ;
191 }
192 var newFilters = null;
193 if (request.status != 304) {
194 newFilters = readFilters(subscription, request.responseText, errorCall back);
195 if (!newFilters)
196 return ;
197 subscription.lastModified = request.getResponseHeader("Last-Modified") ;
198 }
199 if (isBaseLocation && !hadTemporaryRedirect)
200 subscription.alternativeLocations = request.getResponseHeader("X-Alter native-Locations");
201 subscription.lastSuccess = subscription.lastDownload = Math.round(Date.n ow() / MILLISECONDS_IN_SECOND);
202 subscription.downloadStatus = "synchronize_ok";
203 subscription.errors = 0;
204 var now = Math.round((new Date(request.getResponseHeader("Date")).getTim e() || Date.now()) / MILLISECONDS_IN_SECOND);
205 var expires = Math.round(new Date(request.getResponseHeader("Expires")). getTime() / MILLISECONDS_IN_SECOND) || 0;
206 var expirationInterval = (expires ? expires - now : 0);
207 for (var _loopIndex2 = 0;
208 _loopIndex2 < (newFilters || subscription.filters).length; ++ _loopIndex 2) {
209 var filter = (newFilters || subscription.filters)[_loopIndex2];
210 if (filter instanceof CommentFilter && /\bExpires\s*(?::|after)\s*(\d+ )\s*(h)?/i.test(filter.text)) {
211 var interval = parseInt(RegExp["$1"]);
212 if (RegExp["$2"])
213 interval *= SECONDS_IN_HOUR;
214 else
215 interval *= SECONDS_IN_DAY;
216 if (interval > expirationInterval)
217 expirationInterval = interval;
218 }
219 }
220 expirationInterval = Math.min(Math.max(expirationInterval, MIN_EXPIRATIO N_INTERVAL), MAX_EXPIRATION_INTERVAL);
221 subscription.expires = (subscription.lastDownload + expirationInterval * 2);
222 subscription.softExpiration = (subscription.lastDownload + Math.round(ex pirationInterval * (Math.random() * 0.4 + 0.8)));
223 if (newFilters) {
224 for (var i = 0;
225 i < newFilters.length; i++) {
226 var filter = newFilters[i];
227 if (filter instanceof CommentFilter && /^!\s*(\w+)\s*:\s*(.*)/.test( filter.text)) {
228 var keyword = RegExp["$1"].toLowerCase();
229 var value = RegExp["$2"];
230 var known = true;
231 if (keyword == "redirect") {
232 if (isBaseLocation && value != url)
233 subscription.nextURL = value;
234 }
235 else
236 if (keyword == "homepage") {
237 var uri = Utils.makeURI(value);
238 if (uri && (uri.scheme == "http" || uri.scheme == "https"))
239 subscription.homepage = uri.spec;
240 }
241 else
242 known = false;
243 if (known)
244 newFilters.splice(i--, 1);
245 }
246 }
247 }
248 if (isBaseLocation && newURL && newURL != url) {
249 var listed = (subscription.url in FilterStorage.knownSubscriptions);
250 if (listed)
251 FilterStorage.removeSubscription(subscription);
252 url = newURL;
253 var newSubscription = Subscription.fromURL(url);
254 for (var key in newSubscription)
255 delete newSubscription[key];
256 for (var key in subscription)
257 newSubscription[key] = subscription[key];
258 delete Subscription.knownSubscriptions[subscription.url];
259 newSubscription.oldSubscription = subscription;
260 subscription = newSubscription;
261 subscription.url = url;
262 if (!(subscription.url in FilterStorage.knownSubscriptions) && listed)
263 FilterStorage.addSubscription(subscription);
264 }
265 if (newFilters)
266 FilterStorage.updateSubscriptionFilters(subscription, newFilters);
267 delete subscription.oldSubscription;
268 }
269 , false);
270 executing[url] = true;
271 FilterNotifier.triggerListeners("subscription.downloadStatus", subscriptio n);
272 try {
273 request.send(null);
274 }
275 catch (e){
276 delete executing[url];
277 errorCallback("synchronize_connection_error");
278 return ;
279 }
280 }
281
282 };
283 function checkSubscriptions() {
284 if (!Prefs.subscriptions_autoupdate)
285 return ;
286 var time = Math.round(Date.now() / MILLISECONDS_IN_SECOND);
287 for (var _loopIndex3 = 0;
288 _loopIndex3 < FilterStorage.subscriptions.length; ++ _loopIndex3) {
289 var subscription = FilterStorage.subscriptions[_loopIndex3];
290 if (!(subscription instanceof DownloadableSubscription))
291 continue;
292 if (subscription.lastCheck && time - subscription.lastCheck > MAX_ABSENSE_ INTERVAL) {
293 subscription.softExpiration += time - subscription.lastCheck;
294 }
295 subscription.lastCheck = time;
296 if (subscription.expires - time > MAX_EXPIRATION_INTERVAL)
297 subscription.expires = time + MAX_EXPIRATION_INTERVAL;
298 if (subscription.softExpiration - time > MAX_EXPIRATION_INTERVAL)
299 subscription.softExpiration = time + MAX_EXPIRATION_INTERVAL;
300 if (subscription.softExpiration > time && subscription.expires > time)
301 continue;
302 if (time - subscription.lastDownload >= MIN_EXPIRATION_INTERVAL)
303 Synchronizer.execute(subscription, false);
304 }
305 }
306 function readFilters(subscription, text, errorCallback) {
307 var lines = text.split(/[\r\n]+/);
308 if (!/\[Adblock(?:\s*Plus\s*([\d\.]+)?)?\]/i.test(lines[0])) {
309 errorCallback("synchronize_invalid_data");
310 return null;
311 }
312 var minVersion = RegExp["$1"];
313 for (var i = 0;
314 i < lines.length; i++) {
315 if (/!\s*checksum[\s\-:]+([\w\+\/]+)/i.test(lines[i])) {
316 lines.splice(i, 1);
317 var checksumExpected = RegExp["$1"];
318 var checksum = Utils.generateChecksum(lines);
319 if (checksum && checksum != checksumExpected) {
320 errorCallback("synchronize_checksum_mismatch");
321 return null;
322 }
323 break;
324 }
325 }
326 delete subscription.requiredVersion;
327 delete subscription.upgradeRequired;
328 if (minVersion) {
329 subscription.requiredVersion = minVersion;
330 if (Utils.versionComparator.compare(minVersion, Utils.addonVersion) > 0)
331 subscription.upgradeRequired = true;
332 }
333 lines.shift();
334 var result = [];
335 for (var _loopIndex4 = 0;
336 _loopIndex4 < lines.length; ++ _loopIndex4) {
337 var line = lines[_loopIndex4];
338 var filter = Filter.fromText(Filter.normalize(line));
339 if (filter)
340 result.push(filter);
341 }
342 return result;
343 }
344 function setError(subscription, error, channelStatus, responseStatus, download URL, isBaseLocation, manual) {
345 if (!isBaseLocation)
346 subscription.alternativeLocations = null;
347 try {
348 Cu.reportError("Adblock Plus: Downloading filter subscription " + subscrip tion.title + " failed (" + Utils.getString(error) + ")\n" + "Download address: " + downloadURL + "\n" + "Channel status: " + channelStatus + "\n" + "Server resp onse: " + responseStatus);
349 }
350 catch (e){}
351 subscription.lastDownload = Math.round(Date.now() / MILLISECONDS_IN_SECOND);
352 subscription.downloadStatus = error;
353 if (!manual) {
354 if (error == "synchronize_checksum_mismatch") {
355 subscription.errors = 0;
356 }
357 else
358 subscription.errors++;
359 if (subscription.errors >= Prefs.subscriptions_fallbackerrors && /^https?: \/\//i.test(subscription.url)) {
360 subscription.errors = 0;
361 var fallbackURL = Prefs.subscriptions_fallbackurl;
362 fallbackURL = fallbackURL.replace(/%VERSION%/g, encodeURIComponent(Utils .addonVersion));
363 fallbackURL = fallbackURL.replace(/%SUBSCRIPTION%/g, encodeURIComponent( subscription.url));
364 fallbackURL = fallbackURL.replace(/%URL%/g, encodeURIComponent(downloadU RL));
365 fallbackURL = fallbackURL.replace(/%ERROR%/g, encodeURIComponent(error)) ;
366 fallbackURL = fallbackURL.replace(/%CHANNELSTATUS%/g, encodeURIComponent (channelStatus));
367 fallbackURL = fallbackURL.replace(/%RESPONSESTATUS%/g, encodeURIComponen t(responseStatus));
368 var request = new XMLHttpRequest();
369 request.mozBackgroundRequest = true;
370 request.open("GET", fallbackURL);
371 request.overrideMimeType("text/plain");
372 request.channel.loadFlags = request.channel.loadFlags | request.channel. INHIBIT_CACHING | request.channel.VALIDATE_ALWAYS;
373 request.addEventListener("load", function (ev) {
374 if (!(subscription.url in FilterStorage.knownSubscriptions))
375 return ;
376 if (/^301\s+(\S+)/.test(request.responseText))
377 subscription.nextURL = RegExp["$1"];
378 else
379 if (/^410\b/.test(request.responseText)) {
380 var data = "[Adblock]\n" + subscription.filters.map(function (f) {
381 return f.text;
382 }).join("\n");
383 var url = "data:text/plain," + encodeURIComponent(data);
384 var newSubscription = Subscription.fromURL(url);
385 newSubscription.title = subscription.title;
386 newSubscription.disabled = subscription.disabled;
387 FilterStorage.removeSubscription(subscription);
388 FilterStorage.addSubscription(newSubscription);
389 Synchronizer.execute(newSubscription);
390 }
391 }
392 , false);
393 request.send(null);
394 }
395 }
396 }
397 if (typeof _patchFunc5 != "undefined")
398 eval("(" + _patchFunc5.toString() + ")()");
399 window.Synchronizer = Synchronizer;
400 }
401 )(window.SynchronizerPatch);
OLDNEW

Powered by Google App Engine
This is Rietveld