forked from gorhill/httpswitchboard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
1674 lines (1437 loc) · 54.6 KB
/
popup.js
File metadata and controls
1674 lines (1437 loc) · 54.6 KB
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
/*******************************************************************************
httpswitchboard - a Chromium browser extension to black/white list requests.
Copyright (C) 2013 Raymond Hill
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/httpswitchboard
*/
// TODO: cleanup
/******************************************************************************/
/******************************************************************************/
(function() {
/******************************************************************************/
/******************************************************************************/
var HTTPSB = chrome.extension.getBackgroundPage().HTTPSB;
var targetTabId;
var targetPageURL;
var targetPageHostname;
var targetPageDomain;
var matrixCellHotspots = null;
var matrixHasRows = false;
/******************************************************************************/
/******************************************************************************/
// https://github.com/gorhill/httpswitchboard/issues/345
messaging.start('popup.js');
var onMessage = function(msg) {
if ( msg.what === 'urlStatsChanged' ) {
if ( targetPageURL === msg.pageURL ) {
makeMenu();
}
}
};
messaging.listen(onMessage);
/******************************************************************************/
/******************************************************************************/
function getPageStats() {
return HTTPSB.pageStatsFromTabId(targetTabId);
}
/******************************************************************************/
function getUserSetting(setting) {
return HTTPSB.userSettings[setting];
}
function setUserSetting(setting, value) {
messaging.tell({
what: 'userSettings',
name: setting,
value: value
});
}
/******************************************************************************/
function EntryStats(hostname, type) {
this.hostname = hostname;
this.type = type;
this.count = 0;
this.temporaryColor = '';
this.permanentColor = '';
}
EntryStats.prototype.reset = function(hostname, type) {
if ( hostname ) {
this.hostname = hostname;
}
if ( type ) {
this.type = type;
}
this.count = 0;
};
EntryStats.prototype.colourize = function(httpsb, scopeKey) {
httpsb = httpsb || HTTPSB;
if ( !this.hostname || !this.type ) {
return;
}
this.temporaryColor = httpsb.getTemporaryColor(scopeKey, this.type, this.hostname);
this.permanentColor = httpsb.getPermanentColor(scopeKey, this.type, this.hostname);
};
EntryStats.prototype.add = function(other) {
this.count += other.count;
};
/******************************************************************************/
function HostnameStats(hostname) {
this.hostname = hostname;
this.types = {
'*': new EntryStats(hostname, '*'),
main_frame: new EntryStats(hostname, 'main_frame'),
cookie: new EntryStats(hostname, 'cookie'),
stylesheet: new EntryStats(hostname, 'stylesheet'),
image: new EntryStats(hostname, 'image'),
object: new EntryStats(hostname, 'object'),
script: new EntryStats(hostname, 'script'),
xmlhttprequest: new EntryStats(hostname, 'xmlhttprequest'),
sub_frame: new EntryStats(hostname, 'sub_frame'),
other: new EntryStats(hostname, 'other')
};
}
HostnameStats.prototype.junkyard = [];
HostnameStats.prototype.factory = function(hostname) {
var domainStats = HostnameStats.prototype.junkyard.pop();
if ( domainStats ) {
domainStats.reset(hostname);
} else {
domainStats = new HostnameStats(hostname);
}
return domainStats;
};
HostnameStats.prototype.reset = function(hostname) {
if ( hostname ) {
this.hostname = hostname;
} else {
hostname = this.hostname;
}
this.types['*'].reset(hostname);
this.types.main_frame.reset(hostname);
this.types.cookie.reset(hostname);
this.types.stylesheet.reset(hostname);
this.types.image.reset(hostname);
this.types.object.reset(hostname);
this.types.script.reset(hostname);
this.types.xmlhttprequest.reset(hostname);
this.types.sub_frame.reset(hostname);
this.types.other.reset(hostname);
};
HostnameStats.prototype.dispose = function() {
HostnameStats.prototype.junkyard.push(this);
};
HostnameStats.prototype.colourize = function(httpsb, scopeKey) {
httpsb = httpsb || HTTPSB;
this.types['*'].colourize(httpsb, scopeKey);
this.types.main_frame.colourize(httpsb, scopeKey);
this.types.cookie.colourize(httpsb, scopeKey);
this.types.stylesheet.colourize(httpsb, scopeKey);
this.types.image.colourize(httpsb, scopeKey);
this.types.object.colourize(httpsb, scopeKey);
this.types.script.colourize(httpsb, scopeKey);
this.types.xmlhttprequest.colourize(httpsb, scopeKey);
this.types.sub_frame.colourize(httpsb, scopeKey);
this.types.other.colourize(httpsb, scopeKey);
};
HostnameStats.prototype.add = function(other) {
var thisTypes = this.types;
var otherTypes = other.types;
thisTypes['*'].add(otherTypes['*']);
thisTypes.main_frame.add(otherTypes.main_frame);
thisTypes.cookie.add(otherTypes.cookie);
thisTypes.stylesheet.add(otherTypes.stylesheet);
thisTypes.image.add(otherTypes.image);
thisTypes.object.add(otherTypes.object);
thisTypes.script.add(otherTypes.script);
thisTypes.xmlhttprequest.add(otherTypes.xmlhttprequest);
thisTypes.sub_frame.add(otherTypes.sub_frame);
thisTypes.other.add(otherTypes.other);
};
/******************************************************************************/
function MatrixStats() {
// hostname '*' always present
this['*'] = HostnameStats.prototype.factory('*');
}
MatrixStats.prototype.createMatrixStats = function() {
return new MatrixStats();
};
MatrixStats.prototype.reset = function() {
var hostnames = Object.keys(this);
var i = hostnames.length;
var hostname, prop;
while ( i-- ) {
hostname = hostnames[i];
prop = this[hostname];
if ( hostname !== '*' && prop instanceof HostnameStats ) {
prop.dispose();
delete this[hostname];
}
}
this['*'].reset();
};
/******************************************************************************/
var HTTPSBPopup = {
scopeKey: '*',
matrixDomains: {},
matrixStats: MatrixStats.prototype.createMatrixStats(),
matrixHeaderTypes: ['*'],
matrixGroup3Collapsed: false,
groupsSnapshot: [],
domainListSnapshot: 'do not leave this initial string empty',
matrixHeaderPrettyNames: {
'all': '',
'cookie': '',
'stylesheet': '',
'image': '',
'object': '',
'script': '',
'xmlhttprequest': '',
'sub_frame': '',
'other': ''
},
dummy: 0
};
/******************************************************************************/
// This creates a stats entry for each possible rows in the matrix.
function initMatrixStats() {
var pageStats = getPageStats();
if ( !pageStats ) {
return;
}
var matrixStats = HTTPSBPopup.matrixStats;
matrixStats.reset();
// collect all hostnames and ancestors from net traffic
var httpsburi = HTTPSB.URI;
var hostname, reqType, nodes, iNode, node, reqKey, types;
var pageRequests = pageStats.requests;
var reqKeys = pageRequests.getRequestKeys();
var iReqKey = reqKeys.length;
matrixHasRows = iReqKey > 0;
while ( iReqKey-- ) {
reqKey = reqKeys[iReqKey];
hostname = pageRequests.hostnameFromRequestKey(reqKey);
// rhill 2013-10-23: hostname can be empty if the request is a data url
// https://github.com/gorhill/httpswitchboard/issues/26
if ( hostname === '' ) {
hostname = targetPageHostname;
}
reqType = pageRequests.typeFromRequestKey(reqKey);
// we want a row for self and ancestors
nodes = httpsburi.allHostnamesFromHostname(hostname);
iNode = nodes.length;
while ( iNode-- ) {
node = nodes[iNode];
if ( !matrixStats[node] ) {
matrixStats[node] = HostnameStats.prototype.factory(node);
}
}
types = matrixStats[hostname].types;
types[reqType].count += 1;
// https://github.com/gorhill/httpswitchboard/issues/12
// Count requests for whole row.
types['*'].count += 1;
}
updateMatrixStats();
return matrixStats;
}
/******************************************************************************/
function updateMatrixStats() {
// For each hostname/type occurrence, evaluate colors
var httpsb = HTTPSB;
var scopeKey = httpsb.temporaryScopeKeyFromPageURL(targetPageURL);
var matrixStats = HTTPSBPopup.matrixStats;
for ( var hostname in matrixStats ) {
if ( !matrixStats.hasOwnProperty(hostname) ) {
continue;
}
matrixStats[hostname].colourize(httpsb, scopeKey);
}
}
/******************************************************************************/
// For display purpose, create four distinct groups of rows:
// 1st: page domain's related
// 2nd: whitelisted
// 3rd: graylisted
// 4th: blacklisted
function getGroupStats() {
// Try to not reshuffle groups around while popup is opened if
// no new hostname added.
var matrixStats = HTTPSBPopup.matrixStats;
var latestDomainListSnapshot = Object.keys(matrixStats).sort().join();
if ( latestDomainListSnapshot === HTTPSBPopup.domainListSnapshot ) {
return HTTPSBPopup.groupsSnapshot;
}
HTTPSBPopup.domainListSnapshot = latestDomainListSnapshot;
var groups = [
{},
{},
{},
{}
];
// First, group according to whether at least one node in the domain
// hierarchy is white or blacklisted
var httpsburi = HTTPSB.URI;
var pageDomain = targetPageDomain;
var hostname, domain, nodes, node;
var temporaryColor;
var dark, group;
var hostnames = Object.keys(matrixStats);
var iHostname = hostnames.length;
while ( iHostname-- ) {
hostname = hostnames[iHostname];
// '*' is for header, ignore, since header is always at the top
if ( hostname === '*' ) {
continue;
}
// https://github.com/gorhill/httpswitchboard/issues/12
// Ignore rows with no request for now.
if ( matrixStats[hostname].types['*'].count === 0 ) {
continue;
}
// Walk upward the chain of hostname and find at least one which
// is expressly whitelisted or blacklisted.
nodes = httpsburi.allHostnamesFromHostname(hostname);
domain = nodes[nodes.length-1];
while ( true ) {
node = nodes.shift();
if ( !node ) {
break;
}
temporaryColor = matrixStats[node].types['*'].temporaryColor;
dark = temporaryColor.charAt(1) === 'd';
if ( dark ) {
break;
}
}
// Domain of the page comes first
if ( domain === pageDomain ) {
group = 0;
}
// Whitelisted hostnames are second, blacklisted are fourth
else if ( dark ) {
group = temporaryColor.charAt(0) === 'g' ? 1 : 3;
// Graylisted are third
} else {
group = 2;
}
if ( !groups[group][domain] ) {
groups[group][domain] = { all: {}, withRules: {} };
}
groups[group][domain].withRules[hostname] = true;
}
// At this point, one domain could end up in two different groups.
// Generate all nodes possible for each groups, this is useful
// to allow users to toggle permissions for higher-level hostnames
// which are not explicitly part of the web page.
var iGroup = groups.length;
var domains, iDomain;
while ( iGroup-- ) {
group = groups[iGroup];
domains = Object.keys(group);
iDomain = domains.length;
while ( iDomain-- ) {
domain = domains[iDomain];
hostnames = Object.keys(group[domain].withRules);
iHostname = hostnames.length;
while ( iHostname-- ) {
nodes = httpsburi.allHostnamesFromHostname(hostnames[iHostname]);
while ( true ) {
node = nodes.shift();
if ( !node ) {
break;
}
group[domain].all[node] = group[domain].withRules[node];
}
}
}
}
HTTPSBPopup.groupsSnapshot = groups;
return groups;
}
/******************************************************************************/
// helpers
function getCellStats(hostname, type) {
var matrixStats = HTTPSBPopup.matrixStats;
if ( matrixStats[hostname] ) {
return matrixStats[hostname].types[type];
}
return null;
}
function getTemporaryColor(hostname, type) {
var entry = getCellStats(hostname, type);
if ( entry ) {
return entry.temporaryColor;
}
return '';
}
function getPermanentColor(hostname, type) {
var entry = getCellStats(hostname, type);
if ( entry ) {
return entry.permanentColor;
}
return '';
}
function getCellClass(hostname, type) {
var temporaryColor = getTemporaryColor(hostname, type);
var permanentColor = getPermanentColor(hostname, type);
if ( permanentColor === 'xxxx' ) {
return temporaryColor;
}
return temporaryColor + ' ' + permanentColor;
}
// compute next state
function getNextAction(hostname, type, leaning) {
var entry = HTTPSBPopup.matrixStats[hostname].types[type];
var temporaryColor = entry.temporaryColor;
// special case: root toggle only between two states
if ( type === '*' && hostname === '*' ) {
return temporaryColor.charAt(0) === 'g' ? 'blacklist' : 'whitelist';
}
// Lean toward whitelisting?
if ( leaning === 'whitelisting' ) {
if ( temporaryColor.charAt(1) !== 'd' ) {
return 'whitelist';
}
return 'graylist';
}
// Lean toward blacklisting
if ( temporaryColor.charAt(1) !== 'd' ) {
return 'blacklist';
}
return 'graylist';
}
/******************************************************************************/
// This is required for when we update the matrix while it is open:
// the user might have collapsed/expanded one or more domains, and we don't
// want to lose all his hardwork.
function getCollapseState(domain) {
var states = getUserSetting('popupCollapseSpecificDomains');
if ( states !== undefined && states[domain] !== undefined ) {
return states[domain];
}
return getUserSetting('popupCollapseDomains');
}
function toggleCollapseState(element) {
element = $(element);
if ( element.parents('#matHead.collapsible').length > 0 ) {
toggleMainCollapseState(element);
} else {
toggleSpecificCollapseState(element);
}
}
function toggleMainCollapseState(element) {
var matHead = element.parents('#matHead.collapsible')
.toggleClass('collapsed');
var collapsed = matHead.hasClass('collapsed');
$('#matList .matSection.collapsible').toggleClass('collapsed', collapsed);
setUserSetting('popupCollapseDomains', collapsed);
var specificCollapseStates = getUserSetting('popupCollapseSpecificDomains') || {};
var domains = Object.keys(specificCollapseStates);
var i = domains.length;
var domain;
while ( i-- ) {
domain = domains[i];
if ( specificCollapseStates[domain] === collapsed ) {
delete specificCollapseStates[domain];
}
}
setUserSetting('popupCollapseSpecificDomains', specificCollapseStates);
}
function toggleSpecificCollapseState(element) {
// Remember collapse state forever, but only if it is different
// from main collapse switch.
var section = element.parents('.matSection.collapsible')
.toggleClass('collapsed');
var domain = section.prop('domain');
var collapsed = section.hasClass('collapsed');
var mainCollapseState = getUserSetting('popupCollapseDomains');
var specificCollapseStates = getUserSetting('popupCollapseSpecificDomains') || {};
if ( collapsed !== mainCollapseState ) {
specificCollapseStates[domain] = collapsed;
setUserSetting('popupCollapseSpecificDomains', specificCollapseStates);
} else if ( specificCollapseStates[domain] !== undefined ) {
delete specificCollapseStates[domain];
setUserSetting('popupCollapseSpecificDomains', specificCollapseStates);
}
}
/******************************************************************************/
// Update color of matrix cells(s)
// Color changes when rules change
function updateMatrixColors() {
var cells = $('.matrix .matRow.rw > .matCell');
var i = cells.length;
var cell;
while ( i-- ) {
cell = $(cells[i]);
cell.removeClass()
.addClass('matCell ' + getCellClass(cell.prop('hostname'), cell.prop('reqType')));
}
}
/******************************************************************************/
// Update request count of matrix cells(s)
// Count changes when number of distinct requests changes
function updateMatrixCounts() {
}
/******************************************************************************/
// Update behavior of matrix:
// - Whether a section is collapsible or not. It is collapsible if:
// - It has at least one subdomain AND
// - There is no explicit rule anywhere in the subdomain cells AND
// - It is not part of group 3 (blacklisted hostnames)
function updateMatrixBehavior() {
matrixList = matrixList || $('#matList');
var sections = matrixList.find('.matSection');
var i = sections.length;
var section, subdomainRows, j, subdomainRow;
while ( i-- ) {
section = $(sections[i]);
subdomainRows = section.children('.l2:not(.g3)');
j = subdomainRows.length;
while ( j-- ) {
subdomainRow = $(subdomainRows[j]);
subdomainRow.toggleClass('collapsible', subdomainRow.children('.gdt,.rdt').length === 0);
}
section.toggleClass('collapsible', subdomainRows.filter('.collapsible').length > 0);
}
}
/******************************************************************************/
// handle user interaction with filters
function handleFilter(button, leaning) {
var httpsb = HTTPSB;
var scopeKey = httpsb.temporaryScopeKeyFromPageURL(targetPageURL);
// our parent cell knows who we are
var cell = button.closest('div.matCell');
var type = cell.prop('reqType');
var hostname = cell.prop('hostname');
var nextAction = getNextAction(hostname, type, leaning);
if ( nextAction === 'blacklist' ) {
httpsb.blacklistTemporarily(scopeKey, type, hostname);
} else if ( nextAction === 'whitelist' ) {
httpsb.whitelistTemporarily(scopeKey, type, hostname);
} else {
httpsb.graylistTemporarily(scopeKey, type, hostname);
}
updateMatrixStats();
updateMatrixColors();
updateMatrixBehavior();
updateMatrixButtons();
}
function handleWhitelistFilter(button) {
handleFilter(button, 'whitelisting');
}
function handleBlacklistFilter(button) {
handleFilter(button, 'blacklisting');
}
/******************************************************************************/
function getTemporaryRuleset() {
var httpsb = HTTPSB;
var tScopeKey = httpsb.temporaryScopeKeyFromPageURL(targetPageURL);
var pScopeKey = httpsb.permanentScopeKeyFromPageURL(targetPageURL);
var rules = {
tScopeKey: tScopeKey,
pScopeKey: pScopeKey,
add: { white: [], black: [], gray: [] },
remove: { white: [], black: [], gray: [] },
mtxFiltering: httpsb.getTemporaryMtxFiltering(tScopeKey),
abpFiltering: httpsb.getTemporaryABPFiltering(tScopeKey),
count: 0
};
var tscope = httpsb.temporaryScopeFromScopeKey(tScopeKey);
var pscope = pScopeKey === tScopeKey ? httpsb.permanentScopeFromScopeKey(pScopeKey) : null;
var matrixStats = HTTPSBPopup.matrixStats;
var rule, parts;
var listKeys = [ 'white', 'black', 'gray' ];
var listKey;
while ( listKey = listKeys.pop() ) {
// This loop is to find rules in temporary scope which are not found
// in permanent scope (if any).
for ( rule in tscope[listKey].list ) {
if ( pscope && pscope[listKey].list[rule] ) {
continue;
}
// 0 = type, 1 = hostname
parts = rule.split('|');
// For global scope, limit the set of rules to those which
// intersect the matrix content: because the global
// scope means "all of internet", we wouldn't want to
// report temporary rules which are unrelated to the current
// matrix.
if ( tScopeKey === '*' && matrixStats.hasOwnProperty(parts[1]) === false ) {
continue;
}
rules.add[listKey].push({ hostname: parts[1], type: parts[0] });
rules.count += 1;
}
// This loop is to find rules in permanent scope (if any) which
// are not found in temporary scope.
if ( !pscope ) {
continue;
}
for ( rule in pscope[listKey].list ) {
if ( tscope[listKey].list[rule] ) {
continue;
}
// 0 = type, 1 = hostname
parts = rule.split('|');
// For global scope, limit the set of rules to those which
// intersect the matrix content: because the global
// scope means "all of internet", we wouldn't want to
// report temporary rules which are unrelated to the current
// matrix.
if ( pScopeKey === '*' && matrixStats.hasOwnProperty(parts[1]) === false ) {
continue;
}
rules.remove[listKey].push({ hostname: parts[1], type: parts[0] });
rules.count += 1;
}
}
if ( !pscope || rules.mtxFiltering !== pscope.mtxFiltering ) {
rules.count += 1;
}
if ( !pscope || rules.abpFiltering !== pscope.abpFiltering ) {
rules.count += 1;
}
// A temporary scope different from the permanent scope counts for one.
if ( tScopeKey !== pScopeKey ) {
rules.count += 1;
}
// If temporary scope is different than permanent scope, all the rules in
// the permanent scope of narrower level would cease to exist, so we need
// to count them as well.
// TODO: Undecided whether this should be accounted for, as they are not
// seen by the user.
return rules;
}
/******************************************************************************/
var matrixRowPool = [];
var matrixSectionPool = [];
var matrixGroupPool = [];
var matrixRowTemplate = null;
var matrixList = null;
var startMatrixUpdate = function() {
matrixList = matrixList || $('#matList');
matrixList.detach();
var rows = matrixList.find('.matRow');
rows.detach();
matrixRowPool = matrixRowPool.concat(rows.toArray());
var sections = matrixList.find('.matSection');
sections.detach();
matrixSectionPool = matrixSectionPool.concat(sections.toArray());
var groups = matrixList.find('.matGroup');
groups.detach();
matrixGroupPool = matrixGroupPool.concat(groups.toArray());
};
var endMatrixUpdate = function() {
// https://github.com/gorhill/httpswitchboard/issues/246
// If the matrix has no rows, we need to insert a dummy one, invisible,
// to ensure the extension pop-up is properly sized. This is needed because
// the header pane's `position` property is `fixed`, which means it doesn't
// affect layout size, hence the matrix header row will be truncated.
if ( !matrixHasRows ) {
matrixList.append(createMatrixRow().css('visibility', 'hidden'));
}
updateMatrixBehavior();
matrixList.css('display', '');
matrixList.appendTo($('.paneContent'));
};
var createMatrixGroup = function() {
var group = matrixGroupPool.pop();
if ( group ) {
return $(group).removeClass().addClass('matGroup');
}
return $('<div>').addClass('matGroup');
};
var createMatrixSection = function() {
var section = matrixSectionPool.pop();
if ( section ) {
return $(section).removeClass().addClass('matSection');
}
return $('<div>').addClass('matSection');
};
var createMatrixRow = function() {
var row = matrixRowPool.pop();
if ( row ) {
row.style.visibility = '';
row = $(row);
row.children('.matCell').removeClass().addClass('matCell');
row.removeClass().addClass('matRow');
return row;
}
if ( matrixRowTemplate === null ) {
matrixRowTemplate = $('#templates .matRow');
}
return matrixRowTemplate.clone();
};
/******************************************************************************/
function renderMatrixHeaderRow() {
var matHead = $('#matHead.collapsible');
matHead.toggleClass('collapsed', getUserSetting('popupCollapseDomains'));
var cells = matHead.find('.matCell');
$(cells[0]).prop({reqType: '*', hostname: '*'}).addClass(getCellClass('*', '*'));
$(cells[1]).prop({reqType: 'cookie', hostname: '*'}).addClass(getCellClass('*', 'cookie'));
$(cells[2]).prop({reqType: 'stylesheet', hostname: '*'}).addClass(getCellClass('*', 'stylesheet'));
$(cells[3]).prop({reqType: 'image', hostname: '*'}).addClass(getCellClass('*', 'image'));
$(cells[4]).prop({reqType: 'object', hostname: '*'}).addClass(getCellClass('*', 'object'));
$(cells[5]).prop({reqType: 'script', hostname: '*'}).addClass(getCellClass('*', 'script'));
$(cells[6]).prop({reqType: 'xmlhttprequest', hostname: '*'}).addClass(getCellClass('*', 'xmlhttprequest'));
$(cells[7]).prop({reqType: 'sub_frame', hostname: '*'}).addClass(getCellClass('*', 'sub_frame'));
$(cells[8]).prop({reqType: 'other', hostname: '*'}).addClass(getCellClass('*', 'other'));
$('#matHead .matRow').css('display', '');
}
/******************************************************************************/
function renderMatrixCellDomain(cell, domain) {
var contents = $(cell)
.prop({reqType: '*', hostname: domain})
.addClass(getCellClass(domain, '*'))
.contents();
contents[0].textContent = '\u202A' + punycode.toUnicode(domain);
contents[1].textContent = ' ';
}
function renderMatrixCellSubdomain(cell, domain, subomain) {
var contents = $(cell)
.prop({reqType: '*', hostname: subomain})
.addClass(getCellClass(subomain, '*'))
.contents();
contents[0].textContent = '\u202A' + punycode.toUnicode(subomain.slice(0, subomain.lastIndexOf(domain)-1)) + '.';
contents[1].textContent = punycode.toUnicode(domain);
}
function renderMatrixMetaCellDomain(cell, domain) {
var contents = $(cell)
.prop({reqType: '*', hostname: domain})
.addClass(getCellClass(domain, '*'))
.contents();
contents[0].textContent = '\u202A\u2217.' + punycode.toUnicode(domain);
contents[1].textContent = ' ';
}
function renderMatrixCellType(cell, hostname, type, stats) {
cell = $(cell);
cell.prop({reqType: type, hostname: hostname, count: stats.count})
.addClass(getCellClass(hostname, type));
if ( stats.count ) {
cell.text(stats.count);
} else {
cell.text('\u00A0');
}
}
function renderMatrixCellTypes(cells, hostname, stats) {
renderMatrixCellType(cells[1], hostname, 'cookie', stats.cookie);
renderMatrixCellType(cells[2], hostname, 'stylesheet', stats.stylesheet);
renderMatrixCellType(cells[3], hostname, 'image', stats.image);
renderMatrixCellType(cells[4], hostname, 'object', stats.object);
renderMatrixCellType(cells[5], hostname, 'script', stats.script);
renderMatrixCellType(cells[6], hostname, 'xmlhttprequest', stats.xmlhttprequest);
renderMatrixCellType(cells[7], hostname, 'sub_frame', stats.sub_frame);
renderMatrixCellType(cells[8], hostname, 'other', stats.other);
}
/******************************************************************************/
function makeMatrixRowDomain(domain) {
var matrixRow = createMatrixRow().addClass('rw');
var cells = matrixRow.children('.matCell');
renderMatrixCellDomain(cells[0], domain);
renderMatrixCellTypes(cells, domain, HTTPSBPopup.matrixStats[domain].types);
return matrixRow;
}
function makeMatrixRowSubdomain(domain, subdomain) {
var matrixRow = createMatrixRow().addClass('rw');
var cells = matrixRow.children('.matCell');
renderMatrixCellSubdomain(cells[0], domain, subdomain);
renderMatrixCellTypes(cells, subdomain, HTTPSBPopup.matrixStats[subdomain].types);
return matrixRow;
}
function makeMatrixMetaRowDomain(domain, stats) {
var matrixRow = createMatrixRow().addClass('rw');
var cells = matrixRow.children('.matCell');
renderMatrixMetaCellDomain(cells[0], domain);
renderMatrixCellTypes(cells, domain, stats);
return matrixRow;
}
/******************************************************************************/
function renderMatrixMetaCellType(cell, count) {
cell = $(cell);
cell.addClass('rit');
if ( count ) {
cell.text(count);
}
}
function makeMatrixMetaRow(stats) {
var typeStats = stats.types;
var matrixRow = createMatrixRow().addClass('ro');
var cells = matrixRow.children('.matCell');
var contents = $(cells[0])
.addClass('matCell rdt')
.contents();
contents[0].textContent = ' ';
contents[1].textContent = '\u202A' + typeStats['*'].count + ' blacklisted hostname(s)';
renderMatrixMetaCellType(cells[1], typeStats.cookie.count);
renderMatrixMetaCellType(cells[2], typeStats.stylesheet.count);
renderMatrixMetaCellType(cells[3], typeStats.image.count);
renderMatrixMetaCellType(cells[4], typeStats.object.count);
renderMatrixMetaCellType(cells[5], typeStats.script.count);
renderMatrixMetaCellType(cells[6], typeStats.xmlhttprequest.count);
renderMatrixMetaCellType(cells[7], typeStats.sub_frame.count);
renderMatrixMetaCellType(cells[8], typeStats.other.count);
return matrixRow;
}
/******************************************************************************/
function computeMatrixGroupMetaStats(group) {
var metaStats = new HostnameStats();
var domains = Object.keys(group);
var blacklistedCount = 0;
var i = domains.length;
var hostnames, hostname, j;
while ( i-- ) {
hostnames = Object.keys(group[domains[i]].all);
j = hostnames.length;
while ( j-- ) {
hostname = hostnames[j];
if ( getTemporaryColor(hostname, '*') === 'rdt' ) {
blacklistedCount++;
}
metaStats.add(HTTPSBPopup.matrixStats[hostname]);
}
}
metaStats.types['*'].count = blacklistedCount;
return metaStats;
}
/******************************************************************************/
// Compare hostname helper, to order hostname in a logical manner:
// top-most < bottom-most, take into account whether IP address or
// named hostname
function hostnameCompare(a,b) {
// Normalize: most significant parts first
if ( !a.match(/^\d+(\.\d+){1,3}$/) ) {
var aa = a.split('.');
a = aa.slice(-2).concat(aa.slice(0,-2).reverse()).join('.');
}
if ( !b.match(/^\d+(\.\d+){1,3}$/) ) {
var bb = b.split('.');
b = bb.slice(-2).concat(bb.slice(0,-2).reverse()).join('.');
}
return a.localeCompare(b);
}
/******************************************************************************/
function makeMatrixGroup0SectionDomain(domain) {
return makeMatrixRowDomain(domain)
.addClass('g0 l1');
}
function makeMatrixGroup0SectionSubomain(domain, subdomain) {
return makeMatrixRowSubdomain(domain, subdomain)
.addClass('g0 l2');
}
function makeMatrixGroup0SectionMetaDomain(hostnames) {
var metaStats = new HostnameStats();
var i = hostnames.length;
while ( i-- ) {
metaStats.add(HTTPSBPopup.matrixStats[hostnames[i]]);
}
return makeMatrixMetaRowDomain(hostnames[0], metaStats.types)
.addClass('g0 l1 meta');
}
function makeMatrixGroup0Section(hostnames) {
var domain = hostnames[0];
var domainDiv = createMatrixSection()
.toggleClass('collapsed', getCollapseState(domain))
.prop('domain', domain);
if ( hostnames.length > 1 ) {
makeMatrixGroup0SectionMetaDomain(hostnames)
.appendTo(domainDiv);
}
makeMatrixGroup0SectionDomain(domain)
.appendTo(domainDiv);
for ( var i = 1; i < hostnames.length; i++ ) {
makeMatrixGroup0SectionSubomain(domain, hostnames[i])
.appendTo(domainDiv);
}
return domainDiv;
}
function makeMatrixGroup0(group) {
var domains = Object.keys(group).sort(hostnameCompare);
if ( domains.length ) {
var groupDiv = createMatrixGroup()
.addClass('g0');
makeMatrixGroup0Section(Object.keys(group[domains[0]].all).sort(hostnameCompare))
.appendTo(groupDiv);
for ( var i = 1; i < domains.length; i++ ) {
makeMatrixGroup0Section(Object.keys(group[domains[i]].all).sort(hostnameCompare))
.appendTo(groupDiv);
}
groupDiv.appendTo(matrixList);