uBlock/src/js/assets.js

1247 lines
41 KiB
JavaScript
Raw Normal View History

2014-06-24 00:42:43 +02:00
/*******************************************************************************
µBlock - a Chromium browser extension to block requests.
2015-02-13 18:10:10 +01:00
Copyright (C) 2014-2015 Raymond Hill
2014-06-24 00:42:43 +02:00
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see {http://www.gnu.org/licenses/}.
Home: https://github.com/gorhill/uBlock
*/
2014-12-20 21:28:16 +01:00
/* global vAPI, µBlock, YaMD5 */
2014-06-24 00:42:43 +02:00
/*******************************************************************************
File system structure:
assets
ublock
...
thirdparties
...
user
filters.txt
...
2014-06-24 00:42:43 +02:00
*/
/******************************************************************************/
// Low-level asset files manager
µBlock.assets = (function() {
2014-12-20 21:28:16 +01:00
'use strict';
2014-06-24 00:42:43 +02:00
/******************************************************************************/
2014-09-08 23:46:58 +02:00
var oneSecond = 1000;
var oneMinute = 60 * oneSecond;
var oneHour = 60 * oneMinute;
var oneDay = 24 * oneHour;
/******************************************************************************/
var projectRepositoryRoot = µBlock.projectServerRoot;
var thirdpartiesRepositoryRoot = 'https://raw.githubusercontent.com/gorhill/uAssets/master/src';
2014-07-22 18:26:11 +02:00
var nullFunc = function() {};
2015-02-11 18:44:17 +01:00
var reIsExternalPath = /^[a-z]+:\/\//;
var reIsUserPath = /^assets\/user\//;
2014-08-21 16:56:36 +02:00
var lastRepoMetaTimestamp = 0;
2014-12-20 21:28:16 +01:00
var lastRepoMetaIsRemote = false;
2014-09-08 23:46:58 +02:00
var refreshRepoMetaPeriod = 5 * oneHour;
var errorCantConnectTo = vAPI.i18n('errorCantConnectTo');
2014-09-15 17:09:06 +02:00
var exports = {
autoUpdate: true,
2014-12-20 21:28:16 +01:00
autoUpdateDelay: 4 * oneDay,
// https://github.com/gorhill/uBlock/issues/426
allowRemoteFetch: true
};
/******************************************************************************/
var AssetEntry = function() {
this.localChecksum = '';
this.repoChecksum = '';
this.expireTimestamp = 0;
};
var RepoMetadata = function() {
this.entries = {};
this.waiting = [];
};
2014-08-20 15:24:16 +02:00
var repoMetadata = null;
2014-06-24 00:42:43 +02:00
2014-12-21 06:07:08 +01:00
// We need these to persist beyond repoMetaData
var homeURLs = {};
2014-06-24 00:42:43 +02:00
/******************************************************************************/
2014-12-20 21:28:16 +01:00
var stringIsNotEmpty = function(s) {
return typeof s === 'string' && s !== '';
};
/******************************************************************************/
var cacheIsObsolete = function(t) {
return typeof t !== 'number' || (Date.now() - t) >= exports.autoUpdateDelay;
};
/******************************************************************************/
2014-07-22 18:26:11 +02:00
var cachedAssetsManager = (function() {
var exports = {};
var entries = null;
var cachedAssetPathPrefix = 'cached_asset_content://';
var getEntries = function(callback) {
if ( entries !== null ) {
callback(entries);
return;
}
// Flush cached non-user assets if these are from a prior version.
// https://github.com/gorhill/httpswitchboard/issues/212
var onLastVersionRead = function(store) {
var currentVersion = vAPI.app.version;
var lastVersion = store.extensionLastVersion || '0.0.0.0';
if ( currentVersion !== lastVersion ) {
vAPI.storage.set({ 'extensionLastVersion': currentVersion });
}
callback(entries);
};
2014-07-22 18:26:11 +02:00
var onLoaded = function(bin) {
// https://github.com/gorhill/httpswitchboard/issues/381
// Maybe the index was requested multiple times and already
// fetched by one of the occurrences.
if ( entries === null ) {
var lastError = vAPI.lastError();
if ( lastError ) {
console.error(
'µBlock> cachedAssetsManager> getEntries():',
lastError.message
);
}
entries = bin.cached_asset_entries || {};
2014-07-22 18:26:11 +02:00
}
vAPI.storage.get('extensionLastVersion', onLastVersionRead);
2014-07-22 18:26:11 +02:00
};
vAPI.storage.get('cached_asset_entries', onLoaded);
2014-07-22 18:26:11 +02:00
};
2014-07-26 22:10:20 +02:00
exports.entries = getEntries;
2014-07-22 18:26:11 +02:00
exports.load = function(path, cbSuccess, cbError) {
cbSuccess = cbSuccess || nullFunc;
cbError = cbError || cbSuccess;
var details = {
'path': path,
'content': ''
};
var cachedContentPath = cachedAssetPathPrefix + path;
var onLoaded = function(bin) {
var lastError = vAPI.lastError();
if ( lastError ) {
details.error = 'Error: ' + lastError.message;
2014-07-22 18:26:11 +02:00
console.error('µBlock> cachedAssetsManager.load():', details.error);
cbError(details);
2014-12-08 17:16:13 +01:00
return;
}
// Not sure how this can happen, but I've seen it happen. It could
// be because the save occurred while I was stepping in the code
// though, which means it would not occur during normal operation.
// Still, just to be safe.
2014-12-20 21:28:16 +01:00
if ( stringIsNotEmpty(bin[cachedContentPath]) === false ) {
exports.remove(path);
2014-12-08 17:16:13 +01:00
details.error = 'Error: not found';
cbError(details);
return;
2014-07-22 18:26:11 +02:00
}
2014-12-08 17:16:13 +01:00
details.content = bin[cachedContentPath];
cbSuccess(details);
2014-07-22 18:26:11 +02:00
};
var onEntries = function(entries) {
if ( entries[path] === undefined ) {
details.error = 'Error: not found';
cbError(details);
return;
}
vAPI.storage.get(cachedContentPath, onLoaded);
2014-07-22 18:26:11 +02:00
};
getEntries(onEntries);
};
exports.save = function(path, content, cbSuccess, cbError) {
cbSuccess = cbSuccess || nullFunc;
cbError = cbError || cbSuccess;
var details = {
path: path,
content: content
};
2014-12-20 21:28:16 +01:00
if ( content === '' ) {
exports.remove(path);
cbSuccess(details);
return;
}
2014-07-22 18:26:11 +02:00
var cachedContentPath = cachedAssetPathPrefix + path;
var bin = {};
bin[cachedContentPath] = content;
var onSaved = function() {
var lastError = vAPI.lastError();
if ( lastError ) {
details.error = 'Error: ' + lastError.message;
2014-07-22 18:26:11 +02:00
console.error('µBlock> cachedAssetsManager.save():', details.error);
cbError(details);
} else {
cbSuccess(details);
}
};
var onEntries = function(entries) {
entries[path] = Date.now();
bin.cached_asset_entries = entries;
vAPI.storage.set(bin, onSaved);
2014-07-22 18:26:11 +02:00
};
getEntries(onEntries);
};
2014-07-25 22:12:20 +02:00
exports.remove = function(pattern, before) {
2014-07-22 18:26:11 +02:00
var onEntries = function(entries) {
var keystoRemove = [];
var paths = Object.keys(entries);
var i = paths.length;
var path;
while ( i-- ) {
path = paths[i];
if ( typeof pattern === 'string' && path !== pattern ) {
continue;
}
if ( pattern instanceof RegExp && !pattern.test(path) ) {
continue;
}
2014-07-25 22:12:20 +02:00
if ( typeof before === 'number' && entries[path] >= before ) {
continue;
}
2014-07-22 18:26:11 +02:00
keystoRemove.push(cachedAssetPathPrefix + path);
delete entries[path];
}
if ( keystoRemove.length ) {
vAPI.storage.remove(keystoRemove);
vAPI.storage.set({ 'cached_asset_entries': entries });
2014-07-22 18:26:11 +02:00
}
};
getEntries(onEntries);
};
2014-09-09 01:45:22 +02:00
exports.removeAll = function(callback) {
var onEntries = function() {
exports.remove(/^https?:\/\/[a-z0-9]+/);
exports.remove(/^assets\/(ublock|thirdparties)\//);
exports.remove('assets/checksums.txt');
if ( typeof callback === 'function' ) {
callback(null);
2014-09-09 01:45:22 +02:00
}
};
getEntries(onEntries);
};
2014-07-22 18:26:11 +02:00
return exports;
})();
/******************************************************************************/
2014-06-24 00:42:43 +02:00
var getTextFileFromURL = function(url, onLoad, onError) {
// https://github.com/gorhill/uMatrix/issues/15
var onResponseReceived = function() {
if ( this.status !== 0 && ( this.status < 200 || this.status >= 300 ) ) {
2015-02-15 13:16:31 +01:00
return onError.call(this);
}
// xhr for local files gives status 0, but actually succeeds
2015-02-15 13:16:31 +01:00
if ( this.status === 0 && stringIsNotEmpty(this.responseText) === false ) {
return onError.call(this);
}
// we never download anything else than plain text: discard if response
// appears to be a HTML document: could happen when server returns
// some kind of error page I suppose
var text = this.responseText.trim();
if ( text.charAt(0) === '<' && text.slice(-1) === '>' ) {
return onError.call(this);
}
2015-02-15 13:16:31 +01:00
return onLoad.call(this);
};
2014-06-24 00:42:43 +02:00
// console.log('µBlock> getTextFileFromURL("%s"):', url);
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
2015-02-13 18:10:10 +01:00
xhr.timeout = 30000;
xhr.onload = onResponseReceived;
2014-06-24 00:42:43 +02:00
xhr.onerror = onError;
xhr.ontimeout = onError;
xhr.responseType = 'text';
2014-06-24 00:42:43 +02:00
xhr.send();
};
/******************************************************************************/
var updateLocalChecksums = function() {
var localChecksums = [];
2014-08-20 15:24:16 +02:00
var entries = repoMetadata.entries;
var entry;
for ( var path in entries ) {
if ( entries.hasOwnProperty(path) === false ) {
continue;
}
entry = entries[path];
if ( entry.localChecksum !== '' ) {
localChecksums.push(entry.localChecksum + ' ' + path);
}
}
cachedAssetsManager.save('assets/checksums.txt', localChecksums.join('\n'));
2014-06-24 00:42:43 +02:00
};
/******************************************************************************/
// Gather meta data of all assets.
2014-08-21 16:56:36 +02:00
var getRepoMetadata = function(callback) {
callback = callback || nullFunc;
2014-07-22 18:26:11 +02:00
2015-01-16 16:57:56 +01:00
// https://github.com/gorhill/uBlock/issues/515
// Handle re-entrancy here, i.e. we MUST NOT tamper with the waiting list
// of callers, if any, except to add one at the end of the list.
if ( repoMetadata !== null && repoMetadata.waiting.length !== 0 ) {
repoMetadata.waiting.push(callback);
return;
}
2014-12-20 21:28:16 +01:00
if ( exports.allowRemoteFetch && lastRepoMetaIsRemote === false ) {
lastRepoMetaTimestamp = 0;
}
2014-08-21 16:56:36 +02:00
if ( (Date.now() - lastRepoMetaTimestamp) >= refreshRepoMetaPeriod ) {
2014-08-20 15:24:16 +02:00
repoMetadata = null;
}
2014-08-20 15:24:16 +02:00
if ( repoMetadata !== null ) {
2015-01-16 16:57:56 +01:00
callback(repoMetadata);
2014-06-24 00:42:43 +02:00
return;
}
2014-08-21 16:56:36 +02:00
lastRepoMetaTimestamp = Date.now();
2014-12-20 21:28:16 +01:00
lastRepoMetaIsRemote = exports.allowRemoteFetch;
2014-08-21 16:56:36 +02:00
2014-08-20 15:24:16 +02:00
var localChecksums;
var repoChecksums;
2014-07-22 18:26:11 +02:00
var checksumsReceived = function() {
2014-08-20 15:24:16 +02:00
if ( localChecksums === undefined || repoChecksums === undefined ) {
return;
2014-06-24 00:42:43 +02:00
}
2014-08-20 15:24:16 +02:00
// Remove from cache assets which no longer exist in the repo
var entries = repoMetadata.entries;
var checksumsChanged = false;
2014-06-24 00:42:43 +02:00
var entry;
for ( var path in entries ) {
if ( entries.hasOwnProperty(path) === false ) {
continue;
}
entry = entries[path];
// If repo checksums could not be fetched, assume no change
if ( repoChecksums === '' ) {
entry.repoChecksum = entry.localChecksum;
}
if ( entry.repoChecksum !== '' || entry.localChecksum === '' ) {
continue;
}
checksumsChanged = true;
cachedAssetsManager.remove(path);
entry.localChecksum = '';
}
if ( checksumsChanged ) {
updateLocalChecksums();
}
// Notify all waiting callers
2015-01-16 16:57:56 +01:00
// https://github.com/gorhill/uBlock/issues/515
// VERY IMPORTANT: because of re-entrancy, we MUST:
// - process the waiting callers in a FIFO manner
// - not cache repoMetadata.waiting.length, we MUST use the live
// value, because it can change while looping
// - not change the waiting list until they are all processed
for ( var i = 0; i < repoMetadata.waiting.length; i++ ) {
repoMetadata.waiting[i](repoMetadata);
2014-06-24 00:42:43 +02:00
}
2015-01-16 16:57:56 +01:00
repoMetadata.waiting.length = 0;
2014-06-24 00:42:43 +02:00
};
var validateChecksums = function(details) {
if ( details.error || details.content === '' ) {
return '';
}
if ( /^(?:[0-9a-f]{32}\s+\S+(?:\s+|$))+/.test(details.content) === false ) {
return '';
}
return details.content;
2014-06-24 00:42:43 +02:00
};
var parseChecksums = function(text, which) {
2014-08-20 15:24:16 +02:00
var entries = repoMetadata.entries;
var lines = text.split(/\n+/);
var i = lines.length;
var fields, assetPath;
while ( i-- ) {
fields = lines[i].trim().split(/\s+/);
if ( fields.length !== 2 ) {
continue;
}
assetPath = fields[1];
if ( entries[assetPath] === undefined ) {
entries[assetPath] = new AssetEntry();
}
entries[assetPath][which + 'Checksum'] = fields[0];
2014-06-24 00:42:43 +02:00
}
};
var onLocalChecksumsLoaded = function(details) {
if ( localChecksums = validateChecksums(details) ) {
parseChecksums(localChecksums, 'local');
}
checksumsReceived();
2014-07-22 18:26:11 +02:00
};
var onRepoChecksumsLoaded = function(details) {
if ( repoChecksums = validateChecksums(details) ) {
parseChecksums(repoChecksums, 'repo');
2014-07-22 18:26:11 +02:00
}
checksumsReceived();
2014-07-22 18:26:11 +02:00
};
2014-08-20 15:24:16 +02:00
repoMetadata = new RepoMetadata();
repoMetadata.waiting.push(callback);
readRepoFile('assets/checksums.txt', onRepoChecksumsLoaded);
readLocalFile('assets/checksums.txt', onLocalChecksumsLoaded);
2014-06-24 00:42:43 +02:00
};
// https://www.youtube.com/watch?v=-t3WYfgM4x8
2014-06-24 00:42:43 +02:00
/******************************************************************************/
exports.setHomeURL = function(path, homeURL) {
2014-12-21 06:07:08 +01:00
homeURLs[path] = homeURL;
};
/******************************************************************************/
2014-08-20 15:24:16 +02:00
// Get a local asset, do not look-up repo or remote location if local asset
// is not found.
2014-06-24 00:42:43 +02:00
var readLocalFile = function(path, callback) {
var reportBack = function(content, err) {
var details = {
'path': path,
2014-07-22 18:26:11 +02:00
'content': content
2014-06-24 00:42:43 +02:00
};
2014-07-22 18:26:11 +02:00
if ( err ) {
details.error = err;
}
2014-06-24 00:42:43 +02:00
callback(details);
};
2014-08-20 15:24:16 +02:00
var onInstallFileLoaded = function() {
this.onload = this.onerror = null;
2014-08-21 16:56:36 +02:00
//console.log('µBlock> readLocalFile("%s") / onInstallFileLoaded()', path);
2014-06-24 00:42:43 +02:00
reportBack(this.responseText);
};
2014-08-20 15:24:16 +02:00
var onInstallFileError = function() {
this.onload = this.onerror = null;
2014-08-20 15:24:16 +02:00
console.error('µBlock> readLocalFile("%s") / onInstallFileError()', path);
2014-06-24 00:42:43 +02:00
reportBack('', 'Error');
};
2014-09-04 02:55:16 +02:00
var onCachedContentLoaded = function(details) {
//console.log('µBlock> readLocalFile("%s") / onCachedContentLoaded()', path);
reportBack(details.content);
};
2014-09-05 22:15:42 +02:00
2014-09-04 02:55:16 +02:00
var onCachedContentError = function(details) {
//console.error('µBlock> readLocalFile("%s") / onCachedContentError()', path);
if ( reIsExternalPath.test(path) ) {
reportBack('', 'Error: asset not found');
return;
}
2014-09-05 22:15:42 +02:00
// It's ok for user data to not be found
2014-09-04 02:55:16 +02:00
if ( reIsUserPath.test(path) ) {
reportBack('');
2014-08-20 15:24:16 +02:00
return;
}
getTextFileFromURL(vAPI.getURL(details.path), onInstallFileLoaded, onInstallFileError);
2014-06-24 00:42:43 +02:00
};
2014-09-04 02:55:16 +02:00
cachedAssetsManager.load(path, onCachedContentLoaded, onCachedContentError);
2014-06-24 00:42:43 +02:00
};
2014-08-20 15:24:16 +02:00
// https://www.youtube.com/watch?v=r9KVpuFPtHc
2014-06-24 00:42:43 +02:00
/******************************************************************************/
2014-07-25 22:12:20 +02:00
// Get the repository copy of a built-in asset.
var readRepoFile = function(path, callback) {
2014-12-20 21:28:16 +01:00
// https://github.com/gorhill/uBlock/issues/426
if ( exports.allowRemoteFetch === false ) {
readLocalFile(path, callback);
return;
}
2014-06-24 00:42:43 +02:00
var reportBack = function(content, err) {
var details = {
'path': path,
'content': content,
'error': err
};
callback(details);
};
var repositoryURL = projectRepositoryRoot + path;
2014-09-15 17:09:06 +02:00
2014-07-25 22:12:20 +02:00
var onRepoFileLoaded = function() {
this.onload = this.onerror = null;
2014-08-21 16:56:36 +02:00
//console.log('µBlock> readRepoFile("%s") / onRepoFileLoaded()', path);
2014-06-24 00:42:43 +02:00
// https://github.com/gorhill/httpswitchboard/issues/263
if ( this.status === 200 ) {
reportBack(this.responseText);
} else {
2014-08-21 01:39:49 +02:00
reportBack('', 'Error: ' + this.statusText);
2014-06-24 00:42:43 +02:00
}
};
var onRepoFileError = function() {
this.onload = this.onerror = null;
2014-09-15 17:09:06 +02:00
console.error(errorCantConnectTo.replace('{{url}}', repositoryURL));
2014-06-24 00:42:43 +02:00
reportBack('', 'Error');
};
// 'ublock=...' is to skip browser cache
getTextFileFromURL(
2014-09-15 17:09:06 +02:00
repositoryURL + '?ublock=' + Date.now(),
2014-07-25 22:12:20 +02:00
onRepoFileLoaded,
onRepoFileError
2014-07-22 18:26:11 +02:00
);
2014-06-24 00:42:43 +02:00
};
/******************************************************************************/
// An asset from an external source with a copy shipped with the extension:
// Path --> starts with 'assets/(thirdparties|ublock)/', with a home URL
// External -->
// Repository --> has checksum (to detect need for update only)
// Cache --> has expiration timestamp (in cache)
// Local --> install time version
2014-07-25 22:12:20 +02:00
var readRepoCopyAsset = function(path, callback) {
var assetEntry;
2014-12-21 06:07:08 +01:00
var homeURL = homeURLs[path];
2014-07-25 22:12:20 +02:00
var reportBack = function(content, err) {
var details = {
'path': path,
'content': content
};
if ( err ) {
details.error = err;
}
callback(details);
};
2014-06-24 00:42:43 +02:00
var updateChecksum = function() {
2014-08-21 01:39:49 +02:00
if ( assetEntry !== undefined && assetEntry.repoChecksum !== assetEntry.localChecksum ) {
assetEntry.localChecksum = assetEntry.repoChecksum;
updateLocalChecksums();
}
};
2014-06-24 00:42:43 +02:00
var onInstallFileLoaded = function() {
this.onload = this.onerror = null;
2014-08-21 16:56:36 +02:00
//console.log('µBlock> readRepoCopyAsset("%s") / onInstallFileLoaded()', path);
reportBack(this.responseText);
};
var onInstallFileError = function() {
this.onload = this.onerror = null;
console.error('µBlock> readRepoCopyAsset("%s") / onInstallFileError():', path, this.statusText);
reportBack('', 'Error');
};
var onCachedContentLoaded = function(details) {
2014-08-21 16:56:36 +02:00
//console.log('µBlock> readRepoCopyAsset("%s") / onCacheFileLoaded()', path);
reportBack(details.content);
};
2014-06-24 00:42:43 +02:00
var onCachedContentError = function(details) {
2014-08-21 16:56:36 +02:00
//console.log('µBlock> readRepoCopyAsset("%s") / onCacheFileError()', path);
getTextFileFromURL(vAPI.getURL(details.path), onInstallFileLoaded, onInstallFileError);
2014-06-24 00:42:43 +02:00
};
var repositoryURL = projectRepositoryRoot + path;
2014-09-15 17:09:06 +02:00
var repositoryURLSkipCache = repositoryURL + '?ublock=' + Date.now();
2014-07-20 23:32:43 +02:00
var onRepoFileLoaded = function() {
2014-06-24 00:42:43 +02:00
this.onload = this.onerror = null;
2014-12-20 21:28:16 +01:00
if ( stringIsNotEmpty(this.responseText) === false ) {
2014-08-21 01:39:49 +02:00
console.error('µBlock> readRepoCopyAsset("%s") / onRepoFileLoaded("%s"): error', path, repositoryURL);
cachedAssetsManager.load(path, onCachedContentLoaded, onCachedContentError);
2014-06-24 00:42:43 +02:00
return;
}
2014-08-21 16:56:36 +02:00
//console.log('µBlock> readRepoCopyAsset("%s") / onRepoFileLoaded("%s")', path, repositoryURL);
updateChecksum();
cachedAssetsManager.save(path, this.responseText, callback);
2014-06-24 00:42:43 +02:00
};
var onRepoFileError = function() {
2014-06-24 00:42:43 +02:00
this.onload = this.onerror = null;
2014-09-15 17:09:06 +02:00
console.error(errorCantConnectTo.replace('{{url}}', repositoryURL));
cachedAssetsManager.load(path, onCachedContentLoaded, onCachedContentError);
2014-06-24 00:42:43 +02:00
};
2014-07-20 21:00:26 +02:00
var onHomeFileLoaded = function() {
this.onload = this.onerror = null;
2014-12-20 21:28:16 +01:00
if ( stringIsNotEmpty(this.responseText) === false ) {
2014-12-21 06:07:08 +01:00
console.error('µBlock> readRepoCopyAsset("%s") / onHomeFileLoaded("%s"): no response', path, homeURL);
// Fetch from repo only if obsolescence was due to repo checksum
if ( assetEntry.localChecksum !== assetEntry.repoChecksum ) {
2014-09-15 17:09:06 +02:00
getTextFileFromURL(repositoryURLSkipCache, onRepoFileLoaded, onRepoFileError);
} else {
cachedAssetsManager.load(path, onCachedContentLoaded, onCachedContentError);
}
2014-07-20 21:00:26 +02:00
return;
}
2014-12-21 06:07:08 +01:00
//console.log('µBlock> readRepoCopyAsset("%s") / onHomeFileLoaded("%s")', path, homeURL);
updateChecksum();
cachedAssetsManager.save(path, this.responseText, callback);
};
var onHomeFileError = function() {
this.onload = this.onerror = null;
2014-12-21 06:07:08 +01:00
console.error(errorCantConnectTo.replace('{{url}}', homeURL));
// Fetch from repo only if obsolescence was due to repo checksum
if ( assetEntry.localChecksum !== assetEntry.repoChecksum ) {
2014-09-15 17:09:06 +02:00
getTextFileFromURL(repositoryURLSkipCache, onRepoFileLoaded, onRepoFileError);
} else {
cachedAssetsManager.load(path, onCachedContentLoaded, onCachedContentError);
}
};
var onCacheMetaReady = function(entries) {
2014-08-21 01:39:49 +02:00
// Fetch from remote if:
// - Auto-update enabled AND (not in cache OR in cache but obsolete)
2014-09-08 23:46:58 +02:00
var timestamp = entries[path];
2014-12-20 21:28:16 +01:00
var inCache = typeof timestamp === 'number';
2014-12-21 06:07:08 +01:00
if ( exports.allowRemoteFetch && exports.autoUpdate && stringIsNotEmpty(homeURL) ) {
2014-12-20 21:28:16 +01:00
if ( inCache === false || cacheIsObsolete(timestamp) ) {
//console.log('µBlock> readRepoCopyAsset("%s") / onCacheMetaReady(): not cached or obsolete', path);
2014-12-21 06:07:08 +01:00
getTextFileFromURL(homeURL, onHomeFileLoaded, onHomeFileError);
return;
}
2014-08-21 01:39:49 +02:00
}
// In cache
2014-12-20 21:28:16 +01:00
if ( inCache ) {
cachedAssetsManager.load(path, onCachedContentLoaded, onCachedContentError);
2014-07-20 21:00:26 +02:00
return;
}
2014-08-21 01:39:49 +02:00
// Not in cache
getTextFileFromURL(vAPI.getURL(path), onInstallFileLoaded, onInstallFileError);
2014-07-20 21:00:26 +02:00
};
var onRepoMetaReady = function(meta) {
assetEntry = meta.entries[path];
// Asset doesn't exist
if ( assetEntry === undefined ) {
2014-08-21 01:39:49 +02:00
reportBack('', 'Error: asset not found');
return;
}
// Repo copy changed: fetch from home URL
2014-12-20 21:28:16 +01:00
if ( exports.allowRemoteFetch && exports.autoUpdate && assetEntry.localChecksum !== assetEntry.repoChecksum ) {
2014-08-21 16:56:36 +02:00
//console.log('µBlock> readRepoCopyAsset("%s") / onRepoMetaReady(): repo has newer version', path);
2014-12-20 21:28:16 +01:00
if ( stringIsNotEmpty(homeURL) ) {
getTextFileFromURL(homeURL, onHomeFileLoaded, onHomeFileError);
} else {
2014-09-15 17:09:06 +02:00
getTextFileFromURL(repositoryURLSkipCache, onRepoFileLoaded, onRepoFileError);
}
2014-08-21 01:39:49 +02:00
return;
}
2014-08-21 01:39:49 +02:00
// Load from cache
cachedAssetsManager.entries(onCacheMetaReady);
};
2014-08-20 15:24:16 +02:00
getRepoMetadata(onRepoMetaReady);
};
// https://www.youtube.com/watch?v=uvUW4ozs7pY
/******************************************************************************/
// An important asset shipped with the extension -- typically small, or
// doesn't change often:
// Path --> starts with 'assets/(thirdparties|ublock)/', without a home URL
// Repository --> has checksum (to detect need for update and corruption)
// Cache --> whatever from above
// Local --> install time version
var readRepoOnlyAsset = function(path, callback) {
var assetEntry;
var reportBack = function(content, err) {
var details = {
'path': path,
'content': content
};
if ( err ) {
details.error = err;
}
callback(details);
};
var onInstallFileLoaded = function() {
2014-07-20 21:00:26 +02:00
this.onload = this.onerror = null;
2014-08-21 16:56:36 +02:00
//console.log('µBlock> readRepoOnlyAsset("%s") / onInstallFileLoaded()', path);
reportBack(this.responseText);
2014-07-20 21:00:26 +02:00
};
var onInstallFileError = function() {
this.onload = this.onerror = null;
console.error('µBlock> readRepoOnlyAsset("%s") / onInstallFileError()', path);
reportBack('', 'Error');
};
var onCachedContentLoaded = function(details) {
2014-08-21 16:56:36 +02:00
//console.log('µBlock> readRepoOnlyAsset("%s") / onCachedContentLoaded()', path);
reportBack(details.content);
};
var onCachedContentError = function() {
2014-08-21 16:56:36 +02:00
//console.log('µBlock> readRepoOnlyAsset("%s") / onCachedContentError()', path);
getTextFileFromURL(vAPI.getURL(path), onInstallFileLoaded, onInstallFileError);
};
var repositoryURL = projectRepositoryRoot + path + '?ublock=' + Date.now();
var onRepoFileLoaded = function() {
this.onload = this.onerror = null;
if ( typeof this.responseText !== 'string' ) {
console.error('µBlock> readRepoOnlyAsset("%s") / onRepoFileLoaded("%s"): no response', path, repositoryURL);
cachedAssetsManager.load(path, onCachedContentLoaded, onCachedContentError);
return;
2014-07-20 21:00:26 +02:00
}
if ( YaMD5.hashStr(this.responseText) !== assetEntry.repoChecksum ) {
console.error('µBlock> readRepoOnlyAsset("%s") / onRepoFileLoaded("%s"): bad md5 checksum', path, repositoryURL);
cachedAssetsManager.load(path, onCachedContentLoaded, onCachedContentError);
2014-07-20 21:00:26 +02:00
return;
}
2014-08-21 16:56:36 +02:00
//console.log('µBlock> readRepoOnlyAsset("%s") / onRepoFileLoaded("%s")', path, repositoryURL);
assetEntry.localChecksum = assetEntry.repoChecksum;
updateLocalChecksums();
cachedAssetsManager.save(path, this.responseText, callback);
2014-07-20 21:00:26 +02:00
};
var onRepoFileError = function() {
this.onload = this.onerror = null;
2014-09-15 17:09:06 +02:00
console.error(errorCantConnectTo.replace('{{url}}', repositoryURL));
cachedAssetsManager.load(path, onCachedContentLoaded, onCachedContentError);
};
var onRepoMetaReady = function(meta) {
assetEntry = meta.entries[path];
// Asset doesn't exist
if ( assetEntry === undefined ) {
2014-08-21 01:39:49 +02:00
reportBack('', 'Error: asset not found');
2014-07-20 21:00:26 +02:00
return;
}
// Asset added or changed: load from repo URL and then cache result
2014-12-20 21:28:16 +01:00
if ( exports.allowRemoteFetch && exports.autoUpdate && assetEntry.localChecksum !== assetEntry.repoChecksum ) {
2014-08-21 16:56:36 +02:00
//console.log('µBlock> readRepoOnlyAsset("%s") / onRepoMetaReady(): repo has newer version', path);
2014-08-21 01:39:49 +02:00
getTextFileFromURL(repositoryURL, onRepoFileLoaded, onRepoFileError);
return;
}
2014-08-21 01:39:49 +02:00
// Load from cache
cachedAssetsManager.load(path, onCachedContentLoaded, onCachedContentError);
};
2014-08-20 15:24:16 +02:00
getRepoMetadata(onRepoMetaReady);
};
/******************************************************************************/
// Asset doesn't exist. Just for symmetry purpose.
var readNilAsset = function(path, callback) {
callback({
'path': path,
'content': '',
'error': 'Error: asset not found'
});
};
/******************************************************************************/
// An external asset:
// Path --> starts with 'http'
// External --> https://..., http://...
// Cache --> has expiration timestamp (in cache)
var readExternalAsset = function(path, callback) {
var reportBack = function(content, err) {
var details = {
'path': path,
'content': content
};
if ( err ) {
details.error = err;
}
callback(details);
};
var onCachedContentLoaded = function(details) {
2014-08-21 16:56:36 +02:00
//console.log('µBlock> readExternalAsset("%s") / onCachedContentLoaded()', path);
reportBack(details.content);
};
var onCachedContentError = function() {
console.error('µBlock> readExternalAsset("%s") / onCachedContentError()', path);
reportBack('', 'Error');
};
var onExternalFileLoaded = function() {
this.onload = this.onerror = null;
2015-02-06 18:20:30 +01:00
// https://github.com/gorhill/uBlock/issues/708
// A successful download should never return an empty file: turn this
// into an error condition.
if ( stringIsNotEmpty(this.responseText) === false ) {
onExternalFileError();
return;
}
2014-08-21 16:56:36 +02:00
//console.log('µBlock> readExternalAsset("%s") / onExternalFileLoaded1()', path);
cachedAssetsManager.save(path, this.responseText);
reportBack(this.responseText);
};
2014-08-21 01:39:49 +02:00
var onExternalFileError = function() {
this.onload = this.onerror = null;
2014-09-15 17:09:06 +02:00
console.error(errorCantConnectTo.replace('{{url}}', path));
cachedAssetsManager.load(path, onCachedContentLoaded, onCachedContentError);
};
2014-08-21 01:39:49 +02:00
var onCacheMetaReady = function(entries) {
// Fetch from remote if:
// - Not in cache OR
//
2014-08-21 01:39:49 +02:00
// - Auto-update enabled AND in cache but obsolete
var timestamp = entries[path];
2014-12-20 21:28:16 +01:00
var notInCache = typeof timestamp !== 'number';
var updateCache = exports.allowRemoteFetch && exports.autoUpdate && cacheIsObsolete(timestamp);
if ( notInCache || updateCache ) {
2014-08-21 01:39:49 +02:00
getTextFileFromURL(path, onExternalFileLoaded, onExternalFileError);
return;
2014-07-20 21:00:26 +02:00
}
2014-08-21 01:39:49 +02:00
// In cache
cachedAssetsManager.load(path, onCachedContentLoaded, onCachedContentError);
};
2014-08-21 01:39:49 +02:00
cachedAssetsManager.entries(onCacheMetaReady);
};
/******************************************************************************/
// User data:
// Path --> starts with 'assets/user/'
// Cache --> whatever user saved
var readUserAsset = function(path, callback) {
var onCachedContentLoaded = function(details) {
2014-08-21 16:56:36 +02:00
//console.log('µBlock> readUserAsset("%s") / onCachedContentLoaded()', path);
callback({ 'path': path, 'content': details.content });
};
var onCachedContentError = function() {
2014-08-21 16:56:36 +02:00
//console.log('µBlock> readUserAsset("%s") / onCachedContentError()', path);
callback({ 'path': path, 'content': '' });
2014-07-20 21:00:26 +02:00
};
cachedAssetsManager.load(path, onCachedContentLoaded, onCachedContentError);
};
/******************************************************************************/
// Assets
//
// A copy of an asset from an external source shipped with the extension:
// Path --> starts with 'assets/(thirdparties|ublock)/', with a home URL
// External -->
// Repository --> has checksum (to detect obsolescence)
// Cache --> has expiration timestamp (to detect obsolescence)
// Local --> install time version
//
// An important asset shipped with the extension (usually small, or doesn't
// change often):
// Path --> starts with 'assets/(thirdparties|ublock)/', without a home URL
// Repository --> has checksum (to detect obsolescence or data corruption)
// Cache --> whatever from above
// Local --> install time version
//
// An external filter list:
// Path --> starts with 'http'
// External -->
// Cache --> has expiration timestamp (to detect obsolescence)
//
// User data:
// Path --> starts with 'assets/user/'
// Cache --> whatever user saved
//
// When a checksum is present, it is used to determine whether the asset
// needs to be updated.
// When an expiration timestamp is present, it is used to determine whether
// the asset needs to be updated.
//
// If no update required, an asset if first fetched from the cache. If the
// asset is not cached it is fetched from the closest location: local for
// an asset shipped with the extension, external for an asset not shipped
// with the extension.
exports.get = function(path, callback) {
if ( reIsUserPath.test(path) ) {
readUserAsset(path, callback);
return;
2014-07-20 21:00:26 +02:00
}
if ( reIsExternalPath.test(path) ) {
readExternalAsset(path, callback);
return;
}
var onRepoMetaReady = function(meta) {
var assetEntry = meta.entries[path];
// Asset doesn't exist
if ( assetEntry === undefined ) {
readNilAsset(path, callback);
return;
}
// Asset is repo copy of external content
2014-12-21 06:07:08 +01:00
if ( stringIsNotEmpty(homeURLs[path]) ) {
readRepoCopyAsset(path, callback);
return;
}
// Asset is repo only
readRepoOnlyAsset(path, callback);
};
2014-08-20 15:24:16 +02:00
getRepoMetadata(onRepoMetaReady);
2014-06-24 00:42:43 +02:00
};
// https://www.youtube.com/watch?v=98y0Q7nLGWk
2014-06-24 00:42:43 +02:00
/******************************************************************************/
2014-08-21 01:39:49 +02:00
exports.getLocal = readLocalFile;
/******************************************************************************/
2014-06-24 00:42:43 +02:00
exports.put = function(path, content, callback) {
cachedAssetsManager.save(path, content, callback);
2014-07-26 22:10:20 +02:00
};
/******************************************************************************/
exports.metadata = function(callback) {
var out = {};
2014-08-27 15:37:08 +02:00
// https://github.com/gorhill/uBlock/issues/186
// We need to check cache obsolescence when both cache and repo meta data
// has been gathered.
var checkCacheObsolescence = function() {
var entry;
for ( var path in out ) {
if ( out.hasOwnProperty(path) === false ) {
continue;
}
entry = out[path];
2014-12-21 06:07:08 +01:00
entry.cacheObsolete = stringIsNotEmpty(homeURLs[path]) &&
2014-12-20 21:28:16 +01:00
cacheIsObsolete(entry.lastModified);
2014-08-27 15:37:08 +02:00
}
callback(out);
};
var onRepoMetaReady = function(meta) {
var entries = meta.entries;
var entryRepo, entryOut;
for ( var path in entries ) {
if ( entries.hasOwnProperty(path) === false ) {
continue;
}
entryRepo = entries[path];
entryOut = out[path];
if ( entryOut === undefined ) {
entryOut = out[path] = {};
}
entryOut.localChecksum = entryRepo.localChecksum;
entryOut.repoChecksum = entryRepo.repoChecksum;
2014-12-21 06:07:08 +01:00
entryOut.homeURL = homeURLs[path] || '';
entryOut.repoObsolete = entryOut.localChecksum !== entryOut.repoChecksum;
}
2014-08-27 15:37:08 +02:00
checkCacheObsolescence();
};
var onCacheMetaReady = function(entries) {
var entryOut;
for ( var path in entries ) {
if ( entries.hasOwnProperty(path) === false ) {
continue;
}
entryOut = out[path];
if ( entryOut === undefined ) {
entryOut = out[path] = {};
}
entryOut.lastModified = entries[path];
// User data is not literally cache data
if ( reIsUserPath.test(path) ) {
continue;
}
entryOut.cached = true;
if ( reIsExternalPath.test(path) ) {
entryOut.homeURL = path;
}
}
2014-08-21 16:56:36 +02:00
getRepoMetadata(onRepoMetaReady);
};
2014-06-24 00:42:43 +02:00
cachedAssetsManager.entries(onCacheMetaReady);
};
2014-06-24 00:42:43 +02:00
/******************************************************************************/
exports.purge = function(pattern, before) {
cachedAssetsManager.remove(pattern, before);
};
/******************************************************************************/
exports.purgeAll = function(callback) {
2014-09-09 01:45:22 +02:00
cachedAssetsManager.removeAll(callback);
2014-06-24 00:42:43 +02:00
};
/******************************************************************************/
return exports;
2015-02-13 18:10:10 +01:00
})();
/******************************************************************************/
/******************************************************************************/
µBlock.assetUpdater = (function() {
'use strict';
/******************************************************************************/
var µb = µBlock;
var updateDaemonTimerPeriod = 11 * 60 * 1000; // 11 minutes
var updateCycleFirstPeriod = 7 * 60 * 1000; // 7 minutes
var updateCycleNextPeriod = 11 * 60 * 60 * 1000; // 11 hours
var updateCycleTime = 0;
var toUpdate = {};
var toUpdateCount = 0;
var updated = {};
var updatedCount = 0;
var metadata = null;
var onStart = null;
var onCompleted = null;
var exports = {};
/******************************************************************************/
var onAssetUpdated = function(details) {
var path = details.path;
if ( details.error ) {
2015-02-15 13:16:31 +01:00
//console.debug('assets.js > µBlock.assetUpdater/onAssetUpdated: "%s" failed', path);
2015-02-13 18:10:10 +01:00
return;
}
2015-02-15 13:16:31 +01:00
//console.debug('assets.js > µBlock.assetUpdater/onAssetUpdated: "%s"', path);
2015-02-13 18:10:10 +01:00
updated[path] = true;
updatedCount += 1;
// New data available: selfie is now invalid
µb.destroySelfie();
};
/******************************************************************************/
var updateOne = function() {
var metaEntry;
for ( var path in toUpdate ) {
if ( toUpdate.hasOwnProperty(path) === false ) {
continue;
}
if ( toUpdate[path] !== true ) {
continue;
}
toUpdate[path] = false;
toUpdateCount -= 1;
if ( metadata.hasOwnProperty(path) === false ) {
continue;
}
metaEntry = metadata[path];
if ( !metaEntry.cacheObsolete && !metaEntry.repoObsolete ) {
continue;
}
2015-02-15 13:16:31 +01:00
//console.debug('assets.js > µBlock.assetUpdater/updateOne: assets.get("%s")', path);
2015-02-13 18:10:10 +01:00
µb.assets.get(path, onAssetUpdated);
break;
}
};
/******************************************************************************/
var onMetadataReady = function(response) {
metadata = response;
updateOne();
};
/******************************************************************************/
var updateDaemon = function() {
setTimeout(updateDaemon, updateDaemonTimerPeriod);
µb.assets.autoUpdate = µb.userSettings.autoUpdate;
if ( µb.assets.autoUpdate !== true ) {
return;
}
// Start an update cycle?
if ( updateCycleTime !== 0 ) {
if ( Date.now() >= updateCycleTime ) {
2015-02-15 13:16:31 +01:00
//console.debug('assets.js > µBlock.assetUpdater/updateDaemon: update cycle started');
2015-02-13 18:10:10 +01:00
reset();
if ( onStart !== null ) {
onStart();
}
}
return;
}
// Any asset to update?
if ( toUpdateCount !== 0 ) {
if ( metadata === null ) {
µb.assets.metadata(onMetadataReady);
} else {
updateOne();
}
return;
}
// Nothing left to update
// If anything was updated, notify listener
if ( updatedCount !== 0 ) {
if ( onCompleted !== null ) {
2015-02-15 13:16:31 +01:00
//console.debug('assets.js > µBlock.assetUpdater/updateDaemon: update cycle completed');
2015-02-13 18:10:10 +01:00
onCompleted({
updated: JSON.parse(JSON.stringify(updated)), // give callee its own safe copy
updatedCount: updatedCount
});
}
}
// Schedule next update cycle
if ( updateCycleTime === 0 ) {
reset();
2015-02-15 13:16:31 +01:00
//console.debug('assets.js > µBlock.assetUpdater/updateDaemon: update cycle re-scheduled');
2015-02-13 18:10:10 +01:00
updateCycleTime = Date.now() + updateCycleNextPeriod;
}
};
setTimeout(updateDaemon, updateDaemonTimerPeriod);
/******************************************************************************/
var reset = function() {
toUpdate = {};
toUpdateCount = 0;
updated = {};
updatedCount = 0;
updateCycleTime = 0;
metadata = null;
};
/******************************************************************************/
exports.onStart = {
addEventListener: function(callback) {
onStart = callback || null;
if ( onStart !== null ) {
updateCycleTime = Date.now() + updateCycleFirstPeriod;
}
}
};
/******************************************************************************/
exports.onCompleted = {
addEventListener: function(callback) {
onCompleted = callback || null;
}
};
/******************************************************************************/
2015-02-13 18:10:10 +01:00
exports.add = function(path) {
if ( toUpdate.hasOwnProperty(path) ) {
return;
}
2015-02-15 13:16:31 +01:00
//console.debug('assets.js > µBlock.assetUpdater.add("%s")', path);
2015-02-13 18:10:10 +01:00
toUpdate[path] = true;
toUpdateCount += 1;
};
/******************************************************************************/
// Typically called when an update has been forced.
exports.restart = function() {
reset();
updateCycleTime = Date.now() + updateCycleNextPeriod;
};
/******************************************************************************/
return exports;
2014-06-24 00:42:43 +02:00
})();
/******************************************************************************/