From b94d0d4e8bd3a92bbb5e012a63fa782baa774be7 Mon Sep 17 00:00:00 2001 From: TC Date: Thu, 3 Dec 2020 19:02:43 +0100 Subject: [PATCH] Adblocker - advanced options (caching or not, additional lists) --- plugins/adblocker/back.js | 7 ++++++- plugins/adblocker/blocker.js | 29 +++++++++++++++++++++-------- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/plugins/adblocker/back.js b/plugins/adblocker/back.js index 25ba5da9..96d90361 100644 --- a/plugins/adblocker/back.js +++ b/plugins/adblocker/back.js @@ -1,2 +1,7 @@ const { loadAdBlockerEngine } = require("./blocker"); -module.exports = (win) => loadAdBlockerEngine(win.webContents.session); +module.exports = (win, options) => + loadAdBlockerEngine( + win.webContents.session, + options.cache, + options.additionalBlockLists + ); diff --git a/plugins/adblocker/blocker.js b/plugins/adblocker/blocker.js index e17abbb9..7a236c95 100644 --- a/plugins/adblocker/blocker.js +++ b/plugins/adblocker/blocker.js @@ -1,4 +1,4 @@ -const { promises } = require("fs"); // used for caching +const { existsSync, promises, unlinkSync } = require("fs"); // used for caching const path = require("path"); const { ElectronBlocker } = require("@cliqz/adblocker-electron"); @@ -8,16 +8,28 @@ const SOURCES = [ "https://raw.githubusercontent.com/kbinani/adblock-youtube-ads/master/signed.txt", ]; -const loadAdBlockerEngine = (session = undefined) => +const loadAdBlockerEngine = ( + session = undefined, + cache = true, + additionalBlockLists = [] +) => { + const adBlockerCache = path.resolve(__dirname, "ad-blocker-engine.bin"); + if (!cache && existsSync(adBlockerCache)) { + unlinkSync(adBlockerCache); + } + const cachingOptions = cache + ? { + path: adBlockerCache, + read: promises.readFile, + write: promises.writeFile, + } + : undefined; + ElectronBlocker.fromLists( fetch, - SOURCES, + [...SOURCES, ...additionalBlockLists], {}, - { - path: path.resolve(__dirname, "ad-blocker-engine.bin"), - read: promises.readFile, - write: promises.writeFile, - } + cachingOptions ) .then((blocker) => { if (session) { @@ -27,6 +39,7 @@ const loadAdBlockerEngine = (session = undefined) => } }) .catch((err) => console.log("Error loading adBlocker engine", err)); +}; module.exports = { loadAdBlockerEngine }; if (require.main === module) {