forked from gorhill/uBlock
-
-
Notifications
You must be signed in to change notification settings - Fork 191
/
Copy pathcore.js
2495 lines (1875 loc) · 66.9 KB
/
core.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
AdNauseam - Fight back against advertising surveillance.
Copyright (C) 2014-2024 Daniel C. Howe
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/dhowe/AdNauseam
*/
// watch: fswatch - o - r src / js / | xargs - n1 - I{ } ./tools/make - chromium.sh
/* global vAPI, µb */
'use strict';
import µb from '../background.js';
import staticFilteringReverseLookup from '../reverselookup.js';
import staticNetFilteringEngine from '../static-net-filtering.js'
import { broadcast } from '../broadcast.js';
import dnt from './dnt.js'
import {
domainFromHostname,
hostnameFromURI
} from '../uri-utils.js';
import {
CompiledListWriter,
} from '../static-filtering-io.js';
import * as sfp from '../static-filtering-parser.js';
import {
log,
warn,
err,
logNetAllow,
logNetBlock,
logNetEvent
} from './log.js';
import { i18n$ } from '../i18n.js';
import {
DNTAllowed,
DNTHideNotClick,
DNTClickNotHide,
DNTNotify,
addNotification,
removeNotification,
hasDNTNotification,
ShowAdsDebug,
OperaSetting,
FirefoxSetting,
AdBlockerEnabled,
AdNauseamTxt,
EasyList,
BlockingDisabled,
ClickingDisabled,
HidingDisabled,
NewerVersionAvailable
} from './notifications.js';
import {
byField,
trimChar,
toBase64Image,
b64toBlob,
type,
computeHash,
parseHostname,
parseDomain,
isValidDomain
} from './adn-utils.js';
const adnauseam = (function () {
'use strict';
// for debugging only
let // all visits will fail
failAllVisits = 0,
// start with zero ads
clearAdsOnInit = 0,
// reset all ad visit data
clearVisitData = 0,
// testing ['selenium' or 'sessbench']
automatedMode = 0,
// don't wait for user to be idle
disableIdler = 0;
let lastActivity = 0;
let lastUserActivity = 0;
let lastStorageUpdate = 0;
let xhr, idgen, admap, listsLoaded = false;
let inspected, listEntries, devbuild, adsetSize = 0;
const production = 1;
const notifications = [];
const allowedExceptions = [];
const visitedURLs = new Set();
const maxAttemptsPerAd = 3;
const visitTimeout = 20000;
const pollQueueInterval = 5000;
const redactMarker = '********';
const repeatVisitInterval = Number.MAX_VALUE;
const updateStorageInterval = 1000 * 60 * 30; // 30min
// properties set to true for a devbuild
const devProps = ["hidingAds", "clickingAds", "blockingMalware",
"eventLogging", "disableClickingForDNT", "disableHidingForDNT"]
// blocks requests to/from these domains even if the list is not in enabledBlockLists
const allowAnyBlockOnDomains = ['youtube.com', 'funnyordie.com']; // no dnt in here
// allow blocks only from this set of lists (recheck this)
const enabledBlockLists = ['EasyPrivacy',
'uBlock filters – Badware risks', 'uBlock filters – Unbreak',
'uBlock filters – Privacy', 'Malware domains', 'Malware Domain List',
'Anti-ThirdpartySocial', 'AdNauseam filters', 'Fanboy’s Annoyance List',
'CHN: CJX\'s Annoyance List', 'Spam404', 'Anti-Adblock Killer | Reek',
'Fanboy’s Social Blocking List', 'Malware domains (long-lived)',
'Adblock Warning Removal List', 'Malware filter list by Disconnect',
'Basic tracking list by Disconnect', 'EFF DNT Policy Whitelist',
'AdGuard Annoyances', 'AdGuard Tracking Protection'
];
const removableBlockLists = ['hphosts', 'mvps-0', 'plowe-0'];
// mark ad visits as failure if any of these are included in title
const errorStrings = ['file not found', 'website is currently unavailable', 'not found on this server'];
const reSpecialChars = /[\*\^\t\v\n]/, remd5 = /[a-fA-F0-9]{32}/;
/**************************** functions ******************************/
/* called when the addon is first loaded */
const initialize = function (ads) {
// modify XMLHttpRequest to store original request/ad
const XMLHttpRequest_open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (method, url) {
this.delegate = null; // store ad here
this.requestUrl = url; // store original target
return XMLHttpRequest_open.apply(this, arguments);
};
initializeState(ads);
log("INITIALIZE", browser.runtime.getManifest());
setTimeout(pollQueue, pollQueueInterval * 2);
};
const initializeState = function (ads) {
admap = (ads.admap ? ads.admap : ads) || {};
adsetSize = adCount();
validateAdStorage();
if (production) { // disable all test-modes if production
failAllVisits = clearVisitData = automatedMode = clearAdsOnInit = disableIdler = 0;
} else if (automatedMode === 'sessbench') { // using sessbench
setupTesting();
}
}
const setupTesting = function () {
warn('AdNauseam/sessbench: eid=' + chrome.runtime.id);
chrome.runtime.onMessageExternal.addListener(
function (request, sender, sendResponse) {
if (request.what === 'getAdCount') {
const url = request.pageURL,
count = currentCount(),
json = {
url: url,
count: count
};
console.log('[ADN] TESTING: ', JSON.stringify(json));
sendResponse({
what: 'setPageCount',
pageURL: url,
count: count
});
} else if (request.what === 'clearAds') {
clearAds();
}
});
}
/* make sure we have no bad data in ad storage */
const validateAdStorage = function () {
let ads = adlist(), i = ads.length;
if (clearAdsOnInit) {
setTimeout(function () {
warn("[DEBUG] Clearing all ad data!");
clearAds();
}, 2000);
}
if (clearVisitData) clearAdVisits(ads);
while (i--) {
if (!validateFields(ads[i])) {
warn('Invalid ad in storage', ads[i]);
ads.splice(i, 1);
}
}
validateHashes();
removePrivateAds();
computeNextId(ads = adlist());
log('[INIT] Initialized with ' + ads.length + ' ads');
}
const validMD5 = function (s) {
return remd5.test(s);
};
const validateHashes = function () {
let hashes;
let ad;
const pages = Object.keys(admap);
const unhashed = [];
const orphans = [];
/* ForEach pageKey in admap
if (pageKey is not hashed)
add pageKey to unhashed
add all its ads to orpans
if (pageKey is hashed)
add any non-hashed ads to orphans
}*/
const checkHashes = function () {
for (let i = 0; i < pages.length; i++) {
const isHashed = validMD5(pages[i]);
if (!isHashed) {
unhashed.push(pages[i]);
hashes = Object.keys(admap[pages[i]]);
for (let j = 0; j < hashes.length; j++) {
ad = admap[pages[i]][hashes[j]];
orphans.push(ad);
}
} else {
hashes = Object.keys(admap[pages[i]]);
for (let j = hashes.length - 1; j >= 0; j--) {
if (!validMD5(hashes[j])) {
ad = admap[pages[i]][hashes[j]];
delete admap[pages[i]][hashes[j]];
orphans.push(ad);
}
}
}
}
/* if (found unhashed or orphans)
Delete unhashed entries from admap
Add each orphan back to admap
*/
const repairHashes = function () {
orphans.forEach(function (ad) {
createAdmapEntry(ad, admap)
});
unhashed.forEach(function (k) {
delete admap[k]
});
};
if (unhashed.length || orphans.length) repairHashes();
};
checkHashes();
//log('[CRYPT] '+adCount()+ ' ads hash-verified');
}
const clearAdVisits = function (ads) { // for dev-debugging only
warn("[WARN] Clearing all Ad visit data!");
ads = ads || adlist();
ads.forEach(function (ad) {
delete ad.noVisit; // Note: ignore click-prob & assume all ads should be re-visited
delete ad.resolvedTargetUrl;
ad.attemptedTs = 0;
ad.visitedTs = 0;
ad.attempts = 0
});
}
// compute the highest id still in the admap
const computeNextId = function (ads) {
ads = ads || adlist();
idgen = Math.max(0, (Math.max.apply(Math,
ads.map(function (ad) {
return ad ? ad.id : -1;
}))));
}
const pollQueue = function (interval) {
interval = interval || pollQueueInterval;
markActivity();
// changes for #1657
//const pending = pendingAds();
const settings = µb.userSettings;
if (/*pending.length && */settings.clickingAds && !isAutomated()) { // no visits if automated
// check whether an idle timeout has been specified
const idleMs = disableIdler ? 0 : settings.clickOnlyWhenIdleFor;
if (!idleMs || (millis() - lastUserActivity > idleMs)) {
//idleMs && log("[IDLER] "+(millis() - lastUserActivity)+"ms, clicking resumed...");
let next;
if (visitPending(inspected)) {
// if an unvisited ad is being inspected, visit it next
next = inspected;
} else {
// else we pick the next ad needing a visit
next = nextPending();
}
next != undefined && visitAd(next);
}
else if (idleMs) {
log('[IDLER] ' + (millis() - lastUserActivity) + 'ms, waiting until ' + idleMs + 'ms...'); // TMP
}
}
// next poll
//setTimeout(pollQueue, Math.max(1, interval - (millis() - lastActivity)));
setTimeout(pollQueue, Math.max(interval / 2, interval - (millis() - lastActivity)));
}
const markActivity = function () {
return (lastActivity = millis());
}
const nextPending = function () {
let ads = adlist();
// @SALLY: if we sort here newer ads are visited first ?
//ads = ads.sort(byField('-foundTs'));
for (let i = 0; i < ads.length; i++) {
if (visitPending(ads[i])) return ads[i];
}
}
const pendingAds = function () {
return adlist().filter(function (a) {
return visitPending(a);
});
}
const visitPending = function (ad) {
let pending = ad && ad.attempts < maxAttemptsPerAd &&
ad.visitedTs <= 0 && !ad.dntAllowed && !ad.noVisit;
if (pending && visitedURLs.has(ad.targetUrl)) {
log('[NOVISIT] User has already clicked the ad', ad.targetUrl);
ad.noVisit = true; // so we don't recheck it
ad.clickedByUser = true;
pending = false;
}
return pending;
}
const isPopupOpen = function () {
return vAPI.getViews({ type: "popup" }).length;
};
const getExtPageTabId = function (htmlPage) {
const pageUrl = vAPI.getURL(htmlPage);
for (let e of µb.pageStores) {
const pageStore = e[1];
if (pageStore !== null && pageStore.rawURL.startsWith(pageUrl))
return pageStore.tabId;
}
};
const updateAdOnFailure = function (xhr, e) {
const ad = xhr.delegate;
if (ad && ad.visitedTs <= 0) { // make sure we haven't visited already
// update the ad
ad.visitedTs = -millis();
if (!ad.errors) ad.errors = [];
ad.errors.push(xhr.status + ' (' +
xhr.statusText + ')' + (e ? ' ' + e.type : ''));
if (ad.attempts >= maxAttemptsPerAd) {
log('[FAILED] ' + adinfo(ad), ad); // this);
if (ad.title === 'Pending') ad.title = 'Failed';
}
broadcast({
what: 'adVisited',
ad: ad
});
} else {
err("No Ad in updateAdOnFailure()", xhr, e);
}
};
/* send to vault/menu/dashboard if open */
const sendNotifications = function (notes) {
broadcast({
what: 'notifications',
notifications: notes
// TODO: do we need to make these cloneable ? see #1163
});
};
const parseTitle = function (xhr) {
const html = xhr.responseText;
let title = html.match(/<title[^>]*>([^<]+)<\/title>/i);
if (title && title.length > 1) {
title = unescapeHTML(title[1].trim());
for (let i = 0; i < errorStrings.length; i++) {
// check the title isn't something like 'file not found'
if (title.toLowerCase().indexOf(errorStrings[i]) > -1) {
onVisitError.call(xhr, {
title: title,
status: xhr.status,
responseText: html
});
throw Error('Bad-title: ' + title + " from: " + xhr.requestUrl);
}
}
return title;
}
const shtml = html.length > 100 ? html.substring(0, 100) + '...' : html;
warn('[VISIT] No title for ' + xhr.requestUrl, 'Html:\n' + shtml);
return false;
};
const updateAdOnSuccess = async function (xhr, ad, title) {
ad = xhr.delegate;
if (ad) {
if (title) ad.title = title;
if (ad.title === 'Pending')
ad.title = parseDomain(xhr.requestUrl, true);
ad.resolvedTargetUrl = xhr.responseURL; // URL after redirects
ad.visitedTs = millis(); // successful visit time
const tab = await vAPI.tabs.getCurrent();
if (tab && tab.id) { // do click animation
const tabId = tab.id;
µb.updateToolbarIcon(tabId, 0b0111, true); // click icon
}
// else warn('Null tab in click animation: ', tab); // not a problem
broadcast({
what: 'adVisited',
ad: ad
});
if (ad === inspected) inspected = null;
log('[VISIT] ' + adinfo(ad), ad.title);
}
storeAdData();
};
// returns the current active visit attempt or null
const activeVisit = function (pageUrl) {
if (xhr && xhr.delegate) {
if (!pageUrl || xhr.delegate === pageUrl)
return xhr.delegate;
}
};
const onVisitError = function (e) {
if (this == undefined) return;
this.onload = this.onerror = this.ontimeout = null;
markActivity();
// Is it a timeout?
if (e.type === 'timeout') {
warn('[TIMEOUT] Visiting ' + this.requestUrl); //, e, this);
} else {
// or some other error?
warn('onVisitError()', e, this.requestUrl, this.statusText); // this);
}
if (!this.delegate) {
return err('Request received without Ad: ' + this.responseURL);
}
updateAdOnFailure(this, e);
xhr = null; // end the visit
};
const onVisitResponse = function () {
this.onload = this.onerror = this.ontimeout = null;
markActivity();
const ad = this.delegate;
if (!ad) {
return err('Request received without Ad: ' + this.responseURL);
}
if (!ad.id) {
return warn("Visit response from deleted ad! ", ad);
}
ad.attemptedTs = 0; // reset as visit no longer in progress
const status = this.status || 200, html = this.responseText;
if (failAllVisits || status < 200 || status >= 300) {
return onVisitError.call(this, {
status: status,
responseText: html
});
}
try {
if (!isFacebookExternal(this, ad)) {
updateAdOnSuccess(this, ad, parseTitle(this));
}
} catch (e) {
warn(e.message);
}
xhr = null; // end the visit
};
// Checks for external FB link and if so, parses the true link
const isFacebookExternal = function (xhr, ad) {
if (/facebook\.com\/l\.php/.test(xhr.requestUrl)) {
const url = decodeURIComponent(xhr.responseURL);
ad.parsedTargetUrl = decodeURIComponent(url.substring(url.lastIndexOf('http')));
log("[FB-EXT] Parsed: ", ad.parsedTargetUrl);
return true;
}
};
const visitAd = function (ad) {
function timeoutError(xhr) {
return onVisitError.call(xhr, {
type: 'timeout'
});
}
const url = ad && ad.targetUrl, now = markActivity();
// tell menu/vault we have a new attempt
broadcast({
what: 'adAttempt',
ad: ad
});
if (xhr) {
if (xhr.delegate.attemptedTs) {
const elapsed = (now - xhr.delegate.attemptedTs);
// TODO: why does this happen... a redirect?
warn('[TRYING] Attempt to reuse xhr from ' + elapsed + " ms ago");
if (elapsed > visitTimeout)
timeoutError();
}
else {
warn('[TRYING] Attempt to reuse xhr with no attemptedTs!!', xhr);
}
}
ad.attempts++;
ad.attemptedTs = now;
if (!validateTarget(ad)) return deleteAd(ad);
return sendXhr(ad);
// return openAdInNewTab(ad);
// return popUnderAd(ad)
};
const sendXhr = function (ad) {
// if we've parsed an obfuscated target, use it
const target = ad.parsedTargetUrl || ad.targetUrl;
log('[TRYING] ' + adinfo(ad), ad.targetUrl);
xhr = new XMLHttpRequest();
try {
xhr.open('get', target, true);
xhr.withCredentials = true;
xhr.delegate = ad;
xhr.timeout = visitTimeout;
xhr.onload = onVisitResponse;
xhr.onerror = onVisitError;
xhr.ontimeout = onVisitError;
xhr.responseType = ''; // 'document'?;
xhr.send();
} catch (e) {
onVisitError.call(xhr, e);
}
}
const storeAdData = function (immediate) {
// always update store as long as adsetSize is less than 1000
if (adsetSize < 1000) immediate = true;
const now = millis();
// defer if we've recently written and !immediate
if (immediate || (!immediate && now - lastStorageUpdate > updateStorageInterval)) {
vAPI.storage.set({ admap: admap });
µb.changeUserSettings('admap', admap);
lastStorageUpdate = millis();
//log("--Storage Ad Data--")
}
}
const validateTarget = function (ad) {
const url = ad.targetUrl;
if (!/^http/.test(url)) {
// Here we try to extract an obfuscated URL
const idx = url.indexOf('http');
if (idx != -1) {
ad.targetUrl = decodeURIComponent(url.substring(idx));
log("Ad.targetUrl updated: " + ad.targetUrl);
} else {
return warn("Invalid targetUrl: " + url);
}
}
// ad.targetUrl = trimChar(ad.targetUrl, '/'); #751
const dInfo = domainInfo(ad.resolvedTargetUrl || ad.targetUrl);
if (!isValidDomain(dInfo.domain)) {
return warn("Invalid domain: " + url);
}
ad.targetHostname = dInfo.hostname;
ad.targetDomain = dInfo.domain;
// Check: a slash at the end of the domain https://github.com/dhowe/AdNauseam/issues/1304
const idx = url.indexOf(ad.targetDomain) + ad.targetDomain.length;
if (idx < url.length - 1 && url.charAt(idx) != "/") {
ad.targetUrl = url.substring(0, idx) + "/" + url.substring(idx, url.length);
}
return true;
}
const domainInfo = function (url) { // via uBlock/psl
const hostname = hostnameFromURI(url);
const domain = domainFromHostname(hostname);
return { hostname: hostname, domain: domain };
}
const domainFromURI = function (url) { // TODO: replace all uses with domainInfo()
return domainFromHostname(hostnameFromURI(url));
};
const validateFields = function (ad) {
if (ad.visitedTs === 0 && ad.attempts > 0) {
warn('Invalid visitTs/attempts pair', ad);
ad.attempts = 0; // shouldn't happen
}
if (!(ad.pageUrl.startsWith('http') || ad.pageUrl === redactMarker))
warn('Possibly Invalid PageUrl: ', ad.pageUrl);
// re-add if stripped in export
ad.pageDomain = ad.pageDomain || domainFromURI(ad.pageUrl) || ad.pageUrl;
ad.targetDomain = ad.targetDomain || domainFromURI(ad.resolvedTargetUrl || ad.targetUrl);
ad.targetHostname = ad.targetHostname || hostnameFromURI(ad.resolvedTargetUrl || ad.targetUrl);
return ad && type(ad) === 'object' &&
type(ad.pageUrl) === 'string' &&
type(ad.contentType) === 'string' &&
type(ad.contentData) === 'object';
}
const validate = function (ad) {
if (!validateFields(ad)) {
return warn('Invalid ad-fields: ', ad);
}
const cd = ad.contentData, ct = ad.contentType, pu = ad.pageUrl;
ad.title = unescapeHTML(ad.title); // fix to #31
if (ct === 'text') {
cd.title = unescapeHTML(cd.title);
cd.text = unescapeHTML(cd.text);
} else if (ct === 'img') {
if (!/^http/.test(cd.src) && !/^data:image/.test(cd.src)) {
if (/^\/\//.test(cd.src)) {
cd.src = 'http:' + cd.src;
} else {
log("Relative-image: " + cd.src);
cd.src = pu.substring(0, pu.lastIndexOf('/')) + '/' + cd.src;
log(" --> " + cd.src);
}
}
} else {
warn('Invalid ad type: ' + ct);
}
return validateTarget(ad);
};
const clearAdmap = function () {
const pages = Object.keys(admap);
for (let i = 0; i < pages.length; i++) {
if (admap[pages[i]]) {
const hashes = Object.keys(admap[pages[i]]);
for (let j = 0; j < hashes.length; j++) {
delete admap[pages[i]][hashes[j]];
}
}
delete admap[pages[i]];
}
admap = {}; // redundant, remove
};
const purgeDeadAdsAdmap = function (deadAds) {
let deadIds = deadAds.map(deadad => deadad.children.map(c => c.id)[0])
const pages = Object.keys(admap);
for (let i = 0; i < pages.length; i++) {
if (admap[pages[i]]) {
const hashes = Object.keys(admap[pages[i]]);
for (let j = 0; j < hashes.length; j++) {
let ad = admap[pages[i]][hashes[j]];
if (deadIds.includes(ad.id)) {
delete admap[pages[i]][hashes[j]];
}
}
}
if (admap[pages[i]].length < 1) {
delete admap[pages[i]];
}
}
}
const millis = function () {
return +new Date();
}
const adinfo = function (ad) {
const id = ad.id || '?';
return 'Ad#' + id + '(' + ad.contentType + ')';
}
const unescapeHTML = function (s) { // hack
if (s && s.length) {
const entities = [
'#0*32', ' ',
'#0*33', '!',
'#0*34', '"',
'#0*35', '#',
'#0*36', '$',
'#0*37', '%',
'#0*38', '&',
'#0*39', '\'',
'apos', '\'',
'amp', '&',
'lt', '<',
'gt', '>',
'quot', '"',
'#x27', '\'',
'#x60', '`'
];
for (let i = 0; i < entities.length; i += 2) {
s = s.replace(new RegExp('\&' + entities[i] + ';', 'g'), entities[i + 1]);
}
}
return s;
}
const adById = function (id) {
const list = adlist();
for (let i = 0; i < list.length; i++) {
if (list[i].id === id)
return list[i];
}
};
const reloadExtPage = function (htmlPage) {
const tabId = getExtPageTabId(htmlPage);
tabId && vAPI.tabs.reload(tabId);
};
const deleteAd = function (arg) {
const ad = type(arg) === 'object' ? arg : adById(arg), count = adCount();
if (!ad) {
return warn("No Ad to delete", id, admap);
}
const pageHash = YaMD5.hashStr(ad.pageUrl);
if (admap[pageHash]) {
if (pageHash == YaMD5.hashStr("")) {
// private ads, remove all private ads because it's impossible to select each private ad
delete admap[pageHash];
} else {
const hash = computeHash(ad);
if (admap[pageHash][hash]) {
delete admap[pageHash][hash];
} else {
return warn('Delete failed, no ad: ', ad, admap);
}
}
}
else {
return warn('Delete failed, no page key: ', ad, admap);
}
if (adCount() < count) {
log('[DELETE] ' + adinfo(ad));
updateBadges();
} else {
return warn('Unable to delete: ', ad);
}
adsetSize--;
storeAdData();
}
const deadAd = function (ad, setDead) {
console.log("deadAd", ad)
if (!ad) {
return warn("No Ad to set Dead", id, admap);
}
const pageHash = YaMD5.hashStr(ad.pageUrl);
if (pageHash !== YaMD5.hashStr("")) {
const hash = computeHash(ad);
if (admap[pageHash][hash]) {
let addata = admap[pageHash][hash];
if(setDead) { // set ad as dead
if (admap[pageHash][hash]["dead"]) {
admap[pageHash][hash]["dead"] = parseInt(admap[pageHash][hash]["dead"]) + 1;
} else {
admap[pageHash][hash]["dead"] = 1;
}
} else { // set as not dead
admap[pageHash][hash]["dead"] = 0;
}
storeAdData();
}
}
}
const adsForUI = function (pageUrl) {
return {
data: adlist(pageUrl, false, true),
pageUrl: pageUrl,
prefs: contentPrefs(),
current: activeVisit(),
notifications: notifications
};
};