-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathmain.js
More file actions
387 lines (323 loc) · 12.1 KB
/
main.js
File metadata and controls
387 lines (323 loc) · 12.1 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
/* global setImmediate */ // for eslint because setImmediate is node global
import cors from "cors";
import { app, BrowserWindow, dialog, ipcMain, shell } from "electron";
import applog from "electron-log";
import { Buffer } from "node:buffer";
import fs from "node:fs";
import * as fsPromises from "node:fs/promises";
import path from "node:path";
import process from "node:process";
import { fileURLToPath } from "node:url";
import { Conf } from "electron-conf/main";
import { createSplashWindow, createWindow } from "./electron-main/createWindow.js";
import { setCustomSaveFolderIPC } from "./electron-main/customFolderLocationOperation.js";
import { expressApp } from "./electron-main/expressServer.js";
import { getLogFolder, getSaveFolder, readUserSettings } from "./electron-main/filePath.js";
import {
getCustomSaveFolderIPC,
getFfmpegWasmPathIPC,
getSaveFolderIPC,
getVideoFileDataIPC,
getVideoSaveFolderIPC,
} from "./electron-main/getFileAndFolder.js";
import {
getCurrentLogSettings,
manageLogFiles,
setCurrentLogSettings,
} from "./electron-main/logOperations.js";
import {
cancelProcess,
checkPythonInstalled,
downloadModel,
installDependencies,
killCurrentPythonProcess,
resetGlobalCancel,
setupPronunciationInstallStatusIPC,
} from "./electron-main/pronunciationOperations.js";
import { checkDownloads, checkExtractedFolder } from "./electron-main/videoFileOperations.js";
import { verifyAndExtractIPC } from "./electron-main/zipOperation.js";
import {
setupPronunciationCheckerIPC,
setupGetRecordingBlobIPC,
} from "./electron-main/pronunciationCheckerIPC.js";
const DEFAULT_PORT = 8998;
let server; // Declare server at the top so it's in scope for all uses
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
let electronSquirrelStartup = false;
try {
electronSquirrelStartup = (await import("electron-squirrel-startup")).default;
} catch (e) {
console.log("Error importing electron-squirrel-startup:", e);
applog.error("Error importing electron-squirrel-startup:", e);
}
if (electronSquirrelStartup) app.quit();
// Log operations
manageLogFiles();
const conf = new Conf();
conf.registerRendererListener();
let mainWindow;
// Allow requests from localhost:5173 (Vite's default development server)
expressApp.use(cors({ origin: "http://localhost:5173" }));
// Set up rate limiter: maximum of 2000 requests per 15 minutes
/*const limiter = RateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 2000,
});*/
// Set up the express server to serve video files
expressApp.get("/video/:folderName/:fileName", async (req, res) => {
const { folderName, fileName } = req.params;
const documentsPath = await getSaveFolder(readUserSettings);
const videoFolder = path.resolve(documentsPath, "video_files", folderName);
const videoFilePath = path.resolve(videoFolder, fileName);
if (!videoFilePath.startsWith(videoFolder)) {
res.status(403).send("Access denied.");
return;
}
try {
await fsPromises.access(videoFilePath);
const stat = await fsPromises.stat(videoFilePath);
const fileSize = stat.size;
const range = req.headers.range;
if (range) {
const parts = range.replace(/bytes=/, "").split("-");
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
const chunkSize = end - start + 1;
const file = fs.createReadStream(videoFilePath, { start, end });
const head = {
"Content-Range": `bytes ${start}-${end}/${fileSize}`,
"Accept-Ranges": "bytes",
"Content-Length": chunkSize,
"Content-Type": "video/mp4",
};
res.writeHead(206, head);
file.pipe(res);
} else {
const head = {
"Content-Length": fileSize,
"Content-Type": "video/mp4",
};
res.writeHead(200, head);
fs.createReadStream(videoFilePath).pipe(res);
}
} catch {
res.status(404).send("Video file not found.");
return;
}
});
// IPC event from the renderer
ipcMain.handle("open-external-link", async (event, url) => {
await shell.openExternal(url); // Open the external link
});
// Handle saving a recording
ipcMain.handle("save-recording", async (event, key, arrayBuffer) => {
const saveFolder = await getSaveFolder(readUserSettings);
const recordingFolder = path.join(saveFolder, "saved_recordings");
const filePath = path.join(recordingFolder, `${key}.wav`);
// Ensure the directory exists
try {
await fsPromises.access(recordingFolder);
} catch {
await fsPromises.mkdir(recordingFolder, { recursive: true });
}
try {
const buffer = Buffer.from(arrayBuffer);
await fsPromises.writeFile(filePath, buffer);
console.log("Recording saved to:", filePath);
applog.log("Recording saved to:", filePath);
return "Success";
} catch (error) {
console.error("Error saving the recording to disk:", error);
throw error;
}
});
// Handle checking if a recording exists
ipcMain.handle("check-recording-exists", async (event, key) => {
const saveFolder = await getSaveFolder(readUserSettings);
const filePath = path.join(saveFolder, "saved_recordings", `${key}.wav`);
try {
await fsPromises.access(filePath);
return true;
} catch {
return false;
}
});
// Handle playing a recording (this can be improved for streaming)
ipcMain.handle("play-recording", async (event, key) => {
const filePath = path.join(
await getSaveFolder(readUserSettings),
"saved_recordings",
`${key}.wav`
);
// Check if the file exists
try {
const data = await fsPromises.readFile(filePath);
return data.buffer; // Return the ArrayBuffer to the renderer process
} catch {
console.error("File not found:", filePath);
throw new Error("Recording file not found");
}
});
/* Video file operations */
// Get video file data
getVideoFileDataIPC(__dirname);
// IPC event to get and open the video folder
getVideoSaveFolderIPC();
// Check video file downloads
checkDownloads();
// Check video file extracted folder
checkExtractedFolder();
/* End video file operations */
// IPC event to get the current server port
ipcMain.handle("get-port", () => {
return server?.address()?.port || DEFAULT_PORT;
});
ipcMain.handle("open-log-folder", async () => {
// Open the folder in the file manager
const logFolder = await getLogFolder(readUserSettings);
await shell.openPath(logFolder); // Open the folder
return logFolder; // Send the path back to the renderer
});
ipcMain.handle("open-recording-folder", async () => {
// Open the folder in the file manager
const recordingFolder = await getSaveFolder(readUserSettings);
const recordingFolderPath = path.join(recordingFolder, "saved_recordings");
try {
await fsPromises.access(recordingFolderPath);
} catch {
await fsPromises.mkdir(recordingFolderPath, { recursive: true });
}
await shell.openPath(recordingFolderPath); // Open the folder
return recordingFolderPath; // Send the path back to the renderer
});
// IPC event to verify and extract a zip file
verifyAndExtractIPC();
// Listen for logging messages from the renderer process
ipcMain.on("renderer-log", (event, logMessage) => {
const { level, message } = logMessage;
if (applog[level]) {
applog[level](`Renderer log: ${message}`);
}
});
// Handle uncaught exceptions globally and quit the app
process.on("uncaughtException", (error) => {
console.error("An uncaught error occurred:", error);
applog.error("An uncaught error occurred:", error);
app.quit(); // Quit the app on an uncaught exception
});
// Handle unhandled promise rejections globally and quit the app
process.on("unhandledRejection", (reason, promise) => {
console.error("Unhandled promise rejection at:", promise, "reason:", reason);
applog.error("Unhandled promise rejection at:", promise, "reason:", reason);
app.quit(); // Quit the app on an unhandled promise rejection
});
app.on("renderer-process-crashed", (event, webContents, killed) => {
applog.error("Renderer process crashed", { event, killed });
app.quit();
});
// Quit when all windows are closed, except on macOS.
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
// Recreate the window on macOS when the dock icon is clicked.
app.on("activate", () => {
if (mainWindow === null) {
createWindow(__dirname, (srv) => {
server = srv;
});
}
});
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
process.exit(0);
} else {
app.whenReady()
.then(() => {
// 1. Show splash window immediately
createSplashWindow(__dirname, ipcMain, conf);
// 2. Start heavy work in parallel after splash is shown
setImmediate(() => {
// Create main window (can be shown after splash)
createWindow(__dirname, (srv) => {
server = srv;
});
// Wait for log settings and manage logs in background
ipcMain.once("update-log-settings", (event, settings) => {
setCurrentLogSettings(settings);
applog.info("Log settings received from renderer:", settings);
manageLogFiles().then(() => {
applog.info("Log files managed successfully.");
});
});
});
})
.catch((error) => {
// Catch any errors thrown in the app.whenReady() promise itself
applog.error("Error in app.whenReady():", error);
});
}
getFfmpegWasmPathIPC(__dirname);
/* Custom save folder operations */
// IPC: Get current save folder (resolved)
getSaveFolderIPC();
// IPC: Get current custom save folder (raw, may be undefined)
getCustomSaveFolderIPC();
// IPC: Set custom save folder
setCustomSaveFolderIPC();
/* End custom save folder operations */
// IPC: Show open dialog for folder selection
ipcMain.handle("show-open-dialog", async (event, options) => {
const win = BrowserWindow.getFocusedWindow();
const result = await dialog.showOpenDialog(win, options);
return result.filePaths;
});
ipcMain.handle("get-log-settings", async () => {
return getCurrentLogSettings();
});
// DEBUG: Trace undefined logs
const origConsoleLog = console.log;
console.log = (...args) => {
if (args.length === 1 && args[0] === undefined) {
origConsoleLog.call(console, "console.log(undefined) called! Stack trace:");
origConsoleLog.call(console, new Error().stack);
}
origConsoleLog.apply(console, args);
};
/* Pronunciation checker operations */
ipcMain.handle("check-python-installed", async () => {
try {
const result = await checkPythonInstalled();
if (result.found) {
applog.info("Python found:", result.version);
} else {
applog.error("Python not found. Stderr:", result.stderr);
}
return result;
} catch (err) {
applog.error("Error checking Python installation:", err);
return { found: false, version: null, stderr: String(err) };
}
});
installDependencies();
downloadModel();
cancelProcess();
// Setup pronunciation install status IPC
setupPronunciationInstallStatusIPC();
// Before starting a new workflow, reset the global cancel flag
ipcMain.handle("pronunciation-reset-cancel-flag", async () => {
resetGlobalCancel();
});
/* End pronunciation checker operations */
ipcMain.handle("get-recording-path", async (_event, wordKey) => {
const saveFolder = await getSaveFolder(readUserSettings);
return path.join(saveFolder, "saved_recordings", `${wordKey}.wav`);
});
setupPronunciationCheckerIPC();
setupGetRecordingBlobIPC();
app.on("before-quit", async () => {
await killCurrentPythonProcess();
});