Compare commits

1 Commits
Author SHA1 Message Date
RHUA c986972d51 feat: 书籍链接解析下载 2026-10-12 09:08:21 +08:00
32 changed files with 281 additions and 4073 deletions
+7
View File
@@ -11,3 +11,10 @@
**/.test **/.test
/.appanalyzer /.appanalyzer
/.work /.work
oh-package-lock.json5
*.hap
*.hsp
*.har
/build-profile.json5
.DS_Store
.npmrc
Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 160 KiB

File diff suppressed because one or more lines are too long
-56
View File
@@ -1,56 +0,0 @@
{
app: {
signingConfigs: [
{
name: 'default',
type: 'HarmonyOS',
material: {
certpath: 'C:\\Users\\rhua0016\\.ohos\\config\\default_myApp_ieXKPqh0DFdNpChgqL5ts5xchUSwW4cDj9Xy1HGk=.cer',
keyAlias: 'debugKey',
keyPassword: '0000001b9da1865d76d742e37d653d5b5816fe427f2609585298e2e8a681d77c15f31603d0acb89784c409',
profile: 'C:\\Users\\rhua0016\\.ohos\\config\\default_myApp_ieXKPqh0DFdNpChgqL5ts5xchUSwW4cDj9Xy1HGk=.p7b',
signAlg: 'SHA256withECDSA',
storeFile: 'C:\\Users\\rhua0016\\.ohos\\config\\default_myApp_ieXKPqh0DFdNpChgqL5ts5xchUSwW4cDj9Xy1HGk=.p12',
storePassword: '0000001b9da1865d76d742e37d653d5b5816fe427f2609585298e2e8a681d77c15f31603d0acb89784c409',
},
},
],
products: [
{
name: 'default',
signingConfig: 'default',
targetSdkVersion: '26.0.0',
compatibleSdkVersion: '26.0.0',
runtimeOS: 'HarmonyOS',
buildOption: {
strictMode: {
caseSensitiveCheck: true,
useNormalizedOHMUrl: true,
},
},
},
],
buildModeSet: [
{
name: 'debug',
},
{
name: 'release',
},
],
},
modules: [
{
name: 'entry',
srcPath: './entry',
targets: [
{
name: 'default',
applyToProducts: [
'default',
],
},
],
},
],
}
+3 -8
View File
@@ -61,7 +61,7 @@ export class AppHub {
} }
/** /**
* 处理来自浏览器“打开方式”/系统分享面板传入的书籍链接(ESJZone / 轻之国度)。 * 处理来自浏览器“打开方式”/系统分享面板传入的 esjzone 链接。
*/ */
static handleWant(w: Want): void { static handleWant(w: Want): void {
let url: string = ''; let url: string = '';
@@ -73,13 +73,13 @@ export class AppHub {
const keys = Object.keys(params); const keys = Object.keys(params);
for (const k of keys) { for (const k of keys) {
const v = params[k]; const v = params[k];
if (typeof v === 'string' && v.startsWith('http') && isBookSiteUrl(v)) { if (typeof v === 'string' && v.indexOf('esjzone') >= 0 && v.startsWith('http')) {
url = v; url = v;
break; break;
} }
} }
} }
if (url !== '' && isBookSiteUrl(url)) { if (url !== '' && url.indexOf('esjzone') >= 0) {
AppHub.latestLink = url; AppHub.latestLink = url;
AppHub.linkSeq += 1; AppHub.linkSeq += 1;
AppHub.emit('link', url); AppHub.emit('link', url);
@@ -96,8 +96,3 @@ export class AppHub {
return AppHub.linkSeq; return AppHub.linkSeq;
} }
} }
/** 是否为受支持书源的链接(esjzone / lightnovel 域名) */
function isBookSiteUrl(v: string): boolean {
return v.indexOf('esjzone') >= 0 || v.indexOf('lightnovel') >= 0;
}
-892
View File
@@ -1,892 +0,0 @@
import { VolumeChapterNode, urlHandler, imgPlaceholder, isImgPlaceholder, sanitizeFileName, clipName } from './EsjCore';
import { HtmlNode, parseHtml } from './HtmlParser';
import { httpPostJson } from '../net/HttpUtil';
/**
* 轻之国度(www.lightnovel.fun)书源逻辑,移植自用户脚本「LK EPUB 导出(PC 版)」:
* pc-proxy JSON API 目录/章节抓取、[res] 插图资源解析、正文净化为文本行、
* 整卷长文按目录/标题拆分。仅读取账号正常可读内容,不调用解锁、购买或管理接口。
*/
export const LK_SITE: string = 'https://www.lightnovel.fun';
const LK_API: string = LK_SITE + '/api/pc-proxy/api/new-content-read/';
/** LK 请求配置(Cookie 由用户在设置中粘贴) */
export interface LkApiCfg {
cookie: string;
securityKey: string;
timeoutMs: number;
retry: number;
}
/** 目录抓取结果(节点为 ESJ 同构的 VolumeChapterNode,可直接进入任务管线) */
export interface LkCatalogResult {
ok: boolean;
error: string;
bookId: string;
bookName: string;
author: string;
coverUrl: string;
nodes: VolumeChapterNode[];
volumeTitles: string[]; // 实际收录卷的标题(按目录顺序)
volumeTotal: number; // 书籍全部卷数(用于判断"部分卷")
}
/** 卷信息(等价脚本 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[]; // 行是否来自 h1-h3 标题(长文拆分用,等价脚本 heading 判定)
noConv: boolean[]; // 行是否位于 pre/code 内(繁简转换跳过,等价脚本 simplifyContent)
}
export interface LkChapterParse {
status: string; // ok | locked | error
lines: string[];
heads: boolean[];
noConv: boolean[];
error: string;
}
/** 长文拆分片段 */
export interface LkLinePart {
title: string;
lines: string[];
}
type JObj = Record<string, Object>;
// ---------------- URL / Cookie ----------------
export function isLkUrl(url: string): boolean {
return url.toLowerCase().indexOf('lightnovel') >= 0;
}
/** 解析书籍编号:支持 /book/<id> 与 /reader/<id>/<ch> 两种链接 */
export function parseBookId(url: string): string {
let m = /\/book\/(\d+)/.exec(url);
if (m !== null) {
return m[1];
}
m = /\/reader\/(\d+)(?:\/\d+)?/.exec(url);
return m === null ? '' : m[1];
}
export function bookPageUrl(bookId: string): string {
return LK_SITE + '/book/' + bookId;
}
export function readerPageUrl(bookId: string, chapterId: string): string {
return LK_SITE + '/reader/' + bookId + '/' + chapterId;
}
/** 从章节页链接提取章节编号 */
export function chapterIdFromUrl(url: string): string {
const m = /\/reader\/\d+\/(\d+)/.exec(url);
return m === null ? '' : m[1];
}
/** 从 Cookie 提取 lk_security_key(等价脚本 localStorage/cookie 双读取中的 cookie 路径) */
export function extractSecurityKey(cookie: string): string {
const m = /(?:^|;\s*)lk_security_key=([^;]*)/.exec(cookie);
return m === null ? '' : m[1];
}
// ---------------- JSON 访问辅助 ----------------
function asObj(v: Object | undefined): JObj | null {
if (v === undefined || v === null) {
return null;
}
if (typeof v !== 'object' || Array.isArray(v)) {
return null;
}
return v as JObj;
}
function asArr(v: Object | undefined): Object[] | null {
if (v === undefined || v === null) {
return null;
}
return Array.isArray(v) ? v as Object[] : null;
}
function jStr(o: JObj | null, key: string): string {
if (o === null) {
return '';
}
const v = o[key];
if (typeof v === 'string') {
return v as string;
}
if (typeof v === 'number') {
return String(v);
}
return '';
}
function jYes(v: Object | undefined): boolean {
if (typeof v === 'boolean') {
return v as boolean;
}
if (typeof v === 'number') {
return (v as number) === 1;
}
if (typeof v === 'string') {
return (v as string) === '1';
}
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 {
return s.replace(CONTROL_RE, '');
}
function sleep(ms: number): Promise<void> {
return new Promise<void>((resolve: (v: void) => void) => {
setTimeout((): void => resolve(), ms);
});
}
// ---------------- API ----------------
async function apiPost(endpoint: string, payload: Record<string, Object>, cfg: LkApiCfg): Promise<JObj> {
const body: Record<string, Object> = {};
const keys = Object.keys(payload);
for (const k of keys) {
body[k] = payload[k];
}
if (cfg.securityKey.length > 0) {
body['security_key'] = cfg.securityKey;
}
const resp = await httpPostJson(LK_API + endpoint, cfg.cookie, JSON.stringify(body),
cfg.timeoutMs, cfg.retry, LK_SITE);
if (!resp.ok) {
throw new Error(`站点返回 ${resp.error}(${endpoint}),请在原站确认登录或稍后重试`);
}
let env: JObj;
try {
env = JSON.parse(resp.text) as JObj;
} catch (e) {
throw new Error('站点返回的不是有效数据,请在原站确认登录状态');
}
const codeRaw = env['code'];
const code = typeof codeRaw === 'number' ? codeRaw as number : Number(codeRaw);
const data = asObj(env['data']);
if (!Number.isFinite(code) || code !== 0 || data === null) {
const msg = jStr(env, 'message').length > 0 ? jStr(env, 'message') : jStr(env, 'msg');
throw new Error(msg.length > 0 ? msg : '接口错误 ' + jStr(env, 'code'));
}
return data;
}
/** 目录分页聚合(等价脚本 allPages:pageSize 20、总数/has_next 双重判定、缺号与重复即停止) */
async function allPages(endpoint: string, payload: Record<string, Object>, idKey: string,
cfg: LkApiCfg): Promise<JObj[]> {
const list: JObj[] = [];
const seen: Set<string> = new Set();
for (let page = 1; page <= 1000; page++) {
const body: Record<string, Object> = {};
for (const k of Object.keys(payload)) {
body[k] = payload[k];
}
body['page'] = page;
body['pageSize'] = 20;
body['page_size'] = 20;
const data = await apiPost(endpoint, body, cfg);
const items = asArr(data['list']) ?? asArr(data['items']);
if (items === null) {
throw new Error('目录格式发生变化,已停止,避免漏章');
}
for (const it of items) {
const io = asObj(it);
if (io === null) {
throw new Error('目录格式发生变化,已停止,避免漏章');
}
const id = jStr(io, idKey);
if (id.length === 0 || seen.has(id)) {
throw new Error('目录含缺失或重复编号,已停止,避免漏章');
}
seen.add(id);
list.push(io);
}
const pi = asObj(data['pagination']);
const info = asObj(data['page_info']);
let totalValue: Object | undefined = pi !== null ? pi['total'] : undefined;
if (totalValue === undefined) {
totalValue = data['total'];
}
if (totalValue === undefined && info !== null) {
totalValue = info['count'];
}
let total = NaN;
if (typeof totalValue === 'number') {
total = totalValue as number;
} else if (typeof totalValue === 'string' && (totalValue as string).length > 0) {
total = Number(totalValue);
}
if (!Number.isNaN(total)) {
if (total < 0) {
throw new Error('目录总数无效');
}
if (list.length >= total) {
if (list.length !== total) {
throw new Error('目录数量变化,请重新载入目录');
}
return list;
}
}
if (items.length === 0) {
if (!Number.isNaN(total) && list.length < total) {
throw new Error('目录分页不完整,请稍后重试');
}
return list;
}
if (Number.isNaN(total)) {
let next: Object | undefined = info !== null ? info['has_next'] : undefined;
if (next === undefined) {
next = data['has_more'];
}
if (next === undefined) {
next = data['hasMore'];
}
if (next !== undefined) {
if (!jYes(next)) {
return list;
}
} else if (items.length < 20) {
return list;
}
}
await sleep(180);
}
throw new Error('目录超过支持范围,已停止,未生成不完整文件');
}
// ---------------- 资源映射 ----------------
function resUrlOf(v: JObj): string {
const cands: string[] = ['url', 'src', 'res_url', 'resUrl'];
for (const c of cands) {
const u = jStr(v, c);
if (u.length > 0) {
return u;
}
}
return '';
}
function resKeyOf(v: JObj, fallback: string): string {
const cands: string[] = ['res_key', 'resKey', 'key'];
for (const c of cands) {
const k = jStr(v, c);
if (k.length > 0) {
return k;
}
}
return fallback;
}
/** 解析 legacy_resources:res_info/对象表 + images/attachments/files 数组 */
function resourceMapOf(data: JObj): Map<string, string> {
const out: Map<string, string> = new Map();
const lr = asObj(data['legacy_resources']);
if (lr === null) {
return out;
}
let info = asObj(lr['res_info']);
if (info === null) {
info = asObj(lr['resInfo']);
}
if (info === null) {
info = lr;
}
for (const key of Object.keys(info)) {
const v = asObj(info[key]);
if (v === null) {
continue;
}
const url = resUrlOf(v);
if (url.length > 0) {
out.set(resKeyOf(v, key), url);
}
}
const groups: string[] = ['images', 'attachments', 'files'];
for (const g of groups) {
const arr = asArr(lr[g]);
if (arr === null) {
continue;
}
for (const it of arr) {
const v = asObj(it);
if (v === null) {
continue;
}
const url = resUrlOf(v);
const key = resKeyOf(v, '');
if (url.length > 0 && key.length > 0) {
out.set(key, url);
}
}
}
return out;
}
// ---------------- 正文净化:HTML → 文本行 ----------------
const DROP_TAGS: Set<string> = new Set<string>(['script', 'style', 'iframe', 'object', 'embed', 'form',
'input', 'button', 'textarea', 'select', 'link', 'meta', 'base', 'noscript', 'svg', 'math',
'audio', 'video', 'source']);
const SKIP_TEXT_TAGS: Set<string> = new Set<string>(['rt', 'rp']);
// 标题判定仅 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;
}
emitPlaceholder(url: string): void {
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 {
this.cur += text;
}
markHead(): void {
this.curHead = true;
}
enterPre(): void {
this.preDepth++;
}
exitPre(): void {
if (this.preDepth > 0) {
this.preDepth--;
}
}
}
/** 文本节点:处理 [res]key[/res] 插图标记(等价脚本 appendText) */
function appendText(b: LineBuilder, raw: string, res: Map<string, string>, baseUrl: string): void {
const text = cleanText(raw).replace(/[\r\n]+/g, ' ');
if (text.length === 0) {
return;
}
let idx = 0;
RES_RE.lastIndex = 0;
let m: RegExpExecArray | null = RES_RE.exec(text);
while (m !== null) {
if (m.index > idx) {
b.append(text.substring(idx, m.index));
}
const key = m[1].trim();
let url = res.get(key) ?? '';
if (url.length === 0 && /^https?:\/\//i.test(key)) {
url = key;
}
const abs = url.length > 0 ? urlHandler(url, baseUrl) : '';
if (abs.length > 0) {
b.emitPlaceholder(abs);
} else {
b.append('〔无法解析的插图:' + key.substring(0, 60) + '〕');
}
idx = m.index + m[0].length;
m = RES_RE.exec(text);
}
if (idx < text.length) {
b.append(text.substring(idx));
}
}
function walkChildren(children: HtmlNode[], b: LineBuilder, res: Map<string, string>, baseUrl: string): void {
for (const c of children) {
walkNode(c, b, res, baseUrl);
}
}
function walkNode(n: HtmlNode, b: LineBuilder, res: Map<string, string>, baseUrl: string): void {
if (n.isText) {
appendText(b, n.text, res, baseUrl);
return;
}
const tag = n.tag;
if (DROP_TAGS.has(tag) || SKIP_TEXT_TAGS.has(tag)) {
return;
}
if (tag === 'br' || tag === 'hr') {
b.flush();
return;
}
if (tag === 'img') {
let src = n.attrs['src'] ?? '';
if (src.length === 0) {
src = n.attrs['data-src'] ?? '';
}
const abs = src.length > 0 ? urlHandler(src, baseUrl) : '';
if (abs.length > 0) {
b.emitPlaceholder(abs);
} else {
b.append('〔插图地址缺失〕');
}
return;
}
if (tag === 'a') {
const href = n.attrs['href'] ?? '';
const abs = href.length > 0 && !href.startsWith('#') ? urlHandler(href, baseUrl) : '';
if (abs.length > 0) {
// 沿用 ESJ 书源的链接标注习惯:URL 独立成行,便于 TXT/EPUB 保留来源
b.flush();
b.lines.push('[' + abs + ']');
b.heads.push(false);
}
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)) {
b.markHead();
}
walkChildren(n.children, b, res, baseUrl);
b.flush();
return;
}
walkChildren(n.children, b, res, baseUrl);
}
export function htmlToLines(html: string, res: Map<string, string>, baseUrl: string): LkLineContent {
const b = new LineBuilder();
const root = parseHtml(html);
walkChildren(root.children, b, res, baseUrl);
b.flush();
const r: LkLineContent = { lines: b.lines, heads: b.heads, noConv: b.noConv };
return r;
}
/** 旧文 BBCode 兜底(等价脚本 plainHTML:b/i/u/s/quote、img、url,其余标记剔除) */
export function bbcodeToLines(text: string, baseUrl: string): LkLineContent {
let s = cleanText(text);
for (let i = 0; i < 3; i++) {
s = s.replace(/\[(?:b|i|u|s|quote)\]([\s\S]*?)\[\/(?:b|i|u|s|quote)\]/gi, '$1');
}
s = s.replace(/\[\/?(?:size|color|font|align)(?:=[^\]]*)?\]/gi, '');
s = s.replace(/\[img\](https?:\/\/[^\s]+?)\[\/img\]/gi, '\n@@LKIMG:$1@@\n');
s = s.replace(/\[url=([^\s\]]+)\]([\s\S]*?)\[\/url\]/gi,
(_m: string, p1: string, p2: string): string => '\n[' + p1 + ']\n' + p2 + '\n');
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();
if (t.length === 0) {
continue;
}
const im = /^@@LKIMG:(.+?)@@$/.exec(t);
if (im !== null) {
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, noConv: noConv };
return r;
}
// ---------------- 章节解析 ----------------
function parseChapterData(data: JObj, bookId: string, chapterId: string): LkChapterParse {
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: [], noConv: [], error: '' };
return r;
}
const rp = asObj(data['render_preview']);
const bs = asObj(data['body_snapshot']);
let html = rp !== null ? jStr(rp, 'body_html') : '';
if (html.length === 0 && bs !== null) {
html = jStr(bs, 'body_html');
}
if (html.length === 0) {
html = jStr(data, 'body_html');
}
if (html.length === 0) {
html = jStr(data, 'content_html');
}
let text = rp !== null ? jStr(rp, 'body_text') : '';
if (text.length === 0 && bs !== null) {
text = jStr(bs, 'body_text');
}
if (text.length === 0) {
text = jStr(data, 'body_text');
}
const reader = readerPageUrl(bookId, chapterId);
const res = resourceMapOf(data);
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, 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, noConv: c2.noConv, error: '' };
return r3;
}
}
const r4: LkChapterParse = { status: 'error', lines: [], heads: [], noConv: [], error: '该章节未返回正文' };
return r4;
}
/** 抓取并解析章节正文(供 TaskPool 并发任务调用) */
export async function fetchChapterLines(bookId: string, chapterId: string, cfg: LkApiCfg): Promise<LkChapterParse> {
const payload: Record<string, Object> = { 'book_id': bookId, 'chapter_id': chapterId };
const data = await apiPost('get-chapter-detail', payload, cfg);
return parseChapterData(data, bookId, chapterId);
}
// ---------------- 目录抓取 ----------------
/** 书籍详情 + 卷列表(不含章节;等价脚本打开面板时的 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, 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);
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 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: ''
};
nodes.push(volNode);
const chPayload: Record<string, Object> = { 'book_id': bookId, 'volume_id': volumeId };
const chapters = await allPages('get-volume-chapters', chPayload, 'chapter_id', cfg);
for (const c of chapters) {
const chId = jStr(c, 'chapter_id');
const cNode: VolumeChapterNode = {
value: nodes.length, level: 1, fatherValue: volNode.value,
isVolume: false, isChapter: true, title: conv(jStr(c, 'title')), url: readerPageUrl(bookId, chId)
};
nodes.push(cNode);
}
}
const r: LkCatalogResult = {
ok: true, error: '', bookId: bookId, bookName: bookName,
author: author, coverUrl: coverUrl, nodes: nodes,
volumeTitles: volumeTitles, volumeTotal: volumeTotal
};
return r;
}
// ---------------- 整卷长文拆分 ----------------
const TITLE_MARKER_RE =
/^(?:第?[零〇一二三四五六七八九十百千万两壹贰叁肆伍陆柒捌玖拾\d]+[话話章幕节節卷]|第?[最終终]+[话話章]|序章|序幕|序言|前言|楔子|尾[声聲]|终章|終章|[后後][记記]|[间間]章|番外|特典)$/u;
const HEAD_PATTERNS: RegExp[] = [
/^.{0,16}特典[\s 【「::]/u,
/^(?:[【\[((]?第?[零〇一二三四五六七八九十百千万两壹贰叁肆伍陆柒捌玖拾\d]+[章话話幕节節][】\]))]?|chapter\s+\d+|episode\s+\d+)(?:[\s ::·.—-]|$)/iu,
/^(?:【(?:第.{1,10}[话話章幕节節]|最[终終][话話章]|尾[声聲]|序章|[后後][记記])】|第[零〇一二三四五六七八九十百千万两\d]+[话話章幕节節][\s ::]|.{0,16}(?:店|书屋|書屋)特典[\s 【「::]|(?:番外|特典|[后後][记記])[\s 【::])/u
];
interface SplitRow {
index: number; // 在 lines 中的下标
title: string;
key: string;
headTag: boolean;
}
interface SplitEntry {
title: string;
key: string;
}
interface SplitBoundary {
index: number;
title: string;
}
function bareTitle(t: string): boolean {
return TITLE_MARKER_RE.test(t.replace(/[\s【】\[\]「」]/g, ''));
}
function isHeadingLine(title: string, headTag: boolean): boolean {
if (title.length > 100 || /^[「『“"]/.test(title) || /[。;;]/.test(title)) {
return false;
}
if (headTag) {
return true;
}
if (bareTitle(title)) {
return true;
}
for (const re of HEAD_PATTERNS) {
if (re.test(title)) {
return true;
}
}
return false;
}
/** 目录匹配键:NFKC + 去尾部省略号页码 + 只保留字母数字与 CJK + 小写(等价脚本 normalize) */
function normKey(title: string): string {
let v = title.normalize('NFKC');
v = v.replace(/[..·…]{2,}\s*\d+\s*$/u, '');
let out = '';
for (const ch of v) {
const cp = ch.codePointAt(0) as number;
if ((cp >= 0x30 && cp <= 0x39) || (cp >= 0x41 && cp <= 0x5A) || (cp >= 0x61 && cp <= 0x7A) || cp >= 0x2E80) {
out += ch;
}
}
return out.toLowerCase();
}
/**
* 整卷长文拆分(等价脚本 splitContent 的行版本):
* 优先按正文内目录匹配拆分(≥2 项且 ≥75% 命中),否则按标题行拆分(≥2 个),
* 无依据时整篇保留为单片段。图片占位行不参与匹配但保留在所属片段中。
*/
export function splitChapterLines(lines: string[], heads: boolean[], fallbackTitle: string): LkLinePart[] {
const rows: SplitRow[] = [];
for (let i = 0; i < lines.length; i++) {
if (isImgPlaceholder(lines[i])) {
continue;
}
const title = lines[i].replace(/\s+/g, ' ').trim();
if (title.length === 0) {
continue;
}
rows.push({ index: i, title: title, key: normKey(title), headTag: heads[i] === true });
}
const tocAt = rows.findIndex((r: SplitRow): boolean => /^(?:目录|目錄|contents|tableofcontents)$/i.test(r.key));
let tocEnd = tocAt;
const entries: SplitEntry[] = [];
const boundaries: SplitBoundary[] = [];
if (tocAt >= 0) {
for (let i = tocAt + 1; i < rows.length && i < tocAt + 180; i++) {
const row = rows[i];
if (row.title.length > 120 || /^[「『“"]/.test(row.title) || /[。;;]/.test(row.title)) {
break;
}
if (entries.some((e: SplitEntry): boolean => e.key === row.key)) {
break; // 重复项已是正文开头
}
let title = row.title;
let end = i;
if (bareTitle(title) && i + 1 < rows.length && rows[i + 1].title.length <= 100
&& !isHeadingLine(rows[i + 1].title, rows[i + 1].headTag)) {
title = title + ' ' + rows[i + 1].title;
end = i + 1;
}
const key = normKey(title);
if (entries.some((e: SplitEntry): boolean => e.key === key)) {
break;
}
entries.push({ title: title, key: key });
tocEnd = end;
i = end;
}
let cursor = tocEnd + 1;
for (const entry of entries) {
for (let i = cursor; i < rows.length; i++) {
const row = rows[i];
if (row.title.length > 150) {
continue;
}
const pair = bareTitle(row.title) && i + 1 < rows.length
? normKey(row.title + ' ' + rows[i + 1].title) : '';
if (row.key === entry.key || (pair.length > 0 && pair === entry.key)) {
boundaries.push({ index: row.index, title: entry.title });
cursor = pair === entry.key ? i + 2 : i + 1;
break;
}
}
}
if (boundaries.length >= 2 && entries.length > 0 && boundaries.length >= entries.length * 0.75) {
// 后记、实体店特典常没有列入正文目录;只补明确的独立标题
const lastIdx = boundaries[boundaries.length - 1].index;
for (const row of rows) {
if (row.index > lastIdx && isHeadingLine(row.title, row.headTag)) {
boundaries.push({ index: row.index, title: row.title });
}
}
} else {
boundaries.length = 0;
}
}
if (boundaries.length === 0) {
for (const row of rows) {
if (row.index > tocEnd && isHeadingLine(row.title, row.headTag)) {
boundaries.push({ index: row.index, title: row.title });
}
}
// 至少两个明确标题才进行拆分;无依据时整篇保留
if (boundaries.length < 2) {
boundaries.length = 0;
}
}
if (boundaries.length === 0) {
const whole: LkLinePart = { title: fallbackTitle, lines: lines };
return [whole];
}
const starts: SplitBoundary[] = [];
let frontNonEmpty = false;
for (let i = 0; i < boundaries[0].index; i++) {
if (lines[i].trim().length > 0) {
frontNonEmpty = true;
break;
}
}
if (frontNonEmpty) {
starts.push({ index: 0, title: '卷首 · 制作信息与目录' });
}
for (const b of boundaries) {
starts.push({ index: b.index, title: b.title });
}
const parts: LkLinePart[] = [];
for (let k = 0; k < starts.length; k++) {
const from = starts[k].index;
const to = k + 1 < starts.length ? starts[k + 1].index - 1 : lines.length - 1;
parts.push({ title: starts[k].title, lines: lines.slice(from, to + 1) });
}
return parts;
}
+31 -94
View File
@@ -2,66 +2,42 @@ import { preferences } from '@kit.ArkData';
import { common } from '@kit.AbilityKit'; import { common } from '@kit.AbilityKit';
/** /**
* 应用配置:按书源分组的选项 + 通用下载选项,全部页面可配置并持久化。 * 应用配置:对应原脚本开头全部参数,全部页面可配置并持久化。
* * - siteUrl -> base_url
* 各书源选项(互不通用,来源于各自脚本): * - cookie -> esj.txt 第一行(含 ews_key / ews_token)
* - ESJZone(esj.py):站点域名 base_url、Cookie(ews_key/ews_token)、章节插图、封面 * - convertMode -> opencc t2s / s2t / none
* - 轻之国度(LK EPUB 导出脚本):Cookie(lk_security_key)、嵌入正文插图、 * - threadCount -> threadNum(并发数)
* 图片失败时保留说明并继续(skip-images)、整本下载使用书籍封面、候选封面数量(1-60) * - retryCount -> retrying stop_max_attempt_number
* * - timeoutSec -> requests timeout
* 通用选项(两站语义一致):繁简转换、并发数、重试、超时、EPUB/TXT 输出。 * - downloadImages / downloadCover / outputEpub / outputTxt -> 输出控制
*/ */
export const CONVERT_T2S: string = 't2s'; export const CONVERT_T2S: string = 't2s';
export const CONVERT_S2T: string = 's2t'; export const CONVERT_S2T: string = 's2t';
export const CONVERT_NONE: string = 'none'; 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 { export interface AppSettings {
esj: EsjSettings; siteUrl: string;
lk: LkSettings; cookie: string;
convertMode: string; // t2s / s2t / none convertMode: string;
threadCount: number; // 并发数 threadCount: number;
retryCount: number; // 失败重试次数 retryCount: number;
timeoutSec: number; // 请求超时(秒) timeoutSec: number;
downloadImages: boolean;
downloadCover: boolean;
outputEpub: boolean; outputEpub: boolean;
outputTxt: boolean; outputTxt: boolean;
} }
export function defaultSettings(): AppSettings { export function defaultSettings(): AppSettings {
const s: AppSettings = { const s: AppSettings = {
esj: { siteUrl: 'https://www.esjzone.cc/',
siteUrl: 'https://www.esjzone.cc/', cookie: '',
cookie: '',
downloadImages: true,
downloadCover: true
},
lk: {
cookie: '',
downloadImages: true,
skipFailedImages: false,
useBookCover: true,
coverCandidateCount: 4
},
convertMode: CONVERT_T2S, convertMode: CONVERT_T2S,
threadCount: 2, threadCount: 2,
retryCount: 3, retryCount: 3,
timeoutSec: 25, timeoutSec: 25,
downloadImages: true,
downloadCover: true,
outputEpub: true, outputEpub: true,
outputTxt: true outputTxt: true
}; };
@@ -79,7 +55,16 @@ export class ConfigStore {
if (raw.length > 0) { if (raw.length > 0) {
try { try {
const obj = JSON.parse(raw) as Record<string, Object>; const obj = JSON.parse(raw) as Record<string, Object>;
ConfigStore.parse(obj, base); 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) { } catch (e) {
// 配置损坏时使用默认值 // 配置损坏时使用默认值
} }
@@ -87,42 +72,6 @@ export class ConfigStore {
ConfigStore.cache = base; 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 { static get(): AppSettings {
if (ConfigStore.cache === null) { if (ConfigStore.cache === null) {
ConfigStore.cache = defaultSettings(); ConfigStore.cache = defaultSettings();
@@ -139,29 +88,17 @@ export class ConfigStore {
await ConfigStore.prefs.flush(); await ConfigStore.prefs.flush();
} }
/** ESJ Cookie 是否包含关键登录字段 */ /** cookie 是否包含关键登录字段 */
static cookieOk(cookie: string): boolean { static cookieOk(cookie: string): boolean {
return cookie.indexOf('ews_key') >= 0 && cookie.indexOf('ews_token') >= 0; return cookie.indexOf('ews_key') >= 0 && cookie.indexOf('ews_token') >= 0;
} }
/** 轻之国度 Cookie 是否包含安全密钥(公开内容可不配置) */
static lkCookieOk(cookie: string): boolean {
return cookie.indexOf('lk_security_key') >= 0;
}
/** 清理 cookie 字符串:去掉换行、首尾空格 */ /** 清理 cookie 字符串:去掉换行、首尾空格 */
static cleanCookie(cookie: string): string { static cleanCookie(cookie: string): string {
return cookie.replace(/\r?\n/g, '').trim(); return cookie.replace(/\r?\n/g, '').trim();
} }
} }
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 { function strOf(obj: Record<string, Object>, key: string, def: string): string {
const v = obj[key]; const v = obj[key];
return typeof v === 'string' ? v : def; return typeof v === 'string' ? v : def;
+3 -22
View File
@@ -1,20 +1,16 @@
import { TocPreviewNode } from './TaskModel'; import { TocPreviewNode } from './TaskModel';
/** /**
* 单本下载的"选章 + 自定义标题 + LK 卷/封面"草稿。 * 单本下载的"选章 + 自定义标题"草稿。
* 与目标 URL 绑定;URL 变化时自动清空,避免串书。 * 与目标 URL 绑定;URL 变化时自动清空,避免串书。
*/ */
export class DownloadDraft { export class DownloadDraft {
static url: string = ''; static url: string = '';
static customTitle: string = ''; static customTitle: string = '';
static chapterFilter: number[] = []; // 空 = 全部章节(ESJ 按章选择) static chapterFilter: number[] = []; // 空 = 全部章节
static nodes: TocPreviewNode[] = []; // 已抓取的目录缓存(ESJ 选章用) static nodes: TocPreviewNode[] = []; // 已抓取的目录缓存
static bookName: string = ''; static bookName: string = '';
static author: 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 { static reset(): void {
DownloadDraft.url = ''; DownloadDraft.url = '';
@@ -23,10 +19,6 @@ export class DownloadDraft {
DownloadDraft.nodes = []; DownloadDraft.nodes = [];
DownloadDraft.bookName = ''; DownloadDraft.bookName = '';
DownloadDraft.author = ''; DownloadDraft.author = '';
DownloadDraft.lkVolumeIds = [];
DownloadDraft.lkVolumeTotal = 0;
DownloadDraft.lkCoverUrl = '';
DownloadDraft.lkCoverVolumeId = '';
} }
/** 目标 URL 变化时清空草稿(避免不同书籍沿用旧的选章/标题) */ /** 目标 URL 变化时清空草稿(避免不同书籍沿用旧的选章/标题) */
@@ -55,15 +47,4 @@ export class DownloadDraft {
} }
return n; 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;
}
} }
+25 -601
View File
@@ -2,17 +2,13 @@ import { taskpool } from '@kit.ArkTS';
import { fileIo as fs } from '@kit.CoreFileKit'; import { fileIo as fs } from '@kit.CoreFileKit';
import { util } from '@kit.ArkTS'; import { util } from '@kit.ArkTS';
import { ConfigStore, AppSettings } from './Config'; import { ConfigStore, AppSettings } from './Config';
import { TaskInfo, ChapterNode, BookProgress, TocPreviewNode, TocPreviewResult, ChapterPart, import { TaskInfo, ChapterNode, BookProgress, TocPreviewNode, TocPreviewResult } from './TaskModel';
LkCoverCandidate, LkCoverCandidatesResult } from './TaskModel';
import { NodeStatus, TaskStatus } from '../common/Theme'; import { NodeStatus, TaskStatus } from '../common/Theme';
import { AppHub } from '../common/AppHub'; import { AppHub } from '../common/AppHub';
import { OpenCC } from '../core/OpenCC'; import { OpenCC } from '../core/OpenCC';
import { analyzeDetail, parseListPage, urlHandler, isImgPlaceholder, imgPlaceholderUrl, hostOf, VolumeChapterNode } from '../core/EsjCore'; import { analyzeDetail, parseListPage, urlHandler, isImgPlaceholder, imgPlaceholderUrl, hostOf, VolumeChapterNode } from '../core/EsjCore';
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 { buildEpub, EpubBuildInput, EpubImageItem, EpubNodeItem, escapeXml } from '../core/EpubWriter';
import { fetchChapterJob, fetchImageJob, fetchLkChapterJob, import { fetchChapterJob, fetchImageJob, FetchChapterArgs, FetchImageArgs, FetchChapterResult, FetchImageResult } from '../worker/Jobs';
FetchChapterArgs, FetchImageArgs, FetchChapterResult, FetchImageResult, FetchLkChapterArgs, FetchLkChapterResult } from '../worker/Jobs';
import { httpGetText } from '../net/HttpUtil'; import { httpGetText } from '../net/HttpUtil';
import { LibraryStore, BookRecord } from './LibraryStore'; import { LibraryStore, BookRecord } from './LibraryStore';
@@ -39,7 +35,6 @@ export class TaskManager {
activeTaskId: string = ''; activeTaskId: string = '';
private imgMap: Map<string, ImageState> = new Map(); private imgMap: Map<string, ImageState> = new Map();
private imgBytes: number = 0; // 已成功图片累计字节数(384MB 上限,等价脚本)
private lastEmit: number = 0; private lastEmit: number = 0;
tasksSnapshot(): TaskInfo[] { tasksSnapshot(): TaskInfo[] {
@@ -55,24 +50,18 @@ export class TaskManager {
return null; return null;
} }
createTask(mode: string, url: string, customTitle: string = '', chapterFilter: number[] = [], createTask(mode: string, url: string, customTitle: string = '', chapterFilter: number[] = []): TaskInfo {
source: string = 'esj', lkCoverUrl: string = '', lkVolumeIds: string[] = []): TaskInfo {
const t = new TaskInfo(); const t = new TaskInfo();
t.id = 'task_' + Date.now().toString(36) + '_' + Math.floor(Math.random() * 1000); t.id = 'task_' + Date.now().toString(36) + '_' + Math.floor(Math.random() * 1000);
t.mode = mode; t.mode = mode;
t.source = source;
t.url = url; t.url = url;
t.customTitle = customTitle; t.customTitle = customTitle;
t.lkCoverUrl = lkCoverUrl;
for (const v of lkVolumeIds) {
t.lkVolumeIds.push(v);
}
for (const v of chapterFilter) { for (const v of chapterFilter) {
t.chapterFilter.push(v); t.chapterFilter.push(v);
} }
t.createdAt = Date.now(); t.createdAt = Date.now();
this.tasks.unshift(t); this.tasks.unshift(t);
t.addLog('info', mode === 'list' ? '创建批量下载任务' : (source === 'lk' ? '创建轻之国度下载任务' : '创建下载任务')); t.addLog('info', mode === 'list' ? '创建批量下载任务' : '创建下载任务');
this.emit(true); this.emit(true);
if (this.activeTaskId === '') { if (this.activeTaskId === '') {
this.startTask(t); this.startTask(t);
@@ -83,187 +72,26 @@ export class TaskManager {
/** 拉取目录预览(选章下载用)。返回纯数据,不改任务状态。 */ /** 拉取目录预览(选章下载用)。返回纯数据,不改任务状态。 */
async fetchTocPreview(url: string): Promise<TocPreviewResult> { async fetchTocPreview(url: string): Promise<TocPreviewResult> {
const s = ConfigStore.get(); const s = ConfigStore.get();
if (url.toLowerCase().indexOf('lightnovel') >= 0) {
return this.fetchTocPreviewLk(url, s);
}
const empty: TocPreviewNode[] = []; const empty: TocPreviewNode[] = [];
const resp = await httpGetText(url, s.esj.cookie, s.timeoutSec * 1000, s.retryCount); const resp = await httpGetText(url, s.cookie, s.timeoutSec * 1000, s.retryCount);
if (!resp.ok) { if (!resp.ok) {
const r: TocPreviewResult = { ok: false, error: resp.error, nodes: empty, bookName: '', author: '' }; const r: TocPreviewResult = { ok: false, error: resp.error, nodes: empty, bookName: '', author: '' };
return r; return r;
} }
const cc = await OpenCC.getConverter(s.convertMode, AppHub.uiContext()); const cc = await OpenCC.getConverter(s.convertMode, AppHub.uiContext());
const detail = analyzeDetail(resp.text, s.esj.siteUrl, cc !== null ? (x: string): string => cc.convert(x) : null); const detail = analyzeDetail(resp.text, s.siteUrl, cc !== null ? (x: string): string => cc.convert(x) : null);
if (!detail.ok) { if (!detail.ok) {
const r2: TocPreviewResult = { ok: false, error: detail.error, nodes: empty, bookName: '', author: '' }; const r2: TocPreviewResult = { ok: false, error: detail.error, nodes: empty, bookName: '', author: '' };
return r2; return r2;
} }
const nodes: TocPreviewNode[] = []; const nodes: TocPreviewNode[] = [];
for (const n of detail.nodes) { 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, url: n.url }); 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 }; const r3: TocPreviewResult = { ok: true, error: '', nodes: nodes, bookName: detail.bookName, author: detail.author };
return r3; return r3;
} }
/** LK 目录预览:书籍详情 + 全部卷章(分页) */
private async fetchTocPreviewLk(url: string, s: AppSettings): Promise<TocPreviewResult> {
const empty: TocPreviewNode[] = [];
const bookId = parseBookId(url);
if (bookId.length === 0) {
const r: TocPreviewResult =
{ ok: false, error: '链接中未找到书籍编号(需要 lightnovel.fun/book/<id> 链接)', nodes: empty, bookName: '', author: '' };
return r;
}
const cookie = ConfigStore.cleanCookie(s.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 {
const cat: LkCatalogResult = await fetchCatalog(bookId, cfg,
cc !== null ? (x: string): string => cc.convert(x) : null);
const nodes: TocPreviewNode[] = [];
for (const n of cat.nodes) {
nodes.push({ value: n.value, level: n.level, fatherValue: n.fatherValue, isVolume: n.isVolume, isChapter: n.isChapter, title: n.title, url: n.url });
}
const r2: TocPreviewResult = { ok: true, error: '', nodes: nodes, bookName: cat.bookName, author: cat.author };
return r2;
} catch (e) {
const r3: TocPreviewResult = { ok: false, error: (e as Error).message, nodes: empty, bookName: '', author: '' };
return r3;
}
}
/**
* 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 { requestCancel(id: string): void {
const t = this.findTask(id); const t = this.findTask(id);
if (t === null) { if (t === null) {
@@ -370,8 +198,6 @@ export class TaskManager {
try { try {
if (t.mode === 'list') { if (t.mode === 'list') {
await this.runList(t, s); await this.runList(t, s);
} else if (t.source === 'lk') {
await this.runBookLk(t, s, retryOnly);
} else { } else {
await this.runBook(t, s, t.url, null, retryOnly); await this.runBook(t, s, t.url, null, retryOnly);
} }
@@ -392,25 +218,24 @@ export class TaskManager {
if (t.status !== TaskStatus.DONE_WITH_FAIL) { if (t.status !== TaskStatus.DONE_WITH_FAIL) {
this.cleanupCache(t); this.cleanupCache(t);
this.imgMap.clear(); this.imgMap.clear();
this.imgBytes = 0;
} }
this.finishActive(t); this.finishActive(t);
} }
} }
private async runList(t: TaskInfo, s: AppSettings): Promise<void> { private async runList(t: TaskInfo, s: AppSettings): Promise<void> {
const mismatch = checkDomain(t.url, s.esj.siteUrl); const mismatch = checkDomain(t.url, s.siteUrl);
if (mismatch.length > 0) { if (mismatch.length > 0) {
throw new Error(mismatch); throw new Error(mismatch);
} }
t.phase = 'list'; t.phase = 'list';
t.addLog('info', '开始收集书籍列表…'); t.addLog('info', '开始收集书籍列表…');
this.emit(true); this.emit(true);
const firstPage = await httpGetText(t.url, s.esj.cookie, s.timeoutSec * 1000, s.retryCount); const firstPage = await httpGetText(t.url, s.cookie, s.timeoutSec * 1000, s.retryCount);
if (!firstPage.ok) { if (!firstPage.ok) {
throw new Error('列表页下载失败: ' + firstPage.error); throw new Error('列表页下载失败: ' + firstPage.error);
} }
const firstInfo = parseListPage(firstPage.text, s.esj.siteUrl); const firstInfo = parseListPage(firstPage.text, s.siteUrl);
const total = firstInfo.totalCount > 0 ? firstInfo.totalCount : 1; const total = firstInfo.totalCount > 0 ? firstInfo.totalCount : 1;
t.addLog('info', `列表「${firstInfo.title}」共 ${total} 页`); t.addLog('info', `列表「${firstInfo.title}」共 ${total} 页`);
const bookUrls: string[] = []; const bookUrls: string[] = [];
@@ -426,12 +251,12 @@ export class TaskManager {
return; return;
} }
const pageUrl = t.url + p + '.html'; const pageUrl = t.url + p + '.html';
const resp = await httpGetText(pageUrl, s.esj.cookie, s.timeoutSec * 1000, s.retryCount); const resp = await httpGetText(pageUrl, s.cookie, s.timeoutSec * 1000, s.retryCount);
if (!resp.ok) { if (!resp.ok) {
t.addLog('warn', `第 ${p} 页下载失败: ${resp.error}`); t.addLog('warn', `第 ${p} 页下载失败: ${resp.error}`);
continue; continue;
} }
const info = parseListPage(resp.text, s.esj.siteUrl); const info = parseListPage(resp.text, s.siteUrl);
for (const u of info.bookUrls) { for (const u of info.bookUrls) {
if (!seen.has(u)) { if (!seen.has(u)) {
seen.add(u); seen.add(u);
@@ -493,7 +318,7 @@ export class TaskManager {
let recordId = bookUrl; let recordId = bookUrl;
if (!retryOnly) { if (!retryOnly) {
const mismatch = checkDomain(bookUrl, s.esj.siteUrl); const mismatch = checkDomain(bookUrl, s.siteUrl);
if (mismatch.length > 0) { if (mismatch.length > 0) {
throw new Error(mismatch); throw new Error(mismatch);
} }
@@ -501,13 +326,13 @@ export class TaskManager {
t.currentTitle = '获取书籍信息'; t.currentTitle = '获取书籍信息';
this.emit(true); this.emit(true);
const resp = await httpGetText(bookUrl, s.esj.cookie, s.timeoutSec * 1000, s.retryCount); const resp = await httpGetText(bookUrl, s.cookie, s.timeoutSec * 1000, s.retryCount);
if (!resp.ok) { if (!resp.ok) {
throw new Error('详情页下载失败: ' + resp.error); throw new Error('详情页下载失败: ' + resp.error);
} }
const cc = await OpenCC.getConverter(s.convertMode, AppHub.uiContext()); const cc = await OpenCC.getConverter(s.convertMode, AppHub.uiContext());
const convertFn = cc !== null ? (x: string): string => cc.convert(x) : null; const convertFn = cc !== null ? (x: string): string => cc.convert(x) : null;
const detail = analyzeDetail(resp.text, s.esj.siteUrl, convertFn); const detail = analyzeDetail(resp.text, s.siteUrl, convertFn);
if (!detail.ok) { if (!detail.ok) {
throw new Error(detail.error); throw new Error(detail.error);
} }
@@ -606,8 +431,8 @@ export class TaskManager {
const txtPath = AppHub.uiContext().filesDir + '/library/' + unique + '.txt'; const txtPath = AppHub.uiContext().filesDir + '/library/' + unique + '.txt';
// 封面 // 封面
if (s.esj.downloadCover && coverUrl.length > 0) { if (s.downloadCover && coverUrl.length > 0) {
await this.ensureImage(t, s, coverUrl, imgDir, s.esj.cookie); await this.ensureImage(t, s, coverUrl, imgDir);
} }
// 章节并发下载 // 章节并发下载
@@ -618,7 +443,6 @@ export class TaskManager {
n.status === NodeStatus.DONE || n.status === NodeStatus.LOCKED).length; n.status === NodeStatus.DONE || n.status === NodeStatus.LOCKED).length;
if (!retryOnly) { if (!retryOnly) {
this.imgMap.clear(); this.imgMap.clear();
this.imgBytes = 0;
} }
const cursor: Cursor = { i: 0 }; const cursor: Cursor = { i: 0 };
const workers: Promise<void>[] = []; const workers: Promise<void>[] = [];
@@ -675,7 +499,7 @@ export class TaskManager {
} }
}); });
let cover: EpubImageItem | undefined = undefined; let cover: EpubImageItem | undefined = undefined;
if (s.esj.downloadCover && coverUrl.length > 0) { if (s.downloadCover && coverUrl.length > 0) {
const cv = this.imgMap.get(coverUrl); const cv = this.imgMap.get(coverUrl);
if (cv !== undefined && cv.status === 'done') { 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: coverUrl, fileName: 'cover' + cv.fileName.substring(cv.fileName.lastIndexOf('.')), contentType: cv.contentType, filePath: cv.filePath };
@@ -749,8 +573,8 @@ export class TaskManager {
node.status = NodeStatus.DOWNLOADING; node.status = NodeStatus.DOWNLOADING;
t.currentTitle = node.node.title; t.currentTitle = node.node.title;
this.emit(false); this.emit(false);
const fullUrl = urlHandler(node.node.url, s.esj.siteUrl); const fullUrl = urlHandler(node.node.url, s.siteUrl);
const args: FetchChapterArgs = { url: fullUrl, cookie: s.esj.cookie, timeoutMs: s.timeoutSec * 1000, retry: s.retryCount }; const args: FetchChapterArgs = { url: fullUrl, cookie: s.cookie, timeoutMs: s.timeoutSec * 1000, retry: s.retryCount };
const job = new taskpool.Task(fetchChapterJob, args); const job = new taskpool.Task(fetchChapterJob, args);
let result: FetchChapterResult | null = null; let result: FetchChapterResult | null = null;
try { try {
@@ -795,8 +619,8 @@ export class TaskManager {
} }
// 内联下载本章图片 // 内联下载本章图片
for (const line of node.lines) { for (const line of node.lines) {
if (isImgPlaceholder(line) && s.esj.downloadImages) { if (isImgPlaceholder(line) && s.downloadImages) {
await this.ensureImage(t, s, imgPlaceholderUrl(line), imgDir, s.esj.cookie); await this.ensureImage(t, s, imgPlaceholderUrl(line), imgDir);
if (t.cancelRequested) { if (t.cancelRequested) {
return; return;
} }
@@ -808,394 +632,15 @@ export class TaskManager {
} }
} }
// ---------------- LK(轻之国度 lightnovel.fun)主流程 ---------------- private async ensureImage(t: TaskInfo, s: AppSettings, url: string, imgDir: string): Promise<void> {
/**
* 下载轻之国度书籍(等价脚本按卷模型):所选卷抓取完整目录并并发抓章,
* 部分卷合并命名「书名 — 卷1、卷2」;整卷长文按目录/标题拆分;图片匿名抓取。
*/
private async runBookLk(t: TaskInfo, s: AppSettings, retryOnly: boolean = false): Promise<boolean> {
const cacheDir = AppHub.uiContext().cacheDir + '/task_' + t.id;
const chDir = cacheDir + '/chapters';
const imgDir = cacheDir + '/images';
const bookId = parseBookId(t.url);
if (bookId.length === 0) {
throw new Error('链接中未找到书籍编号(需要 lightnovel.fun/book/<id> 链接)');
}
const bookUrl = bookPageUrl(bookId);
let bookName = t.bookName;
let author = t.author;
let coverUrl = t.coverUrl;
let unique = '';
let recordId = bookUrl;
if (!retryOnly) {
const host = hostOf(t.url);
if (host.indexOf('lightnovel.fun') < 0) {
throw new Error(`链接域名(${host}) 不受支持,请使用 lightnovel.fun 的书籍链接`);
}
t.phase = 'detail';
t.currentTitle = '获取书籍信息与目录';
this.emit(true);
const cookie = ConfigStore.cleanCookie(s.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, t.lkVolumeIds);
if (t.cancelRequested) {
return true;
}
if (cat.nodes.filter((n: VolumeChapterNode): boolean => n.isChapter).length === 0) {
throw new Error('所选卷没有可下载的章节');
}
const partial = t.lkVolumeIds.length > 0 && t.lkVolumeIds.length < cat.volumeTotal;
t.lkVolumeTotal = cat.volumeTotal;
author = cat.author;
coverUrl = cat.coverUrl;
t.author = author;
t.coverUrl = coverUrl;
// 等价脚本命名:自定义标题 > 部分卷「书名 — 卷1、卷2」> 原书名
if (t.customTitle.length > 0) {
bookName = t.customTitle;
} else if (partial) {
bookName = clipMergedName(cat.bookName + ' — ' + cat.volumeTitles.join('、'));
} else {
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));
// 部分卷下载与整本/原书记录隔离(等价脚本各自生成独立文件)
const baseName = `《${bookName}》${author}`;
recordId = (t.customTitle.length > 0 || partial) ? bookUrl + '#' + baseName : bookUrl;
t.lkRecordId = recordId;
unique = LibraryStore.uniqueName(baseName, recordId);
} else {
// 增量重试:缓存必须仍存在
if (!fs.accessSync(cacheDir)) {
throw new Error('任务缓存已被清理,请重新下载这本书');
}
ensureDir(chDir);
ensureDir(imgDir);
if (t.nodes.length === 0) {
throw new Error('没有可重试的章节');
}
recordId = t.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';
// 封面策略(等价脚本:单卷=自定义候选封面;整本=书籍封面;部分多卷=无封面;均匿名抓取)
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, '');
}
// 章节并发下载
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();
this.imgBytes = 0;
}
const cursor: Cursor = { i: 0 };
const workers: Promise<void>[] = [];
for (let w = 0; w < Math.max(1, s.threadCount); w++) {
workers.push(this.chapterWorkerLk(t, s, bookId, chapterNodes, cursor, chDir, imgDir));
}
await Promise.all(workers);
if (t.cancelRequested) {
return true;
}
// 整卷长文拆分片段展开为独立章节节点
this.expandParts(t, chDir);
t.currentTitle = '正在打包';
// 组装 TXT(LK 无独立简介段)
if (s.outputTxt) {
let txt = '';
for (const n of t.nodes) {
if (n.node.isChapter && n.status === NodeStatus.FAILED) {
txt += n.node.title + '章节下载失败\n' + n.node.url + '\n';
continue;
}
txt += n.node.title + '\n';
if (n.node.isChapter) {
txt += txtOfLines(n.lines, this.imgMap);
}
}
writeTextFileSync(txtPath, txt);
}
// 打包 EPUB
if (s.outputEpub) {
t.phase = 'build';
this.emit(true);
const nodeItems: EpubNodeItem[] = [];
for (const n of t.nodes) {
const fileName = n.node.isChapter
? (n.status === NodeStatus.FAILED ? `error_novel_${n.node.value}.xhtml` : `novel_${n.node.value}.xhtml`)
: `volume_${n.node.value}.xhtml`;
if (n.node.isChapter && n.fragmentPath === '') {
// 失败章节写入错误占位
const failPath = chDir + '/' + fileName;
const failLines = ['章节下载失败', n.node.url, n.error];
writeFragment(failPath, failLines);
n.fragmentPath = failPath;
}
nodeItems.push({ node: n.node, fileName: fileName, fragmentPath: n.node.isChapter ? n.fragmentPath : '' });
}
const images: EpubImageItem[] = [];
this.imgMap.forEach((v: ImageState, k: string): void => {
if (v.status === 'done' && k !== coverFinal) {
images.push({ url: k, fileName: v.fileName, contentType: v.contentType, filePath: v.filePath });
}
});
let cover: EpubImageItem | undefined = undefined;
if (coverFinal.length > 0) {
const cv = this.imgMap.get(coverFinal);
if (cv !== undefined && cv.status === 'done') {
cover = { url: coverFinal, fileName: 'cover' + cv.fileName.substring(cv.fileName.lastIndexOf('.')), contentType: cv.contentType, filePath: cv.filePath };
} else {
t.addLog('warn', '封面未嵌入:下载失败');
}
}
const buildInput: EpubBuildInput = {
outPath: epubPath, bookName: bookName, author: author, changeDate: '',
cover: cover, nodes: nodeItems, images: images
};
try {
buildEpub(buildInput);
t.epubPath = epubPath;
} catch (e) {
t.addLog('error', 'EPUB 打包失败: ' + (e as Error).message);
}
}
t.txtPath = s.outputTxt ? txtPath : '';
// 入库
const record: BookRecord = {
id: recordId, url: bookUrl, name: bookName, author: author, date: '',
baseName: unique,
epubPath: t.epubPath, txtPath: t.txtPath,
chapters: chapterNodes.length, createdAt: Date.now()
};
LibraryStore.upsert(record);
t.phase = 'done';
const failedNow = t.failedChapters;
const lockedCount = t.nodes.filter((n: ChapterNode): boolean => n.status === NodeStatus.LOCKED).length;
if (failedNow > 0) {
t.status = TaskStatus.DONE_WITH_FAIL;
t.addLog('ok', `《${bookName}》下载完成,${failedNow} 章失败可重试${lockedCount > 0 ? `(另 ${lockedCount} 章无权限)` : ''}`);
} else {
t.status = TaskStatus.DONE;
t.addLog('ok', `《${bookName}》下载完成${lockedCount > 0 ? `(${lockedCount} 章无阅读权限,已跳过)` : ''}`);
// 无失败章节,释放章节文本内存
for (const n of t.nodes) {
n.lines = [];
n.parts = [];
}
}
return true;
}
private async chapterWorkerLk(t: TaskInfo, s: AppSettings, bookId: string, list: ChapterNode[],
cursor: Cursor, chDir: string, imgDir: string): Promise<void> {
const cc = await OpenCC.getConverter(s.convertMode, AppHub.uiContext());
while (!t.cancelRequested) {
const idx = cursor.i;
if (idx >= list.length) {
return;
}
cursor.i++;
const node = list[idx];
if (node.status !== NodeStatus.PENDING) {
// 增量重试时跳过已完成的章节
continue;
}
node.status = NodeStatus.DOWNLOADING;
t.currentTitle = node.node.title;
this.emit(false);
const cookie = ConfigStore.cleanCookie(s.lk.cookie);
const args: FetchLkChapterArgs = {
bookId: bookId, chapterId: chapterIdFromUrl(node.node.url),
cookie: cookie, securityKey: extractSecurityKey(cookie),
timeoutMs: s.timeoutSec * 1000, retry: s.retryCount
};
const job = new taskpool.Task(fetchLkChapterJob, args);
let result: FetchLkChapterResult | null = null;
try {
result = await taskpool.execute(job) as FetchLkChapterResult;
} catch (e) {
result = { ok: false, status: 'error', lines: [], heads: [], noConv: [], 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;
}
// 转换文本(图片占位行与 pre/code 行不转换,等价脚本 simplifyContent)
let lines = result.lines;
if (cc !== null) {
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;
node.lines = ['该章节当前不可读,需登录或取得阅读权限'];
} else if (lines.length === 0) {
node.status = NodeStatus.DONE;
node.lines = ['【空】'];
} else {
node.status = NodeStatus.DONE;
node.lines = lines;
// 整卷长文:目录/标题匹配成功时暂存片段,打包前展开
const parts: LkLinePart[] = splitChapterLines(lines, result.heads, node.node.title);
if (parts.length > 1) {
const chapterParts: ChapterPart[] = [];
for (const p of parts) {
chapterParts.push({ title: p.title, lines: p.lines });
}
node.parts = chapterParts;
t.addLog('info', `「${node.node.title}」检测到卷内目录/标题,将拆分为 ${parts.length} 节`);
}
}
if (node.node.isChapter && node.parts.length <= 1) {
const fragPath = `${chDir}/novel_${node.node.value}.xhtml`;
writeFragment(fragPath, node.lines);
node.fragmentPath = fragPath;
}
// 内联下载本章图片(匿名,按 URL 去重)
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++;
node.touch();
this.emit(false);
}
}
/** 将长文拆分片段展开为独立章节节点(新 value 接在最大值之后,沿用原章节的父卷) */
private expandParts(t: TaskInfo, chDir: string): void {
let hasParts = false;
for (const n of t.nodes) {
if (n.node.isChapter && n.parts.length > 1) {
hasParts = true;
break;
}
}
if (!hasParts) {
return;
}
let maxV = 0;
for (const n of t.nodes) {
if (n.node.value > maxV) {
maxV = n.node.value;
}
}
const out: ChapterNode[] = [];
let partCount = 0;
for (const n of t.nodes) {
if (n.node.isChapter && n.parts.length > 1) {
for (const p of n.parts) {
maxV++;
partCount++;
const copy: VolumeChapterNode = {
value: maxV, level: n.node.level, fatherValue: n.node.fatherValue,
isVolume: false, isChapter: true, title: p.title, url: n.node.url
};
const cn = new ChapterNode(copy);
cn.status = NodeStatus.DONE;
cn.lines = p.lines;
const fragPath = `${chDir}/novel_${maxV}.xhtml`;
writeFragment(fragPath, p.lines);
cn.fragmentPath = fragPath;
out.push(cn);
}
continue;
}
out.push(n);
}
t.nodes = out;
t.addLog('info', `长章节已拆分为 ${partCount} 节`);
}
/** cookie 按书源传入:ESJ 用站点 Cookie,LK 按脚本约定插图/封面匿名抓取(传 '') */
private async ensureImage(t: TaskInfo, s: AppSettings, url: string, imgDir: string,
cookie: string): Promise<void> {
if (this.imgMap.has(url)) { if (this.imgMap.has(url)) {
return; return;
} }
const st: ImageState = { status: 'inflight', fileName: '', filePath: '', contentType: '', error: '' }; const st: ImageState = { status: 'inflight', fileName: '', filePath: '', contentType: '', error: '' };
this.imgMap.set(url, st); this.imgMap.set(url, st);
t.totalImages = this.imgMap.size; t.totalImages = this.imgMap.size;
const fullUrl = urlHandler(url, s.esj.siteUrl); const fullUrl = urlHandler(url, s.siteUrl);
const args: FetchImageArgs = { url: fullUrl, cookie: cookie, timeoutMs: s.timeoutSec * 1000, retry: s.retryCount }; const args: FetchImageArgs = { url: fullUrl, cookie: s.cookie, timeoutMs: s.timeoutSec * 1000, retry: s.retryCount };
const job = new taskpool.Task(fetchImageJob, args); const job = new taskpool.Task(fetchImageJob, args);
let result: FetchImageResult | null = null; let result: FetchImageResult | null = null;
try { try {
@@ -1204,16 +649,6 @@ export class TaskManager {
result = { ok: false, ext: '', hash: '', data: new ArrayBuffer(0), error: (e as Error).message }; result = { ok: false, ext: '', hash: '', data: new ArrayBuffer(0), error: (e as Error).message };
} }
if (result !== null && result.ok) { 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 fileName = `Image_${result.hash}${result.ext}`;
const filePath = imgDir + '/' + fileName; const filePath = imgDir + '/' + fileName;
try { try {
@@ -1249,17 +684,6 @@ 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 { function checkDomain(url: string, siteUrl: string): string {
const h1 = hostOf(url); const h1 = hostOf(url);
const h2 = hostOf(siteUrl); const h2 = hostOf(siteUrl);
+1 -30
View File
@@ -11,19 +11,12 @@ export interface LogLine {
msg: string; msg: string;
} }
/** LK 整卷长文拆分出的片段(多于 1 段时在打包前展开为独立章节节点) */
export interface ChapterPart {
title: string;
lines: string[];
}
export class ChapterNode { export class ChapterNode {
node: VolumeChapterNode; node: VolumeChapterNode;
status: string = NodeStatus.PENDING; status: string = NodeStatus.PENDING;
lines: string[] = []; // 转换后的文本行(含图片占位行) lines: string[] = []; // 转换后的文本行(含图片占位行)
error: string = ''; error: string = '';
fragmentPath: string = ''; fragmentPath: string = '';
parts: ChapterPart[] = []; // 非空且 >1 段时表示长文已拆分
doneTick: number = 0; // 用于驱动 UI 刷新 doneTick: number = 0; // 用于驱动 UI 刷新
constructor(node: VolumeChapterNode) { constructor(node: VolumeChapterNode) {
@@ -54,7 +47,6 @@ export interface TocPreviewNode {
isVolume: boolean; isVolume: boolean;
isChapter: boolean; isChapter: boolean;
title: string; title: string;
url: string; // 章节/卷的原始链接(章节用于封面候选扫描取 chapter_id)
} }
export interface TocPreviewResult { export interface TocPreviewResult {
@@ -65,26 +57,9 @@ export interface TocPreviewResult {
author: string; 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 { export class TaskInfo {
id: string = ''; id: string = '';
mode: string = 'book'; // book | list mode: string = 'book'; // book | list
source: string = 'esj'; // esj | lk(书源,由链接域名决定)
url: string = ''; url: string = '';
status: string = TaskStatus.QUEUED; status: string = TaskStatus.QUEUED;
bookName: string = ''; bookName: string = '';
@@ -108,11 +83,7 @@ export class TaskInfo {
createdAt: number = 0; createdAt: number = 0;
cancelRequested: boolean = false; cancelRequested: boolean = false;
customTitle: string = ''; // 用户自定义 EPUB 标题(空=用原书名) customTitle: string = ''; // 用户自定义 EPUB 标题(空=用原书名)
chapterFilter: number[] = []; // 选中的章节节点 value(空=全部,ESJ 按章) chapterFilter: number[] = []; // 选中的章节节点 value(空=全部)
lkVolumeIds: string[] = []; // LK 选中的卷(空=整本)
lkVolumeTotal: number = 0; // LK 全部卷数(用于判断单卷/整本/部分多卷)
lkRecordId: string = ''; // LK 部分卷下载的入库 id(重试时复用,避免覆盖整本记录)
lkCoverUrl: string = ''; // LK 自定义封面图片地址(空=按设置决定)
activeBooksDone: number = 0; activeBooksDone: number = 0;
activeBooksTotal: number = 0; activeBooksTotal: number = 0;
versionTick: number = 0; // 每次有变化自增,驱动界面刷新 versionTick: number = 0; // 每次有变化自增,驱动界面刷新
-58
View File
@@ -58,23 +58,6 @@ function imgHeaders(cookie: string): Record<string, string> {
return h; return h;
} }
/** JSON API 请求头:站点代理接口需要浏览态的 Origin/Referer */
function apiHeaders(cookie: string, origin: string): Record<string, string> {
const h: Record<string, string> = {
'User-Agent': DEFAULT_UA,
'Content-Type': 'application/json',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Origin': origin,
'Referer': origin + '/',
'Connection': 'keep-alive'
};
if (cookie.length > 0) {
h['Cookie'] = cookie;
}
return h;
}
function sleep(ms: number): Promise<void> { function sleep(ms: number): Promise<void> {
return new Promise<void>((resolve: (v: void) => void) => { return new Promise<void>((resolve: (v: void) => void) => {
setTimeout((): void => resolve(), ms); setTimeout((): void => resolve(), ms);
@@ -121,47 +104,6 @@ export async function httpGetText(url: string, cookie: string, timeoutMs: number
return r2; return r2;
} }
/**
* POST JSON(轻之国度 pc-proxy 接口),带重试。origin 用于 Origin/Referer 头。
*/
export async function httpPostJson(url: string, cookie: string, body: string, timeoutMs: number,
retry: number, origin: string): Promise<HttpResultText> {
const attempts = retry + 1;
let lastErr = '';
for (let a = 0; a < attempts; a++) {
if (a > 0) {
await sleep(1500);
}
const req = http.createHttp();
try {
const resp = await req.request(url, {
method: http.RequestMethod.POST,
header: apiHeaders(cookie, origin),
extraData: body,
expectDataType: http.HttpDataType.STRING,
usingCache: false,
connectTimeout: Math.max(5000, Math.min(timeoutMs, 20000)),
readTimeout: timeoutMs
});
req.destroy();
if (resp.responseCode >= 200 && resp.responseCode < 300) {
const r: HttpResultText = { ok: true, code: resp.responseCode, text: resp.result as string, error: '' };
return r;
}
lastErr = 'HTTP ' + resp.responseCode;
} catch (e) {
lastErr = '网络错误: ' + (e as Error).message;
try {
req.destroy();
} catch (e2) {
// 忽略销毁异常
}
}
}
const r2: HttpResultText = { ok: false, code: 0, text: '', error: lastErr };
return r2;
}
/** /**
* GET 二进制(图片),带重试。 * GET 二进制(图片),带重试。
*/ */
+5 -7
View File
@@ -11,13 +11,14 @@ import { LibraryView } from '../view/LibraryView';
import { SettingsView } from '../view/SettingsView'; import { SettingsView } from '../view/SettingsView';
import { TaskDetailPage } from '../view/TaskDetailPage'; import { TaskDetailPage } from '../view/TaskDetailPage';
import { ChapterSelectPage } from '../view/ChapterSelectPage'; import { ChapterSelectPage } from '../view/ChapterSelectPage';
import { LkCoverSelectPage } from '../view/LkCoverSelectPage';
import { LkVolumeSelectPage } from '../view/LkVolumeSelectPage';
import { HDS_MATERIAL, InsetKey, Insets } from '../common/Theme'; import { HDS_MATERIAL, InsetKey, Insets } from '../common/Theme';
const TAB_TITLES: string[] = ['下载', '书库', '设置']; const TAB_TITLES: string[] = ['下载', '书库', '设置'];
/** 应用入口:下载 / 书库 / 设置三页签,子页面经 HdsNavDestination 路由。 */ /**
* 应用入口:HdsNavigation(沉浸光感标题栏 + 渐变模糊)+ HdsTabs 悬浮底部页签(沉浸光感材质),
* 子页面(任务详情 / 选章)通过 HdsNavDestination 路由。
*/
@Entry @Entry
@Component @Component
struct Index { struct Index {
@@ -43,10 +44,6 @@ struct Index {
TaskDetailPage() TaskDetailPage()
} else if (name === 'chapterSelect') { } else if (name === 'chapterSelect') {
ChapterSelectPage() ChapterSelectPage()
} else if (name === 'lkVolumeSelect') {
LkVolumeSelectPage()
} else if (name === 'lkCoverSelect') {
LkCoverSelectPage()
} }
} }
@@ -96,6 +93,7 @@ struct Index {
title: { mainTitle: TAB_TITLES[this.currentTab] } title: { mainTitle: TAB_TITLES[this.currentTab] }
}, },
style: { style: {
// 非沉浸式列表类页面推荐 GRADIENT_BLUR + 沉浸光感材质
scrollEffectOpts: { scrollEffectOpts: {
enableScrollEffect: true, enableScrollEffect: true,
scrollEffectType: ScrollEffectType.GRADIENT_BLUR scrollEffectType: ScrollEffectType.GRADIENT_BLUR
@@ -7,7 +7,10 @@ import { TocPreviewNode } from '../model/TaskModel';
import { DownloadDraft } from '../model/Draft'; import { DownloadDraft } from '../model/Draft';
import { SymIcon, EmptyView, FloatingToolbar, ToolbarAction } from './Widgets'; import { SymIcon, EmptyView, FloatingToolbar, ToolbarAction } from './Widgets';
/** 选章下载页:抓取目录并勾选章节,确认后回填首页草稿。 */ /**
* 选章下载页:抓取目录 → 勾选章节(点卷名整卷切换)→ 确认后回填草稿。
* 保存的草稿在首页用于「开始下载(已选 N 章)」。操作集中在底部悬浮工具栏。
*/
@Component @Component
export struct ChapterSelectPage { export struct ChapterSelectPage {
@Consume pathStack: NavPathStack; @Consume pathStack: NavPathStack;
@@ -106,6 +109,7 @@ export struct ChapterSelectPage {
this.recount(); this.recount();
} }
/** 卷节点:切换其所有子孙章节 */
childrenOf(volumeValue: number): number[] { childrenOf(volumeValue: number): number[] {
const out: number[] = []; const out: number[] = [];
for (let i = 0; i < this.nodes.length; i++) { for (let i = 0; i < this.nodes.length; i++) {
@@ -284,6 +288,7 @@ export struct ChapterSelectPage {
.justifyContent(FlexAlign.Center) .justifyContent(FlexAlign.Center)
.padding(Dim.pagePad) .padding(Dim.pagePad)
} else { } else {
// 章节列表:卷为分组卡片的标题行,内容延伸到标题栏与悬浮工具栏下方
List({ space: 0, scroller: this.scroller }) { List({ space: 0, scroller: this.scroller }) {
ForEach(this.nodes, (n: TocPreviewNode, idx: number) => { ForEach(this.nodes, (n: TocPreviewNode, idx: number) => {
ListItem() { ListItem() {
@@ -303,6 +308,7 @@ export struct ChapterSelectPage {
.contentEndOffset(Insets.contentBottom(this.bottomInset)) .contentEndOffset(Insets.contentBottom(this.bottomInset))
.clipContent(ContentClipMode.SAFE_AREA) .clipContent(ContentClipMode.SAFE_AREA)
// 悬浮工具栏
FloatingToolbar() { FloatingToolbar() {
ToolbarAction({ ToolbarAction({
label: '全选', label: '全选',
+91 -258
View File
@@ -7,10 +7,12 @@ import { TaskManager } from '../model/TaskManager';
import { TaskInfo } from '../model/TaskModel'; import { TaskInfo } from '../model/TaskModel';
import { DownloadDraft } from '../model/Draft'; import { DownloadDraft } from '../model/Draft';
import { hostOf } from '../core/EsjCore'; import { hostOf } from '../core/EsjCore';
import { parseBookId } from '../core/LkCore';
import { PrimaryButton, EmptyView, SymIcon, SegmentedControl } from './Widgets'; import { PrimaryButton, EmptyView, SymIcon, SegmentedControl } from './Widgets';
/** 下载页:新建任务(粘贴链接、选章、自定义标题)+ 任务进度列表。 */ /**
* 下载页:新建任务(粘贴链接、模式识别、选章与自定义标题、域名/Cookie 检查)+ 任务进度列表。
* 页面标题由根 HdsNavigation 标题栏承载,内容区延伸至标题栏与悬浮页签下方。
*/
@Component @Component
export struct HomeView { export struct HomeView {
@Consume pathStack: NavPathStack; @Consume pathStack: NavPathStack;
@@ -22,10 +24,10 @@ export struct HomeView {
@State modeIdx: number = 0; // 0 单本 1 批量 @State modeIdx: number = 0; // 0 单本 1 批量
@State tasks: TaskInfo[] = []; @State tasks: TaskInfo[] = [];
@State cookieReady: boolean = false; @State cookieReady: boolean = false;
@State lkCookieReady: boolean = false;
@State siteHost: string = ''; @State siteHost: string = '';
@State threadCount: number = 2; @State threadCount: number = 2;
@State convertLabel: string = '繁→简'; @State convertLabel: string = '繁→简';
@State autoDetected: boolean = false;
@State draftTick: number = 0; // 选章草稿变化时自增,驱动刷新 @State draftTick: number = 0; // 选章草稿变化时自增,驱动刷新
@State titleInput: string = ''; @State titleInput: string = '';
@@ -74,9 +76,8 @@ export struct HomeView {
refreshConfig(): void { refreshConfig(): void {
const s: AppSettings = ConfigStore.get(); const s: AppSettings = ConfigStore.get();
this.siteHost = hostOf(s.esj.siteUrl); this.siteHost = hostOf(s.siteUrl);
this.cookieReady = ConfigStore.cookieOk(ConfigStore.cleanCookie(s.esj.cookie)); this.cookieReady = ConfigStore.cookieOk(ConfigStore.cleanCookie(s.cookie));
this.lkCookieReady = ConfigStore.lkCookieOk(ConfigStore.cleanCookie(s.lk.cookie));
this.threadCount = s.threadCount; this.threadCount = s.threadCount;
this.convertLabel = s.convertMode === 't2s' ? '繁→简' : (s.convertMode === 's2t' ? '简→繁' : '不转换'); this.convertLabel = s.convertMode === 't2s' ? '繁→简' : (s.convertMode === 's2t' ? '简→繁' : '不转换');
} }
@@ -85,75 +86,22 @@ export struct HomeView {
return hostOf(this.urlInput.trim()); return hostOf(this.urlInput.trim());
} }
/** 书源:'' 未知 | 'esj' ESJZone | 'lk' 轻之国度 */
src(): string {
const h = this.urlHost();
if (h.indexOf('lightnovel') >= 0) {
return 'lk';
}
if (h.indexOf('esjzone') >= 0) {
return 'esj';
}
return '';
}
isEsjUrl(): boolean { isEsjUrl(): boolean {
return this.src() === 'esj'; return this.urlHost().indexOf('esjzone') >= 0;
}
isLkUrl(): boolean {
return this.src() === 'lk';
} }
domainMatch(): boolean { domainMatch(): boolean {
return this.isEsjUrl() && this.urlHost() === this.siteHost; return this.isEsjUrl() && this.urlHost() === this.siteHost;
} }
/** LK 仅接受主站域名(API 固定在 www.lightnovel.fun) */
lkHostOk(): boolean {
const h = this.urlHost();
return h === 'www.lightnovel.fun' || h === 'lightnovel.fun';
}
lkBookId(): string {
return parseBookId(this.urlInput.trim());
}
canStart(): boolean {
const src = this.src();
if (src === 'esj') {
return this.domainMatch();
}
if (src === 'lk') {
return this.lkHostOk() && this.lkBookId().length > 0;
}
return false;
}
canSelectChapters(): boolean {
const src = this.src();
if (src === 'esj') {
return this.domainMatch();
}
if (src === 'lk') {
return this.lkHostOk() && this.lkBookId().length > 0;
}
return false;
}
detectMode(): void { detectMode(): void {
const u = this.urlInput.trim(); const u = this.urlInput.trim();
if (this.isLkUrl()) {
// LK 暂只支持单本书籍
if (/\/(?:book|reader)\/\d+/.test(u)) {
this.modeIdx = 0;
}
return;
}
if (u.indexOf('/detail/') >= 0 || /\/\d+\.html/.test(u)) { if (u.indexOf('/detail/') >= 0 || /\/\d+\.html/.test(u)) {
this.modeIdx = 0; this.modeIdx = 0;
this.autoDetected = true;
} else if (u.indexOf('/list-') >= 0 || u.indexOf('/tags/') >= 0) { } else if (u.indexOf('/list-') >= 0 || u.indexOf('/tags/') >= 0) {
this.modeIdx = 1; this.modeIdx = 1;
this.autoDetected = true;
} }
} }
@@ -176,23 +124,16 @@ export struct HomeView {
startTask(): void { startTask(): void {
const url = this.urlInput.trim(); const url = this.urlInput.trim();
if (!this.canStart()) { if (url.length === 0 || !this.isEsjUrl() || !this.domainMatch()) {
return; return;
} }
if (this.src() === 'lk') { if (this.modeIdx === 0) {
DownloadDraft.onUrlChanged(url);
const partial = DownloadDraft.lkVolumeFilterActive(url);
const volumes = partial ? DownloadDraft.lkVolumeIds.slice() : [];
const title = DownloadDraft.url === url ? DownloadDraft.customTitle : '';
const cover = DownloadDraft.lkVolumeSingle(url) ? DownloadDraft.lkCoverUrl : '';
TaskManager.instance.createTask('book', url, title, [], 'lk', cover, volumes);
} else if (this.modeIdx === 0) {
DownloadDraft.onUrlChanged(url); DownloadDraft.onUrlChanged(url);
const filter = DownloadDraft.filterActiveFor(url) ? DownloadDraft.chapterFilter.slice() : []; const filter = DownloadDraft.filterActiveFor(url) ? DownloadDraft.chapterFilter.slice() : [];
const title = DownloadDraft.url === url ? DownloadDraft.customTitle : ''; const title = DownloadDraft.url === url ? DownloadDraft.customTitle : '';
TaskManager.instance.createTask('book', url, title, filter, 'esj'); TaskManager.instance.createTask('book', url, title, filter);
} else { } else {
TaskManager.instance.createTask('list', url, '', [], 'esj'); TaskManager.instance.createTask('list', url);
} }
this.urlInput = ''; this.urlInput = '';
this.titleInput = ''; this.titleInput = '';
@@ -202,7 +143,7 @@ export struct HomeView {
switchSiteTo(host: string): void { switchSiteTo(host: string): void {
const s: AppSettings = ConfigStore.get(); const s: AppSettings = ConfigStore.get();
s.esj.siteUrl = 'https://' + host + '/'; s.siteUrl = 'https://' + host + '/';
ConfigStore.save(s).then((): void => { ConfigStore.save(s).then((): void => {
this.refreshConfig(); this.refreshConfig();
promptAction.showToast({ message: '站点域名已切换' }); promptAction.showToast({ message: '站点域名已切换' });
@@ -219,13 +160,6 @@ export struct HomeView {
if (this.modeIdx === 1) { if (this.modeIdx === 1) {
return '开始批量下载'; return '开始批量下载';
} }
if (this.src() === 'lk') {
const url = this.urlInput.trim();
if (DownloadDraft.lkVolumeFilterActive(url)) {
return `开始下载(已选 ${DownloadDraft.lkVolumeIds.length} 卷)`;
}
return '开始下载整本';
}
const n = this.draftFilterCount(); const n = this.draftFilterCount();
return n > 0 ? `开始下载(已选 ${n} 章)` : '开始下载这本书'; return n > 0 ? `开始下载(已选 ${n} 章)` : '开始下载这本书';
} }
@@ -275,57 +209,13 @@ export struct HomeView {
} }
openChapterSelect(): void { openChapterSelect(): void {
if (!this.canSelectChapters()) { if (!this.domainMatch()) {
return; return;
} }
DownloadDraft.onUrlChanged(this.urlInput.trim()); DownloadDraft.onUrlChanged(this.urlInput.trim());
this.pathStack.pushPathByName('chapterSelect', this.urlInput.trim()); 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 @Builder
miniAction(label: string, color: ResourceColor, action: () => void) { miniAction(label: string, color: ResourceColor, action: () => void) {
Button(label, { type: ButtonType.Capsule }) Button(label, { type: ButtonType.Capsule })
@@ -341,7 +231,7 @@ export struct HomeView {
taskCard(t: TaskInfo) { taskCard(t: TaskInfo) {
Column({ space: 10 }) { Column({ space: 10 }) {
Row({ space: 8 }) { Row({ space: 8 }) {
Text(t.mode === 'list' ? '批量' : (t.source === 'lk' ? 'LK' : '单本')) Text(t.mode === 'list' ? '批量' : '单本')
.fontSize(FontSize.cap) .fontSize(FontSize.cap)
.fontColor($r('app.color.brand')) .fontColor($r('app.color.brand'))
.backgroundColor($r('app.color.brand_soft')) .backgroundColor($r('app.color.brand_soft'))
@@ -423,15 +313,22 @@ export struct HomeView {
build() { build() {
Scroll(this.scroller) { Scroll(this.scroller) {
Column({ space: Dim.cardGap }) { Column({ space: Dim.cardGap }) {
// 新建任务卡片
Column({ space: 12 }) { Column({ space: 12 }) {
Text('新建任务') Column({ space: 2 }) {
.fontSize(FontSize.body) Text('新建任务')
.fontWeight(FontWeight.Medium) .fontSize(FontSize.body)
.fontColor($r('app.color.font_pri')) .fontWeight(FontWeight.Medium)
.width('100%') .fontColor($r('app.color.font_pri'))
Text('粘贴 ESJZone 链接,自动抓取章节并打包 EPUB / TXT')
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
}
.width('100%')
.alignItems(HorizontalAlign.Start)
Row({ space: 8 }) { Row({ space: 8 }) {
TextInput({ text: this.urlInput, placeholder: 'esjzone.cc/detail/… 或 lightnovel.fun/book/…' }) TextInput({ text: this.urlInput, placeholder: 'https://www.esjzone.cc/detail/…' })
.fontSize(FontSize.sub) .fontSize(FontSize.sub)
.height(40) .height(40)
.borderRadius(20) .borderRadius(20)
@@ -463,15 +360,26 @@ export struct HomeView {
} }
.width('100%') .width('100%')
SegmentedControl({ Column({ space: 6 }) {
options: this.src() === 'lk' ? ['单本书籍'] : ['单本书籍', '批量列表'], SegmentedControl({
activeIndex: this.modeIdx, options: ['单本书籍', '批量列表'],
onSelect: (idx: number): void => { activeIndex: this.modeIdx,
this.modeIdx = idx; onSelect: (idx: number): void => {
this.modeIdx = idx;
}
})
if (this.autoDetected) {
Text('已根据链接自动识别下载模式,可手动修改')
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
.padding({ left: 4 })
} }
}) }
.width('100%')
.alignItems(HorizontalAlign.Start)
if (this.modeIdx === 0 && (this.src() === 'lk' ? this.lkHostOk() : this.domainMatch())) { // 单本模式:自定义标题 + 选章
if (this.modeIdx === 0 && this.domainMatch()) {
Column({ space: 6 }) { Column({ space: 6 }) {
TextInput({ text: this.titleInput, placeholder: '自定义标题(可选,留空使用原书名)' }) TextInput({ text: this.titleInput, placeholder: '自定义标题(可选,留空使用原书名)' })
.fontSize(FontSize.sub) .fontSize(FontSize.sub)
@@ -486,133 +394,50 @@ export struct HomeView {
DownloadDraft.customTitle = v; DownloadDraft.customTitle = v;
this.titleInput = v; this.titleInput = v;
}) })
if (this.src() === 'lk') { Row({ space: 6 }) {
// LK:按卷选择(等价脚本卷勾选面板,全选即整本) SymIcon({
Row({ space: 6 }) { sym: $r('sys.symbol.list_bullet'),
SymIcon({ iconSize: 16,
sym: $r('sys.symbol.list_bullet'), colorRes: $r('app.color.brand')
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();
}) })
// LK:单卷下载时的候选封面入口(等价脚本单卷封面面板) Text('选择章节')
if (this.lkVolumeSingle()) { .fontSize(FontSize.sub)
Row({ space: 6 }) { .fontColor($r('app.color.font_pri'))
SymIcon({ Blank()
sym: $r('sys.symbol.picture'), Text(this.draftFilterCount() > 0 ? `已选 ${this.draftFilterCount()} 章` : '全部章节')
iconSize: 16, .fontSize(FontSize.cap)
colorRes: $r('app.color.brand') .fontColor(this.draftFilterCount() > 0 ? $r('app.color.brand') : $r('app.color.font_ter'))
}) SymIcon({
Text('自定义封面') sym: $r('sys.symbol.chevron_right'),
.fontSize(FontSize.sub) iconSize: 14,
.fontColor($r('app.color.font_pri')) colorRes: $r('app.color.font_ter')
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%') .width('100%')
.alignItems(HorizontalAlign.Start) .alignItems(HorizontalAlign.Start)
} }
if (this.urlInput.trim().length > 0 && this.src() === '') { // 状态提示行
if (this.urlInput.trim().length > 0 && !this.isEsjUrl()) {
Row({ space: 6 }) { Row({ space: 6 }) {
SymIcon({ SymIcon({
sym: $r('sys.symbol.exclamationmark_triangle'), sym: $r('sys.symbol.exclamationmark_triangle'),
iconSize: 15, iconSize: 15,
colorRes: $r('app.color.warn') colorRes: $r('app.color.warn')
}) })
Text('无法识别的链接,目前支持 ESJZone 与 轻之国度(lightnovel.fun)') Text('不是 esjzone 链接,请检查')
.fontSize(FontSize.cap) .fontSize(FontSize.cap)
.fontColor($r('app.color.warn')) .fontColor($r('app.color.warn'))
} }
} else if (this.src() === 'lk' && !this.lkHostOk()) {
Row({ space: 6 }) {
SymIcon({
sym: $r('sys.symbol.exclamationmark_triangle'),
iconSize: 15,
colorRes: $r('app.color.warn')
})
Text(`仅支持 www.lightnovel.fun 链接(当前:${this.urlHost()})`)
.fontSize(FontSize.cap)
.fontColor($r('app.color.warn'))
}
} else if (this.src() === 'lk') {
Row({ space: 6 }) {
SymIcon({
sym: $r('sys.symbol.checkmark_circle'),
iconSize: 15,
colorRes: $r('app.color.ok')
})
Text(`轻之国度 · ${this.urlHost()} · 书籍编号 ${this.lkBookId()}`)
.fontSize(FontSize.cap)
.fontColor($r('app.color.ok'))
}
} else if (this.isEsjUrl() && !this.domainMatch()) { } else if (this.isEsjUrl() && !this.domainMatch()) {
Row({ space: 6 }) { Row({ space: 6 }) {
SymIcon({ SymIcon({
@@ -645,13 +470,9 @@ export struct HomeView {
} }
Row({ space: 8 }) { Row({ space: 8 }) {
Text(this.src() === 'lk' Text(`Cookie ${this.cookieReady ? '已配置' : '未配置'}`)
? `LK Cookie ${this.lkCookieReady ? '已配置' : '未配置'}`
: `Cookie ${this.cookieReady ? '已配置' : '未配置'}`)
.fontSize(FontSize.cap) .fontSize(FontSize.cap)
.fontColor(this.src() === 'lk' .fontColor(this.cookieReady ? $r('app.color.ok') : $r('app.color.warn'))
? (this.lkCookieReady ? $r('app.color.ok') : $r('app.color.warn'))
: (this.cookieReady ? $r('app.color.ok') : $r('app.color.warn')))
Text('·') Text('·')
.fontColor($r('app.color.font_ter')) .fontColor($r('app.color.font_ter'))
Text(`并发 ${this.threadCount}`) Text(`并发 ${this.threadCount}`)
@@ -674,11 +495,17 @@ export struct HomeView {
PrimaryButton({ PrimaryButton({
label: this.startLabel(), label: this.startLabel(),
isEnabled: this.canStart(), isEnabled: this.isEsjUrl() && this.domainMatch(),
onTap: (): void => { onTap: (): void => {
this.startTask(); this.startTask();
} }
}) })
if (!this.cookieReady) {
Text('提示:未配置 Cookie 时,部分书籍(如 R18 区)将无法访问。可在「设置 → Cookie」中粘贴。')
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
}
} }
.width('100%') .width('100%')
.padding(Dim.cardPad) .padding(Dim.cardPad)
@@ -699,7 +526,7 @@ export struct HomeView {
EmptyView({ EmptyView({
sym: $r('sys.symbol.arrow_down_circle'), sym: $r('sys.symbol.arrow_down_circle'),
title: '暂无下载任务', title: '暂无下载任务',
sub: '粘贴书籍链接开始下载' sub: '粘贴书籍详情页链接开始\n批量模式支持 /list-/ 与 /tags/ 列表链接'
}) })
} }
.width('100%') .width('100%')
@@ -710,6 +537,12 @@ export struct HomeView {
this.taskCard(t) this.taskCard(t)
}, (t: TaskInfo) => t.id + t.status + t.doneChapters + t.failedChapters + t.progressPercent()) }, (t: TaskInfo) => t.id + t.status + t.doneChapters + t.failedChapters + t.progressPercent())
} }
Text('下载期间请保持应用在前台;书籍完成后可在「书库」中导出或分享。')
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
.width('100%')
.padding({ left: 12, right: 12 })
} }
.width('100%') .width('100%')
.padding({ .padding({
+9 -1
View File
@@ -212,7 +212,7 @@ export struct LibraryView {
EmptyView({ EmptyView({
sym: $r('sys.symbol.book_pages_fill'), sym: $r('sys.symbol.book_pages_fill'),
title: '书库还是空的', title: '书库还是空的',
sub: '完成下载后,书籍会自动保存在这里' sub: '完成下载后,书籍会自动保存在这里\n支持系统分享给阅读器或导出到本地'
}) })
} }
.width('100%') .width('100%')
@@ -225,6 +225,14 @@ export struct LibraryView {
this.bookCard(r) this.bookCard(r)
} }
}, (r: BookRecord) => r.id + r.date) }, (r: BookRecord) => r.id + r.date)
ListItem() {
Text('文件保存在应用沙箱 library 目录;「导出」可保存到用户选择的位置。')
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
.width('100%')
.padding({ left: 12, right: 12, top: 4 })
}
} }
.width('100%') .width('100%')
.height('100%') .height('100%')
@@ -1,313 +0,0 @@
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();
}
})
}
}
@@ -1,289 +0,0 @@
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();
}
})
}
}
+90 -203
View File
@@ -3,38 +3,32 @@ import { promptAction } from '@kit.ArkUI';
import { AppHub } from '../common/AppHub'; import { AppHub } from '../common/AppHub';
import { Dim, FontSize, InsetKey, Insets } from '../common/Theme'; import { Dim, FontSize, InsetKey, Insets } from '../common/Theme';
import { ConfigStore, AppSettings, CONVERT_T2S, CONVERT_S2T, CONVERT_NONE } from '../model/Config'; import { ConfigStore, AppSettings, CONVERT_T2S, CONVERT_S2T, CONVERT_NONE } from '../model/Config';
import { OpenCC } from '../core/OpenCC';
import { hostOf } from '../core/EsjCore'; import { hostOf } from '../core/EsjCore';
import { SectionCard, SettingRow, SegmentedControl, SymIcon } from './Widgets'; import { SectionCard, SettingRow, SegmentedControl, SymIcon } from './Widgets';
/** /**
* 设置页:按书源分组的选项(ESJZone / 轻之国度各自独立)+ 两站共用的通用选项。 * 设置页:原脚本的全部参数(站点、Cookie、并发、重试、超时、繁简转换、输出),
* 各书源选项来源于对应脚本,语义互不混用;修改即持久化。 * 修改即持久化。
*/ */
@Component @Component
export struct SettingsView { export struct SettingsView {
scroller: Scroller = new Scroller(); scroller: Scroller = new Scroller();
@StorageProp(InsetKey.TOP) topInset: number = 0; @StorageProp(InsetKey.TOP) topInset: number = 0;
@StorageProp(InsetKey.BOTTOM) bottomInset: number = 0; @StorageProp(InsetKey.BOTTOM) bottomInset: number = 0;
// ESJZone
@State siteUrl: string = ''; @State siteUrl: string = '';
@State cookie: 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 convertMode: string = CONVERT_T2S;
@State threadCount: number = 2; @State threadCount: number = 2;
@State retryCount: number = 3; @State retryCount: number = 3;
@State timeoutSec: number = 25; @State timeoutSec: number = 25;
@State downloadImages: boolean = true;
@State downloadCover: boolean = true;
@State outputEpub: boolean = true; @State outputEpub: boolean = true;
@State outputTxt: boolean = true; @State outputTxt: boolean = true;
@State showCookieHelp: boolean = false; @State showCookieHelp: boolean = false;
@State showLkCookieHelp: boolean = false; @State dictLoaded: boolean = false;
@State dictSize: number = 0;
private configListener: (data?: string) => void = (_d?: string): void => { private configListener: (data?: string) => void = (_d?: string): void => {
this.loadFromStore(); this.loadFromStore();
}; };
@@ -50,42 +44,29 @@ export struct SettingsView {
loadFromStore(): void { loadFromStore(): void {
const s = ConfigStore.get(); const s = ConfigStore.get();
this.siteUrl = s.esj.siteUrl; this.siteUrl = s.siteUrl;
this.cookie = s.esj.cookie; this.cookie = s.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.convertMode = s.convertMode;
this.threadCount = s.threadCount; this.threadCount = s.threadCount;
this.retryCount = s.retryCount; this.retryCount = s.retryCount;
this.timeoutSec = s.timeoutSec; this.timeoutSec = s.timeoutSec;
this.downloadImages = s.downloadImages;
this.downloadCover = s.downloadCover;
this.outputEpub = s.outputEpub; this.outputEpub = s.outputEpub;
this.outputTxt = s.outputTxt; this.outputTxt = s.outputTxt;
this.dictLoaded = OpenCC.loadedMode === this.convertMode;
} }
private persist(): void { private persist(): void {
const s: AppSettings = { const s: AppSettings = {
esj: { siteUrl: this.siteUrl,
siteUrl: this.siteUrl, cookie: this.cookie,
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, convertMode: this.convertMode,
threadCount: this.threadCount, threadCount: this.threadCount,
retryCount: this.retryCount, retryCount: this.retryCount,
timeoutSec: this.timeoutSec, timeoutSec: this.timeoutSec,
downloadImages: this.downloadImages,
downloadCover: this.downloadCover,
outputEpub: this.outputEpub, outputEpub: this.outputEpub,
outputTxt: this.outputTxt outputTxt: this.outputTxt
}; };
@@ -98,10 +79,6 @@ export struct SettingsView {
return ConfigStore.cookieOk(ConfigStore.cleanCookie(this.cookie)); return ConfigStore.cookieOk(ConfigStore.cleanCookie(this.cookie));
} }
lkCookieOk(): boolean {
return ConfigStore.lkCookieOk(ConfigStore.cleanCookie(this.lkCookie));
}
async pasteCookie(): Promise<void> { async pasteCookie(): Promise<void> {
try { try {
const data = await pasteboard.getSystemPasteboard().getData(); const data = await pasteboard.getSystemPasteboard().getData();
@@ -118,31 +95,33 @@ export struct SettingsView {
} }
} }
async pasteLkCookie(): Promise<void> { async warmDict(): Promise<void> {
try { try {
const data = await pasteboard.getSystemPasteboard().getData(); const cc = await OpenCC.getConverter(this.convertMode, AppHub.uiContext());
const txt = data.getPrimaryText() ?? ''; if (cc !== null) {
if (txt.length > 0) { this.dictLoaded = true;
this.lkCookie = ConfigStore.cleanCookie(txt); this.dictSize = cc.dictSize();
this.persist();
promptAction.showToast({ message: this.lkCookieOk() ? 'LK Cookie 已粘贴并识别到 lk_security_key' : '已粘贴,但未检测到 lk_security_key' });
} else {
promptAction.showToast({ message: '剪贴板为空' });
} }
} catch (e) { } catch (e) {
promptAction.showToast({ message: '读取剪贴板失败' }); this.dictLoaded = false;
} }
} }
build() { build() {
Scroll(this.scroller) { Scroll(this.scroller) {
Column({ space: Dim.cardGap + 4 }) { Column({ space: Dim.cardGap + 4 }) {
// ---------- ESJZone ---------- Text('所有配置修改后立即生效并自动保存')
SectionCard({ title: 'ESJZone(esjzone.cc)' }) { .fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
.width('100%')
.padding({ left: 12 })
// ---------- 站点与账号 ----------
SectionCard({ title: '站点与账号' }) {
Column({ space: 4 }) { Column({ space: 4 }) {
SettingRow({ SettingRow({
title: '站点域名', title: '站点域名',
desc: '需与下载链接、Cookie 的域名一致' desc: '脚本中的 base_url,需与下载链接、Cookie 的域名一致'
}) })
Row({ space: 8 }) { Row({ space: 8 }) {
TextInput({ text: this.siteUrl, placeholder: 'https://www.esjzone.cc/' }) TextInput({ text: this.siteUrl, placeholder: 'https://www.esjzone.cc/' })
@@ -188,8 +167,8 @@ export struct SettingsView {
Divider().strokeWidth(0.5).color($r('app.color.divider')) Divider().strokeWidth(0.5).color($r('app.color.divider'))
SettingRow({ SettingRow({
title: 'ESJ Cookie', title: 'Cookie',
desc: this.cookieOk() ? '已检测到 ews_key / ews_token' : 'esj.txt 第一行内容,可直接粘贴' desc: this.cookieOk() ? '已检测到 ews_key / ews_token' : '原脚本 esj.txt 第一行内容,可直接粘贴'
}) })
TextArea({ text: this.cookie, placeholder: 'ews_key=…;ews_token=…;' }) TextArea({ text: this.cookie, placeholder: 'ews_key=…;ews_token=…;' })
.fontSize(FontSize.cap) .fontSize(FontSize.cap)
@@ -250,157 +229,17 @@ export struct SettingsView {
.borderRadius(10) .borderRadius(10)
.backgroundColor($r('app.color.input_bg')) .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%') .width('100%')
.padding({ left: Dim.cardPad, right: Dim.cardPad }) .padding({ left: Dim.cardPad, right: Dim.cardPad })
} }
// ---------- 轻之国度 ---------- // ---------- 下载 ----------
SectionCard({ title: '轻之国度(lightnovel.fun)' }) { SectionCard({ title: '下载' }) {
Column({ space: 4 }) {
SettingRow({
title: 'LK Cookie',
desc: this.lkCookieOk() ? '已检测到 lk_security_key' : '站点固定为 www.lightnovel.fun;公开内容可不配置'
})
TextArea({ text: this.lkCookie, placeholder: 'lk_security_key=…; 其他 Cookie 一并粘贴更稳妥' })
.fontSize(FontSize.cap)
.height(72)
.borderRadius(10)
.backgroundColor($r('app.color.input_bg'))
.fontColor($r('app.color.font_pri'))
.placeholderColor($r('app.color.font_ter'))
.width('100%')
.onChange((v: string) => {
this.lkCookie = v;
this.persist();
})
Row({ space: 12 }) {
Text('粘贴')
.fontSize(FontSize.sub)
.fontColor($r('app.color.brand'))
.padding(6)
.onClick(() => {
this.pasteLkCookie();
})
Text('清空')
.fontSize(FontSize.sub)
.fontColor($r('app.color.err'))
.padding(6)
.onClick(() => {
this.lkCookie = '';
this.persist();
})
Text('使用说明')
.fontSize(FontSize.sub)
.fontColor($r('app.color.font_sec'))
.padding(6)
.onClick(() => {
this.showLkCookieHelp = !this.showLkCookieHelp;
})
Blank()
if (this.lkCookieOk()) {
Row({ space: 4 }) {
SymIcon({
sym: $r('sys.symbol.checkmark_circle'),
iconSize: 14,
colorRes: $r('app.color.ok')
})
Text('有效格式')
.fontSize(FontSize.cap)
.fontColor($r('app.color.ok'))
}
}
}
.width('100%')
if (this.showLkCookieHelp) {
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%')
.padding(10)
.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: '通用(两站共用)' }) {
Column({ space: 4 }) { Column({ space: 4 }) {
SettingRow({ SettingRow({
title: '并发数', title: '并发数',
desc: `同时下载 ${this.threadCount} 个章节(站点有反爬,不建议过大)`, desc: `同时下载 ${this.threadCount} 个章节(原脚本 threadNum,站点有反爬,不建议过大)`,
valueText: `${this.threadCount}` valueText: `${this.threadCount}`
}) })
Slider({ value: this.threadCount, min: 1, max: 6, step: 1, style: SliderStyle.OutSet }) Slider({ value: this.threadCount, min: 1, max: 6, step: 1, style: SliderStyle.OutSet })
@@ -415,6 +254,7 @@ export struct SettingsView {
SettingRow({ SettingRow({
title: '失败重试次数', title: '失败重试次数',
desc: '每个请求失败后的重试次数',
valueText: `${this.retryCount}` valueText: `${this.retryCount}`
}) })
Slider({ value: this.retryCount, min: 0, max: 5, step: 1, style: SliderStyle.OutSet }) Slider({ value: this.retryCount, min: 0, max: 5, step: 1, style: SliderStyle.OutSet })
@@ -429,6 +269,7 @@ export struct SettingsView {
SettingRow({ SettingRow({
title: '请求超时', title: '请求超时',
desc: `读取超时 ${this.timeoutSec} 秒`,
valueText: `${this.timeoutSec}s` valueText: `${this.timeoutSec}s`
}) })
Slider({ value: this.timeoutSec, min: 10, max: 60, step: 5, style: SliderStyle.OutSet }) Slider({ value: this.timeoutSec, min: 10, max: 60, step: 5, style: SliderStyle.OutSet })
@@ -442,7 +283,36 @@ export struct SettingsView {
Divider().strokeWidth(0.5).color($r('app.color.divider')) Divider().strokeWidth(0.5).color($r('app.color.divider'))
SettingRow({ SettingRow({
title: '繁简转换' title: '下载章节插图',
desc: '关闭后插图在正文中保留为文字链接',
showToggle: true,
isOn: this.downloadImages,
onToggle: (v: boolean): void => {
this.downloadImages = v;
this.persist();
}
})
SettingRow({
title: '下载封面',
desc: '生成 EPUB 封面页',
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: '繁简转换',
desc: '原脚本 opencc t2s(繁→简)/ s2t(简→繁)'
}) })
SegmentedControl({ SegmentedControl({
options: ['繁→简', '简→繁', '不转换'], options: ['繁→简', '简→繁', '不转换'],
@@ -450,13 +320,28 @@ export struct SettingsView {
onSelect: (idx: number): void => { onSelect: (idx: number): void => {
this.convertMode = idx === 0 ? CONVERT_T2S : (idx === 1 ? CONVERT_S2T : CONVERT_NONE); this.convertMode = idx === 0 ? CONVERT_T2S : (idx === 1 ? CONVERT_S2T : CONVERT_NONE);
this.persist(); this.persist();
this.dictLoaded = false;
if (this.convertMode !== CONVERT_NONE) {
this.warmDict();
}
} }
}) })
Text(this.convertMode === CONVERT_NONE
? '保持原文,不做转换'
: (this.dictLoaded ? `词典已就绪(${this.dictSize} 条词条,OpenCC 数据)` : '词典将在首次转换时自动加载'))
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
}
.width('100%')
.padding({ left: Dim.cardPad, right: Dim.cardPad })
}
Divider().strokeWidth(0.5).color($r('app.color.divider')) // ---------- 输出 ----------
SectionCard({ title: '输出' }) {
Column({ space: 4 }) {
SettingRow({ SettingRow({
title: '生成 EPUB', title: '生成 EPUB',
desc: '含封面、插图、嵌套目录',
showToggle: true, showToggle: true,
isOn: this.outputEpub, isOn: this.outputEpub,
onToggle: (v: boolean): void => { onToggle: (v: boolean): void => {
@@ -468,8 +353,10 @@ export struct SettingsView {
this.persist(); this.persist();
} }
}) })
Divider().strokeWidth(0.5).color($r('app.color.divider'))
SettingRow({ SettingRow({
title: '生成 TXT', title: '生成 TXT',
desc: '插图以原始链接形式保留',
showToggle: true, showToggle: true,
isOn: this.outputTxt, isOn: this.outputTxt,
onToggle: (v: boolean): void => { onToggle: (v: boolean): void => {
@@ -492,13 +379,13 @@ export struct SettingsView {
// ---------- 关于 ---------- // ---------- 关于 ----------
SectionCard({ title: '关于' }) { SectionCard({ title: '关于' }) {
Column({ space: 6 }) { Column({ space: 6 }) {
Text('ESJ / LK 下载器 v1.1.0') Text('ESJ下载器 v1.0.0')
.fontSize(FontSize.sub) .fontSize(FontSize.sub)
.fontColor($r('app.color.font_pri')) .fontColor($r('app.color.font_pri'))
Text('ESJZone 书源由 esj.py 移植;轻之国度书源由用户脚本「LK EPUB 导出(PC 版)」移植,各书源的抓取与输出选项保持与原脚本一致。') Text('由 esj.py(ESJZone 小说抓取脚本)移植:目录结构分析、章节净化、繁简转换、EPUB/TXT 打包逻辑与原脚本保持一致。繁简词典来自 OpenCC(Apache-2.0 / opencc-data)。')
.fontSize(FontSize.cap) .fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter')) .fontColor($r('app.color.font_ter'))
Text('请仅将本工具用于个人备份与学习,尊重原作者版权。') Text('请仅将本工具用于个人备份与学习,尊重原作者版权;下载期间请保持应用前台运行。')
.fontSize(FontSize.cap) .fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter')) .fontColor($r('app.color.font_ter'))
} }
+8 -1
View File
@@ -4,7 +4,10 @@ import { TaskInfo, ChapterNode, NodeDataSource, LogLine } from '../model/TaskMod
import { NodeStatus, TaskStatus, Dim, FontSize, HDS_MATERIAL, InsetKey, Insets } from '../common/Theme'; import { NodeStatus, TaskStatus, Dim, FontSize, HDS_MATERIAL, InsetKey, Insets } from '../common/Theme';
import { EmptyView, SymIcon, FloatingToolbar, ToolbarAction } from './Widgets'; import { EmptyView, SymIcon, FloatingToolbar, ToolbarAction } from './Widgets';
/** 任务详情:单书模式展示章节树,批量模式展示书籍进度,可展开运行日志。 */ /**
* 任务详情:单书模式展示章节树状态,批量模式展示每本书进度;含实时日志。
* HdsNavDestination 沉浸光感标题栏 + 底部悬浮工具栏承载页面操作。
*/
@Component @Component
export struct TaskDetailPage { export struct TaskDetailPage {
@Consume pathStack: NavPathStack; @Consume pathStack: NavPathStack;
@@ -182,6 +185,7 @@ export struct TaskDetailPage {
} else { } else {
Scroll(this.scroller) { Scroll(this.scroller) {
Column({ space: Dim.cardGap }) { Column({ space: Dim.cardGap }) {
// 总览卡片
Column({ space: 12 }) { Column({ space: 12 }) {
Row({ space: 16 }) { Row({ space: 16 }) {
Stack() { Stack() {
@@ -240,6 +244,7 @@ export struct TaskDetailPage {
.backgroundColor($r('app.color.card_bg')) .backgroundColor($r('app.color.card_bg'))
if (this.mode === 'book') { if (this.mode === 'book') {
// 章节列表
Column() { Column() {
Text(`章节 (${this.totalCh})`) Text(`章节 (${this.totalCh})`)
.fontSize(FontSize.sub) .fontSize(FontSize.sub)
@@ -264,9 +269,11 @@ export struct TaskDetailPage {
.backgroundColor($r('app.color.card_bg')) .backgroundColor($r('app.color.card_bg'))
.clip(true) .clip(true)
} else { } else {
// 批量:书籍列表
this.bookListCard() this.bookListCard()
} }
// 日志(由悬浮工具栏展开 / 收起)
if (this.showLog) { if (this.showLog) {
Column({ space: 8 }) { Column({ space: 8 }) {
Text('运行日志') Text('运行日志')
-43
View File
@@ -1,6 +1,5 @@
import { httpGetText, httpGetBinary, sniffImageExt } from '../net/HttpUtil'; import { httpGetText, httpGetBinary, sniffImageExt } from '../net/HttpUtil';
import { parseChapterContent } from '../core/EsjCore'; import { parseChapterContent } from '../core/EsjCore';
import { fetchChapterLines, LkApiCfg } from '../core/LkCore';
import { sha256Hash32 } from './HashUtil'; import { sha256Hash32 } from './HashUtil';
/** /**
@@ -62,11 +61,6 @@ export async function fetchImageJob(args: FetchImageArgs): Promise<FetchImageRes
const r: FetchImageResult = { ok: false, ext: '', hash: '', data: new ArrayBuffer(0), error: resp.error }; const r: FetchImageResult = { ok: false, ext: '', hash: '', data: new ArrayBuffer(0), error: resp.error };
return r; 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); const ext = sniffImageExt(resp.data, resp.contentType);
if (ext.length === 0 || resp.data.byteLength === 0) { if (ext.length === 0 || resp.data.byteLength === 0) {
const r2: FetchImageResult = { ok: false, ext: '', hash: '', data: new ArrayBuffer(0), error: '无法识别的图片类型: ' + resp.contentType }; const r2: FetchImageResult = { ok: false, ext: '', hash: '', data: new ArrayBuffer(0), error: '无法识别的图片类型: ' + resp.contentType };
@@ -76,40 +70,3 @@ export async function fetchImageJob(args: FetchImageArgs): Promise<FetchImageRes
const r3: FetchImageResult = { ok: true, ext: ext, hash: hash, data: resp.data, error: '' }; const r3: FetchImageResult = { ok: true, ext: ext, hash: hash, data: resp.data, error: '' };
return r3; return r3;
} }
export interface FetchLkChapterArgs {
bookId: string;
chapterId: string;
cookie: string;
securityKey: string;
timeoutMs: number;
retry: number;
}
export interface FetchLkChapterResult {
ok: boolean;
status: string; // ok | locked | error
lines: string[];
heads: boolean[]; // 行是否来自 h1-h3 标题(长文拆分用)
noConv: boolean[]; // 行是否位于 pre/code 内(繁简转换跳过)
error: string;
}
@Concurrent
export async function fetchLkChapterJob(args: FetchLkChapterArgs): Promise<FetchLkChapterResult> {
const cfg: LkApiCfg = {
cookie: args.cookie, securityKey: args.securityKey,
timeoutMs: args.timeoutMs, retry: args.retry
};
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, noConv: parsed.noConv, error: parsed.error
};
return r;
} catch (e) {
const r2: FetchLkChapterResult = { ok: false, status: 'error', lines: [], heads: [], noConv: [], error: (e as Error).message };
return r2;
}
}
+1 -3
View File
@@ -53,9 +53,7 @@
{ "scheme": "https", "host": "www.esjzone.cc" }, { "scheme": "https", "host": "www.esjzone.cc" },
{ "scheme": "https", "host": "www.esjzone.one" }, { "scheme": "https", "host": "www.esjzone.one" },
{ "scheme": "https", "host": "esjzone.cc" }, { "scheme": "https", "host": "esjzone.cc" },
{ "scheme": "https", "host": "esjzone.one" }, { "scheme": "https", "host": "esjzone.one" }
{ "scheme": "https", "host": "www.lightnovel.fun" },
{ "scheme": "https", "host": "lightnovel.fun" }
] ]
} }
] ]
Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 KiB

After

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 130 KiB

-2
View File
@@ -1,2 +0,0 @@
{
}
@@ -1,35 +0,0 @@
import { hilog } from '@kit.PerformanceAnalysisKit';
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
export default function abilityTest() {
describe('ActsAbilityTest', () => {
// Defines a test suite. Two parameters are supported: test suite name and test suite function.
beforeAll(() => {
// Presets an action, which is performed only once before all test cases of the test suite start.
// This API supports only one parameter: preset action function.
})
beforeEach(() => {
// Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function.
})
afterEach(() => {
// Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function.
})
afterAll(() => {
// Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function.
})
it('assertContain', 0, () => {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
hilog.info(0x0000, 'testTag', '%{public}s', 'it begin');
let a = 'abc';
let b = 'b';
// Defines a variety of assertion methods, which are used to declare expected boolean conditions.
expect(a).assertContain(b);
expect(a).assertEqual(a);
})
})
}
@@ -1,5 +0,0 @@
import abilityTest from './Ability.test';
export default function testsuite() {
abilityTest();
}
-12
View File
@@ -1,12 +0,0 @@
{
"module": {
"name": "entry_test",
"type": "feature",
"deviceTypes": [
"phone",
"tablet"
],
"deliveryWithInstall": true,
"installationFree": false
}
}
-5
View File
@@ -1,5 +0,0 @@
import localUnitTest from './LocalUnit.test';
export default function testsuite() {
localUnitTest();
}
-33
View File
@@ -1,33 +0,0 @@
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
export default function localUnitTest() {
describe('localUnitTest', () => {
// Defines a test suite. Two parameters are supported: test suite name and test suite function.
beforeAll(() => {
// Presets an action, which is performed only once before all test cases of the test suite start.
// This API supports only one parameter: preset action function.
});
beforeEach(() => {
// Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function.
});
afterEach(() => {
// Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function.
});
afterAll(() => {
// Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function.
});
it('assertContain', 0, () => {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
let a = 'abc';
let b = 'b';
// Defines a variety of assertion methods, which are used to declare expected boolean conditions.
expect(a).assertContain(b);
expect(a).assertEqual(a);
});
});
}
-28
View File
@@ -1,28 +0,0 @@
{
"meta": {
"stableOrder": true,
"enableUnifiedLockfile": false
},
"lockfileVersion": 3,
"ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.",
"specifiers": {
"@ohos/hamock@1.0.0": "@ohos/hamock@1.0.0",
"@ohos/hypium@1.0.25": "@ohos/hypium@1.0.25"
},
"packages": {
"@ohos/hamock@1.0.0": {
"name": "@ohos/hamock",
"version": "1.0.0",
"integrity": "sha512-K6lDPYc6VkKe6ZBNQa9aoG+ZZMiwqfcR/7yAVFSUGIuOAhPvCJAo9+t1fZnpe0dBRBPxj2bxPPbKh69VuyAtDg==",
"resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/hamock/-/hamock-1.0.0.har",
"registryType": "ohpm"
},
"@ohos/hypium@1.0.25": {
"name": "@ohos/hypium",
"version": "1.0.25",
"integrity": "sha512-l6uO2pjl8HyEKdekLqQt7tUpWbDqX/42zoAzkagtUVZAW9jT6lMvbe54MVjoLxq/RwQGygRvi6j4GpypSMFSHw==",
"resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/hypium/-/hypium-1.0.25.har",
"registryType": "ohpm"
}
}
}