Files
DownloadHelper/entry/src/main/ets/model/TaskManager.ets
T
R-HUA 5a731e80b6 feat: 实现 LK/ESJ 双书源小说下载器主体
- 下载/书库/设置三页签 UI(HdsNavigation + HdsTabs,沉浸式避让)
- core: LkCore/EsjCore 双书源抓取、HtmlParser、EpubWriter/ZipWriter EPUB 导出
- OpenCC 简繁转换(rawfile 内置词库)
- model: TaskManager/LibraryStore/Config/Draft;worker: 后台任务
- 支持浏览器通过 esjzone/lightnovel 链接唤起(viewData intent)
- 应用更名 ESJ下载器,bundleName 改为 com.esj.downloader
2026-10-11 18:09:36 +08:00

1219 lines
43 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { taskpool } from '@kit.ArkTS';
import { fileIo as fs } from '@kit.CoreFileKit';
import { util } from '@kit.ArkTS';
import { ConfigStore, AppSettings } from './Config';
import { TaskInfo, ChapterNode, BookProgress, TocPreviewNode, TocPreviewResult, ChapterPart } from './TaskModel';
import { NodeStatus, TaskStatus } from '../common/Theme';
import { AppHub } from '../common/AppHub';
import { OpenCC } from '../core/OpenCC';
import { analyzeDetail, parseListPage, urlHandler, isImgPlaceholder, imgPlaceholderUrl, hostOf, VolumeChapterNode } from '../core/EsjCore';
import { fetchCatalog, splitChapterLines, parseBookId, bookPageUrl, chapterIdFromUrl, extractSecurityKey,
LkApiCfg, LkCatalogResult, LkLinePart } from '../core/LkCore';
import { buildEpub, EpubBuildInput, EpubImageItem, EpubNodeItem, escapeXml } from '../core/EpubWriter';
import { fetchChapterJob, fetchImageJob, fetchLkChapterJob,
FetchChapterArgs, FetchImageArgs, FetchChapterResult, FetchImageResult, FetchLkChapterArgs, FetchLkChapterResult } from '../worker/Jobs';
import { httpGetText } from '../net/HttpUtil';
import { LibraryStore, BookRecord } from './LibraryStore';
/**
* 任务编排:等价原脚本的 downloadOneBook / 批量列表下载流程。
* 单任务串行运行,任务内部按配置的并发数抓取章节;图片随章节内联抓取并按内容去重。
*/
interface ImageState {
status: string; // inflight | done | failed
fileName: string;
filePath: string;
contentType: string;
error: string;
}
interface Cursor {
i: number;
}
export class TaskManager {
static instance: TaskManager = new TaskManager();
tasks: TaskInfo[] = [];
activeTaskId: string = '';
private imgMap: Map<string, ImageState> = new Map();
private lastEmit: number = 0;
tasksSnapshot(): TaskInfo[] {
return this.tasks.slice();
}
findTask(id: string): TaskInfo | null {
for (const t of this.tasks) {
if (t.id === id) {
return t;
}
}
return null;
}
createTask(mode: string, url: string, customTitle: string = '', chapterFilter: number[] = [],
source: string = 'esj'): TaskInfo {
const t = new TaskInfo();
t.id = 'task_' + Date.now().toString(36) + '_' + Math.floor(Math.random() * 1000);
t.mode = mode;
t.source = source;
t.url = url;
t.customTitle = customTitle;
for (const v of chapterFilter) {
t.chapterFilter.push(v);
}
t.createdAt = Date.now();
this.tasks.unshift(t);
t.addLog('info', mode === 'list' ? '创建批量下载任务' : (source === 'lk' ? '创建轻之国度下载任务' : '创建下载任务'));
this.emit(true);
if (this.activeTaskId === '') {
this.startTask(t);
}
return t;
}
/** 拉取目录预览(选章下载用)。返回纯数据,不改任务状态。 */
async fetchTocPreview(url: string): Promise<TocPreviewResult> {
const s = ConfigStore.get();
if (url.toLowerCase().indexOf('lightnovel') >= 0) {
return this.fetchTocPreviewLk(url, s);
}
const empty: TocPreviewNode[] = [];
const resp = await httpGetText(url, s.cookie, s.timeoutSec * 1000, s.retryCount);
if (!resp.ok) {
const r: TocPreviewResult = { ok: false, error: resp.error, nodes: empty, bookName: '', author: '' };
return r;
}
const cc = await OpenCC.getConverter(s.convertMode, AppHub.uiContext());
const detail = analyzeDetail(resp.text, s.siteUrl, cc !== null ? (x: string): string => cc.convert(x) : null);
if (!detail.ok) {
const r2: TocPreviewResult = { ok: false, error: detail.error, nodes: empty, bookName: '', author: '' };
return r2;
}
const nodes: TocPreviewNode[] = [];
for (const n of detail.nodes) {
nodes.push({ value: n.value, level: n.level, fatherValue: n.fatherValue, isVolume: n.isVolume, isChapter: n.isChapter, title: n.title });
}
const r3: TocPreviewResult = { ok: true, error: '', nodes: nodes, bookName: detail.bookName, author: detail.author };
return r3;
}
/** LK 目录预览:书籍详情 + 全部卷章(分页) */
private async fetchTocPreviewLk(url: string, s: AppSettings): Promise<TocPreviewResult> {
const empty: TocPreviewNode[] = [];
const bookId = parseBookId(url);
if (bookId.length === 0) {
const r: TocPreviewResult =
{ ok: false, error: '链接中未找到书籍编号(需要 lightnovel.fun/book/<id> 链接)', nodes: empty, bookName: '', author: '' };
return r;
}
const cookie = ConfigStore.cleanCookie(s.lkCookie);
const cfg: LkApiCfg = {
cookie: cookie, securityKey: extractSecurityKey(cookie),
timeoutMs: s.timeoutSec * 1000, retry: s.retryCount
};
const cc = await OpenCC.getConverter(s.convertMode, AppHub.uiContext());
try {
const cat: LkCatalogResult = await fetchCatalog(bookId, cfg,
cc !== null ? (x: string): string => cc.convert(x) : null);
const nodes: TocPreviewNode[] = [];
for (const n of cat.nodes) {
nodes.push({ value: n.value, level: n.level, fatherValue: n.fatherValue, isVolume: n.isVolume, isChapter: n.isChapter, title: n.title });
}
const r2: TocPreviewResult = { ok: true, error: '', nodes: nodes, bookName: cat.bookName, author: cat.author };
return r2;
} catch (e) {
const r3: TocPreviewResult = { ok: false, error: (e as Error).message, nodes: empty, bookName: '', author: '' };
return r3;
}
}
requestCancel(id: string): void {
const t = this.findTask(id);
if (t === null) {
return;
}
t.cancelRequested = true;
t.addLog('warn', '已请求取消,等待进行中的请求结束…');
this.emit(true);
if (t.status === TaskStatus.QUEUED) {
t.status = TaskStatus.CANCELLED;
t.addLog('warn', '任务已取消');
this.emit(true);
}
}
removeTask(id: string): void {
const idx = this.tasks.findIndex((t: TaskInfo): boolean => t.id === id);
if (idx >= 0) {
if (this.tasks[idx].status === TaskStatus.RUNNING) {
this.requestCancel(id);
}
this.tasks.splice(idx, 1);
this.emit(true);
}
}
/** 重试失败章节(仅单书模式;复用仍存在的缓存与已下载图片做增量重建) */
retryFailed(id: string): void {
if (this.activeTaskId !== '') {
return;
}
const t = this.findTask(id);
if (t === null || t.status !== TaskStatus.DONE_WITH_FAIL || t.mode !== 'book') {
return;
}
for (const n of t.nodes) {
if (n.status === NodeStatus.FAILED) {
n.status = NodeStatus.PENDING;
n.error = '';
n.lines = [];
n.fragmentPath = '';
}
}
// 重置失败的图片,允许重新抓取
const removeUrls: string[] = [];
this.imgMap.forEach((v: ImageState, k: string): void => {
if (v.status === 'failed') {
removeUrls.push(k);
}
});
for (const u of removeUrls) {
this.imgMap.delete(u);
}
t.failedChapters = 0;
t.errorMessage = '';
t.cancelRequested = false;
t.addLog('info', '重试失败章节');
this.emit(true);
this.startTask(t, true);
}
private startTask(t: TaskInfo, retryOnly: boolean = false): void {
if (this.activeTaskId !== '') {
return;
}
this.activeTaskId = t.id;
t.status = TaskStatus.RUNNING;
this.emit(true);
this.run(t, retryOnly).then((): void => {
/* 由 run 内部收尾 */
}).catch((e: Error): void => {
t.status = TaskStatus.FAILED;
t.errorMessage = e.message;
t.addLog('error', '任务异常: ' + e.message);
this.finishActive(t);
});
}
private finishActive(t: TaskInfo): void {
this.activeTaskId = '';
this.emit(true);
// 启动队列中的下一个任务
for (const nt of this.tasks) {
if (nt.status === TaskStatus.QUEUED) {
this.startTask(nt);
break;
}
}
}
private emit(force: boolean): void {
const now = Date.now();
if (!force && now - this.lastEmit < 400) {
return;
}
this.lastEmit = now;
AppHub.emit('tasks', '');
}
// ---------------- 主流程 ----------------
private async run(t: TaskInfo, retryOnly: boolean = false): Promise<void> {
const s = ConfigStore.get();
try {
if (t.mode === 'list') {
await this.runList(t, s);
} else if (t.source === 'lk') {
await this.runBookLk(t, s, retryOnly);
} else {
await this.runBook(t, s, t.url, null, retryOnly);
}
if (t.cancelRequested) {
t.status = TaskStatus.CANCELLED;
t.addLog('warn', '任务已取消');
}
} catch (e) {
if (!t.cancelRequested) {
t.status = TaskStatus.FAILED;
t.errorMessage = (e as Error).message;
t.addLog('error', (e as Error).message);
} else {
t.status = TaskStatus.CANCELLED;
}
} finally {
// 存在失败章节的任务保留缓存与图片映射以便重试,其余清理
if (t.status !== TaskStatus.DONE_WITH_FAIL) {
this.cleanupCache(t);
this.imgMap.clear();
}
this.finishActive(t);
}
}
private async runList(t: TaskInfo, s: AppSettings): Promise<void> {
const mismatch = checkDomain(t.url, s.siteUrl);
if (mismatch.length > 0) {
throw new Error(mismatch);
}
t.phase = 'list';
t.addLog('info', '开始收集书籍列表…');
this.emit(true);
const firstPage = await httpGetText(t.url, s.cookie, s.timeoutSec * 1000, s.retryCount);
if (!firstPage.ok) {
throw new Error('列表页下载失败: ' + firstPage.error);
}
const firstInfo = parseListPage(firstPage.text, s.siteUrl);
const total = firstInfo.totalCount > 0 ? firstInfo.totalCount : 1;
t.addLog('info', `列表「${firstInfo.title}」共 ${total} 页`);
const bookUrls: string[] = [];
const seen: Set<string> = new Set();
for (const u of firstInfo.bookUrls) {
if (!seen.has(u)) {
seen.add(u);
bookUrls.push(u);
}
}
for (let p = 2; p <= total; p++) {
if (t.cancelRequested) {
return;
}
const pageUrl = t.url + p + '.html';
const resp = await httpGetText(pageUrl, s.cookie, s.timeoutSec * 1000, s.retryCount);
if (!resp.ok) {
t.addLog('warn', `第 ${p} 页下载失败: ${resp.error}`);
continue;
}
const info = parseListPage(resp.text, s.siteUrl);
for (const u of info.bookUrls) {
if (!seen.has(u)) {
seen.add(u);
bookUrls.push(u);
}
}
t.currentTitle = `收集列表 ${p}/${total}`;
this.emit(false);
}
t.addLog('info', `共发现 ${bookUrls.length} 本小说`);
t.activeBooksTotal = bookUrls.length;
t.phase = 'chapters';
for (let i = 0; i < bookUrls.length; i++) {
if (t.cancelRequested) {
return;
}
const bp: BookProgress = {
url: bookUrls[i], name: '', author: '', date: '', status: 'running',
doneCh: 0, totalCh: 0, message: ''
};
t.books.push(bp);
try {
const ok = await this.runBook(t, s, bookUrls[i], bp);
bp.status = t.cancelRequested ? 'cancelled' : (ok ? 'done' : 'skipped');
} catch (e) {
bp.status = 'failed';
bp.message = (e as Error).message;
t.addLog('error', `书籍下载失败: ${(e as Error).message}`);
}
t.activeBooksDone++;
this.emit(true);
}
if (t.cancelRequested) {
return;
}
const failedCount = t.books.filter((b: BookProgress): boolean => b.status === 'failed').length;
t.status = failedCount > 0 ? TaskStatus.DONE_WITH_FAIL : TaskStatus.DONE;
t.addLog('ok', `批量任务完成:成功 ${t.activeBooksDone - failedCount},失败 ${failedCount}`);
}
/**
* 下载单本书。bp 非空表示处于批量模式;retryOnly 表示失败章节增量重试
* (复用现存缓存目录、已完成章节与图片)。
* 返回 true=完成;抛出异常=失败;返回 false=已存在跳过。
*/
private async runBook(t: TaskInfo, s: AppSettings, bookUrl: string, bp: BookProgress | null,
retryOnly: boolean = false): Promise<boolean> {
const cacheDir = AppHub.uiContext().cacheDir + '/task_' + t.id;
const chDir = cacheDir + '/chapters';
const imgDir = cacheDir + '/images';
let bookName = t.bookName;
let author = t.author;
let changeDate = t.changeDate;
let coverUrl = t.coverUrl;
let descLines: string[] = t.descLines;
let descFragmentPath = '';
let unique = '';
let recordId = bookUrl;
if (!retryOnly) {
const mismatch = checkDomain(bookUrl, s.siteUrl);
if (mismatch.length > 0) {
throw new Error(mismatch);
}
t.phase = 'detail';
t.currentTitle = '获取书籍信息';
this.emit(true);
const resp = await httpGetText(bookUrl, s.cookie, s.timeoutSec * 1000, s.retryCount);
if (!resp.ok) {
throw new Error('详情页下载失败: ' + resp.error);
}
const cc = await OpenCC.getConverter(s.convertMode, AppHub.uiContext());
const convertFn = cc !== null ? (x: string): string => cc.convert(x) : null;
const detail = analyzeDetail(resp.text, s.siteUrl, convertFn);
if (!detail.ok) {
throw new Error(detail.error);
}
if (detail.nodes.length === 0 && detail.descLines.length === 0) {
throw new Error('未解析到章节列表,页面结构可能已变化');
}
// 批量模式日期去重(等价脚本的已存在判断)
if (bp !== null) {
const exist = LibraryStore.findByUrl(bookUrl);
if (exist !== null && exist.date.length > 0 && detail.changeDate.length > 0 && exist.date === detail.changeDate) {
bp.name = exist.name;
bp.author = exist.author;
bp.date = exist.date;
bp.status = 'skipped';
bp.message = `更新日期 ${exist.date} 已存在,跳过`;
t.addLog('info', `《${exist.name}》更新日期 ${exist.date} 已存在,跳过`);
return false;
}
}
bookName = detail.bookName;
author = detail.author;
changeDate = detail.changeDate;
coverUrl = detail.coverUrl;
// 自定义 EPUB 标题(选章下载/改名场景)
if (t.customTitle.length > 0) {
bookName = t.customTitle;
}
t.bookName = bookName;
t.author = author;
t.changeDate = changeDate;
t.coverUrl = coverUrl;
if (bp !== null) {
bp.name = bookName;
bp.author = author;
bp.date = changeDate;
}
if (bookName !== detail.bookName) {
t.addLog('info', `《${detail.bookName}》${author} 开始下载(标题:${bookName})`);
} else {
t.addLog('info', `《${bookName}》${author} 开始下载`);
}
ensureDir(cacheDir);
ensureDir(chDir);
ensureDir(imgDir);
t.nodes = detail.nodes.map((n): ChapterNode => new ChapterNode(n));
// 选章下载:仅保留选中章节及其所属卷
if (t.chapterFilter.length > 0) {
t.nodes = filterSelectedNodes(t.nodes, t.chapterFilter);
const selCount = t.nodes.filter((n: ChapterNode): boolean => n.node.isChapter).length;
if (selCount === 0) {
throw new Error('未选中任何章节');
}
t.addLog('info', `选章下载:${selCount}/${detail.nodes.filter((n: VolumeChapterNode): boolean => n.isChapter).length} 章`);
}
// 简介片段
descLines = detail.descLines;
t.descLines = descLines;
if (descLines.length > 0) {
if (allBlankLines(descLines)) {
descLines = ['【空】'];
t.descLines = descLines;
}
descFragmentPath = chDir + '/desc.xhtml';
writeFragment(descFragmentPath, descLines);
}
// 文件名(同一 id 复用旧名覆盖;选章/自定义名与原书互不影响)
const baseName = `《${bookName}》${author}`;
recordId = t.customTitle.length > 0 ? bookUrl + '#' + baseName : bookUrl;
unique = LibraryStore.uniqueName(baseName, recordId);
} else {
// 增量重试:缓存必须仍存在
if (!fs.accessSync(cacheDir)) {
throw new Error('任务缓存已被清理,请重新下载这本书');
}
ensureDir(chDir);
ensureDir(imgDir);
if (t.nodes.length === 0) {
throw new Error('没有可重试的章节');
}
if (descLines.length > 0) {
descFragmentPath = chDir + '/desc.xhtml';
if (!fs.accessSync(descFragmentPath)) {
writeFragment(descFragmentPath, descLines);
}
}
recordId = t.customTitle.length > 0 ? bookUrl + '#' + `《${bookName}》${author}` : bookUrl;
const exist = LibraryStore.findById(recordId);
unique = exist !== null && exist.baseName.length > 0 ? exist.baseName : `《${bookName}》${author}`;
}
const epubPath = AppHub.uiContext().filesDir + '/library/' + unique + '.epub';
const txtPath = AppHub.uiContext().filesDir + '/library/' + unique + '.txt';
// 封面
if (s.downloadCover && coverUrl.length > 0) {
await this.ensureImage(t, s, coverUrl, imgDir);
}
// 章节并发下载
t.phase = 'chapters';
const chapterNodes = t.nodes.filter((n: ChapterNode): boolean => n.node.isChapter);
t.totalChapters = chapterNodes.length;
t.doneChapters = chapterNodes.filter((n: ChapterNode): boolean =>
n.status === NodeStatus.DONE || n.status === NodeStatus.LOCKED).length;
if (!retryOnly) {
this.imgMap.clear();
}
const cursor: Cursor = { i: 0 };
const workers: Promise<void>[] = [];
for (let w = 0; w < Math.max(1, s.threadCount); w++) {
workers.push(this.chapterWorker(t, s, chapterNodes, cursor, chDir, imgDir));
}
await Promise.all(workers);
if (t.cancelRequested) {
return true;
}
t.currentTitle = '正在打包';
// 组装 TXT
if (s.outputTxt) {
let txt = '';
if (descLines.length > 0) {
txt += '简介\n' + txtOfLines(descLines, this.imgMap);
}
for (const n of t.nodes) {
if (n.node.isChapter && n.status === NodeStatus.FAILED) {
txt += n.node.title + '章节下载失败\n' + n.node.url + '\n';
continue;
}
txt += n.node.title + '\n';
if (n.node.isChapter) {
txt += txtOfLines(n.lines, this.imgMap);
}
}
writeTextFileSync(txtPath, txt);
}
// 打包 EPUB
if (s.outputEpub) {
t.phase = 'build';
this.emit(true);
const nodeItems: EpubNodeItem[] = [];
for (const n of t.nodes) {
const fileName = n.node.isChapter
? (n.status === NodeStatus.FAILED ? `error_novel_${n.node.value}.xhtml` : `novel_${n.node.value}.xhtml`)
: `volume_${n.node.value}.xhtml`;
if (n.node.isChapter && n.fragmentPath === '') {
// 失败章节写入错误占位(等价脚本 error_novel)
const failPath = chDir + '/' + fileName;
const failLines = ['章节下载失败', n.node.url, n.error];
writeFragment(failPath, failLines);
n.fragmentPath = failPath;
}
nodeItems.push({ node: n.node, fileName: fileName, fragmentPath: n.node.isChapter ? n.fragmentPath : '' });
}
const images: EpubImageItem[] = [];
this.imgMap.forEach((v: ImageState, k: string): void => {
if (v.status === 'done' && k !== coverUrl) {
images.push({ url: k, fileName: v.fileName, contentType: v.contentType, filePath: v.filePath });
}
});
let cover: EpubImageItem | undefined = undefined;
if (s.downloadCover && coverUrl.length > 0) {
const cv = this.imgMap.get(coverUrl);
if (cv !== undefined && cv.status === 'done') {
cover = { url: coverUrl, fileName: 'cover' + cv.fileName.substring(cv.fileName.lastIndexOf('.')), contentType: cv.contentType, filePath: cv.filePath };
}
}
const buildInput: EpubBuildInput = {
outPath: epubPath, bookName: bookName, author: author, changeDate: changeDate,
cover: cover, descFragmentPath: descFragmentPath !== '' ? descFragmentPath : undefined,
nodes: nodeItems, images: images
};
try {
buildEpub(buildInput);
t.epubPath = epubPath;
} catch (e) {
t.addLog('error', 'EPUB 打包失败: ' + (e as Error).message);
}
}
t.txtPath = s.outputTxt ? txtPath : '';
// 入库
const record: BookRecord = {
id: recordId, url: bookUrl, name: bookName, author: author, date: changeDate,
baseName: unique,
epubPath: t.epubPath, txtPath: t.txtPath,
chapters: chapterNodes.length, createdAt: Date.now()
};
LibraryStore.upsert(record);
t.phase = 'done';
const failedNow = t.failedChapters;
if (bp !== null) {
// 批量模式:单本结果记入 bp,任务状态由 runList 统一收尾
if (failedNow > 0) {
bp.message = `完成,${failedNow} 章失败`;
t.addLog('warn', `《${bookName}》完成,${failedNow} 章失败(批量模式不做单章重试)`);
}
t.failedChapters = 0;
// 批量模式不保留已完成书籍的章节文本
for (const n of t.nodes) {
n.lines = [];
}
return true;
}
if (failedNow > 0) {
t.status = TaskStatus.DONE_WITH_FAIL;
t.addLog('ok', `《${bookName}》下载完成,${failedNow} 章失败可重试`);
} else {
t.status = TaskStatus.DONE;
t.addLog('ok', `《${bookName}》${changeDate} 下载完成`);
// 无失败章节,释放章节文本内存
for (const n of t.nodes) {
n.lines = [];
}
}
return true;
}
private async chapterWorker(t: TaskInfo, s: AppSettings, list: ChapterNode[], cursor: Cursor,
chDir: string, imgDir: string): Promise<void> {
while (!t.cancelRequested) {
const idx = cursor.i;
if (idx >= list.length) {
return;
}
cursor.i++;
const node = list[idx];
if (node.status !== NodeStatus.PENDING) {
// 增量重试时跳过已完成的章节
continue;
}
node.status = NodeStatus.DOWNLOADING;
t.currentTitle = node.node.title;
this.emit(false);
const fullUrl = urlHandler(node.node.url, s.siteUrl);
const args: FetchChapterArgs = { url: fullUrl, cookie: s.cookie, timeoutMs: s.timeoutSec * 1000, retry: s.retryCount };
const job = new taskpool.Task(fetchChapterJob, args);
let result: FetchChapterResult | null = null;
try {
result = await taskpool.execute(job) as FetchChapterResult;
} catch (e) {
result = { ok: false, status: 'error', lines: [], error: '任务执行失败: ' + (e as Error).message };
}
if (t.cancelRequested) {
node.status = NodeStatus.PENDING;
return;
}
if (result === null || !result.ok || result.status === 'error') {
node.status = NodeStatus.FAILED;
node.error = result !== null ? result.error : '未知错误';
t.failedChapters++;
t.doneChapters++;
t.addLog('error', `章节下载失败「${node.node.title}」: ${node.error}`);
node.touch();
this.emit(false);
continue;
}
// 转换文本(图片占位行不转换)
let lines = result.lines;
const cc = await OpenCC.getConverter(s.convertMode, AppHub.uiContext());
if (cc !== null) {
lines = lines.map((l: string): string => isImgPlaceholder(l) ? l : cc.convert(l));
}
if (result.status === 'locked') {
node.status = NodeStatus.LOCKED;
node.lines = ['本章节需要密码,已跳过'];
} else if (lines.length === 0) {
node.status = NodeStatus.DONE;
node.lines = ['【空】'];
} else {
node.status = NodeStatus.DONE;
node.lines = lines;
}
if (node.node.isChapter) {
const fragPath = `${chDir}/novel_${node.node.value}.xhtml`;
writeFragment(fragPath, node.lines);
node.fragmentPath = fragPath;
}
// 内联下载本章图片
for (const line of node.lines) {
if (isImgPlaceholder(line) && s.downloadImages) {
await this.ensureImage(t, s, imgPlaceholderUrl(line), imgDir);
if (t.cancelRequested) {
return;
}
}
}
t.doneChapters++;
node.touch();
this.emit(false);
}
}
// ---------------- LK(轻之国度 lightnovel.fun)主流程 ----------------
/**
* 下载轻之国度书籍:pc-proxy API 取详情与全部卷章目录,并发抓取章节,
* 整卷长文按目录/标题拆分后并入节点表;图片匿名抓取。
*/
private async runBookLk(t: TaskInfo, s: AppSettings, retryOnly: boolean = false): Promise<boolean> {
const cacheDir = AppHub.uiContext().cacheDir + '/task_' + t.id;
const chDir = cacheDir + '/chapters';
const imgDir = cacheDir + '/images';
const bookId = parseBookId(t.url);
if (bookId.length === 0) {
throw new Error('链接中未找到书籍编号(需要 lightnovel.fun/book/<id> 链接)');
}
const bookUrl = bookPageUrl(bookId);
let bookName = t.bookName;
let author = t.author;
let coverUrl = t.coverUrl;
let unique = '';
let recordId = bookUrl;
if (!retryOnly) {
const host = hostOf(t.url);
if (host.indexOf('lightnovel.fun') < 0) {
throw new Error(`链接域名(${host}) 不受支持,请使用 lightnovel.fun 的书籍链接`);
}
t.phase = 'detail';
t.currentTitle = '获取书籍信息与目录';
this.emit(true);
const cookie = ConfigStore.cleanCookie(s.lkCookie);
const cfg: LkApiCfg = {
cookie: cookie, securityKey: extractSecurityKey(cookie),
timeoutMs: s.timeoutSec * 1000, retry: s.retryCount
};
const cc = await OpenCC.getConverter(s.convertMode, AppHub.uiContext());
const cat: LkCatalogResult = await fetchCatalog(bookId, cfg,
cc !== null ? (x: string): string => cc.convert(x) : null);
if (t.cancelRequested) {
return true;
}
if (cat.nodes.filter((n: VolumeChapterNode): boolean => n.isChapter).length === 0) {
throw new Error('当前书籍没有可下载的章节');
}
bookName = t.customTitle.length > 0 ? t.customTitle : cat.bookName;
author = cat.author;
coverUrl = cat.coverUrl;
t.bookName = bookName;
t.author = author;
t.coverUrl = coverUrl;
if (bookName !== cat.bookName) {
t.addLog('info', `《${cat.bookName}》${author} 开始下载(轻之国度,标题:${bookName})`);
} else {
t.addLog('info', `《${bookName}》${author} 开始下载(轻之国度)`);
}
ensureDir(cacheDir);
ensureDir(chDir);
ensureDir(imgDir);
t.nodes = cat.nodes.map((n: VolumeChapterNode): ChapterNode => new ChapterNode(n));
// 选章下载:仅保留选中章节及其所属卷
if (t.chapterFilter.length > 0) {
const totalCh = cat.nodes.filter((n: VolumeChapterNode): boolean => n.isChapter).length;
t.nodes = filterSelectedNodes(t.nodes, t.chapterFilter);
const selCount = t.nodes.filter((n: ChapterNode): boolean => n.node.isChapter).length;
if (selCount === 0) {
throw new Error('未选中任何章节');
}
t.addLog('info', `选章下载:${selCount}/${totalCh} 章`);
}
const baseName = `《${bookName}》${author}`;
recordId = t.customTitle.length > 0 ? bookUrl + '#' + baseName : bookUrl;
unique = LibraryStore.uniqueName(baseName, recordId);
} else {
// 增量重试:缓存必须仍存在
if (!fs.accessSync(cacheDir)) {
throw new Error('任务缓存已被清理,请重新下载这本书');
}
ensureDir(chDir);
ensureDir(imgDir);
if (t.nodes.length === 0) {
throw new Error('没有可重试的章节');
}
recordId = t.customTitle.length > 0 ? bookUrl + '#' + `《${t.bookName}》${t.author}` : bookUrl;
const exist = LibraryStore.findById(recordId);
unique = exist !== null && exist.baseName.length > 0 ? exist.baseName : `《${t.bookName}》${t.author}`;
}
const epubPath = AppHub.uiContext().filesDir + '/library/' + unique + '.epub';
const txtPath = AppHub.uiContext().filesDir + '/library/' + unique + '.txt';
// 封面(匿名抓取)
if (s.downloadCover && coverUrl.length > 0) {
await this.ensureImage(t, s, coverUrl, imgDir, false);
}
// 章节并发下载
t.phase = 'chapters';
const chapterNodes = t.nodes.filter((n: ChapterNode): boolean => n.node.isChapter);
t.totalChapters = chapterNodes.length;
t.doneChapters = chapterNodes.filter((n: ChapterNode): boolean =>
n.status === NodeStatus.DONE || n.status === NodeStatus.LOCKED).length;
if (!retryOnly) {
this.imgMap.clear();
}
const cursor: Cursor = { i: 0 };
const workers: Promise<void>[] = [];
for (let w = 0; w < Math.max(1, s.threadCount); w++) {
workers.push(this.chapterWorkerLk(t, s, bookId, chapterNodes, cursor, chDir, imgDir));
}
await Promise.all(workers);
if (t.cancelRequested) {
return true;
}
// 整卷长文拆分片段展开为独立章节节点
this.expandParts(t, chDir);
t.currentTitle = '正在打包';
// 组装 TXT(LK 无独立简介段)
if (s.outputTxt) {
let txt = '';
for (const n of t.nodes) {
if (n.node.isChapter && n.status === NodeStatus.FAILED) {
txt += n.node.title + '章节下载失败\n' + n.node.url + '\n';
continue;
}
txt += n.node.title + '\n';
if (n.node.isChapter) {
txt += txtOfLines(n.lines, this.imgMap);
}
}
writeTextFileSync(txtPath, txt);
}
// 打包 EPUB
if (s.outputEpub) {
t.phase = 'build';
this.emit(true);
const nodeItems: EpubNodeItem[] = [];
for (const n of t.nodes) {
const fileName = n.node.isChapter
? (n.status === NodeStatus.FAILED ? `error_novel_${n.node.value}.xhtml` : `novel_${n.node.value}.xhtml`)
: `volume_${n.node.value}.xhtml`;
if (n.node.isChapter && n.fragmentPath === '') {
// 失败章节写入错误占位
const failPath = chDir + '/' + fileName;
const failLines = ['章节下载失败', n.node.url, n.error];
writeFragment(failPath, failLines);
n.fragmentPath = failPath;
}
nodeItems.push({ node: n.node, fileName: fileName, fragmentPath: n.node.isChapter ? n.fragmentPath : '' });
}
const images: EpubImageItem[] = [];
this.imgMap.forEach((v: ImageState, k: string): void => {
if (v.status === 'done' && k !== coverUrl) {
images.push({ url: k, fileName: v.fileName, contentType: v.contentType, filePath: v.filePath });
}
});
let cover: EpubImageItem | undefined = undefined;
if (s.downloadCover && coverUrl.length > 0) {
const cv = this.imgMap.get(coverUrl);
if (cv !== undefined && cv.status === 'done') {
cover = { url: coverUrl, fileName: 'cover' + cv.fileName.substring(cv.fileName.lastIndexOf('.')), contentType: cv.contentType, filePath: cv.filePath };
}
}
const buildInput: EpubBuildInput = {
outPath: epubPath, bookName: bookName, author: author, changeDate: '',
cover: cover, nodes: nodeItems, images: images
};
try {
buildEpub(buildInput);
t.epubPath = epubPath;
} catch (e) {
t.addLog('error', 'EPUB 打包失败: ' + (e as Error).message);
}
}
t.txtPath = s.outputTxt ? txtPath : '';
// 入库
const record: BookRecord = {
id: recordId, url: bookUrl, name: bookName, author: author, date: '',
baseName: unique,
epubPath: t.epubPath, txtPath: t.txtPath,
chapters: chapterNodes.length, createdAt: Date.now()
};
LibraryStore.upsert(record);
t.phase = 'done';
const failedNow = t.failedChapters;
const lockedCount = t.nodes.filter((n: ChapterNode): boolean => n.status === NodeStatus.LOCKED).length;
if (failedNow > 0) {
t.status = TaskStatus.DONE_WITH_FAIL;
t.addLog('ok', `《${bookName}》下载完成,${failedNow} 章失败可重试${lockedCount > 0 ? `(另 ${lockedCount} 章无权限)` : ''}`);
} else {
t.status = TaskStatus.DONE;
t.addLog('ok', `《${bookName}》下载完成${lockedCount > 0 ? `(${lockedCount} 章无阅读权限,已跳过)` : ''}`);
// 无失败章节,释放章节文本内存
for (const n of t.nodes) {
n.lines = [];
n.parts = [];
}
}
return true;
}
private async chapterWorkerLk(t: TaskInfo, s: AppSettings, bookId: string, list: ChapterNode[],
cursor: Cursor, chDir: string, imgDir: string): Promise<void> {
const cc = await OpenCC.getConverter(s.convertMode, AppHub.uiContext());
while (!t.cancelRequested) {
const idx = cursor.i;
if (idx >= list.length) {
return;
}
cursor.i++;
const node = list[idx];
if (node.status !== NodeStatus.PENDING) {
// 增量重试时跳过已完成的章节
continue;
}
node.status = NodeStatus.DOWNLOADING;
t.currentTitle = node.node.title;
this.emit(false);
const cookie = ConfigStore.cleanCookie(s.lkCookie);
const args: FetchLkChapterArgs = {
bookId: bookId, chapterId: chapterIdFromUrl(node.node.url),
cookie: cookie, securityKey: extractSecurityKey(cookie),
timeoutMs: s.timeoutSec * 1000, retry: s.retryCount
};
const job = new taskpool.Task(fetchLkChapterJob, args);
let result: FetchLkChapterResult | null = null;
try {
result = await taskpool.execute(job) as FetchLkChapterResult;
} catch (e) {
result = { ok: false, status: 'error', lines: [], heads: [], error: '任务执行失败: ' + (e as Error).message };
}
if (t.cancelRequested) {
node.status = NodeStatus.PENDING;
return;
}
if (result === null || !result.ok || result.status === 'error') {
node.status = NodeStatus.FAILED;
node.error = result !== null ? result.error : '未知错误';
t.failedChapters++;
t.doneChapters++;
t.addLog('error', `章节下载失败「${node.node.title}」: ${node.error}`);
node.touch();
this.emit(false);
continue;
}
// 转换文本(图片占位行不转换)
let lines = result.lines;
if (cc !== null) {
lines = lines.map((l: string): string => isImgPlaceholder(l) ? l : cc.convert(l));
}
if (result.status === 'locked') {
node.status = NodeStatus.LOCKED;
node.lines = ['该章节当前不可读,需登录或取得阅读权限'];
} else if (lines.length === 0) {
node.status = NodeStatus.DONE;
node.lines = ['【空】'];
} else {
node.status = NodeStatus.DONE;
node.lines = lines;
// 整卷长文:目录/标题匹配成功时暂存片段,打包前展开
const parts: LkLinePart[] = splitChapterLines(lines, result.heads, node.node.title);
if (parts.length > 1) {
const chapterParts: ChapterPart[] = [];
for (const p of parts) {
chapterParts.push({ title: p.title, lines: p.lines });
}
node.parts = chapterParts;
t.addLog('info', `「${node.node.title}」检测到卷内目录/标题,将拆分为 ${parts.length} 节`);
}
}
if (node.node.isChapter && node.parts.length <= 1) {
const fragPath = `${chDir}/novel_${node.node.value}.xhtml`;
writeFragment(fragPath, node.lines);
node.fragmentPath = fragPath;
}
// 内联下载本章图片(匿名,按 URL 去重)
for (const line of node.lines) {
if (isImgPlaceholder(line) && s.downloadImages) {
await this.ensureImage(t, s, imgPlaceholderUrl(line), imgDir, false);
if (t.cancelRequested) {
return;
}
}
}
t.doneChapters++;
node.touch();
this.emit(false);
}
}
/** 将长文拆分片段展开为独立章节节点(新 value 接在最大值之后,沿用原章节的父卷) */
private expandParts(t: TaskInfo, chDir: string): void {
let hasParts = false;
for (const n of t.nodes) {
if (n.node.isChapter && n.parts.length > 1) {
hasParts = true;
break;
}
}
if (!hasParts) {
return;
}
let maxV = 0;
for (const n of t.nodes) {
if (n.node.value > maxV) {
maxV = n.node.value;
}
}
const out: ChapterNode[] = [];
let partCount = 0;
for (const n of t.nodes) {
if (n.node.isChapter && n.parts.length > 1) {
for (const p of n.parts) {
maxV++;
partCount++;
const copy: VolumeChapterNode = {
value: maxV, level: n.node.level, fatherValue: n.node.fatherValue,
isVolume: false, isChapter: true, title: p.title, url: n.node.url
};
const cn = new ChapterNode(copy);
cn.status = NodeStatus.DONE;
cn.lines = p.lines;
const fragPath = `${chDir}/novel_${maxV}.xhtml`;
writeFragment(fragPath, p.lines);
cn.fragmentPath = fragPath;
out.push(cn);
}
continue;
}
out.push(n);
}
t.nodes = out;
t.addLog('info', `长章节已拆分为 ${partCount} 节`);
}
/** useCookie=false 用于 LK:插图按脚本约定匿名抓取(不附带 Cookie/security_key) */
private async ensureImage(t: TaskInfo, s: AppSettings, url: string, imgDir: string,
useCookie: boolean = true): Promise<void> {
if (this.imgMap.has(url)) {
return;
}
const st: ImageState = { status: 'inflight', fileName: '', filePath: '', contentType: '', error: '' };
this.imgMap.set(url, st);
t.totalImages = this.imgMap.size;
const fullUrl = urlHandler(url, s.siteUrl);
const args: FetchImageArgs = { url: fullUrl, cookie: useCookie ? s.cookie : '', timeoutMs: s.timeoutSec * 1000, retry: s.retryCount };
const job = new taskpool.Task(fetchImageJob, args);
let result: FetchImageResult | null = null;
try {
result = await taskpool.execute(job) as FetchImageResult;
} catch (e) {
result = { ok: false, ext: '', hash: '', data: new ArrayBuffer(0), error: (e as Error).message };
}
if (result !== null && result.ok) {
const fileName = `Image_${result.hash}${result.ext}`;
const filePath = imgDir + '/' + fileName;
try {
const f = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE | fs.OpenMode.TRUNC);
fs.writeSync(f.fd, result.data);
fs.closeSync(f);
st.status = 'done';
st.fileName = fileName;
st.filePath = filePath;
st.contentType = 'image/' + result.ext.substring(1);
} catch (e) {
st.status = 'failed';
st.error = '写入失败: ' + (e as Error).message;
}
} else {
st.status = 'failed';
st.error = result !== null ? result.error : '未知错误';
t.addLog('warn', `图片下载失败: ${url} ${st.error}`);
}
t.doneImages++;
this.emit(false);
}
private cleanupCache(t: TaskInfo): void {
try {
const cacheDir = AppHub.uiContext().cacheDir + '/task_' + t.id;
deleteDirRecursive(cacheDir);
} catch (e) {
// 目录不存在或删除失败,忽略
}
}
}
// ---------------- 辅助函数 ----------------
function checkDomain(url: string, siteUrl: string): string {
const h1 = hostOf(url);
const h2 = hostOf(siteUrl);
if (h1.length === 0 || h2.length === 0) {
return '链接或站点域名无法解析';
}
if (h1 !== h2) {
return `链接域名(${h1}) 与设置中的站点域名(${h2}) 不一致。请修改设置中的站点域名,或使用对应域名的 Cookie。`;
}
return '';
}
function ensureDir(path: string): void {
try {
if (!fs.accessSync(path)) {
fs.mkdirSync(path, true);
}
} catch (e) {
try {
fs.mkdirSync(path, true);
} catch (e2) {
// 忽略
}
}
}
function deleteDirRecursive(path: string): void {
try {
if (!fs.accessSync(path)) {
return;
}
const children = fs.listFileSync(path);
for (const name of children) {
const full = path + '/' + name;
if (fs.statSync(full).isDirectory()) {
deleteDirRecursive(full);
} else {
fs.unlinkSync(full);
}
}
fs.rmdirSync(path);
} catch (e) {
// 尽力清理
}
}
/** 将文本行写入片段文件:文本行转 <p>,占位行原样保留(打包时替换) */
function writeFragment(path: string, lines: string[]): void {
const out: string[] = [];
for (const line of lines) {
if (isImgPlaceholder(line)) {
out.push(line);
} else {
out.push('<p>' + escapeXml(line) + '</p>');
}
}
writeTextFileSync(path, out.join('\n'));
}
function writeTextFileSync(path: string, text: string): void {
const bytes = util.TextEncoder.create().encodeInto(text);
const f = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE | fs.OpenMode.TRUNC);
try {
fs.writeSync(f.fd, bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
} finally {
fs.closeSync(f);
}
}
/** 文本行 → TXT 内容(占位行替换为 URL,等价脚本 imgTagConvert) */
function txtOfLines(lines: string[], imgMap: Map<string, ImageState>): string {
const out: string[] = [];
for (const line of lines) {
if (isImgPlaceholder(line)) {
const url = imgPlaceholderUrl(line);
const st = imgMap.get(url);
if (st !== undefined && st.status === 'done') {
out.push(url);
} else {
out.push('下载失败:' + url);
}
} else {
out.push(line);
}
}
return out.join('\n') + '\n';
}
function allBlankLines(lines: string[]): boolean {
for (const l of lines) {
if (isImgPlaceholder(l)) {
return false; // 图片占位也算有效内容
}
if (l.replace(/\s/g, '').length > 0) {
return false;
}
}
return true;
}
/**
* 选章过滤:保留选中章节与其所属各级卷,并重排 value/fatherValue,
* 使剩余节点仍构成一棵合法目录树(等价于脚本对 node 列表的裁剪)。
*/
function filterSelectedNodes(nodes: ChapterNode[], filter: number[]): ChapterNode[] {
const selected: Set<number> = new Set();
for (const v of filter) {
selected.add(v);
}
const keep: boolean[] = new Array(nodes.length);
keep.fill(false);
// 自底向上:章节按选中集,卷按"含被保留子节点"保留
for (let i = nodes.length - 1; i >= 0; i--) {
const nd = nodes[i].node;
if (nd.isChapter) {
keep[i] = selected.has(nd.value);
} else {
let any = false;
for (let j = i + 1; j < nodes.length; j++) {
if (keep[j] && nodes[j].node.fatherValue === nd.value) {
any = true;
break;
}
}
keep[i] = any;
}
}
const out: ChapterNode[] = [];
const idMap: Map<number, number> = new Map();
for (let i = 0; i < nodes.length; i++) {
if (!keep[i]) {
continue;
}
const src = nodes[i].node;
const copy: VolumeChapterNode = {
value: src.value, level: src.level, fatherValue: src.fatherValue,
isVolume: src.isVolume, isChapter: src.isChapter, title: src.title, url: src.url
};
idMap.set(src.value, out.length);
out.push(new ChapterNode(copy));
}
for (const cn of out) {
cn.node.value = idMap.get(cn.node.value) ?? cn.node.value;
}
for (const cn of out) {
if (cn.node.fatherValue >= 0) {
cn.node.fatherValue = idMap.get(cn.node.fatherValue) ?? -1;
}
}
return out;
}