feat: 书籍链接解析下载
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
import { preferences } from '@kit.ArkData';
|
||||
import { common } from '@kit.AbilityKit';
|
||||
|
||||
/**
|
||||
* 应用配置:对应原脚本开头全部参数,全部页面可配置并持久化。
|
||||
* - siteUrl -> base_url
|
||||
* - cookie -> esj.txt 第一行(含 ews_key / ews_token)
|
||||
* - convertMode -> opencc t2s / s2t / none
|
||||
* - threadCount -> threadNum(并发数)
|
||||
* - retryCount -> retrying stop_max_attempt_number
|
||||
* - timeoutSec -> requests timeout
|
||||
* - downloadImages / downloadCover / outputEpub / outputTxt -> 输出控制
|
||||
*/
|
||||
export const CONVERT_T2S: string = 't2s';
|
||||
export const CONVERT_S2T: string = 's2t';
|
||||
export const CONVERT_NONE: string = 'none';
|
||||
|
||||
export interface AppSettings {
|
||||
siteUrl: string;
|
||||
cookie: string;
|
||||
convertMode: string;
|
||||
threadCount: number;
|
||||
retryCount: number;
|
||||
timeoutSec: number;
|
||||
downloadImages: boolean;
|
||||
downloadCover: boolean;
|
||||
outputEpub: boolean;
|
||||
outputTxt: boolean;
|
||||
}
|
||||
|
||||
export function defaultSettings(): AppSettings {
|
||||
const s: AppSettings = {
|
||||
siteUrl: 'https://www.esjzone.cc/',
|
||||
cookie: '',
|
||||
convertMode: CONVERT_T2S,
|
||||
threadCount: 2,
|
||||
retryCount: 3,
|
||||
timeoutSec: 25,
|
||||
downloadImages: true,
|
||||
downloadCover: true,
|
||||
outputEpub: true,
|
||||
outputTxt: true
|
||||
};
|
||||
return s;
|
||||
}
|
||||
|
||||
export class ConfigStore {
|
||||
private static prefs: preferences.Preferences | null = null;
|
||||
private static cache: AppSettings | null = null;
|
||||
|
||||
static async init(ctx: common.Context): Promise<void> {
|
||||
ConfigStore.prefs = await preferences.getPreferences(ctx, 'esj_config');
|
||||
const raw = ConfigStore.prefs.getSync('settings_json', '') as string;
|
||||
const base = defaultSettings();
|
||||
if (raw.length > 0) {
|
||||
try {
|
||||
const obj = JSON.parse(raw) as Record<string, Object>;
|
||||
base.siteUrl = strOf(obj, 'siteUrl', base.siteUrl);
|
||||
base.cookie = strOf(obj, 'cookie', base.cookie);
|
||||
base.convertMode = strOf(obj, 'convertMode', base.convertMode);
|
||||
base.threadCount = numOf(obj, 'threadCount', base.threadCount);
|
||||
base.retryCount = numOf(obj, 'retryCount', base.retryCount);
|
||||
base.timeoutSec = numOf(obj, 'timeoutSec', base.timeoutSec);
|
||||
base.downloadImages = boolOf(obj, 'downloadImages', base.downloadImages);
|
||||
base.downloadCover = boolOf(obj, 'downloadCover', base.downloadCover);
|
||||
base.outputEpub = boolOf(obj, 'outputEpub', base.outputEpub);
|
||||
base.outputTxt = boolOf(obj, 'outputTxt', base.outputTxt);
|
||||
} catch (e) {
|
||||
// 配置损坏时使用默认值
|
||||
}
|
||||
}
|
||||
ConfigStore.cache = base;
|
||||
}
|
||||
|
||||
static get(): AppSettings {
|
||||
if (ConfigStore.cache === null) {
|
||||
ConfigStore.cache = defaultSettings();
|
||||
}
|
||||
return ConfigStore.cache;
|
||||
}
|
||||
|
||||
static async save(s: AppSettings): Promise<void> {
|
||||
ConfigStore.cache = s;
|
||||
if (ConfigStore.prefs === null) {
|
||||
return;
|
||||
}
|
||||
ConfigStore.prefs.putSync('settings_json', JSON.stringify(s));
|
||||
await ConfigStore.prefs.flush();
|
||||
}
|
||||
|
||||
/** cookie 是否包含关键登录字段 */
|
||||
static cookieOk(cookie: string): boolean {
|
||||
return cookie.indexOf('ews_key') >= 0 && cookie.indexOf('ews_token') >= 0;
|
||||
}
|
||||
|
||||
/** 清理 cookie 字符串:去掉换行、首尾空格 */
|
||||
static cleanCookie(cookie: string): string {
|
||||
return cookie.replace(/\r?\n/g, '').trim();
|
||||
}
|
||||
}
|
||||
|
||||
function strOf(obj: Record<string, Object>, key: string, def: string): string {
|
||||
const v = obj[key];
|
||||
return typeof v === 'string' ? v : def;
|
||||
}
|
||||
|
||||
function numOf(obj: Record<string, Object>, key: string, def: number): number {
|
||||
const v = obj[key];
|
||||
return typeof v === 'number' ? v : def;
|
||||
}
|
||||
|
||||
function boolOf(obj: Record<string, Object>, key: string, def: boolean): boolean {
|
||||
const v = obj[key];
|
||||
return typeof v === 'boolean' ? v : def;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { TocPreviewNode } from './TaskModel';
|
||||
|
||||
/**
|
||||
* 单本下载的"选章 + 自定义标题"草稿。
|
||||
* 与目标 URL 绑定;URL 变化时自动清空,避免串书。
|
||||
*/
|
||||
export class DownloadDraft {
|
||||
static url: string = '';
|
||||
static customTitle: string = '';
|
||||
static chapterFilter: number[] = []; // 空 = 全部章节
|
||||
static nodes: TocPreviewNode[] = []; // 已抓取的目录缓存
|
||||
static bookName: string = '';
|
||||
static author: string = '';
|
||||
|
||||
static reset(): void {
|
||||
DownloadDraft.url = '';
|
||||
DownloadDraft.customTitle = '';
|
||||
DownloadDraft.chapterFilter = [];
|
||||
DownloadDraft.nodes = [];
|
||||
DownloadDraft.bookName = '';
|
||||
DownloadDraft.author = '';
|
||||
}
|
||||
|
||||
/** 目标 URL 变化时清空草稿(避免不同书籍沿用旧的选章/标题) */
|
||||
static onUrlChanged(newUrl: string): void {
|
||||
if (DownloadDraft.url === newUrl) {
|
||||
return;
|
||||
}
|
||||
DownloadDraft.reset();
|
||||
DownloadDraft.url = newUrl;
|
||||
}
|
||||
|
||||
static hasCacheFor(url: string): boolean {
|
||||
return DownloadDraft.url === url && DownloadDraft.nodes.length > 0;
|
||||
}
|
||||
|
||||
static filterActiveFor(url: string): boolean {
|
||||
return DownloadDraft.url === url && DownloadDraft.chapterFilter.length > 0;
|
||||
}
|
||||
|
||||
static chapterTotal(): number {
|
||||
let n = 0;
|
||||
for (const nd of DownloadDraft.nodes) {
|
||||
if (nd.isChapter) {
|
||||
n++;
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import { preferences } from '@kit.ArkData';
|
||||
import { fileIo as fs } from '@kit.CoreFileKit';
|
||||
import { AppHub } from '../common/AppHub';
|
||||
|
||||
/**
|
||||
* 书库记录:已生成书籍的持久化索引。
|
||||
*/
|
||||
|
||||
export interface BookRecord {
|
||||
id: string; // 原书下载 = 详情页链接;选章/自定义标题下载 = 链接#《自定义名》作者
|
||||
url: string; // 详情页链接
|
||||
name: string;
|
||||
author: string;
|
||||
date: string; // 更新日期
|
||||
baseName: string; // 不含扩展名的文件名(《书名》作者)
|
||||
epubPath: string;
|
||||
txtPath: string;
|
||||
chapters: number;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export class LibraryStore {
|
||||
private static prefs: preferences.Preferences | null = null;
|
||||
private static records: BookRecord[] = [];
|
||||
|
||||
static async init(): Promise<void> {
|
||||
LibraryStore.prefs = await preferences.getPreferences(AppHub.uiContext(), 'esj_library');
|
||||
const raw = LibraryStore.prefs.getSync('library_json', '') as string;
|
||||
LibraryStore.records = [];
|
||||
if (raw.length > 0) {
|
||||
try {
|
||||
const arr = JSON.parse(raw) as BookRecord[];
|
||||
for (const r of arr) {
|
||||
LibraryStore.records.push(r);
|
||||
}
|
||||
} catch (e) {
|
||||
LibraryStore.records = [];
|
||||
}
|
||||
}
|
||||
ensureLibraryDir();
|
||||
}
|
||||
|
||||
static list(): BookRecord[] {
|
||||
return LibraryStore.records.slice().sort((a: BookRecord, b: BookRecord): number => b.createdAt - a.createdAt);
|
||||
}
|
||||
|
||||
static save(): void {
|
||||
if (LibraryStore.prefs === null) {
|
||||
return;
|
||||
}
|
||||
LibraryStore.prefs.putSync('library_json', JSON.stringify(LibraryStore.records));
|
||||
LibraryStore.prefs.flush();
|
||||
}
|
||||
|
||||
static findByUrl(url: string): BookRecord | null {
|
||||
// 仅匹配"原书下载"记录(id === 链接),批量模式的日期去重使用
|
||||
for (const r of LibraryStore.records) {
|
||||
if (r.id === url) {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static findById(id: string): BookRecord | null {
|
||||
for (const r of LibraryStore.records) {
|
||||
if (r.id === id) {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 同一 id 重新下载时替换记录并清理旧文件;不同 id(如选章自定义名)各自独立保留 */
|
||||
static upsert(record: BookRecord): void {
|
||||
const idx = LibraryStore.records.findIndex((r: BookRecord): boolean => r.id === record.id);
|
||||
if (idx >= 0) {
|
||||
const old = LibraryStore.records[idx];
|
||||
if (old.baseName !== record.baseName) {
|
||||
// 文件名变了:清理旧文件,避免残留
|
||||
deleteQuietly(old.epubPath);
|
||||
deleteQuietly(old.txtPath);
|
||||
}
|
||||
LibraryStore.records.splice(idx, 1);
|
||||
}
|
||||
LibraryStore.records.push(record);
|
||||
LibraryStore.save();
|
||||
}
|
||||
|
||||
static remove(id: string): void {
|
||||
const idx = LibraryStore.records.findIndex((r: BookRecord): boolean => r.id === id);
|
||||
if (idx >= 0) {
|
||||
const old = LibraryStore.records[idx];
|
||||
deleteQuietly(old.epubPath);
|
||||
deleteQuietly(old.txtPath);
|
||||
LibraryStore.records.splice(idx, 1);
|
||||
LibraryStore.save();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 为书籍生成不冲突的基础文件名。
|
||||
* 同一 id(原书刷新 / 同名选章重下)复用旧文件名以便覆盖;
|
||||
* 不同内容若与磁盘文件重名则追加序号。
|
||||
*/
|
||||
static uniqueName(base: string, id: string): string {
|
||||
const exist = LibraryStore.findById(id);
|
||||
if (exist !== null && exist.baseName.length > 0) {
|
||||
return exist.baseName;
|
||||
}
|
||||
const dir = AppHub.uiContext().filesDir + '/library';
|
||||
let name = base;
|
||||
let n = 2;
|
||||
while (LibraryStore.existsFile(dir + '/' + name + '.epub') || LibraryStore.existsFile(dir + '/' + name + '.txt')) {
|
||||
name = base + `(${n})`;
|
||||
n++;
|
||||
if (n > 50) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
static existsFile(path: string): boolean {
|
||||
try {
|
||||
return fs.accessSync(path);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function deleteQuietly(path: string): void {
|
||||
if (path.length === 0) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (fs.accessSync(path)) {
|
||||
fs.unlinkSync(path);
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
|
||||
export function ensureLibraryDir(): void {
|
||||
const dir = AppHub.uiContext().filesDir + '/library';
|
||||
try {
|
||||
if (!fs.accessSync(dir)) {
|
||||
fs.mkdirSync(dir, true);
|
||||
}
|
||||
} catch (e) {
|
||||
try {
|
||||
fs.mkdirSync(dir, true);
|
||||
} catch (e2) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,837 @@
|
||||
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 } 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 { buildEpub, EpubBuildInput, EpubImageItem, EpubNodeItem, escapeXml } from '../core/EpubWriter';
|
||||
import { fetchChapterJob, fetchImageJob, FetchChapterArgs, FetchImageArgs, FetchChapterResult, FetchImageResult } 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[] = []): TaskInfo {
|
||||
const t = new TaskInfo();
|
||||
t.id = 'task_' + Date.now().toString(36) + '_' + Math.floor(Math.random() * 1000);
|
||||
t.mode = mode;
|
||||
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' ? '创建批量下载任务' : '创建下载任务');
|
||||
this.emit(true);
|
||||
if (this.activeTaskId === '') {
|
||||
this.startTask(t);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/** 拉取目录预览(选章下载用)。返回纯数据,不改任务状态。 */
|
||||
async fetchTocPreview(url: string): Promise<TocPreviewResult> {
|
||||
const s = ConfigStore.get();
|
||||
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;
|
||||
}
|
||||
|
||||
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 {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
private async ensureImage(t: TaskInfo, s: AppSettings, url: string, imgDir: string): 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: 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;
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import { VolumeChapterNode } from '../core/EsjCore';
|
||||
import { NodeStatus, TaskStatus } from '../common/Theme';
|
||||
|
||||
/**
|
||||
* 任务数据模型 + UI 数据源。
|
||||
*/
|
||||
|
||||
export interface LogLine {
|
||||
time: string;
|
||||
level: string; // info | warn | error | ok
|
||||
msg: string;
|
||||
}
|
||||
|
||||
export class ChapterNode {
|
||||
node: VolumeChapterNode;
|
||||
status: string = NodeStatus.PENDING;
|
||||
lines: string[] = []; // 转换后的文本行(含图片占位行)
|
||||
error: string = '';
|
||||
fragmentPath: string = '';
|
||||
doneTick: number = 0; // 用于驱动 UI 刷新
|
||||
|
||||
constructor(node: VolumeChapterNode) {
|
||||
this.node = node;
|
||||
}
|
||||
|
||||
touch(): void {
|
||||
this.doneTick++;
|
||||
}
|
||||
}
|
||||
|
||||
export interface BookProgress {
|
||||
url: string;
|
||||
name: string;
|
||||
author: string;
|
||||
date: string;
|
||||
status: string;
|
||||
doneCh: number;
|
||||
totalCh: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/** 章节选择页用的目录预览节点(纯数据,可跨线程返回) */
|
||||
export interface TocPreviewNode {
|
||||
value: number;
|
||||
level: number;
|
||||
fatherValue: number;
|
||||
isVolume: boolean;
|
||||
isChapter: boolean;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export interface TocPreviewResult {
|
||||
ok: boolean;
|
||||
error: string;
|
||||
nodes: TocPreviewNode[];
|
||||
bookName: string;
|
||||
author: string;
|
||||
}
|
||||
|
||||
export class TaskInfo {
|
||||
id: string = '';
|
||||
mode: string = 'book'; // book | list
|
||||
url: string = '';
|
||||
status: string = TaskStatus.QUEUED;
|
||||
bookName: string = '';
|
||||
author: string = '';
|
||||
changeDate: string = '';
|
||||
coverUrl: string = '';
|
||||
descLines: string[] = []; // 转换后的简介行(含图片占位)
|
||||
phase: string = ''; // detail | list | chapters | images | build
|
||||
totalChapters: number = 0;
|
||||
doneChapters: number = 0;
|
||||
failedChapters: number = 0;
|
||||
totalImages: number = 0;
|
||||
doneImages: number = 0;
|
||||
currentTitle: string = '';
|
||||
nodes: ChapterNode[] = [];
|
||||
books: BookProgress[] = []; // 批量模式
|
||||
logs: LogLine[] = [];
|
||||
errorMessage: string = '';
|
||||
epubPath: string = '';
|
||||
txtPath: string = '';
|
||||
createdAt: number = 0;
|
||||
cancelRequested: boolean = false;
|
||||
customTitle: string = ''; // 用户自定义 EPUB 标题(空=用原书名)
|
||||
chapterFilter: number[] = []; // 选中的章节节点 value(空=全部)
|
||||
activeBooksDone: number = 0;
|
||||
activeBooksTotal: number = 0;
|
||||
versionTick: number = 0; // 每次有变化自增,驱动界面刷新
|
||||
|
||||
touch(): void {
|
||||
this.versionTick++;
|
||||
}
|
||||
|
||||
addLog(level: string, msg: string): void {
|
||||
const d = new Date();
|
||||
const time = `${d.getHours() < 10 ? '0' : ''}${d.getHours()}:${d.getMinutes() < 10 ? '0' : ''}${d.getMinutes()}:${d.getSeconds() < 10 ? '0' : ''}${d.getSeconds()}`;
|
||||
this.logs.push({ time: time, level: level, msg: msg });
|
||||
if (this.logs.length > 400) {
|
||||
this.logs.splice(0, this.logs.length - 400);
|
||||
}
|
||||
}
|
||||
|
||||
progressPercent(): number {
|
||||
if (this.mode === 'list') {
|
||||
if (this.activeBooksTotal === 0) {
|
||||
return this.phase === 'list' ? 5 : 0;
|
||||
}
|
||||
return Math.floor(this.activeBooksDone * 100 / this.activeBooksTotal);
|
||||
}
|
||||
if (this.totalChapters === 0) {
|
||||
return this.status === TaskStatus.DONE || this.status === TaskStatus.DONE_WITH_FAIL ? 100 : 0;
|
||||
}
|
||||
return Math.floor(this.doneChapters * 100 / this.totalChapters);
|
||||
}
|
||||
}
|
||||
|
||||
/** LazyForEach 数据源 */
|
||||
export class NodeDataSource implements IDataSource {
|
||||
private listeners: DataChangeListener[] = [];
|
||||
items: ChapterNode[] = [];
|
||||
|
||||
setItems(items: ChapterNode[]): void {
|
||||
this.items = items;
|
||||
this.notifyDataReload();
|
||||
}
|
||||
|
||||
totalCount(): number {
|
||||
return this.items.length;
|
||||
}
|
||||
|
||||
getData(index: number): ChapterNode {
|
||||
return this.items[index];
|
||||
}
|
||||
|
||||
idxOf(node: ChapterNode): number {
|
||||
return this.items.indexOf(node);
|
||||
}
|
||||
|
||||
registerDataChangeListener(listener: DataChangeListener): void {
|
||||
this.listeners.push(listener);
|
||||
}
|
||||
|
||||
unregisterDataChangeListener(listener: DataChangeListener): void {
|
||||
const idx = this.listeners.indexOf(listener);
|
||||
if (idx >= 0) {
|
||||
this.listeners.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
|
||||
notifyDataReload(): void {
|
||||
for (const l of this.listeners) {
|
||||
l.onDataReloaded();
|
||||
}
|
||||
}
|
||||
|
||||
notifyChangedAt(index: number): void {
|
||||
for (const l of this.listeners) {
|
||||
l.onDataChange(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class TaskDataSource implements IDataSource {
|
||||
private listeners: DataChangeListener[] = [];
|
||||
items: TaskInfo[] = [];
|
||||
|
||||
setItems(items: TaskInfo[]): void {
|
||||
this.items = items;
|
||||
this.notifyDataReload();
|
||||
}
|
||||
|
||||
totalCount(): number {
|
||||
return this.items.length;
|
||||
}
|
||||
|
||||
getData(index: number): TaskInfo {
|
||||
return this.items[index];
|
||||
}
|
||||
|
||||
registerDataChangeListener(listener: DataChangeListener): void {
|
||||
this.listeners.push(listener);
|
||||
}
|
||||
|
||||
unregisterDataChangeListener(listener: DataChangeListener): void {
|
||||
const idx = this.listeners.indexOf(listener);
|
||||
if (idx >= 0) {
|
||||
this.listeners.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
|
||||
notifyDataReload(): void {
|
||||
for (const l of this.listeners) {
|
||||
l.onDataReloaded();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user