forked from dangeredwolf/ModernDeck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
1490 lines (1175 loc) · 37.4 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
/*
main.js
Copyright (c) 2014-2022 dangeredwolf
Released under the MIT license
made with love <3
*/
const electron = require("electron");
const I18nData = require("./i18nMain.js").default;
const {
app,
BrowserWindow,
ipcMain,
session,
systemPreferences,
Menu,
dialog,
nativeTheme,
nativeImage,
protocol,
Tray,
globalShortcut
} = require("electron");
const fs = require("fs");
const path = require("path");
const url = require("url");
const https = require("https");
const separator = process.platform === "win32" ? "\\" : "/";
const log = require("electron-log");
const { autoUpdater } = require("electron-updater");
const Store = require("electron-store");
const store = new Store({name:"mtdsettings"});
// const disableCss = false; // use storage.mtd_safemode
const isAppX = !!process.windowsStore;
const isFlatpak = (process.platform === "linux" && process.env.FLATPAK_HOST === "1")
const isMAS = !!process.mas;
const isDev = false;
let enableTray = true;
let enableBackground = true;
let shouldQuitIfErrorClosed = true;
let hidden = false;
let mainWindow;
let errorWindow;
let tray = null;
let isRestarting = false;
let closeForReal = false;
let mtdAppTag = '';
let lang = store.get("mtd_lang");
if (process.execPath.match(/:\\Program Files/g) === null) {
autoUpdater.setFeedURL({
"owner": "dangeredwolf",
"repo": "ModernDeck",
"provider": "github"
});
} else {
autoUpdater.setFeedURL({
"owner": "dangeredwolf",
"repo": "ModernDeckEnterprise",
"provider": "github"
});
}
let enterpriseConfig = {};
if (process.platform === "win32") {
try {
let configFile = fs.readFileSync("C:\\ProgramData\\ModernDeck\\config.json");
try {
enterpriseConfig = JSON.parse(configFile);
} catch(e) {
app.on("ready", () => {
dialog.showMessageBoxSync({
type:"error",
title:"ModernDeck",
message:"ModernDeck detected an enterprise config file, but an error occurred while reading it. Please ensure the JSON is free from any errors.\n\n" + e
});
})
}
} catch (e) {
console.error("Could not read organization config file");
console.error(e);
}
}
console.log(enterpriseConfig);
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = "info";
switch(enterpriseConfig.autoUpdatePolicy) {
case "disabled":
case "manual":
case "checkOnly":
case "autoDownload":
if (enterpriseConfig.autoUpdateInstallOnQuit === false) {
autoUpdater.autoInstallOnAppQuit = false;
}
if (enterpriseConfig.autoUpdatePolicy !== "autoDownload") {
autoUpdater.autoDownload = false;
}
break;
}
app.setAppUserModelId("com.dangeredwolf.ModernDeck");
let useDir = "common";
const I18n = function(key) {
let foundStr = I18nData[key];
if (!foundStr) {
console.warn("Main process missing translation: " + key);
return key;
}
return foundStr[lang] || key;
}
const mtdSchemeHandler = async (request, callback) => {
if (request.url === "moderndeck://background/") {
callback({
path: enterpriseConfig.customLoginImage
});
return;
}
let myUrl = new url.URL(request.url);
const filePath = path.join(electron.app.getAppPath(), useDir, myUrl.hostname, myUrl.pathname);
callback({
path: filePath
});
};
const template = [
{
label: "ModernDeck",
role: "appMenu",
submenu: [
{ label: I18n("About ModernDeck"), click() { if (!mainWindow){return;}mainWindow.show();mainWindow.webContents.send("aboutMenu"); } },
{ label: I18n("Check for Updates..."), click(){ if (!mainWindow){return;}mainWindow.show();mainWindow.webContents.send("checkForUpdatesMenu"); } },
{ type: "separator" },
{ label: I18n("Preferences..."), click(){ if (!mainWindow){return;}mainWindow.show();mainWindow.webContents.send("openSettings"); } },
{ label: I18n("Accounts..."), click(){ if (!mainWindow){return;}mainWindow.show();mainWindow.webContents.send("accountsMan"); } },
{ type: "separator" },
{ role: "services" },
{ type: "separator" },
{ role: "hide" },
{ role: "hideothers" },
{ role: "unhide" },
{ type: "separator" },
{ role: "quit" }
]
},
{
role: "fileMenu",
submenu: [
{ label: I18n("New Tweet..."), click(){ if (!mainWindow){return;}mainWindow.show();mainWindow.webContents.send("newTweet"); } },
{ label: I18n("New Direct Message..."), click(){ if (!mainWindow){return;}mainWindow.show();mainWindow.webContents.send("newDM"); } },
{ type: "separator" },
{ role: "close" }
]
},
{
role: "editMenu",
submenu: [
{ role: "undo" },
{ role: "redo" },
{ type: "separator" },
{ role: "cut" },
{ role: "copy" },
{ role: "paste" },
{ role: "delete" },
{ role: "selectAll" },
{ type: "separator" },
{
label: I18n("Speech"),
submenu: [
{ role: "startspeaking" },
{ role: "stopspeaking" }
]
}
]
},
{
role: "viewMenu",
submenu: [
{ role: "reload" },
{ role: "forcereload" },
{ type: "separator" },
{ role: "resetzoom" },
{ role: "zoomin" },
{ role: "zoomout" },
{ role: "toggledevtools" },
{ type: "separator" },
{ role: "togglefullscreen" }
]
},
{
role: "windowMenu",
submenu: [
{ role: "minimize" },
{ role: "zoom" },
{ type: "separator" },
{ role: "front" },
{ type: "separator" },
{ role: "window" }
]
},
{
role: "help",
submenu: [
{ label: I18n("Send Feedback"), click(){ electron.shell.openExternal("https://github.com/dangeredwolf/ModernDeck/issues");}},
{ label: I18n("Message @ModernDeck"), click(){ if (!mainWindow){electron.shell.openExternal("https://twitter.com/messages/compose?recipient_id=2927859037");return;}mainWindow.show();mainWindow.webContents.send("msgModernDeck"); } },
]
}
]
const menu = Menu.buildFromTemplate(template);
// if (process.platform === "darwin")
Menu.setApplicationMenu(menu);
function loadEnterpriseConfigMain() {
if (enterpriseConfig.disableDevTools) {
// https://stackoverflow.com/questions/40304833/how-to-make-the-dev-tools-not-show-up-on-screen-by-default-electron
globalShortcut.register("Control+Shift+I", () => {});
}if (enterpriseConfig.disableZoom) {
globalShortcut.register("Control+-", () => {});
globalShortcut.register("Control+Shift+=", () => {});
}
}
function isRosetta() {
let cpu0 = require("os").cpus()[0];
if (cpu0 && cpu0.model) {
return process.arch === "x64" && process.platform === "darwin" && cpu0.model.indexOf("VirtualApple") > -1
} else {
return false;
}
}
function makeErrorWindow() {
const { shell } = electron;
shell.beep();
errorWindow = new BrowserWindow({
width: 600,
height: 260,
webPreferences: {
scrollBounce: true,
nodeIntegration: true
},
enableRemoteModule:true,
parent:mainWindow || null,
autoHideMenuBar:true
});
shouldQuitIfErrorClosed = true;
errorWindow.webContents.on("new-window", (event, url) => {
const { shell } = electron;
event.preventDefault();
shell.openExternal(url);
});
errorWindow.on("closed", () => {
errorWindow = null;
if (shouldQuitIfErrorClosed) {
app.quit();
}
});
errorWindow.loadURL(__dirname + separator + "sadmoderndeck.html");
errorWindow.webContents.on("did-start-navigation", (event, url) => {
event.preventDefault();
});
}
function makeLoginWindow(url,teams) {
let originalUrl = url;
let loginWindow = new BrowserWindow({
width: 710,
height: 490,
webPreferences: {
scrollBounce: true,
nodeIntegration: false
},
parent:mainWindow || null,
modal:true,
autoHideMenuBar:true
});
loginWindow.on("closed", () => {
loginWindow = null;
});
loginWindow.webContents.on("will-navigate", (event, url) => {
console.log("will-navigate", url);
const { shell } = electron;
if (url.indexOf("https://tweetdeck.twitter.com") >= 0 && !teams) {
console.log("Hello tweetdeck!");
if (loginWindow) {
loginWindow.close();
}
if (mainWindow) {
mainWindow.reload();
}
event.preventDefault();
return;
}
if (url.indexOf("twitter.com/logout") >= 0) {
console.log("Hello logout!");
if (mainWindow) {
mainWindow.reload();
}
if (loginWindow) {
loginWindow.close();
}
event.preventDefault();
return;
}
if (url.indexOf("twitter.com/logout") >= 0 || url.indexOf("twitter.com/login") >= 0 || url.indexOf("twitter.com/i/flow/login") >= 0 ||url.indexOf("twitter.com/account/login_verification") >= 0 || teams) {
return;
}
if (url.indexOf("twitter.com/account") >= 0 || url.indexOf("twitter.com/signup") >= 0|| url.indexOf("twitter.com/signup") >= 0) {
event.preventDefault();
shell.openExternal(url);
return;
}
if (url.indexOf("twitter.com/sessions") >= 0) {
return;
}
event.preventDefault();
});
loginWindow.webContents.on("did-navigate-in-page", (event, url) => {
console.log("did-navigate-in-page", url);
if (url.indexOf("https://tweetdeck.twitter.com") >= 0) {
console.log("Hello tweetdeck2!");
if (mainWindow) {
mainWindow.loadURL(url);
}
if (loginWindow) {
loginWindow.close();
}
event.preventDefault();
return;
}
if (url.indexOf("/i/flow/signup") >= 0 || url.indexOf("/i/flow/password_reset") >= 0) {
event.preventDefault();
loginWindow.webContents.goBack();
const {shell} = electron;
shell.openExternal(url);
return;
}
if (url.indexOf("twitter.com/logout") >= 0 || url.indexOf("twitter.com/login") >= 0 || url.indexOf("twitter.com/i/flow/login") >= 0) {
return;
}
if (loginWindow) {
loginWindow.loadURL(originalUrl);
}
});
loginWindow.webContents.on("new-window", (event, url) => {
console.log("new-window", url);
const {shell} = electron;
event.preventDefault();
shell.openExternal(url);
});
loginWindow.loadURL(url);
return loginWindow;
}
function saveImageAs(url) {
if (!url) {
throw "saveImageAs requires \"URL\" as an argument";
return;
}
let fileType = url.match(/(?<=format=)(\w{3,4})|(?<=\.)(\w{3,4}(?=\?))/g)[0] || "file";
let fileName = url.match(/(?<=media\/)[\w\d_\-]+|[\w\d_\-]+(?=\.m)/g)[0] || "jpg";
// console.log("saveImageAs");
let savePath = dialog.showSaveDialogSync({defaultPath:fileName + "." + fileType});
// console.log(savePath);
if (savePath) {
try {
const file = fs.createWriteStream(savePath);
const request = https.get(url, function(response) {
// console.log("Piping file...");
response.pipe(file);
});
} catch(e) {
console.log(e);
}
}
};
function saveWindowBounds() {
if (!mainWindow) {
return;
}
try {
let bounds = mainWindow.getBounds();
store.set("mtd_fullscreen", mainWindow.isFullScreen());
store.set("mtd_maximised", mainWindow.isMaximized());
if (!mainWindow.isMaximized() && !mainWindow.isFullScreen())
store.set("mtd_windowBounds", mainWindow.getBounds());
const matchedDisplay = electron.screen.getDisplayMatching({
x: bounds.x,
y: bounds.y,
width: bounds.width,
height: bounds.height
});
store.set("mtd_usedDisplay", matchedDisplay.id);
} catch(e) {
console.error(e);
}
}
function makeWindow() {
const lock = app.requestSingleInstanceLock();
if (!lock) {
closeForReal = true;
app.quit();
return;
}
let display = {};
if (!store.has("mtd_nativetitlebar")) {
store.set("mtd_nativetitlebar",false);
}
protocol.registerFileProtocol("moderndeck", mtdSchemeHandler);
isRestarting = false;
let useFrame = store.get("mtd_nativetitlebar") || store.get("mtd_safemode") || process.platform === "darwin";
let titleBarStyle = "hidden";
if (store.get("mtd_nativetitlebar")) {
titleBarStyle = "default";
}
if (store.has("mtd_updatechannel")) {
if (store.get("mtd_updatechannel") === "beta") {
autoUpdater.allowPrerelease = true;
}
autoUpdater.channel = store.get("mtd_updatechannel");
}
let bounds = store.get("mtd_windowBounds") || {};
let useXY = !!bounds.x && !!bounds.y
mainWindow = new BrowserWindow({
width: bounds.width || 1024,
height: bounds.height || 660,
x: useXY ? bounds.x : undefined,
y: useXY ? bounds.y : undefined,
webPreferences: {
defaultFontFamily:"Roboto",
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true,
webgl: false,
plugins: false,
scrollBounce:true,
// preload: __dirname+separator+useDir+separator+"resources"+separator+"moderndeck.js"
},
autoHideMenuBar:true,
nodeIntegrationInSubFrames:false,
title:"ModernDeck",
// icon:__dirname+useDir+"/resources/favicon.ico",
frame:useFrame,
titleBarStyle:titleBarStyle,
minWidth:375,
show:false,
backgroundThrottling:true,
backgroundColor:"#111"
});
// macOS specific: Don't run from DMG, move to Applications folder.
if (process.platform === "darwin" && !app.isInApplicationsFolder() && !isDev) {
const { dialog } = electron;
dialog.showMessageBox({
type: "warning",
title: "ModernDeck",
message: I18n("Updates might not work correctly if you aren't running ModernDeck from the Applications folder.\n\nWould you like to move it there?"),
buttons: [I18n("Not Now"), I18n("Yes, Move It")]
}, (response) => {
if (response == 1) {
let moveMe;
try {
moveMe = app.moveToApplicationsFolder();
} catch (e) {
console.error(e);
}
if (!moveMe){
dialog.showMessageBox({
type: "error",
title: "ModernDeck",
message: I18n("We couldn't automatically move ModernDeck to the applications folder. You may need to move it yourself."),
buttons: [I18n("OK")]
});
}
}
});
}
// Prevent changing the Page Title
mainWindow.on("page-title-updated", (event,url) => {
event.preventDefault();
});
// Save window bounds if it's closed, or otherwise occasionally
mainWindow.on("close",(e) => {
setTimeout(saveWindowBounds, 0);
});
setInterval(saveWindowBounds, 60 * 1000);
mainWindow.show();
hidden = false;
require("@electron/remote/main").enable(mainWindow.webContents);
updateAppTag();
try {
mainWindow.webContents.executeJavaScript(`
document.getElementsByClassName("js-signin-ui block")[0].innerHTML =
\`<img class="mtd-loading-logo" src="moderndeck://resources/img/moderndeck.png" style="display: none;">
<div class="preloader-wrapper active">
<div class="spinner-layer">
<div class="circle-clipper left">
<div class="circle"></div>
</div>
<div class="gap-patch">
<div class="circle"></div>
</div>
<div class="circle-clipper right">
<div class="circle"></div>
</div>
</div>
</div>\`;
if (typeof mtdLoadStyleCSS === "undefined") {
mtdLoadStyleCSS = \`
img.spinner-centered {
display:none!important
}
\`
mtdLoadStyle = document.createElement("style");
mtdLoadStyle.appendChild(document.createTextNode(mtdLoadStyleCSS))
document.head.appendChild(mtdLoadStyle);
}
if (document.getElementsByClassName("spinner-centered")[0]) {
document.getElementsByClassName("spinner-centered")[0].remove();
}
document.getElementsByTagName("html")[0].style = "background: #111;";
document.getElementsByTagName("body")[0].style = "background: #111;";
`)
} catch(e) {
}
mainWindow.webContents.on("dom-ready", (event, url) => {
mainWindow.webContents.executeJavaScript(`
document.getElementsByTagName("html")[0].style = "background: #111!important;";
document.getElementsByTagName("body")[0].style = "background: #111!important;";
if (typeof mtdLoadStyleCSS === "undefined") {
mtdLoadStyleCSS = \`
img.spinner-centered {
display:none!important
}
\`
mtdLoadStyle = document.createElement("style");
mtdLoadStyle.appendChild(document.createTextNode(mtdLoadStyleCSS))
document.head.appendChild(mtdLoadStyle);
}
if (document.getElementsByClassName("spinner-centered")[0]) {
document.getElementsByClassName("spinner-centered")[0].remove();
}
document.getElementsByClassName("js-signin-ui block")[0].innerHTML =
\`<img class="mtd-loading-logo" src="moderndeck://resources/img/moderndeck.png" style="display: none;">
<div class="preloader-wrapper active">
<div class="spinner-layer">
<div class="circle-clipper left">
<div class="circle"></div>
</div>
<div class="gap-patch">
<div class="circle"></div>
</div>
<div class="circle-clipper right">
<div class="circle"></div>
</div>
</div>
</div>\`;
`)
mainWindow.webContents.executeJavaScript(
'\
var injurl = document.createElement("div");\
injurl.setAttribute("type","moderndeck://");\
injurl.id = "MTDURLExchange";\
document.head.appendChild(injurl);\
\
var InjectScript2 = document.createElement("script");\
InjectScript2.src = "moderndeck://resources/libraries/moduleraid.min.js";\
InjectScript2.type = "text/javascript";\
document.head.appendChild(InjectScript2);'
+
(store.get("mtd_safemode") ? 'document.getElementsByTagName("html")[0].classList.add("mtd-disable-css");' :
'var injStyles = document.createElement("link");\
injStyles.rel = "stylesheet";\
injStyles.href = "moderndeck://resources/moderndeck.css";\
document.head.appendChild(injStyles);')
+
'var InjectScript = document.createElement("script");\
InjectScript.src = "moderndeck://resources/moderndeck.js";\
InjectScript.type = "text/javascript";\
document.head.appendChild(InjectScript);\
');
updateAppTag();
});
mainWindow.webContents.on("did-fail-load", (event, code, desc) => {
let msg = "ModernDeck failed to start." + "\n\n";
// These codes aren't necessarily fatal errors, so we ignore them instead of forcing the user to shut down ModernDeck.
if (code === -3 || code === -11 || code === -2 || code === -1) {
return;
}
makeErrorWindow();
mainWindow.hide();
errorWindow.webContents.executeJavaScript(`
document.getElementById("code").innerHTML = "${desc}";
document.getElementById("close").innerHTML = "${I18n("Close")}";
document.getElementById("retry").innerHTML = "${I18n("Retry")}";
document.getElementById("twitterStatus").innerHTML = "${I18n("Twitter Status")}";
`);
console.log(desc);
return;
});
/*
The content security policy needs to be replaced to be able to interact with GIF services
*/
mainWindow.webContents.session.webRequest.onHeadersReceived(
{urls:["https://tweetdeck.twitter.com/*"]},
(details, callback) => {
let foo = details.responseHeaders;
foo["content-security-policy"] =[
"default-src 'self'; connect-src * moderndeck:; "+
"font-src https: blob: data: * moderndeck:; "+
"frame-src https: moderndeck:; "+
"frame-ancestors 'self' https: moderndeck:; "+
"img-src https: file: data: blob: moderndeck:; "+
"media-src * moderndeck: blob: https:; "+
"object-src 'self' https:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://moderndeck.org moderndeck: https://*.twitter.com https://*.twimg.com https://api-ssl.bitly.com blob:; "+
"style-src 'self' 'unsafe-inline' 'unsafe-eval' https: moderndeck: blob:;"];
callback({ responseHeaders: foo});
}
);
mainWindow.webContents.session.webRequest.onBeforeSendHeaders({urls:["https://twitter.com/i/jot*", "https://tweetdeck.twitter.com/Users*"]}, (details, callback) => {
callback({cancel: true})
})
// mainWindow.webContents.session.webRequest.onHeadersReceived(
// {urls:["https://*.twitter.com/*","https://*.twimg.com/*"]},
// (details, callback) => {
// let foo = details.responseHeaders;
// foo["Access-Control-Allow-Origin"] =[
// "moderndeck://."];
// foo["Access-Control-Allow-Credentials"] = [
// "true"
// ]
// callback({ responseHeaders: foo});
// }
// );
mainWindow.webContents.loadURL("https://tweetdeck.twitter.com");
/*
Web content requests to navigate away from page.
If this is not a TweetDeck URL, we will instead pass
it on to the browser, unless...
...if it is a Twitter URL, we pop it up in a login Window.
*/
mainWindow.webContents.on("will-navigate", (event, url) => {
const { shell } = electron;
console.log(url);
if (url.indexOf("https://tweetdeck.twitter.com") < 0 && url.indexOf("moderndeck://.") < 0) {
event.preventDefault();
console.log(url);
if (url.indexOf("twitter.com/login") >= 0 || url.indexOf("twitter.com/i/flow/login") >= 0 || url.indexOf("twitter.com/logout") >= 0) {
console.log("this is a login window! will-navigate");
event.newGuest = makeLoginWindow(url,false);
} else {
shell.openExternal(url);
}
}
updateAppTag();
});
/*
Web content requests to open a new window.
This is redirected in browser if it is not a TweetDeck URL.
If it is a Twitter URL, we pop it up in a login Window.
*/
mainWindow.webContents.on("new-window", (event, url) => {
const { shell } = electron;
event.preventDefault();
console.log(url);
if (url.indexOf("https://twitter.com/teams/authorize") >= 0) {
console.log("this is a login teams window! new-window");
event.newGuest = makeLoginWindow(url,true);
} else if (url.indexOf("twitter.com/login") >= 0 || url.indexOf("twitter.com/i/flow/login") >= 0 || url.indexOf("twitter.com/logout") >= 0) {
console.log("this is a login non-teams window! new-window");
event.newGuest = makeLoginWindow(url,false);
} else {
shell.openExternal(url).catch(() => {
mainWindow.webContents.send("failedOpenUrl");
})
}
return event.newGuest;
});
// i actually forget why this is here
mainWindow.webContents.on("context-menu", (event, params) => {
if (!mainWindow || !mainWindow.webContents) { return }
mainWindow.webContents.send("context-menu", params);
});
/*
If a user uses native context menus, this is mtdInject telling us
to put up a native context menu with the given commands, instead
of it doing it itself.
*/
ipcMain.on("getEnterpriseConfig", (event, params) => {
if (!mainWindow || !mainWindow.webContents) { return }
mainWindow.webContents.send("enterpriseConfig", enterpriseConfig);
});
ipcMain.on("nativeContextMenu", (event, params) => {
console.log(params);
let newMenu = Menu.buildFromTemplate(params);
console.log(newMenu);
newMenu.popup();
});
ipcMain.on("errorReload", (event, params) => {
mainWindow.reload();
mainWindow.show();
shouldQuitIfErrorClosed = false;
errorWindow.close();
});
ipcMain.on("loadSettingsDialog", (event, params) => {
dialog.showOpenDialog(
{ filters: [{ name: I18n("Preferences JSON File"), extensions: ["json"] }] }
).then((results) => {
console.log(results);
if (typeof results.filePaths === "undefined") {
return;
}
fs.readFile(results.filePaths[0], "utf-8", (_, load) => {
mainWindow.webContents.send("settingsReceived", JSON.parse(load));
});
});
});
ipcMain.on("tweetenImportDialog", (event, params) => {
dialog.showOpenDialog(
{ filters: [{ name: I18n("Tweeten Settings JSON"), extensions: ["json"] }] }
).then((results) => {
if (typeof results.filePaths === "undefined") {
return;
}
fs.readFile(results.filePaths[0], "utf-8", (_, load) => {
mainWindow.webContents.send("tweetenSettingsReceived", JSON.parse(load));
});
});
});
ipcMain.on("saveSettings", (event, params) => {
dialog.showSaveDialog(
{
title: I18n("ModernDeck Preferences"),
defaultPath: "settings.json",
filters: [{ name: I18n("Preferences JSON File"), extensions: ["json"] }]
}
).then((results) => {
if (results.filePath === undefined) {
return;
}
fs.writeFile(results.filePath, params, (e) => {});
});
})
ipcMain.on("errorQuit", (event, params) => {
app.quit();
});
ipcMain.on("drawerOpen", (event, params) => {
console.log("open");
if (!mainWindow || !mainWindow.webContents) { return }
mainWindow.webContents.executeJavaScript("document.querySelector(\"html\").classList.add(\"mtd-drawer-open\");");
});
ipcMain.on("drawerClose", (event, params) => {
console.log("close");
if (!mainWindow || !mainWindow.webContents) { return }
mainWindow.webContents.executeJavaScript("document.querySelector(\"html\").classList.remove(\"mtd-drawer-open\");");
});
ipcMain.on("maximizeButton", (event) => {
let window = BrowserWindow.getFocusedWindow();
if (!window) {
return;
}
if (window.isMaximized()) {
window.unmaximize();
} else {
window.maximize();
}
});
ipcMain.on("minimize", (event) => {
BrowserWindow.getFocusedWindow().minimize();
});
/*
The options below are for right click menu actions
*/
ipcMain.on("copy", (event) => {
if (!mainWindow || !mainWindow.webContents) { return }
mainWindow.webContents.copy();
});
ipcMain.on("cut", (event) => {
if (!mainWindow || !mainWindow.webContents) { return }
mainWindow.webContents.cut();
});
ipcMain.on("paste", (event) => {
if (!mainWindow || !mainWindow.webContents) { return }
mainWindow.webContents.paste();
});
ipcMain.on("delete", (event) => {
if (!mainWindow || !mainWindow.webContents) { return }
mainWindow.webContents.delete();
});
ipcMain.on("selectAll", (event) => {
if (!mainWindow || !mainWindow.webContents) { return }
mainWindow.webContents.selectAll();
});
ipcMain.on("undo", (event) => {
if (!mainWindow || !mainWindow.webContents) { return }
mainWindow.webContents.undo();
});
ipcMain.on("redo", (event) => {
if (!mainWindow || !mainWindow.webContents) { return }
mainWindow.webContents.redo();
});
ipcMain.on("copyImage", (event, arg) => {
if (!mainWindow || !mainWindow.webContents) { return }
mainWindow.webContents.copyImageAt(arg.x, arg.y);
});
ipcMain.on("saveImage", (event, arg) => {
saveImageAs(arg);
});