1
0
Fork 0
mirror of https://github.com/gorhill/uMatrix.git synced 2024-06-02 02:14:52 +12:00
uMatrix/src/js/hosts-files.js

458 lines
15 KiB
JavaScript
Raw Normal View History

2014-10-18 08:01:09 +13:00
/*******************************************************************************
uMatrix - a Chromium browser extension to black/white list requests.
2018-01-30 11:19:42 +13:00
Copyright (C) 2014-2018 Raymond Hill
2014-10-18 08:01:09 +13: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/uMatrix
*/
/* global uDom */
'use strict';
2014-10-18 08:01:09 +13:00
/******************************************************************************/
(function() {
/******************************************************************************/
var listDetails = {},
lastUpdateTemplateString = vAPI.i18n('hostsFilesLastUpdate'),
hostsFilesSettingsHash,
2018-01-30 11:19:42 +13:00
reValidExternalList = /^[a-z-]+:\/\/\S*\/\S+$/m;
2015-05-02 11:27:43 +12:00
/******************************************************************************/
vAPI.messaging.addListener(function onMessage(msg) {
2014-10-18 08:01:09 +13:00
switch ( msg.what ) {
case 'assetUpdated':
updateAssetStatus(msg);
break;
case 'assetsUpdated':
document.body.classList.remove('updating');
break;
2015-05-02 11:27:43 +12:00
case 'loadHostsFilesCompleted':
renderHostsFiles();
break;
default:
break;
2014-10-18 08:01:09 +13:00
}
});
2015-04-12 09:15:57 +12:00
/******************************************************************************/
2015-05-02 11:27:43 +12:00
var renderNumber = function(value) {
return value.toLocaleString();
};
2014-10-18 08:01:09 +13:00
/******************************************************************************/
var renderHostsFiles = function(soft) {
var listEntryTemplate = uDom('#templates .listEntry'),
listStatsTemplate = vAPI.i18n('hostsFilesPerFileStats'),
renderElapsedTimeToString = vAPI.i18n.renderElapsedTimeToString,
reExternalHostFile = /^https?:/;
2014-10-18 08:01:09 +13:00
// Assemble a pretty list name if possible
2018-01-30 11:19:42 +13:00
var listNameFromListKey = function(collection, listKey) {
let list = collection.get(listKey);
let listTitle = list ? list.title : '';
if ( listTitle === '' ) { return listKey; }
2014-10-24 12:40:48 +13:00
return listTitle;
};
2018-01-30 11:19:42 +13:00
var liFromListEntry = function(collection, listKey, li) {
var entry = collection.get(listKey),
elem;
if ( !li ) {
li = listEntryTemplate.clone().nodeAt(0);
2014-10-18 08:01:09 +13:00
}
if ( li.getAttribute('data-listkey') !== listKey ) {
li.setAttribute('data-listkey', listKey);
elem = li.querySelector('input[type="checkbox"]');
2018-01-30 11:19:42 +13:00
elem.checked = entry.selected === true;
elem = li.querySelector('a:nth-of-type(1)');
elem.setAttribute('href', 'asset-viewer.html?url=' + encodeURI(listKey));
elem.setAttribute('type', 'text/html');
2018-01-30 11:19:42 +13:00
elem.textContent = listNameFromListKey(collection, listKey);
li.classList.remove('toRemove');
2018-01-30 11:19:42 +13:00
elem = li.querySelector('a.support');
if ( entry.supportURL ) {
elem.setAttribute(
'href',
entry.supportURL ? entry.supportURL : ''
);
}
2018-01-30 11:19:42 +13:00
li.classList.toggle('external', entry.external === true);
2014-10-18 08:01:09 +13:00
}
// https://github.com/gorhill/uBlock/issues/1429
if ( !soft ) {
elem = li.querySelector('input[type="checkbox"]');
2018-01-30 11:19:42 +13:00
elem.checked = entry.selected === true;
2014-10-24 12:40:48 +13:00
}
elem = li.querySelector('span.counts');
var text = '';
if ( !isNaN(+entry.entryUsedCount) && !isNaN(+entry.entryCount) ) {
text = listStatsTemplate
2018-01-30 11:19:42 +13:00
.replace('{{used}}', renderNumber(entry.selected ? entry.entryUsedCount : 0))
.replace('{{total}}', renderNumber(entry.entryCount));
2015-05-02 11:27:43 +12:00
}
elem.textContent = text;
2015-05-02 11:27:43 +12:00
// https://github.com/chrisaljoudi/uBlock/issues/104
var asset = listDetails.cache[listKey] || {};
var remoteURL = asset.remoteURL;
li.classList.toggle(
'unsecure',
typeof remoteURL === 'string' && remoteURL.lastIndexOf('http:', 0) === 0
);
li.classList.toggle('failed', asset.error !== undefined);
li.classList.toggle('obsolete', asset.obsolete === true);
li.classList.toggle('cached', asset.cached === true && asset.writeTime > 0);
2014-10-24 12:40:48 +13:00
if ( asset.cached ) {
li.querySelector('.status.cache').setAttribute(
'title',
lastUpdateTemplateString.replace('{{ago}}', renderElapsedTimeToString(asset.writeTime))
);
2014-10-24 12:40:48 +13:00
}
li.classList.remove('discard');
2015-05-02 11:27:43 +12:00
return li;
2014-10-24 12:40:48 +13:00
};
2018-01-30 11:19:42 +13:00
var onRenderAssetFiles = function(collection, listSelector) {
var assetKeys = Array.from(collection.keys());
2015-05-09 01:02:12 +12:00
// Sort works this way:
// - Send /^https?:/ items at the end (custom hosts file URL)
2018-01-30 11:19:42 +13:00
assetKeys.sort(function(a, b) {
var ta = collection.get(a).title || a,
tb = collection.get(b).title || b;
2015-05-09 01:02:12 +12:00
if ( reExternalHostFile.test(ta) === reExternalHostFile.test(tb) ) {
2015-05-02 11:27:43 +12:00
return ta.localeCompare(tb);
2014-10-24 12:40:48 +13:00
}
return reExternalHostFile.test(tb) ? -1 : 1;
2015-05-02 11:27:43 +12:00
});
2018-01-30 11:19:42 +13:00
let ulList = document.querySelector(listSelector),
liLast = ulList.querySelector('.notAnAsset');
2018-01-30 11:19:42 +13:00
for ( let i = 0; i < assetKeys.length; i++ ) {
let liReuse = i < ulList.childElementCount ?
ulList.children[i] :
null;
if (
liReuse !== null &&
liReuse.classList.contains('notAnAsset')
) {
liReuse = null;
}
let liEntry = liFromListEntry(collection, assetKeys[i], liReuse);
if ( liEntry.parentElement === null ) {
ulList.insertBefore(liEntry, liLast);
}
2014-10-24 12:40:48 +13:00
}
2018-01-30 11:19:42 +13:00
};
var onAssetDataReceived = function(details) {
// Preprocess.
details.hosts = new Map(details.hosts);
details.recipes = new Map(details.recipes);
// Before all, set context vars
listDetails = details;
document.body.classList.toggle(
'contributor',
listDetails.contributor === true
);
2018-01-30 11:19:42 +13:00
// Incremental rendering: this will allow us to easily discard unused
// DOM list entries.
uDom('#hosts .listEntry:not(.notAnAsset)').addClass('discard');
2018-01-30 11:19:42 +13:00
onRenderAssetFiles(details.hosts, '#hosts');
onRenderAssetFiles(details.recipes, '#recipes');
uDom('.listEntry.discard').remove();
2014-10-24 12:40:48 +13:00
uDom('#listsOfBlockedHostsPrompt').text(
2015-05-02 11:27:43 +12:00
vAPI.i18n('hostsFilesStats').replace(
'{{blockedHostnameCount}}',
renderNumber(details.blockedHostnameCount)
)
2014-10-24 12:40:48 +13:00
);
uDom('#autoUpdate').prop('checked', listDetails.autoUpdate === true);
uDom.nodeFromSelector('#recipes .toInline > input[type="checkbox"]').checked =
listDetails.userRecipes.enabled === true;
uDom.nodeFromSelector('#recipes .toInline > textarea').value =
listDetails.userRecipes.content;
if ( !soft ) {
hostsFilesSettingsHash = hashFromCurrentFromSettings();
}
2015-05-02 11:27:43 +12:00
renderWidgets();
2014-10-24 12:40:48 +13:00
};
2018-01-30 11:19:42 +13:00
vAPI.messaging.send(
'hosts-files.js',
{ what: 'getAssets' },
onAssetDataReceived
);
2014-10-24 12:40:48 +13:00
};
2014-10-18 08:01:09 +13:00
/******************************************************************************/
2015-05-02 11:27:43 +12:00
var renderWidgets = function() {
2018-01-30 11:19:42 +13:00
uDom('#buttonUpdate').toggleClass('disabled', document.querySelector('body:not(.updating) .assets .listEntry.obsolete > input[type="checkbox"]:checked') === null);
uDom('#buttonPurgeAll').toggleClass('disabled', document.querySelector('.assets .listEntry.cached') === null);
uDom('#buttonApply').toggleClass('disabled', hostsFilesSettingsHash === hashFromCurrentFromSettings());
2015-05-02 11:27:43 +12:00
};
/******************************************************************************/
var updateAssetStatus = function(details) {
2018-01-30 11:19:42 +13:00
var li = document.querySelector('.assets .listEntry[data-listkey="' + details.key + '"]');
if ( li === null ) { return; }
li.classList.toggle('failed', !!details.failed);
li.classList.toggle('obsolete', !details.cached);
li.classList.toggle('cached', !!details.cached);
if ( details.cached ) {
li.querySelector('.status.cache').setAttribute(
'title',
lastUpdateTemplateString.replace(
'{{ago}}',
vAPI.i18n.renderElapsedTimeToString(Date.now())
)
);
2014-10-24 12:40:48 +13:00
}
renderWidgets();
2014-10-24 12:40:48 +13:00
};
2014-10-18 08:01:09 +13:00
/*******************************************************************************
2014-10-24 12:40:48 +13:00
Compute a hash from all the settings affecting how assets are loaded
in memory.
2014-10-18 08:01:09 +13:00
**/
2014-10-18 08:01:09 +13:00
var hashFromCurrentFromSettings = function() {
let listHash = [],
listEntries = document.querySelectorAll(
'.assets .listEntry[data-listkey]:not(.toRemove)'
);
for ( let liEntry of listEntries ) {
if ( liEntry.querySelector('input[type="checkbox"]:checked') !== null ) {
listHash.push(liEntry.getAttribute('data-listkey'));
}
}
return [
listHash.join(),
document.querySelector('.listEntry.toRemove') !== null,
reValidExternalList.test(
textFromTextarea(
'#hosts .toImport > input[type="checkbox"]:checked ~ textarea'
)
),
textFromTextarea(
'#hosts .toInline > input[type="checkbox"]:checked ~ textarea'
),
reValidExternalList.test(
textFromTextarea(
'#recipes .toImport > input[type="checkbox"]:checked ~ textarea'
)
),
textFromTextarea(
'#recipes .toInline > input[type="checkbox"]:checked ~ textarea'
),
].join('\n');
};
/******************************************************************************/
var textFromTextarea = function(textarea) {
if ( typeof textarea === 'string' ) {
textarea = document.querySelector(textarea);
}
return textarea !== null ? textarea.value.trim() : '';
2014-10-24 12:40:48 +13:00
};
2014-10-18 08:01:09 +13:00
/******************************************************************************/
var onHostsFilesSettingsChanged = function() {
renderWidgets();
2014-10-24 12:40:48 +13:00
};
/******************************************************************************/
2018-01-30 11:19:42 +13:00
var onRemoveExternalAsset = function(ev) {
var liEntry = uDom(this).ancestors('[data-listkey]'),
listKey = liEntry.attr('data-listkey');
if ( listKey ) {
liEntry.toggleClass('toRemove');
renderWidgets();
}
2014-10-24 12:40:48 +13:00
ev.preventDefault();
};
/******************************************************************************/
var onPurgeClicked = function() {
var button = uDom(this),
liEntry = button.ancestors('[data-listkey]'),
listKey = liEntry.attr('data-listkey');
if ( !listKey ) { return; }
vAPI.messaging.send('hosts-files.js', { what: 'purgeCache', assetKey: listKey });
liEntry.addClass('obsolete');
liEntry.removeClass('cached');
if ( liEntry.descendants('input').first().prop('checked') ) {
renderWidgets();
2014-10-24 12:40:48 +13:00
}
};
/******************************************************************************/
2018-01-30 11:19:42 +13:00
var selectAssets = function(callback) {
var prepareChanges = function(listSelector) {
var out = {
toSelect: [],
toImport: '',
toRemove: [],
toInline: {
enabled: false,
content: ''
}
2018-01-30 11:19:42 +13:00
};
let root = document.querySelector(listSelector);
// Lists to select or remove
let liEntries = root.querySelectorAll(
'.listEntry[data-listkey]:not(.notAnAsset)'
);
for ( let liEntry of liEntries ) {
if ( liEntry.classList.contains('toRemove') ) {
out.toRemove.push(liEntry.getAttribute('data-listkey'));
} else if ( liEntry.querySelector('input[type="checkbox"]:checked') ) {
2018-01-30 11:19:42 +13:00
out.toSelect.push(liEntry.getAttribute('data-listkey'));
}
}
2015-05-02 11:27:43 +12:00
2018-01-30 11:19:42 +13:00
// External hosts files to import
let input = root.querySelector(
'.toImport > input[type="checkbox"]:checked'
);
2018-01-30 11:19:42 +13:00
if ( input !== null ) {
let textarea = root.querySelector('.toImport textarea');
2018-01-30 11:19:42 +13:00
out.toImport = textarea.value.trim();
textarea.value = '';
input.checked = false;
}
// Inline data
out.toInline.enabled = root.querySelector(
'.toInline > input[type="checkbox"]:checked'
) !== null;
out.toInline.content = textFromTextarea('.toInline > textarea');
2018-01-30 11:19:42 +13:00
return out;
};
vAPI.messaging.send(
'hosts-files.js',
{
2018-01-30 11:19:42 +13:00
what: 'selectAssets',
hosts: prepareChanges('#hosts'),
recipes: prepareChanges('#recipes')
},
callback
);
hostsFilesSettingsHash = hashFromCurrentFromSettings();
2014-10-24 12:40:48 +13:00
};
2014-10-18 08:01:09 +13:00
/******************************************************************************/
2014-10-24 12:40:48 +13:00
var buttonApplyHandler = function() {
2015-05-02 11:27:43 +12:00
uDom('#buttonApply').removeClass('enabled');
2018-01-30 11:19:42 +13:00
selectAssets(function(response) {
if ( response && response.hostsChanged ) {
vAPI.messaging.send('hosts-files.js', { what: 'reloadHostsFiles' });
}
if ( response && response.recipesChanged ) {
vAPI.messaging.send('hosts-files.js', { what: 'reloadRecipeFiles' });
}
});
renderWidgets();
2014-10-24 12:40:48 +13:00
};
/******************************************************************************/
var buttonUpdateHandler = function() {
2015-05-02 11:27:43 +12:00
uDom('#buttonUpdate').removeClass('enabled');
2018-01-30 11:19:42 +13:00
selectAssets(function() {
document.body.classList.add('updating');
vAPI.messaging.send('hosts-files.js', { what: 'forceUpdateAssets' });
renderWidgets();
});
renderWidgets();
2014-10-24 12:40:48 +13:00
};
/******************************************************************************/
var buttonPurgeAllHandler = function() {
2015-05-02 11:27:43 +12:00
uDom('#buttonPurgeAll').removeClass('enabled');
vAPI.messaging.send(
'hosts-files.js',
{ what: 'purgeAllCaches' },
function() {
renderHostsFiles(true);
}
);
2014-10-24 12:40:48 +13:00
};
/******************************************************************************/
var autoUpdateCheckboxChanged = function() {
vAPI.messaging.send(
'hosts-files.js',
{
what: 'userSettings',
name: 'autoUpdate',
value: this.checked
}
);
2014-10-24 12:40:48 +13:00
};
/******************************************************************************/
uDom('#autoUpdate').on('change', autoUpdateCheckboxChanged);
uDom('#buttonApply').on('click', buttonApplyHandler);
uDom('#buttonUpdate').on('click', buttonUpdateHandler);
uDom('#buttonPurgeAll').on('click', buttonPurgeAllHandler);
2018-01-30 11:19:42 +13:00
uDom('.assets').on('change', '.listEntry > input', onHostsFilesSettingsChanged);
uDom('.assets').on('input', '.listEntry > textarea', onHostsFilesSettingsChanged);
2018-01-30 11:19:42 +13:00
uDom('.assets').on('click', '.listEntry > a.remove', onRemoveExternalAsset);
uDom('.assets').on('click', 'span.cache', onPurgeClicked);
2014-10-24 12:40:48 +13:00
renderHostsFiles();
2014-10-18 08:01:09 +13:00
/******************************************************************************/
})();