-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
1797 lines (1554 loc) · 64 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 prompt = require('electron-prompt');
const sharp = require('sharp');
const ShutdownHandler = require('@paymoapp/electron-shutdown-handler').default;
const fetch = require('electron-fetch').default
const isMac = process.platform === 'darwin'
const isWindows = process.platform === 'win32'
const isLinux = process.platform === 'linux'
/*if ((isMac) || (isLinux)) {
var { app, clipboard, BrowserWindow, Menu, Tray, nativeImage, Notification, dialog, session, shell, powerMonitor, nativeTheme } = require('electron')
}
if (isWindows) {
var { app, clipboard, Menu, Tray, nativeImage, Notification, dialog, session, shell, powerMonitor, nativeTheme } = require('electron')
var { BrowserWindow } = require('electron-acrylic-window') // return BrowserWindows to electron in case of not using electron-acrylic-window
}*/
const { app, clipboard, BrowserWindow, Menu, Tray, nativeImage, Notification, dialog, session, shell, powerMonitor, nativeTheme } = require('electron')
const { exec } = require('child_process');
//const SystemIdleTime = require('@paulcbetts/system-idle-time');
const SystemIdleTime = require('desktop-idle');
const fs = require("fs");
const { join } = require('path');
const path = require('node:path');
const Store = require('electron-store');
const theme = nativeTheme.shouldUseDarkColors ? 'dark' : 'light'
const gotTheLock = app.requestSingleInstanceLock();
// if dev mode then use different userData folder
if (!app.isPackaged) {
console.log('App is in dev mode');
let current_app_dir = app.getPath('userData')
app.setPath ('userData', current_app_dir+"-dev");
} else {
console.log('App is in production mode');
}
try {
var i18n = new(require('./translations/i18n'));
main();
async function main() {
const store = new Store();
// TODO check allow_multiple in newer version
let allow_multiple = false/*store.get('allow_multiple') ? JSON.parse(store.get('allow_multiple')) : false;*/
// prevent multiple instances, focus on the existed app instead
if (!gotTheLock) {
if (!allow_multiple) {
app.exit(0);
}
} else {
if (!allow_multiple) {
app.on('second-instance', (event) => {
if (win) {
//if (win.isMinimized()) win.restore();
win.show();
win.focus();
if (isMac) app.dock.show();
}
})
}
try {
// to check prompted status for dialogs
let prompted = false
let auto_login_error = false
let idleTime_non_active = 0;
// to check gui_blocked status
//let gui_blocked = false
//let is_notification = false;
// for storing unread counter
let unread = false;
let unread_prev = false;
// to store settings menu opened status
let settings_opened = false;
setTimeout(function() {checkNewVersion(app.getVersion())},3000);
let url = "";
const url_example = 'https://cloud.example.com';
if (!((app.commandLine.getSwitchValue("server_url") == undefined) || (app.commandLine.getSwitchValue("server_url") == ""))) {
// overwrite server_url if arg is given
store.set('server_url',app.commandLine.getSwitchValue("server_url"))
url = app.commandLine.getSwitchValue("server_url");
} else if (!((store.get('server_url') == undefined) || (store.get('server_url') == ""))) {
url = store.get('server_url');
}
let iconPath = path.join(__dirname,store.get('app_icon_name')||'iconTemplate.png');
let icon = nativeImage.createFromPath(iconPath); // template with center transparency
let trayIcon = icon
let dockIcon = icon
if (isMac) {
var icon_bw = await bw_icon_process(icon);
// as this icon is for macos tray only resize it here
icon_bw = icon_bw.resize({width:16});
}
//icon = icon_bw
//const icon_notification = nativeImage.createFromPath(path.join(__dirname,store.get('notification_icon_name')||'notification.png'));
//const icon_red_dot = nativeImage.createFromPath(path.join(__dirname,'red_dot.png'));
//const icon = './icon.png';
// set run at startup
if (store.get('run_at_startup')) {
app.setLoginItemSettings({
openAtLogin: true,
//name: app.getName() + " v."+app.getVersion() // to fix version in registry autorun
name: app.getName()
})
if (isLinux) {
let executable = "talk-electron";
if (process.env.APPIMAGE) {
executable = process.env.APPIMAGE;
} else {
executable = app.getPath('exe');
}
let shortcut_contents = `[Desktop Entry]
Categories=Utility;
Comment=Talk web embedded app
Exec=sleep 15 && "`+executable+`"
Icon=talk-electron
Name=NC Talk Electron
StartupWMClass=NC Talk Electron
Terminal=false
Type=Application
Icon=talk-electron`;
if (!fs.existsSync(app.getPath('home')+"/.config/autostart/talk-electron.desktop")) {
fs.writeFileSync(app.getPath('home')+"/.config/autostart/talk-electron.desktop",shortcut_contents, 'utf-8');
}
}
} else {
app.setLoginItemSettings({
openAtLogin: false,
//name: app.getName() + " v."+app.getVersion() // to fix version in registry autorun
name: app.getName()
})
if (isLinux) {
if (fs.existsSync(app.getPath('home')+"/.config/autostart/talk-electron.desktop")) {
fs.unlinkSync(app.getPath('home')+"/.config/autostart/talk-electron.desktop")
}
}
}
var win = null;
//var win_loading = null;
var appIcon = null;
var MainMenu = null;
let mainMenuTemplate = [
{
label: i18n.__('file'),
submenu: [
{
label: i18n.__('open_nc'),
click: () => {
shell.openExternal(store.get('server_url'));
},
},
{
label: i18n.__('preferences'),
click: () => {
openSettings();
},
},
{ type: 'separator' },
{
label: i18n.__('exit'),
accelerator: isMac ? 'Cmd+Q' : 'Alt+X',
click: () => {
store.set('bounds', win.getBounds());
store.delete('latestVersion');
store.delete('releaseUrl');
app.exit(0);
},
}
]
},
{
label : i18n.__('view'),
submenu : [
//{ label : "Обновить", role : "reload" },
{ label: i18n.__('refresh'),
click: () => {
/*if (!gui_blocked) {
block_gui_loading(true);*/
win.reload()
//}
},
accelerator: isMac ? 'Cmd+R' : 'Ctrl+R'
},
{ type: 'separator' },
{ label: i18n.__('hide'),
click: () => {
if (isMac) app.dock.hide();
/*if (!isMac)*/ win.hide();
},
accelerator: isMac ? 'Cmd+H' : 'Ctrl+H',
role : "hide"
},
{ label: i18n.__('fullscreen'),
accelerator: isMac ? 'Cmd+M' : 'Ctrl+M',
click: () => {
checkMaximize(true);
if (isMac) { /*app.dock.setIcon(icon); */app.dock.show();};
},
},
]
},
{
label : "?",
submenu : [
{ label : i18n.__('help'),
accelerator: 'F1',
click: () => {
openPopup('https://docs.nextcloud.com/server/latest/user_manual/ru/talk');
//app.exit(0);
}
},
{ label: i18n.__('open_devtools'),
accelerator: 'F12',
click: () => {
win.webContents.toggleDevTools();
}
},
{ type: 'separator' },
{ label : i18n.__('about'),
// for linux compatibility
click: () => {
app.showAboutPanel();
}
}
]
}
];
let appIconMenuTemplate = [
{
label: i18n.__('show'),
click: () => {
/*if (gui_blocked) {
win_loading.show();
}*/
win.show()
if (isMac) { //app.dock.setIcon(dockIcon);
app.dock.show(); addBadgeMac();
};
},
},
{
label: i18n.__('hide'),
click: () => {
if (isMac) app.dock.hide();
/*if (!isMac)*/ win.hide();
//win_loading.hide();
},
role : "hide"
},
{ type: 'separator' },
{
label: i18n.__('open_nc'),
click: () => {
shell.openExternal(store.get('server_url'));
},
},
{
label: i18n.__('preferences'),
click: () => {
openSettings();
},
},
{
label : i18n.__('about'),
// for linux compatibility
click: () => {
app.showAboutPanel();
}
},
{ type: 'separator' },
{
label: i18n.__('exit'),
click: () => {
store.set('bounds', win.getBounds());
store.delete('latestVersion');
store.delete('releaseUrl');
app.exit(0);
},
}
];
/*function checkInactivity() {
const idleTime = SystemIdleTime.getIdleTime();
console.log('Idle time is:'+idleTime+' s');
//const idleTime = Date.now() - lastActivityTime;
if (idleTime > 4 * 60 ) {
console.log("User is not active for 4 minutes...");
} else {
//simulateActivity();
if (!win.isVisible() || !win.isFocused()) {
console.log("User is active for the last 4 minutes so reloading window to simulate activity...");
win.reload();
}
}
}*/
function checkInactivity(activity_check_interval) {
let idleTime = SystemIdleTime.getIdleTime();
if (!win.isVisible() || !win.isFocused()) {
idleTime_non_active = idleTime_non_active + activity_check_interval;
} else {
idleTime_non_active = 0;
}
//console.log('Current idle time is:'+idleTime+' s');
//console.log('Current hidden or unfocused time is:'+idleTime_non_active+' s');
if (idleTime_non_active > 4 * 60) {
if (idleTime <= 4 * 60) {
console.log("Window is hidden or unfocused for more than 4 minutes, but user was active - reloading the page...");
idleTime_non_active = 0;
win.reload();
}
}
}
function checkMaximize(click) {
if (win.isMaximized()) {
if (click) {
mainMenuTemplate[1].submenu[3].label = i18n.__("fullscreen");
win.unmaximize()
} else {
mainMenuTemplate[1].submenu[3].label = i18n.__("restore");
}
} else {
if (click) {
mainMenuTemplate[1].submenu[3].label = i18n.__("restore");
win.maximize()
} else {
mainMenuTemplate[1].submenu[3].label = i18n.__("fullscreen");
}
}
MainMenu = Menu.buildFromTemplate(mainMenuTemplate);
Menu.setApplicationMenu(MainMenu);
checkNewVersion(app.getVersion());
}
function isInternalLink(url) {
return url.startsWith('file')
}
function isExternalLink(url) {
return !isInternalLink(url)
}
function applyContextMenu(win) {
win.webContents.on('context-menu', (event, params) => {
const menuItems = []
let haveContext = false;
// Add context actions for misspelling words and typos
const menuMisspellingItems = [
...params.dictionarySuggestions.map(suggestion => ({
label: suggestion,
click: () => win.webContents.replaceMisspelling(suggestion),
})),
{ type: 'separator' },
{
//label: 'Add to dictionary',
label: i18n.__('add_to_dict'),
click: () => win.webContents.session.addWordToSpellCheckerDictionary(params.misspelledWord),
},
{ type: 'separator' },
]
if (params.misspelledWord) {
menuItems.push(...menuMisspellingItems)
haveContext = true;
}
// Add context actions for handling images
const menuImageItems = [
{
//label: 'Copy image',
label: i18n.__('copy_image'),
click: () => win.webContents.copyImageAt(params.x, params.y),
},
{
//label: 'Save image',
label: i18n.__('save_image'),
click: () => win.webContents.downloadURL(params.srcURL),
},
{ type: 'separator' },
]
if (params.hasImageContents) {
menuItems.push(...menuImageItems)
haveContext = true;
}
// Add context actions for handling links
const menuLinkItems = [
{
//label: 'Copy link address',
label: i18n.__('copy_link_address'),
click: () => clipboard.writeText(params.linkURL),
},
{
//label: 'Copy link text',
label: i18n.__('copy_link_text'),
click: () => clipboard.writeText(params.linkText.trim() || params.linkURL),
},
{ type: 'separator' },
]
if (params.linkURL && isExternalLink(params.linkURL)) {
menuItems.push(...menuLinkItems)
haveContext = true;
}
// Add context actions for clipboard events and text editing
const menuClipboardItems = [
{
role: 'copy',
label: i18n.__('copy'),
enabled: params.selectionText && params.editFlags.canCopy,
},
{
role: 'cut',
label: i18n.__('cut'),
enabled: params.selectionText && params.isEditable && params.editFlags.canCut,
visible: params.isEditable,
},
{
role: 'selectAll',
label: i18n.__('select_all'),
enabled: params.editFlags.canSelectAll,
},
{
role: 'paste',
label: i18n.__('paste'),
enabled: params.isEditable && params.editFlags.canPaste,
visible: params.isEditable,
},
{ type: 'separator' },
]
if (params.isEditable || params.selectionText.length) {
menuItems.push(...menuClipboardItems)
haveContext = true;
}
// TODO Remove or hide from production DevTools toggle before final release
//menuItems.push({ role: 'toggleDevTools' })
if (haveContext) {
Menu.buildFromTemplate(menuItems).popup()
}
})
}
function getSettings(win) {
var lang_files = JSON.stringify(i18n.___("get_locales"));
win.webContents.executeJavaScript(`loadSettings(`+JSON.stringify(store.store)+`,`+lang_files+`);`);
}
function addNewVersionLink(releaseUrl,latestVersion) {
const separator = { type: 'separator' };
const menu = Menu.getApplicationMenu();
const newVersionLabel = i18n.__('new_version')+latestVersion;
const newVersionMenuItem = {
label: newVersionLabel,
click: () => {
shell.openExternal(releaseUrl);
}
};
const menuItems = menu.items.map(item => item);
const exists = menuItems.some(item => item.label === newVersionLabel);
if (!exists) {
menuItems.push(separator);
menuItems.push(newVersionMenuItem);
const updatedMenu = Menu.buildFromTemplate(menuItems);
Menu.setApplicationMenu(updatedMenu);
}
}
async function checkNewVersion(currentVersion) {
const cachedVersion = store.get('latestVersion');
const cachedUrl = store.get('releaseUrl');
const apiUrl = `https://api.github.com/repos/drlight17/talk-electron/releases/latest`;
try {
let latestVersion;
let releaseUrl;
if (!cachedVersion && !cachedUrl) {
//console.log("Fetch new version info from github.")
const response = await fetch(apiUrl);
const data = await response.json();
// Извлекаем версию последнего релиза (tag name)
latestVersion = data.tag_name;
releaseUrl = data.html_url;
store.set('latestVersion', latestVersion);
store.set('releaseUrl', releaseUrl);
//console.log(`Current version: ${currentVersion}`);
//console.log(`Latest version: ${latestVersion}`);
} else {
//console.log("Using version info from cache.")
latestVersion = cachedVersion;
releaseUrl = cachedUrl;
}
const comparison = compareVersions(currentVersion, latestVersion);
if (comparison === 0) {
//console.log("You are using the latest version.");
} else if (comparison < 0) {
//console.log("A new version is available: " + latestVersion);
addNewVersionLink(releaseUrl,latestVersion);
} else {
//console.log("You are using a newer version.");
}
} catch (error) {
console.error('Error fetching the latest release:', error);
}
}
function compareVersions(version1, version2) {
const cleanVersion1 = version1.replace(/^v/, '');
const cleanVersion2 = version2.replace(/^v/, '');
const parts1 = cleanVersion1.split('.');
const parts2 = cleanVersion2.split('.');
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const part1 = parts1[i] || '0';
const part2 = parts2[i] || '0';
const comparison = part1.localeCompare(part2, undefined, { numeric: true });
if (comparison !== 0) {
return comparison;
}
}
return 0;
}
function localizeSettings(win) {
//win.webContents.toggleDevTools();
win.webContents.executeJavaScript(`get_all_ids();`);
win.webContents.on('console-message', (event, level, message, line, sourceId) => {
try {
if (JSON.parse(message).action == 'return_localize_ids') {
obj = JSON.parse(JSON.parse(message).localization_ids);
obj.forEach( id => {
let setting_loc= i18n.__(id.replace('_id',''))
win.webContents.executeJavaScript(`localize_setting("`+id+`","`+setting_loc+`");`);
// localization of allow_domain_id title
if (id == 'allow_domain_id') {
id = id.replace('_id','_title')
let setting_loc= i18n.__(id.replace('_id','_title'))
win.webContents.executeJavaScript(`localize_setting("`+id+`","`+setting_loc+`");`);
}
});
}
}
catch (err) {
//console.log(err);
//dialog.showErrorBox('Ошибка', "Подробнее: "+JSON.stringify(err));
}
});
}
// dirty function to apply unread badge to dock icon on Mac with 1s timeout
function addBadgeMac () {
//console.log(app.dock.getBadge());
//setTimeout (function() {
// force dockIcon!
app.dock.setIcon(dockIcon);
if (unread!=0) {
app.dock.setBadge('');
app.dock.setBadge(unread.toString());
} else {
app.dock.setBadge('');
}
//}, 1000);
}
function setSettings(message,win) {
try {
if (JSON.parse(message).action == 'save_settings') {
obj = JSON.parse(JSON.parse(message).settings);
for (var key in obj){
store.set(key, obj[key]);
}
//win.close();
app.relaunch();
app.exit(0);
}
}
catch (err) {
//console.log(err);
//dialog.showErrorBox('Ошибка', "Подробнее: "+JSON.stringify(err));
}
}
/*function switchSpinner(state) {
if (state) {
// prevent memory leaking
if (win_loading) {
win_loading.destroy();
}
win_loading = new BrowserWindow({
//modal: !isMac,
frame : false,
movable: false,
focusable: false,
icon:icon,
minWidth: 512, // temporary restrict min window width by 512px,
title: app.getName() + " - " + store.get('server_url') + " - Загрузка...",
resizable:false,
parent: win,
opacity: 0.6, // return in case of not using electron-acrylic-window
//vibrancy: 'fullscreen-ui', // on MacOS
//backgroundMaterial: 'acrylic', // on Windows 11
transparent: true, // on linux, also see css
show: false
})
win_loading.loadFile('loading.html');
// TODO change y position for linux
//win_loading.setEnabled(false);
//win_loading.setOpacity(0.8)
//win.hide();
//if (!store.get('start_hidden')) {
if (isLinux) {
if ((!initialized)) {
// linux first run +29px fix (check non-KDE...)
win_loading.setBounds({x: store.get('bounds').x, y: store.get('bounds').y, width: store.get('bounds').width, height:store.get('bounds').height + 29} );
} else {
win_loading.setBounds({x: store.get('bounds').x, y: store.get('bounds').y - 29, width: store.get('bounds').width, height:store.get('bounds').height + 29} );
}
} else {
win_loading.setBounds(store.get('bounds'));
}
if (win.isVisible()) {
if (isLinux) {
win.setResizable(false)
}
win_loading.show();
}
} else {
win_loading.hide();
if (win.isVisible()) {
win.setResizable(true)
win.focus();
}
}
// show devtools
//win_loading.webContents.openDevTools()
}*/
function openSettings() {
if (!(settings_opened)) {
let win_settings = new BrowserWindow({
modal: !isMac,
icon:icon,
title:i18n.__('preferences'),
width: 500,
height: 400,
resizable:false,
parent: win
})
win_settings.loadFile('settings.html');
win_settings.setMenu(null);
// override fonts to Arial to fix any app startup errors
win_settings.webContents.on('did-finish-load', () => {
win_settings.webContents.insertCSS(`
* {
font-family: 'Arial', sans-serif !important;
}
`);
});
// save app name title
win_settings.on('page-title-updated', function(e) {
e.preventDefault()
});
win_settings.once('ready-to-show', () => {
if (isMac) {
win.show();
app.dock.show();
}
localizeSettings(win_settings);
win_settings.show();
settings_opened = true;
getSettings(win_settings);
win_settings.webContents.on('console-message', (event, level, message, line, sourceId) => {
setSettings(message,win_settings);
});
});
win_settings.on('closed', function(e) {
settings_opened = false;
});
//win_settings.webContents.openDevTools()
}
}
function openPopup(url) {
// check for cloud profile link
let allow_navi = false;
if (url.includes('/settings/user')) {
title = i18n.__("user_settings") + " - " + store.get('server_url');
allow_navi = true;
} else if (url.includes('/u/')) {
allow_navi = true;
title = i18n.__("profile") + " - " + store.get('server_url')
} else {
title = i18n.__("help") + " - " + store.get('server_url')
}
let win_popup = new BrowserWindow({
modal: !isMac,
icon:icon,
title:title,
parent: win
})
var theUrl = url;
win_popup.loadURL(theUrl);
win_popup.setMenu(null);
// override fonts to Arial to fix any app startup errors
win_popup.webContents.on('did-finish-load', () => {
win_popup.webContents.insertCSS(`
* {
font-family: 'Arial', sans-serif !important;
}
`);
});
//block_gui_loading(false);
// save app name title
win_popup.on('page-title-updated', function(e) {
e.preventDefault()
});
// add app styling override for cloud
win_popup.on('ready-to-show', () => {
win_popup.show();
if (url.includes('/u/')) {
win_popup.webContents.insertCSS('#app-content div.admin.access__section, #app-content div.shared.access__section, #app-content .social-button, #header, #app-content-vue div.profile__sidebar a.user-actions__primary {display:none!important;}');
win_popup.webContents.insertCSS('.profile__header__container {justify-items:end}');
} else {
win_popup.webContents.insertCSS('#app-content div.admin.access__section, #app-content div.shared.access__section, #app-content .social-button, #header, div.profile__wrapper div.profile__sidebar div.user-actions,#app-content-vue a[href*="/settings/user"] {display:none!important;}');
}
win_popup.webContents.insertCSS('#content-vue { margin-top: 0px!important; height: 100% !important;}');
})
win_popup.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
})
// prevent navigation away from help pages
win_popup.webContents.on('will-navigate', (event,redirectUrl) => {
if (!(allow_navi)) {
// check for nextcloud help urls
if (!(redirectUrl.includes('docs.nextcloud.com'))) {
event.preventDefault();
}
}
});
//win_popup.webContents.openDevTools()
}
// function to create badge img buffer 16x16
async function createBadge (unread,purpose) {
//unread = 13
// commented for telegram style non-notificationable unread messages
/*if (purpose == "tray") {
var badge_color = "grey"
var text_color = "wheat"
}*/
if ((purpose == "taskbar")||(purpose == "tray")) {
if (isMac) {
if (theme == 'dark') {
var badge_color = "white"
var text_color = "black"
} else {
var badge_color = "black"
var text_color = "white"
}
} else {
var badge_color = "red"
var text_color = "white"
}
var font_size = "65"
}
if (unread >= 100) {
unread = '∞'
font_size = "90"
}
// colored text
let font_family = !isLinux ? "system-ui, -apple-system, 'Segoe UI', Roboto, Oxygen-Sans, Cantarell, Ubuntu, 'Helvetica Neue', 'Noto Sans', 'Liberation Sans', Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'" : "Noto Sans"
var SVGtext = `<text style="fill: `+text_color+`; stroke: `+text_color+`; /*stroke-width:3*/" font-family="`+font_family+`" font-size="`+font_size+`" text-anchor="middle" x="40" y="65" >`+unread+`</text>`
// transparent text
//var SVGtext = `<mask id="clip"><rect width="100%" height="100%" fill="`+text_color+`"/><text font-size="`+font_size+`" font-weight="bold" text-anchor="middle" x="40" y="65">`+unread+`</text></mask>`
// for colored text
var badge = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="82" height="82"><circle cx="41" cy="41" r="40.5" fill="`+badge_color+`" />`+SVGtext+`</svg>`;
// for transparent text
//var badge = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="82" height="82"><circle cx="41" cy="41" r="40.5" fill="`+text_color+`" /><circle mask="url(#clip)" stroke-width="2" style="stroke:`+badge_color+`;" cx="41" cy="41" r="40.5" fill="`+badge_color+`" />`+SVGtext+`</svg>`
//var badge = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="82" height="82"><circle mask="url(#clip)" stroke-width="2" style="stroke:`+text_color+`;" cx="41" cy="41" r="40.5" fill="`+badge_color+`" />`+SVGtext+`</svg>`
convertIcon(badge,unread,purpose)
}
// convert icon to B&W
async function bw_icon_process(icon) {
if (theme == 'dark') {
var linear = 3 // for white color
} else {
var linear = 0 // for black color
}
var newImage = await sharp(icon.toPNG()).greyscale().linear(linear, 0).png({colors:2}).toBuffer();
return nativeImage.createFromBuffer(newImage);
}
async function convertIcon (badge,unread,purpose) {
if (purpose == "tray") {
//let newImage = await sharp(Buffer.from(badge)).toBuffer();
// process icon for macos to black and white colors
if (isMac) {
icon = await bw_icon_process(icon)
}
// var newImage = await sharp(Buffer.from(badge)).toBuffer();
var newImage = await sharp(icon.toPNG()).toBuffer();
newImage = await sharp(newImage).resize(120, 120).toBuffer();
newImage = await sharp(newImage).composite([{ input: Buffer.from(badge), top: 45, left: 45, blend: 'over'}]).toBuffer();
trayIcon = nativeImage.createFromBuffer(newImage);
// set linux taskbar image same as tray
if (isLinux) {
win.setIcon(trayIcon)
}
if (isMac) {
trayIcon = trayIcon.resize({width:16});
}
appIcon.setImage(trayIcon);
// apply theme to the tray icon - don't apply
//trayIcon.setTemplateImage(true);
// tray icon title
appIcon.setToolTip(app.getName() + " v."+app.getVersion() + " - " + store.get('server_url') + " - " + i18n.__("unread_messages") + ": " + unread);
win.setTitle(app.getName() + " v."+app.getVersion() + " - " + store.get('server_url') + " - " + i18n.__("unread_messages") + ": " + unread)
return;
}
if (purpose == "taskbar") {
// windows the icon to display on the bottom right corner of the taskbar icon
let newImage = await sharp(Buffer.from(badge)).toBuffer();
win.setOverlayIcon(nativeImage.createFromBuffer(newImage), i18n.__('unread_messages') + ": " + unread);
return;
}
}
/*function addNotificationToTray () {
console.log("Found unread notification!");
let trayIcon = icon_notification.resize({width:16});
// apply theme to the tray icon
trayIcon.setTemplateImage(true);
// set mac dock icon
if (isMac) {
//app.dock.setIcon(icon_notification);
app.dock.setBadge(' ');
}
appIcon.setImage(trayIcon);
is_notification = true;
if (store.get('show_on_notify')) {
win.show();
if (isMac) app.dock.show();
}
win.flashFrame(true);
win.setOverlayIcon(icon_notification, 'Есть непрочитанные уведомления');
appIcon.setToolTip(app.getName()+" - Есть непрочитанные уведомления");
}*/
async function UnreadTray (unread,removed) {
//console.log("Found " + unread +" messages!");
// create icon with unread counter
if (unread === 0) {
// apply theme to the tray icon - don't apply
//trayIcon.setTemplateImage(true);
// set mac dock icon
if (isMac) {
//app.dock.setIcon(icon);
addBadgeMac();
icon_bw = await bw_icon_process(icon);
trayIcon = icon_bw.resize({width:16});
} else {
trayIcon = icon/*.resize({width:16});*/
}
appIcon.setImage(trayIcon);
//is_notification = false;
win.flashFrame(false);
win.setOverlayIcon(null, '');
// tray icon badge
appIcon.setToolTip(app.getName() + " v."+app.getVersion() + " - " + store.get('server_url'));
} else {
createBadge(unread,"tray");
//let trayIcon = icon_notification.resize({width:16});
createBadge(unread,"taskbar");
// set mac dock icon
if (isMac) {
//app.dock.setIcon(icon_notification);
addBadgeMac();
}
//is_notification = true;
if (store.get('show_on_new_message')) {
if (unread_prev != unread) {
// check if win is in not hidden
if (!win.isVisible()) {
win.show();
if (isMac) app.dock.show();
}
}
}
if ((!removed)&&(!win.isFocused())) {
if (unread_prev != unread) {
win.flashFrame(true);
}
}
}