You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

390 lines
13 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. /*******************************************************************************
  2. uMatrix - a Chromium browser extension to black/white list requests.
  3. Copyright (C) 2014-2017 Raymond Hill
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see {http://www.gnu.org/licenses/}.
  14. Home: https://github.com/gorhill/uMatrix
  15. */
  16. /* global uDom */
  17. 'use strict';
  18. /******************************************************************************/
  19. (function() {
  20. /******************************************************************************/
  21. var listDetails = {},
  22. lastUpdateTemplateString = vAPI.i18n('hostsFilesLastUpdate'),
  23. hostsFilesSettingsHash,
  24. reValidExternalList = /[a-z-]+:\/\/\S*\/\S+/;
  25. /******************************************************************************/
  26. vAPI.messaging.addListener(function onMessage(msg) {
  27. switch ( msg.what ) {
  28. case 'assetUpdated':
  29. updateAssetStatus(msg);
  30. break;
  31. case 'assetsUpdated':
  32. document.body.classList.remove('updating');
  33. break;
  34. case 'loadHostsFilesCompleted':
  35. renderHostsFiles();
  36. break;
  37. default:
  38. break;
  39. }
  40. });
  41. /******************************************************************************/
  42. var renderNumber = function(value) {
  43. return value.toLocaleString();
  44. };
  45. /******************************************************************************/
  46. var renderHostsFiles = function(soft) {
  47. var listEntryTemplate = uDom('#templates .listEntry'),
  48. listStatsTemplate = vAPI.i18n('hostsFilesPerFileStats'),
  49. renderElapsedTimeToString = vAPI.i18n.renderElapsedTimeToString,
  50. reExternalHostFile = /^https?:/;
  51. // Assemble a pretty list name if possible
  52. var listNameFromListKey = function(listKey) {
  53. var list = listDetails.current[listKey] || listDetails.available[listKey];
  54. var listTitle = list ? list.title : '';
  55. if ( listTitle === '' ) { return listKey; }
  56. return listTitle;
  57. };
  58. var liFromListEntry = function(listKey, li) {
  59. var entry = listDetails.available[listKey],
  60. elem;
  61. if ( !li ) {
  62. li = listEntryTemplate.clone().nodeAt(0);
  63. }
  64. if ( li.getAttribute('data-listkey') !== listKey ) {
  65. li.setAttribute('data-listkey', listKey);
  66. elem = li.querySelector('input[type="checkbox"]');
  67. elem.checked = entry.off !== true;
  68. elem = li.querySelector('a:nth-of-type(1)');
  69. elem.setAttribute('href', 'asset-viewer.html?url=' + encodeURI(listKey));
  70. elem.setAttribute('type', 'text/html');
  71. elem.textContent = listNameFromListKey(listKey);
  72. li.classList.remove('toRemove');
  73. if ( entry.supportName ) {
  74. li.classList.add('support');
  75. elem = li.querySelector('a.support');
  76. elem.setAttribute('href', entry.supportURL);
  77. elem.setAttribute('title', entry.supportName);
  78. } else {
  79. li.classList.remove('support');
  80. }
  81. if ( entry.external ) {
  82. li.classList.add('external');
  83. } else {
  84. li.classList.remove('external');
  85. }
  86. if ( entry.instructionURL ) {
  87. li.classList.add('mustread');
  88. elem = li.querySelector('a.mustread');
  89. elem.setAttribute('href', entry.instructionURL);
  90. } else {
  91. li.classList.remove('mustread');
  92. }
  93. }
  94. // https://github.com/gorhill/uBlock/issues/1429
  95. if ( !soft ) {
  96. elem = li.querySelector('input[type="checkbox"]');
  97. elem.checked = entry.off !== true;
  98. }
  99. elem = li.querySelector('span.counts');
  100. var text = '';
  101. if ( !isNaN(+entry.entryUsedCount) && !isNaN(+entry.entryCount) ) {
  102. text = listStatsTemplate
  103. .replace('{{used}}', renderNumber(entry.off ? 0 : entry.entryUsedCount))
  104. .replace('{{total}}', renderNumber(entry.entryCount));
  105. }
  106. elem.textContent = text;
  107. // https://github.com/chrisaljoudi/uBlock/issues/104
  108. var asset = listDetails.cache[listKey] || {};
  109. var remoteURL = asset.remoteURL;
  110. li.classList.toggle(
  111. 'unsecure',
  112. typeof remoteURL === 'string' && remoteURL.lastIndexOf('http:', 0) === 0
  113. );
  114. li.classList.toggle('failed', asset.error !== undefined);
  115. li.classList.toggle('obsolete', asset.obsolete === true);
  116. li.classList.toggle('cached', asset.cached === true && asset.writeTime > 0);
  117. if ( asset.cached ) {
  118. li.querySelector('.status.cache').setAttribute(
  119. 'title',
  120. lastUpdateTemplateString.replace('{{ago}}', renderElapsedTimeToString(asset.writeTime))
  121. );
  122. }
  123. li.classList.remove('discard');
  124. return li;
  125. };
  126. var onListsReceived = function(details) {
  127. // Before all, set context vars
  128. listDetails = details;
  129. // Incremental rendering: this will allow us to easily discard unused
  130. // DOM list entries.
  131. uDom('#lists .listEntry').addClass('discard');
  132. var availableLists = details.available,
  133. listKeys = Object.keys(details.available);
  134. // Sort works this way:
  135. // - Send /^https?:/ items at the end (custom hosts file URL)
  136. listKeys.sort(function(a, b) {
  137. var ta = availableLists[a].title || a,
  138. tb = availableLists[b].title || b;
  139. if ( reExternalHostFile.test(ta) === reExternalHostFile.test(tb) ) {
  140. return ta.localeCompare(tb);
  141. }
  142. return reExternalHostFile.test(tb) ? -1 : 1;
  143. });
  144. var ulList = document.querySelector('#lists');
  145. for ( var i = 0; i < listKeys.length; i++ ) {
  146. var liEntry = liFromListEntry(listKeys[i], ulList.children[i]);
  147. if ( liEntry.parentElement === null ) {
  148. ulList.appendChild(liEntry);
  149. }
  150. }
  151. uDom('#lists .listEntry.discard').remove();
  152. uDom('#listsOfBlockedHostsPrompt').text(
  153. vAPI.i18n('hostsFilesStats').replace(
  154. '{{blockedHostnameCount}}',
  155. renderNumber(details.blockedHostnameCount)
  156. )
  157. );
  158. uDom('#autoUpdate').prop('checked', listDetails.autoUpdate === true);
  159. if ( !soft ) {
  160. hostsFilesSettingsHash = hashFromCurrentFromSettings();
  161. }
  162. renderWidgets();
  163. };
  164. vAPI.messaging.send('hosts-files.js', { what: 'getLists' }, onListsReceived);
  165. };
  166. /******************************************************************************/
  167. var renderWidgets = function() {
  168. uDom('#buttonUpdate').toggleClass('disabled', document.querySelector('body:not(.updating) #lists .listEntry.obsolete > input[type="checkbox"]:checked') === null);
  169. uDom('#buttonPurgeAll').toggleClass('disabled', document.querySelector('#lists .listEntry.cached') === null);
  170. uDom('#buttonApply').toggleClass('disabled', hostsFilesSettingsHash === hashFromCurrentFromSettings());
  171. };
  172. /******************************************************************************/
  173. var updateAssetStatus = function(details) {
  174. var li = document.querySelector('#lists .listEntry[data-listkey="' + details.key + '"]');
  175. if ( li === null ) { return; }
  176. li.classList.toggle('failed', !!details.failed);
  177. li.classList.toggle('obsolete', !details.cached);
  178. li.classList.toggle('cached', !!details.cached);
  179. if ( details.cached ) {
  180. li.querySelector('.status.cache').setAttribute(
  181. 'title',
  182. lastUpdateTemplateString.replace(
  183. '{{ago}}',
  184. vAPI.i18n.renderElapsedTimeToString(Date.now())
  185. )
  186. );
  187. }
  188. renderWidgets();
  189. };
  190. /*******************************************************************************
  191. Compute a hash from all the settings affecting how filter lists are loaded
  192. in memory.
  193. **/
  194. var hashFromCurrentFromSettings = function() {
  195. var hash = [],
  196. listHash = [],
  197. listEntries = document.querySelectorAll('#lists .listEntry[data-listkey]:not(.toRemove)'),
  198. liEntry,
  199. i = listEntries.length;
  200. while ( i-- ) {
  201. liEntry = listEntries[i];
  202. if ( liEntry.querySelector('input[type="checkbox"]:checked') !== null ) {
  203. listHash.push(liEntry.getAttribute('data-listkey'));
  204. }
  205. }
  206. hash.push(
  207. listHash.sort().join(),
  208. reValidExternalList.test(document.getElementById('externalHostsFiles').value),
  209. document.querySelector('#lists .listEntry.toRemove') !== null
  210. );
  211. return hash.join();
  212. };
  213. /******************************************************************************/
  214. var onHostsFilesSettingsChanged = function() {
  215. renderWidgets();
  216. };
  217. /******************************************************************************/
  218. var onRemoveExternalHostsFile = function(ev) {
  219. var liEntry = uDom(this).ancestors('[data-listkey]'),
  220. listKey = liEntry.attr('data-listkey');
  221. if ( listKey ) {
  222. liEntry.toggleClass('toRemove');
  223. renderWidgets();
  224. }
  225. ev.preventDefault();
  226. };
  227. /******************************************************************************/
  228. var onPurgeClicked = function() {
  229. var button = uDom(this),
  230. liEntry = button.ancestors('[data-listkey]'),
  231. listKey = liEntry.attr('data-listkey');
  232. if ( !listKey ) { return; }
  233. vAPI.messaging.send('hosts-files.js', { what: 'purgeCache', assetKey: listKey });
  234. liEntry.addClass('obsolete');
  235. liEntry.removeClass('cached');
  236. if ( liEntry.descendants('input').first().prop('checked') ) {
  237. renderWidgets();
  238. }
  239. };
  240. /******************************************************************************/
  241. var selectHostsFiles = function(callback) {
  242. // Hosts files to select
  243. var toSelect = [],
  244. liEntries = document.querySelectorAll('#lists .listEntry[data-listkey]:not(.toRemove)'),
  245. i = liEntries.length,
  246. liEntry;
  247. while ( i-- ) {
  248. liEntry = liEntries[i];
  249. if ( liEntry.querySelector('input[type="checkbox"]:checked') !== null ) {
  250. toSelect.push(liEntry.getAttribute('data-listkey'));
  251. }
  252. }
  253. // External hosts files to remove
  254. var toRemove = [];
  255. liEntries = document.querySelectorAll('#lists .listEntry.toRemove[data-listkey]');
  256. i = liEntries.length;
  257. while ( i-- ) {
  258. toRemove.push(liEntries[i].getAttribute('data-listkey'));
  259. }
  260. // External hosts files to import
  261. var externalListsElem = document.getElementById('externalHostsFiles'),
  262. toImport = externalListsElem.value.trim();
  263. externalListsElem.value = '';
  264. vAPI.messaging.send(
  265. 'hosts-files.js',
  266. {
  267. what: 'selectHostsFiles',
  268. toSelect: toSelect,
  269. toImport: toImport,
  270. toRemove: toRemove
  271. },
  272. callback
  273. );
  274. hostsFilesSettingsHash = hashFromCurrentFromSettings();
  275. };
  276. /******************************************************************************/
  277. var buttonApplyHandler = function() {
  278. uDom('#buttonApply').removeClass('enabled');
  279. selectHostsFiles(function() {
  280. vAPI.messaging.send('hosts-files.js', { what: 'reloadHostsFiles' });
  281. });
  282. renderWidgets();
  283. };
  284. /******************************************************************************/
  285. var buttonUpdateHandler = function() {
  286. uDom('#buttonUpdate').removeClass('enabled');
  287. selectHostsFiles(function() {
  288. document.body.classList.add('updating');
  289. vAPI.messaging.send('hosts-files.js', { what: 'forceUpdateAssets' });
  290. renderWidgets();
  291. });
  292. renderWidgets();
  293. };
  294. /******************************************************************************/
  295. var buttonPurgeAllHandler = function() {
  296. uDom('#buttonPurgeAll').removeClass('enabled');
  297. vAPI.messaging.send(
  298. 'hosts-files.js',
  299. { what: 'purgeAllCaches' },
  300. function() {
  301. renderHostsFiles(true);
  302. }
  303. );
  304. };
  305. /******************************************************************************/
  306. var autoUpdateCheckboxChanged = function() {
  307. vAPI.messaging.send(
  308. 'hosts-files.js',
  309. {
  310. what: 'userSettings',
  311. name: 'autoUpdate',
  312. value: this.checked
  313. }
  314. );
  315. };
  316. /******************************************************************************/
  317. uDom('#autoUpdate').on('change', autoUpdateCheckboxChanged);
  318. uDom('#buttonApply').on('click', buttonApplyHandler);
  319. uDom('#buttonUpdate').on('click', buttonUpdateHandler);
  320. uDom('#buttonPurgeAll').on('click', buttonPurgeAllHandler);
  321. uDom('#lists').on('change', '.listEntry > input', onHostsFilesSettingsChanged);
  322. uDom('#lists').on('click', '.listEntry > a.remove', onRemoveExternalHostsFile);
  323. uDom('#lists').on('click', 'span.cache', onPurgeClicked);
  324. uDom('#externalHostsFiles').on('input', onHostsFilesSettingsChanged);
  325. renderHostsFiles();
  326. /******************************************************************************/
  327. })();