-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.js
More file actions
833 lines (744 loc) · 25.8 KB
/
Copy pathmain.js
File metadata and controls
833 lines (744 loc) · 25.8 KB
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
const fs = require("node:fs");
const path = require("node:path");
const isMac = process.platform === "darwin"; // macOS check
const arch = process.arch;
const {
app,
session,
Menu,
dialog,
ipcMain,
MessageChannelMain,
BrowserWindow,
powerSaveBlocker,
} = require("electron");
app.commandLine.appendSwitch("disable-renderer-backgrounding");
app.commandLine.appendSwitch("force-high-performance-gpu");
app.commandLine.appendSwitch("xdg-portal-required-version", "4");
const isX11 = process.platform === 'linux' && !!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY;
if (isX11) {
// WebGPU flags needed for Linux
app.commandLine.appendSwitch("enable-unsafe-webgpu");
app.commandLine.appendSwitch("enable-features", "Vulkan");
}
process.env["TF_ENABLE_ONEDNN_OPTS"] = "1";
// Set the AppUserModelID (to prevent the two pinned icons bug)
app.setAppUserModelId('com.electron.chirpity');
const version = app.getVersion();
function copyFilesOnly(srcDir, destDir) {
for (const item of fs.readdirSync(srcDir)) {
if (['config.json',
'archive.sqlite',
'archive.sqlite.shm',
'archive.sqlite.wal',
'XCcache.json',
'settings.json'].includes(item)){
const srcPath = path.join(srcDir, item);
const destPath = path.join(destDir, item);
// Copy files
fs.copyFileSync(srcPath, destPath);
}
}
}
// // When dmg is installed over a pkg installation, the app crashes, so...
const userData = app.getPath("userData");
const CONFIG_FILE = path.join(userData, 'config.json');
function checkForMigration() {
if (isMac && ! fs.existsSync(path.join(userData, 'pkg2dmg')) && fs.existsSync(CONFIG_FILE)){
console.log(`existing config found`)
try {
const data = fs.readFileSync(CONFIG_FILE);
const semver = require('semver');
const {VERSION} = JSON.parse(data);
if (semver.gt(VERSION, '5.6.1')) {
console.log(`No migrating needed for version ${VERSION}`)
fs.writeFileSync(path.join(userData, 'pkg2dmg'), "");
return; // no migration needed
}
console.log(`migrating settings from version ${VERSION}`)
const movedSettings = userData+' old'
fs.renameSync(userData, movedSettings);
fs.mkdirSync(userData)
copyFilesOnly(movedSettings, userData)
fs.writeFileSync(path.join(userData, 'pkg2dmg'), "");
console.log('Migration done')
} catch (err) {
console.error(err);
}
}
}
checkForMigration();
const { autoUpdater } = require("electron-updater");
const log = require("electron-log");
const crypto = require("node:crypto");
const settings = require("electron-settings");
const keytar = require('keytar');
const SERVICE = 'Chirpity';
const ACCOUNT = 'uuid';
let DEBUG = false;
/**
* Ensure and return persistent install information, creating and storing it in the system keychain if missing or invalid.
* Attempts to read an existing record from the keychain; if none exists or it lacks a valid `installedAt`, a new record is generated and persisted. If a provided `date` is invalid, the current time is used. Keychain read/write failures are logged and the new record is returned (but may not be persisted).
* @param {string|Date|number} [date] - Optional install timestamp (ISO string, Date object, or epoch milliseconds) to use when creating a new record.
* @returns {{appId: string, installedAt: string}} An object containing `appId` (a UUID) and `installedAt` (an ISO 8601 timestamp).
*/
async function getInstallInfo(date) {
//if (!!process.env.CI) return { appId: crypto.randomUUID(), installedAt: Date.now().toISOString() }; // Don't use keychain in CI, just return dummy data
// First, try the current key (ACCOUNT = 'uuid')
try {
const raw = await keytar.getPassword(SERVICE, ACCOUNT);
if (raw) {
try {
const parsed = JSON.parse(raw);
if (parsed && typeof parsed.installedAt === "string") {
return parsed;
}
console.warn("getInstallInfo: keychain entry missing valid installedAt, will attempt migration or recreate", date);
} catch (e) {
console.warn("getInstallInfo: failed to parse current keychain entry, will attempt migration or recreate", e.message);
}
}
} catch (error) {
console.warn("getInstallInfo: keychain read failed for current key, will attempt migration or recreate:", error.message);
}
// If no current entry, try legacy key 'install-info' and migrate it if present
try {
const legacyRaw = await keytar.getPassword(SERVICE, 'install-info');
if (legacyRaw) {
let migratedDateStr = null;
let legacyAppId = null;
try {
const legacyParsed = JSON.parse(legacyRaw);
// Accept either { installedAt: '...' } or { installedAt: '...', appId: '...' }
if (legacyParsed && typeof legacyParsed.installedAt === 'string') {
migratedDateStr = legacyParsed.installedAt;
if (legacyParsed.appId) legacyAppId = legacyParsed.appId;
}
} catch (e) {
// Not JSON — maybe it's a raw date string
const maybeDate = new Date(legacyRaw);
if (!Number.isNaN(maybeDate.getTime())) {
migratedDateStr = maybeDate.toISOString();
}
}
if (migratedDateStr) {
const installInfo = {
appId: legacyAppId || crypto.randomUUID(),
installedAt: migratedDateStr,
};
try {
await keytar.setPassword(SERVICE, ACCOUNT, JSON.stringify(installInfo));
try {
// Remove legacy key to avoid confusion; ignore failures
await keytar.deletePassword(SERVICE, 'install-info');
} catch (delErr) {
console.warn('getInstallInfo: failed to delete legacy install-info key:', delErr.message);
}
console.info('getInstallInfo: migrated legacy install-info to', ACCOUNT);
} catch (writeErr) {
console.warn('getInstallInfo: failed to write migrated installInfo to keychain:', writeErr.message);
}
return installInfo;
} else {
console.warn('getInstallInfo: legacy install-info found but no usable date; will recreate.');
}
}
} catch (legacyErr) {
console.warn('getInstallInfo: error reading legacy install-info key:', legacyErr.message);
}
let effectiveDate = date ? new Date(date) : new Date();
if (Number.isNaN(effectiveDate.getTime())) {
console.warn("getInstallInfo: invalid date provided, falling back to now. Date:", effectiveDate);
effectiveDate = new Date();
}
const installInfo = {
appId: crypto.randomUUID(),
installedAt: effectiveDate.toISOString(),
};
console.log('attempt to set new service password, using ', installInfo)
try {
await keytar.setPassword(SERVICE, ACCOUNT, JSON.stringify(installInfo));
} catch (error) {
console.warn("getInstallInfo: keychain write failed (using in‑memory date only):", error.message);
}
return installInfo;
}
//require('update-electron-app')();
let files = [];
let unsavedRecords = false;
// List of supported file for opening:
const SUPPORTED_FILES = [
".wav",
".flac",
".opus",
".m4a",
".mp3",
".mpga",
".ogg",
".aac",
".mpeg",
".mp4",
".mov",
];
//-------------------------------------------------------------------
// Logging
// This logging setup is not required for auto-updates to work,
// but it sure makes debugging easier :)
//-------------------------------------------------------------------
console.log = log.log;
console.warn = log.warn;
console.error = log.error;
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = "info";
autoUpdater.allowPrerelease = false;
const channel = `latest-${arch}`;
log.info('channel:', channel)
autoUpdater.channel = channel;
log.info('App starting...');
// Set membership URL here
process.env.MEMBERSHIP_API_ENDPOINT = 'https://subscriber.mattkirkland.co.uk/check-uuid_v2';
// Define the menu template
const template = [
...(isMac
? [
{
label: "Chirpity",
submenu: [
{ role: "about" },
{ type: "separator" },
{ role: "services" },
{ type: "separator" },
{ role: "hide" },
{ role: "hideOthers" },
{ role: "unhide" },
{ type: "separator" },
{ role: "quit" },
],
},
]
: []),
{
label: "Edit",
submenu: [
{ role: "undo" },
{ role: "redo" },
{ type: "separator" },
{ role: "cut" },
{ role: "copy" },
{ role: "paste" },
{ role: "selectAll" },
],
},
];
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
// Updates
// Function to fetch release notes from GitHub API
async function fetchReleaseNotes(version) {
try {
const response = await fetch(
"https://api.github.com/repos/Mattk70/Chirpity-Electron/releases/latest"
);
if (response.ok) {
const data = await response.json();
if (data && data.body) {
return data.body;
}
} else {
console.error("Error fetching release notes:", response.statusText);
}
} catch (error) {
console.error("Error fetching release notes:", error);
}
return "Release notes not available.";
}
autoUpdater.on("checking-for-update", function () {
logUpdateStatus("Checking for update...");
if (process.env.PORTABLE_EXECUTABLE_DIR) {
logUpdateStatus("This is a portable exe");
}
});
autoUpdater.on("update-available", async function (info) {
if (!process.env.PORTABLE_EXECUTABLE_DIR) {
autoUpdater.downloadUpdate();
} else {
// Fetch release notes from GitHub API
const releaseNotes = await fetchReleaseNotes(info.version);
dialog.showMessageBox({
type: "info",
title: "Update Available",
message: `A new version (${info.version}) is available.\n\nRelease Notes:\n${releaseNotes}`,
buttons: ["OK"],
defaultId: 1,
noLink: true,
});
}
});
autoUpdater.on("update-not-available", function (_info) {
logUpdateStatus("Update not available.");
});
autoUpdater.on("error", function (err) {
logUpdateStatus("Error in auto-updater:" + err);
});
autoUpdater.on("download-progress", function (progressObj) {
try{
mainWindow.webContents.send("download-progress", progressObj);
} catch {
logUpdateStatus('mainwindow progress update failed')
}
});
autoUpdater.on("update-downloaded", async function (info) {
// Fetch release notes from GitHub API
const releaseNotes = await fetchReleaseNotes(info.version);
log.info(JSON.stringify(info));
// Display dialog to the user with release notes
dialog
.showMessageBox({
type: "info",
title: "Update Available",
message: `A new version (${info.version}) is available.\n\nRelease Notes:\n${releaseNotes}\n\nDo you want to install it now?`,
buttons: ["Quit and Install", "Install after Exit"],
defaultId: 1,
noLink: true,
})
.then((result) => {
if (result.response === 0) {
// User clicked 'Yes', start the installation
autoUpdater.quitAndInstall(true, true);
}
})
});
function logUpdateStatus(message) {
console.log(message);
}
process.stdin.resume(); //so the program will not close instantly
function getFileFromArgs(args) {
return args.find(arg => SUPPORTED_FILES.some(ext => arg.toLowerCase().endsWith(ext)));
}
async function exitHandler(options, exitCode) {
if (options.cleanup) {
// clean up settings.json litter
const conf = userData;
fs.readdir(conf, (err, files) => {
if (err) {
console.error("Error reading folder:", err);
return;
}
files.forEach((file) => {
if (file.startsWith("settings.json.")) {
fs.unlink(path.join(conf, file), (err) => {
if (err) {
console.error("Error deleting file:", err);
} else {
DEBUG && console.log("Deleted file:", file);
}
});
}
});
});
// Disable debug mode here?
} else {
DEBUG && console.log("no clean");
}
if (exitCode || exitCode === 0) {
DEBUG && console.log(`App closed with code: ${exitCode}`);
}
}
//do something when app is closing
process.on("exit", exitHandler.bind(undefined, { cleanup: true }));
process.on("SIGINT", () => {
exitHandler({ cleanup: true });
app.quit(); // Triggers before-quit handler
});
process.on("SIGUSR1", () => app.quit());
process.on("SIGUSR2", () => app.quit());
process.on("uncaughtException", (err) => {
console.error("Uncaught exception:", err);
app.quit();
});
ipcMain.handle('getPath', () => userData);
ipcMain.handle('getAppPath', () => app.getAppPath());
ipcMain.handle('trialPeriod', () => 14*24*3600*1000); // 14 days
ipcMain.handle('getLocale', () => app.getLocale());
ipcMain.handle('getTemp', () => app.getPath('temp'));
ipcMain.handle('isMac', () => isMac);
ipcMain.handle('getAudio', () => path.join(__dirname.replace('app.asar', ''), 'Help', 'example.mp3'));
ipcMain.handle('exitApplication', () => app.quit());
ipcMain.handle('getInstallInfo', (_e, date) => getInstallInfo(date));
let mainWindow;
let workerWindow;
async function windowStateKeeper(windowName) {
let window, windowState;
async function setBounds() {
// Restore from settings
if (await settings.has(`windowState.${windowName}`)) {
windowState = await settings.get(`windowState.${windowName}`);
} else {
// Default
windowState = {
x: undefined,
y: undefined,
width: 1280,
height: 768,
};
}
}
async function saveState() {
if (!windowState.isMaximized) {
windowState = window.getBounds();
}
windowState.isMaximized = window.isMaximized();
windowState.isFullScreen = window.isFullScreen();
try {
await settings.set(`windowState.${windowName}`, windowState);
} catch {} // do nothing
}
function track(win) {
window = win;
["resize", "move", "maximize", "unmaximize"].forEach((event) => {
win.on(event, saveState);
});
}
await setBounds();
return { ...windowState, track };
}
async function createWindow() {
// Create the browser window.
// Get window state
const mainWindowStateKeeper = await windowStateKeeper("main");
mainWindow = new BrowserWindow({
show: false,
title: "Chirpity Nocmig",
x: mainWindowStateKeeper.x,
y: mainWindowStateKeeper.y,
width: mainWindowStateKeeper.width,
height: mainWindowStateKeeper.height,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
nodeIntegration: true,
contextIsolation: true,
backgroundThrottling: false,
},
});
mainWindow.setFullScreen(mainWindowStateKeeper.isFullScreen);
mainWindowStateKeeper.isMaximized && mainWindow.maximize();
// Track window state
mainWindowStateKeeper.track(mainWindow);
// Set icon
mainWindow.setIcon(__dirname + "/img/icon/icon.png");
// Hide nav bar except in ci mode
mainWindow.setMenuBarVisibility(!!process.env.CI);
// and load the index.html of the app.
mainWindow.loadFile("index.html");
mainWindow.once("ready-to-show", () => {
mainWindow.show();
DEBUG && mainWindow.webContents.openDevTools({ mode: "detach" });
});
DEBUG && console.log("main window created");
// Emitted when the window is closed.
mainWindow.on("closed", () => {
app.quit();
});
if (!isMac) {
mainWindow.on("close", (e) => {
if (unsavedRecords && !process.env.CI) {
const choice = dialog.showMessageBoxSync(mainWindow, {
type: "warning",
buttons: ["Yes", "No"],
title: "Unsaved Records",
message: "There are unsaved records, are you sure you want to exit?",
});
if (choice === 1) {
e.preventDefault(); // Prevent the app from closing
}
}
})
}
}
async function createWorker() {
// hidden worker
// Get window state
const mainWindowStateKeeper = await windowStateKeeper("worker");
workerWindow = new BrowserWindow({
show: false,
x: mainWindowStateKeeper.x,
y: mainWindowStateKeeper.y,
width: mainWindowStateKeeper.width,
height: mainWindowStateKeeper.height,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
contextIsolation: false,
backgroundThrottling: false,
},
});
// Track window state
mainWindowStateKeeper.track(workerWindow);
workerWindow.setIcon(__dirname + "/img/icon/icon.png");
await workerWindow.loadFile("worker.html");
workerWindow.on("closed", () => {
workerWindow = undefined;
});
workerWindow.once("ready-to-show", () => {
if (DEBUG) {
workerWindow.show();
workerWindow.webContents.openDevTools();
}
});
DEBUG && console.log("worker created");
}
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit()
} else {
app.on('second-instance', (e, commandLine) => {
// This event is emitted when a second instance is launched
// Focus the primary instance's window
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
const filePath = getFileFromArgs(commandLine)
if (filePath) {
mainWindow.webContents.send('open-file', filePath);
}
}
});
}
// This method will be called when Electron has finished loading
app.whenReady().then(async () => {
// Update the userData path for portable app
if (process.env.PORTABLE_EXECUTABLE_DIR) {
app.setPath(
"userData",
path.join(process.env.PORTABLE_EXECUTABLE_DIR, "chirpity-data")
);
ipcMain.handle("getVersion", () => version + " (Portable)");
} else {
ipcMain.handle("getVersion", () => version);
}
// Set referer for openstreetmap
const filter = {
urls: ['https://tile.openstreetmap.org/*','https://*.tile.openstreetmap.org/*']
};
session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
// Set a custom referer
details.requestHeaders['Referer'] = 'https://chirpity.app/map';
callback({ requestHeaders: details.requestHeaders });
});
// Debug mode
try {
// Specify the file path
const filePath = path.join(userData, 'config.json');
// Read the contents of the file synchronously
const fileContent = fs.readFileSync(filePath, 'utf8');
const config = JSON.parse(fileContent);
DEBUG = process.env.CI === 'e2e' ? false : config.debug;
} catch (error) {
console.warn('CONFIG: Error reading file:', error.message);
}
DEBUG && console.log('CI mode' , process.env.CI)
await createWorker();
await createWindow();
if (isMac) {
//const appIcon = new Tray('./img/icon/icon.png')
app.dock.setIcon(__dirname + '/img/icon/icon.png');
app.dock.bounce();
} else {
// Quit when all windows are closed.
app.on('window-all-closed', () => {
app.quit()
})
const filePath = getFileFromArgs(process.argv);
if (filePath) {
mainWindow.webContents.once('did-finish-load', () => {
mainWindow.webContents.send('open-file', filePath);
});
}
}
app.on("activate", async () => {
const windowsOpen = BrowserWindow.getAllWindows().length
if (!windowsOpen) {
await createWorker();
await createWindow();
} else if (windowsOpen === 1) {
await createWindow();
}
});
app.on('open-file', (event, path) => {
files.push(path);
DEBUG && console.log('file passed to open:', path)
});
ipcMain.handle('openFiles', async (_event, _method, config) => {
const {type, fileOrFolder, multi, buttonLabel, title} = config;
let options;
if (type === 'audio') {
options = {
properties: [fileOrFolder, multi].filter(Boolean),
buttonLabel: buttonLabel,
title: title
}
if (fileOrFolder === 'openFile' ){
options.filters = [{ name: 'Audio Files', extensions: ['mp3', 'wav', 'ogg', 'aac', 'flac', 'm4a', 'mpga', 'mpeg', 'mp4', 'opus', 'mov'] } ]
}
} else {
const ext = type === 'Text' ? ['txt', 'csv'] : ['csv'];
console.log('selecting ', type, ext )
options = {
filters: [
{ name: `${type} Files`, extensions: ext }
],
properties: ['openFile']
}
}
// Show file dialog
return await dialog.showOpenDialog(mainWindow, options);
})
/**
* Retrieves the first file path from the given arguments that matches a supported file extension.
*
* This function iterates over an array of arguments and returns the first element that ends with any
* of the file extensions defined in the global `SUPPORTED_FILES` array. The check is performed in a
* case-insensitive manner.
*
* @param {string[]} args - An array of command line arguments potentially containing file paths.
* @returns {string|undefined} The first matching file path with a supported extension, or `undefined` if none is found.
*/
ipcMain.handle('selectDirectory', async (_e, path) => {
// Show file dialog to select a directory
return await dialog.showOpenDialog(mainWindow, {
// From docs:
// Note: On Windows and Linux an open dialog can not be both a file selector and a directory selector,
// so if you set properties to ['openFile', 'openDirectory'] on these platforms,
// a directory selector will be shown.
defaultPath: path,
properties: ['openDirectory']
});
})
mainWindow.webContents.setWindowOpenHandler(({ url, frameName }) => {
require('electron').shell.openExternal(url);
return {
action: 'deny',
}
});
workerWindow.webContents.once('render-process-gone', (e, details) => {
DEBUG && console.log(details);
const dialogOpts = {
type: 'warning',
title: 'Crash report',
detail: 'Oh no! Chirpity has crashed. It is most likely that it has run out of memory.\nTry lowering the batch size and / or number of threads\nYou will find those options in the Expert tab of Settings'
};
dialog.showMessageBox(dialogOpts).then((returnValue) => {
if (returnValue.response === 0) {
//app.relaunch();
app.quit();
}
})
});
//Update handling
if (process.env.CI) {
console.log("Auto-updater disabled in CI environment");
} else {
autoUpdater.autoDownload = false;
autoUpdater.checkForUpdates().catch(error => console.warn('Error checking for updates', error))
}
});
let DB_CLOSED = false;
let DB_CLOSE_REQUESTED = false;
app.on('before-quit', async (event) => {
if (DB_CLOSED) return;
// Always block quit while DB is still open
event.preventDefault();
if (DB_CLOSE_REQUESTED) return;
DB_CLOSE_REQUESTED = true;
try{
workerWindow.webContents.postMessage("close-database", null);
} catch {
console.log('workerWindow closed before DB close call')
}
// Add timeout to force quit after 5 seconds
setTimeout(() => {
if (!DB_CLOSED) {
console.warn('Database closure timed out after 5 seconds, forcing quit...');
DB_CLOSED = true;
app.quit();
}
}, 5000);
});
ipcMain.on('database-closed', () =>{
DB_CLOSED = true;
app.quit()
})
ipcMain.handle("request-worker-channel", (_event) => {
// Create a new channel ...
const { port1, port2 } = new MessageChannelMain();
// ... send one end to the worker ...
workerWindow.webContents.postMessage("new-client", undefined, [port1]);
// ... and the other end to the UI window.
mainWindow.webContents.postMessage("provide-worker-channel", undefined, [
port2,
]);
// Now the main window and the worker can communicate with each other
// without going through the main process!
});
ipcMain.on("unsaved-records", (_event, data) => {
unsavedRecords = data.newValue; // Update the variable with the new value
});
ipcMain.handle("exportData", async (event, arg) => {
const {defaultPath} = arg;
return await dialog
.showSaveDialog(mainWindow, {
filters: [{ name: "Text Files", extensions: ["txt", "csv"] }],
defaultPath
})
.then((file) => file.filePath)
})
ipcMain.handle("saveFile", async (event, arg) => {
// Show file dialog to select audio file
const { file, filename, extension } = arg;
dialog
.showSaveDialog(mainWindow, {
title: "Save File",
filters: [{ name: "Audio files", extensions: [extension] }],
defaultPath: filename,
})
.then((saveObj) => {
// Check if the user cancelled the operation
const { canceled, filePath } = saveObj;
if (canceled) {
DEBUG && console.log("User cancelled the save operation.");
fs.rmSync(file);
return;
}
try {
// Copy file to the destination
fs.copyFileSync(file, filePath);
// Remove the original file
fs.unlinkSync(file);
DEBUG && console.log(`File moved from ${file} to ${filePath}`);
} catch (error) {
console.error(`Error moving file: ${error}`);
}
});
});
let powerSaveID = null;
ipcMain.on("powerSaveControl", (e, on) => {
if (on) {
powerSaveID = powerSaveBlocker.start("prevent-app-suspension");
//DEBUG && console.log(powerSaveBlocker.isStarted(powerSaveID), powerSaveID)
} else {
if (powerSaveID !== null) powerSaveBlocker.stop(powerSaveID);
//DEBUG && console.log(powerSaveBlocker.isStarted(powerSaveID), powerSaveID)
}
});
ipcMain.on("debug-mode", (e, on) => {
DEBUG = !!on;
if (on) {
mainWindow?.webContents.openDevTools({ mode: "detach" });
workerWindow?.show();
workerWindow?.webContents.openDevTools();
} else {
mainWindow?.webContents.closeDevTools();
workerWindow?.webContents.closeDevTools();
workerWindow?.hide();
}
});