Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement simple event emitter for FiltersEngine and sub-classes #251

Merged
merged 1 commit into from
Aug 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/adblocker-electron-example/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
Blocking ads in Electron using @cliqz/adblocker.

```sh
$ npx electron index.js
$ yarn start
```
40 changes: 34 additions & 6 deletions packages/adblocker-electron-example/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { app, BrowserWindow, session } from 'electron';
import fetch from 'node-fetch';

import { ElectronBlocker, fetchLists, fetchResources } from '@cliqz/adblocker-electron';
import { ElectronBlocker, fetchLists, fetchResources, Request } from '@cliqz/adblocker-electron';

// Polyfill fetch API for Node.js environment
// @ts-ignore
Expand Down Expand Up @@ -52,6 +52,15 @@ async function loadAdblocker(): Promise<ElectronBlocker> {
});
}

function getUrlToLoad(): string {
let url = 'https://www.mangareader.net/';
if (process.argv[process.argv.length - 1].endsWith('.js') === false) {
url = process.argv[process.argv.length - 1];
}

return url;
}

let mainWindow: BrowserWindow | null = null;

async function createWindow() {
Expand All @@ -67,12 +76,31 @@ async function createWindow() {
const engine = await loadAdblocker();
engine.enableBlockingInSession(session.defaultSession);

let url = 'https://www.mangareader.net/';
if (process.argv[process.argv.length - 1].endsWith('.js') === false) {
url = process.argv[process.argv.length - 1];
}
engine.on('request-blocked', (request: Request) => {
console.log('blocked', request.url);
});

engine.on('request-redirected', (request: Request) => {
console.log('redirected', request.url);
});

engine.on('request-whitelisted', (request: Request) => {
console.log('whitelisted', request.url);
});

engine.on('csp-injected', (request: Request) => {
console.log('csp', request.url);
});

engine.on('script-injected', (script: string, url: string) => {
console.log('script', script.length, url);
});

engine.on('style-injected', (style: string, url: string) => {
console.log('style', style.length, url);
});

mainWindow.loadURL(url);
mainWindow.loadURL(getUrlToLoad());
mainWindow.webContents.openDevTools();

mainWindow.on('closed', () => {
Expand Down
3 changes: 1 addition & 2 deletions packages/adblocker-electron-example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"url": "git@github.com:cliqz-oss/adblocker.git"
},
"scripts": {
"start": "ts-node --project ./tsconfig.json index.ts",
"start": "electron index.js",
"lint": "tslint --config ../../tslint.json --project ./tsconfig.json"
},
"bugs": {
Expand All @@ -27,7 +27,6 @@
"@types/node-fetch": "^2.5.0",
"electron": "^6.0.1",
"node-fetch": "^2.6.0",
"ts-node": "^8.3.0",
"typescript": "^3.5.3"
}
}
99 changes: 73 additions & 26 deletions packages/adblocker-puppeteer-example/index.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,54 @@
import { ENGINE_VERSION, PuppeteerBlocker } from '@cliqz/adblocker-puppeteer';
import axios from 'axios';
import { fetchLists, fetchResources, PuppeteerBlocker, Request } from '@cliqz/adblocker-puppeteer';
import fetch from 'node-fetch';
import puppeteer from 'puppeteer';

// Polyfill fetch API for Node.js environment
// @ts-ignore
global.fetch = fetch;

/**
* Initialize the adblocker using lists of filters and resources. It returns a
* Promise resolving on the `Engine` that we will use to decide what requests
* should be blocked or altered.
*/
async function loadAdblocker(): Promise<PuppeteerBlocker> {
// Fetch `allowed-lists.json` from CDN. It contains information about where
// to find pre-built engines as well as lists of filters (e.g.: Easylist,
// etc.).
console.time('fetch allowed lists');
const { engines } = (await axios.get(
'https://cdn.cliqz.com/adblocker/configs/desktop-ads-trackers/allowed-lists.json',
)).data;
console.timeEnd('fetch allowed lists');

// Once we have the config, we can get the URL of the pre-built engine
// corresponding to our installed @cliqz/adblocker version (i.e.:
// ENGINE_VERSION). This guarantees that we can download a compabitle one.
console.time('fetch serialized engine');
const serialized = (await axios.get(engines[ENGINE_VERSION].url, {
responseType: 'arraybuffer',
})).data;
console.timeEnd('fetch serialized engine');

// Deserialize the FiltersEngine instance from binary form.
console.time('deserialize engine');
const engine = PuppeteerBlocker.deserialize(new Uint8Array(serialized)) as PuppeteerBlocker;
console.timeEnd('deserialize engine');

return engine;
console.log('Fetching resources...');
return Promise.all([fetchLists(), fetchResources()]).then(([responses, resources]) => {
console.log('Initialize adblocker...');
const deduplicatedLines = new Set();
for (let i = 0; i < responses.length; i += 1) {
const lines = responses[i].split(/\n/g);
for (let j = 0; j < lines.length; j += 1) {
deduplicatedLines.add(lines[j]);
}
}
const deduplicatedFilters = Array.from(deduplicatedLines).join('\n');

let t0 = Date.now();
const engine = PuppeteerBlocker.parse(deduplicatedFilters, {
enableCompression: true,
});
let total = Date.now() - t0;
console.log('parsing filters', total);

t0 = Date.now();
engine.updateResources(resources, '' + resources.length);
total = Date.now() - t0;
console.log('parsing resources', total);

t0 = Date.now();
const serialized = engine.serialize();
total = Date.now() - t0;
console.log('serialization', total);
console.log('size', serialized.byteLength);

t0 = Date.now();
const deserialized = PuppeteerBlocker.deserialize(serialized);
total = Date.now() - t0;
console.log('deserialization', total);

return deserialized as PuppeteerBlocker;
});
}

(async () => {
Expand All @@ -38,5 +60,30 @@ async function loadAdblocker(): Promise<PuppeteerBlocker> {

const page = await browser.newPage();
await engine.enableBlockingInPage(page);

engine.on('request-blocked', (request: Request) => {
console.log('blocked', request.url);
});

engine.on('request-redirected', (request: Request) => {
console.log('redirected', request.url);
});

engine.on('request-whitelisted', (request: Request) => {
console.log('whitelisted', request.url);
});

engine.on('csp-injected', (request: Request) => {
console.log('csp', request.url);
});

engine.on('script-injected', (script: string, url: string) => {
console.log('script', script.length, url);
});

engine.on('style-injected', (style: string, url: string) => {
console.log('style', style.length, url);
});

await page.goto('https://www.mangareader.net/');
})();
1 change: 0 additions & 1 deletion packages/adblocker-puppeteer-example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
},
"dependencies": {
"@cliqz/adblocker-puppeteer": "^0.12.0",
"axios": "^0.19.0",
"puppeteer": "^1.18.1",
"ts-node": "^8.3.0",
"typescript": "^3.5.3"
Expand Down
8 changes: 3 additions & 5 deletions packages/adblocker-puppeteer/adblocker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,7 @@ export class PuppeteerBlocker extends FiltersEngine {
// easily be added if puppeteer implements the required capability.

// Register callback for network requets filtering
page.on('request', (request) => {
this.onRequest(request);
});
page.on('request', this.onRequest);

// Register callback to cosmetics injection (CSS + scriptlets)
page.on('framenavigated', async (frame) => {
Expand All @@ -57,7 +55,7 @@ export class PuppeteerBlocker extends FiltersEngine {
});
}

private async onFrame(frame: puppeteer.Frame): Promise<void> {
private onFrame = async (frame: puppeteer.Frame): Promise<void> => {
// DOM features
const { ids, hrefs, classes } = await frame.$$eval(
'[id],[class],[href]',
Expand Down Expand Up @@ -108,7 +106,7 @@ export class PuppeteerBlocker extends FiltersEngine {
}
}

private onRequest(request: puppeteer.Request): void {
private onRequest = (request: puppeteer.Request): void => {
const { redirect, match } = this.match(fromPuppeteerDetails(request));

if (redirect !== undefined) {
Expand Down
39 changes: 11 additions & 28 deletions packages/adblocker-webextension-example/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/

import { fetchLists, fetchResources, WebExtensionBlocker } from '@cliqz/adblocker-webextension';
import { BlockingResponse, fetchLists, fetchResources, Request, WebExtensionBlocker } from '@cliqz/adblocker-webextension';

/**
* Initialize the adblocker using lists of filters and resources. It returns a
Expand Down Expand Up @@ -70,39 +70,22 @@ function updateBlockedCounter(tabId: number, { reset = false, incr = false } = {
});
}

function incrementBlockedCounter(request: Request, blockingResponse: BlockingResponse): void {
updateBlockedCounter(request.tabId, {
incr: Boolean(blockingResponse.match),
reset: request.isMainFrame(),
});
}

// Whenever the active tab changes, then we update the count of blocked request
chrome.tabs.onActivated.addListener(({ tabId }: chrome.tabs.TabActiveInfo) =>
updateBlockedCounter(tabId),
);

loadAdblocker().then((engine) => {
// Start listening to requests, and allow 'blocking' so that we can cancel
// some of them (or redirect).
chrome.webRequest.onBeforeRequest.addListener(
(details) => {
const blockingResponse = engine.onBeforeRequest(details);

updateBlockedCounter(details.tabId, {
incr: Boolean(blockingResponse.cancel || blockingResponse.redirectUrl),
reset: details.type === 'main_frame',
});

return blockingResponse;
},
{
urls: ['<all_urls>'],
},
['blocking'],
);

chrome.webRequest.onHeadersReceived.addListener(
(details) => engine.onHeadersReceived(details),
{ urls: ['<all_urls>'], types: ['main_frame'] },
['blocking', 'responseHeaders'],
);

// Start listening to messages coming from the content-script
chrome.runtime.onMessage.addListener((...args) => engine.onRuntimeMessage(...args));
engine.enableBlockingInBrowser();
engine.on('request-blocked', incrementBlockedCounter);
engine.on('request-redirected', incrementBlockedCounter);

console.log('Ready to roll!');
});
4 changes: 4 additions & 0 deletions packages/adblocker-webextension/adblocker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ describe('#fromWebRequestDetails', () => {
expect(
fromWebRequestDetails({
initiator: 'https://sub.foo.com',
tabId: 0,
type: 'script',
url: 'https://url',
}),
Expand All @@ -78,6 +79,7 @@ describe('#fromWebRequestDetails', () => {
expect(
fromWebRequestDetails({
originUrl: 'https://sub.foo.com',
tabId: 0,
type: 'script',
url: 'https://url',
}),
Expand All @@ -91,6 +93,7 @@ describe('#fromWebRequestDetails', () => {
expect(
fromWebRequestDetails({
documentUrl: 'https://sub.foo.com',
tabId: 0,
type: 'script',
url: 'https://url',
}),
Expand All @@ -104,6 +107,7 @@ describe('#fromWebRequestDetails', () => {
expect(
fromWebRequestDetails({
documentUrl: 'https://sub.soURCE.com',
tabId: 0,
type: 'script',
url: 'https://sub.url.com',
}),
Expand Down
Loading