-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
375 lines (333 loc) · 11.7 KB
/
Copy pathserver.js
File metadata and controls
375 lines (333 loc) · 11.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
const fs = require("fs");
const http = require("http");
const path = require("path");
const PORT = Number(process.env.PORT || 8797);
const ROOT = __dirname;
const WECHAT_COOKIE = process.env.WECHAT_COOKIE || "";
const WECHAT_PROFILE_DIR = path.join(ROOT, ".wechat-browser-profile");
const BROWSER_HEADLESS = process.env.HEADLESS !== "0";
const HTML_FILE =
fs.readdirSync(ROOT).find((name) => name.endsWith(".html")) ||
"layout-tool.html";
let browserContextPromise = null;
let shutdownTimer = null;
function cancelShutdownTimer() {
if (shutdownTimer) {
clearTimeout(shutdownTimer);
shutdownTimer = null;
}
}
async function closeBrowserContext() {
if (!browserContextPromise) return;
try {
const context = await browserContextPromise;
await context.close();
} catch {}
browserContextPromise = null;
}
function scheduleShutdown() {
cancelShutdownTimer();
shutdownTimer = setTimeout(async () => {
await closeBrowserContext();
server.close(() => process.exit(0));
setTimeout(() => process.exit(0), 1000).unref();
}, 3000);
shutdownTimer.unref();
}
function send(res, status, body, headers = {}) {
res.writeHead(status, {
"Access-Control-Allow-Origin": "*",
"Cache-Control": "no-store",
...headers,
});
res.end(body);
}
function sendJson(res, status, payload) {
send(res, status, JSON.stringify(payload), {
"Content-Type": "application/json; charset=utf-8",
});
}
function isAllowedArticleUrl(articleUrl) {
try {
const parsed = new URL(articleUrl);
return /^https?:$/.test(parsed.protocol);
} catch {
return false;
}
}
function isWechatBlockedContent(text) {
const content = text || "";
return (
/requiring CAPTCHA|CAPTCHA|WeChat Security/i.test(content) ||
content.includes("环境异常") ||
content.includes("完成验证") ||
content.includes("访问频率") ||
content.includes("请输入验证码") ||
content.includes("验证后即可继续访问")
);
}
function hasWechatArticleContent(html) {
return /id=["']js_content["']|class=["'][^"']*rich_media_content/i.test(
html || "",
);
}
function getWechatHeaders(userAgent) {
const headers = {
"User-Agent": userAgent,
Accept: "text/html,application/xhtml+xml",
};
if (WECHAT_COOKIE) headers.Cookie = WECHAT_COOKIE;
return headers;
}
async function fetchText(url, headers, timeout = 4500) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, {
headers,
redirect: "follow",
signal: controller.signal,
});
const text = await response.text();
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return text;
} finally {
clearTimeout(timer);
}
}
async function fetchBinary(url, headers, timeout = 12000) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, {
headers,
redirect: "follow",
signal: controller.signal,
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const contentType =
response.headers.get("content-type") || "application/octet-stream";
const buffer = Buffer.from(await response.arrayBuffer());
return { buffer, contentType };
} finally {
clearTimeout(timer);
}
}
async function fetchWechatDirect(articleUrl) {
const headersList = [
getWechatHeaders(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
),
getWechatHeaders(
"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.49 NetType/WIFI Language/zh_CN",
),
];
const attempts = headersList.map(async (headers) => {
const html = await fetchText(articleUrl, headers, 4500);
if (!html || html.length < 500) throw new Error("returned too little");
if (isWechatBlockedContent(html)) {
throw new Error("wechat verification page");
}
if (!hasWechatArticleContent(html)) {
throw new Error("article container not found");
}
return { html, source: "server-direct" };
});
return Promise.any(attempts);
}
async function getBrowserContext() {
if (!browserContextPromise) {
browserContextPromise = (async () => {
let chromium;
try {
({ chromium } = require("playwright"));
} catch {
throw new Error(
"Playwright is not installed. Run: npm install && npx playwright install chromium",
);
}
return chromium.launchPersistentContext(WECHAT_PROFILE_DIR, {
headless: BROWSER_HEADLESS,
locale: "zh-CN",
userAgent:
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
args: [
"--disable-dev-shm-usage",
"--disable-gpu",
],
extraHTTPHeaders: WECHAT_COOKIE
? {
Cookie: WECHAT_COOKIE,
Referer: "https://mp.weixin.qq.com/",
}
: {
Referer: "https://mp.weixin.qq.com/",
},
});
})();
}
return browserContextPromise;
}
async function fetchWechatBrowser(articleUrl) {
const context = await getBrowserContext();
const page = await context.newPage();
try {
await page.route("**/*", (route) => {
const type = route.request().resourceType();
if (["image", "media", "font"].includes(type)) {
route.abort();
} else {
route.continue();
}
});
await page.goto(articleUrl, {
waitUntil: "domcontentloaded",
timeout: 10000,
});
if (isWechatBlockedContent(await page.content())) {
console.log(
"WeChat verification page detected. Complete verification in the opened browser window.",
);
}
await page.waitForSelector("#js_content, .rich_media_content", {
timeout: 90000,
});
const html = await page.evaluate(() => {
document.querySelectorAll("img").forEach((img) => {
const dataSrc = img.getAttribute("data-src");
if (dataSrc && !img.getAttribute("src")) {
img.setAttribute("src", dataSrc);
}
});
return document.documentElement.outerHTML;
});
if (!html || html.length < 500) throw new Error("browser returned too little");
if (isWechatBlockedContent(html)) throw new Error("wechat verification page");
if (!hasWechatArticleContent(html)) throw new Error("article container not found");
return { html, source: "playwright-browser" };
} finally {
await page.close().catch(() => {});
}
}
async function fetchWechatArticle(articleUrl) {
const errors = [];
try {
return await fetchWechatDirect(articleUrl);
} catch (error) {
errors.push(`direct: ${error.message || error}`);
}
try {
return await fetchWechatBrowser(articleUrl);
} catch (error) {
errors.push(`browser: ${error.message || error}`);
}
throw new Error(errors.join("; "));
}
async function fetchWechatArticleFast(articleUrl) {
try {
return await fetchWechatDirect(articleUrl);
} catch (directError) {
try {
return await fetchWechatBrowser(articleUrl);
} catch (browserError) {
throw new Error(
`direct: ${directError.message || directError}; browser: ${browserError.message || browserError}`,
);
}
}
}
const server = http.createServer(async (req, res) => {
try {
if (!(req.url || "").startsWith("/api/shutdown")) {
cancelShutdownTimer();
}
if (req.method === "OPTIONS") {
send(res, 204, "", {
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
});
return;
}
const requestUrl = new URL(req.url, `http://${req.headers.host}`);
if (requestUrl.pathname === "/api/shutdown") {
sendJson(res, 200, { ok: true });
scheduleShutdown();
return;
}
if (requestUrl.pathname === "/api/cancel-shutdown") {
cancelShutdownTimer();
sendJson(res, 200, { ok: true });
return;
}
if (requestUrl.pathname === "/api/wechat") {
const articleUrl = requestUrl.searchParams.get("url") || "";
if (!isAllowedArticleUrl(articleUrl)) {
sendJson(res, 400, { error: "Invalid article URL" });
return;
}
try {
const startedAt = Date.now();
const result = await fetchWechatArticleFast(articleUrl);
sendJson(res, 200, {
html: result.html,
elapsedMs: Date.now() - startedAt,
source: result.source,
});
} catch (error) {
sendJson(res, 502, {
error: error.message || "WeChat article fetch failed",
});
}
return;
}
if (requestUrl.pathname === "/api/image-proxy") {
const imageUrl = requestUrl.searchParams.get("url") || "";
if (!isAllowedArticleUrl(imageUrl)) {
sendJson(res, 400, { error: "Invalid image URL" });
return;
}
try {
const { buffer, contentType } = await fetchBinary(
imageUrl,
getWechatHeaders(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
),
);
send(res, 200, buffer, {
"Content-Type": contentType,
"Cache-Control": "public, max-age=86400",
});
} catch (error) {
sendJson(res, 502, {
error: error.message || "Image proxy failed",
});
}
return;
}
const filePath =
requestUrl.pathname === "/"
? path.join(ROOT, HTML_FILE)
: path.join(ROOT, decodeURIComponent(requestUrl.pathname));
if (!filePath.startsWith(ROOT) || !fs.existsSync(filePath)) {
send(res, 404, "Not found", { "Content-Type": "text/plain" });
return;
}
const ext = path.extname(filePath).toLowerCase();
const contentType =
ext === ".html"
? "text/html; charset=utf-8"
: "application/octet-stream";
send(res, 200, fs.readFileSync(filePath), {
"Content-Type": contentType,
});
} catch (error) {
sendJson(res, 500, { error: error.message || "Server error" });
}
});
server.listen(PORT, () => {
console.log(`FoodTalks layout tool: http://localhost:${PORT}`);
});
process.on("SIGINT", async () => {
await closeBrowserContext();
process.exit(0);
});