-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
595 lines (516 loc) · 17.7 KB
/
main.js
File metadata and controls
595 lines (516 loc) · 17.7 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
const {
app,
BrowserWindow,
BrowserView,
ipcMain,
dialog,
shell,
} = require("electron");
const path = require("path");
const fs = require("fs");
let mainWindow;
let config = {};
let serverUrl = null;
function loadConfig() {
try {
const configPath = path.join(__dirname, "config.json");
const configData = fs.readFileSync(configPath, "utf8");
config = JSON.parse(configData);
} catch (error) {
console.error("Failed to load config:", error);
config = {
appName: "Local Network Browser",
scanPort: 8800,
};
}
}
async function createWindow() {
mainWindow = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 800,
minHeight: 600,
title: config.appName || "Local Network Browser",
autoHideMenuBar: true, // 메뉴바 자동 숨김 (Alt 키로 토글 가능)
webPreferences: {
preload: path.join(__dirname, "preload.js"),
contextIsolation: true,
nodeIntegration: false,
},
icon: path.join(__dirname, "build/icon.png"),
backgroundColor: "#ffffff",
});
// 항상 스캔 페이지로 시작
mainWindow.loadFile("index.html");
mainWindow.on("closed", () => {
mainWindow = null;
});
}
// 수동 다운로드 처리 함수
async function handleManualDownload(url, fileName, webContents) {
const { net } = require("electron");
try {
// 저장 위치 선택 다이얼로그
const { canceled, filePath } = await dialog.showSaveDialog(mainWindow, {
title: "파일 저장",
defaultPath: path.join(app.getPath("downloads"), fileName),
buttonLabel: "저장",
properties: ["createDirectory", "showOverwriteConfirmation"],
});
if (canceled || !filePath) {
console.log(`[Download] User canceled download: ${fileName}`);
return;
}
console.log(`[Download] Starting manual download to: ${filePath}`);
// 다운로드 시작
const request = net.request(url);
// 세션 쿠키 전달
const cookies = await webContents.session.cookies.get({});
if (cookies.length > 0) {
const cookieString = cookies
.map((c) => `${c.name}=${c.value}`)
.join("; ");
request.setHeader("Cookie", cookieString);
}
let receivedBytes = 0;
let totalBytes = 0;
const chunks = [];
request.on("response", (response) => {
totalBytes = parseInt(response.headers["content-length"] || "0");
console.log(`[Download] Response received, size: ${totalBytes} bytes`);
response.on("data", (chunk) => {
chunks.push(chunk);
receivedBytes += chunk.length;
const percent =
totalBytes > 0 ? Math.round((receivedBytes / totalBytes) * 100) : 0;
console.log(
`[Download] Progress: ${percent}% (${receivedBytes}/${totalBytes} bytes)`,
);
});
response.on("end", () => {
const buffer = Buffer.concat(chunks);
fs.writeFileSync(filePath, buffer);
console.log(`[Download] Completed: ${fileName}`);
console.log(`[Download] Saved to: ${filePath}`);
// Finder에서 파일 위치 표시
shell.showItemInFolder(filePath);
});
response.on("error", (err) => {
console.error(`[Download] Response error:`, err);
});
});
request.on("error", (err) => {
console.error(`[Download] Request error:`, err);
});
request.end();
} catch (error) {
console.error(`[Download] Error:`, error);
}
}
// BrowserView로 서버 로드
function loadServerInBrowserView(serverUrl) {
// 기존 view가 있으면 제거
if (mainWindow.getBrowserView()) {
mainWindow.removeBrowserView(mainWindow.getBrowserView());
}
// 새 BrowserView 생성
const view = new BrowserView({
webPreferences: {
contextIsolation: true, // PDF.js 등 브라우저 API와의 충돌 방지
nodeIntegration: false,
partition: "persist:main", // 세션 유지
plugins: true, // PDF 뷰어 플러그인 활성화
sandbox: false, // 파일 업로드 지원
webSecurity: false, // 로컬 서버 리소스 접근을 위해 비활성화
allowRunningInsecureContent: true, // HTTP 콘텐츠 허용
},
});
mainWindow.setBrowserView(view);
// 창 크기에 맞춰 BrowserView 크기 설정 (타이틀바 제외한 콘텐츠 영역)
const contentBounds = mainWindow.getContentBounds();
view.setBounds({
x: 0,
y: 0,
width: contentBounds.width,
height: contentBounds.height,
});
view.setAutoResize({ width: true, height: true });
// 세션 쿠키 영속화 로직
view.webContents.session.webRequest.onHeadersReceived((details, callback) => {
const setCookieHeaders =
details.responseHeaders["Set-Cookie"] ||
details.responseHeaders["set-cookie"];
if (setCookieHeaders) {
const updatedCookies = setCookieHeaders.map((cookieStr) => {
if (!cookieStr.match(/expires=/i) && !cookieStr.match(/max-age=/i)) {
return `${cookieStr}; Max-Age=2592000`; // 30일
}
return cookieStr;
});
details.responseHeaders["Set-Cookie"] = updatedCookies;
}
callback({ responseHeaders: details.responseHeaders });
});
// 서버 URL 로드
view.webContents.loadURL(serverUrl);
// 다운로드 URL 패턴 감지 및 처리
view.webContents.on("will-navigate", (event, url) => {
// 다운로드로 보이는 URL 패턴 감지
if (
url.includes("/download") ||
(url.includes("/api/docs/") && url.includes("/files/"))
) {
console.log(`[Download] Detected download URL: ${url}`);
// will-download 이벤트가 트리거되도록 허용
}
});
// 파일 다운로드 처리 (자동 다운로드)
view.webContents.session.on("will-download", (event, item, webContents) => {
const fileName = item.getFilename();
const url = item.getURL();
const downloadsPath = app.getPath("downloads");
const savePath = path.join(downloadsPath, fileName);
console.log(`[Download] Starting download: ${fileName}`);
console.log(`[Download] URL: ${url}`);
console.log(`[Download] Save path: ${savePath}`);
// 다운로드 폴더에 자동 저장
item.setSavePath(savePath);
// 다운로드 진행 상황
item.on("updated", (event, state) => {
if (state === "interrupted") {
console.log(`[Download] Interrupted: ${fileName}`);
} else if (state === "progressing") {
if (item.isPaused()) {
console.log(`[Download] Paused: ${fileName}`);
} else {
const received = item.getReceivedBytes();
const total = item.getTotalBytes();
const percent = total > 0 ? Math.round((received / total) * 100) : 0;
console.log(
`[Download] Progress: ${fileName} - ${percent}% (${received}/${total} bytes)`,
);
}
}
});
// 다운로드 완료
item.once("done", (event, state) => {
if (state === "completed") {
const savedPath = item.getSavePath();
console.log(`[Download] Completed: ${fileName}`);
console.log(`[Download] Saved to: ${savedPath}`);
// Finder에서 파일 위치 표시
shell.showItemInFolder(savedPath);
} else {
console.log(`[Download] Failed: ${fileName}, state: ${state}`);
}
});
});
// 새 창 열기 처리
view.webContents.setWindowOpenHandler(({ url }) => {
// 다운로드 URL 감지
if (
url.includes("/download") ||
(url.includes("/files/") && url.includes("/api/docs/"))
) {
console.log(`[Download] Intercepting download URL: ${url}`);
// 파일명 추출 시도
const urlParts = url.split("/");
const fileName = urlParts[urlParts.length - 1] || "download";
// 다운로드 처리
handleManualDownload(url, fileName, view.webContents);
return { action: "deny" }; // 새 창 열기 차단
}
// 외부 링크 처리
if (
url.startsWith("http") &&
!url.includes("localhost") &&
!url.includes("192.168")
) {
shell.openExternal(url);
return { action: "deny" };
}
return { action: "allow" };
});
// 권한 처리
view.webContents.session.setPermissionRequestHandler(
(webContents, permission, callback) => {
const allowedPermissions = [
"media",
"mediaKeySystem",
"geolocation",
"notifications",
"camera",
"microphone",
"clipboard-read",
"clipboard-write",
];
callback(allowedPermissions.includes(permission));
},
);
// 개발자 도구 (디버깅용) - 프로덕션에서는 비활성화
// view.webContents.openDevTools();
// 콘솔 메시지 로깅
view.webContents.on(
"console-message",
(event, level, message, line, sourceId) => {
console.log(`[BrowserView Console]: ${message}`);
},
);
// 파일 업로드 이벤트 모니터링
view.webContents.on("did-finish-load", () => {
console.log("Page loaded, injecting debug code...");
view.webContents
.executeJavaScript(
`
console.log('Debug code injected');
// PDF.js를 위한 URL.parse polyfill (Node.js API를 브라우저 API로 변환)
if (typeof URL !== 'undefined' && !URL.parse) {
URL.parse = function(urlString, baseURL) {
try {
return new URL(urlString, baseURL);
} catch (e) {
console.error('URL.parse polyfill error:', e);
return null;
}
};
console.log('URL.parse polyfill injected for PDF.js compatibility');
}
// 다운로드 링크 가로채기
document.addEventListener('click', function(e) {
const target = e.target.closest('a, button');
if (target) {
const href = target.getAttribute('href') || target.dataset.href || '';
const onclick = target.getAttribute('onclick') || '';
// 다운로드 링크 감지
if (href.includes('/download') || onclick.includes('download')) {
console.log('[Download Intercept] Download link clicked:', href || onclick);
e.preventDefault();
e.stopPropagation();
// Electron에 다운로드 요청 전달 (새 창으로)
if (href) {
window.open(href, '_blank');
}
return false;
}
}
}, true);
// 파일 입력 모니터링
document.addEventListener('change', function(e) {
if (e.target.type === 'file') {
console.log('File selected:', e.target.files[0]);
console.log('File input name:', e.target.name);
console.log('File size:', e.target.files[0]?.size);
console.log('File type:', e.target.files[0]?.type);
}
}, true);
// Form submit 모니터링
document.addEventListener('submit', function(e) {
console.log('Form submitted:', e.target);
const formData = new FormData(e.target);
for (let [key, value] of formData.entries()) {
console.log('FormData:', key, value);
}
}, true);
// XMLHttpRequest 모니터링
const originalXHRSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(data) {
console.log('XHR Send to:', this._url || 'unknown');
if (data instanceof FormData) {
console.log('Sending FormData');
// FormData 내용 확인
for (let [key, value] of data.entries()) {
if (value instanceof File) {
console.log('FormData file:', key, value.name, value.size, value.type);
} else {
console.log('FormData field:', key, value);
}
}
}
// 에러 처리 추가
this.addEventListener('error', function() {
console.error('XHR Error:', this.status, this.statusText);
});
this.addEventListener('load', function() {
if (this.status >= 400) {
console.error('XHR Response Error:', this.status, this.responseText);
} else {
console.log('XHR Success:', this.status);
}
});
return originalXHRSend.call(this, data);
};
// XHR open 모니터링
const originalXHROpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
this._url = url;
console.log('XHR Open:', method, url);
return originalXHROpen.apply(this, arguments);
};
// Fetch API 모니터링
const originalFetch = window.fetch;
window.fetch = function(url, options) {
console.log('Fetch:', url, options?.method || 'GET');
if (options?.body instanceof FormData) {
console.log('Fetch with FormData');
}
return originalFetch.apply(this, arguments);
};
console.log('File inputs found:', document.querySelectorAll('input[type="file"]').length);
`,
)
.catch((err) => console.error("Failed to inject debug code:", err));
});
// 네트워크 요청 모니터링
view.webContents.session.webRequest.onBeforeRequest((details, callback) => {
if (details.method === "POST" || details.uploadData) {
console.log(`[Network] ${details.method} ${details.url}`);
if (details.uploadData) {
const totalSize = details.uploadData
.map((d) => d.bytes?.length || 0)
.reduce((a, b) => a + b, 0);
console.log("[Network] Upload data size:", totalSize, "bytes");
// 업로드 데이터 상세 정보
details.uploadData.forEach((data, index) => {
if (data.bytes) {
console.log(
`[Network] Upload part ${index}: ${data.bytes.length} bytes`,
);
// 처음 100바이트만 출력 (디버깅용)
const preview = Buffer.from(data.bytes).toString(
"utf8",
0,
Math.min(100, data.bytes.length),
);
console.log(`[Network] Preview: ${preview}...`);
}
if (data.file) {
console.log(`[Network] File: ${data.file}`);
}
});
}
}
callback({});
});
// Response 모니터링 추가 (모든 요청)
view.webContents.session.webRequest.onCompleted((details) => {
// PDF 파일이나 에러 응답 로깅
if (details.url.includes(".pdf") || details.statusCode >= 400) {
console.log(
`[Network] ${details.method} ${details.url} - Status: ${details.statusCode}`,
);
if (details.statusCode === 404) {
console.log("[Network] 404 Error - File not found:", details.url);
}
}
// POST 요청의 성공 응답도 로깅 (파일 업로드 확인용)
if (details.method === "POST" && details.statusCode < 400) {
console.log(
`[Network] POST Success: ${details.url} - Status: ${details.statusCode}`,
);
}
});
// 에러 처리
view.webContents.on("crashed", (event, killed) => {
console.error("WebContents crashed:", killed);
});
}
// 네트워크 스캔 및 서버 찾기
ipcMain.handle("scan-and-connect", async () => {
const scanner = require("./network-scanner");
const port = config.scanPort || 8800;
try {
// 서버 찾기 (단일 포트만 스캔)
const foundServer = await scanner.findServer(port);
if (foundServer) {
serverUrl = foundServer;
// 창 제목을 앱 이름으로 설정
if (mainWindow) {
mainWindow.setTitle(config.appName);
}
// BrowserView로 서버 로드
loadServerInBrowserView(foundServer);
return { success: true, url: foundServer };
} else {
return { success: false, message: `No server found on port ${port}` };
}
} catch (error) {
console.error("Scan failed:", error);
return { success: false, error: error.message };
}
});
// 설정 가져오기
ipcMain.handle("get-config", () => {
return config;
});
// 재시도
ipcMain.handle("retry-scan", async () => {
// 로딩 페이지로 돌아가기
mainWindow.loadFile("index.html");
// 다시 스캔 시작
return await ipcMain._events["scan-and-connect"][0]();
});
// 저장된 서버 URL 가져오기 (내부 사용)
async function getSavedServerInternal() {
try {
const savedPath = path.join(app.getPath("userData"), "saved-server.json");
if (fs.existsSync(savedPath)) {
const data = fs.readFileSync(savedPath, "utf8");
return JSON.parse(data);
}
} catch (error) {
console.error("Failed to load saved server:", error);
}
return null;
}
// 저장된 서버 URL 가져오기 (IPC)
ipcMain.handle("get-saved-server", () => {
return getSavedServerInternal();
});
// 저장된 서버로 직접 연결 (스캔 없이)
ipcMain.handle("connect-to-saved-server", async (event, url) => {
try {
serverUrl = url;
// 창 제목을 앱 이름으로 설정
if (mainWindow) {
mainWindow.setTitle(config.appName);
}
// BrowserView로 서버 로드
loadServerInBrowserView(url);
return { success: true, url: url };
} catch (error) {
console.error("Failed to connect to saved server:", error);
return { success: false, error: error.message };
}
});
// 서버 URL 저장
ipcMain.handle("save-server", (event, url) => {
try {
const savedPath = path.join(app.getPath("userData"), "saved-server.json");
fs.writeFileSync(
savedPath,
JSON.stringify({
url: url,
lastSeen: new Date().toISOString(),
}),
"utf8",
);
return { success: true };
} catch (error) {
console.error("Failed to save server:", error);
return { success: false };
}
});
app.whenReady().then(async () => {
loadConfig();
await createWindow();
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});