2
* This file is part of Adblock Plus <https://adblockplus.org/>,
3
* Copyright (C) 2006-2015 Eyeo GmbH
5
* Adblock Plus is free software: you can redistribute it and/or modify
6
* it under the terms of the GNU General Public License version 3 as
7
* published by the Free Software Foundation.
9
* Adblock Plus is distributed in the hope that it will be useful,
10
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
* GNU General Public License for more details.
14
* You should have received a copy of the GNU General Public License
15
* along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
19
* @fileOverview Downloads a set of URLs in regular time intervals.
22
let {Utils} = require("utils");
24
let MILLIS_IN_SECOND = exports.MILLIS_IN_SECOND = 1000;
25
let MILLIS_IN_MINUTE = exports.MILLIS_IN_MINUTE = 60 * MILLIS_IN_SECOND;
26
let MILLIS_IN_HOUR = exports.MILLIS_IN_HOUR = 60 * MILLIS_IN_MINUTE;
27
let MILLIS_IN_DAY = exports.MILLIS_IN_DAY = 24 * MILLIS_IN_HOUR;
30
* Creates a new downloader instance.
31
* @param {Function} dataSource Function that will yield downloadable objects on each check
32
* @param {Integer} initialDelay Number of milliseconds to wait before the first check
33
* @param {Integer} checkInterval Interval between the checks
36
let Downloader = exports.Downloader = function Downloader(dataSource, initialDelay, checkInterval)
38
this.dataSource = dataSource;
39
this._timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
40
this._timer.initWithCallback(function()
42
this._timer.delay = checkInterval;
44
}.bind(this), initialDelay, Ci.nsITimer.TYPE_REPEATING_SLACK);
45
this._downloading = Object.create(null);
47
Downloader.prototype =
50
* Timer triggering the downloads.
56
* Map containing the URLs of objects currently being downloaded as its keys.
61
* Function that will yield downloadable objects on each check.
67
* Maximal time interval that the checks can be left out until the soft
68
* expiration interval increases.
71
maxAbsenceInterval: 1 * MILLIS_IN_DAY,
74
* Minimal time interval before retrying a download after an error.
77
minRetryInterval: 1 * MILLIS_IN_DAY,
80
* Maximal allowed expiration interval, larger expiration intervals will be
84
maxExpirationInterval: 14 * MILLIS_IN_DAY,
87
* Maximal number of redirects before the download is considered as failed.
93
* Called whenever expiration intervals for an object need to be adapted.
96
onExpirationChange: null,
99
* Callback to be triggered whenever a download starts.
102
onDownloadStarted: null,
105
* Callback to be triggered whenever a download finishes successfully. The
106
* callback can return an error code to indicate that the data is wrong.
109
onDownloadSuccess: null,
112
* Callback to be triggered whenever a download fails.
115
onDownloadError: null,
118
* Checks whether anything needs downloading.
122
let now = Date.now();
123
for (let downloadable of this.dataSource())
125
if (downloadable.lastCheck && now - downloadable.lastCheck > this.maxAbsenceInterval)
127
// No checks for a long time interval - user must have been offline, e.g.
128
// during a weekend. Increase soft expiration to prevent load peaks on the
130
downloadable.softExpiration += now - downloadable.lastCheck;
132
downloadable.lastCheck = now;
134
// Sanity check: do expiration times make sense? Make sure people changing
135
// system clock don't get stuck with outdated subscriptions.
136
if (downloadable.hardExpiration - now > this.maxExpirationInterval)
137
downloadable.hardExpiration = now + this.maxExpirationInterval;
138
if (downloadable.softExpiration - now > this.maxExpirationInterval)
139
downloadable.softExpiration = now + this.maxExpirationInterval;
141
// Notify the caller about changes to expiration parameters
142
if (this.onExpirationChange)
143
this.onExpirationChange(downloadable);
145
// Does that object need downloading?
146
if (downloadable.softExpiration > now && downloadable.hardExpiration > now)
149
// Do not retry downloads too often
150
if (downloadable.lastError && now - downloadable.lastError < this.minRetryInterval)
153
this._download(downloadable, 0);
158
* Stops the periodic checks.
162
this._timer.cancel();
166
* Checks whether an address is currently being downloaded.
168
isDownloading: function(/**String*/ url) /**Boolean*/
170
return url in this._downloading;
174
* Starts downloading for an object.
176
download: function(/**Downloadable*/ downloadable)
178
// Make sure to detach download from the current execution context
179
Utils.runAsync(this._download.bind(this, downloadable, 0));
183
* Generates the real download URL for an object by appending various
186
getDownloadUrl: function(/**Downloadable*/ downloadable) /** String*/
188
let {addonName, addonVersion, application, applicationVersion, platform, platformVersion} = require("info");
189
let url = downloadable.redirectURL || downloadable.url;
190
if (url.indexOf("?") >= 0)
194
// We limit the download count to 4+ to keep the request anonymized
195
let downloadCount = downloadable.downloadCount;
196
if (downloadCount > 4)
197
downloadCount = "4+";
198
url += "addonName=" + encodeURIComponent(addonName) +
199
"&addonVersion=" + encodeURIComponent(addonVersion) +
200
"&application=" + encodeURIComponent(application) +
201
"&applicationVersion=" + encodeURIComponent(applicationVersion) +
202
"&platform=" + encodeURIComponent(platform) +
203
"&platformVersion=" + encodeURIComponent(platformVersion) +
204
"&lastVersion=" + encodeURIComponent(downloadable.lastVersion) +
205
"&downloadCount=" + encodeURIComponent(downloadCount);
209
_download: function(downloadable, redirects)
211
if (this.isDownloading(downloadable.url))
214
let downloadUrl = this.getDownloadUrl(downloadable);
217
let errorCallback = function errorCallback(error)
219
let channelStatus = -1;
222
channelStatus = request.channel.status;
225
let responseStatus = request.status;
227
Cu.reportError("Adblock Plus: Downloading URL " + downloadable.url + " failed (" + error + ")\n" +
228
"Download address: " + downloadUrl + "\n" +
229
"Channel status: " + channelStatus + "\n" +
230
"Server response: " + responseStatus);
232
if (this.onDownloadError)
234
// Allow one extra redirect if the error handler gives us a redirect URL
235
let redirectCallback = null;
236
if (redirects <= this.maxRedirects)
238
redirectCallback = function redirectCallback(url)
240
downloadable.redirectURL = url;
241
this._download(downloadable, redirects + 1);
245
this.onDownloadError(downloadable, downloadUrl, error, channelStatus, responseStatus, redirectCallback);
251
request = new XMLHttpRequest();
252
request.mozBackgroundRequest = true;
253
request.open("GET", downloadUrl);
257
errorCallback("synchronize_invalid_url");
262
request.overrideMimeType("text/plain");
263
request.channel.loadFlags = request.channel.loadFlags |
264
request.channel.INHIBIT_CACHING |
265
request.channel.VALIDATE_ALWAYS;
267
// Override redirect limit from preferences, user might have set it to 1
268
if (request.channel instanceof Ci.nsIHttpChannel)
269
request.channel.redirectionLimit = this.maxRedirects;
276
request.addEventListener("error", function(event)
281
delete this._downloading[downloadable.url];
282
errorCallback("synchronize_connection_error");
283
}.bind(this), false);
285
request.addEventListener("load", function(event)
290
delete this._downloading[downloadable.url];
292
// Status will be 0 for non-HTTP requests
293
if (request.status && request.status != 200)
295
errorCallback("synchronize_connection_error");
299
downloadable.downloadCount++;
301
this.onDownloadSuccess(downloadable, request.responseText, errorCallback, function redirectCallback(url)
303
if (redirects >= this.maxRedirects)
304
errorCallback("synchronize_connection_error");
307
downloadable.redirectURL = url;
308
this._download(downloadable, redirects + 1);
311
}.bind(this), false);
315
this._downloading[downloadable.url] = true;
316
if (this.onDownloadStarted)
317
this.onDownloadStarted(downloadable);
321
* Produces a soft and a hard expiration interval for a given supplied
322
* expiration interval.
323
* @return {Array} soft and hard expiration interval
325
processExpirationInterval: function(/**Integer*/ interval)
327
interval = Math.min(Math.max(interval, 0), this.maxExpirationInterval);
328
let soft = Math.round(interval * (Math.random() * 0.4 + 0.8));
329
let hard = interval * 2;
330
let now = Date.now();
331
return [now + soft, now + hard];
336
* An object that can be downloaded by the downloadable
337
* @param {String} url URL that has to be requested for the object
340
let Downloadable = exports.Downloadable = function Downloadable(url)
344
Downloadable.prototype =
347
* URL that has to be requested for the object.
353
* URL that the download was redirected to if any.
359
* Time of last download error or 0 if the last download was successful.
365
* Time of last check whether the object needs downloading.
371
* Object version corresponding to the last successful download.
377
* Soft expiration interval, will increase if no checks are performed for a
384
* Hard expiration interval, this is fixed.
390
* Number indicating how often the object was downloaded.