-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
main.js
2218 lines (1984 loc) · 63.5 KB
/
main.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
// Modules to control application life and create native browser window
const electron = require('electron')
const process = require('process')
const prompt = require('electron-prompt');
const unhandled = require('electron-unhandled');
const fs = require('fs');
const path = require('path');
const {app, BrowserWindow, BrowserView, webFrameMain, desktopCapturer, ipcMain, screen, shell, globalShortcut, session, dialog} = require('electron')
const contextMenu = require('electron-context-menu');
const Yargs = require('yargs')
const isDev = require('electron-is-dev');
const { Readable } = require('stream');
const { fetch: undiciFetch } = require('undici');
const activeStreams = new Map();
const https = require('https');
process.on('uncaughtException', function (error) {
console.error("uncaughtException");
console.error(error);
});
unhandled();
var ver = app.getVersion();
function createYargs(){
var argv = Yargs.usage('Usage: $0 -w=num -h=num -u="string" -p')
.example(
'$0 -w=1280 -h=720 -u="https://vdo.ninja/?view=xxxx"',
"Loads the stream with ID xxxx into a window sized 1280x720"
)
.option("w", {
alias: "width",
describe: "The width of the window in pixel.",
type: "number",
nargs: 1,
default: 1280
})
.option("h", {
alias: "height",
describe: "The height of the window in pixels.",
type: "number",
nargs: 1,
default: 720
})
.option("u", {
alias: "url",
describe: "The URL of the window to load.",
default: "https://vdo.ninja/electron?version="+ver,
type: "string"
})
.option("t", {
alias: "title",
describe: "The default Title for the app Window",
type: "string",
default: null
})
.option("p", {
alias: "pin",
describe: "Toggle always on top",
type: "boolean",
default: process.platform == 'darwin'
})
.option("a", {
alias: "hwa",
describe: "Enable Hardware Acceleration",
type: "boolean",
default: true
})
.option("x", {
alias: "x",
describe: "Window X position",
type: "number",
nargs: 1,
default: -1
})
.option("y", {
alias: "y",
describe: "Window Y position",
type: "number",
nargs: 1,
default: -1
})
.option("node", {
alias: "n",
describe: "Enables node-integration, allowing for screen capture, global hotkeys, prompts, and more.",
type: "boolean",
default: false
})
.option("minimized", {
alias: "min",
describe: "Starts the window minimized",
type: "boolean",
default: false
})
.option("fullscreen", {
alias: "f",
describe: "Enables full-screen mode for the first window on its load.",
type: "boolean",
default: false
})
.option("unclickable", {
alias: "uc",
describe: "The page will pass thru any mouse clicks or other mouse events",
type: "boolean",
default: false
})
.option("savefolder", {
alias: "sf",
describe: "Where to save a file on disk",
type: "string",
default: null
})
.option("mediafoundation", {
alias: "mf",
describe: "Enable media foundation video capture",
type: "string",
default: null
})
.option("disablemediafoundation", {
alias: "dmf",
describe: "Disable media foundation video capture; helps capture some webcams",
type: "string",
default: null
})
.option("css", {
alias: "css",
describe: "Have local CSS script be auto-loaded into every page",
type: "string",
default: null
})
.option("chroma", {
alias: "color",
describe: "Set background CSS to target hex color; FFF or 0000 are examples.",
type: "string",
default: null
})
.option("hidecursor", {
alias: "hc",
describe: "Hide the mouse pointer / cursor",
type: "boolean",
default: null
})
.describe("help", "Show help.") // Override --help usage message.
.wrap(process.stdout.columns);
return argv.argv;
}
var Argv = createYargs();
if (Argv.help) {
Argv.showHelp();
process.exit(0); // Exit the script after showing help.
}
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
return
}
function parseDeepLink(deepLinkUrl) {
console.log('Parsing deep link:', deepLinkUrl);
try {
// Create a copy of default args
const newArgs = {...Argv};
deepLinkUrl = deepLinkUrl.replace("electroncapture://", "https://");
let url = new URL(deepLinkUrl);
console.log('Parsed URL:', {
pathname: url.pathname,
search: url.search,
hash: url.hash
});
newArgs.url = url.href;
// Parse window parameters from query string
const params = new URLSearchParams(url.search);
// Map URL parameters to window arguments
if (params.has('w')) newArgs.width = parseInt(params.get('w'));
if (params.has('h')) newArgs.height = parseInt(params.get('h'));
if (params.has('x')) newArgs.x = parseInt(params.get('x'));
if (params.has('y')) newArgs.y = parseInt(params.get('y'));
if (params.has('pin')) newArgs.pin = params.get('pin') === 'true';
if (params.has('title')) newArgs.title = params.get('title');
if (params.has('full')) newArgs.fullscreen = params.get('full') === 'true';
if (params.has('min')) newArgs.minimized = params.get('min') === 'true';
console.log('Parsed deep link args:', newArgs);
return newArgs;
} catch (error) {
console.error('Error parsing deep link URL:', error);
return null;
}
}
function registerProtocolHandling() {
// Check if we're already the default protocol handler
if (process.defaultApp) {
if (process.argv.length >= 2) {
app.setAsDefaultProtocolClient('electroncapture', process.execPath, [path.resolve(process.argv[1])])
}
} else {
app.setAsDefaultProtocolClient('electroncapture');
}
// Handle the case where the app is not the default handler
if (!app.isDefaultProtocolClient('electroncapture')) {
try {
app.setAsDefaultProtocolClient('electroncapture');
} catch (error) {
console.error('Failed to register protocol handler:', error);
}
}
}
// Handle deep linking on Windows
if (process.platform === 'win32') {
const deepLinkUrl = process.argv.find(arg => arg.startsWith('electroncapture://'));
if (deepLinkUrl) {
console.log('Found deep link in initial launch:', deepLinkUrl);
const args = parseDeepLink(deepLinkUrl);
if (args && args.url) {
Argv = args; // Update initial arguments if valid
}
}
}
// Register protocol client
if (process.defaultApp) {
if (process.argv.length >= 2) {
app.setAsDefaultProtocolClient('electroncapture', process.execPath, [path.resolve(process.argv[1])])
}
} else {
app.setAsDefaultProtocolClient('electroncapture');
}
function getDirectories(path) {
return fs.readdirSync(path).filter(function (file) {
return fs.statSync(path+'/'+file).isDirectory();
});
}
if (Argv.title){
app.setAppUserModelId(Argv.title);
} else {
app.setAppUserModelId("ele.cap");
}
if (!(Argv.hwa)){
app.disableHardwareAcceleration();
console.log("HWA DISABLED");
}
if (!(Argv.mf)){
app.commandLine.appendSwitch('enable-features', 'MediaFoundationVideoCapture');
//app.commandLine.appendSwitch('force-directshow')
//console.log("Media Foundations video cap ENABLED");
// --force-directshow
}
if (!(Argv.dmf)){
app.commandLine.appendSwitch('disable-features', 'MediaFoundationVideoCapture');
//app.commandLine.appendSwitch('force-directshow')
//console.log("Media Foundations video cap ENABLED");
// --force-directshow
}
app.commandLine.appendSwitch('enable-features', 'WebAssemblySimd'); // Might not be needed in the future with Chromium; not supported on older Chromium. For faster greenscreen effects.
app.commandLine.appendSwitch('webrtc-max-cpu-consumption-percentage', '100');
app.commandLine.appendSwitch('disable-backgrounding-occluded-windows');
app.commandLine.appendSwitch('max-web-media-player-count', '5000');
app.commandLine.appendSwitch('disable-site-isolation-trials');
app.commandLine.appendSwitch('ignore-certificate-errors');
app.commandLine.appendSwitch('disable-renderer-backgrounding');
app.commandLine.appendSwitch('disable-http-cache');
app.commandLine.appendSwitch('ignore-certificate-errors-spki-list');
app.commandLine.appendSwitch('unsafely-treat-insecure-origin-as-secure', 'http://insecure.vdo.ninja,http://insecure.rtc.ninja,http://whip.vdo.ninja,https://whip.vdo.ninja,http://whep.vdo.ninja,https://whep.vdo.ninja,http://insecure.versus.cam,http://127.0.0.1,https://vdo.ninja,https://versus.cam,https://rtc.ninja');
var counter=0;
var forcingAspectRatio = false;
var extensions = [];
try {
var dir = false;
if (process.platform == 'win32'){
dir = process.env.APPDATA.replace("Roaming","")+"\\Local\\Google\\Chrome\\User Data\\Default\\Extensions";
if (dir){
//dir = dir.replace("Roaming","");
var ttt = getDirectories(dir);
ttt.forEach(d=>{
try {
var ddd = getDirectories(dir+"\\"+d);
var fd = fs.readFileSync(dir+"\\"+d+"\\"+ddd[0]+"\\manifest.json", 'utf8');
var json = JSON.parse(fd);
if (json.name.startsWith("_")){
return;
}
extensions.push({
"name": json.name,
"location": dir+"\\"+d+"\\"+ddd[0]
});
} catch(e){}
});
}
} else if (process.platform == 'darwin'){
dir = process.env.HOME + "/Library/Application Support/Google/Chrome/Default/Extensions";
console.log(dir);
if (dir){
//dir = dir.replace("Roaming","");
var ttt = getDirectories(dir);
ttt.forEach(d=>{
try {
var ddd = getDirectories(dir+"/"+d);
var fd = fs.readFileSync(dir+"."+d+"/"+ddd[0]+"/manifest.json", 'utf8');
var json = JSON.parse(fd);
if (json.name.startsWith("_")){
return;
}
extensions.push({
"name": json.name,
"location": dir+"/"+d+"/"+ddd[0]
});
} catch(e){console.error(e);}
});
}
}
} catch(e){console.error(e);}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
const httpsAgent = new https.Agent({
rejectUnauthorized: false
});
function formatURL(inputURL) {
if (!inputURL.startsWith("http://") && !inputURL.startsWith("https://") && !inputURL.startsWith("file://")) {
return "https://" + inputURL;
}
return inputURL;
}
ipcMain.handle('noCORSFetch', async (event, args) => {
const streamId = Date.now().toString();
try {
const isHttps = args.url.toLowerCase().startsWith('https://');
const fetchOptions = {
method: args.method || 'GET',
headers: {
...args.headers
}
};
// Add dispatcher with SSL verification disabled for HTTPS URLs
if (isHttps) {
fetchOptions.dispatcher = new (require('undici').Agent)({
connect: {
rejectUnauthorized: false
}
});
}
const response = await undiciFetch(args.url, fetchOptions);
if (!response.ok) {
return {
ok: false,
status: response.status,
statusText: response.statusText
};
}
const contentType = response.headers.get('content-type') || '';
const boundaryMatch = contentType.match(/boundary=([^;]+)/i);
const boundary = boundaryMatch ? boundaryMatch[1] : null;
const reader = response.body.getReader();
activeStreams.set(streamId, {
reader,
buffer: Buffer.alloc(0)
});
return {
ok: true,
status: response.status,
streamId,
contentType,
boundary: boundary ? `${boundary}` : null
};
} catch (error) {
console.error('Fetch error:', error);
return {
ok: false,
error: error.message
};
}
});
// Rest of the code remains unchanged
ipcMain.handle('readStreamChunk', async (event, streamId) => {
const stream = activeStreams.get(streamId);
if (!stream) return { done: true };
try {
const { done, value } = await stream.reader.read();
if (done) {
activeStreams.delete(streamId);
return { done: true };
}
return {
done: false,
value: Array.from(value)
};
} catch (error) {
console.error('Stream read error:', error);
activeStreams.delete(streamId);
throw error;
}
});
ipcMain.handle('closeStream', async (event, streamId) => {
const stream = activeStreams.get(streamId);
if (stream?.reader) {
try {
await stream.reader.cancel();
} catch (e) {
console.error('Error closing stream:', e);
}
activeStreams.delete(streamId);
}
return true;
});
ipcMain.on('prompt', function(eventRet, arg) { // this enables a PROMPT pop up , which is used to BLOCK the main thread until the user provides input. VDO.Ninja uses prompt for passwords, etc.
try {
arg.val = arg.val || '';
arg.title = arg.title.replace("\n","<br /><br />");
prompt({
title: "",
label: arg.title,
width: 700,
useHtmlLabel: true,
inputAttrs: {
type: 'string',
placeholder: arg.val
},
type: 'input',
resizable: true,
alwaysOnTop: true
})
.then((r) => {
if(r === null) {
console.log('user cancelled');
} else {
console.log('result', r);
eventRet.returnValue = r;
}
})
.catch(console.error);
} catch(e){console.error(e);}
});
ipcMain.on('getSources', async function(eventRet, args) {
try{
const sources = await desktopCapturer.getSources({ types: args.types });
eventRet.returnValue = sources;
} catch(e){console.error(e);}
});
async function createWindow(args, reuse=false){
var webSecurity = true;
// Check if args are valid
if (!args || typeof args !== 'object') {
console.error('Invalid args passed to createWindow:', args);
args = createYargs(); // Use default args if invalid
}
var URL = args.url, NODE = args.node, WIDTH = args.width, HEIGHT = args.height, TITLE = args.title, PIN = args.pin, X = args.x, Y = args.y, FULLSCREEN = args.fullscreen, UNCLICKABLE = args.uc, MINIMIZED = args.min, CSS = args.css, BGCOLOR = args.chroma;
console.log(args);
var CSSCONTENT = "";
if (BGCOLOR){
CSSCONTENT = "body {background-color:#"+BGCOLOR+"!important;}";
}
if (CSS){
var p = path.join(__dirname, '.', CSS);
console.log("Trying: "+p);
var res, rej;
var promise = new Promise((resolve, reject) => {
res = resolve;
rej = reject;
});
promise.resolve = res;
promise.reject = rej;
fs.readFile(p, 'utf8', function (err, data) {
if (err) {
console.log("Trying: "+CSS);
fs.readFile(CSS, 'utf8', function (err, data) {
if (err) {
console.log("Couldn't read specified CSS file");
} else{
CSSCONTENT += data;
}
promise.resolve();
});
} else {
CSSCONTENT += data;
promise.resolve();
}
});
await promise;
if (CSSCONTENT){
console.log("Loaded specified file.");
}
}
try {
if (URL.startsWith("file:")){
webSecurity = false; // not ideal, but to open local files, this is needed.
// warn the user in some way that this window is tained. perhaps detect if they navigate to a different website or load an iframe that it will be a security concern?
// maybe filter all requests to file:// and ensure they are made from a file:// resource already.
} else if (!(URL.startsWith("http"))){
URL = "https://"+URL.toString();
}
} catch(e){
URL = "https://vdo.ninja/electron?version="+ver;
}
let currentTitle = "ElectronCapture";
if (reuse){
currentTitle = reuse;
} else if (TITLE===null){
counter+=1;
currentTitle = "Electron "+(counter.toString());
} else if (counter==0){
counter+=1;
currentTitle = TITLE.toString();
} else {
counter+=1;
currentTitle = TITLE.toString() + " " +(counter.toString());
}
let factor = screen.getPrimaryDisplay().scaleFactor;
var ttt = screen.getPrimaryDisplay().workAreaSize;
var targetWidth = WIDTH / factor;
var targetHeight = HEIGHT / factor;
var tainted = false;
if (targetWidth > ttt.width){
targetHeight = parseInt(targetHeight * ttt.width / targetWidth);
targetWidth = ttt.width;
tainted=true;
}
if (targetHeight > ttt.height){
targetWidth = parseInt(targetWidth * ttt.height / targetHeight);
targetHeight = ttt.height;
tainted=true;
}
// Create the browser window.
var mainWindow = new BrowserWindow({
transparent: true,
//focusable: false,
width: targetWidth,
height: targetHeight,
frame: false,
backgroundColor: '#0000',
fullscreenable: true,
titleBarStyle: 'hidden',
roundedCorners: false,
show: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
pageVisibility: true,
partition: 'persist:abc',
contextIsolation: true,
backgroundThrottling: false,
webSecurity: webSecurity,
nodeIntegrationInSubFrames: NODE,
nodeIntegration: NODE // this could be a security hazard, but useful for enabling screen sharing and global hotkeys
},
title: currentTitle
});
mainWindow.webContents.session.webRequest.onHeadersReceived({ urls: [ "*://*/*" ] },
(d, c)=>{
if(d.responseHeaders['X-Frame-Options']){
delete d.responseHeaders['X-Frame-Options'];
} else if(d.responseHeaders['x-frame-options']) {
delete d.responseHeaders['x-frame-options'];
}
c({cancel: false, responseHeaders: d.responseHeaders});
}
);
//var appData = process.env.APPDATA+"\\..\\Local" || (process.platform == 'darwin' ? process.env.HOME + '/Library/Preferences' : process.env.HOME + "/.local/share")
mainWindow.args = args; // storing settings
mainWindow.vdonVersion = false;
mainWindow.PPTHotkey = false;
if (UNCLICKABLE){
mainWindow.mouseEvent = true;
mainWindow.setIgnoreMouseEvents(mainWindow.mouseEvent);
}
ipcMain.on("vdonVersion", function(eventRet, arg) { // this enables a PROMPT pop up , which is used to BLOCK the main thread until the user provides input. VDO.Ninja uses prompt for passwords, etc.
if (mainWindow){
mainWindow.vdonVersion = arg.ver || false;
}
console.log("arg vdonVersion:",arg);
});
ipcMain.on('PPTHotkey', function(eventRet, value) { //
console.log("updatePPT recieved 2:", value);
if (!mainWindow){return;}
if (mainWindow.PPTHotkey){
try {
if (globalShortcut.isRegistered(mainWindow.PPTHotkey)){
globalShortcut.unregister(mainWindow.PPTHotkey);
}
} catch(e){
}
}
if (!value){
mainWindow.PPTHotkey=false;
return;
}
mainWindow.PPTHotkey = "";
if (value.ctrl){
mainWindow.PPTHotkey += "CommandOrControl";
}
if (value.alt){
if (mainWindow.PPTHotkey){mainWindow.PPTHotkey+="+";}
mainWindow.PPTHotkey += "Alt";
}
if (value.meta){
if (mainWindow.PPTHotkey){mainWindow.PPTHotkey+="+";}
mainWindow.PPTHotkey += "Meta";
}
if (value.key){
if (mainWindow.PPTHotkey){mainWindow.PPTHotkey+="+";}
var matched = false;
if (value.key === "+"){
mainWindow.PPTHotkey += "Plus";
matched = true;
} else if (value.key === " "){
mainWindow.PPTHotkey += "Space";
matched = true;
} else if (value.key.length === 1){
mainWindow.PPTHotkey += value.key.toUpperCase();
matched = true;
} else {
var possibleKeyCodes = ["Space","Backspace","Tab","Capslock","Return","Enter","Plus","Numlock","Scrolllock","Delete","Insert","Return","Up","Down","Left","Right","Home","End","PageUp","PageDown","Escape","Esc","VolumeUp","VolumeDown","VolumeMute","MediaNextTrack","MediaPreviousTrack","MediaStop","MediaPlayPause","PrintScreen","num0","num1","num2","num3","num4","num5","num6","num7","num8","num9","numdec","numadd","numsub","nummult","numdiv"];
for (var i = 0;i<possibleKeyCodes.length;i++){
if (possibleKeyCodes[i].toLowerCase() === value.key.toLowerCase()){
mainWindow.PPTHotkey += possibleKeyCodes[i];
matched = true;
break;
}
}
}
if (!matched){
mainWindow.PPTHotkey += value.key.toUpperCase(); // last resort
}
} else {
//console.log("Can't register just a control button; needs a key for global hotkeys");
return;
}
console.log("mainWindow.PPTHotkey:"+mainWindow.PPTHotkey);
const ret_ppt = globalShortcut.register(mainWindow.PPTHotkey, function(){
if (mainWindow) {
mainWindow.webContents.send('postMessage', {'PPT':true, "node":mainWindow.node})
}
});
if (!ret_ppt) {
//console.log('registration failed3')
};
});
try {
mainWindow.node = NODE;
if ((X!=-1) || (Y!=-1)) {
if (X==-1){X=0;}
if (Y==-1){Y=0;}
mainWindow.setPosition(Math.floor(X/factor), Math.floor(Y/factor))
}
} catch(e){console.error(e);}
mainWindow.on('blur', () => {
mainWindow.setBackgroundColor('#00000000'); // tmp fix for bug in e.js
globalShortcut.unregister('Alt+Enter');
});
mainWindow.on('focus', () => {
mainWindow.setBackgroundColor('#00000000'); // tmp fix for bug in e.js
globalShortcut.register('Alt+Enter', () => {
if (mainWindow && mainWindow.isFocused()) {
if (process.platform == "darwin"){ // On certain electron builds, fullscreen fails on macOS; this is in case it starts happening again
mainWindow.isMaximized() ? mainWindow.unmaximize() : mainWindow.maximize();
} else {
if (mainWindow.full || mainWindow.isFullScreen()){
mainWindow.full = false;
mainWindow.setFullScreen(false);
} else {
mainWindow.full = true;
mainWindow.setFullScreen(true);
}
}
}
});
});
mainWindow.webContents.on('will-prevent-unload', (event) => {
const options = {
type: 'question',
buttons: ['Cancel', 'Leave'],
message: 'Leave Site?',
detail: 'This will end any active streams and may cause any recording that are in progress to be lost.',
};
const response = dialog.showMessageBoxSync(null, options)
if (response === 1) event.preventDefault();
});
mainWindow.on('close', function(e) {
e.preventDefault();
mainWindow.hide(); // hide, and wait 2 second before really closing; this allows for saving of files.
mainWindow.webContents.send('postMessage', {'hangup':true});
setTimeout(function(mainWindow){
mainWindow.destroy();
mainWindow = null
},1500,mainWindow); // takes 500ms to save properly; with a 1s buffer for safety
globalShortcut.unregister('CommandOrControl+M');
globalShortcut.unregisterAll();
});
mainWindow.on('closed', async function (e) {
//e.preventDefault();
globalShortcut.unregister('CommandOrControl+M');
globalShortcut.unregisterAll();
mainWindow = null
});
mainWindow.on("page-title-updated", function(event) {
console.log("page-title-updated");
event.preventDefault();
});
mainWindow.webContents.on("did-fail-load", function(e) {
console.error("failed to load");
console.error(e);
//app.quit();
});
mainWindow.webContents.on('new-window', (event, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => {
console.log("new-window");
mainWindow.webContents.mainFrame.frames.forEach(frame => {
if (frame.url === referrer.url) {
event.preventDefault();
frame.executeJavaScript('(function () {\
window.location = "'+url+'";\
})();');
} else if (frame.frames){
frame.frames.forEach(subframe => {
if (subframe.url === referrer.url) {
event.preventDefault();
subframe.executeJavaScript('(function () {\
window.location = "'+url+'";\
})();');
}
})
}
});
});
mainWindow.webContents.session.on('will-download', (event, item, webContents) => {
console.log("will-download");
if (mainWindow.webContents){
var currentURL = mainWindow.webContents.getURL();
} else if (webContents.getURL){
var currentURL = webContents.getURL();
}
if (currentURL.includes("autorecord") || (args.savefolder!==null)){
var dir = args.savefolder;
if (!dir && (process.platform == 'darwin')){ //process.env.USERPROFILE
dir = process.env.HOME + "/Downloads/";
} else if (!dir && (process.platform == 'win32')){ //process.env.USERPROFILE
dir = process.env.USERPROFILE + "\\Downloads\\";
} else if (!dir && process.env.HOME){ //process.env.USERPROFILE
dir = process.env.HOME + "/";
} else if (!dir && process.env.USERPROFILE){ //process.env.USERPROFILE
dir = process.env.USERPROFILE + "/";
}
if (dir!==null){
console.log("Auto saving too "+dir + item.getFilename());
item.setSavePath(dir + item.getFilename())
}
}
});
mainWindow.webContents.on('did-finish-load', function(e){
console.log("did-finish-load");
if (tainted){
mainWindow.setSize(parseInt(WIDTH/factor), parseInt(HEIGHT/factor)); // allows for larger than display resolution.
tainted=false;
}
if (mainWindow && mainWindow.webContents.getURL().includes('youtube.com')){
console.log("Youtube ad skipper inserted");
setInterval(function(mw){
try {
mw.webContents.executeJavaScript('\
if (typeof xxxxxx == "undefined") {\
var xxxxxx = setInterval(function(){\
if (document.querySelector(".ytp-ad-skip-button")){\
document.querySelector(".ytp-ad-skip-button").click();\
}\
},500);\
}\
');
} catch(e){
clearInterval(this);
return;
}
},5000, mainWindow);
}
if (CSSCONTENT && mainWindow && mainWindow.webContents){
try {
mainWindow.webContents.insertCSS(CSSCONTENT, {cssOrigin: 'user'});
console.log("Inserting specified CSS contained in the file");
} catch(e){
console.log(e);
}
}
//
});
//ipcMain.on('postMessage', (msg) => {
// console.log('We received a postMessage from the preload script')
//})
ipcMain.on('getAppVersion', function(eventRet) {
try{
if (mainWindow) {
mainWindow.webContents.send('appVersion', app.getVersion());
}
} catch(e){console.error(e);}
});
if (mainWindow){
const ret = globalShortcut.register('CommandOrControl+M', () => {
console.log('CommandOrControl+M is pressed')
if (mainWindow.node && mainWindow.vdonVersion){
mainWindow.webContents.send('postMessage', {'micOld':'toggle'})
} else if (mainWindow && mainWindow.vdonVersion) {
mainWindow.webContents.send('postMessage', {'mic':'toggle'})
}
});
if (!ret) {
console.log('registration failed1')
}
}
const ret_refresh = globalShortcut.register('CommandOrControl+Shift+Alt+R', () => {
console.log('CommandOrControl+Shift+Alt+R')
if (mainWindow) {
mainWindow.reload();
}
});
if (!ret_refresh) {
console.log('registration failed2')
}
const socialstream = globalShortcut.register('CommandOrControl+Shift+Alt+X', () => {
console.log('CommandOrControl+Shift+Alt+X')
if (mainWindow) {
if (mainWindow.mouseEvent){
mainWindow.mouseEvent = false;
mainWindow.setIgnoreMouseEvents(mainWindow.mouseEvent);
mainWindow.show()
if (!mainWindow.args.pin){
mainWindow.setAlwaysOnTop(false);
}
} else {
mainWindow.mouseEvent = true;
mainWindow.setIgnoreMouseEvents(mainWindow.mouseEvent);
if (process.platform == 'darwin'){
mainWindow.setAlwaysOnTop(true, "floating", 1)
} else {
mainWindow.setAlwaysOnTop(true, "level");
}
}
}
});
if (!socialstream) {
console.log('registration failed3')
}
// "CommandOrControl+Shift+X
try {
if (PIN == true) {
// "floating" + 1 is higher than all regular windows, but still behind things
// like spotlight or the screen saver
mainWindow.setAlwaysOnTop(true, "level");
// allows the window to show over a fullscreen window
mainWindow.setVisibleOnAllWorkspaces(true);
} else {
mainWindow.setAlwaysOnTop(false);
// allows the window to show over a fullscreen window
mainWindow.setVisibleOnAllWorkspaces(false);
}
if (reuse){
if (FULLSCREEN){
if (process.platform == "darwin"){
mainWindow.maximize();
} else {
mainWindow.setFullScreen(true);
}
}
} else if (FULLSCREEN){
if (process.platform == "darwin"){
mainWindow.maximize();
} else {
mainWindow.setFullScreen(true);
}
}
if (process.platform == "darwin"){
try { // MacOS
app.dock.hide();
} catch (e){
// Windows?
}
}
} catch(e){console.error(e);}
mainWindow.once('ready-to-show', () => {
console.log("ready to show");
if (MINIMIZED){
mainWindow.minimize();
//+ KravchenkoAndrey 08.01.2022
} else if (UNCLICKABLE){
mainWindow.showInactive();
//- KravchenkoAndrey 08.01.2022
} else {