-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
987 lines (840 loc) · 31.3 KB
/
index.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
const { app, BrowserWindow, Tray, Menu, MenuItem } = require('electron');
const electronShell = require('electron').shell;
const toasted = require('toasted-notifier');
const process = require('process');
const path = require('path');
const moment = require('moment');
const Store = require('./store.js');
/*
Declare > Prompt
@docs : https://araxeus.github.io/custom-electron-prompt/
*/
const prompt = require('custom-electron-prompt');
/*
Debug > Print args
*/
console.log(process.argv);
/*
Declare > Package
*/
const packageJson = require('./package.json');
const appVer = packageJson.version;
const appName = packageJson.name;
const appAuthor = packageJson.author;
const appElectron = process.versions.electron;
const appRepo = packageJson.repository;
const appIcon = app.getAppPath() + '/assets/icons/ntfy.png';
/*
Declare > Window
*/
let winMain, winAbout, timerPollrate, tray;
/*
Declare > CLI State
bWinHidden --hidden app closes to tray on start
bDevTools --dev dev tools added to menu
bHotkeysEnabled --hotkeys keyboard shortcuts added to menu
bQuitOnClose --quit when pressing top-right close button, app exits instead of going to tray
*/
let bDevTools = 0;
let bHotkeysEnabled = 0;
let bQuitOnClose = 0;
let bStartHidden = 0;
let bWinHidden = 0;
/*
Declare > Status
*/
let statusHasError = false;
let statusBadURL = false;
let statusMessage;
/*
Declare > Fallback
fallback values in case a user does something unforseen to cause an index error
*/
const _Instance = 'https://ntfy.sh/app';
const _Datetime = 'YYYY-MM-DD hh:mm a';
const _Pollrate = 5;
/*
Declare > Store Values
@note : defaults will not be set until the first time a user edits any of their settings.
storage: AppData\Roaming\ntfy-desktop
*/
const store = new Store({
configName: 'prefs',
defaults: {
instanceURL: _Instance,
apiToken: '',
topics: 'topic1,topic2,topic3',
bHotkeys: 0,
bDevTools: 0,
bQuitOnClose: 0,
bStartHidden: 0,
bPersistentNoti: 0,
datetime: _Datetime
}
});
/*
Validate instance url
*/
function validateUrl(uri, tries, delay) {
return new Promise((success, reject) => {
(function rec(i) {
fetch(uri, {mode: 'no-cors'}).then((r) => {
success(r); // success: resolve promise
}).catch( err => {
if (tries === 0) // num of tries reached
return reject(err);
setTimeout(() => rec(--tries), delay ) // retry
}); // retries exceeded
})(tries);
});
}
/*
Get Message Data
Even though ntfy's permissions are open by default, provide authorization bearer for users who
have their permissions set to 'deny'.
API Token can be specified in app.
*/
async function GetMessageData(uri) {
const cfgApiToken = store.get('apiToken');
let req = await fetch(uri, {
method: 'GET',
headers: {
'Accept': 'application/json',
Authorization: `Bearer ${cfgApiToken}`
}
});
/*
ntfy has the option to output message results as json, however the structure of that json
is not properly formatted json and adds a newline to the end of each message.
bring the json results in as a string, split them at newline and then push them to a new
array.
*/
const json = await req.text();
let jsonArr = [];
const entries = json.split('\n');
for (let i = 0; i < entries.length; i++) {
jsonArr.push(entries[i]);
}
/*
Filter out empty entry in array which was caused by the last newline
*/
const jsonResult = jsonArr.filter(function (el) {
return el != null && el != '';
});
return jsonResult;
}
/*
Get Messages
ntfy url requires '&poll=1' otherwise the requests will freeze.
@ref : https://docs.ntfy.sh/subscribe/api/#poll-for-messages
*/
const msgHistory = [];
async function GetMessages() {
const cfgPollrate = store.get('pollrate') || _Pollrate;
const cfgTopics = store.get('topics');
const cfgInstanceURL = store.get('instanceURL');
if (cfgInstanceURL === '' || cfgInstanceURL === null) {
console.log(`URL Missing, skipping GetMessages(): ${uri}`);
return;
}
let uri = `${cfgInstanceURL}/${cfgTopics}/json?since=${cfgPollrate}s&poll=1`;
console.log(`URL: ${uri}`);
/*
For the official ntfy.sh API, url must be changed internally
https://ntfy.sh/app/ -> https://ntfy.sh/
*/
if (uri.includes('ntfy.sh/app')) {
uri = uri.replace("ntfy.sh/app", 'ntfy.sh');
}
/*
Bad URL detected, skip polling
*/
if ( statusBadURL == true ) {
console.error(`Invalid instance URL specified, skipping polling`);
return;
}
const json = await GetMessageData(uri);
console.log(`CHECKING FOR NEW MESSAGES`);
console.log(`---------------------------------------------------------`);
console.log(`InstanceURL ........... ${cfgInstanceURL}`);
console.log(`Query ................. ${uri}`);
console.log(`Topics ................ ${cfgTopics}`);
/*
Loop ntfy api results.
only items with event = 'message' will be allowed through to display in a notification.
*/
console.log(`---------------------------------------------------------`);
console.log(`History ............... ${msgHistory}`);
console.log(`Messages .............. ${JSON.stringify(json)}`);
console.log(`---------------------------------------------------------\n`);
for (let i = 0; i < json.length; i++) {
const object = JSON.parse(json[i]);
const id = object.id;
const type = object.event;
const time = object.time;
const expires = object.expires;
const message = object.message;
const topic = object.topic;
const cfgPersistent = store.get('bPersistentNoti') == 0 ? false : true;
const cfgInstanceURL = store.get('instanceURL');
if (type != 'message')
continue;
/*
convert unix timestamp into human readable
*/
const dateHuman = moment.unix(time).format(store.get('datetime' || _Datetime));
/*
debugging to console to show the status of messages
*/
const msgStatus = msgHistory.includes(id) === true ? 'already sent, skipping' : 'pending send';
console.log(`Messages .............. ${type}:${id} ${msgStatus}`);
/*
@ref : https://github.com/Aetherinox/toasted-notifier
*/
if (!msgHistory.includes(id)) {
toasted.notify({
title: `${topic} - ${dateHuman}`,
subtitle: `${dateHuman}`,
message: `${message}`,
sound: 'Pop',
open: cfgInstanceURL,
persistent: cfgPersistent,
sticky: cfgPersistent
});
msgHistory.push(id);
console.log(` Topic .............. ${type}:${id} ${topic}`);
console.log(` Date ............... ${type}:${id} ${dateHuman}`);
console.log(` InstanceURL ........ ${type}:${id} ${cfgInstanceURL}`);
console.log(` Persistent ......... ${type}:${id} ${cfgPersistent}`);
}
console.log(`Messages .............. ${type}:${id} sent`);
}
console.log(`\n\n`);
return json;
}
/*
Menu > Main
Entries for the top interface menu
App | Configure | Help
*/
const menu_Main = [
{
label: '&App',
id: 'app',
submenu: [
{
label: 'Quit',
id: 'quit',
accelerator: (bHotkeysEnabled == 1 || store.get('bHotkeys') == 1) ? 'CTRL+Q' : '',
click: function () {
app.isQuiting = true;
app.quit();
}
}
]
},
{
label: '&Configure',
id: 'configure',
submenu: [
{
label: 'General',
id: 'general',
accelerator: (bHotkeysEnabled == 1 || store.get('bHotkeys') == 1) ? 'CTRL+G' : '',
click: function () {
prompt(
{
title: 'General Settings',
label: 'General Settings<div class="label-desc">Change the overall functionality of the app.</div>',
useHtmlLabel: true,
alwaysOnTop: true,
type: 'multiInput',
resizable: false,
customStylesheet: path.join(__dirname, `pages`, `css`, `prompt.css`),
height: 480,
icon: appIcon,
multiInputOptions:
[
{
label: 'Developer tools in app menu',
selectOptions: { 0: 'Disabled', 1: 'Enabled' },
value: store.get('bDevTools'),
},
{
label: 'Allow usage of hotkeys to navigate',
selectOptions: { 0: 'Disabled', 1: 'Enabled' },
value: store.get('bHotkeys'),
},
{
label: 'Quit app instead of send-to-tray for close button',
selectOptions: { 0: 'Disabled', 1: 'Enabled' },
value: store.get('bQuitOnClose'),
},
{
label: 'Start app minimized in tray',
selectOptions: { 0: 'Disabled', 1: 'Enabled' },
value: store.get('bStartHidden'),
}
],
},
winMain
)
.then((response) => {
if (response !== null) {
// do not update dev tools if value hasn't changed
if ( store.get('bDevTools') !== response[0])
{
store.set('bDevTools', response[0]);
activeDevTools();
}
store.set('bHotkeys', response[1]);
store.set('bQuitOnClose', response[2]);
store.set('bStartHidden', response[3]);
}
})
.catch((response) => {
console.error
})
/*
setTimeout(function (){
BrowserWindow.getFocusedWindow().webContents.openDevTools();
}, 3000);
*/
}
},
{
label: 'URL',
accelerator: (bHotkeysEnabled == 1 || store.get('bHotkeys') == 1) ? 'CTRL+U' : '',
click: function () {
prompt(
{
title: 'Set Server Instance',
label: 'Server URL<div class="label-desc">This can either be the URL to the official ntfy.sh server, or your own self-hosted domain / ip.<br><br>Remove everything to set back to official ntfy.sh server.</div>',
useHtmlLabel: true,
value: store.get('instanceURL') || _Instance,
alwaysOnTop: true,
type: 'input',
customStylesheet: path.join(__dirname, `pages`, `css`, `prompt.css`),
height: 290,
icon: appIcon,
inputAttrs: {
type: 'url'
}
},
winMain
)
.then((response) => {
if (response !== null) {
const newUrl = (response === "" ? _Instance : response);
store.set('instanceURL', newUrl);
/*
Validate URL.
Invalid URLs should not perform polling.
load default _Instance url
*/
validateUrl(store.get('instanceURL'), 3, 1000).then( item => {
statusBadURL = false;
console.log(`Successfully resolved `+ store.get('instanceURL'));
winMain.loadURL(store.get('instanceURL'));
}).catch( err => {
statusBadURL = true;
const msg = `Failed to resolve `+ store.get('instanceURL') + ` - defaulting to ${_Instance}`;
statusMessage = `${msg}`;
console.error(`${msg}`);
store.set('instanceURL', _Instance);
winMain.loadURL(_Instance);
});
}
})
.catch((response) => {
console.error
})
/*
setTimeout(function (){
BrowserWindow.getFocusedWindow().webContents.openDevTools();
}, 3000);
*/
}
},
{
label: 'API Token',
accelerator: (bHotkeysEnabled == 1 || store.get('bHotkeys') == 1) ? 'CTRL+T' : '',
click: function () {
prompt(
{
title: 'Set API Token',
label: 'API Token<div class="label-desc">Generate an API token within ntfy.sh or your self-hosted instance and provide it below to receive desktop push notifications.</div>',
useHtmlLabel: true,
value: store.get('apiToken'),
alwaysOnTop: true,
type: 'input',
customStylesheet: path.join(__dirname, `pages`, `css`, `prompt.css`),
height: 265,
icon: appIcon,
inputAttrs: {
type: 'text'
}
},
winMain
)
.then((response) => {
if (response !== null) {
store.set('apiToken', response);
}
})
.catch((response) => {
console.error
})
}
},
{
label: 'Topics',
accelerator: (bHotkeysEnabled == 1 || store.get('bHotkeys') == 1) ? 'CTRL+SHIFT+T' : '',
click: function () {
prompt(
{
title: 'Set Subscribed Topics',
label: 'Subscribed Topics<div class="label-desc">Specify a list of topics you would like to receive push notifications for, separated by commas.<br><br>Ex: Meetings,Personal,Urgent</div>',
useHtmlLabel: true,
value: store.get('topics'),
alwaysOnTop: true,
type: 'input',
customStylesheet: path.join(__dirname, `pages`, `css`, `prompt.css`),
height: 290,
icon: appIcon,
inputAttrs: {
type: 'text'
}
},
winMain
)
.then((response) => {
if (response !== null) {
// do not update topics unless values differ from original, since we need to reload the page
if ( store.get('topics') !== response)
{
store.set('topics', response);
if (typeof (store.get('instanceURL')) !== 'string' || store.get('instanceURL') === '' || store.get('instanceURL') === null ) {
store.set('instanceURL', _Instance);
}
winMain.loadURL(store.get('instanceURL'));
}
}
})
.catch((response) => {
console.error
})
}
},
{
label: 'Notifications',
accelerator: (bHotkeysEnabled == 1 || store.get('bHotkeys') == 1) ? 'CTRL+N' : '',
click: function () {
prompt(
{
title: 'Notifications',
label: 'Notification Settings<div class="label-desc">Determines how notifications will behave</div>',
useHtmlLabel: true,
alwaysOnTop: true,
type: 'multiInput',
resizable: false,
customStylesheet: path.join(__dirname, `pages`, `css`, `prompt.css`),
height: 400,
icon: appIcon,
multiInputOptions:
[
{
label: 'Stay on screen until dismissed',
selectOptions: { 0: 'Disabled', 1: 'Enabled' },
value: store.get('bPersistentNoti'),
},
{
label: 'Datetime format for notification title',
value: store.get('datetime') || _Datetime,
inputAttrs:
{
placeholder: `${_Datetime}`,
required: true
}
},
{
label: 'Polling rate / fetch messages (seconds)',
value: store.get('pollrate') || _Pollrate,
inputAttrs: {
type: 'number',
required: true,
min: 5,
step: 1
}
}
]
},
winMain
)
.then((response) => {
if (response !== null) {
store.set('bPersistentNoti', response[0])
store.set('datetime', response[1])
store.set('pollrate', response[2])
const cfgPollrate = (store.get('pollrate') || _Pollrate);
const fetchInterval = (cfgPollrate * 1000) + 600;
clearInterval(timerPollrate);
timerPollrate = setInterval(GetMessages, fetchInterval);
}
})
.catch((response) => {
console.error
})
/*
setTimeout(function (){
BrowserWindow.getFocusedWindow().webContents.openDevTools();
}, 3000);
*/
}
}
]
},
{
label: '&Help',
id: 'help',
submenu: [
{
id: 'about',
label: 'About',
click() {
const aboutTitle = `About`;
winAbout = new BrowserWindow({
width: 480,
height: 440,
title: `${aboutTitle}`,
icon: appIcon,
parent: winMain,
center: true,
resizable: false,
fullscreenable: false,
minimizable: false,
maximizable: false,
modal: true,
backgroundColor: '#212121',
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true
}
});
winAbout.loadFile(path.join(__dirname, `pages`, `about.html`)).then(() => {
winAbout.webContents
.executeJavaScript(
`
setTitle('${aboutTitle}');
setAppInfo('${appRepo}', '${appName}', '${appVer}', '${appAuthor}', '${appElectron}');`,
true
)
.then((result) => {})
.catch(console.error);
});
winAbout.webContents.on('new-window', function (e, url) {
e.preventDefault();
require('electron').shell.openExternal(url);
});
// Remove menubar from about window
winAbout.setMenu(null);
}
},
{
label: 'View New Releases',
click() {
electronShell.openExternal(`${packageJson.homepage}`);
}
}
]
}];
/*
Tray > Context Menu
*/
const contextMenu = Menu.buildFromTemplate([
{
label: 'Show App',
click: function () {
winMain.show();
}
},
{
label: 'Quit',
click: function () {
app.isQuiting = true;
app.quit();
}
}
]);
/*
Main Menu > Set
*/
const header_menu = Menu.buildFromTemplate(menu_Main);
Menu.setApplicationMenu(header_menu);
/*
Main Menu > Developer Tools
slides in top position of 'App' menu
when user disables dev console, must re-build menu, otherwise dev tools will stick
App | Configure | Help
*/
function activeDevTools() {
const header_menu = Menu.buildFromTemplate(menu_Main);
Menu.setApplicationMenu(header_menu);
if (bDevTools == 1 || store.get('bDevTools') == 1) {
let menuItem = header_menu.getMenuItemById('app')
menuItem.submenu.insert(0, new MenuItem(
{
label: 'Toggle Dev Tools',
accelerator: process.platform === 'darwin' ? 'ALT+CMD+I' : 'CTRL+SHIFT+I',
click: () => {
winMain.webContents.toggleDevTools();
}
},
{
type: 'separator'
}))
}
}
/*
App > Ready
*/
function ready() {
/*
New Window
*/
winMain = new BrowserWindow({
title: `${appName}`,
width: 1280,
height: 720,
icon: appIcon,
backgroundColor: '#212121'
});
/*
Load default url to main window
since the user has settings they can modify; add check to instanceUrl and ensure it is a valid string.
otherwise app will return invalid index and stop loading.
*/
if (typeof (store.get('instanceURL')) !== 'string' || store.get('instanceURL') === '' || store.get('instanceURL') === null ) {
store.set('instanceURL', _Instance);
statusHasError = true;
statusMessage = `Invalid instance URL specified; defaulting to ${_Instance}`;
}
/*
Validate URL.
Invalid URLs should not perform polling.
load default _Instance url
*/
validateUrl(store.get('instanceURL'), 3, 1000).then( item => {
statusBadURL = false;
console.log(`Successfully resolved `+ store.get('instanceURL'));
winMain.loadURL(store.get('instanceURL'));
}).catch( err => {
statusBadURL = true;
const msg = `Failed to resolve `+ store.get('instanceURL') + ` - defaulting to ${_Instance}`;
statusMessage = `${msg}`;
console.error(`${msg}`);
store.set('instanceURL', _Instance);
winMain.loadURL(_Instance);
});
/*
Event > Page Title Update
*/
winMain.on('page-title-updated', (e) => {
e.preventDefault();
});
/*
Event > Close
if --quit cli argument specified, app will completely quit when close pressed.
otherwise; app will hide
*/
winMain.on('close', function (e) {
if (!app.isQuiting) {
e.preventDefault();
if (bQuitOnClose == 1 || store.get('bQuitOnClose') == 1) {
app.isQuiting = true;
app.quit();
} else {
winMain.hide();
}
}
return false;
});
/*
Event > Closed
*/
winMain.on('closed', () => {
winMain = null;
});
/*
Event > New Window
buttons leading to external websites should open in user browser
*/
winMain.webContents.on('new-window', (e, url) => {
e.preventDefault();
require('electron').shell.openExternal(url);
});
/*
Display footer div on website if something has gone wrong.
user shouldn't see this unless its something serious
*/
winMain.webContents.on('did-finish-load', (e, url)=> {
if ((statusHasError === true || statusBadURL == true) && statusMessage !== '') {
winMain.webContents
.executeJavaScript(
`
const div = document.createElement("div");
div.style.position = "sticky";
div.style.height = "34px";
div.style.width = "100%";
div.style.zIndex = "3000";
div.style.overflow = "hidden";
div.style.marginTop = "-34px";
div.style.padding = "7px";
div.style.paddingLeft = "20px";
div.style.paddingRight = "20px";
div.style.backgroundColor = "rgb(151 63 63)";
div.style.textAlign = "center";
div.style.fontSize = "13px";
const span = document.createElement("span");
span.setAttribute("class","ntfy-notify error");
span.textContent = '${statusMessage}';
div.appendChild(span);
document.body.appendChild(div);
`)
}
}
);
/*
Event > Input
*/
winMain.webContents.on('before-input-event', (e, input) => {
/*
Input > Refresh Page (CTRL + r)
*/
if ((bHotkeysEnabled == 1 || store.get('bHotkeys') == 1) && input.type === 'keyDown' && input.control && input.key === 'r') {
winMain.webContents.reload();
}
/*
Input > Zoom In (CTRL + =)
*/
if ((bHotkeysEnabled == 1 || store.get('bHotkeys') == 1) && input.type === 'keyDown' && input.control && input.key === '=') {
winMain.webContents.zoomFactor += 0.1;
}
/*
Input > Zoom Out (CTRL + -)
*/
if ((bHotkeysEnabled == 1 || store.get('bHotkeys') == 1) && input.type === 'keyDown' && input.control && input.key === '-') {
winMain.webContents.zoomFactor -= 0.1;
}
/*
Input > Zoom Reset (CTRL + 0)
*/
if ((bHotkeysEnabled == 1 || store.get('bHotkeys') == 1) && input.type === 'keyDown' && input.control && input.key === '0') {
winMain.webContents.zoomFactor = 1;
}
/*
Input > Quit (CTRL + q)
*/
if ((bHotkeysEnabled == 1 || store.get('bHotkeys') == 1) && input.type === 'keyDown' && input.control && input.key === 'q') {
app.isQuiting = true;
app.quit();
}
/*
Input > Minimize to tray (CTRL + m)
*/
if ((bHotkeysEnabled == 1 || store.get('bHotkeys') == 1) && input.type === 'keyDown' && input.control && input.key === 'm') {
bWinHidden = 1;
winMain.hide();
}
/*
Input > Dev Tools (CTRL + SHIFT + I || F12)
*/
if (((bHotkeysEnabled == 1 || store.get('bHotkeys') == 1) && input.control && input.shift) || input.key === 'F12') {
if (input.type === 'keyDown' && (input.key === 'I' || input.key === 'F12')) {
winMain.webContents.toggleDevTools();
winMain.webContents.on('devtools-opened', () => {
winMain.webContents.devToolsWebContents
.executeJavaScript(
`
new Promise((resolve)=> {
let keysPressed = {};
addEventListener('keydown', (e) => {
if (e.key === 'F12') {
resolve();
}
}, { once: true });
addEventListener('keydown', (e) => {
keysPressed[e.key] = true;
if (keysPressed['Control'] && keysPressed['Shift'] && e.key == 'I') {
resolve();
}
});
addEventListener('keyup', (e) => {
delete keysPressed[e.key];
});
})
`
)
.then(() => {
winMain.webContents.toggleDevTools();
});
});
}
}
});
/*
Tray
Windows : left-click opens app, right-click opens context menu
Linux : left and right click have same functionality
*/
tray = new Tray(appIcon);
tray.setToolTip(`${appName}`);
tray.setContextMenu(contextMenu);
tray.on('click', function () {
if (bWinHidden) {
bWinHidden = 0;
winMain.show();
} else {
bWinHidden = 1;
winMain.hide();
}
});
/*
Loop args
--hidden : automatically hide window
--dev : enable developer tools
--quit : quit app when close button pressed
*/
for (let i = 0; i < process.argv.length; i++) {
if (process.argv[i] === '--hidden') {
bWinHidden = 1;
} else if (process.argv[i] === '--dev') {
bDevTools = 1;
activeDevTools()
} else if (process.argv[i] === '--quit') {
bQuitOnClose = 1;
} else if (process.argv[i] === '--hotkeys') {
bHotkeysEnabled = 1;
}
}
/*
Run timer every X seconds to check for new messages
*/
const fetchInterval = ((store.get('pollrate') || _Pollrate) * 1000) + 600;
timerPollrate = setInterval(GetMessages, fetchInterval);
/*
Check stored setting for developer tools and set state when
app launches
*/
activeDevTools()
/*
Start minimized in tray
*/
if( store.get('bStartHidden') == 1 || bWinHidden == 1)
winMain.hide();
}
/*
App > Ready
*/
app.on('ready', ready);