-
Notifications
You must be signed in to change notification settings - Fork 594
/
Copy pathdesktop-ipc.ts
1388 lines (1165 loc) · 37.7 KB
/
desktop-ipc.ts
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
import { IActivityWatchEventResult } from '@gauzy/contracts';
import { ScreenCaptureNotification, WindowManager, loginPage } from '@gauzy/desktop-window';
import { BrowserWindow, app, desktopCapturer, ipcMain, screen, systemPreferences } from 'electron';
import log from 'electron-log';
import { resetPermissions } from 'mac-screen-capture-permissions';
import moment from 'moment';
import * as _ from 'underscore';
import { SleepInactivityTracking } from './contexts';
import {
DialogStopTimerLogoutConfirmation,
PowerManagerDetectInactivity,
PowerManagerPreventDisplaySleep
} from './decorators';
import { DesktopDialog } from './desktop-dialog';
import NotificationDesktop from './desktop-notifier';
import { DesktopOsInactivityHandler } from './desktop-os-inactivity-handler';
import { DesktopPowerManager } from './desktop-power-manager';
import { notifyScreenshot, takeshot } from './desktop-screenshot';
import { LocalStore } from './desktop-store';
import TimerHandler from './desktop-timer';
import { UIError } from './error-handler';
import {
ActivityWatchAfkService,
ActivityWatchEventAdapter,
ActivityWatchEventManager,
ActivityWatchEventTableList
} from './integrations';
import { IDesktopEvent, IPowerManager } from './interfaces';
import {
DesktopOfflineModeHandler,
Interval,
IntervalService,
IntervalTO,
Timer,
TimerService,
TimerTO,
UserService
} from './offline';
import { pluginListeners } from './plugin-system';
import { RemoteSleepTracking } from './strategies';
import { TranslateService } from './translation';
const timerHandler = new TimerHandler();
console.log = log.log;
Object.assign(console, log.functions);
const offlineMode = DesktopOfflineModeHandler.instance;
const userService = new UserService();
const intervalService = new IntervalService();
const timerService = new TimerService();
const windowManager = WindowManager.getInstance();
export function ipcMainHandler(store, startServer, knex, config, timeTrackerWindow) {
log.info('IPC Main Handler');
ipcMain.removeAllListeners('return_time_sheet');
ipcMain.removeAllListeners('return_toggle_api');
ipcMain.removeAllListeners('set_project_task');
removeAllHandlers();
log.info('Removed All Listeners');
ipcMain.handle('START_SERVER', async (event, arg) => {
log.info('Handle Start Server');
try {
const baseUrl = arg.serverUrl
? arg.serverUrl
: arg.port
? `http://localhost:${arg.port}`
: `http://localhost:${config.API_DEFAULT_PORT}`;
global.variableGlobal = {
API_BASE_URL: baseUrl,
IS_INTEGRATED_DESKTOP: arg.isLocalServer
};
return await startServer(arg);
} catch (error) {
log.error(error);
return null;
}
});
ipcMain.on('return_time_sheet', async (event, arg) => {
try {
log.info('Return Time Sheet');
await timerHandler.processWithQueue(
`gauzy-queue`,
{
type: 'update-timer-time-slot',
data: {
id: arg.timerId,
timeSheetId: arg.timeSheetId,
timeLogId: arg.timeLogId
}
},
knex
);
} catch (error) {
log.error('Error on return time sheet', error);
throw new UIError('400', error, 'IPCQSHEET');
}
});
ipcMain.on('return_toggle_api', async (event, arg) => {
try {
log.info('Return Toggle API');
await timerHandler.processWithQueue(
`gauzy-queue`,
{
type: 'update-timer-time-slot',
data: {
id: arg.timerId,
timeLogId: arg.result.id
}
},
knex
);
} catch (error) {
log.info('Error on return toggle api', error);
throw new UIError('400', error, 'IPCQSLOT');
}
});
ipcMain.on('failed_synced_timeslot', async (event, arg) => {
try {
log.info('Failed Synced TimeSlot');
const interval = new Interval(arg.params);
interval.screenshots = arg.params.b64Imgs;
interval.stoppedAt = new Date();
interval.synced = false;
interval.timerId = timerHandler.lastTimer?.id;
await intervalService.create(interval.toObject());
await countIntervalQueue(timeTrackerWindow, false);
await latestScreenshots(timeTrackerWindow);
} catch (error) {
log.info('Error on failed synced TimeSlot', error);
throw new UIError('400', error, 'IPCSAVESLOT');
}
});
ipcMain.on('set_project_task', (event, arg) => {
event.sender.send('set_project_task_reply', arg);
});
ipcMain.on('time_tracker_ready', async (event, arg) => {
log.info('Time Tracker Ready');
// Update preferred language
timeTrackerWindow.webContents.send('preferred_language_change', TranslateService.preferredLanguage);
// Check Authenticated user
await checkAuthenticatedUser(timeTrackerWindow);
try {
const lastTime = await timerService.findLastOne();
log.info('Last Capture Time (Desktop IPC):', lastTime);
await offlineMode.connectivity();
log.info('Network state', offlineMode.enabled ? 'Offline' : 'Online');
event.sender.send('timer_tracker_show', {
...LocalStore.beforeRequestParams(),
timeSlotId: lastTime ? lastTime.timeslotId : null,
isOffline: offlineMode.enabled
});
await countIntervalQueue(timeTrackerWindow, false);
await sequentialSyncQueue(timeTrackerWindow);
await latestScreenshots(timeTrackerWindow);
} catch (error) {
log.error('Error on time tracker ready', error);
throw new UIError('500', error, 'IPCINIT');
}
});
ipcMain.on('screen_shoot', async (event, arg) => {
log.info(`Taken Screenshot: ${moment().format()}`);
event.sender.send('take_screen_shoot');
});
ipcMain.on('get_last_screen_capture', (event, arg) => {
log.info(`Get Last Screenshot: ${moment().format()}`);
event.sender.send('get_last_screen');
});
ipcMain.on('update_app_setting', (event, arg) => {
log.info(`Update App Setting: ${moment().format()}`);
LocalStore.updateApplicationSetting(arg.values);
});
ipcMain.on('update_project_on', (event, arg) => {
log.info(`Update Project On: ${moment().format()}`);
LocalStore.updateConfigProject(arg);
});
ipcMain.on('request_permission', async (event) => {
log.info('Request Permission');
try {
if (process.platform === 'darwin') {
log.info('Request Permission for Darwin');
if (isScreenUnauthorized()) {
log.info('Screen is Unauthorized');
event.sender.send('stop_from_tray', {
quitApp: false
});
// Trigger macOS to ask user for screen capture permission
try {
await desktopCapturer.getSources({
types: ['screen']
});
} catch (err) {
log.error('Error on request permission', err);
// soft fail
}
}
}
} catch (error) {
log.error('Error on request permission', error);
throw new UIError('500', error, 'IPCPERM');
}
});
ipcMain.on('reset_permissions', () => {
log.info('Reset Permissions');
if (process.platform === 'darwin') {
log.info('Reset Permissions for Darwin');
if (isScreenUnauthorized()) {
log.info('Screen is Unauthorized');
const name = app.getName().split('-').join('');
resetPermissions({ bundleId: 'com.ever.' + name });
}
}
});
ipcMain.on('auth_failed', (event, arg) => {
event.sender.send('show_error_message', arg.message);
});
ipcMain.handle('DESKTOP_CAPTURER_GET_SOURCES', async (event, opts) => {
log.info('Desktop Capturer Get Sources');
return await desktopCapturer.getSources(opts);
});
ipcMain.handle('UPDATE_SYNCED_TIMER', async (event, arg) => {
log.info('Update Synced Timer');
try {
if (!arg.id) {
const lastCapture = await timerService.findLastOne();
if (lastCapture && lastCapture.id) {
const { id } = lastCapture;
arg = {
...arg,
id
};
}
}
if (arg.id) {
if (!offlineMode.enabled) {
console.log('Update Synced Timer Online');
await timerService.update(
new Timer({
id: arg.id,
synced: true,
...(arg.lastTimer && {
timelogId: arg.lastTimer?.id,
timesheetId: arg.lastTimer?.timesheetId
}),
...(arg.lastTimer?.startedAt && {
startedAt: new Date(arg.lastTimer?.startedAt)
}),
...(!arg.lastTimer && {
synced: false,
isStartedOffline: arg.isStartedOffline,
isStoppedOffline: arg.isStoppedOffline
}),
...(arg.timeSlotId && {
timeslotId: arg.timeSlotId
})
})
);
} else {
console.log('Update Synced Timer Offline');
await timerService.update(
new Timer({
id: arg.id,
...(arg.startedAt && {
startedAt: new Date(arg.startedAt)
})
})
);
}
} else {
console.log('No arg.id found');
}
console.log('Count Interval Queue');
await countIntervalQueue(timeTrackerWindow, true);
if (!isQueueThreadTimerLocked) {
console.log('sequentialSyncQueue');
await sequentialSyncQueue(timeTrackerWindow);
}
} catch (error) {
log.error('Error on update synced timer', error);
throw new UIError('400', error, 'IPCUPDATESYNCTMR');
}
});
ipcMain.handle('COLLECT_ACTIVITIES', async (event, { quitApp }) => {
try {
log.info('Collect Activities');
return await timerHandler.collectAllActivities(knex, quitApp);
} catch (error) {
log.error('Error collecting activities', error);
throw new UIError('500', error, 'HANDLE ACTIVITIES');
}
});
ipcMain.handle('UPDATE_SYNCED', async (event, arg: IntervalTO) => {
try {
log.info('Update Synced');
const interval = new Interval(arg);
interval.screenshots = [];
await intervalService.synced(interval);
await countIntervalQueue(timeTrackerWindow, true);
} catch (error) {
log.error('Error on update synced', error);
throw new UIError('400', error, 'IPCUPDATESYNCINTERVAL');
}
});
ipcMain.handle('FINISH_SYNCED_TIMER', async (event, arg) => {
try {
log.info('Finish Synced Timer');
const total = await intervalService.countNoSynced();
await countIntervalQueue(timeTrackerWindow, false);
if (total === 0) {
isQueueThreadTimerLocked = false;
log.info('...FINISH SYNC');
}
} catch (error) {
log.error('Error on finish synced timer', error);
}
});
ipcMain.handle('SAVED_THEME', () => {
return LocalStore.getStore('appSetting').theme;
});
pluginListeners();
}
function isScreenUnauthorized() {
return systemPreferences.getMediaAccessStatus('screen') !== 'granted';
}
export function ipcTimer(
store,
knex,
setupWindow,
timeTrackerWindow,
notificationWindow,
settingWindow,
imageView,
config,
createSettingsWindow,
windowPath,
soundPath,
alwaysOn
) {
let powerManager: IPowerManager;
let powerManagerPreventSleep: PowerManagerPreventDisplaySleep;
let powerManagerDetectInactivity: PowerManagerDetectInactivity;
app.whenReady().then(async () => {
if (!notificationWindow) {
try {
notificationWindow = new ScreenCaptureNotification(
!process.env.IS_DESKTOP_TIMER ? windowPath.screenshotWindow : windowPath.timeTrackerUi
);
log.info('App Name:', app.getName());
await notificationWindow.loadURL();
} catch (error) {
log.error('Error on create notification window', error);
throw new UIError('500', error, 'IPCNOTIF');
}
}
});
ipcMain.on('create-synced-interval', async (_event, arg) => {
log.info('Create Synced Interval');
try {
const interval = new Interval(arg);
interval.screenshots = arg.b64Imgs;
interval.stoppedAt = new Date();
interval.synced = true;
interval.timerId = timerHandler.lastTimer?.id;
await intervalService.create(interval.toObject());
await latestScreenshots(timeTrackerWindow);
} catch (error) {
log.error('Error on create synced interval', error);
throw new UIError('400', error, 'IPCSAVEINTER');
}
});
offlineMode.on('offline', async () => {
log.info('Offline mode triggered...');
const windows = [alwaysOn.browserWindow, timeTrackerWindow];
for (const window of windows) {
window.webContents.send('offline-handler', true);
}
});
offlineMode.on('connection-restored', async () => {
log.info('Api connected...');
try {
const windows = [alwaysOn.browserWindow, timeTrackerWindow];
for (const window of windows) {
window.webContents.send('offline-handler', false);
}
await sequentialSyncQueue(timeTrackerWindow);
} catch (error) {
log.error('Error on connection restored', error);
throw new UIError('500', error, 'IPCRESTORE');
}
});
offlineMode.trigger();
ipcMain.handle('START_TIMER', async (event, arg) => {
log.info(`Start Timer: ${moment().format()}`);
// Check Authenticated user
const isAuth = await checkAuthenticatedUser(timeTrackerWindow);
log.info(`Authenticated User: ${isAuth}`);
try {
powerManager = new DesktopPowerManager(timeTrackerWindow);
powerManagerPreventSleep = new PowerManagerPreventDisplaySleep(powerManager);
powerManagerDetectInactivity = new PowerManagerDetectInactivity(powerManager);
new DesktopOsInactivityHandler(powerManagerDetectInactivity);
const setting = LocalStore.getStore('appSetting');
log.info(`Timer Start: ${moment().format()}`);
store.set({
project: {
projectId: arg?.projectId,
taskId: arg?.taskId,
note: arg?.note,
aw: arg?.aw,
organizationContactId: arg?.organizationContactId,
organizationTeamId: arg?.organizationTeamId
}
});
// Check API connection before starting
await offlineMode.connectivity();
log.info(`API Connection: ${moment().format()}`);
// Start Timer
const timerResponse = await timerHandler.startTimer(setupWindow, knex, timeTrackerWindow, arg?.timeLog);
settingWindow.webContents.send('app_setting_update', {
setting: LocalStore.getStore('appSetting')
});
if (setting && setting.preventDisplaySleep) {
log.info('Prevent Display Sleep');
powerManagerPreventSleep.start();
}
if (arg?.isRemoteTimer) {
log.info(`SleepInactivityTracking: ${moment().format()}`);
powerManager.sleepTracking = new SleepInactivityTracking(new RemoteSleepTracking(timeTrackerWindow));
} else {
log.info(`StartInactivityDetection: ${moment().format()}`);
powerManagerDetectInactivity.startInactivityDetection();
}
return timerResponse;
} catch (error) {
log.error('Error on start timer', error);
timeTrackerWindow.webContents.send('emergency_stop');
throw new UIError('400', error, 'IPCSTARTMR');
}
});
ipcMain.handle('DELETE_TIME_SLOT', async (event, intervalId: number | string) => {
try {
log.info(`Delete Time Slot: ${moment().format()}`);
const count = await intervalService.countNoSynced();
const notify = new NotificationDesktop();
const notification = {
message: TranslateService.instant('TIMER_TRACKER.NATIVE_NOTIFICATION.SCREENSHOT_REMOVED'),
title: process.env.DESCRIPTION
};
if (typeof intervalId === 'number' && intervalId && count > 0 && offlineMode.enabled) {
await intervalService.remove(intervalId);
await countIntervalQueue(timeTrackerWindow, false);
await latestScreenshots(timeTrackerWindow);
notify.customNotification(notification.message, notification.title);
}
if (!offlineMode.enabled && typeof intervalId === 'string') {
await intervalService.removeByRemoteId(intervalId);
const lastTimer = await timerService.findLastCapture();
const lastInterval = await intervalService.findLastInterval();
if (lastTimer) {
lastTimer.timeslotId = lastInterval.remoteId;
await timerService.update(new Timer(lastTimer));
}
notify.customNotification(notification.message, notification.title);
return lastInterval.remoteId;
}
} catch (error) {
log.error('Error on delete time slot', error);
throw new UIError('400', error, 'IPCRMSLOT');
}
});
ActivityWatchEventManager.onPushWindowActivity(async (_, result: IActivityWatchEventResult) => {
const collections: IDesktopEvent[] = ActivityWatchEventAdapter.collections(result);
if (!collections.length) return;
try {
await timerHandler.processWithQueue(
`gauzy-queue`,
{
type: ActivityWatchEventTableList.WINDOW,
data: collections
},
knex
);
} catch (error) {
log.error('Error on push window activity', error);
throw new UIError('500', error, 'IPCQWIN');
}
});
ActivityWatchEventManager.onPushAfkActivity(async (_, result: IActivityWatchEventResult) => {
const collections: IDesktopEvent[] = ActivityWatchEventAdapter.collections(result);
if (!collections.length) return;
try {
await timerHandler.processWithQueue(
`gauzy-queue`,
{
type: ActivityWatchEventTableList.AFK,
data: collections
},
knex
);
} catch (error) {
log.error('Error on push afk activity', error);
throw new UIError('500', error, 'IPCQWIN');
}
});
ActivityWatchEventManager.onPushFirefoxActivity(async (_, result: IActivityWatchEventResult) => {
const collections: IDesktopEvent[] = ActivityWatchEventAdapter.collections(result);
if (!collections.length) return;
try {
await timerHandler.processWithQueue(
`gauzy-queue`,
{
type: ActivityWatchEventTableList.FIREFOX,
data: collections
},
knex
);
} catch (error) {
log.error('Error on push firefox activity', error);
throw new UIError('500', error, 'IPCQWIN');
}
});
ActivityWatchEventManager.onPushChromeActivity(async (_, result: IActivityWatchEventResult) => {
const collections: IDesktopEvent[] = ActivityWatchEventAdapter.collections(result);
if (!collections.length) return;
try {
await timerHandler.processWithQueue(
`gauzy-queue`,
{
type: ActivityWatchEventTableList.CHROME,
data: collections
},
knex
);
} catch (error) {
log.error('Error on push chrome activity', error);
throw new UIError('500', error, 'IPCQWIN');
}
});
ActivityWatchEventManager.onRemoveAfkLocalData(async (_, value: any) => {
try {
const afkService = new ActivityWatchAfkService();
await afkService.clear();
} catch (error) {
log.error('Error on remove afk local data', error);
throw new UIError('500', error, 'IPCRMAFK');
}
});
ActivityWatchEventManager.onRemoveLocalData(async (_, value: any) => {
try {
await timerHandler.processWithQueue(
`gauzy-queue`,
{
type: 'remove-window-events'
},
knex
);
} catch (error) {
log.error('Error on remove local data', error);
throw new UIError('500', error, 'IPCRMAW');
}
});
ActivityWatchEventManager.onStatusChange((_, value: boolean) => {
LocalStore.updateApplicationSetting({
awIsConnected: value
});
});
ActivityWatchEventManager.onSet((_, aw) => {
const projectInfo = LocalStore.getStore('project');
store.set({
project: {
...projectInfo,
aw
}
});
});
ActivityWatchEventManager.onPushEdgeActivity(async (_, result: IActivityWatchEventResult) => {
const collections: IDesktopEvent[] = ActivityWatchEventAdapter.collections(result);
if (!collections.length) return;
try {
await timerHandler.processWithQueue(
`gauzy-queue`,
{
type: ActivityWatchEventTableList.EDGE,
data: collections
},
knex
);
} catch (error) {
log.error('Error on push edge activity', error);
throw new UIError('500', error, 'IPCQWIN');
}
});
ipcMain.on('remove_wakatime_local_data', async (event, arg) => {
try {
if (arg.idsWakatime && arg.idsWakatime.length > 0) {
await timerHandler.processWithQueue(
`gauzy-queue`,
{
type: 'remove-wakatime-events',
data: arg.idsWakatime
},
knex
);
}
} catch (error) {
log.error('Error on remove wakatime local data', error);
throw new UIError('500', error, 'IPCRMWK');
}
});
ipcMain.handle('STOP_TIMER', async (event, arg) => {
try {
log.info(`Timer Stop: ${moment().format()}`);
// Check api connection before to stop
if (!arg.isEmergency) {
// We check connectivity before stop timer, but we don't block the process for now...
// Instead, we should notify the user that timer might not stop correctly and retry stop the timer after connection to API is restored
setTimeout(async () => {
log.info('Check API Connection During Stop Timer...');
await offlineMode.connectivity();
if (offlineMode.enabled) {
console.log('Offline Mode: Mark as stopped offline');
await markLastTimerAsStoppedOffline();
// We may want to show some notification to user that timer might not stop correctly, but not with Error, more like notification popup
// throw new Error('Cannot establish connection to API during Timer Stop');
} else {
console.log('API working well During Stop Timer');
}
}, 10);
}
console.log('Continue stopping timer ...');
// Stop Timer
const timerResponse = await timerHandler.stopTimer(setupWindow, timeTrackerWindow, knex, arg.quitApp);
console.log('Timer Stopped ...');
settingWindow.webContents.send('app_setting_update', {
setting: LocalStore.getStore('appSetting')
});
if (powerManagerPreventSleep) {
console.log('Stop Prevent Display Sleep');
powerManagerPreventSleep.stop();
}
if (powerManagerDetectInactivity) {
console.log('Stop Inactivity Detection');
powerManagerDetectInactivity.stopInactivityDetection();
}
return timerResponse;
} catch (error) {
log.info('Error on stop timer', error);
timeTrackerWindow.webContents.send('emergency_stop');
throw new UIError('500', error, 'IPCSTOPTMR');
}
});
ipcMain.on('return_time_slot', async (event, arg) => {
try {
log.info(`Return To Timeslot Last Timeslot ID: ${arg.timeSlotId} and Timer ID: ${arg.timerId}`);
await timerHandler.processWithQueue(
`gauzy-queue`,
{
type: 'update-timer-time-slot',
data: {
id: arg.timerId,
timeSlotId: arg.timeSlotId
}
},
knex
);
timeTrackerWindow.webContents.send('refresh_time_log', LocalStore.beforeRequestParams());
// after update time slot do upload screenshot
// check config
const appSetting = LocalStore.getStore('appSetting');
log.info(`App Setting: ${moment().format()}`, appSetting);
log.info(`Config: ${moment().format()}`, config);
if (!arg.quitApp) {
log.info('TimeLogs:', arg.timeLogs);
// create new timer entry after create timeslot
let timeLogs = arg.timeLogs;
timeLogs = _.sortBy(timeLogs, 'recordedAt').reverse();
const [timeLog] = timeLogs;
await timerHandler.createTimer(timeLog);
}
} catch (error) {
log.error('Error on return time slot', error);
throw new UIError('500', error, 'IPCRTNSLOT');
}
});
ipcMain.on('show_screenshot_notif_window', async (event, arg) => {
log.info(`Show Screenshot Notification Window: ${moment().format()}`);
const appSetting = LocalStore.getStore('appSetting');
const notify = new NotificationDesktop();
if (appSetting) {
if (appSetting.simpleScreenshotNotification) {
notify.customNotification(
TranslateService.instant('TIMER_TRACKER.NATIVE_NOTIFICATION.SCREENSHOT_TAKEN'),
process.env.DESCRIPTION
);
} else if (appSetting.screenshotNotification) {
try {
await notifyScreenshot(notificationWindow, arg, windowPath, soundPath, timeTrackerWindow);
} catch (error) {
throw new UIError('500', error, 'IPCNTFSHOT');
}
}
}
});
ipcMain.on('save_screen_shoot', async (event, arg) => {
log.info(`Save Screen Shoot: ${moment().format()}`);
try {
await takeshot(timeTrackerWindow, arg, notificationWindow, false, windowPath, soundPath);
} catch (error) {
log.error('Error on save screen shoot', error);
throw new UIError('400', error, 'IPCTKSHOT');
}
});
ipcMain.on('show_image', (event, arg) => {
imageView.show();
imageView.webContents.send('show_image', arg);
imageView.webContents.send('refresh_menu');
});
ipcMain.on('close_image_view', () => {
imageView.hide();
});
ipcMain.on('save_temp_screenshot', async (event, arg) => {
try {
log.info(`Save Temp Screenshot: ${moment().format()}`);
await takeshot(timeTrackerWindow, arg, notificationWindow, true, windowPath, soundPath);
} catch (error) {
log.error('Error on save temp screenshot', error);
throw new UIError('400', error, 'IPCSAVESHOT');
}
});
ipcMain.on('open_setting_window', async (event, arg) => {
log.info(`Open Setting Window: ${moment().format()}`);
const appSetting = LocalStore.getStore('appSetting');
const config = LocalStore.getStore('configs');
const auth = LocalStore.getStore('auth');
const addSetting = LocalStore.getStore('additionalSetting');
if (!settingWindow) {
settingWindow = await createSettingsWindow(settingWindow, windowPath.timeTrackerUi, windowPath.preloadPath);
}
settingWindow.show();
settingWindow.webContents.send('app_setting', {
...LocalStore.beforeRequestParams(),
setting: appSetting,
config: config,
auth,
additionalSetting: addSetting
});
settingWindow.webContents.send('goto_top_menu');
});
ipcMain.on('switch_aw_option', (event, arg) => {
const settings = LocalStore.getStore('appSetting');
timeTrackerWindow.webContents.send('update_setting_value', settings);
});
ipcMain.on('logout_desktop', async (event, arg) => {
try {
log.info('Logout Desktop');
timeTrackerWindow.webContents.send('logout', arg);
} catch (error) {
log.error('Error Logout Desktop', error);
}
});
ipcMain.on('navigate_to_login', async () => {
try {
log.info('Navigate To Login');
if (timeTrackerWindow && process.env.IS_DESKTOP_TIMER) {
await timeTrackerWindow.loadURL(loginPage(windowPath.timeTrackerUi));
}
LocalStore.updateAuthSetting({ isLogout: true });
if (settingWindow) {
settingWindow.webContents.send('logout_success');
}
} catch (error) {
log.error('IPCQNVGLOGIN', error);
}
});
ipcMain.on('expand', (event, arg) => {
try {
log.info(`Expand: ${moment().format()}`);
resizeWindow(timeTrackerWindow, arg);
event.sender.send('expand', arg);
} catch (error) {
log.error('error on change window width', error);
}
});
function resizeWindow(window: BrowserWindow, isExpanded: boolean): void {
const display = screen.getPrimaryDisplay();
const { height, width } = display.workAreaSize;
log.info('workAreaSize', { height, width });
const maxHeight = height <= 768 ? height - 20 : 768;
const maxWidth = height < 768 ? 360 - 50 : 360;
const widthLarge = height < 768 ? 1280 - 50 : 1280;
switch (process.platform) {
case 'linux':
{
const wx = isExpanded ? 1280 : 360;
const hx = 748;
window.setMinimumSize(wx, hx);
window.setSize(wx, hx, true);
window.setResizable(false);
}
break;
case 'darwin':
{
window.setSize(isExpanded ? widthLarge : maxWidth, maxHeight, true);
if (isExpanded) window.center();
}
break;
default:
{
let calculatedX = (width - (isExpanded ? widthLarge : maxWidth)) * 0.5;
let calculatedY = (height - maxHeight) * 0.5;
// Ensure x and y are not negative
calculatedX = Math.max(0, calculatedX);
calculatedY = Math.max(0, calculatedY);
// Ensure window does not exceed screen bounds
calculatedX = Math.min(calculatedX, width - (isExpanded ? widthLarge : maxWidth));
calculatedY = Math.min(calculatedY, height - maxHeight);
const bounds = {
width: isExpanded ? widthLarge : maxWidth,
height: maxHeight,
x: Math.round(calculatedX),
y: Math.round(calculatedY)
};
log.info('Bounds', JSON.stringify(bounds));
window.setBounds(bounds, true);
}
break;
}
}
ipcMain.on('timer_stopped', (event, arg) => {
log.info(`Timer Stopped: ${moment().format()}`);
timeTrackerWindow.webContents.send('timer_already_stop');
});
ipcMain.on('refresh-timer', async (event) => {
log.info(`Refresh Timer: ${moment().format()}`);
try {
const lastTime = await timerService.findLastCapture();
log.info('Last Capture Time Start Tracking Time (Desktop Try):', lastTime);
if (!isQueueThreadTimerLocked) {
await sequentialSyncQueue(timeTrackerWindow);
}
await latestScreenshots(timeTrackerWindow);
await countIntervalQueue(timeTrackerWindow, false);
timeTrackerWindow.webContents.send('timer_tracker_show', {
...LocalStore.beforeRequestParams(),
timeSlotId: lastTime ? lastTime.timeslotId : null
});
} catch (error) {
log.error('Error on refresh timer', error);