-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
670 lines (578 loc) · 25.5 KB
/
Copy pathserver.ts
File metadata and controls
670 lines (578 loc) · 25.5 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
import express from "express";
import dotenv from "dotenv";
import { chromium, Browser, BrowserContext, Page } from "playwright";
import cors from "cors";
import path from "path";
import fs from "fs";
import { fileURLToPath } from "url";
import { GoogleGenAI } from "@google/genai";
import axios from "axios";
import * as cheerio from "cheerio";
import { YoutubeTranscript } from "youtube-transcript";
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = 3000;
app.use(cors());
app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ extended: true, limit: "50mb" }));
// 로컬 데이터베이스 (history.json, config.json) 설정
// Electron 앱에서 제공하는 USER_DATA_PATH를 사용하거나, 개발 환경에서는 __dirname을 사용합니다.
const userDataPath = process.env.USER_DATA_PATH || __dirname;
const HISTORY_FILE = path.join(userDataPath, "history.json");
const CONFIG_FILE = path.join(userDataPath, "config.json");
if (!fs.existsSync(HISTORY_FILE)) {
fs.writeFileSync(HISTORY_FILE, JSON.stringify([]));
}
if (!fs.existsSync(CONFIG_FILE)) {
fs.writeFileSync(CONFIG_FILE, JSON.stringify({}));
}
function saveToHistory(entry: any) {
try {
const data = JSON.parse(fs.readFileSync(HISTORY_FILE, "utf-8"));
entry.id = Date.now().toString();
entry.created_at = new Date().toISOString();
data.push(entry);
fs.writeFileSync(HISTORY_FILE, JSON.stringify(data, null, 2));
} catch (error) {
console.error("History Save Error:", error);
}
}
app.get("/api/history", (req, res) => {
try {
const data = JSON.parse(fs.readFileSync(HISTORY_FILE, "utf-8"));
res.json(data);
} catch (error) {
res.status(500).json({ error: "Failed to read history" });
}
});
app.post("/api/save-draft-history", (req, res) => {
try {
saveToHistory(req.body);
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: "Failed to save history" });
}
});
// 개인 설정 저장 및 불러오기 API
app.get("/api/settings", (req, res) => {
try {
const data = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf-8"));
res.json(data);
} catch (error) {
res.status(500).json({ error: "Failed to read settings" });
}
});
app.post("/api/settings", (req, res) => {
try {
const newSettings = req.body;
fs.writeFileSync(CONFIG_FILE, JSON.stringify(newSettings, null, 2));
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: "Failed to save settings" });
}
});
// 로깅 헬퍼 함수
const logToFile = (message: string) => {
const logMsg = `[${new Date().toISOString()}] ${message}\n`;
console.log(logMsg.trim());
const userDataPath = process.env.USER_DATA_PATH || __dirname;
fs.appendFileSync(path.join(userDataPath, 'server_execution.log'), logMsg);
};
// Playwright Browser 관리 상태
let globalBrowser: Browser | null = null;
let globalContext: BrowserContext | null = null;
let globalPage: Page | null = null;
let idleTimer: NodeJS.Timeout | null = null;
// 유휴 30초 후 브라우저 컨텍스트 정리
const scheduleContextClose = () => {
if (idleTimer) clearTimeout(idleTimer);
idleTimer = setTimeout(async () => {
logToFile("Idle Timeout Reached (30s) - Cleaning up Playwright Context...");
if (globalContext) {
await globalContext.close();
globalContext = null;
}
if (globalBrowser) {
await globalBrowser.close();
globalBrowser = null;
}
globalPage = null;
logToFile("Playwright Browser closed.");
}, 30000); // 30 seconds
};
// 컨텍스트 정리 타이머 취소
const cancelContextClose = () => {
if (idleTimer) {
clearTimeout(idleTimer);
idleTimer = null;
logToFile("Batch Upload received - Canceled context close timer.");
}
};
async function getOrCreatePage() {
cancelContextClose(); // 요청이 들어오면 유휴 타이머 취소
if (!globalContext) {
logToFile("Launching new browser context...");
const userDataPath = process.env.USER_DATA_PATH || __dirname;
const userDataDir = path.join(userDataPath, 'naver_profile');
globalContext = await chromium.launchPersistentContext(userDataDir, {
headless: false,
channel: 'chrome',
viewport: { width: 1280, height: 800 },
permissions: ['clipboard-read', 'clipboard-write']
});
globalBrowser = globalContext.browser() || null;
globalPage = null;
}
if (!globalPage || globalPage.isClosed()) {
logToFile("Opening new page as globalPage...");
const pages = globalContext.pages();
if (pages.length > 0) {
logToFile("Reusing existing page from context...");
globalPage = pages[0];
} else {
globalPage = await globalContext.newPage();
}
// 페이지 이탈 경고 무시
globalPage.on('dialog', async (dialog) => {
logToFile("Dialog appeared (e.g. beforeunload). Accepting automatically.");
await dialog.accept();
});
} else {
logToFile("Reusing existing globalPage tab.");
}
return { context: globalContext, page: globalPage };
}
// 2. 외부 링크 스크래핑 API
app.post("/api/fetch-links", async (req, res) => {
const { urls } = req.body;
if (!urls || !Array.isArray(urls)) {
return res.status(400).json({ error: "Invalid URLs provided" });
}
try {
const results = [];
for (const url of urls) {
logToFile(`Fetching content from: ${url}`);
if (url.includes('youtube.com') || url.includes('youtu.be')) {
try {
const transcript = await YoutubeTranscript.fetchTranscript(url);
const fullText = transcript.map(t => t.text).join(' ');
const truncatedText = fullText.substring(0, 10000); // 1만 자까지 (영상 대본은 정보량이 많으므로)
results.push({ url, content: `[유튜브 영상 대본]\n${truncatedText}`, success: true });
logToFile(`Successfully fetched ${truncatedText.length} characters of YouTube transcript from ${url}`);
} catch (ytErr: any) {
logToFile(`Failed to fetch YouTube transcript from ${url}: ${ytErr.message}`);
results.push({ url, error: "Failed to fetch YouTube transcript (대본이 제공되지 않는 영상일 수 있습니다)", success: false });
}
continue;
}
try {
const response = await axios.get(url, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
},
timeout: 10000 // 10초 타임아웃
});
const html = response.data;
const $ = cheerio.load(html);
// 노이즈 제거: 광고, 사이드바, 댓글, 관련기사, 네비게이션 등
$('script, style, noscript, nav, footer, header, aside').remove();
$('[class*="relate"], [class*="recommend"], [class*="popular"], [class*="most"], [class*="comment"], [class*="ad-"], [class*="banner"], [id*="relate"], [id*="comment"], [id*="ad"]').remove();
// 기사 본문 우선 추출: 시멘틱 태그 → 뉴스사 공통 클래스 → body 전체 순서로 시도
const articleSelectors = [
'article',
'main',
'[itemprop="articleBody"]',
'.article-body', '.article_body', '.articleBody',
'.news-content', '.news_content', '.newsContent',
'.article-text', '.article_text',
'.content-text', '.content_text',
'.story-body', '.story_body',
'.post-content', '.post_content',
'#articleBody', '#article-body', '#newsContent', '#articeBody',
'.view-content', '#content'
];
let text = '';
for (const sel of articleSelectors) {
const el = $(sel);
if (el.length > 0) {
text = el.text().replace(/\s+/g, ' ').trim();
if (text.length > 300) break; // 충분한 본문을 찾으면 중단
}
}
// 모든 시도 실패 시 body 전체 사용
if (text.length < 300) {
text = $('body').text().replace(/\s+/g, ' ').trim();
}
// 8000자로 확대 (기사 전문 전달 목적)
const truncatedText = text.substring(0, 8000);
results.push({ url, content: truncatedText, success: true });
logToFile(`Successfully fetched ${truncatedText.length} characters from ${url}`);
} catch (err: any) {
logToFile(`Failed to fetch ${url}: ${err.message}`);
results.push({ url, error: "Failed to fetch content", success: false });
}
}
res.json({ results });
} catch (error: any) {
logToFile(`Fetch links error: ${error.message}`);
res.status(500).json({ error: error.message });
}
});
// 3. 네이버 블로그 자동 임시저장 API
app.post("/api/upload-draft", async (req, res) => {
const logToFileLocally = (msg: string) => {
logToFile("--- New Draft Upload Request --- " + msg);
};
logToFileLocally("");
const { title, body, keywords, topTemplate, bottomTemplate, useTopSeparator, useBottomSeparator, templateMode } = req.body;
if (!title) {
return res.status(400).json({ error: "Missing required fields" });
}
// --- (snip) ... Browser/Naver Login logic remains completely untouched until typing ---
try {
let { context, page } = await getOrCreatePage();
logToFile("Navigating to Naver Main Page (or waiting if already there)...");
await page.goto('https://www.naver.com/', { waitUntil: 'domcontentloaded' });
// 로그인 확인 (로그아웃 텍스트로 판단)
logToFile("로그인 상태를 확인합니다...");
const isLoggedOut = !await page.locator('text="로그아웃"').first().isVisible().catch(() => false);
if (isLoggedOut || page.url().includes('nidlogin.login')) {
logToFile("로그인이 필요합니다. 네이버 웹페이지 우측 상단에서 직접 로그인을 진행해주세요...");
// 로그인 후 "로그아웃" 글자가 나타날 때까지 무제한 대기
await page.waitForFunction(() => {
return document.body.innerText.includes('로그아웃');
}, { timeout: 300000 }).catch(() => { });
logToFile("로그인 완료 감지!");
await page.waitForTimeout(2000); // UI 렌더링 대기
} else {
logToFile("이미 네이버에 로그인 되어 있습니다.");
}
logToFile("우측 내 정보 위젯에서 '블로그' 탭을 클릭합니다...");
try {
// 1. 위젯 영역(#account) 안에서 "블로그"라는 텍스트를 찾아 클릭
const accountWidget = page.locator('#account, div[class*="MyView-module"]').first();
// 블로그 탭을 명시적으로 클릭
const blogTab = accountWidget.locator('a:has-text("블로그"), button:has-text("블로그"), span:has-text("블로그")').filter({ hasText: /^블로그$/ }).first();
if (await blogTab.isVisible()) {
await blogTab.click();
} else {
await accountWidget.locator('text="블로그"').first().click();
}
logToFile("위젯 하단의 '글쓰기' 항목이 갱신되길 기다립니다...");
await page.waitForTimeout(1500);
logToFile("위젯 하단 '글쓰기' 버튼을 클릭하여 새 탭을 엽니다...");
// 2. "글쓰기" 클릭 (보통 새 탭으로 띄워짐)
const [newPage] = await Promise.all([
context.waitForEvent('page', { timeout: 10000 }),
accountWidget.locator('text="글쓰기"').first().click()
]);
if (newPage) {
logToFile("새 탭에서 블로그 글쓰기 에디터가 열렸습니다!");
page = newPage;
}
} catch (e) {
logToFile("네이버 메인 화면에서 UI 클릭 실패. 차선책으로 바로 이동합니다.");
await page.goto(`https://blog.naver.com/postwrite`, {
waitUntil: 'domcontentloaded',
referer: 'https://www.naver.com/'
});
}
// SmartEditor iframe 로드 대기
logToFile("Waiting for SmartEditor iframe...");
await page.waitForSelector('iframe#mainFrame', { timeout: 30000 });
const frameElement = await page.$('iframe#mainFrame');
const frame = await frameElement?.contentFrame();
if (!frame) {
throw new Error("Cannot find SmartEditor iframe");
}
logToFile("Writing Title and Content in SmartEditor...");
try {
// typeParagraphs와 insertSeparator 함수 정의를 상단으로 이동
const typeParagraphs = async (text: string) => {
if (!text) return;
// document.execCommand('bold')로 볼드 직접 제어 (버튼 selector 불필요)
let isBoldOn = false;
const setBold = async (target: boolean) => {
if (isBoldOn !== target) {
await frame.evaluate(() => document.execCommand('bold'));
await page.waitForTimeout(50);
isBoldOn = target;
}
};
const paragraphs = text.split('\n');
for (const p of paragraphs) {
// 단락 시작 전 항상 볼드 OFF 보장
await setBold(false);
const trimmed = p.trim();
if (trimmed === '') {
await page.keyboard.press('Enter');
continue;
}
const parts = trimmed.split('**');
for (let i = 0; i < parts.length; i++) {
const partContent = parts[i];
const needBold = i % 2 !== 0;
await setBold(needBold);
if (partContent !== '') {
await page.keyboard.type(partContent, { delay: 10 });
}
}
// 단락 끝 항상 볼드 OFF 보장
await setBold(false);
await page.keyboard.press('Enter');
}
};
const insertSeparator = async () => {
logToFile("Inserting Naver separator...");
// 네이버 에디터 툴바의 구분선 메뉴 클릭 (보통 상단 툴바에 위치)
const separatorBtn = frame.locator('button.se-divider-button, .se-toolbar-button-divider button').first();
if (await separatorBtn.isVisible()) {
await separatorBtn.click();
await page.waitForTimeout(500); // 렌더링 기다림
await page.keyboard.press('Enter'); // 새로 내려온 줄로 커서 이동
} else {
logToFile("WARNING: Separator button not visible. Skipping.");
}
};
// 팝업이 있다면 무시/닫기
await frame.click('.se-popup-button-cancel', { timeout: 2000 }).catch(() => logToFile("이전 글 복원 팝업 없음"));
if (templateMode === 'naver') {
logToFile("Naver Template Mode Selected");
// 1. 템플릿 버튼 클릭 (에디터 프레임 외부, 상단 툴바에 있을 수 있음. 우측에 있을 경우 대비)
// 보통 네이버 스마트에디터의 템플릿 버튼은 우측 상단 '템플릿'
logToFile("Clicking '템플릿' button...");
try {
// 메인 페이지(부모창)에서 '템플릿' 버튼 찾기 대신 프레임 내부에서 찾기
const templateBtn = frame.locator('button:has-text("템플릿"), span:has-text("템플릿")').filter({ hasText: /^템플릿$/ }).first();
await templateBtn.click();
} catch (e) {
logToFile("'템플릿' 버튼을 찾을 수 없습니다.");
throw new Error("네이버 '템플릿' 버튼 클릭에 실패했습니다.");
}
// 2. '내 템플릿' 탭 클릭
logToFile("Clicking '내 템플릿' tab...");
await page.waitForTimeout(1000);
try {
const myTemplateTab = frame.locator('button, a').filter({ hasText: '내 템플릿' }).first();
await myTemplateTab.click();
await page.waitForTimeout(1000); // 목록 렌더링 대기
} catch (e) {
logToFile("내 템플릿 탭을 찾을 수 없습니다.");
throw new Error("'내 템플릿' 탭을 찾을 수 없습니다.");
}
// HTML dump for debugging after opening templates tab
const frameHtml = await frame.content();
const dumpPath = path.join(userDataPath, 'naver_templates_dump.html');
fs.writeFileSync(dumpPath, frameHtml);
logToFile("Dumped Naver Templates HTML to " + dumpPath);
// 3. 첫번째 템플릿 클릭
logToFile("Selecting the first template...");
try {
// .se-template-list-item 또는 ul/li 안의 첫 번째 버튼 클릭 (구조 탐색)
// 보통 목록은 .se-template-list 안에 li, button 형태입니다.
const firstTemplateBtn = frame.locator('ul.se-doc-template-list li.se-doc-template-item a.se-doc-template').first();
if (await firstTemplateBtn.isVisible({ timeout: 2000 })) {
await firstTemplateBtn.click();
} else {
// 다른 선택자 시도
const fallbackFirstItem = frame.locator('text="내 템플릿"').locator('..').locator('..').locator('li').first();
await fallbackFirstItem.click();
}
logToFile("Wait for template to load in editor...");
await page.waitForTimeout(3000); // 템플릿이 에디터 패널에 로딩 대기
// 사용자의 구체적인 요구사항: 템플릿쪽 x 버튼 눌러서 템플릿 닫기
logToFile("Closing template selection panel...");
try {
// 스마트에디터의 템플릿 패널 닫기 X 버튼
const closeBtn = frame.locator('button.se-doc-template-close-button, button[title*="닫기"], .se-help-panel-close-button').first();
if (await closeBtn.isVisible({ timeout: 2000 })) {
await closeBtn.click();
logToFile("Successfully closed template panel.");
}
} catch (e) {
logToFile("Close template panel button not found, continuing...");
}
await page.waitForTimeout(500); // 패널 닫히는 애니메이션 대기
} catch (e) {
logToFile("첫번째 템플릿 클릭 실패.");
throw new Error("저장된 '내 템플릿'이 하나도 없거나 불러오기에 실패했습니다.");
}
// 4. 제목 바꾸기
logToFile("Typing new title...");
const titleSelector = '.se-documentTitle, .se-title-text, [placeholder="제목"]';
await frame.waitForSelector(titleSelector, { timeout: 15000 });
const titleLoc = frame.locator(titleSelector).first();
await titleLoc.click();
await page.keyboard.press('ControlOrMeta+a');
await page.keyboard.press('Backspace');
await page.waitForTimeout(100);
await page.keyboard.type(title, { delay: 50 });
// 5. [원고] 텍스트 찾아서 대체하기
// 5. [원고] 텍스트 찾아서 대체하기
logToFile("Locating '[원고]' placeholder and replacing...");
const found = await frame.evaluate(() => {
const selection = window.getSelection();
if (selection) selection.removeAllRanges();
// wrapAround=true 로 문서 전체 검색
const isFound = (window as any).find('[원고]', false, false, true);
if (isFound && selection && selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
// 플레이라이트 자체적인 좌표 클릭 타겟 확보용 임시 span
const span = document.createElement('span');
span.id = 'playwright-target-node';
span.textContent = ' '; // 가시적 클릭 가능 영역 제공
range.deleteContents();
range.insertNode(span);
// 브라우저 뷰포트를 요소 중앙으로 부드럽게 스크롤
span.scrollIntoView({ behavior: 'smooth', block: 'center' });
return true;
}
return false;
});
if (found) {
logToFile("Found '[원고]', injected clickable layout anchor. Waiting for visual scroll...");
await page.waitForTimeout(1000); // 뷰스크롤 이동 모션 대기 및 시각적 안정
logToFile("Clicking exact coordinate to realign Playwright caret...");
const targetLoc = frame.locator('#playwright-target-node').first();
await targetLoc.click();
// 백스페이스로 노드를 지우면 Playwright가 포커스를 잃고 문서 맨 위로 점프해버립니다.
// 따라서 스페이스바 한 칸은 남겨두고 바로 타자를 칩니다.
await page.waitForTimeout(200);
// 그 자리에서 곧바로 타자 수행
await typeParagraphs(body);
// 디버깅용 스크린샷 창단
const debugScreenshotPath = path.join(userDataPath, 'debug_after_typing.png');
await page.screenshot({ path: debugScreenshotPath, fullPage: true });
} else {
logToFile("WARNING: '[원고]' text not found in the template. Typing at current cursor position instead.");
await typeParagraphs(body);
}
} else {
// 기존 '직접 작성 (Custom)' 모드 로직
logToFile("Custom Mode Selected");
logToFile("Waiting for title textbox...");
const titleSelector = '.se-documentTitle, .se-title-text, [placeholder="제목"]';
await frame.waitForSelector(titleSelector, { timeout: 15000 });
logToFile("Found title textbox, clicking...");
await frame.locator(titleSelector).first().click();
logToFile("Typing title...");
await page.keyboard.type(title, { delay: 50 });
// 본문 내용 입력 영역 클릭 (포커스 이동)
logToFile("Pressing Tab to focus body...");
await page.keyboard.press('Tab');
await page.waitForTimeout(500);
// 1. 상단 템플릿
if (topTemplate) {
logToFile("Typing Top Template...");
await typeParagraphs(topTemplate);
}
// 2. 상단 구분선
if (useTopSeparator) {
await insertSeparator();
}
// 3. AI 본문
logToFile("Typing Body...");
await typeParagraphs(body);
// 4. 하단 구분선
if (useBottomSeparator) {
await insertSeparator();
}
// 5. 하단 템플릿
if (bottomTemplate) {
logToFile("Typing Bottom Template...");
await typeParagraphs(bottomTemplate);
}
}
logToFile("Clicking Save Draft...");
const evaluateClickSave = async (ctx: any) => {
return await ctx.evaluate(() => {
const elements = Array.from(document.querySelectorAll('button, a, span'));
for (const el of elements) {
const text = el.textContent?.trim() || '';
// "저장" 이라는 단어로 시작하는 버튼/텍스트 찾기 (예: "저장", "저장 | 0")
if (text.startsWith('저장') && el.getBoundingClientRect().width > 0) {
const rect = el.getBoundingClientRect();
// 화면 위쪽에 위치한 버튼인지 확인 (에디터 상단 툴바)
if (rect.top >= 0 && rect.top < 150) {
let targetToClick = el;
// 만약 span 이면 부모 버튼을 클릭하도록 처리
if (el.tagName.toLowerCase() === 'span') {
const parentBtn = el.closest('button, a');
if (parentBtn) targetToClick = parentBtn;
}
(targetToClick as HTMLElement).click();
return true;
}
}
}
return false;
});
};
let clickedSave = false;
try {
logToFile("Looking for Save button in frame...");
clickedSave = await evaluateClickSave(frame);
} catch (e) { }
if (!clickedSave) {
logToFile("Save button not found in frame. Trying main page...");
try {
clickedSave = await evaluateClickSave(page);
} catch (e) { }
}
if (clickedSave) {
logToFile("Successfully found and clicked 'Save' button.");
await page.waitForTimeout(5000);
} else {
throw new Error("우측 상단의 '저장' 버튼을 찾을 수 없습니다.");
}
logToFile("Draft saved successfully.");
if (!req.body.skipHistorySave) {
saveToHistory({
keyword: keywords && keywords.length > 0 ? keywords[0] : (title || "Unknown"),
title,
body
});
}
res.json({ success: true, message: "Naver Blog Draft Saved Successfully" });
} catch (innerError: any) {
logToFile("Inner error encountered during editor actions: " + innerError.message);
if (frame) {
logToFile("Captured error frame content, but not saving to file to avoid watcher triggers.");
}
throw innerError;
}
} catch (error: any) {
logToFile("Playwright Error: " + error.message + "\n" + error.stack);
res.status(500).json({ error: error.message });
} finally {
if (globalContext) {
for (const p of globalContext.pages()) {
if (p !== globalPage && !p.isClosed()) {
logToFile("Closing temporary editor page tab...");
await p.close().catch(() => { });
}
}
}
logToFile("Scheduling browser context close timer...");
scheduleContextClose();
}
});
async function startServer() {
// Vite middleware for development
if (process.env.NODE_ENV !== "production") {
const { createServer: createViteServer } = await import("vite");
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
app.use(vite.middlewares);
} else {
app.use(express.static(path.join(__dirname, "../dist")));
}
app.listen(PORT, "0.0.0.0", () => {
console.log(`Server running on http://localhost:${PORT}`);
});
}
startServer();