feat: lk下载功能选项

This commit is contained in:
R-HUA
2026-10-12 09:12:07 +08:00
parent 5a731e80b6
commit 727473fdcc
11 changed files with 1404 additions and 209 deletions
+124 -16
View File
@@ -19,7 +19,7 @@ export interface LkApiCfg {
retry: number;
}
/** 目录抓取结果(节点为 ESJ 同构的 VolumeChapterNode,可直接进入选章/任务管线) */
/** 目录抓取结果(节点为 ESJ 同构的 VolumeChapterNode,可直接进入任务管线) */
export interface LkCatalogResult {
ok: boolean;
error: string;
@@ -28,18 +28,38 @@ export interface LkCatalogResult {
author: string;
coverUrl: string;
nodes: VolumeChapterNode[];
volumeTitles: string[]; // 实际收录卷的标题(按目录顺序)
volumeTotal: number; // 书籍全部卷数(用于判断"部分卷")
}
/** 章节解析结果:文本行 + 是否来自 h1-h6 标题(供长文拆分使用) */
/** 卷信息(等价脚本 get-book-volumes 列表项) */
export interface LkVolumeInfo {
volumeId: string;
title: string;
chapterCount: number; // API 未返回时为 NaN
}
export interface LkVolumeListResult {
ok: boolean;
error: string;
bookName: string;
author: string;
coverUrl: string;
volumes: LkVolumeInfo[];
}
/** 章节解析结果:文本行 + 标题/免转换标记(供长文拆分与繁简转换使用) */
export interface LkLineContent {
lines: string[];
heads: boolean[];
heads: boolean[]; // 行是否来自 h1-h3 标题(长文拆分用,等价脚本 heading 判定)
noConv: boolean[]; // 行是否位于 pre/code 内(繁简转换跳过,等价脚本 simplifyContent)
}
export interface LkChapterParse {
status: string; // ok | locked | error
lines: string[];
heads: boolean[];
noConv: boolean[];
error: string;
}
@@ -133,6 +153,20 @@ function jYes(v: Object | undefined): boolean {
return false;
}
function jNum(o: JObj | null, key: string): number {
if (o === null) {
return NaN;
}
const v = o[key];
if (typeof v === 'number') {
return v as number;
}
if (typeof v === 'string' && (v as string).length > 0) {
return Number(v);
}
return NaN;
}
const CONTROL_RE = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF\uD800-\uDFFF]/gu;
function cleanText(s: string): string {
@@ -335,24 +369,28 @@ const DROP_TAGS: Set<string> = new Set<string>(['script', 'style', 'iframe', 'ob
'input', 'button', 'textarea', 'select', 'link', 'meta', 'base', 'noscript', 'svg', 'math',
'audio', 'video', 'source']);
const SKIP_TEXT_TAGS: Set<string> = new Set<string>(['rt', 'rp']);
const HEAD_TAGS: Set<string> = new Set<string>(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
const BLOCK_TAGS: Set<string> = new Set<string>(['p', 'div', 'table', 'thead', 'tbody', 'tfoot', 'tr',
'td', 'th', 'caption', 'ul', 'ol', 'li', 'blockquote', 'pre', 'figure', 'figcaption', 'section',
'article', 'aside', 'header', 'footer', 'hr', 'details', 'summary']);
// 标题判定仅 h1-h3(等价脚本 heading() 的 /^h[1-3]$/)
const HEAD_TAGS: Set<string> = new Set<string>(['h1', 'h2', 'h3']);
const BLOCK_TAGS: Set<string> = new Set<string>(['p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'table',
'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'caption', 'ul', 'ol', 'li', 'blockquote', 'pre',
'figure', 'figcaption', 'section', 'article', 'aside', 'header', 'footer', 'hr', 'details', 'summary']);
const RES_RE = /\[res\]([\s\S]*?)\[\/res\]/gi;
class LineBuilder {
lines: string[] = [];
heads: boolean[] = [];
noConv: boolean[] = [];
private cur: string = '';
private curHead: boolean = false;
private preDepth: number = 0;
flush(): void {
const t = this.cur.trim();
if (t.length > 0) {
this.lines.push(t);
this.heads.push(this.curHead);
this.noConv.push(this.preDepth > 0);
}
this.cur = '';
this.curHead = false;
@@ -362,12 +400,14 @@ class LineBuilder {
this.flush();
this.lines.push(imgPlaceholder(url));
this.heads.push(false);
this.noConv.push(false);
}
emitLine(text: string): void {
this.flush();
this.lines.push(text);
this.heads.push(false);
this.noConv.push(false);
}
append(text: string): void {
@@ -377,6 +417,16 @@ class LineBuilder {
markHead(): void {
this.curHead = true;
}
enterPre(): void {
this.preDepth++;
}
exitPre(): void {
if (this.preDepth > 0) {
this.preDepth--;
}
}
}
/** 文本节点:处理 [res]key[/res] 插图标记(等价脚本 appendText) */
@@ -455,6 +505,19 @@ function walkNode(n: HtmlNode, b: LineBuilder, res: Map<string, string>, baseUrl
walkChildren(n.children, b, res, baseUrl);
return;
}
if (tag === 'pre' || tag === 'code') {
// pre/code 内容不做繁简转换(等价脚本 simplifyContent 跳过 closest('code,pre'))
b.enterPre();
if (BLOCK_TAGS.has(tag)) {
b.flush();
walkChildren(n.children, b, res, baseUrl);
b.flush();
} else {
walkChildren(n.children, b, res, baseUrl);
}
b.exitPre();
return;
}
if (BLOCK_TAGS.has(tag)) {
b.flush();
if (HEAD_TAGS.has(tag)) {
@@ -472,7 +535,7 @@ export function htmlToLines(html: string, res: Map<string, string>, baseUrl: str
const root = parseHtml(html);
walkChildren(root.children, b, res, baseUrl);
b.flush();
const r: LkLineContent = { lines: b.lines, heads: b.heads };
const r: LkLineContent = { lines: b.lines, heads: b.heads, noConv: b.noConv };
return r;
}
@@ -489,6 +552,7 @@ export function bbcodeToLines(text: string, baseUrl: string): LkLineContent {
s = s.replace(/\[url\](https?:\/\/[^\s]+?)\[\/url\]/gi, '\n[$1]\n$1\n');
const lines: string[] = [];
const heads: boolean[] = [];
const noConv: boolean[] = [];
const raw = s.split(/\r?\n/);
for (const l of raw) {
const t = l.trim();
@@ -500,12 +564,14 @@ export function bbcodeToLines(text: string, baseUrl: string): LkLineContent {
const abs = urlHandler(im[1], baseUrl);
lines.push(abs.length > 0 ? imgPlaceholder(abs) : '〔无法解析的插图:' + im[1].substring(0, 60) + '〕');
heads.push(false);
noConv.push(false);
continue;
}
lines.push(t);
heads.push(false);
noConv.push(false);
}
const r: LkLineContent = { lines: lines, heads: heads };
const r: LkLineContent = { lines: lines, heads: heads, noConv: noConv };
return r;
}
@@ -515,7 +581,7 @@ function parseChapterData(data: JObj, bookId: string, chapterId: string): LkChap
const locked = jYes(data['locked']) || jYes(data['is_locked'])
|| (jYes(data['brave_required']) && !jYes(data['unlocked']));
if (locked) {
const r: LkChapterParse = { status: 'locked', lines: [], heads: [], error: '' };
const r: LkChapterParse = { status: 'locked', lines: [], heads: [], noConv: [], error: '' };
return r;
}
const rp = asObj(data['render_preview']);
@@ -542,17 +608,17 @@ function parseChapterData(data: JObj, bookId: string, chapterId: string): LkChap
if (html.trim().length > 0) {
const c = htmlToLines(html, res, reader);
if (c.lines.length > 0) {
const r2: LkChapterParse = { status: 'ok', lines: c.lines, heads: c.heads, error: '' };
const r2: LkChapterParse = { status: 'ok', lines: c.lines, heads: c.heads, noConv: c.noConv, error: '' };
return r2;
}
} else if (text.trim().length > 0) {
const c2 = bbcodeToLines(text, reader);
if (c2.lines.length > 0) {
const r3: LkChapterParse = { status: 'ok', lines: c2.lines, heads: c2.heads, error: '' };
const r3: LkChapterParse = { status: 'ok', lines: c2.lines, heads: c2.heads, noConv: c2.noConv, error: '' };
return r3;
}
}
const r4: LkChapterParse = { status: 'error', lines: [], heads: [], error: '该章节未返回正文' };
const r4: LkChapterParse = { status: 'error', lines: [], heads: [], noConv: [], error: '该章节未返回正文' };
return r4;
}
@@ -565,9 +631,40 @@ export async function fetchChapterLines(bookId: string, chapterId: string, cfg:
// ---------------- 目录抓取 ----------------
/** 抓取书籍详情 + 全部卷章目录(分页),产出与 ESJ 同构的目录树 */
/** 书籍详情 + 卷列表(不含章节;等价脚本打开面板时的 loadCatalog) */
export async function fetchVolumeList(bookId: string, cfg: LkApiCfg,
convert: ((s: string) => string) | null): Promise<LkVolumeListResult> {
const conv = (s: string): string => convert !== null ? convert(s) : s;
const detailPayload: Record<string, Object> = { 'book_id': bookId, 'with_volumes': 0 };
const book = await apiPost('get-book-detail', detailPayload, cfg);
const bookName = clipName(sanitizeFileName(conv(jStr(book, 'title'))), 48);
const author = clipName(sanitizeFileName(conv(jStr(book, 'author_name'))), 16);
const coverRaw = jStr(book, 'cover_url');
const coverUrl = coverRaw.length > 0 ? urlHandler(coverRaw, bookPageUrl(bookId)) : '';
const volPayload: Record<string, Object> = { 'book_id': bookId };
const volumes = await allPages('get-book-volumes', volPayload, 'volume_id', cfg);
const list: LkVolumeInfo[] = [];
for (const v of volumes) {
const info: LkVolumeInfo = {
volumeId: jStr(v, 'volume_id'),
title: conv(jStr(v, 'title')),
chapterCount: jNum(v, 'chapter_count')
};
list.push(info);
}
const r: LkVolumeListResult = {
ok: true, error: '', bookName: bookName, author: author,
coverUrl: coverUrl, volumes: list
};
return r;
}
/**
* 抓取书籍详情 + 卷章目录(章节按需分页)。volumeIds 非空时只抓取所选卷
* (等价脚本"下载所选卷":仅读取所选卷的完整目录),空数组 = 全部卷。
*/
export async function fetchCatalog(bookId: string, cfg: LkApiCfg,
convert: ((s: string) => string) | null): Promise<LkCatalogResult> {
convert: ((s: string) => string) | null, volumeIds: string[] = []): Promise<LkCatalogResult> {
const conv = (s: string): string => convert !== null ? convert(s) : s;
const detailPayload: Record<string, Object> = { 'book_id': bookId, 'with_volumes': 0 };
const book = await apiPost('get-book-detail', detailPayload, cfg);
@@ -578,14 +675,24 @@ export async function fetchCatalog(bookId: string, cfg: LkApiCfg,
const volPayload: Record<string, Object> = { 'book_id': bookId };
const volumes = await allPages('get-book-volumes', volPayload, 'volume_id', cfg);
const volumeTotal = volumes.length;
const picked: Set<string> = new Set();
for (const id of volumeIds) {
picked.add(id);
}
const volumeTitles: string[] = [];
const nodes: VolumeChapterNode[] = [];
for (let vi = 0; vi < volumes.length; vi++) {
const v = volumes[vi];
const volumeId = jStr(v, 'volume_id');
if (picked.size > 0 && !picked.has(volumeId)) {
continue;
}
let vTitle = conv(jStr(v, 'title')).trim();
if (vTitle.length === 0) {
vTitle = '卷' + (vi + 1);
}
volumeTitles.push(vTitle);
const volNode: VolumeChapterNode = {
value: nodes.length, level: 0, fatherValue: -1,
isVolume: true, isChapter: false, title: vTitle, url: ''
@@ -604,7 +711,8 @@ export async function fetchCatalog(bookId: string, cfg: LkApiCfg,
}
const r: LkCatalogResult = {
ok: true, error: '', bookId: bookId, bookName: bookName,
author: author, coverUrl: coverUrl, nodes: nodes
author: author, coverUrl: coverUrl, nodes: nodes,
volumeTitles: volumeTitles, volumeTotal: volumeTotal
};
return r;
}
+89 -35
View File
@@ -2,45 +2,66 @@ import { preferences } from '@kit.ArkData';
import { common } from '@kit.AbilityKit';
/**
* 应用配置:对应原脚本开头全部参数,全部页面可配置并持久化。
* - siteUrl -> base_url
* - cookie -> esj.txt 第一行(含 ews_key / ews_token)
* - lkCookie -> 轻之国度(lightnovel.fun)Cookie,含 lk_security_key
* - convertMode -> opencc t2s / s2t / none
* - threadCount -> threadNum(并发数)
* - retryCount -> retrying stop_max_attempt_number
* - timeoutSec -> requests timeout
* - downloadImages / downloadCover / outputEpub / outputTxt -> 输出控制
* 应用配置:按书源分组的选项 + 通用下载选项,全部页面可配置并持久化。
*
* 各书源选项(互不通用,来源于各自脚本):
* - ESJZone(esj.py):站点域名 base_url、Cookie(ews_key/ews_token)、章节插图、封面
* - 轻之国度(LK EPUB 导出脚本):Cookie(lk_security_key)、嵌入正文插图、
* 图片失败时保留说明并继续(skip-images)、整本下载使用书籍封面、候选封面数量(1-60)
*
* 通用选项(两站语义一致):繁简转换、并发数、重试、超时、EPUB/TXT 输出。
*/
export const CONVERT_T2S: string = 't2s';
export const CONVERT_S2T: string = 's2t';
export const CONVERT_NONE: string = 'none';
/** ESJZone 书源选项 */
export interface EsjSettings {
siteUrl: string; // 站点域名(esjzone.cc / esjzone.one),需与链接、Cookie 一致
cookie: string; // esj.txt 第一行内容,含 ews_key / ews_token
downloadImages: boolean; // 下载章节插图
downloadCover: boolean; // 下载书籍封面
}
/** 轻之国度书源选项 */
export interface LkSettings {
cookie: string; // 站点 Cookie,含 lk_security_key;公开内容可不配置
downloadImages: boolean; // 嵌入正文插图
skipFailedImages: boolean; // 图片失败时保留说明并继续(关闭则该章节标记失败,可重试)
useBookCover: boolean; // 整本下载时使用书籍封面(选章下载用候选封面,见封面选择页)
coverCandidateCount: number; // 封面候选页扫描的不同图片数量(1-60,默认 4)
}
export interface AppSettings {
siteUrl: string;
cookie: string;
lkCookie: string;
convertMode: string;
threadCount: number;
retryCount: number;
timeoutSec: number;
downloadImages: boolean;
downloadCover: boolean;
esj: EsjSettings;
lk: LkSettings;
convertMode: string; // t2s / s2t / none
threadCount: number; // 并发数
retryCount: number; // 失败重试次数
timeoutSec: number; // 请求超时(秒)
outputEpub: boolean;
outputTxt: boolean;
}
export function defaultSettings(): AppSettings {
const s: AppSettings = {
siteUrl: 'https://www.esjzone.cc/',
cookie: '',
lkCookie: '',
esj: {
siteUrl: 'https://www.esjzone.cc/',
cookie: '',
downloadImages: true,
downloadCover: true
},
lk: {
cookie: '',
downloadImages: true,
skipFailedImages: false,
useBookCover: true,
coverCandidateCount: 4
},
convertMode: CONVERT_T2S,
threadCount: 2,
retryCount: 3,
timeoutSec: 25,
downloadImages: true,
downloadCover: true,
outputEpub: true,
outputTxt: true
};
@@ -58,17 +79,7 @@ export class ConfigStore {
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.lkCookie = strOf(obj, 'lkCookie', base.lkCookie);
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);
ConfigStore.parse(obj, base);
} catch (e) {
// 配置损坏时使用默认值
}
@@ -76,6 +87,42 @@ export class ConfigStore {
ConfigStore.cache = base;
}
/** 兼容两种持久化格式:新版按书源分组;旧版扁平字段(升级迁移) */
private static parse(obj: Record<string, Object>, base: AppSettings): void {
const esjObj = asRecord(obj['esj']);
const lkObj = asRecord(obj['lk']);
if (esjObj !== null) {
base.esj.siteUrl = strOf(esjObj, 'siteUrl', base.esj.siteUrl);
base.esj.cookie = strOf(esjObj, 'cookie', base.esj.cookie);
base.esj.downloadImages = boolOf(esjObj, 'downloadImages', base.esj.downloadImages);
base.esj.downloadCover = boolOf(esjObj, 'downloadCover', base.esj.downloadCover);
} else {
// 旧版扁平字段
base.esj.siteUrl = strOf(obj, 'siteUrl', base.esj.siteUrl);
base.esj.cookie = strOf(obj, 'cookie', base.esj.cookie);
base.esj.downloadImages = boolOf(obj, 'downloadImages', base.esj.downloadImages);
base.esj.downloadCover = boolOf(obj, 'downloadCover', base.esj.downloadCover);
}
if (lkObj !== null) {
base.lk.cookie = strOf(lkObj, 'cookie', base.lk.cookie);
base.lk.downloadImages = boolOf(lkObj, 'downloadImages', base.lk.downloadImages);
base.lk.skipFailedImages = boolOf(lkObj, 'skipFailedImages', base.lk.skipFailedImages);
base.lk.useBookCover = boolOf(lkObj, 'useBookCover', base.lk.useBookCover);
base.lk.coverCandidateCount = numOf(lkObj, 'coverCandidateCount', base.lk.coverCandidateCount);
} else {
// 旧版:lkCookie 单独存放,插图/封面开关与 ESJ 共用
base.lk.cookie = strOf(obj, 'lkCookie', base.lk.cookie);
base.lk.downloadImages = boolOf(obj, 'downloadImages', base.lk.downloadImages);
base.lk.useBookCover = boolOf(obj, 'downloadCover', base.lk.useBookCover);
}
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.outputEpub = boolOf(obj, 'outputEpub', base.outputEpub);
base.outputTxt = boolOf(obj, 'outputTxt', base.outputTxt);
}
static get(): AppSettings {
if (ConfigStore.cache === null) {
ConfigStore.cache = defaultSettings();
@@ -92,7 +139,7 @@ export class ConfigStore {
await ConfigStore.prefs.flush();
}
/** cookie 是否包含关键登录字段 */
/** ESJ Cookie 是否包含关键登录字段 */
static cookieOk(cookie: string): boolean {
return cookie.indexOf('ews_key') >= 0 && cookie.indexOf('ews_token') >= 0;
}
@@ -108,6 +155,13 @@ export class ConfigStore {
}
}
function asRecord(v: Object | undefined): Record<string, Object> | null {
if (v === undefined || v === null || typeof v !== 'object' || Array.isArray(v)) {
return null;
}
return v as Record<string, Object>;
}
function strOf(obj: Record<string, Object>, key: string, def: string): string {
const v = obj[key];
return typeof v === 'string' ? v : def;
+22 -3
View File
@@ -1,16 +1,20 @@
import { TocPreviewNode } from './TaskModel';
/**
* 单本下载的"选章 + 自定义标题"草稿。
* 单本下载的"选章 + 自定义标题 + LK 卷/封面"草稿。
* 与目标 URL 绑定;URL 变化时自动清空,避免串书。
*/
export class DownloadDraft {
static url: string = '';
static customTitle: string = '';
static chapterFilter: number[] = []; // 空 = 全部章节
static nodes: TocPreviewNode[] = []; // 已抓取的目录缓存
static chapterFilter: number[] = []; // 空 = 全部章节(ESJ 按章选择)
static nodes: TocPreviewNode[] = []; // 已抓取的目录缓存(ESJ 选章用)
static bookName: string = '';
static author: string = '';
static lkVolumeIds: string[] = []; // LK 选中的卷(等价脚本卷勾选;长度 == lkVolumeTotal 表示整本)
static lkVolumeTotal: number = 0; // LK 卷总数(0 = 尚未确认过卷选择)
static lkCoverUrl: string = ''; // LK 候选封面(仅单卷下载时生效;空 = 不设置)
static lkCoverVolumeId: string = ''; // 候选封面所属卷(换卷后旧封面失效,等价脚本 syncSingle)
static reset(): void {
DownloadDraft.url = '';
@@ -19,6 +23,10 @@ export class DownloadDraft {
DownloadDraft.nodes = [];
DownloadDraft.bookName = '';
DownloadDraft.author = '';
DownloadDraft.lkVolumeIds = [];
DownloadDraft.lkVolumeTotal = 0;
DownloadDraft.lkCoverUrl = '';
DownloadDraft.lkCoverVolumeId = '';
}
/** 目标 URL 变化时清空草稿(避免不同书籍沿用旧的选章/标题) */
@@ -47,4 +55,15 @@ export class DownloadDraft {
}
return n;
}
/** LK 部分卷下载(选中的卷少于总卷数) */
static lkVolumeFilterActive(url: string): boolean {
return DownloadDraft.url === url && DownloadDraft.lkVolumeTotal > 0
&& DownloadDraft.lkVolumeIds.length > 0 && DownloadDraft.lkVolumeIds.length < DownloadDraft.lkVolumeTotal;
}
/** LK 单卷下载(等价脚本 single:非整本且恰好选中 1 卷) */
static lkVolumeSingle(url: string): boolean {
return DownloadDraft.url === url && DownloadDraft.lkVolumeTotal > 1 && DownloadDraft.lkVolumeIds.length === 1;
}
}
+259 -64
View File
@@ -2,13 +2,14 @@ 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 { TaskInfo, ChapterNode, BookProgress, TocPreviewNode, TocPreviewResult, ChapterPart,
LkCoverCandidate, LkCoverCandidatesResult } 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 { fetchCatalog, fetchVolumeList, fetchChapterLines, splitChapterLines, parseBookId, bookPageUrl, chapterIdFromUrl, extractSecurityKey,
LkApiCfg, LkCatalogResult, LkLinePart, LkVolumeListResult, LkVolumeInfo } 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';
@@ -38,6 +39,7 @@ export class TaskManager {
activeTaskId: string = '';
private imgMap: Map<string, ImageState> = new Map();
private imgBytes: number = 0; // 已成功图片累计字节数(384MB 上限,等价脚本)
private lastEmit: number = 0;
tasksSnapshot(): TaskInfo[] {
@@ -54,13 +56,17 @@ export class TaskManager {
}
createTask(mode: string, url: string, customTitle: string = '', chapterFilter: number[] = [],
source: string = 'esj'): TaskInfo {
source: string = 'esj', lkCoverUrl: string = '', lkVolumeIds: string[] = []): 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;
t.lkCoverUrl = lkCoverUrl;
for (const v of lkVolumeIds) {
t.lkVolumeIds.push(v);
}
for (const v of chapterFilter) {
t.chapterFilter.push(v);
}
@@ -81,20 +87,20 @@ export class TaskManager {
return this.fetchTocPreviewLk(url, s);
}
const empty: TocPreviewNode[] = [];
const resp = await httpGetText(url, s.cookie, s.timeoutSec * 1000, s.retryCount);
const resp = await httpGetText(url, s.esj.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);
const detail = analyzeDetail(resp.text, s.esj.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 });
nodes.push({ value: n.value, level: n.level, fatherValue: n.fatherValue, isVolume: n.isVolume, isChapter: n.isChapter, title: n.title, url: n.url });
}
const r3: TocPreviewResult = { ok: true, error: '', nodes: nodes, bookName: detail.bookName, author: detail.author };
return r3;
@@ -109,7 +115,7 @@ export class TaskManager {
{ ok: false, error: '链接中未找到书籍编号(需要 lightnovel.fun/book/<id> 链接)', nodes: empty, bookName: '', author: '' };
return r;
}
const cookie = ConfigStore.cleanCookie(s.lkCookie);
const cookie = ConfigStore.cleanCookie(s.lk.cookie);
const cfg: LkApiCfg = {
cookie: cookie, securityKey: extractSecurityKey(cookie),
timeoutMs: s.timeoutSec * 1000, retry: s.retryCount
@@ -120,7 +126,7 @@ export class TaskManager {
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 });
nodes.push({ value: n.value, level: n.level, fatherValue: n.fatherValue, isVolume: n.isVolume, isChapter: n.isChapter, title: n.title, url: n.url });
}
const r2: TocPreviewResult = { ok: true, error: '', nodes: nodes, bookName: cat.bookName, author: cat.author };
return r2;
@@ -130,6 +136,134 @@ export class TaskManager {
}
}
/**
* LK 卷列表(等价脚本打开面板时的 loadCatalog):书籍详情 + 卷勾选列表,
* 供「选择卷」页使用;每次调用都重新抓取(等价脚本的"刷新目录")。
*/
async fetchLkVolumeList(url: string): Promise<LkVolumeListResult> {
const s = ConfigStore.get();
const emptyVol: LkVolumeInfo[] = [];
const fail = (err: string): LkVolumeListResult =>
({ ok: false, error: err, bookName: '', author: '', coverUrl: '', volumes: emptyVol });
const bookId = parseBookId(url);
if (bookId.length === 0) {
return fail('链接中未找到书籍编号');
}
const cookie = ConfigStore.cleanCookie(s.lk.cookie);
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 {
return await fetchVolumeList(bookId, cfg, cc !== null ? (x: string): string => cc.convert(x) : null);
} catch (e) {
return fail((e as Error).message);
}
}
/**
* LK 候选封面扫描(等价脚本 loadCovers):按目标卷的章节顺序扫描正文,
* 收集不同插图地址直到 count 张,并逐张匿名下载预览图到缓存。
* volumeId 为空时扫描整本。
*/
async fetchLkCoverCandidates(url: string, count: number, volumeId: string,
onProgress: (text: string) => void): Promise<LkCoverCandidatesResult> {
const s = ConfigStore.get();
const empty: LkCoverCandidate[] = [];
const fail = (err: string): LkCoverCandidatesResult =>
({ ok: false, error: err, candidates: empty, scanned: 0, total: 0 });
const bookId = parseBookId(url);
if (bookId.length === 0) {
return fail('链接中未找到书籍编号');
}
if (!(count >= 1 && count <= 60)) {
return fail('候选数量需为 1-60 的整数');
}
// 仅抓取目标卷的完整目录(等价脚本只读取所选卷)
const ids: string[] = [];
if (volumeId.length > 0) {
ids.push(volumeId);
}
const cookie = ConfigStore.cleanCookie(s.lk.cookie);
const cfg: LkApiCfg = {
cookie: cookie, securityKey: extractSecurityKey(cookie),
timeoutMs: s.timeoutSec * 1000, retry: s.retryCount
};
let cat: LkCatalogResult;
try {
// 章节标题保持原文(等价脚本封面卡片不转换文字)
cat = await fetchCatalog(bookId, cfg, null, ids);
} catch (e) {
return fail((e as Error).message);
}
let chapters: VolumeChapterNode[] = [];
for (const n of cat.nodes) {
if (n.isChapter) {
chapters.push(n);
}
}
if (chapters.length === 0) {
return fail('没有可扫描的章节');
}
const cacheDir = AppHub.uiContext().cacheDir + '/lk_covers/' + Date.now().toString(36);
ensureDir(cacheDir);
const seen: Set<string> = new Set();
const out: LkCoverCandidate[] = [];
let scanned = 0;
for (const ch of chapters) {
if (out.length >= count) {
break;
}
onProgress(`正在扫描:${ch.title}(${scanned + 1}/${chapters.length} 章)`);
try {
const parsed = await fetchChapterLines(bookId, chapterIdFromUrl(ch.url), cfg);
if (parsed.status === 'ok') {
for (const line of parsed.lines) {
if (!isImgPlaceholder(line)) {
continue;
}
const u = imgPlaceholderUrl(line);
if (seen.has(u)) {
continue;
}
seen.add(u);
const cand: LkCoverCandidate = { url: u, previewPath: '', error: '', chapterTitle: ch.title };
// 匿名下载预览(与正文插图一致的匿名约定)
const args: FetchImageArgs = { url: u, cookie: '', timeoutMs: s.timeoutSec * 1000, retry: s.retryCount };
try {
const r = await taskpool.execute(new taskpool.Task(fetchImageJob, args)) as FetchImageResult;
if (r !== null && r.ok && r.data.byteLength > 0) {
const filePath = cacheDir + '/cand_' + out.length + r.ext;
const f = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE | fs.OpenMode.TRUNC);
try {
fs.writeSync(f.fd, r.data);
} finally {
fs.closeSync(f);
}
cand.previewPath = filePath;
} else {
cand.error = r !== null ? r.error : '未知错误';
}
} catch (e) {
cand.error = (e as Error).message;
}
out.push(cand);
if (out.length >= count) {
break;
}
}
}
} catch (e) {
// 单章失败不中断扫描
}
scanned++;
await sleep(180);
}
const r2: LkCoverCandidatesResult = { ok: true, error: '', candidates: out, scanned: scanned, total: chapters.length };
return r2;
}
requestCancel(id: string): void {
const t = this.findTask(id);
if (t === null) {
@@ -258,24 +392,25 @@ export class TaskManager {
if (t.status !== TaskStatus.DONE_WITH_FAIL) {
this.cleanupCache(t);
this.imgMap.clear();
this.imgBytes = 0;
}
this.finishActive(t);
}
}
private async runList(t: TaskInfo, s: AppSettings): Promise<void> {
const mismatch = checkDomain(t.url, s.siteUrl);
const mismatch = checkDomain(t.url, s.esj.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);
const firstPage = await httpGetText(t.url, s.esj.cookie, s.timeoutSec * 1000, s.retryCount);
if (!firstPage.ok) {
throw new Error('列表页下载失败: ' + firstPage.error);
}
const firstInfo = parseListPage(firstPage.text, s.siteUrl);
const firstInfo = parseListPage(firstPage.text, s.esj.siteUrl);
const total = firstInfo.totalCount > 0 ? firstInfo.totalCount : 1;
t.addLog('info', `列表「${firstInfo.title}」共 ${total} 页`);
const bookUrls: string[] = [];
@@ -291,12 +426,12 @@ export class TaskManager {
return;
}
const pageUrl = t.url + p + '.html';
const resp = await httpGetText(pageUrl, s.cookie, s.timeoutSec * 1000, s.retryCount);
const resp = await httpGetText(pageUrl, s.esj.cookie, s.timeoutSec * 1000, s.retryCount);
if (!resp.ok) {
t.addLog('warn', `第 ${p} 页下载失败: ${resp.error}`);
continue;
}
const info = parseListPage(resp.text, s.siteUrl);
const info = parseListPage(resp.text, s.esj.siteUrl);
for (const u of info.bookUrls) {
if (!seen.has(u)) {
seen.add(u);
@@ -358,7 +493,7 @@ export class TaskManager {
let recordId = bookUrl;
if (!retryOnly) {
const mismatch = checkDomain(bookUrl, s.siteUrl);
const mismatch = checkDomain(bookUrl, s.esj.siteUrl);
if (mismatch.length > 0) {
throw new Error(mismatch);
}
@@ -366,13 +501,13 @@ export class TaskManager {
t.currentTitle = '获取书籍信息';
this.emit(true);
const resp = await httpGetText(bookUrl, s.cookie, s.timeoutSec * 1000, s.retryCount);
const resp = await httpGetText(bookUrl, s.esj.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);
const detail = analyzeDetail(resp.text, s.esj.siteUrl, convertFn);
if (!detail.ok) {
throw new Error(detail.error);
}
@@ -471,8 +606,8 @@ export class TaskManager {
const txtPath = AppHub.uiContext().filesDir + '/library/' + unique + '.txt';
// 封面
if (s.downloadCover && coverUrl.length > 0) {
await this.ensureImage(t, s, coverUrl, imgDir);
if (s.esj.downloadCover && coverUrl.length > 0) {
await this.ensureImage(t, s, coverUrl, imgDir, s.esj.cookie);
}
// 章节并发下载
@@ -483,6 +618,7 @@ export class TaskManager {
n.status === NodeStatus.DONE || n.status === NodeStatus.LOCKED).length;
if (!retryOnly) {
this.imgMap.clear();
this.imgBytes = 0;
}
const cursor: Cursor = { i: 0 };
const workers: Promise<void>[] = [];
@@ -539,7 +675,7 @@ export class TaskManager {
}
});
let cover: EpubImageItem | undefined = undefined;
if (s.downloadCover && coverUrl.length > 0) {
if (s.esj.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 };
@@ -613,8 +749,8 @@ export class TaskManager {
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 fullUrl = urlHandler(node.node.url, s.esj.siteUrl);
const args: FetchChapterArgs = { url: fullUrl, cookie: s.esj.cookie, timeoutMs: s.timeoutSec * 1000, retry: s.retryCount };
const job = new taskpool.Task(fetchChapterJob, args);
let result: FetchChapterResult | null = null;
try {
@@ -659,8 +795,8 @@ export class TaskManager {
}
// 内联下载本章图片
for (const line of node.lines) {
if (isImgPlaceholder(line) && s.downloadImages) {
await this.ensureImage(t, s, imgPlaceholderUrl(line), imgDir);
if (isImgPlaceholder(line) && s.esj.downloadImages) {
await this.ensureImage(t, s, imgPlaceholderUrl(line), imgDir, s.esj.cookie);
if (t.cancelRequested) {
return;
}
@@ -675,8 +811,8 @@ export class TaskManager {
// ---------------- LK(轻之国度 lightnovel.fun)主流程 ----------------
/**
* 下载轻之国度书籍:pc-proxy API 取详情与全部卷章目录,并发抓取章节,
* 整卷长文按目录/标题拆分后并入节点表;图片匿名抓取。
* 下载轻之国度书籍(等价脚本按卷模型):所选卷抓取完整目录并并发抓章,
* 部分卷合并命名「书名 — 卷1、卷2」;整卷长文按目录/标题拆分;图片匿名抓取。
*/
private async runBookLk(t: TaskInfo, s: AppSettings, retryOnly: boolean = false): Promise<boolean> {
const cacheDir = AppHub.uiContext().cacheDir + '/task_' + t.id;
@@ -702,48 +838,50 @@ export class TaskManager {
t.currentTitle = '获取书籍信息与目录';
this.emit(true);
const cookie = ConfigStore.cleanCookie(s.lkCookie);
const cookie = ConfigStore.cleanCookie(s.lk.cookie);
const cfg: LkApiCfg = {
cookie: cookie, securityKey: extractSecurityKey(cookie),
timeoutMs: s.timeoutSec * 1000, retry: s.retryCount
};
const cc = await OpenCC.getConverter(s.convertMode, AppHub.uiContext());
// 仅读取所选卷的完整目录(等价脚本 exportBook);空数组 = 整本
const cat: LkCatalogResult = await fetchCatalog(bookId, cfg,
cc !== null ? (x: string): string => cc.convert(x) : null);
cc !== null ? (x: string): string => cc.convert(x) : null, t.lkVolumeIds);
if (t.cancelRequested) {
return true;
}
if (cat.nodes.filter((n: VolumeChapterNode): boolean => n.isChapter).length === 0) {
throw new Error('当前书籍没有可下载的章节');
throw new Error('所选卷没有可下载的章节');
}
bookName = t.customTitle.length > 0 ? t.customTitle : cat.bookName;
const partial = t.lkVolumeIds.length > 0 && t.lkVolumeIds.length < cat.volumeTotal;
t.lkVolumeTotal = cat.volumeTotal;
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})`);
// 等价脚本命名:自定义标题 > 部分卷「书名 — 卷1、卷2」> 原书名
if (t.customTitle.length > 0) {
bookName = t.customTitle;
} else if (partial) {
bookName = clipMergedName(cat.bookName + ' — ' + cat.volumeTitles.join('、'));
} else {
t.addLog('info', `《${bookName}》${author} 开始下载(轻之国度)`);
bookName = cat.bookName;
}
t.bookName = bookName;
if (bookName !== cat.bookName) {
t.addLog('info', `《${cat.bookName}》${author} 开始下载(轻之国度,收录 ${cat.volumeTitles.length}/${cat.volumeTotal} 卷,标题:${bookName})`);
} else {
t.addLog('info', `《${bookName}》${author} 开始下载(轻之国度,整本 ${cat.volumeTotal} 卷)`);
}
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;
recordId = (t.customTitle.length > 0 || partial) ? bookUrl + '#' + baseName : bookUrl;
t.lkRecordId = recordId;
unique = LibraryStore.uniqueName(baseName, recordId);
} else {
// 增量重试:缓存必须仍存在
@@ -755,16 +893,22 @@ export class TaskManager {
if (t.nodes.length === 0) {
throw new Error('没有可重试的章节');
}
recordId = t.customTitle.length > 0 ? bookUrl + '#' + `《${t.bookName}》${t.author}` : bookUrl;
recordId = t.lkRecordId.length > 0 ? t.lkRecordId
: (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);
// 封面策略(等价脚本:单卷=自定义候选封面;整本=书籍封面;部分多卷=无封面;均匿名抓取)
const totalV = t.lkVolumeTotal;
const singleVolume = t.lkVolumeIds.length === 1 && totalV > 1;
const wholeBook = t.lkVolumeIds.length === 0 || (totalV > 0 && t.lkVolumeIds.length >= totalV);
const coverFinal = singleVolume && t.lkCoverUrl.length > 0 ? t.lkCoverUrl
: (wholeBook && s.lk.useBookCover ? coverUrl : '');
if (coverFinal.length > 0) {
await this.ensureImage(t, s, coverFinal, imgDir, '');
}
// 章节并发下载
@@ -775,6 +919,7 @@ export class TaskManager {
n.status === NodeStatus.DONE || n.status === NodeStatus.LOCKED).length;
if (!retryOnly) {
this.imgMap.clear();
this.imgBytes = 0;
}
const cursor: Cursor = { i: 0 };
const workers: Promise<void>[] = [];
@@ -826,15 +971,17 @@ export class TaskManager {
}
const images: EpubImageItem[] = [];
this.imgMap.forEach((v: ImageState, k: string): void => {
if (v.status === 'done' && k !== coverUrl) {
if (v.status === 'done' && k !== coverFinal) {
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 (coverFinal.length > 0) {
const cv = this.imgMap.get(coverFinal);
if (cv !== undefined && cv.status === 'done') {
cover = { url: coverUrl, fileName: 'cover' + cv.fileName.substring(cv.fileName.lastIndexOf('.')), contentType: cv.contentType, filePath: cv.filePath };
cover = { url: coverFinal, fileName: 'cover' + cv.fileName.substring(cv.fileName.lastIndexOf('.')), contentType: cv.contentType, filePath: cv.filePath };
} else {
t.addLog('warn', '封面未嵌入:下载失败');
}
}
const buildInput: EpubBuildInput = {
@@ -894,7 +1041,7 @@ export class TaskManager {
node.status = NodeStatus.DOWNLOADING;
t.currentTitle = node.node.title;
this.emit(false);
const cookie = ConfigStore.cleanCookie(s.lkCookie);
const cookie = ConfigStore.cleanCookie(s.lk.cookie);
const args: FetchLkChapterArgs = {
bookId: bookId, chapterId: chapterIdFromUrl(node.node.url),
cookie: cookie, securityKey: extractSecurityKey(cookie),
@@ -905,7 +1052,7 @@ export class TaskManager {
try {
result = await taskpool.execute(job) as FetchLkChapterResult;
} catch (e) {
result = { ok: false, status: 'error', lines: [], heads: [], error: '任务执行失败: ' + (e as Error).message };
result = { ok: false, status: 'error', lines: [], heads: [], noConv: [], error: '任务执行失败: ' + (e as Error).message };
}
if (t.cancelRequested) {
node.status = NodeStatus.PENDING;
@@ -921,10 +1068,12 @@ export class TaskManager {
this.emit(false);
continue;
}
// 转换文本(图片占位行不转换)
// 转换文本(图片占位行与 pre/code 行不转换,等价脚本 simplifyContent)
let lines = result.lines;
if (cc !== null) {
lines = lines.map((l: string): string => isImgPlaceholder(l) ? l : cc.convert(l));
const noConv = result.noConv;
lines = lines.map((l: string, i: number): string =>
isImgPlaceholder(l) || (i < noConv.length && noConv[i]) ? l : cc.convert(l));
}
if (result.status === 'locked') {
node.status = NodeStatus.LOCKED;
@@ -952,12 +1101,37 @@ export class TaskManager {
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 (s.lk.downloadImages) {
let imgFailed = '';
for (const line of node.lines) {
if (!isImgPlaceholder(line)) {
continue;
}
const imgUrl = imgPlaceholderUrl(line);
await this.ensureImage(t, s, imgUrl, imgDir, '');
if (t.cancelRequested) {
return;
}
// 等价脚本 skip-images 开关:关闭时插图失败视为章节失败,不静默缺图
if (!s.lk.skipFailedImages) {
const stImg = this.imgMap.get(imgUrl);
if (stImg !== undefined && stImg.status === 'failed') {
imgFailed = stImg.error;
break;
}
}
}
if (imgFailed.length > 0) {
node.status = NodeStatus.FAILED;
node.error = '插图下载失败(' + imgFailed + ');可开启「图片失败时继续」后重试';
t.failedChapters++;
t.doneChapters++;
node.fragmentPath = '';
node.parts = [];
t.addLog('error', `章节下载失败「${node.node.title}」: ${node.error}`);
node.touch();
this.emit(false);
continue;
}
}
t.doneChapters++;
@@ -1011,17 +1185,17 @@ export class TaskManager {
t.addLog('info', `长章节已拆分为 ${partCount} 节`);
}
/** useCookie=false 用于 LK:插图按脚本约定匿名抓取(不附带 Cookie/security_key) */
/** cookie 按书源传入:ESJ 用站点 Cookie,LK 按脚本约定插图/封面匿名抓取(传 '') */
private async ensureImage(t: TaskInfo, s: AppSettings, url: string, imgDir: string,
useCookie: boolean = true): Promise<void> {
cookie: 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: useCookie ? s.cookie : '', timeoutMs: s.timeoutSec * 1000, retry: s.retryCount };
const fullUrl = urlHandler(url, s.esj.siteUrl);
const args: FetchImageArgs = { url: fullUrl, cookie: cookie, timeoutMs: s.timeoutSec * 1000, retry: s.retryCount };
const job = new taskpool.Task(fetchImageJob, args);
let result: FetchImageResult | null = null;
try {
@@ -1030,6 +1204,16 @@ export class TaskManager {
result = { ok: false, ext: '', hash: '', data: new ArrayBuffer(0), error: (e as Error).message };
}
if (result !== null && result.ok) {
// 等价脚本 asset():插图总量超过 384MB 停止(按失败图片处理,可跳过或重试)
if (this.imgBytes + result.data.byteLength > 384 * 1024 * 1024) {
st.status = 'failed';
st.error = '插图总量超过 384MB';
t.addLog('warn', `图片下载失败: ${url} ${st.error}`);
t.doneImages++;
this.emit(false);
return;
}
this.imgBytes += result.data.byteLength;
const fileName = `Image_${result.hash}${result.ext}`;
const filePath = imgDir + '/' + fileName;
try {
@@ -1065,6 +1249,17 @@ export class TaskManager {
// ---------------- 辅助函数 ----------------
function sleep(ms: number): Promise<void> {
return new Promise<void>((resolve: (v: void) => void) => {
setTimeout((): void => resolve(), ms);
});
}
/** 部分卷合并命名限长(等价脚本对文件名 150 字的截断思路) */
function clipMergedName(name: string): string {
return name.length > 100 ? name.substring(0, 99) + '…' : name;
}
function checkDomain(url: string, siteUrl: string): string {
const h1 = hostOf(url);
const h2 = hostOf(siteUrl);
+22 -1
View File
@@ -54,6 +54,7 @@ export interface TocPreviewNode {
isVolume: boolean;
isChapter: boolean;
title: string;
url: string; // 章节/卷的原始链接(章节用于封面候选扫描取 chapter_id)
}
export interface TocPreviewResult {
@@ -64,6 +65,22 @@ export interface TocPreviewResult {
author: string;
}
/** LK 封面候选项(等价脚本 coverRecords:含预览图本地路径;下载失败的不可选) */
export interface LkCoverCandidate {
url: string;
previewPath: string;
error: string;
chapterTitle: string;
}
export interface LkCoverCandidatesResult {
ok: boolean;
error: string;
candidates: LkCoverCandidate[];
scanned: number;
total: number;
}
export class TaskInfo {
id: string = '';
mode: string = 'book'; // book | list
@@ -91,7 +108,11 @@ export class TaskInfo {
createdAt: number = 0;
cancelRequested: boolean = false;
customTitle: string = ''; // 用户自定义 EPUB 标题(空=用原书名)
chapterFilter: number[] = []; // 选中的章节节点 value(空=全部)
chapterFilter: number[] = []; // 选中的章节节点 value(空=全部,ESJ 按章)
lkVolumeIds: string[] = []; // LK 选中的卷(空=整本)
lkVolumeTotal: number = 0; // LK 全部卷数(用于判断单卷/整本/部分多卷)
lkRecordId: string = ''; // LK 部分卷下载的入库 id(重试时复用,避免覆盖整本记录)
lkCoverUrl: string = ''; // LK 自定义封面图片地址(空=按设置决定)
activeBooksDone: number = 0;
activeBooksTotal: number = 0;
versionTick: number = 0; // 每次有变化自增,驱动界面刷新
+6
View File
@@ -11,6 +11,8 @@ import { LibraryView } from '../view/LibraryView';
import { SettingsView } from '../view/SettingsView';
import { TaskDetailPage } from '../view/TaskDetailPage';
import { ChapterSelectPage } from '../view/ChapterSelectPage';
import { LkCoverSelectPage } from '../view/LkCoverSelectPage';
import { LkVolumeSelectPage } from '../view/LkVolumeSelectPage';
import { HDS_MATERIAL, InsetKey, Insets } from '../common/Theme';
const TAB_TITLES: string[] = ['下载', '书库', '设置'];
@@ -41,6 +43,10 @@ struct Index {
TaskDetailPage()
} else if (name === 'chapterSelect') {
ChapterSelectPage()
} else if (name === 'lkVolumeSelect') {
LkVolumeSelectPage()
} else if (name === 'lkCoverSelect') {
LkCoverSelectPage()
}
}
+145 -30
View File
@@ -74,9 +74,9 @@ export struct HomeView {
refreshConfig(): void {
const s: AppSettings = ConfigStore.get();
this.siteHost = hostOf(s.siteUrl);
this.cookieReady = ConfigStore.cookieOk(ConfigStore.cleanCookie(s.cookie));
this.lkCookieReady = ConfigStore.lkCookieOk(ConfigStore.cleanCookie(s.lkCookie));
this.siteHost = hostOf(s.esj.siteUrl);
this.cookieReady = ConfigStore.cookieOk(ConfigStore.cleanCookie(s.esj.cookie));
this.lkCookieReady = ConfigStore.lkCookieOk(ConfigStore.cleanCookie(s.lk.cookie));
this.threadCount = s.threadCount;
this.convertLabel = s.convertMode === 't2s' ? '繁→简' : (s.convertMode === 's2t' ? '简→繁' : '不转换');
}
@@ -181,9 +181,11 @@ export struct HomeView {
}
if (this.src() === 'lk') {
DownloadDraft.onUrlChanged(url);
const filter = DownloadDraft.filterActiveFor(url) ? DownloadDraft.chapterFilter.slice() : [];
const partial = DownloadDraft.lkVolumeFilterActive(url);
const volumes = partial ? DownloadDraft.lkVolumeIds.slice() : [];
const title = DownloadDraft.url === url ? DownloadDraft.customTitle : '';
TaskManager.instance.createTask('book', url, title, filter, 'lk');
const cover = DownloadDraft.lkVolumeSingle(url) ? DownloadDraft.lkCoverUrl : '';
TaskManager.instance.createTask('book', url, title, [], 'lk', cover, volumes);
} else if (this.modeIdx === 0) {
DownloadDraft.onUrlChanged(url);
const filter = DownloadDraft.filterActiveFor(url) ? DownloadDraft.chapterFilter.slice() : [];
@@ -200,7 +202,7 @@ export struct HomeView {
switchSiteTo(host: string): void {
const s: AppSettings = ConfigStore.get();
s.siteUrl = 'https://' + host + '/';
s.esj.siteUrl = 'https://' + host + '/';
ConfigStore.save(s).then((): void => {
this.refreshConfig();
promptAction.showToast({ message: '站点域名已切换' });
@@ -217,6 +219,13 @@ export struct HomeView {
if (this.modeIdx === 1) {
return '开始批量下载';
}
if (this.src() === 'lk') {
const url = this.urlInput.trim();
if (DownloadDraft.lkVolumeFilterActive(url)) {
return `开始下载(已选 ${DownloadDraft.lkVolumeIds.length} 卷)`;
}
return '开始下载整本';
}
const n = this.draftFilterCount();
return n > 0 ? `开始下载(已选 ${n} 章)` : '开始下载这本书';
}
@@ -273,6 +282,50 @@ export struct HomeView {
this.pathStack.pushPathByName('chapterSelect', this.urlInput.trim());
}
/** LK 候选封面仅对单卷下载有意义(等价脚本) */
openCoverSelect(): void {
if (!this.canSelectChapters()) {
return;
}
if (!DownloadDraft.lkVolumeSingle(this.urlInput.trim())) {
promptAction.showToast({ message: '请先选择单卷:自定义封面仅用于单卷下载' });
return;
}
DownloadDraft.onUrlChanged(this.urlInput.trim());
this.pathStack.pushPathByName('lkCoverSelect', this.urlInput.trim());
}
openVolumeSelect(): void {
if (!this.canSelectChapters()) {
return;
}
DownloadDraft.onUrlChanged(this.urlInput.trim());
this.pathStack.pushPathByName('lkVolumeSelect', this.urlInput.trim());
}
lkVolumeSingle(): boolean {
// 读取 draftTick 使 build 跟踪该状态:卷/封面确认返回后触发刷新
const _tick = this.draftTick;
return DownloadDraft.lkVolumeSingle(this.urlInput.trim());
}
lkVolumeStatusText(): string {
const _tick = this.draftTick;
const url = this.urlInput.trim();
if (DownloadDraft.lkVolumeFilterActive(url)) {
return `已选 ${DownloadDraft.lkVolumeIds.length}/${DownloadDraft.lkVolumeTotal} 卷`;
}
if (DownloadDraft.lkVolumeTotal > 0 && DownloadDraft.lkVolumeIds.length >= DownloadDraft.lkVolumeTotal) {
return `整本(${DownloadDraft.lkVolumeTotal} 卷)`;
}
return '整本';
}
draftCoverSet(): boolean {
const _tick = this.draftTick;
return DownloadDraft.lkVolumeSingle(this.urlInput.trim()) && DownloadDraft.lkCoverUrl.length > 0;
}
@Builder
miniAction(label: string, color: ResourceColor, action: () => void) {
Button(label, { type: ButtonType.Capsule })
@@ -433,33 +486,95 @@ export struct HomeView {
DownloadDraft.customTitle = v;
this.titleInput = v;
})
Row({ space: 6 }) {
SymIcon({
sym: $r('sys.symbol.list_bullet'),
iconSize: 16,
colorRes: $r('app.color.brand')
if (this.src() === 'lk') {
// LK:按卷选择(等价脚本卷勾选面板,全选即整本)
Row({ space: 6 }) {
SymIcon({
sym: $r('sys.symbol.list_bullet'),
iconSize: 16,
colorRes: $r('app.color.brand')
})
Text('选择卷')
.fontSize(FontSize.sub)
.fontColor($r('app.color.font_pri'))
Blank()
Text(this.lkVolumeStatusText())
.fontSize(FontSize.cap)
.fontColor(DownloadDraft.lkVolumeFilterActive(this.urlInput.trim())
? $r('app.color.brand') : $r('app.color.font_ter'))
SymIcon({
sym: $r('sys.symbol.chevron_right'),
iconSize: 14,
colorRes: $r('app.color.font_ter')
})
}
.width('100%')
.height(40)
.padding({ left: 12, right: 12 })
.borderRadius(20)
.backgroundColor($r('app.color.input_bg'))
.onClick(() => {
this.openVolumeSelect();
})
Text('选择章节')
.fontSize(FontSize.sub)
.fontColor($r('app.color.font_pri'))
Blank()
Text(this.draftFilterCount() > 0 ? `已选 ${this.draftFilterCount()} 章` : '全部章节')
.fontSize(FontSize.cap)
.fontColor(this.draftFilterCount() > 0 ? $r('app.color.brand') : $r('app.color.font_ter'))
SymIcon({
sym: $r('sys.symbol.chevron_right'),
iconSize: 14,
colorRes: $r('app.color.font_ter')
// LK:单卷下载时的候选封面入口(等价脚本单卷封面面板)
if (this.lkVolumeSingle()) {
Row({ space: 6 }) {
SymIcon({
sym: $r('sys.symbol.picture'),
iconSize: 16,
colorRes: $r('app.color.brand')
})
Text('自定义封面')
.fontSize(FontSize.sub)
.fontColor($r('app.color.font_pri'))
Blank()
Text(this.draftCoverSet() ? '已设置候选封面' : '未设置')
.fontSize(FontSize.cap)
.fontColor(this.draftCoverSet() ? $r('app.color.brand') : $r('app.color.font_ter'))
SymIcon({
sym: $r('sys.symbol.chevron_right'),
iconSize: 14,
colorRes: $r('app.color.font_ter')
})
}
.width('100%')
.height(40)
.padding({ left: 12, right: 12 })
.borderRadius(20)
.backgroundColor($r('app.color.input_bg'))
.onClick(() => {
this.openCoverSelect();
})
}
} else {
Row({ space: 6 }) {
SymIcon({
sym: $r('sys.symbol.list_bullet'),
iconSize: 16,
colorRes: $r('app.color.brand')
})
Text('选择章节')
.fontSize(FontSize.sub)
.fontColor($r('app.color.font_pri'))
Blank()
Text(this.draftFilterCount() > 0 ? `已选 ${this.draftFilterCount()} 章` : '全部章节')
.fontSize(FontSize.cap)
.fontColor(this.draftFilterCount() > 0 ? $r('app.color.brand') : $r('app.color.font_ter'))
SymIcon({
sym: $r('sys.symbol.chevron_right'),
iconSize: 14,
colorRes: $r('app.color.font_ter')
})
}
.width('100%')
.height(40)
.padding({ left: 12, right: 12 })
.borderRadius(20)
.backgroundColor($r('app.color.input_bg'))
.onClick(() => {
this.openChapterSelect();
})
}
.width('100%')
.height(40)
.padding({ left: 12, right: 12 })
.borderRadius(20)
.backgroundColor($r('app.color.input_bg'))
.onClick(() => {
this.openChapterSelect();
})
}
.width('100%')
.alignItems(HorizontalAlign.Start)
@@ -0,0 +1,313 @@
import { promptAction } from '@kit.ArkUI';
import { HdsNavDestination, HdsNavDestinationTitleMode, ScrollEffectType } from '@kit.UIDesignKit';
import { AppHub } from '../common/AppHub';
import { Dim, FontSize, HDS_MATERIAL, InsetKey, Insets } from '../common/Theme';
import { ConfigStore } from '../model/Config';
import { TaskManager } from '../model/TaskManager';
import { LkCoverCandidate } from '../model/TaskModel';
import { DownloadDraft } from '../model/Draft';
import { SymIcon, FloatingToolbar, ToolbarAction } from './Widgets';
/**
* LK 封面候选选择页(等价脚本单卷封面面板):
* 按章节顺序扫描正文插图,列出前 N 张不同图片(N 为设置中的候选数量),
* 从中选一张作为本次下载的封面,也可不设置。仅对选章下载生效。
*/
@Component
export struct LkCoverSelectPage {
@Consume pathStack: NavPathStack;
@StorageProp(InsetKey.TOP) topInset: number = 0;
@StorageProp(InsetKey.BOTTOM) bottomInset: number = 0;
private scroller: Scroller = new Scroller();
@State targetUrl: string = '';
@State loading: boolean = false;
@State loadError: string = '';
@State scanText: string = '';
@State candidates: LkCoverCandidate[] = [];
@State selected: number = -1; // -1 = 不设置封面
aboutToAppear(): void {
// 从导航参数兜底获取目标 URL
try {
const params = this.pathStack.getParamByName('lkCoverSelect') as Array<Object>;
if (params !== undefined && params.length > 0) {
this.targetUrl = params[params.length - 1] as string;
}
} catch (e) {
// 忽略
}
if (this.targetUrl.length > 0) {
this.scan();
}
}
async scan(): Promise<void> {
if (this.targetUrl.length === 0 || this.loading) {
return;
}
// 等价脚本:封面面板仅在单卷下载出现
if (!DownloadDraft.lkVolumeSingle(this.targetUrl)) {
this.loadError = '自定义封面仅用于单卷下载:请先在「选择卷」中只勾选一卷';
return;
}
this.loading = true;
this.loadError = '';
this.candidates = [];
this.selected = -1;
const count = ConfigStore.get().lk.coverCandidateCount;
const volumeId = DownloadDraft.lkVolumeIds.length > 0 ? DownloadDraft.lkVolumeIds[0] : '';
const res = await TaskManager.instance.fetchLkCoverCandidates(this.targetUrl, count, volumeId,
(text: string): void => {
this.scanText = text;
});
this.loading = false;
if (!res.ok) {
this.loadError = res.error;
return;
}
this.candidates = res.candidates;
let selectable = 0;
for (const c of this.candidates) {
if (c.previewPath.length > 0) {
selectable++;
}
}
if (this.candidates.length === 0) {
this.scanText = '正文没有找到可用的图片地址,可无封面下载。';
} else {
this.scanText = `已列出 ${this.candidates.length} 张(${selectable} 张可选)` +
`${this.candidates.length < count ? ',已遍历全部章节' : ''}。点击图片选择封面。`;
}
}
confirm(): void {
if (this.selected >= 0 && this.selected < this.candidates.length) {
const c = this.candidates[this.selected];
if (c.previewPath.length === 0) {
promptAction.showToast({ message: '该图片加载失败,请选择其他图片' });
return;
}
DownloadDraft.lkCoverUrl = c.url;
DownloadDraft.lkCoverVolumeId = DownloadDraft.lkVolumeIds.length > 0 ? DownloadDraft.lkVolumeIds[0] : '';
} else {
DownloadDraft.lkCoverUrl = '';
DownloadDraft.lkCoverVolumeId = '';
}
AppHub.emit('draft', '');
promptAction.showToast({ message: DownloadDraft.lkCoverUrl.length > 0 ? '已选择封面' : '未设置封面' });
this.pathStack.pop();
}
subTitle(): string | undefined {
const name = DownloadDraft.bookName.length > 0 ? `《${DownloadDraft.bookName}》 · ` : '';
return this.loading ? `${name}正在扫描…`
: `${name}${this.selected >= 0 ? '已选择第 ' + (this.selected + 1) + ' 张' : '未选择封面'}`;
}
@Builder
candidateCard(c: LkCoverCandidate, idx: number) {
Column({ space: 6 }) {
if (c.previewPath.length > 0) {
Image(c.previewPath)
.width('100%')
.height(110)
.objectFit(ImageFit.Contain)
.borderRadius(8)
.backgroundColor($r('app.color.chip_bg'))
} else {
Column({ space: 6 }) {
SymIcon({
sym: $r('sys.symbol.exclamationmark_triangle'),
iconSize: 20,
colorRes: $r('app.color.font_ter')
})
Text('加载失败')
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
}
.width('100%')
.height(110)
.justifyContent(FlexAlign.Center)
.borderRadius(8)
.backgroundColor($r('app.color.chip_bg'))
}
Text(`第 ${idx + 1} 张`)
.fontSize(FontSize.cap)
.fontWeight(this.selected === idx ? FontWeight.Medium : FontWeight.Normal)
.fontColor(this.selected === idx ? $r('app.color.brand') : $r('app.color.font_sec'))
.maxLines(1)
Text(c.chapterTitle)
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
}
.width('100%')
.padding(6)
.borderRadius(12)
.border({
width: 2,
color: this.selected === idx ? $r('app.color.brand') : Color.Transparent
})
.backgroundColor($r('app.color.card_bg'))
.opacity(c.previewPath.length > 0 ? 1 : 0.55)
.onClick(() => {
if (c.previewPath.length > 0) {
this.selected = this.selected === idx ? -1 : idx;
}
})
}
build() {
HdsNavDestination() {
Stack({ alignContent: Alignment.Bottom }) {
if (this.loading) {
Column({ space: 12 }) {
LoadingProgress()
.width(44)
.height(44)
.color($r('app.color.brand'))
Text(this.scanText.length > 0 ? this.scanText : '正在扫描候选封面…')
.fontSize(FontSize.sub)
.fontColor($r('app.color.font_sec'))
.textAlign(TextAlign.Center)
.maxLines(2)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
.padding(Dim.pagePad)
} else if (this.loadError.length > 0) {
Column({ space: 12 }) {
Text(this.loadError)
.fontSize(FontSize.sub)
.fontColor($r('app.color.err'))
.textAlign(TextAlign.Center)
Button('重新扫描', { type: ButtonType.Capsule })
.fontSize(FontSize.sub)
.height(40)
.padding({ left: 32, right: 32 })
.backgroundColor($r('app.color.brand'))
.fontColor($r('app.color.on_brand'))
.onClick(() => {
this.scan();
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
.padding(Dim.pagePad)
} else {
Scroll(this.scroller) {
Column({ space: 12 }) {
Text(this.scanText)
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_sec'))
.width('100%')
// 不设置封面
Row({ space: 10 }) {
SymIcon({
sym: this.selected === -1 ? $r('sys.symbol.checkmark_circle_fill') : $r('sys.symbol.circle'),
iconSize: 20,
colorRes: this.selected === -1 ? $r('app.color.brand') : $r('app.color.font_ter')
})
Column({ space: 2 }) {
Text('不设置封面')
.fontSize(FontSize.sub)
.fontColor($r('app.color.font_pri'))
Text('本次下载不嵌入封面图')
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
}
.alignItems(HorizontalAlign.Start)
.layoutWeight(1)
}
.width('100%')
.padding(12)
.borderRadius(Dim.innerRadius)
.border({
width: 2,
color: this.selected === -1 ? $r('app.color.brand') : Color.Transparent
})
.backgroundColor($r('app.color.card_bg'))
.onClick(() => {
this.selected = -1;
})
Grid() {
ForEach(this.candidates, (c: LkCoverCandidate, idx: number) => {
GridItem() {
this.candidateCard(c, idx)
}
}, (c: LkCoverCandidate, idx: number) => `${idx}_${c.previewPath.length > 0 ? 1 : 0}_${this.selected === idx ? 1 : 0}`)
}
.columnsTemplate('1fr 1fr 1fr')
.columnsGap(10)
.rowsGap(10)
.width('100%')
Text('按本卷章节与正文顺序取图;封面独立于「嵌入正文插图」开关。整本下载默认使用书籍封面,此处选择仅对单卷下载生效。')
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
.width('100%')
}
.width('100%')
.padding({
top: Insets.contentTop(this.topInset),
left: Dim.pagePad,
right: Dim.pagePad,
bottom: Insets.contentBottom(this.bottomInset)
})
}
.scrollBar(BarState.Off)
.align(Alignment.Top)
.clipContent(ContentClipMode.SAFE_AREA)
.width('100%')
.height('100%')
FloatingToolbar() {
ToolbarAction({
label: '重新扫描',
onTap: (): void => {
this.scan();
}
})
ToolbarAction({
label: this.selected >= 0 ? `确定(第 ${this.selected + 1} 张)` : '确定(不设置)',
primary: true,
onTap: (): void => {
this.confirm();
}
})
}
}
}
.width('100%')
.height('100%')
.backgroundColor($r('app.color.page_bg'))
}
.titleMode(HdsNavDestinationTitleMode.MINI)
.titleBar({
content: {
title: { mainTitle: '选择封面' }
},
style: {
scrollEffectOpts: {
enableScrollEffect: true,
scrollEffectType: ScrollEffectType.GRADIENT_BLUR
},
systemMaterialEffect: HDS_MATERIAL
}
})
.bindToScrollable([this.scroller])
.ignoreLayoutSafeArea([LayoutSafeAreaType.SYSTEM], [LayoutSafeAreaEdge.TOP, LayoutSafeAreaEdge.BOTTOM])
.onReady((ctx: NavDestinationContext) => {
const p = ctx.pathInfo.param as Object;
if (typeof p === 'string' && p.length > 0 && this.targetUrl === '') {
this.targetUrl = p;
this.scan();
}
})
}
}
@@ -0,0 +1,289 @@
import { promptAction } from '@kit.ArkUI';
import { HdsNavDestination, HdsNavDestinationTitleMode, ScrollEffectType } from '@kit.UIDesignKit';
import { AppHub } from '../common/AppHub';
import { Dim, FontSize, HDS_MATERIAL, InsetKey, Insets } from '../common/Theme';
import { TaskManager } from '../model/TaskManager';
import { LkVolumeInfo } from '../core/LkCore';
import { DownloadDraft } from '../model/Draft';
import { SymIcon, FloatingToolbar, ToolbarAction } from './Widgets';
/**
* LK 选择卷页(等价脚本卷勾选面板):列出书籍全部卷,默认全选,
* 可整卷勾选后「下载所选卷」或全选时等于「下载整本」。含刷新目录。
*/
@Component
export struct LkVolumeSelectPage {
@Consume pathStack: NavPathStack;
@StorageProp(InsetKey.TOP) topInset: number = 0;
@StorageProp(InsetKey.BOTTOM) bottomInset: number = 0;
private scroller: Scroller = new Scroller();
@State targetUrl: string = '';
@State loading: boolean = false;
@State loadError: string = '';
@State bookName: string = '';
@State volumes: LkVolumeInfo[] = [];
@State selected: boolean[] = [];
@State selCount: number = 0;
aboutToAppear(): void {
// 从导航参数兜底获取目标 URL
try {
const params = this.pathStack.getParamByName('lkVolumeSelect') as Array<Object>;
if (params !== undefined && params.length > 0) {
this.targetUrl = params[params.length - 1] as string;
}
} catch (e) {
// 忽略
}
if (this.targetUrl.length > 0) {
this.load();
}
}
async load(): Promise<void> {
if (this.targetUrl.length === 0 || this.loading) {
return;
}
this.loading = true;
this.loadError = '';
const res = await TaskManager.instance.fetchLkVolumeList(this.targetUrl);
if (!res.ok) {
this.loadError = res.error;
this.loading = false;
return;
}
this.bookName = res.bookName;
this.volumes = res.volumes;
// 默认全选(等价脚本勾选框默认选中);已有部分选择时回显
const sel: boolean[] = [];
for (let i = 0; i < this.volumes.length; i++) {
sel.push(true);
}
if (DownloadDraft.url === this.targetUrl && DownloadDraft.lkVolumeTotal === this.volumes.length
&& DownloadDraft.lkVolumeIds.length > 0 && DownloadDraft.lkVolumeIds.length < this.volumes.length) {
const picked: Set<string> = new Set();
for (const id of DownloadDraft.lkVolumeIds) {
picked.add(id);
}
for (let i = 0; i < this.volumes.length; i++) {
sel[i] = picked.has(this.volumes[i].volumeId);
}
}
this.selected = sel;
this.recount();
this.loading = false;
}
private recount(): void {
let c = 0;
for (let i = 0; i < this.selected.length; i++) {
if (this.selected[i]) {
c++;
}
}
this.selCount = c;
}
toggleVolume(idx: number): void {
if (idx < 0 || idx >= this.selected.length) {
return;
}
const sel = this.selected.slice();
sel[idx] = !sel[idx];
this.selected = sel;
this.recount();
}
selectAll(): void {
const sel: boolean[] = [];
for (let i = 0; i < this.selected.length; i++) {
sel.push(true);
}
this.selected = sel;
this.recount();
}
selectNone(): void {
const sel: boolean[] = [];
for (let i = 0; i < this.selected.length; i++) {
sel.push(false);
}
this.selected = sel;
this.recount();
}
confirm(): void {
if (this.selCount === 0) {
promptAction.showToast({ message: '请至少选择一卷' });
return;
}
DownloadDraft.onUrlChanged(this.targetUrl);
DownloadDraft.bookName = this.bookName;
const ids: string[] = [];
for (let i = 0; i < this.volumes.length; i++) {
if (this.selected[i]) {
ids.push(this.volumes[i].volumeId);
}
}
DownloadDraft.lkVolumeIds = ids;
DownloadDraft.lkVolumeTotal = this.volumes.length;
// 等价脚本:封面面板仅在单卷下载出现;换卷后旧封面失效(syncSingle 清空封面)
if (ids.length !== 1 || this.volumes.length <= 1) {
DownloadDraft.lkCoverUrl = '';
DownloadDraft.lkCoverVolumeId = '';
} else if (DownloadDraft.lkCoverUrl.length > 0 && DownloadDraft.lkCoverVolumeId !== ids[0]) {
DownloadDraft.lkCoverUrl = '';
DownloadDraft.lkCoverVolumeId = '';
}
AppHub.emit('draft', '');
this.pathStack.pop();
}
private subTitle(): string | undefined {
if (this.volumes.length === 0) {
return undefined;
}
const name = this.bookName.length > 0 ? `《${this.bookName}》 · ` : '';
return `${name}已选 ${this.selCount}/${this.volumes.length} 卷`;
}
@Builder
volumeRow(v: LkVolumeInfo, idx: number) {
Row({ space: 12 }) {
SymIcon({
sym: this.selected[idx] ? $r('sys.symbol.checkmark_circle_fill') : $r('sys.symbol.circle'),
iconSize: 20,
colorRes: this.selected[idx] ? $r('app.color.brand') : $r('app.color.font_ter')
})
Text(v.title)
.fontSize(FontSize.sub)
.fontColor($r('app.color.font_pri'))
.maxLines(2)
.layoutWeight(1)
if (Number.isFinite(v.chapterCount) && v.chapterCount > 0) {
Text(`${v.chapterCount} 章`)
.fontSize(FontSize.cap)
.fontColor($r('app.color.brand'))
.backgroundColor($r('app.color.brand_soft'))
.padding({ left: 8, right: 8, top: 2, bottom: 2 })
.borderRadius(10)
}
}
.width('100%')
.constraintSize({ minHeight: 52 })
.padding({ left: 16, right: 16 })
.onClick(() => {
this.toggleVolume(idx);
})
}
build() {
HdsNavDestination() {
Stack({ alignContent: Alignment.Bottom }) {
if (this.loading) {
Column({ space: 12 }) {
LoadingProgress()
.width(44)
.height(44)
.color($r('app.color.brand'))
Text('正在读取卷目录…')
.fontSize(FontSize.sub)
.fontColor($r('app.color.font_sec'))
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
} else if (this.loadError.length > 0) {
Column({ space: 12 }) {
Text(this.loadError)
.fontSize(FontSize.sub)
.fontColor($r('app.color.err'))
.textAlign(TextAlign.Center)
Button('重试', { type: ButtonType.Capsule })
.fontSize(FontSize.sub)
.height(40)
.padding({ left: 32, right: 32 })
.backgroundColor($r('app.color.brand'))
.fontColor($r('app.color.on_brand'))
.onClick(() => {
this.load();
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
.padding(Dim.pagePad)
} else {
List({ space: 0, scroller: this.scroller }) {
ForEach(this.volumes, (v: LkVolumeInfo, idx: number) => {
ListItem() {
this.volumeRow(v, idx)
}
}, (v: LkVolumeInfo, idx: number) => `${idx}_${this.selected[idx] ? 1 : 0}`)
}
.width('100%')
.height('100%')
.scrollBar(BarState.Auto)
.divider({ strokeWidth: 0.5, color: $r('app.color.divider'), startMargin: 48, endMargin: 16 })
.contentStartOffset(Insets.contentTop(this.topInset))
.contentEndOffset(Insets.contentBottom(this.bottomInset))
.clipContent(ContentClipMode.SAFE_AREA)
FloatingToolbar() {
ToolbarAction({
label: '全选',
onTap: (): void => {
this.selectAll();
}
})
ToolbarAction({
label: '清空',
onTap: (): void => {
this.selectNone();
}
})
ToolbarAction({
label: '刷新目录',
onTap: (): void => {
this.load();
}
})
ToolbarAction({
label: this.selCount === this.volumes.length ? '确定(整本)' : `确定(${this.selCount} 卷)`,
primary: true,
isEnabled: this.selCount > 0,
onTap: (): void => {
this.confirm();
}
})
}
}
}
.width('100%')
.height('100%')
.backgroundColor($r('app.color.page_bg'))
}
.titleMode(HdsNavDestinationTitleMode.MINI)
.titleBar({
content: {
title: { mainTitle: '选择卷' }
},
style: {
scrollEffectOpts: {
enableScrollEffect: true,
scrollEffectType: ScrollEffectType.GRADIENT_BLUR
},
systemMaterialEffect: HDS_MATERIAL
}
})
.bindToScrollable([this.scroller])
.ignoreLayoutSafeArea([LayoutSafeAreaType.SYSTEM], [LayoutSafeAreaEdge.TOP, LayoutSafeAreaEdge.BOTTOM])
.onReady((ctx: NavDestinationContext) => {
const p = ctx.pathInfo.param as Object;
if (typeof p === 'string' && p.length > 0 && this.targetUrl === '') {
this.targetUrl = p;
this.load();
}
})
}
}
+123 -56
View File
@@ -6,21 +6,31 @@ import { ConfigStore, AppSettings, CONVERT_T2S, CONVERT_S2T, CONVERT_NONE } from
import { hostOf } from '../core/EsjCore';
import { SectionCard, SettingRow, SegmentedControl, SymIcon } from './Widgets';
/** 设置页:站点、Cookie、下载参数、繁简转换与输出设置,修改即持久化。 */
/**
* 设置页:按书源分组的选项(ESJZone / 轻之国度各自独立)+ 两站共用的通用选项。
* 各书源选项来源于对应脚本,语义互不混用;修改即持久化。
*/
@Component
export struct SettingsView {
scroller: Scroller = new Scroller();
@StorageProp(InsetKey.TOP) topInset: number = 0;
@StorageProp(InsetKey.BOTTOM) bottomInset: number = 0;
// ESJZone
@State siteUrl: string = '';
@State cookie: string = '';
@State esjImages: boolean = true;
@State esjCover: boolean = true;
// 轻之国度
@State lkCookie: string = '';
@State lkImages: boolean = true;
@State lkSkipFailed: boolean = false;
@State lkUseBookCover: boolean = true;
@State lkCoverCount: number = 4;
// 通用
@State convertMode: string = CONVERT_T2S;
@State threadCount: number = 2;
@State retryCount: number = 3;
@State timeoutSec: number = 25;
@State downloadImages: boolean = true;
@State downloadCover: boolean = true;
@State outputEpub: boolean = true;
@State outputTxt: boolean = true;
@State showCookieHelp: boolean = false;
@@ -40,30 +50,42 @@ export struct SettingsView {
loadFromStore(): void {
const s = ConfigStore.get();
this.siteUrl = s.siteUrl;
this.cookie = s.cookie;
this.lkCookie = s.lkCookie;
this.siteUrl = s.esj.siteUrl;
this.cookie = s.esj.cookie;
this.esjImages = s.esj.downloadImages;
this.esjCover = s.esj.downloadCover;
this.lkCookie = s.lk.cookie;
this.lkImages = s.lk.downloadImages;
this.lkSkipFailed = s.lk.skipFailedImages;
this.lkUseBookCover = s.lk.useBookCover;
this.lkCoverCount = s.lk.coverCandidateCount;
this.convertMode = s.convertMode;
this.threadCount = s.threadCount;
this.retryCount = s.retryCount;
this.timeoutSec = s.timeoutSec;
this.downloadImages = s.downloadImages;
this.downloadCover = s.downloadCover;
this.outputEpub = s.outputEpub;
this.outputTxt = s.outputTxt;
}
private persist(): void {
const s: AppSettings = {
siteUrl: this.siteUrl,
cookie: this.cookie,
lkCookie: this.lkCookie,
esj: {
siteUrl: this.siteUrl,
cookie: this.cookie,
downloadImages: this.esjImages,
downloadCover: this.esjCover
},
lk: {
cookie: this.lkCookie,
downloadImages: this.lkImages,
skipFailedImages: this.lkSkipFailed,
useBookCover: this.lkUseBookCover,
coverCandidateCount: this.lkCoverCount
},
convertMode: this.convertMode,
threadCount: this.threadCount,
retryCount: this.retryCount,
timeoutSec: this.timeoutSec,
downloadImages: this.downloadImages,
downloadCover: this.downloadCover,
outputEpub: this.outputEpub,
outputTxt: this.outputTxt
};
@@ -115,11 +137,12 @@ export struct SettingsView {
build() {
Scroll(this.scroller) {
Column({ space: Dim.cardGap + 4 }) {
// ---------- 站点与账号 ----------
SectionCard({ title: '站点与账号' }) {
// ---------- ESJZone ----------
SectionCard({ title: 'ESJZone(esjzone.cc)' }) {
Column({ space: 4 }) {
SettingRow({
title: '站点域名'
title: '站点域名',
desc: '需与下载链接、Cookie 的域名一致'
})
Row({ space: 8 }) {
TextInput({ text: this.siteUrl, placeholder: 'https://www.esjzone.cc/' })
@@ -165,8 +188,8 @@ export struct SettingsView {
Divider().strokeWidth(0.5).color($r('app.color.divider'))
SettingRow({
title: 'Cookie',
desc: this.cookieOk() ? '已检测到 ews_key / ews_token' : ''
title: 'ESJ Cookie',
desc: this.cookieOk() ? '已检测到 ews_key / ews_token' : 'esj.txt 第一行内容,可直接粘贴'
})
TextArea({ text: this.cookie, placeholder: 'ews_key=…;ews_token=…;' })
.fontSize(FontSize.cap)
@@ -227,6 +250,29 @@ export struct SettingsView {
.borderRadius(10)
.backgroundColor($r('app.color.input_bg'))
}
Divider().strokeWidth(0.5).color($r('app.color.divider'))
SettingRow({
title: '下载章节插图',
desc: '关闭后插图在正文中保留为文字链接',
showToggle: true,
isOn: this.esjImages,
onToggle: (v: boolean): void => {
this.esjImages = v;
this.persist();
}
})
SettingRow({
title: '下载封面',
desc: '生成 EPUB 封面页',
showToggle: true,
isOn: this.esjCover,
onToggle: (v: boolean): void => {
this.esjCover = v;
this.persist();
}
})
}
.width('100%')
.padding({ left: Dim.cardPad, right: Dim.cardPad })
@@ -237,7 +283,7 @@ export struct SettingsView {
Column({ space: 4 }) {
SettingRow({
title: 'LK Cookie',
desc: this.lkCookieOk() ? '已检测到 lk_security_key' : ''
desc: this.lkCookieOk() ? '已检测到 lk_security_key' : '站点固定为 www.lightnovel.fun;公开内容可不配置'
})
TextArea({ text: this.lkCookie, placeholder: 'lk_security_key=…; 其他 Cookie 一并粘贴更稳妥' })
.fontSize(FontSize.cap)
@@ -290,7 +336,7 @@ export struct SettingsView {
}
.width('100%')
if (this.showLkCookieHelp) {
Text('1. 在浏览器登录 www.lightnovel.fun\n2. 打开开发者工具(F12)→ Application/存储 → Cookies → www.lightnovel.fun\n3. 复制 lk_security_key(建议把整行 Cookie 全部复制)\n4. 粘贴到上方输入框')
Text('1. 在浏览器登录 www.lightnovel.fun\n2. 打开开发者工具(F12)→ Application/存储 → Cookies → www.lightnovel.fun\n3. 复制 lk_security_key(建议把整行 Cookie 全部复制)\n4. 粘贴到上方输入框\n\n说明:带 Cookie 时以你的账号读取章节,权限与网页端一致;Cookie 仅保存在本机。')
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_sec'))
.width('100%')
@@ -298,16 +344,63 @@ export struct SettingsView {
.borderRadius(10)
.backgroundColor($r('app.color.input_bg'))
}
Divider().strokeWidth(0.5).color($r('app.color.divider'))
SettingRow({
title: '嵌入正文插图',
desc: '整本与选章下载均生效',
showToggle: true,
isOn: this.lkImages,
onToggle: (v: boolean): void => {
this.lkImages = v;
this.persist();
}
})
SettingRow({
title: '图片失败时继续',
desc: this.lkSkipFailed ? '失败插图保留占位说明' : '关闭时插图下载失败会标记该章节为失败(可重试)',
showToggle: true,
isOn: this.lkSkipFailed,
onToggle: (v: boolean): void => {
this.lkSkipFailed = v;
this.persist();
}
})
SettingRow({
title: '整本下载使用书籍封面',
desc: '选章下载可在下载页「自定义封面」中选取',
showToggle: true,
isOn: this.lkUseBookCover,
onToggle: (v: boolean): void => {
this.lkUseBookCover = v;
this.persist();
}
})
Divider().strokeWidth(0.5).color($r('app.color.divider'))
SettingRow({
title: '候选封面数量',
desc: '「自定义封面」扫描的不同图片张数(1-60)',
valueText: `${this.lkCoverCount}`
})
Slider({ value: this.lkCoverCount, min: 1, max: 60, step: 1, style: SliderStyle.OutSet })
.width('100%')
.selectedColor($r('app.color.brand'))
.onChange((v: number) => {
this.lkCoverCount = Math.round(v);
this.persist();
})
}
.width('100%')
.padding({ left: Dim.cardPad, right: Dim.cardPad })
}
// ---------- 下载 ----------
SectionCard({ title: '下载' }) {
// ---------- 通用 ----------
SectionCard({ title: '通用(两站共用)' }) {
Column({ space: 4 }) {
SettingRow({
title: '并发数',
desc: `同时下载 ${this.threadCount} 个章节(站点有反爬,不建议过大)`,
valueText: `${this.threadCount}`
})
Slider({ value: this.threadCount, min: 1, max: 6, step: 1, style: SliderStyle.OutSet })
@@ -348,32 +441,6 @@ export struct SettingsView {
Divider().strokeWidth(0.5).color($r('app.color.divider'))
SettingRow({
title: '下载章节插图',
showToggle: true,
isOn: this.downloadImages,
onToggle: (v: boolean): void => {
this.downloadImages = v;
this.persist();
}
})
SettingRow({
title: '下载封面',
showToggle: true,
isOn: this.downloadCover,
onToggle: (v: boolean): void => {
this.downloadCover = v;
this.persist();
}
})
}
.width('100%')
.padding({ left: Dim.cardPad, right: Dim.cardPad })
}
// ---------- 内容转换 ----------
SectionCard({ title: '内容转换' }) {
Column({ space: 10 }) {
SettingRow({
title: '繁简转换'
})
@@ -385,14 +452,9 @@ export struct SettingsView {
this.persist();
}
})
}
.width('100%')
.padding({ left: Dim.cardPad, right: Dim.cardPad })
}
// ---------- 输出 ----------
SectionCard({ title: '输出' }) {
Column({ space: 4 }) {
Divider().strokeWidth(0.5).color($r('app.color.divider'))
SettingRow({
title: '生成 EPUB',
showToggle: true,
@@ -406,7 +468,6 @@ export struct SettingsView {
this.persist();
}
})
Divider().strokeWidth(0.5).color($r('app.color.divider'))
SettingRow({
title: '生成 TXT',
showToggle: true,
@@ -420,6 +481,9 @@ export struct SettingsView {
this.persist();
}
})
Text('文件命名:《书名》作者.epub / .txt')
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
}
.width('100%')
.padding({ left: Dim.cardPad, right: Dim.cardPad })
@@ -431,6 +495,9 @@ export struct SettingsView {
Text('ESJ / LK 下载器 v1.1.0')
.fontSize(FontSize.sub)
.fontColor($r('app.color.font_pri'))
Text('ESJZone 书源由 esj.py 移植;轻之国度书源由用户脚本「LK EPUB 导出(PC 版)」移植,各书源的抓取与输出选项保持与原脚本一致。')
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
Text('请仅将本工具用于个人备份与学习,尊重原作者版权。')
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
+12 -4
View File
@@ -62,6 +62,11 @@ export async function fetchImageJob(args: FetchImageArgs): Promise<FetchImageRes
const r: FetchImageResult = { ok: false, ext: '', hash: '', data: new ArrayBuffer(0), error: resp.error };
return r;
}
// 等价脚本 normalizeImage:单张插图超过 32MB 拒绝
if (resp.data.byteLength > 32 * 1024 * 1024) {
const r1: FetchImageResult = { ok: false, ext: '', hash: '', data: new ArrayBuffer(0), error: '单张插图超过 32MB' };
return r1;
}
const ext = sniffImageExt(resp.data, resp.contentType);
if (ext.length === 0 || resp.data.byteLength === 0) {
const r2: FetchImageResult = { ok: false, ext: '', hash: '', data: new ArrayBuffer(0), error: '无法识别的图片类型: ' + resp.contentType };
@@ -85,7 +90,8 @@ export interface FetchLkChapterResult {
ok: boolean;
status: string; // ok | locked | error
lines: string[];
heads: boolean[]; // 行是否来自 h1-h6 标题(长文拆分用)
heads: boolean[]; // 行是否来自 h1-h3 标题(长文拆分用)
noConv: boolean[]; // 行是否位于 pre/code 内(繁简转换跳过)
error: string;
}
@@ -97,11 +103,13 @@ export async function fetchLkChapterJob(args: FetchLkChapterArgs): Promise<Fetch
};
try {
const parsed = await fetchChapterLines(args.bookId, args.chapterId, cfg);
const r: FetchLkChapterResult =
{ ok: parsed.status !== 'error', status: parsed.status, lines: parsed.lines, heads: parsed.heads, error: parsed.error };
const r: FetchLkChapterResult = {
ok: parsed.status !== 'error', status: parsed.status,
lines: parsed.lines, heads: parsed.heads, noConv: parsed.noConv, error: parsed.error
};
return r;
} catch (e) {
const r2: FetchLkChapterResult = { ok: false, status: 'error', lines: [], heads: [], error: (e as Error).message };
const r2: FetchLkChapterResult = { ok: false, status: 'error', lines: [], heads: [], noConv: [], error: (e as Error).message };
return r2;
}
}