-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.js
274 lines (244 loc) · 7.99 KB
/
main.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
require("dotenv").config();
const { app, BrowserWindow, ipcMain } = require("electron");
const path = require("path");
const http = require("http");
const AuthManager = require("./authManager");
const UploadManager = require("./uploadManager");
const FileManager = require("./fileManager");
const log = require("electron-log");
class Application {
constructor() {
this.window = null;
this.authManager = new AuthManager();
this.uploadManager = new UploadManager();
this.fileManager = new FileManager();
this.server = null;
}
createWindow() {
this.window = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, "preload.js"),
},
});
this.window.on("closed", () => {
this.window = null;
});
}
async initialize() {
await app.whenReady();
this.createWindow();
this.setupEventHandlers();
this.setupIpcHandlers();
await this.ensureServerRunning();
await this.initializeWindow();
}
setupEventHandlers() {
app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit();
});
app.on("activate", async () => {
if (!this.window) {
this.createWindow();
await this.initializeWindow();
}
});
app.on("will-quit", () => {
if (this.server) this.server.close(() => log.info("Server closed."));
});
}
async ensureServerRunning() {
if (!this.server || !this.server.listening) {
await new Promise((resolve) => {
this.startLocalServer();
this.server.once("listening", resolve);
});
}
}
startLocalServer() {
this.server = http.createServer(async (req, res) => {
if (req.url.startsWith("/callback")) {
const url = `http://localhost:${this.server.address().port}${req.url}`;
try {
await this.authManager.handleCallback(url);
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Authentication successful! You can close this window.");
if (this.window) this.window.loadFile("index.html");
} catch (error) {
log.error("Authentication failed:", error);
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Authentication failed. Please try again.");
}
} else {
res.writeHead(404);
res.end();
}
});
this.server.listen(0, () => {
const port = this.server.address().port;
log.info(`Auth server listening on port ${port}`);
this.authManager.config.port = port;
this.authManager.redirectUri = `http://localhost:${port}/callback`;
});
}
async initializeWindow() {
try {
if (!this.window || this.window.isDestroyed()) {
this.createWindow();
}
const tokens = this.authManager.loadTokens();
if (tokens && this.authManager.isAccessTokenValid(tokens)) {
await this.window.loadFile("index.html");
} else if (tokens?.refreshToken) {
try {
await this.authManager.refreshAccessToken(tokens.refreshToken);
await this.window.loadFile("index.html");
} catch (error) {
log.error("Refresh failed:", error);
const authUrl = this.authManager.buildAuthUrl().toString();
await this.window.loadURL(authUrl);
}
} else {
const authUrl = this.authManager.buildAuthUrl().toString();
await this.window.loadURL(authUrl).catch(async () => {
log.info("Retrying auth initialization...");
await this.initializeWindow();
});
}
} catch (error) {
log.error("Window initialization failed:", error);
if (this.window || !this.window.isDestroyed()) {
this.createWindow();
}
await this.window.loadFile("error.html");
}
}
async handleCallback(url) {
try {
await this.authManager.handleCallback(url);
if (this.window) this.window.loadFile("index.html");
if (this.server) {
this.server.close(() => {
log.info("Server stopped after successful authentication.");
this.server = null;
});
}
} catch (error) {
log.error("Authentication failed:", error);
if (this.window) this.window.loadFile("error.html");
}
}
async handleLogout() {
this.authManager.logout();
if (this.server) {
await new Promise((resolve) => {
this.server.close(() => {
log.info("Server closed during logout");
this.server = null;
resolve();
});
});
}
if (this.window && !this.window.isDestroyed()) {
await this.window.webContents.session.clearStorageData();
await new Promise((resolve) => {
this.window.once("closed", () => {
this.window = null;
resolve();
});
this.window.close();
});
}
await this.ensureServerRunning();
await this.initializeWindow();
}
setupIpcHandlers() {
ipcMain.on("upload-file", async (event, filePath) => {
try {
let tokens = this.authManager.loadTokens();
if (!tokens || !this.authManager.isAccessTokenValid(tokens)) {
if (tokens?.refreshToken) {
await this.authManager.refreshAccessToken(tokens.refreshToken);
tokens = this.authManager.loadTokens();
} else {
await this.handleLogout();
throw new Error("Invalid or expired token");
}
}
await this.uploadManager.initialize(tokens.accessToken);
const uploadId = this.uploadManager.addUpload({
path: filePath,
name: path.basename(filePath),
});
this.uploadManager.setCallbacks({
onProgress: (upload) =>
event.reply("upload-progress", {
progress: upload.progress,
speed: upload.speed / (1024 * 1024), // Convert to MB/s
}),
onSuccess: (upload) =>
event.reply("upload-success", {
name: upload.file.name,
path: upload.file.path,
}),
onError: (upload, error) =>
event.reply("upload-error", {
message: error.message,
fileName: upload.file.name,
}),
});
await this.uploadManager.startUpload(uploadId);
} catch (error) {
if (error.message === "Invalid or expired token") {
await this.handleLogout();
}
event.reply("upload-error", { message: error.message });
}
});
ipcMain.on("cancel-upload", (event, filePath) => {
const upload = this.uploadManager.uploads.find(
(u) => u.file.path === filePath,
);
if (upload) this.uploadManager.cancelUpload(upload.id);
});
ipcMain.handle("list-files", async () => {
try {
const tokens = this.authManager.loadTokens();
if (!tokens || !this.authManager.isAccessTokenValid(tokens)) {
await this.handleLogout();
throw new Error("Invalid or expired token");
}
return await this.fileManager.listFiles(tokens.accessToken);
} catch (error) {
if (error.message === "Invalid or expired token") {
await this.handleLogout();
}
throw error;
}
});
ipcMain.handle("delete-file", async (_, fileId) => {
try {
const tokens = this.authManager.loadTokens();
if (!tokens || !this.authManager.isAccessTokenValid(tokens)) {
await this.handleLogout();
throw new Error("Invalid or expired token");
}
return await this.fileManager.deleteFile(fileId, tokens.accessToken);
} catch (error) {
if (error.message === "Invalid or expired token") {
await this.handleLogout();
}
throw error;
}
});
ipcMain.on("logout", () => this.handleLogout());
}
}
const mainApp = new Application();
mainApp.initialize().catch((error) => {
console.error("Failed to initialize application:", error);
app.quit();
});