@acanthis-dec/linovelib 1.4.3 → 1.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +7 -0
- package/dist/index.mjs +167 -48
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/index.d.mts
CHANGED
|
@@ -107,4 +107,11 @@ export declare class LinovelibClient {
|
|
|
107
107
|
export declare function novelIdToCoverUrl(novelId: string): string;
|
|
108
108
|
export declare function extractChapterIllustrationUrls(html: string): string[];
|
|
109
109
|
export declare function rewriteChapterIllustrations(html: string, mapUrl: (originalUrl: string) => string): string;
|
|
110
|
+
/** 搜索验证流程无法自动完成时抛出,便于上层区分站点验证码问题。 */
|
|
111
|
+
export declare class SearchVerificationError extends Error {
|
|
112
|
+
constructor(message: string);
|
|
113
|
+
}
|
|
114
|
+
export declare class SearchRateLimitError extends Error {
|
|
115
|
+
constructor(message: string);
|
|
116
|
+
}
|
|
110
117
|
export type { LinovelibCatalogOptions, LinovelibClientOptions, LinovelibRankingOptions, SessionOptions };
|
package/dist/index.mjs
CHANGED
|
@@ -68,15 +68,22 @@ function extractChapterLogScriptUrl(html) {
|
|
|
68
68
|
})).attr("src") || "";
|
|
69
69
|
return chapterLogScriptUrl.startsWith("http") ? chapterLogScriptUrl : `https://www.linovelib.com${chapterLogScriptUrl}`;
|
|
70
70
|
}
|
|
71
|
-
async function getCoefficientsFromPage(html, fetchClient, cachedVersion) {
|
|
71
|
+
async function getCoefficientsFromPage(html, fetchClient, cachedVersion, logger) {
|
|
72
72
|
const scriptUrl = extractChapterLogScriptUrl(html);
|
|
73
73
|
if (!scriptUrl) throw new Error("Chapter log script URL not found");
|
|
74
74
|
const version = scriptUrl.match(/chapterlog\.js\?(v.*)/)?.[1] || "";
|
|
75
|
-
if (version === cachedVersion)
|
|
75
|
+
if (version === cachedVersion) {
|
|
76
|
+
logger?.debug(`[Coefficients] 命中已缓存的 chapterlog.js 版本: version=${version}`);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const startAt = Date.now();
|
|
80
|
+
logger?.debug(`[Coefficients] chapterlog.js 版本变化 (${cachedVersion ?? "none"} -> ${version}),开始拉取并反混淆提取系数: url=${scriptUrl}`);
|
|
76
81
|
const scriptContent = await fetchClient.text(scriptUrl);
|
|
77
82
|
if (!scriptContent.mimeType.includes("javascript")) throw new Error("Fetched content is not JavaScript");
|
|
83
|
+
const coefficients = await extractCoefficients(scriptContent.data);
|
|
84
|
+
logger?.debug(`[Coefficients] 解扰系数提取完成: version=${version} duration=${Date.now() - startAt}ms`);
|
|
78
85
|
return {
|
|
79
|
-
coefficients
|
|
86
|
+
coefficients,
|
|
80
87
|
version
|
|
81
88
|
};
|
|
82
89
|
}
|
|
@@ -210,9 +217,9 @@ function extractChapterId($) {
|
|
|
210
217
|
});
|
|
211
218
|
return chapterId;
|
|
212
219
|
}
|
|
213
|
-
async function decrypt(html, fetchClient, cachedJsVersion, cachedCoefficients) {
|
|
220
|
+
async function decrypt(html, fetchClient, cachedJsVersion, cachedCoefficients, logger) {
|
|
214
221
|
const $ = cheerio.load(html);
|
|
215
|
-
const coefficientResult = await getCoefficientsFromPage(html, fetchClient, cachedJsVersion);
|
|
222
|
+
const coefficientResult = await getCoefficientsFromPage(html, fetchClient, cachedJsVersion, logger);
|
|
216
223
|
const version = coefficientResult?.version || cachedJsVersion;
|
|
217
224
|
const coefficients = coefficientResult?.coefficients || cachedCoefficients;
|
|
218
225
|
if (!version) throw new Error("Failed to determine chapterlog.js version");
|
|
@@ -269,17 +276,21 @@ async function decrypt(html, fetchClient, cachedJsVersion, cachedCoefficients) {
|
|
|
269
276
|
coefficients
|
|
270
277
|
};
|
|
271
278
|
}
|
|
272
|
-
async function getChapter(id, novelId, chapterQueue, fetchClient, cachedJsVersion, cachedCoefficients) {
|
|
279
|
+
async function getChapter(id, novelId, chapterQueue, fetchClient, cachedJsVersion, cachedCoefficients, logger) {
|
|
280
|
+
const startAt = Date.now();
|
|
273
281
|
const firstPageHtml = await chapterQueue.fetchChapterPart(`https://www.linovelib.com/novel/${novelId}/${id}.html`);
|
|
274
282
|
let $ = cheerio.load(firstPageHtml);
|
|
275
283
|
const chapterName = $("h1").text().trim();
|
|
276
284
|
let nextPageId = $("div.mlfy_page a:last").attr("href")?.match(/\/novel\/(\d+)\/([\d_]+)\.html/)?.[2] || firstPageHtml.match(/url_next:'\/novel\/(\d+)\/([\d_]+)\.html'/)?.[2] || "";
|
|
277
|
-
let content = await decrypt(firstPageHtml, fetchClient, cachedJsVersion, cachedCoefficients);
|
|
285
|
+
let content = await decrypt(firstPageHtml, fetchClient, cachedJsVersion, cachedCoefficients, logger);
|
|
278
286
|
cachedCoefficients = content.coefficients;
|
|
279
287
|
cachedJsVersion = content.version;
|
|
288
|
+
let partCount = 1;
|
|
280
289
|
while (nextPageId?.includes(id)) {
|
|
290
|
+
partCount += 1;
|
|
291
|
+
logger?.debug(`[Chapter] 继续抓取章节分页: novelId=${novelId} chapterId=${id} part=${partCount} nextPageId=${nextPageId}`);
|
|
281
292
|
const nextPageHtml = await chapterQueue.fetchChapterPart(`https://www.linovelib.com/novel/${novelId}/${nextPageId}.html`);
|
|
282
|
-
const nextContent = await decrypt(nextPageHtml, fetchClient, cachedJsVersion, cachedCoefficients);
|
|
293
|
+
const nextContent = await decrypt(nextPageHtml, fetchClient, cachedJsVersion, cachedCoefficients, logger);
|
|
283
294
|
content = {
|
|
284
295
|
...content,
|
|
285
296
|
content: content.content + nextContent.content
|
|
@@ -291,6 +302,7 @@ async function getChapter(id, novelId, chapterQueue, fetchClient, cachedJsVersio
|
|
|
291
302
|
...content,
|
|
292
303
|
content: `<h2>${chapterName}</h2>\n${transformContent(content.content)}`
|
|
293
304
|
};
|
|
305
|
+
logger?.debug(`[Chapter] 章节解扰与拼接完成: novelId=${novelId} chapterId=${id} parts=${partCount} htmlLength=${content.content.length} duration=${Date.now() - startAt}ms`);
|
|
294
306
|
return content;
|
|
295
307
|
}
|
|
296
308
|
// src/novel.ts
|
|
@@ -2234,6 +2246,11 @@ function parseBookHtml($) {
|
|
|
2234
2246
|
// src/search/captcha.ts
|
|
2235
2247
|
const MODEL_FILENAME = "captcha_cropped.onnx";
|
|
2236
2248
|
const TARGET_HEIGHT = 64;
|
|
2249
|
+
const CHANNEL_VARIANT_NAMES = [
|
|
2250
|
+
"saturation",
|
|
2251
|
+
"maxChannel",
|
|
2252
|
+
"minChannel"
|
|
2253
|
+
];
|
|
2237
2254
|
const CHARSET = ["", ..."0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"];
|
|
2238
2255
|
let sessionPromise;
|
|
2239
2256
|
function moduleDirectory() {
|
|
@@ -2258,18 +2275,23 @@ function resolveModelPath() {
|
|
|
2258
2275
|
for (const candidate of candidates) if (existsSync(candidate)) return candidate;
|
|
2259
2276
|
throw new Error(`无法找到搜索验证码识别模型 ${MODEL_FILENAME},尝试过的路径: ${candidates.join(", ")}`);
|
|
2260
2277
|
}
|
|
2261
|
-
async function getSession() {
|
|
2278
|
+
async function getSession(logger) {
|
|
2262
2279
|
if (!sessionPromise) {
|
|
2263
2280
|
sessionPromise = (async () => {
|
|
2281
|
+
const loadStartAt = Date.now();
|
|
2264
2282
|
const ort = await import("onnxruntime-node");
|
|
2265
2283
|
ort.env.logLevel = "error";
|
|
2266
|
-
const
|
|
2267
|
-
|
|
2284
|
+
const modelPath = resolveModelPath();
|
|
2285
|
+
logger?.debug(`[SearchCaptcha] 加载验证码 ONNX 模型: path=${modelPath}`);
|
|
2286
|
+
const model = await readFile(modelPath);
|
|
2287
|
+
const session = await ort.InferenceSession.create(model, {
|
|
2268
2288
|
executionProviders: ["cpu"],
|
|
2269
2289
|
graphOptimizationLevel: "all",
|
|
2270
2290
|
intraOpNumThreads: 1,
|
|
2271
2291
|
interOpNumThreads: 1
|
|
2272
2292
|
});
|
|
2293
|
+
logger?.debug(`[SearchCaptcha] 验证码 ONNX 模型加载完成: bytes=${model.byteLength} duration=${Date.now() - loadStartAt}ms`);
|
|
2294
|
+
return session;
|
|
2273
2295
|
})();
|
|
2274
2296
|
sessionPromise.catch(() => {
|
|
2275
2297
|
sessionPromise = void 0;
|
|
@@ -2389,11 +2411,12 @@ function chooseBest(decoded) {
|
|
|
2389
2411
|
* 识别 linovelib 搜索验证码(4 位数字/字母图片)。
|
|
2390
2412
|
* 使用 ddddocr 的 common_old 裁剪模型(MIT),见 assets/THIRD-PARTY-NOTICES.md。
|
|
2391
2413
|
*/
|
|
2392
|
-
async function solveCaptcha(image) {
|
|
2414
|
+
async function solveCaptcha(image, logger) {
|
|
2415
|
+
const startAt = Date.now();
|
|
2393
2416
|
const decoded = decode(image);
|
|
2394
2417
|
const targetWidth = Math.round(decoded.width * TARGET_HEIGHT / decoded.height);
|
|
2395
2418
|
const ort = await import("onnxruntime-node");
|
|
2396
|
-
const session = await getSession();
|
|
2419
|
+
const session = await getSession(logger);
|
|
2397
2420
|
const inputName = session.inputNames[0];
|
|
2398
2421
|
const outputName = session.outputNames[0];
|
|
2399
2422
|
if (!inputName || !outputName) throw new Error("验证码识别模型缺少输入或输出节点");
|
|
@@ -2412,7 +2435,10 @@ async function solveCaptcha(image) {
|
|
|
2412
2435
|
decodedTexts.push(decodeCtcOutput(output.data, output.dims));
|
|
2413
2436
|
}
|
|
2414
2437
|
if (decodedTexts.length === 0) throw new Error("验证码识别失败:没有任何可用结果");
|
|
2415
|
-
|
|
2438
|
+
const best = chooseBest(decodedTexts);
|
|
2439
|
+
const variantSummary = decodedTexts.map((item, index) => `${CHANNEL_VARIANT_NAMES[index] ?? `v${index}`}=${JSON.stringify(item.text)}(${item.confidence.toFixed(3)})`).join(", ");
|
|
2440
|
+
logger?.debug(`[SearchCaptcha] 识别完成: winner=${JSON.stringify(best.text)}(${best.confidence.toFixed(3)}) image=${decoded.width}x${decoded.height} variants=[${variantSummary}] duration=${Date.now() - startAt}ms`);
|
|
2441
|
+
return best.text;
|
|
2416
2442
|
}
|
|
2417
2443
|
// src/search/v3.ts
|
|
2418
2444
|
const SEARCH_URL = "https://www.linovelib.com/S6/";
|
|
@@ -2421,7 +2447,15 @@ const ORIGIN = "https://www.linovelib.com";
|
|
|
2421
2447
|
const MIN_SEARCH_INTERVAL_MS = 5200;
|
|
2422
2448
|
const MAX_VERIFICATION_ATTEMPTS = 3;
|
|
2423
2449
|
const MAX_RATE_LIMIT_ATTEMPTS = 3;
|
|
2450
|
+
const MAX_SEARCH_PAGES = 15;
|
|
2424
2451
|
const NEXT_PAGE_DELAY_MIN_MS = 300;
|
|
2452
|
+
const SEARCH_REQUEST_RETRY = {
|
|
2453
|
+
retries: 2,
|
|
2454
|
+
minRetryDelayMs: 500,
|
|
2455
|
+
maxRetryDelayMs: 2e3,
|
|
2456
|
+
randomize: true,
|
|
2457
|
+
factor: 2
|
|
2458
|
+
};
|
|
2425
2459
|
const searchRequestHeaders = {
|
|
2426
2460
|
origin: ORIGIN,
|
|
2427
2461
|
referer: `${ORIGIN}/`
|
|
@@ -2468,44 +2502,84 @@ var SearchRateLimitError = class extends Error {
|
|
|
2468
2502
|
*/
|
|
2469
2503
|
var SearchSession = class {
|
|
2470
2504
|
fetchClient;
|
|
2505
|
+
logger;
|
|
2471
2506
|
mutex = new Mutex();
|
|
2472
2507
|
lastSearchAt = 0;
|
|
2473
|
-
constructor(fetchClient) {
|
|
2508
|
+
constructor(fetchClient, logger) {
|
|
2474
2509
|
this.fetchClient = fetchClient;
|
|
2510
|
+
this.logger = logger;
|
|
2475
2511
|
}
|
|
2476
2512
|
async search(keyword) {
|
|
2513
|
+
const queuedAt = Date.now();
|
|
2514
|
+
if (this.mutex.isLocked()) this.logger?.debug(`[SearchSession] 已有搜索任务进行中,排队等待锁: keyword=${JSON.stringify(keyword)}`);
|
|
2477
2515
|
return await this.mutex.runExclusive(async () => {
|
|
2516
|
+
const startAt = Date.now();
|
|
2517
|
+
const lockWaitMs = startAt - queuedAt;
|
|
2518
|
+
this.logger?.debug(`[SearchSession] 开始搜索: keyword=${JSON.stringify(keyword)} lockWait=${lockWaitMs}ms`);
|
|
2478
2519
|
const html = await this.requestSearch(keyword);
|
|
2479
|
-
|
|
2520
|
+
const results = await this.parseResults(keyword, html);
|
|
2521
|
+
this.logger?.debug(`[SearchSession] 搜索完成: keyword=${JSON.stringify(keyword)} count=${results.length} duration=${Date.now() - startAt}ms`);
|
|
2522
|
+
return results;
|
|
2480
2523
|
});
|
|
2481
2524
|
}
|
|
2482
|
-
async parseResults(html) {
|
|
2525
|
+
async parseResults(keyword, html) {
|
|
2483
2526
|
const $ = load(html);
|
|
2484
|
-
if (isBookPage(html) && $("div.book-html-box").length > 0)
|
|
2527
|
+
if (isBookPage(html) && $("div.book-html-box").length > 0) {
|
|
2528
|
+
const book = parseBookHtml($);
|
|
2529
|
+
this.logger?.debug(`[SearchSession] 搜索直达书籍详情页: keyword=${JSON.stringify(keyword)} id=${book.id} title=${JSON.stringify(book.title)}`);
|
|
2530
|
+
return [book];
|
|
2531
|
+
}
|
|
2485
2532
|
const results = parseSearchHtml($);
|
|
2486
2533
|
const totalPages = Number($("em#pagestats").text().match(/1\/(\d+)/)?.[1] ?? "1");
|
|
2487
2534
|
const nextHref = $("a.next").attr("href");
|
|
2488
|
-
|
|
2535
|
+
const hasNext = Boolean(totalPages > 1 && nextHref);
|
|
2536
|
+
this.logger?.debug(`[SearchSession] 搜索首页解析完成: keyword=${JSON.stringify(keyword)} page=1/${totalPages} count=${results.length} hasNext=${hasNext}`);
|
|
2537
|
+
if (totalPages > 1 && nextHref) results.push(...await this.collectNextPages(keyword, nextHref));
|
|
2489
2538
|
return results;
|
|
2490
2539
|
}
|
|
2491
|
-
async collectNextPages(startHref) {
|
|
2540
|
+
async collectNextPages(keyword, startHref) {
|
|
2492
2541
|
const results = [];
|
|
2542
|
+
const visitedUrls = /* @__PURE__ */ new Set();
|
|
2493
2543
|
let href = startHref;
|
|
2544
|
+
let pageNumber = 2;
|
|
2494
2545
|
while (href) {
|
|
2495
|
-
|
|
2496
|
-
|
|
2546
|
+
if (pageNumber > MAX_SEARCH_PAGES) {
|
|
2547
|
+
this.logger?.debug(`[SearchSession] 搜索翻页达到上限 (${MAX_SEARCH_PAGES} 页),停止继续抓取: keyword=${JSON.stringify(keyword)}`);
|
|
2548
|
+
break;
|
|
2549
|
+
}
|
|
2550
|
+
const url = new URL(href, SEARCH_URL).toString();
|
|
2551
|
+
if (visitedUrls.has(url)) {
|
|
2552
|
+
this.logger?.debug(`[SearchSession] 检测到重复翻页链接,终止翻页防死循环: keyword=${JSON.stringify(keyword)} url=${url}`);
|
|
2553
|
+
break;
|
|
2554
|
+
}
|
|
2555
|
+
visitedUrls.add(url);
|
|
2556
|
+
const delay = NEXT_PAGE_DELAY_MIN_MS + Math.random() * 500;
|
|
2557
|
+
this.logger?.debug(`[SearchSession] 准备抓取搜索翻页: keyword=${JSON.stringify(keyword)} page=${pageNumber} delay=${Math.round(delay)}ms url=${url}`);
|
|
2558
|
+
await sleep(delay);
|
|
2559
|
+
const html = await this.fetchPage(url);
|
|
2497
2560
|
const $ = load(html);
|
|
2498
|
-
|
|
2561
|
+
const pageResults = parseSearchHtml($);
|
|
2562
|
+
results.push(...pageResults);
|
|
2499
2563
|
href = $("a.next").attr("href") || void 0;
|
|
2564
|
+
this.logger?.debug(`[SearchSession] 搜索翻页解析完成: keyword=${JSON.stringify(keyword)} page=${pageNumber} count=${pageResults.length} hasNext=${Boolean(href)}`);
|
|
2565
|
+
pageNumber += 1;
|
|
2500
2566
|
}
|
|
2501
2567
|
return results;
|
|
2502
2568
|
}
|
|
2503
2569
|
async fetchPage(url) {
|
|
2504
|
-
let response = await this.fetchClient.text(url, {
|
|
2570
|
+
let response = await this.fetchClient.text(url, {
|
|
2571
|
+
headers: searchRefererHeaders,
|
|
2572
|
+
retry: SEARCH_REQUEST_RETRY
|
|
2573
|
+
});
|
|
2505
2574
|
if (response.mimeType !== "text/html") throw new Error(`Unexpected response type: ${response.mimeType}`);
|
|
2506
2575
|
if (isVerificationPage(response.data)) {
|
|
2576
|
+
this.logger?.debug(`[SearchSession] 搜索翻页时验证态过期,重新执行搜索验证: url=${url}`);
|
|
2507
2577
|
await this.verifySearch(response.data);
|
|
2508
|
-
|
|
2578
|
+
this.logger?.debug(`[SearchSession] 验证态已恢复,重新请求搜索翻页: url=${url}`);
|
|
2579
|
+
response = await this.fetchClient.text(url, {
|
|
2580
|
+
headers: searchRefererHeaders,
|
|
2581
|
+
retry: SEARCH_REQUEST_RETRY
|
|
2582
|
+
});
|
|
2509
2583
|
if (response.mimeType !== "text/html") throw new Error(`Unexpected response type: ${response.mimeType}`);
|
|
2510
2584
|
if (isVerificationPage(response.data)) throw new SearchVerificationError("搜索验证后翻页仍被要求验证");
|
|
2511
2585
|
}
|
|
@@ -2515,16 +2589,26 @@ var SearchSession = class {
|
|
|
2515
2589
|
async requestSearch(keyword) {
|
|
2516
2590
|
for (let attempt = 0; attempt < MAX_RATE_LIMIT_ATTEMPTS; attempt++) {
|
|
2517
2591
|
await this.waitForSearchSlot();
|
|
2592
|
+
const requestStartAt = Date.now();
|
|
2593
|
+
this.logger?.debug(`[SearchSession] 发起搜索 POST 请求: keyword=${JSON.stringify(keyword)} attempt=${attempt + 1}/${MAX_RATE_LIMIT_ATTEMPTS}`);
|
|
2518
2594
|
const response = await this.fetchClient.text(SEARCH_URL, {
|
|
2519
2595
|
method: "POST",
|
|
2520
2596
|
body: new URLSearchParams({ searchkey: keyword }),
|
|
2521
|
-
headers: searchRequestHeaders
|
|
2597
|
+
headers: searchRequestHeaders,
|
|
2598
|
+
retry: SEARCH_REQUEST_RETRY
|
|
2522
2599
|
});
|
|
2523
2600
|
this.lastSearchAt = Date.now();
|
|
2524
2601
|
if (response.mimeType !== "text/html") throw new Error(`Unexpected response type: ${response.mimeType}`);
|
|
2525
2602
|
if (response.data === "") throw new Error("Empty response body when fetching search results");
|
|
2526
|
-
if (isRateLimitedPage(response.data))
|
|
2527
|
-
|
|
2603
|
+
if (isRateLimitedPage(response.data)) {
|
|
2604
|
+
this.logger?.debug(`[SearchSession] 触发站点搜索限流,准备重试: keyword=${JSON.stringify(keyword)} attempt=${attempt + 1}/${MAX_RATE_LIMIT_ATTEMPTS} duration=${this.lastSearchAt - requestStartAt}ms`);
|
|
2605
|
+
continue;
|
|
2606
|
+
}
|
|
2607
|
+
if (isVerificationPage(response.data)) {
|
|
2608
|
+
this.logger?.debug(`[SearchSession] 触发搜索验证页,开始自动识别验证码: keyword=${JSON.stringify(keyword)} duration=${this.lastSearchAt - requestStartAt}ms`);
|
|
2609
|
+
return await this.verifySearch(response.data);
|
|
2610
|
+
}
|
|
2611
|
+
this.logger?.debug(`[SearchSession] 搜索请求成功(免验证态): keyword=${JSON.stringify(keyword)} htmlLength=${response.data.length} duration=${this.lastSearchAt - requestStartAt}ms`);
|
|
2528
2612
|
return response.data;
|
|
2529
2613
|
}
|
|
2530
2614
|
throw new SearchRateLimitError(`搜索请求被站点限流,已重试 ${MAX_RATE_LIMIT_ATTEMPTS} 次`);
|
|
@@ -2538,15 +2622,24 @@ var SearchSession = class {
|
|
|
2538
2622
|
const searchtype = $("input[name=searchtype]").attr("value") ?? "all";
|
|
2539
2623
|
const imageSrc = $("#search-captcha").attr("src");
|
|
2540
2624
|
if (!challenge || !imageSrc || !searchkey) throw new SearchVerificationError("无法解析搜索验证码页面");
|
|
2541
|
-
const
|
|
2625
|
+
const imageUrl = new URL(imageSrc, SEARCH_URL).toString();
|
|
2626
|
+
this.logger?.debug(`[SearchSession] 开始获取搜索验证码图片: attempt=${attempt + 1}/${MAX_VERIFICATION_ATTEMPTS} url=${imageUrl}`);
|
|
2627
|
+
const image = await this.fetchClient.binary(imageUrl, {
|
|
2628
|
+
headers: searchRefererHeaders,
|
|
2629
|
+
retry: SEARCH_REQUEST_RETRY
|
|
2630
|
+
});
|
|
2542
2631
|
if (!image.mimeType.startsWith("image/")) throw new SearchVerificationError(`验证码图片响应类型异常: ${image.mimeType}`);
|
|
2632
|
+
this.logger?.debug(`[SearchSession] 验证码图片已获取: attempt=${attempt + 1}/${MAX_VERIFICATION_ATTEMPTS} mimeType=${image.mimeType} bytes=${image.data.length}`);
|
|
2543
2633
|
let code;
|
|
2544
2634
|
try {
|
|
2545
|
-
code = await solveCaptcha(image.data);
|
|
2635
|
+
code = await solveCaptcha(image.data, this.logger);
|
|
2546
2636
|
} catch (error) {
|
|
2547
2637
|
throw new SearchVerificationError(`验证码识别失败: ${error instanceof Error ? error.message : String(error)}`);
|
|
2548
2638
|
}
|
|
2639
|
+
if (code.length !== 4) this.logger?.debug(`[SearchSession] 验证码识别长度异常 (length=${code.length}): attempt=${attempt + 1}/${MAX_VERIFICATION_ATTEMPTS} code=${JSON.stringify(code)}`);
|
|
2549
2640
|
await this.waitForSearchSlot();
|
|
2641
|
+
const submitStartAt = Date.now();
|
|
2642
|
+
this.logger?.debug(`[SearchSession] 提交搜索验证码: attempt=${attempt + 1}/${MAX_VERIFICATION_ATTEMPTS} code=${JSON.stringify(code)}`);
|
|
2550
2643
|
const response = await this.fetchClient.text(SEARCH_URL, {
|
|
2551
2644
|
method: "POST",
|
|
2552
2645
|
body: new URLSearchParams({
|
|
@@ -2555,31 +2648,47 @@ var SearchSession = class {
|
|
|
2555
2648
|
search_challenge: challenge,
|
|
2556
2649
|
search_code: code
|
|
2557
2650
|
}),
|
|
2558
|
-
headers: searchRefererHeaders
|
|
2651
|
+
headers: searchRefererHeaders,
|
|
2652
|
+
retry: SEARCH_REQUEST_RETRY
|
|
2559
2653
|
});
|
|
2560
2654
|
this.lastSearchAt = Date.now();
|
|
2561
2655
|
if (response.mimeType !== "text/html") throw new Error(`Unexpected response type: ${response.mimeType}`);
|
|
2562
|
-
if (
|
|
2656
|
+
if (response.data === "") throw new Error("Empty response body when submitting search captcha");
|
|
2657
|
+
if (isRateLimitedPage(response.data)) {
|
|
2658
|
+
this.logger?.debug(`[SearchSession] 提交验证码后触发站点搜索限流: attempt=${attempt + 1}/${MAX_VERIFICATION_ATTEMPTS} duration=${this.lastSearchAt - submitStartAt}ms`);
|
|
2659
|
+
throw new SearchRateLimitError("提交搜索验证码时触发站点搜索限流");
|
|
2660
|
+
}
|
|
2661
|
+
if (!isVerificationPage(response.data)) {
|
|
2662
|
+
this.logger?.debug(`[SearchSession] 搜索验证通过: attempt=${attempt + 1}/${MAX_VERIFICATION_ATTEMPTS} htmlLength=${response.data.length} duration=${this.lastSearchAt - submitStartAt}ms`);
|
|
2663
|
+
return response.data;
|
|
2664
|
+
}
|
|
2665
|
+
this.logger?.debug(`[SearchSession] 搜索验证未通过(验证码错误或过期),准备重试: attempt=${attempt + 1}/${MAX_VERIFICATION_ATTEMPTS} code=${JSON.stringify(code)} duration=${this.lastSearchAt - submitStartAt}ms`);
|
|
2563
2666
|
currentHtml = response.data;
|
|
2564
2667
|
}
|
|
2565
2668
|
throw new SearchVerificationError(`搜索验证码连续识别失败(已尝试 ${MAX_VERIFICATION_ATTEMPTS} 次)`);
|
|
2566
2669
|
}
|
|
2567
2670
|
async waitForSearchSlot() {
|
|
2568
2671
|
const elapsed = Date.now() - this.lastSearchAt;
|
|
2569
|
-
if (elapsed < MIN_SEARCH_INTERVAL_MS)
|
|
2672
|
+
if (elapsed < MIN_SEARCH_INTERVAL_MS) {
|
|
2673
|
+
const waitMs = MIN_SEARCH_INTERVAL_MS - elapsed;
|
|
2674
|
+
this.logger?.debug(`[SearchSession] 距离上次搜索间隔 ${elapsed}ms (< ${MIN_SEARCH_INTERVAL_MS}ms),等待 ${waitMs}ms`);
|
|
2675
|
+
await sleep(waitMs);
|
|
2676
|
+
}
|
|
2570
2677
|
}
|
|
2571
2678
|
};
|
|
2572
2679
|
async function searchNovelsV3(keyword, _fetchClient, session) {
|
|
2573
2680
|
return await session.search(keyword);
|
|
2574
2681
|
}
|
|
2575
2682
|
// src/session.ts
|
|
2576
|
-
async function refreshSessionId(fetchClient, loginConfig) {
|
|
2683
|
+
async function refreshSessionId(fetchClient, loginConfig, logger) {
|
|
2684
|
+
const startAt = Date.now();
|
|
2685
|
+
logger?.debug(`[Session] 开始刷新登录会话: username=${JSON.stringify(loginConfig.username)}`);
|
|
2577
2686
|
await fetchClient.request({
|
|
2578
2687
|
url: "https://www.linovelib.com/login.php",
|
|
2579
2688
|
method: "GET",
|
|
2580
2689
|
headers: { referer: "https://www.linovelib.com/" }
|
|
2581
2690
|
});
|
|
2582
|
-
|
|
2691
|
+
const response = await fetchClient.request({
|
|
2583
2692
|
url: "https://www.linovelib.com/login.php?do=submit&jumpurl=https%3A%2F%2Fwww.linovelib.com%2F",
|
|
2584
2693
|
method: "POST",
|
|
2585
2694
|
body: new URLSearchParams({
|
|
@@ -2590,15 +2699,24 @@ async function refreshSessionId(fetchClient, loginConfig) {
|
|
|
2590
2699
|
action: "login"
|
|
2591
2700
|
}),
|
|
2592
2701
|
followRedirects: false
|
|
2593
|
-
})
|
|
2594
|
-
|
|
2595
|
-
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2702
|
+
});
|
|
2703
|
+
const hasPhpSessionId = response.cookies.findIndex((cookie) => cookie.name === "PHPSESSID") !== -1;
|
|
2704
|
+
logger?.debug(`[Session] 登录提交完成: status=${response.status} hasPhpSessionId=${hasPhpSessionId} duration=${Date.now() - startAt}ms`);
|
|
2705
|
+
return hasPhpSessionId;
|
|
2706
|
+
}
|
|
2707
|
+
async function hasValidSession(fetchClient, logger) {
|
|
2708
|
+
const startAt = Date.now();
|
|
2709
|
+
const valid = (await fetchClient.text("https://www.linovelib.com")).data.includes("用户中心");
|
|
2710
|
+
logger?.debug(`[Session] 会话有效性检查完成: valid=${valid} duration=${Date.now() - startAt}ms`);
|
|
2711
|
+
return valid;
|
|
2712
|
+
}
|
|
2713
|
+
async function ensureValidSession(fetchClient, loginConfig, logger) {
|
|
2714
|
+
if (!await hasValidSession(fetchClient, logger)) {
|
|
2715
|
+
logger?.debug("[Session] 当前会话无效或已过期,尝试重新登录");
|
|
2716
|
+
if (!(await refreshSessionId(fetchClient, loginConfig, logger) && await hasValidSession(fetchClient, logger))) {
|
|
2717
|
+
logger?.warn("[Session] 重新登录后会话仍无效");
|
|
2718
|
+
return false;
|
|
2719
|
+
}
|
|
2602
2720
|
}
|
|
2603
2721
|
return true;
|
|
2604
2722
|
}
|
|
@@ -2662,12 +2780,13 @@ var LinovelibClient = class {
|
|
|
2662
2780
|
break;
|
|
2663
2781
|
default: browserFetchOptions.cookieStore = { type: "memory" };
|
|
2664
2782
|
}
|
|
2783
|
+
if (this.logger) browserFetchOptions.logger = this.logger;
|
|
2665
2784
|
this.fetchClient = new BrowserFetchClient(browserFetchOptions);
|
|
2666
2785
|
this.novelChapterQueue = new NovelChapterQueue(this.fetchClient, this.logger);
|
|
2667
2786
|
this.novelInfoQueue = new NovelInfoQueue(this.fetchClient, this.novelChapterQueue, this.logger);
|
|
2668
2787
|
this.novelMediaQueue = new NovelMediaQueue(this.fetchClient, this.logger);
|
|
2669
2788
|
this.novelExploreQueue = new NovelExploreQueue(this.fetchClient, this.logger);
|
|
2670
|
-
this.searchSession = new SearchSession(this.fetchClient);
|
|
2789
|
+
this.searchSession = new SearchSession(this.fetchClient, this.logger);
|
|
2671
2790
|
}
|
|
2672
2791
|
async ensureSession() {
|
|
2673
2792
|
if (!this.options?.session.enabled || this.isSessionValid) return;
|
|
@@ -2676,7 +2795,7 @@ var LinovelibClient = class {
|
|
|
2676
2795
|
this.sessionCheckPromise = ensureValidSession(this.fetchClient, {
|
|
2677
2796
|
username,
|
|
2678
2797
|
password
|
|
2679
|
-
}).then((valid) => {
|
|
2798
|
+
}, this.logger).then((valid) => {
|
|
2680
2799
|
this.isSessionValid = valid;
|
|
2681
2800
|
return valid;
|
|
2682
2801
|
}).finally(() => {
|
|
@@ -2724,7 +2843,7 @@ var LinovelibClient = class {
|
|
|
2724
2843
|
await this.ensureSession();
|
|
2725
2844
|
const cachedJsVersion = this.storage ? await this.storage.getCache("chapterlog_js_version", z.string()) ?? void 0 : void 0;
|
|
2726
2845
|
const cachedCoefficients = this.storage ? await this.storage.getCache("coefficients", descrambleCoefficientsSchema) ?? void 0 : void 0;
|
|
2727
|
-
const result = await getChapter(chapterId, novelId, this.novelChapterQueue, this.fetchClient, cachedJsVersion, cachedCoefficients);
|
|
2846
|
+
const result = await getChapter(chapterId, novelId, this.novelChapterQueue, this.fetchClient, cachedJsVersion, cachedCoefficients, this.logger);
|
|
2728
2847
|
if (this.storage && result) {
|
|
2729
2848
|
await this.storage.setCache("chapterlog_js_version", result.version);
|
|
2730
2849
|
await this.storage.setCache("coefficients", result.coefficients);
|
|
@@ -2771,6 +2890,6 @@ function rewriteChapterIllustrations(html, mapUrl) {
|
|
|
2771
2890
|
});
|
|
2772
2891
|
return $.html();
|
|
2773
2892
|
}
|
|
2774
|
-
export { LINOVELIB_CATALOG_ANIME_IDS, LINOVELIB_CATALOG_PROGRESS_IDS, LINOVELIB_CATALOG_REGION_IDS, LINOVELIB_CATALOG_SORT_IDS, LINOVELIB_CATALOG_TAG_IDS, LINOVELIB_CATALOG_UPDATED_IDS, LINOVELIB_CATALOG_WORDS_IDS, LINOVELIB_CHANNEL_IDS, LINOVELIB_DESKTOP_BASE, LINOVELIB_EXPLORE_SCHEMA, LINOVELIB_RANKING_IDS, LinovelibClient, buildCatalogUrl, buildRankingsUrl, extractChapterIllustrationUrls, extractNovelIdFromHref, isUnresolvedChapterId, isValidLinovelibChannel, isValidLinovelibRanking, normalizeCatalogOptions, novelIdToCoverUrl, parseCatalogHtml, parseHomeHtml, parseNovelStatusText, parseRankingsHtml, resolveDesktopCoverUrl, rewriteChapterIllustrations };
|
|
2893
|
+
export { LINOVELIB_CATALOG_ANIME_IDS, LINOVELIB_CATALOG_PROGRESS_IDS, LINOVELIB_CATALOG_REGION_IDS, LINOVELIB_CATALOG_SORT_IDS, LINOVELIB_CATALOG_TAG_IDS, LINOVELIB_CATALOG_UPDATED_IDS, LINOVELIB_CATALOG_WORDS_IDS, LINOVELIB_CHANNEL_IDS, LINOVELIB_DESKTOP_BASE, LINOVELIB_EXPLORE_SCHEMA, LINOVELIB_RANKING_IDS, LinovelibClient, SearchRateLimitError, SearchVerificationError, buildCatalogUrl, buildRankingsUrl, extractChapterIllustrationUrls, extractNovelIdFromHref, isUnresolvedChapterId, isValidLinovelibChannel, isValidLinovelibRanking, normalizeCatalogOptions, novelIdToCoverUrl, parseCatalogHtml, parseHomeHtml, parseNovelStatusText, parseRankingsHtml, resolveDesktopCoverUrl, rewriteChapterIllustrations };
|
|
2775
2894
|
|
|
2776
2895
|
//# sourceMappingURL=index.mjs.map
|