-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.ts
More file actions
188 lines (165 loc) · 6.31 KB
/
Copy pathmain.ts
File metadata and controls
188 lines (165 loc) · 6.31 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
import { app, BrowserWindow, ipcMain, protocol, shell } from "electron";
import * as path from "path";
import { fileURLToPath } from "url";
import fs from "fs";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const isDev = process.env.NODE_ENV === "development";
let mainWindow: BrowserWindow | null = null;
function createWindow(): void {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, "preload.js"),
webSecurity: false,
},
});
if (isDev) {
mainWindow.loadURL("http://localhost:5173");
mainWindow.webContents.openDevTools();
} else {
const buildPath = path.join(__dirname, "frontend/dist/index.html");
if (fs.existsSync(buildPath)) {
mainWindow.loadURL(`file://${buildPath}`);
} else {
console.error("Build file not found:", buildPath);
}
}
}
// OAuth / protocol handling for Electron: open system browser to backend /login
const CUSTOM_PROTOCOL = process.env.ELECTRON_CUSTOM_PROTOCOL || "docbranch";
const AUTH_BACKEND = process.env.AUTH_SERVER_HOST || "http://localhost:3100";
// Handle protocol activation on macOS
app.on('open-url', (event, url) => {
event.preventDefault();
if (mainWindow) mainWindow.webContents.send('oauth-callback', url);
});
// Single instance lock - capture protocol URL on Windows second-instance
const gotLock = app.requestSingleInstanceLock();
if (!gotLock) {
app.quit();
} else {
app.on('second-instance', (event, argv) => {
const url = argv.find((a) => typeof a === 'string' && a.startsWith(`${CUSTOM_PROTOCOL}://`));
if (url && mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
mainWindow.webContents.send('oauth-callback', url);
}
});
}
// Try to register protocol handler (works for installed apps)
app.whenReady().then(() => {
try {
// In development, register the protocol with explicit execPath and
// app argument so Windows routes protocol URLs to the running Electron
// instance instead of invoking Electron with a malformed app path.
if ((process as any).defaultApp || process.argv[0].endsWith('electron') || process.execPath.endsWith('electron.exe')) {
const appPath = path.resolve(process.argv[1] || '.');
app.setAsDefaultProtocolClient(CUSTOM_PROTOCOL, process.execPath, [appPath]);
} else {
app.setAsDefaultProtocolClient(CUSTOM_PROTOCOL);
}
} catch (e) {
console.warn('Protocol registration failed', e);
}
});
// IPC handler: start OAuth by opening backend /login with electron flag
ipcMain.handle('oauth-start', async () => {
const url = `${AUTH_BACKEND}/login?electron=1&protocol=${encodeURIComponent(CUSTOM_PROTOCOL)}`;
await shell.openExternal(url);
return { opened: true };
});
// IPC handler: start OAuth inside an Electron BrowserWindow (in-app)
ipcMain.handle('oauth-start-in-app', async () => {
return new Promise((resolve, reject) => {
try {
const authWin = new BrowserWindow({
parent: mainWindow || undefined,
modal: !!mainWindow,
show: true,
width: 600,
height: 800,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
},
});
const authUrl = `${AUTH_BACKEND}/login?electron=1&protocol=${encodeURIComponent(CUSTOM_PROTOCOL)}`;
authWin.loadURL(authUrl).catch((e) => console.error('authWin loadURL failed', e));
const cleanup = () => {
try { authWin.close(); } catch (e) {}
};
const handler = (event: any, navigationUrl: string) => {
try {
if (typeof navigationUrl === 'string' && navigationUrl.startsWith(`${CUSTOM_PROTOCOL}://`)) {
// Prevent navigation to the protocol handler - we capture it here
event.preventDefault?.();
const parsed = new URL(navigationUrl);
const access_token = parsed.searchParams.get('access_token');
const id_token = parsed.searchParams.get('id_token');
// Forward to renderer so it can set localStorage and navigate
if (mainWindow) mainWindow.webContents.send('oauth-callback', navigationUrl);
resolve({ access_token, id_token, raw: navigationUrl });
cleanup();
}
} catch (err) {
reject(err);
cleanup();
}
};
authWin.webContents.on('will-redirect', handler as any);
authWin.webContents.on('will-navigate', handler as any);
authWin.on('closed', () => {
reject(new Error('Auth window closed'));
});
} catch (err) {
reject(err);
}
});
});
// Register a protocol to serve PDF worker files
app.whenReady().then(() => {
protocol.registerFileProtocol('pdf-worker', (request, callback) => {
const url = request.url.replace('pdf-worker://', '');
const workerPath = path.join(__dirname, '..', 'node_modules', 'pdfjs-dist', 'build', url);
callback(workerPath);
});
createWindow();
});
// Keep only Electron-specific IPC handlers
ipcMain.handle("load-pdf", async (_, filePath: string) => {
console.log(" IPC load-pdf called with:", filePath);
const exists = fs.existsSync(filePath);
console.log(" File exists?", exists);
if (!exists) {
throw new Error("File not found: " + filePath);
}
const data = fs.readFileSync(filePath);
console.log("Read bytes:", data.length);
return data.toString("base64");
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit();
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
// Save resume JSON to disk
ipcMain.handle("save-resume", async (_, { resumeObj, filename }: { resumeObj: any; filename?: string }) => {
try {
const outDir = path.join(__dirname, 'backend', 'resume-generator', 'resume_json_files');
if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });
const outFile = filename ? path.join(outDir, filename) : path.join(outDir, `resume_${Date.now()}.json`);
fs.writeFileSync(outFile, JSON.stringify(resumeObj, null, 2), 'utf8');
console.log('Saved resume JSON to', outFile);
return outFile;
} catch (err) {
console.error('Failed to save resume JSON:', err);
throw err;
}
});