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

Side by Side Diff: lib/synchronizer.js

Issue 29375915: Issue 4878 - Start using ESLint for adblockpluscore (Closed)
Patch Set: Rebased. Created Feb. 28, 2017, 3:55 p.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
1 /* 1 /*
2 * This file is part of Adblock Plus <https://adblockplus.org/>, 2 * This file is part of Adblock Plus <https://adblockplus.org/>,
3 * Copyright (C) 2006-2016 Eyeo GmbH 3 * Copyright (C) 2006-2016 Eyeo GmbH
4 * 4 *
5 * Adblock Plus is free software: you can redistribute it and/or modify 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 6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation. 7 * published by the Free Software Foundation.
8 * 8 *
9 * Adblock Plus is distributed in the hope that it will be useful, 9 * Adblock Plus is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 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/>. 15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
16 */ 16 */
17 17
18 "use strict";
19
18 /** 20 /**
19 * @fileOverview Manages synchronization of filter subscriptions. 21 * @fileOverview Manages synchronization of filter subscriptions.
20 */ 22 */
21 23
22 Cu.import("resource://gre/modules/XPCOMUtils.jsm"); 24 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
23 Cu.import("resource://gre/modules/Services.jsm"); 25 Cu.import("resource://gre/modules/Services.jsm");
24 26
25 var {Downloader, Downloadable, 27 const {Downloader, Downloadable,
26 MILLIS_IN_SECOND, MILLIS_IN_MINUTE, MILLIS_IN_HOUR, MILLIS_IN_DAY} = require ("downloader"); 28 MILLIS_IN_SECOND, MILLIS_IN_MINUTE,
27 var {Filter, CommentFilter} = require("filterClasses"); 29 MILLIS_IN_HOUR, MILLIS_IN_DAY} = require("downloader");
28 var {FilterStorage} = require("filterStorage"); 30 const {Filter, CommentFilter} = require("filterClasses");
29 var {FilterNotifier} = require("filterNotifier"); 31 const {FilterStorage} = require("filterStorage");
30 var {Prefs} = require("prefs"); 32 const {FilterNotifier} = require("filterNotifier");
31 var {Subscription, DownloadableSubscription} = require("subscriptionClasses"); 33 const {Prefs} = require("prefs");
32 var {Utils} = require("utils"); 34 const {Subscription, DownloadableSubscription} = require("subscriptionClasses");
35 const {Utils} = require("utils");
33 36
34 var INITIAL_DELAY = 1 * MILLIS_IN_MINUTE; 37 let INITIAL_DELAY = 1 * MILLIS_IN_MINUTE;
35 var CHECK_INTERVAL = 1 * MILLIS_IN_HOUR; 38 let CHECK_INTERVAL = 1 * MILLIS_IN_HOUR;
36 var DEFAULT_EXPIRATION_INTERVAL = 5 * MILLIS_IN_DAY; 39 let DEFAULT_EXPIRATION_INTERVAL = 5 * MILLIS_IN_DAY;
Wladimir Palant 2017/03/02 14:07:06 The values declared above are actual constants.
kzar 2017/03/08 12:33:54 Done.
37 40
38 /** 41 /**
39 * The object providing actual downloading functionality. 42 * The object providing actual downloading functionality.
40 * @type Downloader 43 * @type {Downloader}
41 */ 44 */
42 var downloader = null; 45 let downloader = null;
43 46
44 /** 47 /**
45 * This object is responsible for downloading filter subscriptions whenever 48 * This object is responsible for downloading filter subscriptions whenever
46 * necessary. 49 * necessary.
47 * @class 50 * @class
48 */ 51 */
49 var Synchronizer = exports.Synchronizer = 52 let Synchronizer = exports.Synchronizer =
50 { 53 {
51 /** 54 /**
52 * Called on module startup. 55 * Called on module startup.
53 */ 56 */
54 init: function() 57 init()
55 { 58 {
56 downloader = new Downloader(this._getDownloadables.bind(this), INITIAL_DELAY , CHECK_INTERVAL); 59 downloader = new Downloader(this._getDownloadables.bind(this),
57 onShutdown.add(function() 60 INITIAL_DELAY, CHECK_INTERVAL);
61 onShutdown.add(() =>
58 { 62 {
59 downloader.cancel(); 63 downloader.cancel();
60 }); 64 });
61 65
62 downloader.onExpirationChange = this._onExpirationChange.bind(this); 66 downloader.onExpirationChange = this._onExpirationChange.bind(this);
63 downloader.onDownloadStarted = this._onDownloadStarted.bind(this); 67 downloader.onDownloadStarted = this._onDownloadStarted.bind(this);
64 downloader.onDownloadSuccess = this._onDownloadSuccess.bind(this); 68 downloader.onDownloadSuccess = this._onDownloadSuccess.bind(this);
65 downloader.onDownloadError = this._onDownloadError.bind(this); 69 downloader.onDownloadError = this._onDownloadError.bind(this);
66 }, 70 },
67 71
68 /** 72 /**
69 * Checks whether a subscription is currently being downloaded. 73 * Checks whether a subscription is currently being downloaded.
70 * @param {String} url URL of the subscription 74 * @param {string} url URL of the subscription
71 * @return {Boolean} 75 * @return {boolean}
72 */ 76 */
73 isExecuting: function(url) 77 isExecuting(url)
74 { 78 {
75 return downloader.isDownloading(url); 79 return downloader.isDownloading(url);
76 }, 80 },
77 81
78 /** 82 /**
79 * Starts the download of a subscription. 83 * Starts the download of a subscription.
80 * @param {DownloadableSubscription} subscription Subscription to be download ed 84 * @param {DownloadableSubscription} subscription Subscription to be
81 * @param {Boolean} manual true for a manually started download (should not t rigger fallback requests) 85 * downloaded
86 * @param {boolean} manual true for a manually started download
87 * (should not trigger fallback requests)
Wladimir Palant 2017/03/02 14:07:06 Messy indentation here.
kzar 2017/03/08 12:33:53 Done.
82 */ 88 */
83 execute: function(subscription, manual) 89 execute(subscription, manual)
84 { 90 {
85 downloader.download(this._getDownloadable(subscription, manual)); 91 downloader.download(this._getDownloadable(subscription, manual));
86 }, 92 },
87 93
88 /** 94 /**
89 * Yields Downloadable instances for all subscriptions that can be downloaded. 95 * Yields Downloadable instances for all subscriptions that can be downloaded.
90 */ 96 */
91 _getDownloadables: function*() 97 *_getDownloadables()
92 { 98 {
93 if (!Prefs.subscriptions_autoupdate) 99 if (!Prefs.subscriptions_autoupdate)
94 return; 100 return;
95 101
96 for (let subscription of FilterStorage.subscriptions) 102 for (let subscription of FilterStorage.subscriptions)
97 { 103 {
98 if (subscription instanceof DownloadableSubscription) 104 if (subscription instanceof DownloadableSubscription)
99 yield this._getDownloadable(subscription, false); 105 yield this._getDownloadable(subscription, false);
100 } 106 }
101 }, 107 },
102 108
103 /** 109 /**
104 * Creates a Downloadable instance for a subscription. 110 * Creates a Downloadable instance for a subscription.
111 * @param {Subscription} subscription
112 * @param {boolean} manual
113 * @return {Downloadable}
105 */ 114 */
106 _getDownloadable: function(/**Subscription*/ subscription, /**Boolean*/ manual ) /**Downloadable*/ 115 _getDownloadable(subscription, manual)
107 { 116 {
108 let result = new Downloadable(subscription.url); 117 let result = new Downloadable(subscription.url);
109 if (subscription.lastDownload != subscription.lastSuccess) 118 if (subscription.lastDownload != subscription.lastSuccess)
110 result.lastError = subscription.lastDownload * MILLIS_IN_SECOND; 119 result.lastError = subscription.lastDownload * MILLIS_IN_SECOND;
111 result.lastCheck = subscription.lastCheck * MILLIS_IN_SECOND; 120 result.lastCheck = subscription.lastCheck * MILLIS_IN_SECOND;
112 result.lastVersion = subscription.version; 121 result.lastVersion = subscription.version;
113 result.softExpiration = subscription.softExpiration * MILLIS_IN_SECOND; 122 result.softExpiration = subscription.softExpiration * MILLIS_IN_SECOND;
114 result.hardExpiration = subscription.expires * MILLIS_IN_SECOND; 123 result.hardExpiration = subscription.expires * MILLIS_IN_SECOND;
115 result.manual = manual; 124 result.manual = manual;
116 result.downloadCount = subscription.downloadCount; 125 result.downloadCount = subscription.downloadCount;
117 return result; 126 return result;
118 }, 127 },
119 128
120 _onExpirationChange: function(downloadable) 129 _onExpirationChange(downloadable)
121 { 130 {
122 let subscription = Subscription.fromURL(downloadable.url); 131 let subscription = Subscription.fromURL(downloadable.url);
123 subscription.lastCheck = Math.round(downloadable.lastCheck / MILLIS_IN_SECON D); 132 subscription.lastCheck = Math.round(
124 subscription.softExpiration = Math.round(downloadable.softExpiration / MILLI S_IN_SECOND); 133 downloadable.lastCheck / MILLIS_IN_SECOND
125 subscription.expires = Math.round(downloadable.hardExpiration / MILLIS_IN_SE COND); 134 );
135 subscription.softExpiration = Math.round(
136 downloadable.softExpiration / MILLIS_IN_SECOND
137 );
138 subscription.expires = Math.round(
139 downloadable.hardExpiration / MILLIS_IN_SECOND
140 );
126 }, 141 },
127 142
128 _onDownloadStarted: function(downloadable) 143 _onDownloadStarted(downloadable)
129 { 144 {
130 let subscription = Subscription.fromURL(downloadable.url); 145 let subscription = Subscription.fromURL(downloadable.url);
131 FilterNotifier.triggerListeners("subscription.downloading", subscription); 146 FilterNotifier.triggerListeners("subscription.downloading", subscription);
132 }, 147 },
133 148
134 _onDownloadSuccess: function(downloadable, responseText, errorCallback, redire ctCallback) 149 _onDownloadSuccess(downloadable, responseText, errorCallback,
150 redirectCallback)
135 { 151 {
136 let lines = responseText.split(/[\r\n]+/); 152 let lines = responseText.split(/[\r\n]+/);
137 let match = /\[Adblock(?:\s*Plus\s*([\d\.]+)?)?\]/i.exec(lines[0]); 153 let headerMatch = /\[Adblock(?:\s*Plus\s*([\d.]+)?)?\]/i.exec(lines[0]);
138 if (!match) 154 if (!headerMatch)
139 return errorCallback("synchronize_invalid_data"); 155 return errorCallback("synchronize_invalid_data");
140 let minVersion = match[1]; 156 let minVersion = headerMatch[1];
141 157
142 // Don't remove parameter comments immediately but add them to a list first, 158 // Don't remove parameter comments immediately but add them to a list first,
143 // they need to be considered in the checksum calculation. 159 // they need to be considered in the checksum calculation.
144 let remove = []; 160 let remove = [];
145 let params = { 161 let params = {
146 redirect: null, 162 redirect: null,
147 homepage: null, 163 homepage: null,
148 title: null, 164 title: null,
149 version: null, 165 version: null,
150 expires: null 166 expires: null
(...skipping 17 matching lines...) Expand all
168 if (checksum && checksum != value.replace(/=+$/, "")) 184 if (checksum && checksum != value.replace(/=+$/, ""))
169 return errorCallback("synchronize_checksum_mismatch"); 185 return errorCallback("synchronize_checksum_mismatch");
170 } 186 }
171 } 187 }
172 } 188 }
173 189
174 if (params.redirect) 190 if (params.redirect)
175 return redirectCallback(params.redirect); 191 return redirectCallback(params.redirect);
176 192
177 // Handle redirects 193 // Handle redirects
178 let subscription = Subscription.fromURL(downloadable.redirectURL || download able.url); 194 let subscription = Subscription.fromURL(downloadable.redirectURL ||
179 if (downloadable.redirectURL && downloadable.redirectURL != downloadable.url ) 195 downloadable.url);
196 if (downloadable.redirectURL &&
197 downloadable.redirectURL != downloadable.url)
180 { 198 {
181 let oldSubscription = Subscription.fromURL(downloadable.url); 199 let oldSubscription = Subscription.fromURL(downloadable.url);
182 subscription.title = oldSubscription.title; 200 subscription.title = oldSubscription.title;
183 subscription.disabled = oldSubscription.disabled; 201 subscription.disabled = oldSubscription.disabled;
184 subscription.lastCheck = oldSubscription.lastCheck; 202 subscription.lastCheck = oldSubscription.lastCheck;
185 203
186 let listed = (oldSubscription.url in FilterStorage.knownSubscriptions); 204 let listed = (oldSubscription.url in FilterStorage.knownSubscriptions);
187 if (listed) 205 if (listed)
188 FilterStorage.removeSubscription(oldSubscription); 206 FilterStorage.removeSubscription(oldSubscription);
189 207
190 delete Subscription.knownSubscriptions[oldSubscription.url]; 208 delete Subscription.knownSubscriptions[oldSubscription.url];
191 209
192 if (listed) 210 if (listed)
193 FilterStorage.addSubscription(subscription); 211 FilterStorage.addSubscription(subscription);
194 } 212 }
195 213
196 // The download actually succeeded 214 // The download actually succeeded
197 subscription.lastSuccess = subscription.lastDownload = Math.round(Date.now() / MILLIS_IN_SECOND); 215 subscription.lastSuccess = subscription.lastDownload = Math.round(
216 Date.now() / MILLIS_IN_SECOND
217 );
198 subscription.downloadStatus = "synchronize_ok"; 218 subscription.downloadStatus = "synchronize_ok";
199 subscription.downloadCount = downloadable.downloadCount; 219 subscription.downloadCount = downloadable.downloadCount;
200 subscription.errors = 0; 220 subscription.errors = 0;
201 221
202 // Remove lines containing parameters 222 // Remove lines containing parameters
203 for (let i = remove.length - 1; i >= 0; i--) 223 for (let i = remove.length - 1; i >= 0; i--)
204 lines.splice(remove[i], 1); 224 lines.splice(remove[i], 1);
205 225
206 // Process parameters 226 // Process parameters
207 if (params.homepage) 227 if (params.homepage)
(...skipping 29 matching lines...) Expand all
237 if (match) 257 if (match)
238 { 258 {
239 let interval = parseInt(match[1], 10); 259 let interval = parseInt(match[1], 10);
240 if (match[2]) 260 if (match[2])
241 expirationInterval = interval * MILLIS_IN_HOUR; 261 expirationInterval = interval * MILLIS_IN_HOUR;
242 else 262 else
243 expirationInterval = interval * MILLIS_IN_DAY; 263 expirationInterval = interval * MILLIS_IN_DAY;
244 } 264 }
245 } 265 }
246 266
247 let [softExpiration, hardExpiration] = downloader.processExpirationInterval( expirationInterval); 267 let [
268 softExpiration,
269 hardExpiration
270 ] = downloader.processExpirationInterval(expirationInterval);
248 subscription.softExpiration = Math.round(softExpiration / MILLIS_IN_SECOND); 271 subscription.softExpiration = Math.round(softExpiration / MILLIS_IN_SECOND);
249 subscription.expires = Math.round(hardExpiration / MILLIS_IN_SECOND); 272 subscription.expires = Math.round(hardExpiration / MILLIS_IN_SECOND);
250 273
251 if (minVersion) 274 if (minVersion)
252 subscription.requiredVersion = minVersion; 275 subscription.requiredVersion = minVersion;
253 else 276 else
254 delete subscription.requiredVersion; 277 delete subscription.requiredVersion;
255 278
256 // Process filters 279 // Process filters
257 lines.shift(); 280 lines.shift();
258 let filters = []; 281 let filters = [];
259 for (let line of lines) 282 for (let line of lines)
260 { 283 {
261 line = Filter.normalize(line); 284 line = Filter.normalize(line);
262 if (line) 285 if (line)
263 filters.push(Filter.fromText(line)); 286 filters.push(Filter.fromText(line));
264 } 287 }
265 288
266 FilterStorage.updateSubscriptionFilters(subscription, filters); 289 FilterStorage.updateSubscriptionFilters(subscription, filters);
267 290
268 return undefined; 291 return undefined;
269 }, 292 },
270 293
271 _onDownloadError: function(downloadable, downloadURL, error, channelStatus, re sponseStatus, redirectCallback) 294 _onDownloadError(downloadable, downloadURL, error, channelStatus,
295 responseStatus, redirectCallback)
272 { 296 {
273 let subscription = Subscription.fromURL(downloadable.url); 297 let subscription = Subscription.fromURL(downloadable.url);
274 subscription.lastDownload = Math.round(Date.now() / MILLIS_IN_SECOND); 298 subscription.lastDownload = Math.round(Date.now() / MILLIS_IN_SECOND);
275 subscription.downloadStatus = error; 299 subscription.downloadStatus = error;
276 300
277 // Request fallback URL if necessary - for automatic updates only 301 // Request fallback URL if necessary - for automatic updates only
278 if (!downloadable.manual) 302 if (!downloadable.manual)
279 { 303 {
280 subscription.errors++; 304 subscription.errors++;
281 305
282 if (redirectCallback && subscription.errors >= Prefs.subscriptions_fallbac kerrors && /^https?:\/\//i.test(subscription.url)) 306 if (redirectCallback &&
307 subscription.errors >= Prefs.subscriptions_fallbackerrors &&
308 /^https?:\/\//i.test(subscription.url))
283 { 309 {
284 subscription.errors = 0; 310 subscription.errors = 0;
285 311
286 let fallbackURL = Prefs.subscriptions_fallbackurl; 312 let fallbackURL = Prefs.subscriptions_fallbackurl;
287 let {addonVersion} = require("info"); 313 const {addonVersion} = require("info");
288 fallbackURL = fallbackURL.replace(/%VERSION%/g, encodeURIComponent(addon Version)); 314 fallbackURL = fallbackURL.replace(/%VERSION%/g,
289 fallbackURL = fallbackURL.replace(/%SUBSCRIPTION%/g, encodeURIComponent( subscription.url)); 315 encodeURIComponent(addonVersion));
290 fallbackURL = fallbackURL.replace(/%URL%/g, encodeURIComponent(downloadU RL)); 316 fallbackURL = fallbackURL.replace(/%SUBSCRIPTION%/g,
291 fallbackURL = fallbackURL.replace(/%ERROR%/g, encodeURIComponent(error)) ; 317 encodeURIComponent(subscription.url));
292 fallbackURL = fallbackURL.replace(/%CHANNELSTATUS%/g, encodeURIComponent (channelStatus)); 318 fallbackURL = fallbackURL.replace(/%URL%/g,
293 fallbackURL = fallbackURL.replace(/%RESPONSESTATUS%/g, encodeURIComponen t(responseStatus)); 319 encodeURIComponent(downloadURL));
320 fallbackURL = fallbackURL.replace(/%ERROR%/g,
321 encodeURIComponent(error));
322 fallbackURL = fallbackURL.replace(/%CHANNELSTATUS%/g,
323 encodeURIComponent(channelStatus));
324 fallbackURL = fallbackURL.replace(/%RESPONSESTATUS%/g,
325 encodeURIComponent(responseStatus));
294 326
295 let request = new XMLHttpRequest(); 327 let request = new XMLHttpRequest();
296 request.mozBackgroundRequest = true; 328 request.mozBackgroundRequest = true;
297 request.open("GET", fallbackURL); 329 request.open("GET", fallbackURL);
298 request.overrideMimeType("text/plain"); 330 request.overrideMimeType("text/plain");
299 request.channel.loadFlags = request.channel.loadFlags | 331 request.channel.loadFlags = request.channel.loadFlags |
300 request.channel.INHIBIT_CACHING | 332 request.channel.INHIBIT_CACHING |
301 request.channel.VALIDATE_ALWAYS; 333 request.channel.VALIDATE_ALWAYS;
302 request.addEventListener("load", function(ev) 334 request.addEventListener("load", ev =>
303 { 335 {
304 if (onShutdown.done) 336 if (onShutdown.done)
305 return; 337 return;
306 338
307 if (!(subscription.url in FilterStorage.knownSubscriptions)) 339 if (!(subscription.url in FilterStorage.knownSubscriptions))
308 return; 340 return;
309 341
310 let match = /^(\d+)(?:\s+(\S+))?$/.exec(request.responseText); 342 let match = /^(\d+)(?:\s+(\S+))?$/.exec(request.responseText);
311 if (match && match[1] == "301" && match[2] && /^https?:\/\//i.test(mat ch[2])) // Moved permanently 343 if (match && match[1] == "301" && // Moved permanently
344 match[2] && /^https?:\/\//i.test(match[2]))
312 redirectCallback(match[2]); 345 redirectCallback(match[2]);
313 else if (match && match[1] == "410") // Gone 346 else if (match && match[1] == "410") // Gone
314 { 347 {
315 let data = "[Adblock]\n" + subscription.filters.map((f) => f.text).j oin("\n"); 348 let data = "[Adblock]\n" +
349 subscription.filters.map(f => f.text).join("\n");
316 redirectCallback("data:text/plain," + encodeURIComponent(data)); 350 redirectCallback("data:text/plain," + encodeURIComponent(data));
317 } 351 }
318 }, false); 352 }, false);
319 request.send(null); 353 request.send(null);
320 } 354 }
321 } 355 }
322 }, 356 }
323 }; 357 };
324 Synchronizer.init(); 358 Synchronizer.init();
OLDNEW

Powered by Google App Engine
This is Rietveld