-
-
Notifications
You must be signed in to change notification settings - Fork 99
/
background.js
10035 lines (9270 loc) · 291 KB
/
background.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
try {
if (document.title=="Keep Open - Social Stream Ninja"){
window.close();
}
if (document.title == "Close me - Social Stream Ninja"){
window.close();
}
} catch(e){}
var isExtensionOn = false;
var iframe = null;
var settings = {};
var messageTimeout = {};
var lastSentMessage = "";
var lastSentTimestamp = 0;
var lastMessageCounter = 0;
var sentimentAnalysisLoaded = false;
var messageCounter = 0;
var lastAntiSpam = 0;
var connectedPeers = {};
var isSSAPP = false;
var urlParams = new URLSearchParams(window.location.search);
var devmode = urlParams.has("devmode") || false;
var FacebookDupes = "";
var FacebookDupesTime = null;
var fetchNode = false;
var postNode = false;
var putNode = false;
var properties = ["streamID", "password", "state", "settings"];
var streamID = false;
var password = false;
function log(msg, msg2 = null) {
if (devmode) {
if (msg2 !== null) {
console.log(msg, msg2);
} else {
console.log(msg);
}
}
}
function warnlog(msg) {
console.warn(msg);
}
function errorlog(msg) {
console.error(msg);
}
var priorityTabs = new Set();
function generateStreamID() {
var text = "";
var possible = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789";
for (var i = 0; i < 10; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
try {
text = text.replaceAll("AD", "vDAv"); // avoiding adblockers
text = text.replaceAll("Ad", "vdAv");
text = text.replaceAll("ad", "vdav");
text = text.replaceAll("aD", "vDav");
} catch (e) {}
return text;
}
if (typeof chrome.runtime == "undefined") {
if (typeof require !== "undefined"){
var { ipcRenderer, contextBridge } = require("electron");
isSSAPP = true;
} else {
var ipcRenderer = {};
ipcRenderer.sendSync = function(){};
ipcRenderer.invoke = function(){};
ipcRenderer.on = function(){};
console.warn("This isn't a functional mode; not yet at least.");
}
chrome = {};
chrome.browserAction = {};
chrome.browserAction.setIcon = function (icon) {}; // there is no icon in the ssapp
chrome.runtime = {};
chrome.runtime.lastError = false;
//chrome.runtime.lastError.message = "";
chrome.runtime.sendMessage = async function(data, callback){ // uncomment if I need to use it.
let response = await ipcRenderer.sendSync('fromBackground',data);
if (typeof(callback) == "function"){
callback(response);
log(response);
}
};
chrome.runtime.getManifest = function () {
return false; // I'll need to add version info eventually
};
chrome.storage = {};
chrome.storage.sync = {};
chrome.storage.sync.set = function (data) {
log("SYNC SET", data);
ipcRenderer.sendSync("storageSave", data);
log("ipcRenderer.sendSync('storageSave',data);");
};
chrome.storage.sync.get = async function (arg, callback) {
var response = await ipcRenderer.sendSync("storageGet", arg);
callback(response);
};
chrome.storage.sync.remove = async function (arg, callback) {
// only used for upgrading; not important atm.
callback({});
};
chrome.storage.local = {};
chrome.storage.local.get = async function (arg, callback) {
var response = await ipcRenderer.sendSync("storageGet", arg);
callback(response);
};
chrome.storage.local.set = function (data) {
log("LOCAL SYNC SET", data);
ipcRenderer.sendSync("storageSave", data);
log("ipcRenderer.sendSync('storageSave',data);");
};
chrome.tabs = {};
chrome.tabs.query = async function (a, callback) {
var response = await ipcRenderer.sendSync("getTabs", {});
log("chrome.tabs.query");
log(response);
if (callback) {
callback(response);
}
};
chrome.debugger = {};
chrome.debugger.detach = function (a = null, b = null, c = null) {};
chrome.debugger.onDetach = {};
chrome.debugger.onDetach.addListener = function () {};
chrome.debugger.attach = function (a, b, c) {
log("chrome.debugger.attach", c);
c();
};
chrome.tabs.sendMessage = async function (tab = null, message = null, callback = null) {
var response = await ipcRenderer.sendSync("sendToTab", { message: message, tab: tab });
if (callback) {
callback(response);
}
};
chrome.debugger.sendCommand = async function (a = null, b = null, c = null, callback = null) {
if (!c || !a?.tabId) {
log("Missing required parameters");
return;
}
const eventData = {
...c,
tab: a.tabId
};
// Preserve the exact Input.dispatchKeyEvent type
if (b === "Input.dispatchKeyEvent") {
const response = await ipcRenderer.sendSync("sendInputToTab", eventData);
callback?.(response);
} else {
c.tab = a.tabId;
const response = await ipcRenderer.sendSync("sendInputToTab", c); // sendInputToTab
callback?.(response);
}
};
chrome.runtime.onMessage = {};
chrome.notifications = {};
chrome.notifications.create = function (data) {
alert(data.message);
};
window.showSaveFilePicker = async function (opts) {
const filePath = await ipcRenderer.invoke("show-save-dialog", opts);
//console.log(filePath);
return filePath;
};
var onMessageCallback = function (a, b, c) {};
chrome.runtime.onMessage.addListener = function (callback) {
onMessageCallback = callback;
};
ipcRenderer.on("fromMain", (event, ...args) => {
log("FROM MAIN", args);
var sender = {};
sender.tab = {};
sender.tab.id = null;
if (args[0]) {
onMessageCallback(args[0], sender, function (response) {
if (event.returnValue) {
event.returnValue = response;
}
ipcRenderer.send("fromBackgroundResponse", response);
});
}
});
ipcRenderer.on("fromMainSender", (event, args) => {
log("FROM MAINS SENDER", args);
if (args.length) {
if (args[1]) {
var sender = args[1];
} else {
var sender = {};
sender.tab = {};
sender.tab.id = null;
}
onMessageCallback(args[0], sender, function (response) {
if (event.returnValue) {
event.returnValue = response;
}
ipcRenderer.send("fromBackgroundResponse", response);
});
}
});
ipcRenderer.on("fromPopup", (event, ...args) => {
//log("FROM POP UP (redirected)", args[0]);
var sender = {};
sender.tab = {};
sender.tab.id = null;
onMessageCallback(args[0], sender, function (response) {
// (request, sender, sendResponse)
//log("sending response to pop up:",response);
ipcRenderer.send("fromBackgroundPopupResponse", response);
});
});
fetchNode = function (URL, headers = {}, method = 'GET', body = null) {
return ipcRenderer.sendSync("nodefetch", {
url: URL,
headers: headers,
method: method,
body: body
});
};
/* ipcMain.on('nodepost', function(eventRet, args2) {
log("NODE POSTING!");
fetch(args2.url, {
method: 'POST',
headers: args2.headers,
body: JSON.stringify(args2.body)
})
.then(response => response.text())
.then(data => {
eventRet.returnValue = data;
})
.catch(error => {
eventRet.returnValue = null;
});
}); */
postNode = async function (URL, body, headers = {}) {
return await ipcRenderer.sendSync("nodepost", {
url: URL,
body: body,
headers: headers
});
};
putNode = async function (URL, body, headers = {}) {
return await ipcRenderer.sendSync("nodepost", {
url: URL,
body: body,
headers: headers
});
};
window.showOpenFilePicker = async function (a = null, c = null) {
var importFile = await ipcRenderer.sendSync("showOpenDialog", "");
return importFile;
};
//ipcRenderer.send('backgroundLoaded');
//chrome.runtime.onMessage.addListener(
//async function (request, sender, sendResponse) {
} else {
window.alert = alert = function (msg) {
console.warn(new Date().toUTCString() + " : " + msg);
};
if (!chrome.browserAction){
chrome.browserAction = {};
chrome.browserAction.setIcon = function (icon) {};
}
}
log("isSSAPP: " + isSSAPP);
String.prototype.replaceAllCase = function (strReplace, strWith) {
// See http://stackoverflow.com/a/3561711/556609
var esc = strReplace.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
var reg = new RegExp(esc, "ig");
return this.replace(reg, strWith);
};
const validTLDs = new Set(["a","aaa","aarp","abb","abbott","abbvie","abc","able","abogado","abudhabi","ac","academy","accenture","accountant","accountants","aco","actor","ad","ads","adult","ae","aeg","aero","aetna","af","afl","africa","ag","agakhan","agency","ai","aig","airbus","airforce","airtel","akdn","al","alibaba","alipay","allfinanz","allstate","ally","alsace","alstom","am","amazon","americanexpress","americanfamily","amex","amfam","amica","amsterdam","analytics","android","anquan","anz","ao","aol","apartments","app","apple","aq","aquarelle","ar","arab","aramco","archi","army","arpa","art","arte","as","asda","asia","associates","at","athleta","attorney","au","auction","audi","audible","audio","auspost","author","auto","autos","aw","aws","ax","axa","az","azure","b","ba","baby","baidu","banamex","band","bank","bar","barcelona","barclaycard","barclays","barefoot","bargains","baseball","basketball","bauhaus","bayern","bb","bbc","bbt","bbva","bcg","bcn","bd","be","beats","beauty","beer","bentley","berlin","best","bestbuy","bet","bf","bg","bh","bharti","bi","bible","bid","bike","bing","bingo","bio","biz","bj","black","blackfriday","blockbuster","blog","bloomberg","blue","bm","bms","bmw","bn","bnpparibas","bo","boats","boehringer","bofa","bom","bond","boo","book","booking","bosch","bostik","boston","bot","boutique","box","br","bradesco","bridgestone","broadway","broker","brother","brussels","bs","bt","build","builders","business","buy","buzz","bv","bw","by","bz","bzh","c","ca","cab","cafe","cal","call","calvinklein","cam","camera","camp","canon","capetown","capital","capitalone","car","caravan","cards","care","career","careers","cars","casa","case","cash","casino","cat","catering","catholic","cba","cbn","cbre","cc","cd","center","ceo","cern","cf","cfa","cfd","cg","ch","chanel","channel","charity","chase","chat","cheap","chintai","christmas","chrome","church","ci","cipriani","circle","cisco","citadel","citi","citic","city","ck","cl","claims","cleaning","click","clinic","clinique","clothing","cloud","club","clubmed","cm","cn","co","coach","codes","coffee","college","cologne","com","commbank","community","company","compare","computer","comsec","condos","construction","consulting","contact","contractors","cooking","cool","coop","corsica","country","coupon","coupons","courses","cpa","cr","credit","creditcard","creditunion","cricket","crown","crs","cruise","cruises","cu","cuisinella","cv","cw","cx","cy","cymru","cyou","cz","d","dabur","dad","dance","data","date","dating","datsun","day","dclk","dds","de","deal","dealer","deals","degree","delivery","dell","deloitte","delta","democrat","dental","dentist","desi","design","dev","dhl","diamonds","diet","digital","direct","directory","discount","discover","dish","diy","dj","dk","dm","dnp","do","docs","doctor","dog","domains","dot","download","drive","dtv","dubai","dunlop","dupont","durban","dvag","dvr","dz","e","earth","eat","ec","eco","edeka","edu","education","ee","eg","email","emerck","energy","engineer","engineering","enterprises","epson","equipment","er","ericsson","erni","es","esq","estate","et","eu","eurovision","eus","events","exchange","expert","exposed","express","extraspace","f","fage","fail","fairwinds","faith","family","fan","fans","farm","farmers","fashion","fast","fedex","feedback","ferrari","ferrero","fi","fidelity","fido","film","final","finance","financial","fire","firestone","firmdale","fish","fishing","fit","fitness","fj","fk","flickr","flights","flir","florist","flowers","fly","fm","fo","foo","food","football","ford","forex","forsale","forum","foundation","fox","fr","free","fresenius","frl","frogans","frontier","ftr","fujitsu","fun","fund","furniture","futbol","fyi","g","ga","gal","gallery","gallo","gallup","game","games","gap","garden","gay","gb","gbiz","gd","gdn","ge","gea","gent","genting","george","gf","gg","ggee","gh","gi","gift","gifts","gives","giving","gl","glass","gle","global","globo","gm","gmail","gmbh","gmo","gmx","gn","godaddy","gold","goldpoint","golf","goo","goodyear","goog","google","gop","got","gov","gp","gq","gr","grainger","graphics","gratis","green","gripe","grocery","group","gs","gt","gu","gucci","guge","guide","guitars","guru","gw","gy","h","hair","hamburg","hangout","haus","hbo","hdfc","hdfcbank","health","healthcare","help","helsinki","here","hermes","hiphop","hisamitsu","hitachi","hiv","hk","hkt","hm","hn","hockey","holdings","holiday","homedepot","homegoods","homes","homesense","honda","horse","hospital","host","hosting","hot","hotels","hotmail","house","how","hr","hsbc","ht","hu","hughes","hyatt","hyundai","i","ibm","icbc","ice","icu","id","ie","ieee","ifm","ikano","il","im","imamat","imdb","immo","immobilien","in","inc","industries","infiniti","info","ing","ink","institute","insurance","insure","int","international","intuit","investments","io","ipiranga","iq","ir","irish","is","ismaili","ist","istanbul","it","itau","itv","j","jaguar","java","jcb","je","jeep","jetzt","jewelry","jio","jll","jm","jmp","jnj","jo","jobs","joburg","jot","joy","jp","jpmorgan","jprs","juegos","juniper","k","kaufen","kddi","ke","kerryhotels","kerrylogistics","kerryproperties","kfh","kg","kh","ki","kia","kids","kim","kindle","kitchen","kiwi","km","kn","koeln","komatsu","kosher","kp","kpmg","kpn","kr","krd","kred","kuokgroup","kw","ky","kyoto","kz","l","la","lacaixa","lamborghini","lamer","lancaster","land","landrover","lanxess","lasalle","lat","latino","latrobe","law","lawyer","lb","lc","lds","lease","leclerc","lefrak","legal","lego","lexus","lgbt","li","lidl","life","lifeinsurance","lifestyle","lighting","like","lilly","limited","limo","lincoln","link","lipsy","live","living","lk","llc","llp","loan","loans","locker","locus","lol","london","lotte","lotto","love","lpl","lplfinancial","lr","ls","lt","ltd","ltda","lu","lundbeck","luxe","luxury","lv","ly","m","ma","madrid","maif","maison","makeup","man","management","mango","map","market","marketing","markets","marriott","marshalls","mattel","mba","mc","mckinsey","md","me","med","media","meet","melbourne","meme","memorial","men","menu","merckmsd","mg","mh","miami","microsoft","mil","mini","mint","mit","mitsubishi","mk","ml","mlb","mls","mm","mma","mn","mo","mobi","mobile","moda","moe","moi","mom","monash","money","monster","mormon","mortgage","moscow","moto","motorcycles","mov","movie","mp","mq","mr","ms","msd","mt","mtn","mtr","mu","museum","music","mv","mw","mx","my","mz","n","na","nab","nagoya","name","navy","nba","nc","ne","nec","net","netbank","netflix","network","neustar","new","news","next","nextdirect","nexus","nf","nfl","ng","ngo","nhk","ni","nico","nike","nikon","ninja","nissan","nissay","nl","no","nokia","norton","now","nowruz","nowtv","np","nr","nra","nrw","ntt","nu","nyc","nz","o","obi","observer","office","okinawa","olayan","olayangroup","ollo","om","omega","one","ong","onl","online","ooo","open","oracle","orange","org","organic","origins","osaka","otsuka","ott","ovh","p","pa","page","panasonic","paris","pars","partners","parts","party","pay","pccw","pe","pet","pf","pfizer","pg","ph","pharmacy","phd","philips","phone","photo","photography","photos","physio","pics","pictet","pictures","pid","pin","ping","pink","pioneer","pizza","pk","pl","place","play","playstation","plumbing","plus","pm","pn","pnc","pohl","poker","politie","porn","post","pr","pramerica","praxi","press","prime","pro","prod","productions","prof","progressive","promo","properties","property","protection","pru","prudential","ps","pt","pub","pw","pwc","py","q","qa","qpon","quebec","quest","r","racing","radio","re","read","realestate","realtor","realty","recipes","red","redstone","redumbrella","rehab","reise","reisen","reit","reliance","ren","rent","rentals","repair","report","republican","rest","restaurant","review","reviews","rexroth","rich","richardli","ricoh","ril","rio","rip","ro","rocks","rodeo","rogers","room","rs","rsvp","ru","rugby","ruhr","run","rw","rwe","ryukyu","s","sa","saarland","safe","safety","sakura","sale","salon","samsclub","samsung","sandvik","sandvikcoromant","sanofi","sap","sarl","sas","save","saxo","sb","sbi","sbs","sc","scb","schaeffler","schmidt","scholarships","school","schule","schwarz","science","scot","sd","se","search","seat","secure","security","seek","select","sener","services","seven","sew","sex","sexy","sfr","sg","sh","shangrila","sharp","shell","shia","shiksha","shoes","shop","shopping","shouji","show","si","silk","sina","singles","site","sj","sk","ski","skin","sky","skype","sl","sling","sm","smart","smile","sn","sncf","so","soccer","social","softbank","software","sohu","solar","solutions","song","sony","soy","spa","space","sport","spot","sr","srl","ss","st","stada","staples","star","statebank","statefarm","stc","stcgroup","stockholm","storage","store","stream","studio","study","style","su","sucks","supplies","supply","support","surf","surgery","suzuki","sv","swatch","swiss","sx","sy","sydney","systems","sz","t","tab","taipei","talk","taobao","target","tatamotors","tatar","tattoo","tax","taxi","tc","tci","td","tdk","team","tech","technology","tel","temasek","tennis","teva","tf","tg","th","thd","theater","theatre","tiaa","tickets","tienda","tips","tires","tirol","tj","tjmaxx","tjx","tk","tkmaxx","tl","tm","tmall","tn","to","today","tokyo","tools","top","toray","toshiba","total","tours","town","toyota","toys","tr","trade","trading","training","travel","travelers","travelersinsurance","trust","trv","tt","tube","tui","tunes","tushu","tv","tvs","tw","tz","u","ua","ubank","ubs","ug","uk","unicom","university","uno","uol","ups","us","uy","uz","v","va","vacations","vana","vanguard","vc","ve","vegas","ventures","verisign","vermögensberater","vermögensberatung","versicherung","vet","vg","vi","viajes","video","vig","viking","villas","vin","vip","virgin","visa","vision","viva","vivo","vlaanderen","vn","vodka","volvo","vote","voting","voto","voyage","vu","w","wales","walmart","walter","wang","wanggou","watch","watches","weather","weatherchannel","webcam","weber","website","wed","wedding","weibo","weir","wf","whoswho","wien","wiki","williamhill","win","windows","wine","winners","wme","wolterskluwer","woodside","work","works","world","wow","ws","wtc","wtf","x","xbox","xerox","xihuan","xin","xxx","xyz","y","yachts","yahoo","yamaxun","yandex","ye","yodobashi","yoga","yokohama","you","youtube","yt","yun","z","za","zappos","zara","zero","zip","zm","zone","zuerich","zw","IDNs","ελ","ευ","бг","бел","дети","ею","католик","ком","мкд","мон","москва","онлайн","орг","рус","рф","сайт","срб","укр","қаз","հայ","ישראל","קום","ابوظبي","ارامكو","الاردن","البحرين","الجزائر","السعودية","العليان","المغرب","امارات","ایران","بارت","بازار","بيتك","بھارت","تونس","سودان","سورية","شبكة","عراق","عرب","عمان","فلسطين","قطر","كاثوليك","كوم","مصر","مليسيا","موريتانيا","موقع","همراه","پاكستان","پاکستان","ڀارت","कॉम","नेट","भारत","भारतम्","भारोत","संगठन","বাংলা","ভারত","ভাৰত","ਭਾਰਤ","ભારત","ଭାରତ","இந்தியா","இலங்கை","சிங்கப்பூர்","భారత్","ಭಾರತ","ഭാരതം","ලංකා","คอม","ไทย","ລາວ","გე","みんな","アマゾン","クラウド","グーグル","コム","ストア","セール","ファッション","ポイント","世界","中信","中国","中國","中文网","亚马逊","企业","佛山","信息","健康","八卦","公司","公益","台湾","台灣","商城","商店","商标","嘉里","嘉里大酒店","在线","大拿","天主教","娱乐","家電","广东","微博","慈善","我爱你","手机","招聘","政务","政府","新加坡","新闻","时尚","書籍","机构","淡马锡","游戏","澳門","点看","移动","组织机构","网址","网店","网站","网络","联通","谷歌","购物","通販","集团","電訊盈科","飞利浦","食品","餐厅","香格里拉","香港","닷넷","닷컴","삼성","한국"]);
function isValidTLD(tld) {
return validTLDs.has(tld.toLowerCase());
}
function filterXSS(unsafe) {
// this is not foolproof, but it might catch some basic probe attacks that sneak in
try {
return unsafe
.replaceAll("prompt(", "**")
.replaceAll("eval(", "**")
.replaceAll("onclick(", "**")
.replaceAll("alert(", "**")
.replaceAll("onload=", "**")
.replaceAll("onerror=", "**")
.replaceAll(" onmouse", "**") // onmousedown, onmouseup, etc
.replaceAll("onfocusin=", "**")
.replaceAll("onfocusout=", "**")
.replaceAll("onfocus=", "**")
.replaceAll("onblur=", "**")
.replaceAll("oninput=", "**")
.replaceAll("onkeydown=", "**")
.replaceAll("onkeyup=", "**")
.replaceAll("onkeypress=", "**")
.replaceAll("onkeyup", "**")
.replaceAll("=alert", "**")
.replaceAll("=prompt", "**")
.replaceAll("=confirm", "**")
.replaceAll("confirm(", "**")
.replaceAll("=eval", "**")
.replaceAll("ondblclick=", "**")
.replaceAll("javascript:", "**")
.replaceAll("srcdoc=", "**")
.replaceAll("xlink:href=", "**")
.replaceAll("xmlns:xlink=", "**")
.replaceAll("ontouchstart=", "**")
.replaceAll("ontouchend=", "**")
.replaceAll("ontouchmove=", "**")
.replaceAll("ontouchcancel=", "**")
.replaceAll("onchange=", "**")
.replaceAll("src=data:", "*,*")
.replaceAll("data:text/html", "*,*")
.replaceAll("onpageshow=", "**")
.replaceAll("href=//0", "**")
.replaceAll("onhashchange=", "**")
.replaceAll("onscroll=", "**")
.replaceAll("onresize=", "**")
.replaceAll("onhelp=", "**")
.replaceAll("onstart=", "**")
.replaceAll("onfinish=", "**")
.replaceAll("onloadstart=", "**")
.replaceAll("onend=", "**")
.replaceAll("onsubmit=", "**")
.replaceAll("onshow=", "**")
.replaceAll("alert`", "**")
.replaceAll("alert&", "**")
.replaceAll("(alert)(", "**")
.replaceAll("innerHTML", "**")
.replaceAll(" ondrag", "**")
.replaceAll("activate=", "**")
.replaceAll(" onbefore", "**")
.replaceAll("oncopy=", "**")
.replaceAll("oncut=", "**")
.replaceAll("onpaste=", "**")
.replaceAll("onpopstate=", "**")
.replaceAll("onunhandledrejection=", "**")
.replaceAll("onwheel=", "**")
.replaceAll("oncontextmenu=", "**")
.replaceAll("XMLHttpRequest(", "**")
.replaceAll("Object.defineProperty", "**")
.replaceAll("document.createElement(", "**")
.replaceAll("MouseEvent(", "**")
.replaceAll("unescape(", "**")
.replaceAll("onreadystatechange", "**")
.replaceAll("document.write(", "**")
.replaceAll("write(", "**")
.replaceAllCase("<textarea", "**")
.replaceAllCase("<embed", "**")
.replaceAllCase("<iframe", "**")
.replaceAllCase("<input", "**")
.replaceAllCase("<link", "**")
.replaceAllCase("<meta", "**")
.replaceAllCase("<style", "**")
.replaceAllCase("<table", "**")
.replaceAllCase("<layer", "**")
.replaceAllCase("<body", "**")
.replaceAllCase("<object", "**")
.replaceAllCase("<html", "**")
.replaceAllCase("<animation", "**")
.replaceAllCase("<listener", "**")
.replaceAllCase("<handler", "**")
.replaceAllCase("<form", "**")
.replaceAllCase("<?xml", "**")
.replaceAllCase("<stylesheet", "**")
.replaceAllCase("<eval", "**")
.replaceAll("=javascript", "**")
.replaceAll(" formaction=", "**")
.replaceAll("'';!--", "**")
.replaceAllCase("<script", "**")
.replaceAllCase("<audio", "**")
.replaceAllCase("<bgsound", "**")
.replaceAllCase("<blink", "**")
.replaceAllCase("<br><br><br>", "")
.replaceAllCase("<video", "**");
} catch (e) {
return unsafe;
}
}
/////////////// bad word filter
// I welcome updates/additions. The raw list can be found here: https://gist.github.com/steveseguin/da09a700e4fccd7ff82e68f32e384c9d
var badWords = ["fuck","shit","cunt","bitch","nigger","fag","retard","rape","pussy","cock","asshole","whore","slut","gay","lesbian","transgender","transsexual","tranny","chink","spic","kike","jap","wop","redneck","hillbilly","white trash","douche","dick","bastard","fucker","motherfucker","ass","anus","vagina","penis","testicles","masturbate","orgasm","ejaculate","clitoris","pubic","genital","erect","erotic","porn","xxx","dildo","butt plug","anal","sodomy","pedophile","bestiality","necrophilia","incest","suicide","murder","terrorism","drugs","alcohol","smoking","weed","meth","crack","heroin","cocaine","opiate","opium","benzodiazepine","xanax","adderall","ritalin","steroids","viagra","cialis","prostitution","escort"];
const alternativeChars = {
a: ["@", "4"],
e: ["3"],
i: ["1", "!"],
o: ["0"],
s: ["$", "5"],
t: ["7"],
c: ["<"]
};
function generateVariations(word) {
const variations = [word];
for (let i = 0; i < word.length; i++) {
const char = word[i].toLowerCase();
if (alternativeChars.hasOwnProperty(char)) {
const charVariations = alternativeChars[char];
const newVariations = [];
for (const variation of variations) {
for (const altChar of charVariations) {
const newWord = variation.slice(0, i) + altChar + variation.slice(i + 1);
newVariations.push(newWord);
}
}
variations.push(...newVariations);
}
}
return variations;
}
function generateVariationsList(words) {
const variationsList = [];
for (const word of words) {
variationsList.push(...generateVariations(word));
}
return variationsList.filter(word => !word.match(/[A-Z]/));
}
function createProfanityHashTable(profanityVariationsList) {
const hashTable = {};
for (let i = 0; i < profanityVariationsList.length; i++) {
const word = profanityVariationsList[i].toLowerCase();
for (let j = 0; j < word.length; j++) {
const character = word[j];
if (!hashTable[character]) {
hashTable[character] = {};
}
hashTable[character][word] = true;
}
}
return hashTable;
}
function isProfanity(word) {
if (!profanityHashTable) {
return false;
}
const wordLower = word.toLowerCase();
const firstChar = wordLower[0];
const words = profanityHashTable[firstChar];
if (!words) {
return false;
}
return Boolean(words[wordLower]);
}
function filterProfanity(sentence) {
let words = sentence.toLowerCase().split(/[\s\.\-_!?,]+/);
const uniqueWords = new Set(words);
for (let word of uniqueWords) {
if (isProfanity(word)) {
sentence = sentence.replace(new RegExp("\\b" + word + "\\b", "gi"), "*".repeat(word.length));
}
}
return sentence;
}
var profanityHashTable = false;
function initialLoadBadWords(){
try {
// use a custom file named badwords.txt to replace the badWords that are hard-coded. one per line.
fetch("./badwords.txt")
.then(response => response.text())
.then(text => {
let customBadWords = text.split(/\r?\n|\r|\n/g);
customBadWords = generateVariationsList(customBadWords);
profanityHashTable = createProfanityHashTable(customBadWords);
})
.catch(error => {
try {
const customBadwords = localStorage.getItem('customBadwords');
if (customBadwords) {
let customBadWordsList = customBadwords.split(/\r?\n|\r|\n/g);
customBadWordsList = generateVariationsList(customBadWordsList);
profanityHashTable = createProfanityHashTable(customBadWordsList);
} else {
// Use default badwords if no custom file is present
badWords = generateVariationsList(badWords);
profanityHashTable = createProfanityHashTable(badWords);
}
} catch (e) {
badWords = generateVariationsList(badWords);
profanityHashTable = createProfanityHashTable(badWords);
}
});
} catch (e) {
badWords = generateVariationsList(badWords);
profanityHashTable = createProfanityHashTable(badWords);
}
}
initialLoadBadWords();
/////// end of bad word filter
var goodWordsHashTable = false;
function isGoodWord(word) {
const wordLower = word.toLowerCase();
const firstChar = wordLower[0];
const words = goodWordsHashTable[firstChar];
if (!words) {
return false;
}
return Boolean(words[wordLower]);
}
function passGoodWords(sentence) {
let words = sentence.toLowerCase().split(/[\s\.\-_!?,]+/);
const uniqueWords = new Set(words);
for (let word of uniqueWords) {
if (!isGoodWord(word)) {
sentence = sentence.replace(new RegExp("\\b" + word + "\\b", "gi"), "*".repeat(word.length));
}
}
return sentence;
}
try {
// use a custom file named goodwords.txt to replace the badWords that are hard-coded. one per line.
fetch("./goodwords.txt")
.then(response => response.text())
.then(text => {
let customGoodWords = text.split(/\r?\n|\r|\n/g);
goodWordsHashTable = createProfanityHashTable(customGoodWords);
})
.catch(error => {
// no file found or error
});
} catch (e) {}
function replaceURLsWithSubstring(text, replacement = "[Link]") {
if (typeof text !== "string") return text;
try {
// First pattern for traditional URLs
const urlPattern = /\b(?:https?:\/\/)?(?![\d.]+\b(?!\.[a-z]))[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+(?:\/[^\s]*)?/g;
// Second pattern specifically for IP addresses
const ipPattern = /\b(?:https?:\/\/)?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?::\d+)?(?:\/[^\s]*)?/g;
// Apply both replacements
return text
.replace(urlPattern, (match) => {
if (match.startsWith('http://') || match.startsWith('https://')) {
return replacement;
}
const parts = match.split('.');
const potentialTLD = parts[parts.length - 1].split(/[/?#]/)[0];
if (match.includes('/') || isValidTLD(potentialTLD)) {
return replacement;
}
return match;
})
.replace(ipPattern, replacement);
} catch (e) {
console.error(e);
return text;
}
}
function validateRoomId(roomId) {
if (roomId == null || roomId === '') {
return false;
}
let sanitizedId = String(roomId).trim();
if (sanitizedId.length < 1) {
return false;
}
const reservedValues = [
'undefined',
'null',
'false',
'true',
'NaN',
'default',
'room',
'lobby',
'test',
'nothing',
'0',
'1',
'none'
];
if (reservedValues.includes(sanitizedId.toLowerCase())) {
return false;
}
sanitizedId = sanitizedId.replace(/[^a-zA-Z0-9]/g, '_');
if (/^_+$/.test(sanitizedId)) {
return false;
}
if (sanitizedId.length < 2) {
return false;
}
const MAX_LENGTH = 80;
if (sanitizedId.length > MAX_LENGTH) {
return false;
}
// throw new Error('Invalid room ID');
return sanitizedId;
}
function loadSettings(item, resave = false) {
log("loadSettings (or saving new settings)", item);
let reloadNeeded = false;
if (item && item.streamID) {
if (streamID != item.streamID) {
streamID = item.streamID;
streamID = validateRoomId(streamID);
if (!streamID){
try {
chrome.notifications.create({
type: "basic",
iconUrl: "./icons/icon-128.png",
title: "Invalid session ID",
message: "Your session ID is invalid.\n\nPlease correct it to continue"
});
throw new Error('Invalid session ID');
} catch (e) {
console.error(e);
throw new Error('Invalid session ID');
}
}
reloadNeeded = true;
}
} else if (!streamID) {
reloadNeeded = true;
streamID = generateStreamID(); // not stream ID, so lets generate one; then lets save it.
streamID = validateRoomId(streamID);
if (!streamID){
streamID = generateStreamID();
}
streamID = validateRoomId(streamID);
if (!streamID){
try {
chrome.notifications.create({
type: "basic",
iconUrl: "./icons/icon-128.png",
title: "Invalid session ID",
message: "Your session ID is invalid.\n\nPlease correct it to continue"
});
throw new Error('Invalid session ID');
} catch (e) {
console.error(e);
throw new Error('Invalid session ID');
}
}
if (!isSSAPP) {
resave = true;
if (item) {
item.streamID = streamID;
} else {
item = {};
item.streamID = streamID;
}
}
}
if (item && "password" in item) {
if (password != item.password) {
password = item.password;
reloadNeeded = true;
}
}
if (item && item.settings) {
settings = item.settings;
}
if (item && "state" in item) {
if (isExtensionOn != item.state) {
isExtensionOn = item.state;
reloadNeeded = true;
// we're saving below instead
}
}
if (reloadNeeded) {
updateExtensionState(false);
}
if (resave) {
chrome.storage.sync.set(item);
chrome.runtime.lastError;
}
try {
if (isSSAPP && ipcRenderer) {
ipcRenderer.sendSync("fromBackground", { streamID, password, settings, state: isExtensionOn });
//ipcRenderer.send('backgroundLoaded');
}
} catch (e) {
console.error(e);
}
toggleMidi();
if (settings.addkarma) {
if (!sentimentAnalysisLoaded) {
loadSentimentAnalysis();
}
}
for (var i = 1; i <= 10; i++) {
if (settings["timemessageevent" + i]) {
if (settings["timemessagecommand" + i]) {
checkIntervalState(i);
}
}
}
if (settings.translationlanguage) {
changeLg(settings.translationlanguage.optionsetting);
}
}
////////////
var miscTranslations = {
// we won't use after the first load
start: "START",
said: " said: ",
someonesaid: "Someone said: ",
someone: "Someone"
};
async function fetchWithTimeout(URL, timeout = 8000) {
// ref: https://dmitripavlutin.com/timeout-fetch-request/
try {
const controller = new AbortController();
const timeout_id = setTimeout(() => controller.abort(), timeout);
const response = await fetch(URL, { ...{ timeout: timeout }, signal: controller.signal });
clearTimeout(timeout_id);
return response;
} catch (e) {
errorlog(e);
return await fetch(URL);
}
}
async function changeLg(lang) {
log("changeLg: " + lang);
if (!lang) {
log("DISABLING TRANSLATIONS");
settings.translation = false;
chrome.storage.local.set({
settings: settings
});
chrome.runtime.lastError;
pushSettingChange();
return;
}
return await fetchWithTimeout("./translations/" + lang + ".json", 2000)
.then(async function (response) {
try {
if (response.status !== 200) {
return;
}
await response
.json()
.then(function (data) {
if (data.miscellaneous) {
Object.keys(data.miscellaneous).forEach(key => {
miscTranslations[key] = data.miscellaneous[key];
});
}
data.miscellaneous = miscTranslations;
settings.translation = data;
chrome.storage.local.set({
settings: settings
});
chrome.runtime.lastError;
pushSettingChange();
})
.catch(function (e) {
log(e);
});
} catch (e) {
log(e);
}
})
.catch(function (err) {
log(err);
});
}
//////
function checkIntervalState(i) {
if (intervalMessages[i]) {
clearInterval(intervalMessages[i]);
}
if (!isExtensionOn) {
return;
}
if (!i){
return;
}
var offset = 0;
if (settings["timemessageoffset" + i]) {
offset = settings["timemessageoffset" + i].numbersetting;
}
intervalMessages[i] = setTimeout(
function (i) {
let antispam = true;
if ("timemessageinterval" + i in settings) {
if (settings["timemessageinterval" + i].numbersetting == 0) {
if (!isExtensionOn) {
return;
}
if (!settings["timemessagecommand" + i] || !settings["timemessagecommand" + i].textsetting) {
return;
} // failsafe
if (!settings["timemessageevent" + i]) {
return;
} // failsafe
//messageTimeout = Date.now();
var msg = {};
msg.response = settings["timemessagecommand" + i].textsetting;
//sendMessageToTabs(msg, false, null, false, antispam);
sendMessageToTabs(msg, false, null, false, antispam, false);
} else if (settings["timemessageinterval" + i].numbersetting) {
clearInterval(intervalMessages[i]);
intervalMessages[i] = setInterval(
function (i) {
if (!isExtensionOn) {
return;
}
if (!settings["timemessagecommand" + i] || !settings["timemessagecommand" + i].textsetting) {
return;
} // failsafe
if (!settings["timemessageevent" + i]) {
return;
} // failsafe
//messageTimeout = Date.now();
var msg = {};
msg.response = settings["timemessagecommand" + i].textsetting;
//sendMessageToTabs(msg, false, null, false, antispam);
sendMessageToTabs(msg, false, null, false, antispam, false);
},
settings["timemessageinterval" + i].numbersetting * 60000,
i
);
}
} else {
clearInterval(intervalMessages[i]);
intervalMessages[i] = setInterval(
function (i) {
if (!isExtensionOn) {
return;
}
if (!settings["timemessagecommand" + i] || !settings["timemessagecommand" + i].textsetting) {
return;
} // failsafe
if (!settings["timemessageevent" + i]) {
return;
} // failsafe
//messageTimeout = Date.now();
var msg = {};
msg.response = settings["timemessagecommand" + i].textsetting;
sendMessageToTabs(msg, false, null, false, antispam, false);
},
15 * 60000,
i
);
}
},
offset * 60000 || 0,
i
);
}
function pushSettingChange() {
chrome.tabs.query({}, function (tabs) {
chrome.runtime.lastError;
for (var i = 0; i < tabs.length; i++) {
if (!tabs[i].url) {
continue;
}
chrome.tabs.sendMessage(tabs[i].id, { settings: settings, state: isExtensionOn }, function (response = false) {
chrome.runtime.lastError;
});
}
});
}
function sleep(ms = 0) {
return new Promise(r => setTimeout(r, ms)); // LOLz!
}
async function loadmidi() {
const opts = {
types: [
{
description: "JSON file",
accept: { "text/plain": [".json", ".txt", ".data", ".midi"] }
}
]
};
var midiConfigFile = await window.showOpenFilePicker();
try {
midiConfigFile = await midiConfigFile[0].getFile();
midiConfigFile = await midiConfigFile.text();
} catch (e) {}
try {
settings.midiConfig = JSON.parse(midiConfigFile);
} catch (e) {
settings.midiConfig = false;
log(e);
messagePopup({alert: "File does not contain a valid JSON structure"});
}
chrome.storage.local.set({
settings: settings
});
chrome.runtime.lastError;
}
var newFileHandle = false;
async function overwriteFile(data = false) {
if (data == "setup") {
const opts = {
types: [
{
description: "JSON data",
accept: { "text/plain": [".txt"], "application/json": [".json"] }
}
]
};
if (!window.showSaveFilePicker) {
console.warn("Open `brave://flags/#file-system-access-api` and enable to use the File API");
}
newFileHandle = await window.showSaveFilePicker(opts);
} else if (newFileHandle && data) {
if (typeof newFileHandle == "string") {
ipcRenderer.send("write-to-file", { filePath: newFileHandle, data: data });
} else {
const writableStream = await newFileHandle.createWritable();
await writableStream.write(data);
await writableStream.close();
}
}
}
var newSavedNamesFileHandle = false;
var uniqueNameSet = [];
async function overwriteSavedNames(data = false) {
if (data == "setup") {
uniqueNameSet = [];
const opts = {