feat: 实现 LK/ESJ 双书源小说下载器主体

- 下载/书库/设置三页签 UI(HdsNavigation + HdsTabs,沉浸式避让)
- core: LkCore/EsjCore 双书源抓取、HtmlParser、EpubWriter/ZipWriter EPUB 导出
- OpenCC 简繁转换(rawfile 内置词库)
- model: TaskManager/LibraryStore/Config/Draft;worker: 后台任务
- 支持浏览器通过 esjzone/lightnovel 链接唤起(viewData intent)
- 应用更名 ESJ下载器,bundleName 改为 com.esj.downloader
This commit is contained in:
R-HUA
2026-10-11 18:09:36 +08:00
parent 047a06bd19
commit 5a731e80b6
41 changed files with 66306 additions and 76 deletions
+2 -1
View File
@@ -9,4 +9,5 @@
/.clang-format
/.clang-tidy
**/.test
/.appanalyzer
/.appanalyzer
/.work
+1 -2
View File
@@ -1,10 +1,9 @@
{
"app": {
"bundleName": "com.download.helper",
"bundleName": "com.esj.downloader",
"vendor": "example",
"versionCode": 1000000,
"versionName": "1.0.0",
"buildVersion": "1",
"icon": "$media:layered_image",
"label": "$string:app_name"
}
+2 -2
View File
@@ -2,7 +2,7 @@
"string": [
{
"name": "app_name",
"value": "DownloadHelper"
"value": "ESJ下载器"
}
]
}
}
File diff suppressed because one or more lines are too long
+46 -32
View File
@@ -1,42 +1,56 @@
{
"app": {
"signingConfigs": [],
"products": [
app: {
signingConfigs: [
{
"name": "default",
"signingConfig": "default",
"targetSdkVersion": "26.0.0",
"compatibleSdkVersion": "6.1.1(24)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"strictMode": {
"caseSensitiveCheck": true,
"useNormalizedOHMUrl": true
}
}
}
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',
},
},
],
"buildModeSet": [
products: [
{
"name": "debug",
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"
}
]
name: 'release',
},
],
},
"modules": [
modules: [
{
"name": "entry",
"srcPath": "./entry",
"targets": [
name: 'entry',
srcPath: './entry',
targets: [
{
"name": "default",
"applyToProducts": [
"default"
]
}
]
}
]
name: 'default',
applyToProducts: [
'default',
],
},
],
},
],
}
+4 -3
View File
@@ -1,6 +1,7 @@
// @ts-nocheck – Template file, only used when copied into a project directory
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins: [] /* Custom plugin to extend the functionality of Hvigor. */
}
system: hapTasks /* Built-in plugin of Hvigor. It cannot be modified. */,
plugins: [] /* Custom plugin to extend the functionality of Hvigor. */,
};
-3
View File
@@ -1,8 +1,5 @@
# Define project specific obfuscation rules here.
# You can include the obfuscation configuration files in the current module's build-profile.json5.
#
# For more details, see
# https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/source-obfuscation
# Obfuscation options:
# -disable-obfuscation: disable all obfuscations
+103
View File
@@ -0,0 +1,103 @@
import { common, Want } from '@kit.AbilityKit';
export type HubListener = (data?: string) => void;
/**
* 全局单例:持有 UIAbilityContext、事件总线、外部传入的分享/打开链接。
*/
export class AppHub {
private static context: common.UIAbilityContext | null = null;
private static listeners: Map<string, HubListener[]> = new Map();
private static latestLink: string = '';
private static linkSeq: number = 0;
static init(ctx: common.UIAbilityContext): void {
AppHub.context = ctx;
}
static uiContext(): common.UIAbilityContext {
if (AppHub.context === null) {
throw new Error('AppHub not initialized');
}
return AppHub.context;
}
static hasContext(): boolean {
return AppHub.context !== null;
}
static on(event: string, fn: HubListener): void {
const arr = AppHub.listeners.get(event);
if (arr) {
arr.push(fn);
} else {
AppHub.listeners.set(event, [fn]);
}
}
static off(event: string, fn: HubListener): void {
const arr = AppHub.listeners.get(event);
if (!arr) {
return;
}
const idx = arr.indexOf(fn);
if (idx >= 0) {
arr.splice(idx, 1);
}
}
static emit(event: string, data?: string): void {
const arr = AppHub.listeners.get(event);
if (!arr) {
return;
}
for (const fn of arr) {
try {
fn(data);
} catch (e) {
// 单个监听器异常不影响其它监听器
}
}
}
/**
* 处理来自浏览器“打开方式”/系统分享面板传入的书籍链接(ESJZone / 轻之国度)。
*/
static handleWant(w: Want): void {
let url: string = '';
if (w.uri && w.uri.length > 0) {
url = w.uri;
}
if (url === '' && w.parameters) {
const params = w.parameters as Record<string, Object>;
const keys = Object.keys(params);
for (const k of keys) {
const v = params[k];
if (typeof v === 'string' && v.startsWith('http') && isBookSiteUrl(v)) {
url = v;
break;
}
}
}
if (url !== '' && isBookSiteUrl(url)) {
AppHub.latestLink = url;
AppHub.linkSeq += 1;
AppHub.emit('link', url);
}
}
static consumeLink(): string {
const u = AppHub.latestLink;
AppHub.latestLink = '';
return u;
}
static linkSeqValue(): number {
return AppHub.linkSeq;
}
}
/** 是否为受支持书源的链接(esjzone / lightnovel 域名) */
function isBookSiteUrl(v: string): boolean {
return v.indexOf('esjzone') >= 0 || v.indexOf('lightnovel') >= 0;
}
+87
View File
@@ -0,0 +1,87 @@
import { hdsMaterial, SystemMaterialParams } from '@kit.UIDesignKit';
import { uiMaterial } from '@kit.ArkUI';
/**
* 布局与视觉常量,遵循 HarmonyOS Design 8vp 网格与圆角规范。
*/
export class Dim {
static readonly pagePad: number = 16;
static readonly cardPad: number = 16;
static readonly cardGap: number = 12;
static readonly cardRadius: number = 20;
static readonly innerRadius: number = 12;
static readonly btnHeight: number = 40;
static readonly btnRadius: number = 20;
static readonly dividerH: number = 0.5;
/** HDS 标题栏 MINI 模式高度 */
static readonly titleBarH: number = 56;
/** 悬浮底部页签 / 悬浮工具栏高度 */
static readonly floatBarH: number = 56;
/** 悬浮栏距导航条的最小间距(无导航条时使用) */
static readonly floatBarGap: number = 16;
/** 渐变蒙层较悬浮栏顶边高出的距离(设计规范:底部 16vp) */
static readonly floatMaskExtra: number = 16;
}
export class FontSize {
static readonly titleL: number = 26;
static readonly title: number = 20;
static readonly body: number = 16;
static readonly sub: number = 14;
static readonly cap: number = 12;
}
/** AppStorage 中的窗口避让区高度(单位 vp),由 EntryAbility 监听 avoidAreaChange 写入 */
export class InsetKey {
static readonly TOP: string = 'insetTopVp';
static readonly BOTTOM: string = 'insetBottomVp';
}
/** 内容区沉浸到状态栏/导航条下方后,需要为顶部标题栏与底部悬浮栏预留的空间 */
export class Insets {
static contentTop(topInset: number): number {
return topInset + Dim.titleBarH + 8;
}
/** 悬浮栏底边距:有导航条时与其等高,否则使用固定间距 */
static floatBarBottom(bottomInset: number): number {
return bottomInset > 0 ? bottomInset : Dim.floatBarGap;
}
static contentBottom(bottomInset: number): number {
return Insets.floatBarBottom(bottomInset) + Dim.floatBarH + Dim.floatMaskExtra + 8;
}
}
/** 沉浸光感:HDS 组件材质,交由系统根据算力与用户档位自适应 */
export const HDS_MATERIAL: SystemMaterialParams = {
materialType: hdsMaterial.MaterialType.ADAPTIVE,
materialLevel: hdsMaterial.MaterialLevel.ADAPTIVE
};
/** 沉浸光感:底部悬浮组件推荐 THIN 档位(设计规范“沉浸光感-场景规范”) */
export function floatingBarMaterial(): uiMaterial.ImmersiveMaterial {
return new uiMaterial.ImmersiveMaterial({
style: uiMaterial.ImmersiveStyle.THIN,
lightEffect: { color: undefined }
});
}
/** 任务 / 章节状态 */
export class NodeStatus {
static readonly PENDING: string = 'pending';
static readonly DOWNLOADING: string = 'downloading';
static readonly DONE: string = 'done';
static readonly FAILED: string = 'failed';
static readonly LOCKED: string = 'locked';
static readonly SKIPPED: string = 'skipped';
}
export class TaskStatus {
static readonly QUEUED: string = 'queued';
static readonly RUNNING: string = 'running';
static readonly DONE: string = 'done';
static readonly DONE_WITH_FAIL: string = 'doneWithFail';
static readonly FAILED: string = 'failed';
static readonly CANCELLED: string = 'cancelled';
}
+322
View File
@@ -0,0 +1,322 @@
import { fileIo as fs } from '@kit.CoreFileKit';
import { util } from '@kit.ArkTS';
import { ZipWriter } from './ZipWriter';
import { VolumeChapterNode, isImgPlaceholder, imgPlaceholderUrl } from './EsjCore';
/**
* EPUB 3 打包:等价原脚本 ebooklib 的产出(含封面、简介、嵌套目录 NCX/Nav、图片、esjLastChangeDate 元数据)。
* 章节片段文件由任务阶段写入磁盘(内容为转换后的 <p> 行与图片占位行),
* 打包时流式读取,内存占用平稳。
*/
export interface EpubImageItem {
url: string; // 原始图片 URL(占位符 key)
fileName: string; // Image_{hash}{ext}
contentType: string;
filePath: string; // 磁盘绝对路径
}
export interface EpubNodeItem {
node: VolumeChapterNode;
fileName: string; // 包内文件名 novel_3.xhtml / volume_1.xhtml
fragmentPath: string; // 章节片段 html 路径(卷为 '')
}
export interface EpubBuildInput {
outPath: string;
bookName: string;
author: string;
changeDate: string;
cover?: EpubImageItem; // 封面图片
descFragmentPath?: string; // 简介片段
nodes: EpubNodeItem[];
images: EpubImageItem[];
}
export function escapeXml(s: string): string {
let out = s.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, '');
out = out.replace(/&/g, '&amp;');
out = out.replace(/</g, '&lt;');
out = out.replace(/>/g, '&gt;');
out = out.replace(/"/g, '&quot;');
out = out.replace(/'/g, '&apos;');
return out;
}
function contentTypeOf(ext: string): string {
if (ext === '.png') {
return 'image/png';
}
if (ext === '.gif') {
return 'image/gif';
}
if (ext === '.bmp') {
return 'image/bmp';
}
if (ext === '.webp') {
return 'image/webp';
}
return 'image/jpeg';
}
function readFileBytes(path: string): ArrayBuffer {
const st = fs.statSync(path);
const buf = new ArrayBuffer(st.size);
const f = fs.openSync(path, fs.OpenMode.READ_ONLY);
try {
let off = 0;
while (off < st.size) {
const read = fs.readSync(f.fd, buf, { offset: off, length: st.size - off });
if (read <= 0) {
break;
}
off += read;
}
} finally {
fs.closeSync(f);
}
return buf;
}
interface TocEntry {
href: string;
title: string;
children: TocEntry[];
}
interface Counter {
n: number;
}
function readFragmentLines(path: string, images: Map<string, EpubImageItem>): string {
const raw = readFileBytes(path);
const text = util.TextDecoder.create('utf-8').decodeToString(new Uint8Array(raw));
// 替换图片占位行
const lines = text.split('\n');
const out: string[] = [];
for (const line of lines) {
const t = line.trim();
if (t.length === 0) {
continue;
}
if (isImgPlaceholder(t)) {
const url = imgPlaceholderUrl(t);
const img = images.get(url);
if (img === undefined) {
out.push('<p>下载失败:' + escapeXml(url) + '</p>');
} else {
out.push('<img src=\'' + img.fileName + '\'/><br/>');
}
} else {
out.push(t);
}
}
return out.join('\n');
}
function buildTocTree(nodes: EpubNodeItem[]): TocEntry[] {
const roots: TocEntry[] = [];
const byValue: Map<number, TocEntry> = new Map();
for (const item of nodes) {
const entry: TocEntry = {
href: item.fileName,
title: item.node.title,
children: []
};
byValue.set(item.node.value, entry);
if (item.node.fatherValue >= 0) {
const father = byValue.get(item.node.fatherValue);
if (father !== undefined) {
father.children.push(entry);
continue;
}
}
roots.push(entry);
}
return roots;
}
function tocOl(entries: TocEntry[], sb: string[]): void {
sb.push('<ol>');
for (const e of entries) {
if (e.children.length > 0) {
if (e.href.length > 0) {
sb.push('<li><a href="' + escapeXml(e.href) + '">' + escapeXml(e.title) + '</a>');
} else {
sb.push('<li><span>' + escapeXml(e.title) + '</span>');
}
tocOl(e.children, sb);
sb.push('</li>');
} else {
sb.push('<li><a href="' + escapeXml(e.href) + '">' + escapeXml(e.title) + '</a></li>');
}
}
sb.push('</ol>');
}
function ncxPoints(entries: TocEntry[], playOrder: Counter, depth: number, sb: string[]): void {
for (const e of entries) {
const id = 'navPoint-' + playOrder.n;
playOrder.n++;
sb.push('<navPoint id="' + id + '" playOrder="' + playOrder.n + '">');
sb.push('<navLabel><text>' + escapeXml(e.title) + '</text></navLabel>');
sb.push('<content src="' + escapeXml(e.href) + '"/>');
if (e.children.length > 0) {
ncxPoints(e.children, playOrder, depth + 1, sb);
}
sb.push('</navPoint>');
}
}
function wrapXhtml(title: string, body: string): string {
return '<?xml version="1.0" encoding="UTF-8"?>\n' +
'<!DOCTYPE html>\n' +
'<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" xml:lang="zh" lang="zh">\n' +
'<head><title>' + escapeXml(title) + '</title>' +
'<style type="text/css">body{margin:1em;} p{text-indent:0;margin:0.5em 0;} img{max-width:100%;}</style>' +
'</head>\n<body>\n' + body + '\n</body>\n</html>';
}
/**
* 打包 EPUB。返回 true 表示成功。
*/
export function buildEpub(input: EpubBuildInput): boolean {
const zip = new ZipWriter();
zip.open(input.outPath);
try {
const images: Map<string, EpubImageItem> = new Map();
for (const img of input.images) {
images.set(img.url, img);
}
const uuid = util.generateRandomUUID(true);
// mimetype 必须第一个且不压缩
zip.addEntry('mimetype', stringBytes('application/epub+zip'));
zip.addEntry('META-INF/container.xml', stringBytes(
'<?xml version="1.0" encoding="UTF-8"?>\n' +
'<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">\n' +
'<rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles>\n' +
'</container>'));
// 封面
let coverImgName = '';
let coverExt = '';
if (input.cover !== undefined) {
coverImgName = input.cover.fileName;
coverExt = input.cover.fileName.substring(input.cover.fileName.lastIndexOf('.'));
zip.addEntry('OEBPS/' + input.cover.fileName, readFileBytes(input.cover.filePath));
zip.addEntry('OEBPS/cover.xhtml', stringBytes(wrapXhtml('封面',
'<div style="text-align:center;"><img src=\'' + input.cover.fileName + '\'/></div>')));
}
// 简介
let hasDesc = false;
if (input.descFragmentPath !== undefined) {
const descBody = readFragmentLines(input.descFragmentPath, images);
if (descBody.trim().length > 0) {
hasDesc = true;
zip.addEntry('OEBPS/description.xhtml', stringBytes(wrapXhtml('简介', descBody)));
}
}
// 章节
for (let i = 0; i < input.nodes.length; i++) {
const item = input.nodes[i];
const body = item.node.isChapter
? readFragmentLines(item.fragmentPath, images)
: '<h' + Math.min(6, Math.max(1, item.node.level + 1)) + '>' + escapeXml(item.node.title) + '</h' +
Math.min(6, Math.max(1, item.node.level + 1)) + '>';
zip.addEntry('OEBPS/' + item.fileName, stringBytes(wrapXhtml(item.node.title, body)));
}
// 图片
for (const img of input.images) {
if (input.cover !== undefined && img.fileName === input.cover.fileName) {
continue;
}
zip.addEntry('OEBPS/' + img.fileName, readFileBytes(img.filePath));
}
// 目录树
const tocTree = buildTocTree(input.nodes);
const navSb: string[] = [];
tocOl(tocTree, navSb);
const navBody = '<nav epub:type="toc" id="toc"><h1>目录</h1>' + navSb.join('\n') + '</nav>';
zip.addEntry('OEBPS/nav.xhtml', stringBytes(wrapXhtml('目录', navBody)));
const ncxSb: string[] = [];
const playOrder: Counter = { n: 1 };
ncxPoints(tocTree, playOrder, 0, ncxSb);
zip.addEntry('OEBPS/toc.ncx', stringBytes(
'<?xml version="1.0" encoding="UTF-8"?>\n' +
'<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1">\n' +
'<head><meta name="dtb:uid" content="urn:uuid:' + uuid + '"/><meta name="dtb:depth" content="1"/>' +
'<meta name="dtb:totalPageCount" content="0"/><meta name="dtb:maxPageNumber" content="0"/></head>\n' +
'<docTitle><text>' + escapeXml(input.bookName) + '</text></docTitle>\n' +
'<navMap>' + ncxSb.join('\n') + '</navMap>\n</ncx>'));
// content.opf
const manifestSb: string[] = [];
const spineSb: string[] = [];
manifestSb.push('<item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/>');
manifestSb.push('<item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/>');
spineSb.push('<itemref idref="nav"/>');
if (input.cover !== undefined) {
manifestSb.push('<item id="cover-image" href="' + input.cover.fileName +
'" media-type="' + contentTypeOf(coverExt) + '" properties="cover-image"/>');
manifestSb.push('<item id="coverHtml" href="cover.xhtml" media-type="application/xhtml+xml"/>');
spineSb.push('<itemref idref="coverHtml" linear="yes"/>');
}
if (hasDesc) {
manifestSb.push('<item id="description" href="description.xhtml" media-type="application/xhtml+xml"/>');
spineSb.push('<itemref idref="description" linear="yes"/>');
}
for (let i = 0; i < input.nodes.length; i++) {
const item = input.nodes[i];
const id = item.fileName.replace(/\.xhtml$/, '').replace(/\./g, '_');
manifestSb.push('<item id="' + id + '" href="' + escapeXml(item.fileName) + '" media-type="application/xhtml+xml"/>');
spineSb.push('<itemref idref="' + id + '" linear="yes"/>');
}
for (let i = 0; i < input.images.length; i++) {
const img = input.images[i];
if (input.cover !== undefined && img.fileName === input.cover.fileName) {
continue;
}
manifestSb.push('<item id="img' + i + '" href="' + escapeXml(img.fileName) +
'" media-type="' + contentTypeOf(img.fileName.substring(img.fileName.lastIndexOf('.'))) + '"/>');
}
const now = new Date();
const modified = now.getFullYear() + '-' + pad2(now.getMonth() + 1) + '-' + pad2(now.getDate()) +
'T' + pad2(now.getHours()) + ':' + pad2(now.getMinutes()) + ':' + pad2(now.getSeconds()) + 'Z';
const opf =
'<?xml version="1.0" encoding="UTF-8"?>\n' +
'<package xmlns="http://www.idpf.org/2007/opf" unique-identifier="bookid" version="3.0">\n' +
'<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">\n' +
'<dc:identifier id="bookid">urn:uuid:' + uuid + '</dc:identifier>\n' +
'<dc:title>' + escapeXml(input.bookName) + '</dc:title>\n' +
'<dc:creator>' + escapeXml(input.author) + '</dc:creator>\n' +
'<dc:language>zh</dc:language>\n' +
'<meta property="dcterms:modified">' + modified + '</meta>\n' +
'<meta name="esjLastChangeDate" content="' + escapeXml(input.changeDate) + '"/>\n' +
'</metadata>\n' +
'<manifest>\n' + manifestSb.join('\n') + '\n</manifest>\n' +
'<spine toc="ncx">\n' + spineSb.join('\n') + '\n</spine>\n' +
'</package>';
zip.addEntry('OEBPS/content.opf', stringBytes(opf));
zip.finalize();
return true;
} finally {
zip.close();
}
}
function pad2(v: number): string {
return v < 10 ? '0' + v : '' + v;
}
function stringBytes(s: string): ArrayBuffer {
const u8 = util.TextEncoder.create().encodeInto(s);
return u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength);
}
+374
View File
@@ -0,0 +1,374 @@
import { HtmlNode, parseHtml, findFirst, findAll, getText, getTextSimple, isBlankText,
byTag, byTagClass, byTagId, byTagClassExact } from './HtmlParser';
/**
* ESJZone 站点逻辑移植自原 Python 脚本 esj.py:
* 详情页解析、目录结构分析(contentsAnalysis)、章节内容净化(htmlSimplified)、
* 列表页解析、文件名清理。
*/
export interface VolumeChapterNode {
value: number;
level: number;
fatherValue: number;
isVolume: boolean;
isChapter: boolean;
title: string;
url: string;
}
export interface DetailInfo {
ok: boolean;
bookName: string;
author: string;
changeDate: string;
coverUrl: string;
descLines: string[];
nodes: VolumeChapterNode[];
depth: number;
error: string;
}
export interface ChapterContent {
status: string; // ok | locked | error
lines: string[];
error: string;
}
export interface ListPageInfo {
title: string;
totalCount: number;
bookUrls: string[];
}
const IMG_MARK_PREFIX = '[[ESJIMG:';
const IMG_MARK_SUFFIX = ']]';
export function imgPlaceholder(url: string): string {
return IMG_MARK_PREFIX + url + IMG_MARK_SUFFIX;
}
export function isImgPlaceholder(line: string): boolean {
return line.startsWith(IMG_MARK_PREFIX) && line.endsWith(IMG_MARK_SUFFIX);
}
export function imgPlaceholderUrl(line: string): string {
return line.substring(IMG_MARK_PREFIX.length, line.length - IMG_MARK_SUFFIX.length);
}
export function urlHandler(url: string, baseUrl: string): string {
if (url.length === 0) {
return '';
}
const trimmed = url.trim();
if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
return trimmed;
}
if (trimmed.startsWith('//')) {
return 'https:' + trimmed;
}
return joinUrl(baseUrl, trimmed);
}
function joinUrl(base: string, relative: string): string {
let b = base;
while (b.endsWith('/')) {
b = b.substring(0, b.length - 1);
}
let r = relative;
while (r.startsWith('/')) {
r = r.substring(1);
}
return b + '/' + r;
}
export function hostOf(url: string): string {
const m = /^https?:\/\/([^/?#]+)/.exec(url);
return m === null ? '' : m[1].toLowerCase();
}
/** 清理文件名中不允许的字符(对齐脚本 re.sub(r'[\\/:*?"<>|]', '', name)) */
export function sanitizeFileName(name: string): string {
return name.replace(/[\\/:*?"<>|]/g, '').replace(/\s+$/g, '');
}
export function clipName(name: string, maxLen: number): string {
if (name.length > maxLen) {
return name.substring(0, maxLen - 1) + '…';
}
return name;
}
/**
* 提取带超链接标注的文本行:等价脚本在 <a> 前插入 "[href]" 文本节点后 get_text 的效果。
*/
function extractTextLines(node: HtmlNode, marked: Set<HtmlNode>): string[] {
const parts: string[] = [];
const walk = (nd: HtmlNode): void => {
if (nd.isText) {
parts.push(nd.text);
return;
}
if (nd.tag === 'a' && !marked.has(nd)) {
marked.add(nd);
const href = nd.attrs['href'] ?? '';
if (href.length > 0) {
parts.push('[' + href + ']');
}
}
for (const c of nd.children) {
walk(c);
}
};
walk(node);
const out: string[] = [];
for (const p of parts) {
const t = p.trim();
if (t.length > 0) {
out.push(t);
}
}
return out;
}
/**
* 等价脚本的 htmlSimplified:把章节 DOM 净化为纯文本行 + 图片占位行。
* convert 为繁简转换函数(可为 null 表示不转换)。
*/
export function simplifyLines(children: HtmlNode[], convert: ((s: string) => string) | null): string[] {
const out: string[] = [];
const marked: Set<HtmlNode> = new Set();
const pushText = (s: string): void => {
const lines = s.split('\n');
for (let line of lines) {
line = line.trim();
if (line.length === 0) {
continue;
}
out.push(convert !== null ? convert(line) : line);
}
};
const walk = (nodes: HtmlNode[]): void => {
for (const child of nodes) {
if (child.isText) {
pushText(child.text);
continue;
}
if (child.tag === 'img') {
const src = child.attrs['src'] ?? '';
if (src.length > 0) {
out.push(imgPlaceholder(src));
}
continue;
}
const hasImg = findFirst(child, byTag('img')) !== null;
if (hasImg) {
walk(child.children);
continue;
}
const lines = extractTextLines(child, marked);
for (const line of lines) {
out.push(convert !== null ? convert(line) : line);
}
}
};
walk(children);
return out;
}
/**
* 等价脚本的 contentsAnalysis:分析目录结构(details 卷 / p 卷 / a 章节)。
* 返回目录最大深度。
*/
export function contentsAnalysis(children: HtmlNode[], list: VolumeChapterNode[],
levelValue: number, fatherValue: number,
convert: ((s: string) => string) | null): number {
let depth = levelValue;
let idx = 0;
const conv = (s: string): string => convert !== null ? convert(s) : s;
while (idx < children.length) {
const child = children[idx];
if (child.isText || (child.tag === 'p' && isBlankText(getTextSimple(child)))) {
idx++;
continue;
}
const node: VolumeChapterNode =
{ value: list.length, level: levelValue, fatherValue: fatherValue, isVolume: false, isChapter: false, title: '', url: '' };
list.push(node);
if (child.tag === 'details') {
const summary = findFirst(child, byTag('summary'));
node.title = summary !== null ? conv(getTextSimple(summary)) : '';
if (isBlankText(node.title)) {
node.title = '卷';
}
node.isVolume = true;
const inner = summary !== null ? child.children.slice(1) : child.children;
const d = contentsAnalysis(inner, list, levelValue + 1, node.value, convert);
if (d > depth) {
depth = d;
}
} else if (child.tag === 'p') {
node.title = conv(getTextSimple(child));
node.isVolume = true;
let nextP = idx + 1;
while (nextP < children.length) {
const nc = children[nextP];
if (!nc.isText && nc.tag === 'p' && !isBlankText(getTextSimple(nc))) {
break;
}
nextP++;
}
const d = contentsAnalysis(children.slice(idx + 1, nextP), list, levelValue + 1, node.value, convert);
if (d > depth) {
depth = d;
}
idx = nextP;
continue;
} else if (child.tag === 'a') {
node.title = conv(getTextSimple(child));
node.url = child.attrs['href'] ?? '';
node.isChapter = true;
}
idx++;
}
return depth;
}
/**
* 解析书籍详情页(等价脚本 downloadOneBook 的信息获取部分)。
*/
export function analyzeDetail(html: string, baseUrl: string,
convert: ((s: string) => string) | null): DetailInfo {
const soup = parseHtml(html);
const h2 = findFirst(soup, byTag('h2'));
if (h2 === null) {
const info: DetailInfo = {
ok: false, bookName: '', author: '', changeDate: '', coverUrl: '', descLines: [],
nodes: [], depth: 0,
error: '未获取到书籍信息:Cookie 无效/未登录,或站点域名与 Cookie 不匹配(esjzone.cc 与 esjzone.one 的 Cookie 不通用),也可能被站点重定向。'
};
return info;
}
const conv = (s: string): string => convert !== null ? convert(s) : s;
let bookName = sanitizeFileName(conv(getTextSimple(h2)));
let author = '';
const detailUl = findFirst(soup, byTagClass('ul', 'book-detail'));
if (detailUl !== null) {
const a = findFirst(detailUl, byTag('a'));
if (a !== null) {
author = sanitizeFileName(conv(getTextSimple(a)));
}
}
bookName = clipName(bookName, 48);
author = clipName(author, 16);
let changeDate = '';
if (detailUl !== null) {
const dates = getTextSimple(detailUl).match(/\d{4}-\d{2}-\d{2}/g);
if (dates !== null && dates.length > 0) {
changeDate = dates[dates.length - 1];
}
}
let coverUrl = '';
const gallery = findFirst(soup, byTagClass('div', 'product-gallery'));
if (gallery !== null) {
const img = findFirst(gallery, byTag('img'));
if (img !== null) {
const src = img.attrs['src'] ?? '';
if (src.length > 0) {
coverUrl = urlHandler(src, baseUrl);
}
}
}
let descLines: string[] = [];
const descDiv = findFirst(soup, byTagClass('div', 'description'));
if (descDiv !== null) {
descLines = simplifyLines(descDiv.children, convert);
}
const nodes: VolumeChapterNode[] = [];
let depth = 0;
const chapterList = findFirst(soup, byTagId('div', 'chapterList'));
if (chapterList !== null) {
depth = contentsAnalysis(chapterList.children, nodes, 0, -1, convert);
}
const info: DetailInfo = {
ok: true, bookName: bookName, author: author, changeDate: changeDate,
coverUrl: coverUrl, descLines: descLines, nodes: nodes, depth: depth, error: ''
};
return info;
}
/**
* 解析章节页(等价脚本 novelCharacterListNode.downloadCharacter 的章节部分)。
*/
export function parseChapterContent(html: string): ChapterContent {
const soup = parseHtml(html);
const contentDiv = findFirst(soup, byTagClassExact('div', 'forum-content mt-3'));
if (contentDiv === null) {
// 兜底:类名顺序可能不同
const alt = findAll(soup, byTagClass('div', 'forum-content'));
if (alt.length === 0) {
const r: ChapterContent = { status: 'error', lines: [], error: '未找到章节正文(页面结构变化或下载失败)' };
return r;
}
return parseContentDiv(alt[0]);
}
return parseContentDiv(contentDiv);
}
function parseContentDiv(div: HtmlNode): ChapterContent {
const pwBtn = findFirst(div, (n: HtmlNode): boolean =>
!n.isText && n.tag === 'button' && n.classes.indexOf('btn-send-pw') >= 0);
if (pwBtn !== null) {
const r: ChapterContent = { status: 'locked', lines: ['本章节需要密码,已跳过'], error: '' };
return r;
}
const lines = simplifyLines(div.children, null);
if (lines.length === 0) {
const r: ChapterContent = { status: 'ok', lines: [], error: '' };
return r;
}
const r2: ChapterContent = { status: 'ok', lines: lines, error: '' };
return r2;
}
/**
* 解析列表页:书籍总数(script 中的 total: N)与本页书籍链接。
*/
export function parseListPage(html: string, baseUrl: string): ListPageInfo {
const soup = parseHtml(html);
let title = '';
const h1 = findFirst(soup, byTag('h1'));
if (h1 !== null) {
title = getTextSimple(h1).trim();
}
let totalCount = 0;
const scripts = findAll(soup, byTag('script'));
for (const sc of scripts) {
const t = getTextSimple(sc);
const m = /total:\s*(\d+)/.exec(t);
if (m !== null) {
totalCount = parseInt(m[1], 10);
break;
}
}
const bookUrls: string[] = [];
const cards = findAll(soup, byTagClass('div', 'col-xs-6'));
for (const card of cards) {
if (card.classes.indexOf('col-lg-3') < 0 || card.classes.indexOf('col-md-4') < 0) {
continue;
}
const a = findFirst(card, byTag('a'));
if (a !== null) {
const href = a.attrs['href'] ?? '';
if (href.length > 0) {
bookUrls.push(urlHandler(href, baseUrl));
}
}
}
const info: ListPageInfo = { title: title, totalCount: totalCount, bookUrls: bookUrls };
return info;
}
+333
View File
@@ -0,0 +1,333 @@
/**
* 轻量 HTML 解析器:将 HTML 字符串解析为 DOM 树。
* 容错策略与 Python 的 html.parser(BeautifulSoup 默认解析器)一致:
* 不做自动补全,只按出现顺序嵌套,遇到能匹配的结束标签则回退栈。
*/
export interface HtmlNode {
isText: boolean;
tag: string; // 小写标签名;文本节点为 ''
attrs: Record<string, string>;
classes: string[];
id: string;
children: HtmlNode[];
text: string; // 仅文本节点使用
}
const VOID_TAGS: string[] =
['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr'];
const RAW_TAGS: string[] = ['script', 'style'];
export function textNode(t: string): HtmlNode {
return { isText: true, tag: '', attrs: {}, classes: [], id: '', children: [], text: t };
}
export function elementNode(tag: string): HtmlNode {
return { isText: false, tag: tag, attrs: {}, classes: [], id: '', children: [], text: '' };
}
function decodeEntities(s: string): string {
if (s.indexOf('&') < 0) {
return s;
}
let out = s;
out = out.replace(/&nbsp;/g, '\u00A0');
out = out.replace(/&lt;/g, '<');
out = out.replace(/&gt;/g, '>');
out = out.replace(/&quot;/g, '"');
out = out.replace(/&apos;/g, '\'');
out = out.replace(/&#39;/g, '\'');
out = out.replace(/&amp;/g, '&');
// 数字实体
out = out.replace(/&#(\d+);/g, (m: string, p1: string): string => {
const code = parseInt(p1, 10);
return code > 0 && code < 0x110000 ? String.fromCodePoint(code) : m;
});
out = out.replace(/&#x([0-9a-fA-F]+);/g, (m: string, p1: string): string => {
const code = parseInt(p1, 16);
return code > 0 && code < 0x110000 ? String.fromCodePoint(code) : m;
});
return out;
}
/** 找到标签的结束 '>',跳过引号内的内容 */
function findTagEnd(s: string, start: number): number {
let i = start;
const n = s.length;
while (i < n) {
const c = s.charAt(i);
if (c === '"') {
const q = s.indexOf('"', i + 1);
if (q < 0) {
return -1;
}
i = q + 1;
} else if (c === '\'') {
const q = s.indexOf('\'', i + 1);
if (q < 0) {
return -1;
}
i = q + 1;
} else if (c === '>') {
return i;
} else {
i++;
}
}
return -1;
}
function parseAttributes(src: string, node: HtmlNode): void {
let i = 0;
const n = src.length;
// 跳过标签名
while (i < n && !/\s/.test(src.charAt(i))) {
i++;
}
while (i < n) {
while (i < n && /\s/.test(src.charAt(i))) {
i++;
}
if (i >= n) {
break;
}
// 属性名
let nameStart = i;
while (i < n && !/\s/.test(src.charAt(i)) && src.charAt(i) !== '=') {
i++;
}
const name = src.substring(nameStart, i).toLowerCase();
while (i < n && /\s/.test(src.charAt(i))) {
i++;
}
let value = '';
if (i < n && src.charAt(i) === '=') {
i++;
while (i < n && /\s/.test(src.charAt(i))) {
i++;
}
if (i < n && (src.charAt(i) === '"' || src.charAt(i) === '\'')) {
const quote = src.charAt(i);
i++;
const vStart = i;
while (i < n && src.charAt(i) !== quote) {
i++;
}
value = src.substring(vStart, i);
i++; // 跳过结束引号
} else {
const vStart = i;
while (i < n && !/\s/.test(src.charAt(i))) {
i++;
}
value = src.substring(vStart, i);
}
}
if (name.length > 0) {
node.attrs[name] = decodeEntities(value);
}
}
const cls = node.attrs['class'];
if (cls) {
node.classes = cls.split(/\s+/).filter((t: string): boolean => t.length > 0);
}
node.id = node.attrs['id'] ?? '';
}
export function parseHtml(input: string): HtmlNode {
const root = elementNode('#root');
const stack: HtmlNode[] = [root];
const n = input.length;
let i = 0;
const top = (): HtmlNode => stack[stack.length - 1];
const appendText = (t: string): void => {
if (t.length === 0) {
return;
}
top().children.push(textNode(decodeEntities(t)));
};
while (i < n) {
const lt = input.indexOf('<', i);
if (lt < 0) {
appendText(input.substring(i));
break;
}
if (lt > i) {
appendText(input.substring(i, lt));
}
// 注释
if (input.startsWith('<!--', lt)) {
const end = input.indexOf('-->', lt + 4);
i = end < 0 ? n : end + 3;
continue;
}
// DOCTYPE / 处理指令
if (input.startsWith('<!', lt) || input.startsWith('<?', lt)) {
const end = input.indexOf('>', lt);
i = end < 0 ? n : end + 1;
continue;
}
// 结束标签
if (input.startsWith('</', lt)) {
const end = input.indexOf('>', lt);
const name = end < 0 ? '' : input.substring(lt + 2, end).trim().toLowerCase();
if (name.length > 0) {
for (let s = stack.length - 1; s > 0; s--) {
if (stack[s].tag === name) {
stack.length = s; // 回退到该标签处
break;
}
}
}
i = end < 0 ? n : end + 1;
continue;
}
// 开始标签
const end = findTagEnd(input, lt);
if (end < 0) {
appendText(input.substring(lt));
break;
}
let tagSrc = input.substring(lt + 1, end);
let selfClosing = false;
if (tagSrc.endsWith('/')) {
selfClosing = true;
tagSrc = tagSrc.substring(0, tagSrc.length - 1);
}
const wsMatch = /\s/.exec(tagSrc);
let tagName: string;
let attrPart: string;
if (wsMatch === null) {
tagName = tagSrc.toLowerCase();
attrPart = '';
} else {
const wsIdx = wsMatch.index;
tagName = tagSrc.substring(0, wsIdx).toLowerCase();
attrPart = tagSrc.substring(wsIdx);
}
const node = elementNode(tagName);
parseAttributes(attrPart, node);
top().children.push(node);
const isRaw = RAW_TAGS.indexOf(tagName) >= 0;
if (isRaw) {
// script/style: 原样读取内容直到对应结束标签
const closeSearch = input.toLowerCase().indexOf('</' + tagName, end + 1);
if (closeSearch < 0) {
node.children.push(textNode(input.substring(end + 1)));
i = n;
} else {
node.children.push(textNode(input.substring(end + 1, closeSearch)));
const closeEnd = input.indexOf('>', closeSearch);
i = closeEnd < 0 ? n : closeEnd + 1;
}
continue;
}
if (selfClosing || VOID_TAGS.indexOf(tagName) >= 0) {
i = end + 1;
continue;
}
stack.push(node);
i = end + 1;
}
return root;
}
// ---------- 查询辅助(对齐 BeautifulSoup 常用用法) ----------
function hasClassToken(node: HtmlNode, token: string): boolean {
return node.classes.indexOf(token) >= 0;
}
export type NodePredicate = (n: HtmlNode) => boolean;
export function byTag(tag: string): NodePredicate {
return (n: HtmlNode): boolean => !n.isText && n.tag === tag;
}
export function byTagClass(tag: string, cls: string): NodePredicate {
return (n: HtmlNode): boolean => !n.isText && n.tag === tag && hasClassToken(n, cls);
}
export function byTagId(tag: string, id: string): NodePredicate {
return (n: HtmlNode): boolean => !n.isText && n.tag === tag && n.id === id;
}
export function byTagClassExact(tag: string, cls: string): NodePredicate {
return (n: HtmlNode): boolean => !n.isText && n.tag === tag && n.attrs['class'] === cls;
}
function findAllIn(node: HtmlNode, pred: NodePredicate, out: HtmlNode[]): void {
for (const c of node.children) {
if (pred(c)) {
out.push(c);
}
if (!c.isText) {
findAllIn(c, pred, out);
}
}
}
/** 深度优先查找全部匹配节点(等价 find_all) */
export function findAll(node: HtmlNode, pred: NodePredicate): HtmlNode[] {
const out: HtmlNode[] = [];
findAllIn(node, pred, out);
return out;
}
/** 深度优先查找第一个匹配节点(等价 find) */
export function findFirst(node: HtmlNode, pred: NodePredicate): HtmlNode | null {
for (const c of node.children) {
if (pred(c)) {
return c;
}
if (!c.isText) {
const r = findFirst(c, pred);
if (r !== null) {
return r;
}
}
}
return null;
}
/** 判断节点内是否包含匹配后代 */
export function containsNode(node: HtmlNode, pred: NodePredicate): boolean {
return findFirst(node, pred) !== null;
}
export function isBlankText(s: string): boolean {
return s.replace(/\s/g, '').length === 0;
}
/**
* 等价 BeautifulSoup 的 get_text(separator, strip):
* 按文档顺序收集所有文本串,strip 时逐个 trim 并丢弃空白串。
*/
export function getText(node: HtmlNode, separator: string, strip: boolean): string {
const parts: string[] = [];
const collect = (nd: HtmlNode): void => {
if (nd.isText) {
let t = nd.text;
if (strip) {
t = t.trim();
if (t.length === 0) {
return;
}
}
parts.push(t);
return;
}
for (const c of nd.children) {
collect(c);
}
};
collect(node);
return parts.join(separator);
}
/** 等价 .text:无分隔符拼接 */
export function getTextSimple(node: HtmlNode): string {
return getText(node, '', false);
}
+784
View File
@@ -0,0 +1,784 @@
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[];
}
/** 章节解析结果:文本行 + 是否来自 h1-h6 标题(供长文拆分使用) */
export interface LkLineContent {
lines: string[];
heads: boolean[];
}
export interface LkChapterParse {
status: string; // ok | locked | error
lines: string[];
heads: 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;
}
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']);
const HEAD_TAGS: Set<string> = new Set<string>(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
const BLOCK_TAGS: Set<string> = new Set<string>(['p', 'div', 'table', 'thead', 'tbody', 'tfoot', 'tr',
'td', 'th', 'caption', 'ul', 'ol', 'li', 'blockquote', 'pre', 'figure', 'figcaption', 'section',
'article', 'aside', 'header', 'footer', 'hr', 'details', 'summary']);
const RES_RE = /\[res\]([\s\S]*?)\[\/res\]/gi;
class LineBuilder {
lines: string[] = [];
heads: boolean[] = [];
private cur: string = '';
private curHead: boolean = false;
flush(): void {
const t = this.cur.trim();
if (t.length > 0) {
this.lines.push(t);
this.heads.push(this.curHead);
}
this.cur = '';
this.curHead = false;
}
emitPlaceholder(url: string): void {
this.flush();
this.lines.push(imgPlaceholder(url));
this.heads.push(false);
}
emitLine(text: string): void {
this.flush();
this.lines.push(text);
this.heads.push(false);
}
append(text: string): void {
this.cur += text;
}
markHead(): void {
this.curHead = true;
}
}
/** 文本节点:处理 [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 (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 };
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 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);
continue;
}
lines.push(t);
heads.push(false);
}
const r: LkLineContent = { lines: lines, heads: heads };
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: [], 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, error: '' };
return r2;
}
} else if (text.trim().length > 0) {
const c2 = bbcodeToLines(text, reader);
if (c2.lines.length > 0) {
const r3: LkChapterParse = { status: 'ok', lines: c2.lines, heads: c2.heads, error: '' };
return r3;
}
}
const r4: LkChapterParse = { status: 'error', lines: [], heads: [], 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);
}
// ---------------- 目录抓取 ----------------
/** 抓取书籍详情 + 全部卷章目录(分页),产出与 ESJ 同构的目录树 */
export async function fetchCatalog(bookId: string, cfg: LkApiCfg,
convert: ((s: string) => string) | null): 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 nodes: VolumeChapterNode[] = [];
for (let vi = 0; vi < volumes.length; vi++) {
const v = volumes[vi];
const volumeId = jStr(v, 'volume_id');
let vTitle = conv(jStr(v, 'title')).trim();
if (vTitle.length === 0) {
vTitle = '卷' + (vi + 1);
}
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
};
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;
}
+142
View File
@@ -0,0 +1,142 @@
import { util } from '@kit.ArkTS';
import { common } from '@kit.AbilityKit';
/**
* OpenCC 繁简转换(等价原脚本 opencc.OpenCC('t2s.json'/'s2t.json'))。
* 词典文件来自 opencc-data(Apache-2.0),打包于 rawfile/opencc。
* 转换策略:短语词典最长匹配优先,其次单字映射,与 OpenCC 配置链一致。
*/
export class OpenCC {
private phrases: Map<string, string> = new Map();
private chars: Map<string, string> = new Map();
private maxPhraseLen: number = 0;
private loadedMode: string = '';
static instance: OpenCC | null = null;
static loadedMode: string = '';
isLoaded(mode: string): boolean {
return this.loadedMode === mode;
}
/**
* 从 rawfile 加载词典。mode: 't2s' | 's2t'
*/
async load(mode: string, ctx: common.Context): Promise<void> {
if (this.loadedMode === mode) {
return;
}
this.phrases.clear();
this.chars.clear();
this.maxPhraseLen = 0;
const files: string[] = mode === 't2s'
? ['opencc/TSPhrases.txt', 'opencc/TSCharacters.txt']
: ['opencc/STPhrases.txt', 'opencc/STCharacters.txt'];
const rm = ctx.resourceManager;
for (let i = 0; i < files.length; i++) {
const data = await rm.getRawFileContent(files[i]);
const decoder = util.TextDecoder.create('utf-8');
const text = decoder.decodeToString(data);
const isPhrase = i === 0;
this.parseDict(text, isPhrase);
}
this.loadedMode = mode;
OpenCC.loadedMode = mode;
}
private parseDict(text: string, isPhrase: boolean): void {
const lines = text.split('\n');
for (const raw of lines) {
const line = raw.trim();
if (line.length === 0 || line.startsWith('#')) {
continue;
}
const tabIdx = line.indexOf('\t');
if (tabIdx <= 0) {
continue;
}
const key = line.substring(0, tabIdx);
const rest = line.substring(tabIdx + 1);
const tab2 = rest.indexOf('\t');
const value = tab2 >= 0 ? rest.substring(0, tab2) : rest;
if (key.length === 0 || value.length === 0) {
continue;
}
if (isPhrase) {
this.phrases.set(key, value);
if (key.length > this.maxPhraseLen) {
this.maxPhraseLen = key.length;
}
} else {
if (!this.chars.has(key)) {
this.chars.set(key, value);
}
}
}
}
dictSize(): number {
return this.phrases.size + this.chars.size;
}
convert(s: string): string {
if (this.loadedMode.length === 0 || s.length === 0) {
return s;
}
// 快速跳过:无 CJK 字符直接返回
let hasCJK = false;
for (let k = 0; k < s.length; k++) {
const c = s.charCodeAt(k);
if (c >= 0x3400 && c <= 0x9FFF) {
hasCJK = true;
break;
}
}
if (!hasCJK) {
return s;
}
const out: string[] = [];
const len = s.length;
let i = 0;
while (i < len) {
let matched = false;
if (this.maxPhraseLen >= 2) {
const maxK = Math.min(this.maxPhraseLen, len - i);
for (let k = maxK; k >= 2; k--) {
const sub = s.substring(i, i + k);
const v = this.phrases.get(sub);
if (v !== undefined) {
out.push(v);
i += k;
matched = true;
break;
}
}
}
if (matched) {
continue;
}
const ch = s.charAt(i);
const cv = this.chars.get(ch);
if (cv !== undefined) {
out.push(cv);
} else {
out.push(ch);
}
i++;
}
return out.join('');
}
static async getConverter(mode: string, ctx: common.Context): Promise<OpenCC | null> {
if (mode !== 't2s' && mode !== 's2t') {
return null;
}
if (OpenCC.instance === null || !OpenCC.instance.isLoaded(mode)) {
const cc = new OpenCC();
await cc.load(mode, ctx);
OpenCC.instance = cc;
}
return OpenCC.instance;
}
}
+151
View File
@@ -0,0 +1,151 @@
import { fileIo as fs } from '@kit.CoreFileKit';
import { util } from '@kit.ArkTS';
/**
* 极简 ZIP 写入器(仅 STORE 不压缩)。
* EPUB 规范只要求 mimetype 必须为第一个且不压缩的条目,其余条目允许 STORE,
* 图片本身已是压缩格式,文本体量小,此方案换取跨端可靠性与零依赖。
* 边写盘边记录中心目录,内存占用平稳。
*/
interface CdEntry {
nameBytes: Uint8Array;
crc: number;
size: number;
offset: number;
}
const CRC_TABLE: number[] = (() => {
const table: number[] = [];
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) {
if ((c & 1) !== 0) {
c = 0xedb88320 ^ (c >>> 1);
} else {
c = c >>> 1;
}
}
table[n] = c >>> 0;
}
return table;
})();
export function crc32(data: Uint8Array): number {
let c = 0xffffffff;
for (let i = 0; i < data.length; i++) {
c = CRC_TABLE[(c ^ data[i]) & 0xff] ^ (c >>> 8);
}
return (c ^ 0xffffffff) >>> 0;
}
function utf8Bytes(s: string): Uint8Array {
return util.TextEncoder.create().encodeInto(s);
}
export class ZipWriter {
private fd: number = -1;
private offset: number = 0;
private entries: CdEntry[] = [];
isOpen(): boolean {
return this.fd >= 0;
}
open(path: string): void {
const f = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE | fs.OpenMode.TRUNC);
this.fd = f.fd;
this.offset = 0;
this.entries = [];
}
private writeAll(buf: ArrayBuffer): void {
const n = fs.writeSync(this.fd, buf);
if (n !== buf.byteLength) {
throw new Error('zip write failed');
}
this.offset += n;
}
/**
* 添加一个条目(STORE)。data 为完整内容字节。
*/
addEntry(name: string, data: ArrayBuffer): void {
const nameBytes = utf8Bytes(name);
const content = new Uint8Array(data);
const crc = crc32(content);
const localHeader = new ArrayBuffer(30 + nameBytes.length);
const dv = new DataView(localHeader);
dv.setUint32(0, 0x04034b50, true);
dv.setUint16(4, 20, true); // version needed
dv.setUint16(6, 0x0800, true); // UTF-8 flag
dv.setUint16(8, 0, true); // method STORE
const now = new Date();
dv.setUint16(10, dosTime(now), true);
dv.setUint16(12, dosDate(now), true);
dv.setUint32(14, crc, true);
dv.setUint32(18, content.length, true);
dv.setUint32(22, content.length, true);
dv.setUint16(26, nameBytes.length, true);
dv.setUint16(28, 0, true);
new Uint8Array(localHeader, 30).set(nameBytes);
this.writeAll(localHeader);
this.writeAll(data);
const entry: CdEntry = { nameBytes: nameBytes, crc: crc, size: content.length, offset: this.offset - content.length - (30 + nameBytes.length) };
this.entries.push(entry);
}
finalize(): void {
const cdStart = this.offset;
for (const e of this.entries) {
const cd = new ArrayBuffer(46 + e.nameBytes.length);
const dv = new DataView(cd);
dv.setUint32(0, 0x02014b50, true);
dv.setUint16(4, 20, true); // version made by
dv.setUint16(6, 20, true); // version needed
dv.setUint16(8, 0x0800, true);
dv.setUint16(10, 0, true);
dv.setUint16(12, 0, true); // time
dv.setUint16(14, 0, true); // date
dv.setUint32(16, e.crc, true);
dv.setUint32(20, e.size, true);
dv.setUint32(24, e.size, true);
dv.setUint16(28, e.nameBytes.length, true);
dv.setUint16(30, 0, true);
dv.setUint16(32, 0, true);
dv.setUint16(34, 0, true);
dv.setUint16(36, 0, true);
dv.setUint32(38, 0, true);
dv.setUint32(42, e.offset, true);
new Uint8Array(cd, 46).set(e.nameBytes);
this.writeAll(cd);
}
const cdSize = this.offset - cdStart;
const eocd = new ArrayBuffer(22);
const dv2 = new DataView(eocd);
dv2.setUint32(0, 0x06054b50, true);
dv2.setUint16(4, 0, true);
dv2.setUint16(6, 0, true);
dv2.setUint16(8, this.entries.length, true);
dv2.setUint16(10, this.entries.length, true);
dv2.setUint32(12, cdSize, true);
dv2.setUint32(16, cdStart, true);
dv2.setUint16(20, 0, true);
this.writeAll(eocd);
}
close(): void {
if (this.fd >= 0) {
fs.closeSync(this.fd);
this.fd = -1;
}
}
}
function dosTime(d: Date): number {
return (d.getHours() << 11) | (d.getMinutes() << 5) | (Math.floor(d.getSeconds() / 2) & 0x1f);
}
function dosDate(d: Date): number {
return ((d.getFullYear() - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate();
}
@@ -1,20 +1,43 @@
import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
import { AppHub } from '../common/AppHub';
import { InsetKey } from '../common/Theme';
import { ConfigStore } from '../model/Config';
import { LibraryStore } from '../model/LibraryStore';
const DOMAIN = 0x0000;
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
try {
this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
} catch (err) {
hilog.error(DOMAIN, 'testTag', 'Failed to set colorMode. Cause: %{public}s', JSON.stringify(err));
}
AppHub.init(this.context);
ConfigStore.init(this.context).then((): Promise<void> => {
return LibraryStore.init();
}).then((): void => {
AppHub.emit('config', '');
}).catch((e: Error): void => {
hilog.error(DOMAIN, 'testTag', 'init failed %{public}s', e.message);
});
// 冷启动时处理外部传入的 esjzone 链接(浏览器“打开方式”/分享)
AppHub.handleWant(want);
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
}
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
// 热启动时接收新链接
AppHub.handleWant(want);
}
onDestroy(): void {
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy');
}
onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Index', (err) => {
@@ -23,27 +46,39 @@ export default class EntryAbility extends UIAbility {
return;
}
hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
this.trackAvoidArea(windowStage);
});
}
/** 页面内容沉浸到状态栏与导航条下方,记录两者高度(vp)供标题栏 / 悬浮栏避让 */
private trackAvoidArea(windowStage: window.WindowStage): void {
try {
this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
} catch (err) {
hilog.error(DOMAIN, 'testTag', 'Failed to set colorMode. Cause: %{public}s', JSON.stringify(err));
const win = windowStage.getMainWindowSync();
const ui = win.getUIContext();
const update = (): void => {
const sys = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
const nav = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
AppStorage.setOrCreate(InsetKey.TOP, ui.px2vp(sys.topRect.height));
AppStorage.setOrCreate(InsetKey.BOTTOM, ui.px2vp(nav.bottomRect.height));
};
update();
win.on('avoidAreaChange', (_opt: window.AvoidAreaOptions): void => {
update();
});
} catch (e) {
hilog.error(DOMAIN, 'testTag', 'track avoid area failed %{public}s', JSON.stringify(e));
}
}
onWindowStageDestroy(): void {
// Main window is destroyed, release UI related resources
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
}
onForeground(): void {
// Ability has brought to foreground
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
}
onBackground(): void {
// Ability has back to background
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground');
}
}
}
@@ -1,3 +1,18 @@
/*
* Copyright (c) 2026 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
+124
View File
@@ -0,0 +1,124 @@
import { preferences } from '@kit.ArkData';
import { common } from '@kit.AbilityKit';
/**
* 应用配置:对应原脚本开头全部参数,全部页面可配置并持久化。
* - siteUrl -> base_url
* - cookie -> esj.txt 第一行(含 ews_key / ews_token)
* - lkCookie -> 轻之国度(lightnovel.fun)Cookie,含 lk_security_key
* - convertMode -> opencc t2s / s2t / none
* - threadCount -> threadNum(并发数)
* - retryCount -> retrying stop_max_attempt_number
* - timeoutSec -> requests timeout
* - downloadImages / downloadCover / outputEpub / outputTxt -> 输出控制
*/
export const CONVERT_T2S: string = 't2s';
export const CONVERT_S2T: string = 's2t';
export const CONVERT_NONE: string = 'none';
export interface AppSettings {
siteUrl: string;
cookie: string;
lkCookie: string;
convertMode: string;
threadCount: number;
retryCount: number;
timeoutSec: number;
downloadImages: boolean;
downloadCover: boolean;
outputEpub: boolean;
outputTxt: boolean;
}
export function defaultSettings(): AppSettings {
const s: AppSettings = {
siteUrl: 'https://www.esjzone.cc/',
cookie: '',
lkCookie: '',
convertMode: CONVERT_T2S,
threadCount: 2,
retryCount: 3,
timeoutSec: 25,
downloadImages: true,
downloadCover: true,
outputEpub: true,
outputTxt: true
};
return s;
}
export class ConfigStore {
private static prefs: preferences.Preferences | null = null;
private static cache: AppSettings | null = null;
static async init(ctx: common.Context): Promise<void> {
ConfigStore.prefs = await preferences.getPreferences(ctx, 'esj_config');
const raw = ConfigStore.prefs.getSync('settings_json', '') as string;
const base = defaultSettings();
if (raw.length > 0) {
try {
const obj = JSON.parse(raw) as Record<string, Object>;
base.siteUrl = strOf(obj, 'siteUrl', base.siteUrl);
base.cookie = strOf(obj, 'cookie', base.cookie);
base.lkCookie = strOf(obj, 'lkCookie', base.lkCookie);
base.convertMode = strOf(obj, 'convertMode', base.convertMode);
base.threadCount = numOf(obj, 'threadCount', base.threadCount);
base.retryCount = numOf(obj, 'retryCount', base.retryCount);
base.timeoutSec = numOf(obj, 'timeoutSec', base.timeoutSec);
base.downloadImages = boolOf(obj, 'downloadImages', base.downloadImages);
base.downloadCover = boolOf(obj, 'downloadCover', base.downloadCover);
base.outputEpub = boolOf(obj, 'outputEpub', base.outputEpub);
base.outputTxt = boolOf(obj, 'outputTxt', base.outputTxt);
} catch (e) {
// 配置损坏时使用默认值
}
}
ConfigStore.cache = base;
}
static get(): AppSettings {
if (ConfigStore.cache === null) {
ConfigStore.cache = defaultSettings();
}
return ConfigStore.cache;
}
static async save(s: AppSettings): Promise<void> {
ConfigStore.cache = s;
if (ConfigStore.prefs === null) {
return;
}
ConfigStore.prefs.putSync('settings_json', JSON.stringify(s));
await ConfigStore.prefs.flush();
}
/** cookie 是否包含关键登录字段 */
static cookieOk(cookie: string): boolean {
return cookie.indexOf('ews_key') >= 0 && cookie.indexOf('ews_token') >= 0;
}
/** 轻之国度 Cookie 是否包含安全密钥(公开内容可不配置) */
static lkCookieOk(cookie: string): boolean {
return cookie.indexOf('lk_security_key') >= 0;
}
/** 清理 cookie 字符串:去掉换行、首尾空格 */
static cleanCookie(cookie: string): string {
return cookie.replace(/\r?\n/g, '').trim();
}
}
function strOf(obj: Record<string, Object>, key: string, def: string): string {
const v = obj[key];
return typeof v === 'string' ? v : def;
}
function numOf(obj: Record<string, Object>, key: string, def: number): number {
const v = obj[key];
return typeof v === 'number' ? v : def;
}
function boolOf(obj: Record<string, Object>, key: string, def: boolean): boolean {
const v = obj[key];
return typeof v === 'boolean' ? v : def;
}
+50
View File
@@ -0,0 +1,50 @@
import { TocPreviewNode } from './TaskModel';
/**
* 单本下载的"选章 + 自定义标题"草稿。
* 与目标 URL 绑定;URL 变化时自动清空,避免串书。
*/
export class DownloadDraft {
static url: string = '';
static customTitle: string = '';
static chapterFilter: number[] = []; // 空 = 全部章节
static nodes: TocPreviewNode[] = []; // 已抓取的目录缓存
static bookName: string = '';
static author: string = '';
static reset(): void {
DownloadDraft.url = '';
DownloadDraft.customTitle = '';
DownloadDraft.chapterFilter = [];
DownloadDraft.nodes = [];
DownloadDraft.bookName = '';
DownloadDraft.author = '';
}
/** 目标 URL 变化时清空草稿(避免不同书籍沿用旧的选章/标题) */
static onUrlChanged(newUrl: string): void {
if (DownloadDraft.url === newUrl) {
return;
}
DownloadDraft.reset();
DownloadDraft.url = newUrl;
}
static hasCacheFor(url: string): boolean {
return DownloadDraft.url === url && DownloadDraft.nodes.length > 0;
}
static filterActiveFor(url: string): boolean {
return DownloadDraft.url === url && DownloadDraft.chapterFilter.length > 0;
}
static chapterTotal(): number {
let n = 0;
for (const nd of DownloadDraft.nodes) {
if (nd.isChapter) {
n++;
}
}
return n;
}
}
+159
View File
@@ -0,0 +1,159 @@
import { preferences } from '@kit.ArkData';
import { fileIo as fs } from '@kit.CoreFileKit';
import { AppHub } from '../common/AppHub';
/**
* 书库记录:已生成书籍的持久化索引。
*/
export interface BookRecord {
id: string; // 原书下载 = 详情页链接;选章/自定义标题下载 = 链接#《自定义名》作者
url: string; // 详情页链接
name: string;
author: string;
date: string; // 更新日期
baseName: string; // 不含扩展名的文件名(《书名》作者)
epubPath: string;
txtPath: string;
chapters: number;
createdAt: number;
}
export class LibraryStore {
private static prefs: preferences.Preferences | null = null;
private static records: BookRecord[] = [];
static async init(): Promise<void> {
LibraryStore.prefs = await preferences.getPreferences(AppHub.uiContext(), 'esj_library');
const raw = LibraryStore.prefs.getSync('library_json', '') as string;
LibraryStore.records = [];
if (raw.length > 0) {
try {
const arr = JSON.parse(raw) as BookRecord[];
for (const r of arr) {
LibraryStore.records.push(r);
}
} catch (e) {
LibraryStore.records = [];
}
}
ensureLibraryDir();
}
static list(): BookRecord[] {
return LibraryStore.records.slice().sort((a: BookRecord, b: BookRecord): number => b.createdAt - a.createdAt);
}
static save(): void {
if (LibraryStore.prefs === null) {
return;
}
LibraryStore.prefs.putSync('library_json', JSON.stringify(LibraryStore.records));
LibraryStore.prefs.flush();
}
static findByUrl(url: string): BookRecord | null {
// 仅匹配"原书下载"记录(id === 链接),批量模式的日期去重使用
for (const r of LibraryStore.records) {
if (r.id === url) {
return r;
}
}
return null;
}
static findById(id: string): BookRecord | null {
for (const r of LibraryStore.records) {
if (r.id === id) {
return r;
}
}
return null;
}
/** 同一 id 重新下载时替换记录并清理旧文件;不同 id(如选章自定义名)各自独立保留 */
static upsert(record: BookRecord): void {
const idx = LibraryStore.records.findIndex((r: BookRecord): boolean => r.id === record.id);
if (idx >= 0) {
const old = LibraryStore.records[idx];
if (old.baseName !== record.baseName) {
// 文件名变了:清理旧文件,避免残留
deleteQuietly(old.epubPath);
deleteQuietly(old.txtPath);
}
LibraryStore.records.splice(idx, 1);
}
LibraryStore.records.push(record);
LibraryStore.save();
}
static remove(id: string): void {
const idx = LibraryStore.records.findIndex((r: BookRecord): boolean => r.id === id);
if (idx >= 0) {
const old = LibraryStore.records[idx];
deleteQuietly(old.epubPath);
deleteQuietly(old.txtPath);
LibraryStore.records.splice(idx, 1);
LibraryStore.save();
}
}
/**
* 为书籍生成不冲突的基础文件名。
* 同一 id(原书刷新 / 同名选章重下)复用旧文件名以便覆盖;
* 不同内容若与磁盘文件重名则追加序号。
*/
static uniqueName(base: string, id: string): string {
const exist = LibraryStore.findById(id);
if (exist !== null && exist.baseName.length > 0) {
return exist.baseName;
}
const dir = AppHub.uiContext().filesDir + '/library';
let name = base;
let n = 2;
while (LibraryStore.existsFile(dir + '/' + name + '.epub') || LibraryStore.existsFile(dir + '/' + name + '.txt')) {
name = base + `(${n})`;
n++;
if (n > 50) {
break;
}
}
return name;
}
static existsFile(path: string): boolean {
try {
return fs.accessSync(path);
} catch (e) {
return false;
}
}
}
function deleteQuietly(path: string): void {
if (path.length === 0) {
return;
}
try {
if (fs.accessSync(path)) {
fs.unlinkSync(path);
}
} catch (e) {
// 忽略
}
}
export function ensureLibraryDir(): void {
const dir = AppHub.uiContext().filesDir + '/library';
try {
if (!fs.accessSync(dir)) {
fs.mkdirSync(dir, true);
}
} catch (e) {
try {
fs.mkdirSync(dir, true);
} catch (e2) {
// 忽略
}
}
}
File diff suppressed because it is too large Load Diff
+205
View File
@@ -0,0 +1,205 @@
import { VolumeChapterNode } from '../core/EsjCore';
import { NodeStatus, TaskStatus } from '../common/Theme';
/**
* 任务数据模型 + UI 数据源。
*/
export interface LogLine {
time: string;
level: string; // info | warn | error | ok
msg: string;
}
/** LK 整卷长文拆分出的片段(多于 1 段时在打包前展开为独立章节节点) */
export interface ChapterPart {
title: string;
lines: string[];
}
export class ChapterNode {
node: VolumeChapterNode;
status: string = NodeStatus.PENDING;
lines: string[] = []; // 转换后的文本行(含图片占位行)
error: string = '';
fragmentPath: string = '';
parts: ChapterPart[] = []; // 非空且 >1 段时表示长文已拆分
doneTick: number = 0; // 用于驱动 UI 刷新
constructor(node: VolumeChapterNode) {
this.node = node;
}
touch(): void {
this.doneTick++;
}
}
export interface BookProgress {
url: string;
name: string;
author: string;
date: string;
status: string;
doneCh: number;
totalCh: number;
message: string;
}
/** 章节选择页用的目录预览节点(纯数据,可跨线程返回) */
export interface TocPreviewNode {
value: number;
level: number;
fatherValue: number;
isVolume: boolean;
isChapter: boolean;
title: string;
}
export interface TocPreviewResult {
ok: boolean;
error: string;
nodes: TocPreviewNode[];
bookName: string;
author: string;
}
export class TaskInfo {
id: string = '';
mode: string = 'book'; // book | list
source: string = 'esj'; // esj | lk(书源,由链接域名决定)
url: string = '';
status: string = TaskStatus.QUEUED;
bookName: string = '';
author: string = '';
changeDate: string = '';
coverUrl: string = '';
descLines: string[] = []; // 转换后的简介行(含图片占位)
phase: string = ''; // detail | list | chapters | images | build
totalChapters: number = 0;
doneChapters: number = 0;
failedChapters: number = 0;
totalImages: number = 0;
doneImages: number = 0;
currentTitle: string = '';
nodes: ChapterNode[] = [];
books: BookProgress[] = []; // 批量模式
logs: LogLine[] = [];
errorMessage: string = '';
epubPath: string = '';
txtPath: string = '';
createdAt: number = 0;
cancelRequested: boolean = false;
customTitle: string = ''; // 用户自定义 EPUB 标题(空=用原书名)
chapterFilter: number[] = []; // 选中的章节节点 value(空=全部)
activeBooksDone: number = 0;
activeBooksTotal: number = 0;
versionTick: number = 0; // 每次有变化自增,驱动界面刷新
touch(): void {
this.versionTick++;
}
addLog(level: string, msg: string): void {
const d = new Date();
const time = `${d.getHours() < 10 ? '0' : ''}${d.getHours()}:${d.getMinutes() < 10 ? '0' : ''}${d.getMinutes()}:${d.getSeconds() < 10 ? '0' : ''}${d.getSeconds()}`;
this.logs.push({ time: time, level: level, msg: msg });
if (this.logs.length > 400) {
this.logs.splice(0, this.logs.length - 400);
}
}
progressPercent(): number {
if (this.mode === 'list') {
if (this.activeBooksTotal === 0) {
return this.phase === 'list' ? 5 : 0;
}
return Math.floor(this.activeBooksDone * 100 / this.activeBooksTotal);
}
if (this.totalChapters === 0) {
return this.status === TaskStatus.DONE || this.status === TaskStatus.DONE_WITH_FAIL ? 100 : 0;
}
return Math.floor(this.doneChapters * 100 / this.totalChapters);
}
}
/** LazyForEach 数据源 */
export class NodeDataSource implements IDataSource {
private listeners: DataChangeListener[] = [];
items: ChapterNode[] = [];
setItems(items: ChapterNode[]): void {
this.items = items;
this.notifyDataReload();
}
totalCount(): number {
return this.items.length;
}
getData(index: number): ChapterNode {
return this.items[index];
}
idxOf(node: ChapterNode): number {
return this.items.indexOf(node);
}
registerDataChangeListener(listener: DataChangeListener): void {
this.listeners.push(listener);
}
unregisterDataChangeListener(listener: DataChangeListener): void {
const idx = this.listeners.indexOf(listener);
if (idx >= 0) {
this.listeners.splice(idx, 1);
}
}
notifyDataReload(): void {
for (const l of this.listeners) {
l.onDataReloaded();
}
}
notifyChangedAt(index: number): void {
for (const l of this.listeners) {
l.onDataChange(index);
}
}
}
export class TaskDataSource implements IDataSource {
private listeners: DataChangeListener[] = [];
items: TaskInfo[] = [];
setItems(items: TaskInfo[]): void {
this.items = items;
this.notifyDataReload();
}
totalCount(): number {
return this.items.length;
}
getData(index: number): TaskInfo {
return this.items[index];
}
registerDataChangeListener(listener: DataChangeListener): void {
this.listeners.push(listener);
}
unregisterDataChangeListener(listener: DataChangeListener): void {
const idx = this.listeners.indexOf(listener);
if (idx >= 0) {
this.listeners.splice(idx, 1);
}
}
notifyDataReload(): void {
for (const l of this.listeners) {
l.onDataReloaded();
}
}
}
+247
View File
@@ -0,0 +1,247 @@
import { http } from '@kit.NetworkKit';
/**
* HTTP 工具:带重试的 GET(文本/二进制),请求头对齐原脚本。
*/
export const DEFAULT_UA: string =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0';
export interface HttpResultText {
ok: boolean;
code: number;
text: string;
error: string;
}
export interface HttpResultBin {
ok: boolean;
code: number;
data: ArrayBuffer;
contentType: string;
error: string;
}
function pageHeaders(cookie: string): Record<string, string> {
const h: Record<string, string> = {
'User-Agent': DEFAULT_UA,
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'cross-site',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache'
};
if (cookie.length > 0) {
h['Cookie'] = cookie;
}
return h;
}
function imgHeaders(cookie: string): Record<string, string> {
const h: Record<string, string> = {
'User-Agent': DEFAULT_UA,
'Accept': 'image/avif,image/webp,*/*',
'Connection': 'keep-alive',
'Sec-Fetch-Dest': 'image',
'Sec-Fetch-Mode': 'no-cors',
'Sec-Fetch-Site': 'cross-site',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2'
};
if (cookie.length > 0) {
h['Cookie'] = cookie;
}
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> {
return new Promise<void>((resolve: (v: void) => void) => {
setTimeout((): void => resolve(), ms);
});
}
/**
* GET 文本页面,带重试。retry 为失败后重试次数(总尝试 = retry + 1)。
*/
export async function httpGetText(url: string, cookie: string, timeoutMs: number,
retry: number): 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.GET,
header: pageHeaders(cookie),
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;
}
/**
* 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 二进制(图片),带重试。
*/
export async function httpGetBinary(url: string, cookie: string, timeoutMs: number,
retry: number): Promise<HttpResultBin> {
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.GET,
header: imgHeaders(cookie),
expectDataType: http.HttpDataType.ARRAY_BUFFER,
usingCache: false,
connectTimeout: Math.max(5000, Math.min(timeoutMs, 20000)),
readTimeout: timeoutMs
});
const hdr = resp.header as Record<string, Object>;
const ctRaw = hdr['content-type'] ?? hdr['Content-Type'] ?? '';
const ct = ctRaw as string;
req.destroy();
if (resp.responseCode >= 200 && resp.responseCode < 300) {
const r: HttpResultBin =
{ ok: true, code: resp.responseCode, data: resp.result as ArrayBuffer, contentType: ct as string, error: '' };
return r;
}
lastErr = 'HTTP ' + resp.responseCode;
} catch (e) {
lastErr = '网络错误: ' + (e as Error).message;
try {
req.destroy();
} catch (e2) {
// 忽略销毁异常
}
}
}
const r2: HttpResultBin = { ok: false, code: 0, data: new ArrayBuffer(0), contentType: '', error: lastErr };
return r2;
}
/** 通过响应头/魔数判断图片类型,返回扩展名;无法识别返回 '' */
export function sniffImageExt(data: ArrayBuffer, contentType: string): string {
if (data.byteLength >= 4) {
const u8 = new Uint8Array(data, 0, 12);
if (u8[0] === 0xFF && u8[1] === 0xD8) {
return '.jpg';
}
if (u8[0] === 0x89 && u8[1] === 0x50 && u8[2] === 0x4E && u8[3] === 0x47) {
return '.png';
}
if (u8[0] === 0x47 && u8[1] === 0x49 && u8[2] === 0x46) {
return '.gif';
}
if (u8[0] === 0x42 && u8[1] === 0x4D) {
return '.bmp';
}
if (u8[0] === 0x52 && u8[1] === 0x49 && u8[2] === 0x46 && u8[3] === 0x46 &&
u8[8] === 0x57 && u8[9] === 0x45 && u8[10] === 0x42 && u8[11] === 0x50) {
return '.webp';
}
}
const ct = contentType.toLowerCase();
if (ct.indexOf('jpeg') >= 0) {
return '.jpg';
}
if (ct.indexOf('png') >= 0) {
return '.png';
}
if (ct.indexOf('gif') >= 0) {
return '.gif';
}
if (ct.indexOf('bmp') >= 0) {
return '.bmp';
}
if (ct.indexOf('webp') >= 0) {
return '.webp';
}
return '';
}
+98 -15
View File
@@ -1,23 +1,106 @@
import { SymbolGlyphModifier } from '@kit.ArkUI';
import {
HdsNavigation,
HdsNavigationTitleMode,
HdsTabs,
HdsTabsController,
ScrollEffectType
} from '@kit.UIDesignKit';
import { HomeView } from '../view/HomeView';
import { LibraryView } from '../view/LibraryView';
import { SettingsView } from '../view/SettingsView';
import { TaskDetailPage } from '../view/TaskDetailPage';
import { ChapterSelectPage } from '../view/ChapterSelectPage';
import { HDS_MATERIAL, InsetKey, Insets } from '../common/Theme';
const TAB_TITLES: string[] = ['下载', '书库', '设置'];
/** 应用入口:下载 / 书库 / 设置三页签,子页面经 HdsNavDestination 路由。 */
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
@State currentTab: number = 0;
@Provide pathStack: NavPathStack = new NavPathStack();
@StorageProp(InsetKey.BOTTOM) bottomInset: number = 0;
private tabsController: HdsTabsController = new HdsTabsController();
// 每个页签独立的 Scroller,标题栏只绑定当前页签,避免滚动模糊互相干扰
private scrollers: Scroller[] = [new Scroller(), new Scroller(), new Scroller()];
private tabSymbol(sym: Resource, selected: boolean): SymbolGlyphModifier {
return new SymbolGlyphModifier(sym)
.fontColor([selected ? $r('sys.color.ohos_id_color_activated') : $r('sys.color.ohos_id_color_bottom_tab_icon_off')]);
}
private tabBarStyle(sym: Resource, label: string): BottomTabBarStyle {
return new BottomTabBarStyle({ normal: this.tabSymbol(sym, false), selected: this.tabSymbol(sym, true) }, label);
}
@Builder
pagesMap(name: string) {
if (name === 'taskDetail') {
TaskDetailPage()
} else if (name === 'chapterSelect') {
ChapterSelectPage()
}
}
build() {
RelativeContainer() {
Text(this.message)
.id('HelloWorld')
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
this.message = 'Welcome';
})
HdsNavigation(this.pathStack) {
HdsTabs({ controller: this.tabsController }) {
TabContent() {
HomeView({
scroller: this.scrollers[0],
gotoSettings: (): void => {
this.tabsController.changeIndex(2);
}
})
}
.tabBar(this.tabBarStyle($r('sys.symbol.arrow_down_circle'), TAB_TITLES[0]))
TabContent() {
LibraryView({ scroller: this.scrollers[1] })
}
.tabBar(this.tabBarStyle($r('sys.symbol.book_pages_fill'), TAB_TITLES[1]))
TabContent() {
SettingsView({ scroller: this.scrollers[2] })
}
.tabBar(this.tabBarStyle($r('sys.symbol.gearshape'), TAB_TITLES[2]))
}
.vertical(false)
.barPosition(BarPosition.End)
.scrollable(false)
.barOverlap(true)
.barFloatingStyle({
barBottomMargin: Insets.floatBarBottom(this.bottomInset),
systemMaterialEffect: HDS_MATERIAL
})
.width('100%')
.height('100%')
.onChange((index: number) => {
this.currentTab = index;
})
}
.height('100%')
.navDestination(this.pagesMap)
.mode(NavigationMode.Stack)
.titleMode(HdsNavigationTitleMode.MINI)
.hideBackButton(true)
.titleBar({
content: {
title: { mainTitle: TAB_TITLES[this.currentTab] }
},
style: {
scrollEffectOpts: {
enableScrollEffect: true,
scrollEffectType: ScrollEffectType.GRADIENT_BLUR
},
systemMaterialEffect: HDS_MATERIAL
}
})
.bindToScrollable([this.scrollers[this.currentTab]])
.ignoreLayoutSafeArea([LayoutSafeAreaType.SYSTEM], [LayoutSafeAreaEdge.TOP, LayoutSafeAreaEdge.BOTTOM])
.backgroundColor($r('app.color.page_bg'))
.width('100%')
.height('100%')
}
}
}
@@ -0,0 +1,361 @@
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 { TocPreviewNode } from '../model/TaskModel';
import { DownloadDraft } from '../model/Draft';
import { SymIcon, EmptyView, FloatingToolbar, ToolbarAction } from './Widgets';
/** 选章下载页:抓取目录并勾选章节,确认后回填首页草稿。 */
@Component
export struct ChapterSelectPage {
@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 nodes: TocPreviewNode[] = [];
@State selected: boolean[] = [];
@State selCount: number = 0;
@State totalCount: number = 0;
@State bookName: string = '';
@State showNames: boolean = true;
aboutToAppear(): void {
// 从导航参数兜底获取目标 URL
try {
const params = this.pathStack.getParamByName('chapterSelect') as Array<Object>;
if (params !== undefined && params.length > 0) {
this.targetUrl = params[params.length - 1] as string;
}
} catch (e) {
// 忽略
}
if (DownloadDraft.hasCacheFor(this.targetUrl)) {
this.applyNodes(DownloadDraft.nodes.slice());
} else {
this.load();
}
}
async load(): Promise<void> {
if (this.targetUrl.length === 0 || this.loading) {
return;
}
this.loading = true;
this.loadError = '';
const res = await TaskManager.instance.fetchTocPreview(this.targetUrl);
if (!res.ok) {
this.loadError = res.error;
this.loading = false;
return;
}
DownloadDraft.url = this.targetUrl;
DownloadDraft.nodes = res.nodes;
DownloadDraft.bookName = res.bookName;
DownloadDraft.author = res.author;
this.applyNodes(res.nodes);
}
/** 应用节点列表并按草稿过滤条件初始化勾选状态 */
private applyNodes(nodes: TocPreviewNode[]): void {
this.nodes = nodes;
this.bookName = DownloadDraft.bookName;
const total = nodes.filter((n: TocPreviewNode): boolean => n.isChapter).length;
this.totalCount = total;
const filterActive = DownloadDraft.filterActiveFor(this.targetUrl);
const picked: Set<number> = new Set();
if (filterActive) {
for (const v of DownloadDraft.chapterFilter) {
picked.add(v);
}
}
const sel: boolean[] = [];
for (const n of nodes) {
if (!n.isChapter) {
sel.push(true);
continue;
}
sel.push(!filterActive || picked.has(n.value));
}
this.selected = sel;
this.recount();
this.loading = false;
}
private recount(): void {
let c = 0;
for (let i = 0; i < this.nodes.length; i++) {
if (this.nodes[i].isChapter && this.selected[i]) {
c++;
}
}
this.selCount = c;
}
toggleChapter(idx: number): void {
if (idx < 0 || idx >= this.selected.length || !this.nodes[idx].isChapter) {
return;
}
const sel = this.selected.slice();
sel[idx] = !sel[idx];
this.selected = sel;
this.recount();
}
childrenOf(volumeValue: number): number[] {
const out: number[] = [];
for (let i = 0; i < this.nodes.length; i++) {
if (this.nodes[i].isChapter && this.nodes[i].fatherValue === volumeValue) {
out.push(i);
}
}
return out;
}
toggleVolume(idx: number): void {
const nd = this.nodes[idx];
if (nd.isChapter) {
return;
}
const childIdx = this.childrenOf(nd.value);
if (childIdx.length === 0) {
return;
}
const allOn = childIdx.every((i: number): boolean => this.selected[i]);
const sel = this.selected.slice();
for (const i of childIdx) {
sel[i] = !allOn;
}
this.selected = sel;
this.recount();
}
selectAll(): void {
const sel = this.selected.slice();
for (let i = 0; i < sel.length; i++) {
if (this.nodes[i].isChapter) {
sel[i] = true;
}
}
this.selected = sel;
this.recount();
}
selectNone(): void {
const sel = this.selected.slice();
for (let i = 0; i < sel.length; i++) {
if (this.nodes[i].isChapter) {
sel[i] = false;
}
}
this.selected = sel;
this.recount();
}
confirm(): void {
if (this.selCount === 0) {
promptAction.showToast({ message: '请至少选择一章' });
return;
}
if (this.selCount === this.totalCount) {
DownloadDraft.chapterFilter = [];
} else {
const filter: number[] = [];
for (let i = 0; i < this.nodes.length; i++) {
if (this.nodes[i].isChapter && this.selected[i]) {
filter.push(this.nodes[i].value);
}
}
DownloadDraft.chapterFilter = filter;
}
AppHub.emit('draft', '');
this.pathStack.pop();
}
volumeSelectedCount(idx: number): number {
let c = 0;
for (const i of this.childrenOf(this.nodes[idx].value)) {
if (this.selected[i]) {
c++;
}
}
return c;
}
private subTitle(): string | undefined {
if (this.totalCount === 0) {
return undefined;
}
const name = this.bookName.length > 0 ? `《${this.bookName}》· ` : '';
return `${name}已选 ${this.selCount}/${this.totalCount} 章`;
}
@Builder
chapterRow(n: TocPreviewNode, 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(n.title)
.fontSize(FontSize.sub)
.fontColor($r('app.color.font_pri'))
.maxLines(2)
.layoutWeight(1)
}
.width('100%')
.constraintSize({ minHeight: 48 })
.padding({ left: 16 + n.level * 16, right: 16 })
.onClick(() => {
this.toggleChapter(idx);
})
}
@Builder
volumeRow(n: TocPreviewNode, idx: number) {
Row({ space: 8 }) {
SymIcon({
sym: $r('sys.symbol.folder'),
iconSize: 16,
colorRes: $r('app.color.brand')
})
Text(n.title)
.fontSize(FontSize.sub)
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.font_pri'))
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.layoutWeight(1)
Text(`${this.volumeSelectedCount(idx)}/${this.childrenOf(n.value).length}`)
.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%')
.height(48)
.padding({ left: 16 + n.level * 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 }) {
EmptyView({
sym: $r('sys.symbol.exclamationmark_triangle'),
title: '目录获取失败',
sub: this.loadError
})
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.nodes, (n: TocPreviewNode, idx: number) => {
ListItem() {
if (n.isChapter) {
this.chapterRow(n, idx)
} else {
this.volumeRow(n, idx)
}
}
}, (n: TocPreviewNode, idx: number) => `${idx}_${this.selected[idx] ? 1 : 0}_${this.showNames ? 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: this.selCount === this.totalCount ? '确定(全部)' : `确定(${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: '选择章节', subTitle: this.subTitle() }
},
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;
if (DownloadDraft.hasCacheFor(this.targetUrl)) {
this.applyNodes(DownloadDraft.nodes.slice());
} else {
this.load();
}
}
})
}
}
+614
View File
@@ -0,0 +1,614 @@
import { pasteboard } from '@kit.BasicServicesKit';
import { promptAction } from '@kit.ArkUI';
import { AppHub } from '../common/AppHub';
import { Dim, FontSize, TaskStatus, InsetKey, Insets } from '../common/Theme';
import { ConfigStore, AppSettings } from '../model/Config';
import { TaskManager } from '../model/TaskManager';
import { TaskInfo } from '../model/TaskModel';
import { DownloadDraft } from '../model/Draft';
import { hostOf } from '../core/EsjCore';
import { parseBookId } from '../core/LkCore';
import { PrimaryButton, EmptyView, SymIcon, SegmentedControl } from './Widgets';
/** 下载页:新建任务(粘贴链接、选章、自定义标题)+ 任务进度列表。 */
@Component
export struct HomeView {
@Consume pathStack: NavPathStack;
scroller: Scroller = new Scroller();
gotoSettings: () => void = () => {};
@StorageProp(InsetKey.TOP) topInset: number = 0;
@StorageProp(InsetKey.BOTTOM) bottomInset: number = 0;
@State urlInput: string = '';
@State modeIdx: number = 0; // 0 单本 1 批量
@State tasks: TaskInfo[] = [];
@State cookieReady: boolean = false;
@State lkCookieReady: boolean = false;
@State siteHost: string = '';
@State threadCount: number = 2;
@State convertLabel: string = '繁→简';
@State draftTick: number = 0; // 选章草稿变化时自增,驱动刷新
@State titleInput: string = '';
private linkListener: (data?: string) => void = (data?: string): void => {
const u = data ?? '';
if (u.length > 0) {
this.urlInput = u;
DownloadDraft.onUrlChanged(u);
this.titleInput = DownloadDraft.customTitle;
this.detectMode();
promptAction.showToast({ message: '已接收链接', duration: 1500 });
}
};
private tasksListener: (data?: string) => void = (_data?: string): void => {
this.tasks = TaskManager.instance.tasksSnapshot();
};
private configListener: (data?: string) => void = (_data?: string): void => {
this.refreshConfig();
};
private draftListener: (data?: string) => void = (_data?: string): void => {
this.draftTick++;
};
aboutToAppear(): void {
this.refreshConfig();
this.tasks = TaskManager.instance.tasksSnapshot();
AppHub.on('link', this.linkListener);
AppHub.on('tasks', this.tasksListener);
AppHub.on('config', this.configListener);
AppHub.on('draft', this.draftListener);
const pending = AppHub.consumeLink();
if (pending.length > 0) {
this.urlInput = pending;
DownloadDraft.onUrlChanged(pending);
this.titleInput = DownloadDraft.customTitle;
this.detectMode();
}
}
aboutToDisappear(): void {
AppHub.off('link', this.linkListener);
AppHub.off('tasks', this.tasksListener);
AppHub.off('config', this.configListener);
AppHub.off('draft', this.draftListener);
}
refreshConfig(): void {
const s: AppSettings = ConfigStore.get();
this.siteHost = hostOf(s.siteUrl);
this.cookieReady = ConfigStore.cookieOk(ConfigStore.cleanCookie(s.cookie));
this.lkCookieReady = ConfigStore.lkCookieOk(ConfigStore.cleanCookie(s.lkCookie));
this.threadCount = s.threadCount;
this.convertLabel = s.convertMode === 't2s' ? '繁→简' : (s.convertMode === 's2t' ? '简→繁' : '不转换');
}
urlHost(): string {
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 {
return this.src() === 'esj';
}
isLkUrl(): boolean {
return this.src() === 'lk';
}
domainMatch(): boolean {
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 {
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)) {
this.modeIdx = 0;
} else if (u.indexOf('/list-') >= 0 || u.indexOf('/tags/') >= 0) {
this.modeIdx = 1;
}
}
async pasteUrl(): Promise<void> {
try {
const data = await pasteboard.getSystemPasteboard().getData();
const txt = data.getPrimaryText() ?? '';
if (txt.length > 0) {
this.urlInput = txt.trim();
DownloadDraft.onUrlChanged(this.urlInput);
this.titleInput = DownloadDraft.customTitle;
this.detectMode();
} else {
promptAction.showToast({ message: '剪贴板为空' });
}
} catch (e) {
promptAction.showToast({ message: '读取剪贴板失败' });
}
}
startTask(): void {
const url = this.urlInput.trim();
if (!this.canStart()) {
return;
}
if (this.src() === 'lk') {
DownloadDraft.onUrlChanged(url);
const filter = DownloadDraft.filterActiveFor(url) ? DownloadDraft.chapterFilter.slice() : [];
const title = DownloadDraft.url === url ? DownloadDraft.customTitle : '';
TaskManager.instance.createTask('book', url, title, filter, 'lk');
} else if (this.modeIdx === 0) {
DownloadDraft.onUrlChanged(url);
const filter = DownloadDraft.filterActiveFor(url) ? DownloadDraft.chapterFilter.slice() : [];
const title = DownloadDraft.url === url ? DownloadDraft.customTitle : '';
TaskManager.instance.createTask('book', url, title, filter, 'esj');
} else {
TaskManager.instance.createTask('list', url, '', [], 'esj');
}
this.urlInput = '';
this.titleInput = '';
DownloadDraft.reset();
promptAction.showToast({ message: '任务已创建' });
}
switchSiteTo(host: string): void {
const s: AppSettings = ConfigStore.get();
s.siteUrl = 'https://' + host + '/';
ConfigStore.save(s).then((): void => {
this.refreshConfig();
promptAction.showToast({ message: '站点域名已切换' });
});
}
draftFilterCount(): number {
// 读取 draftTick 使 build 跟踪该状态:选章确认返回后触发刷新
const _tick = this.draftTick;
return DownloadDraft.filterActiveFor(this.urlInput.trim()) ? DownloadDraft.chapterFilter.length : 0;
}
startLabel(): string {
if (this.modeIdx === 1) {
return '开始批量下载';
}
const n = this.draftFilterCount();
return n > 0 ? `开始下载(已选 ${n} 章)` : '开始下载这本书';
}
statusText(t: TaskInfo): string {
switch (t.status) {
case TaskStatus.QUEUED:
return '排队中';
case TaskStatus.RUNNING:
if (t.mode === 'list') {
if (t.phase === 'list') {
return `收集列表 · ${t.currentTitle}`;
}
return `${t.activeBooksDone}/${t.activeBooksTotal} 本 · ${t.currentTitle}`;
}
return `第 ${t.doneChapters}/${t.totalChapters} 章 · ${t.currentTitle}`;
case TaskStatus.DONE:
return '已完成';
case TaskStatus.DONE_WITH_FAIL:
return t.mode === 'book' ? `完成(${t.failedChapters} 章失败)` : '完成(部分书籍失败)';
case TaskStatus.FAILED:
return '失败';
case TaskStatus.CANCELLED:
return '已取消';
default:
return '';
}
}
statusColor(t: TaskInfo): Resource {
switch (t.status) {
case TaskStatus.DONE:
return $r('app.color.ok');
case TaskStatus.DONE_WITH_FAIL:
return $r('app.color.warn');
case TaskStatus.FAILED:
return $r('app.color.err');
case TaskStatus.CANCELLED:
return $r('app.color.font_ter');
default:
return $r('app.color.brand');
}
}
openDetail(t: TaskInfo): void {
this.pathStack.pushPathByName('taskDetail', t.id);
}
openChapterSelect(): void {
if (!this.canSelectChapters()) {
return;
}
DownloadDraft.onUrlChanged(this.urlInput.trim());
this.pathStack.pushPathByName('chapterSelect', this.urlInput.trim());
}
@Builder
miniAction(label: string, color: ResourceColor, action: () => void) {
Button(label, { type: ButtonType.Capsule })
.fontSize(FontSize.cap)
.fontColor(color)
.height(28)
.padding({ left: 12, right: 12 })
.backgroundColor($r('app.color.chip_bg'))
.onClick(action)
}
@Builder
taskCard(t: TaskInfo) {
Column({ space: 10 }) {
Row({ space: 8 }) {
Text(t.mode === 'list' ? '批量' : (t.source === 'lk' ? 'LK' : '单本'))
.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)
Text(t.mode === 'list' ? '批量列表任务' : (t.bookName.length > 0 ? `《${t.bookName}》` : '书籍'))
.fontSize(FontSize.body)
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.font_pri'))
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.layoutWeight(1)
if (t.status !== TaskStatus.RUNNING && t.status !== TaskStatus.QUEUED) {
Text(this.statusText(t))
.fontSize(FontSize.cap)
.fontColor(this.statusColor(t))
.maxLines(1)
}
}
.width('100%')
if (t.status === TaskStatus.RUNNING || t.status === TaskStatus.DONE ||
t.status === TaskStatus.DONE_WITH_FAIL) {
Progress({ value: Math.min(100, t.progressPercent()), total: 100, type: ProgressType.Capsule })
.width('100%')
.height(6)
.color(this.statusColor(t))
.backgroundColor($r('app.color.chip_bg'))
}
if (t.status === TaskStatus.RUNNING || t.status === TaskStatus.QUEUED) {
Text(this.statusText(t))
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_sec'))
.maxLines(2)
.width('100%')
}
if (t.status === TaskStatus.FAILED && t.errorMessage.length > 0) {
Text(t.errorMessage)
.fontSize(FontSize.cap)
.fontColor($r('app.color.err'))
.maxLines(3)
.width('100%')
}
Row({ space: 8 }) {
Blank()
if (t.status === TaskStatus.DONE_WITH_FAIL && t.mode === 'book') {
this.miniAction('重试失败章节', $r('app.color.warn'), (): void => {
TaskManager.instance.retryFailed(t.id);
})
}
if (t.status === TaskStatus.RUNNING || t.status === TaskStatus.QUEUED) {
this.miniAction('取消', $r('app.color.err'), (): void => {
TaskManager.instance.requestCancel(t.id);
})
} else {
this.miniAction('删除', $r('app.color.font_sec'), (): void => {
TaskManager.instance.removeTask(t.id);
this.tasks = TaskManager.instance.tasksSnapshot();
})
}
this.miniAction('详情', $r('app.color.brand'), (): void => {
this.openDetail(t);
})
}
.width('100%')
}
.width('100%')
.padding(Dim.cardPad)
.borderRadius(Dim.cardRadius)
.backgroundColor($r('app.color.card_bg'))
.onClick(() => {
this.openDetail(t);
})
}
build() {
Scroll(this.scroller) {
Column({ space: Dim.cardGap }) {
Column({ space: 12 }) {
Text('新建任务')
.fontSize(FontSize.body)
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.font_pri'))
.width('100%')
Row({ space: 8 }) {
TextInput({ text: this.urlInput, placeholder: 'esjzone.cc/detail/… 或 lightnovel.fun/book/…' })
.fontSize(FontSize.sub)
.height(40)
.borderRadius(20)
.backgroundColor($r('app.color.input_bg'))
.fontColor($r('app.color.font_pri'))
.placeholderColor($r('app.color.font_ter'))
.layoutWeight(1)
.onChange((v: string) => {
this.urlInput = v;
DownloadDraft.onUrlChanged(v.trim());
this.titleInput = DownloadDraft.customTitle;
this.detectMode();
})
Button() {
SymIcon({
sym: $r('sys.symbol.text_clipboard'),
iconSize: 18,
colorRes: $r('app.color.brand')
})
}
.type(ButtonType.Circle)
.width(40)
.height(40)
.backgroundColor($r('app.color.brand_soft'))
.accessibilityText('粘贴链接')
.onClick(() => {
this.pasteUrl();
})
}
.width('100%')
SegmentedControl({
options: this.src() === 'lk' ? ['单本书籍'] : ['单本书籍', '批量列表'],
activeIndex: this.modeIdx,
onSelect: (idx: number): void => {
this.modeIdx = idx;
}
})
if (this.modeIdx === 0 && (this.src() === 'lk' ? this.lkHostOk() : this.domainMatch())) {
Column({ space: 6 }) {
TextInput({ text: this.titleInput, placeholder: '自定义标题(可选,留空使用原书名)' })
.fontSize(FontSize.sub)
.height(40)
.borderRadius(20)
.backgroundColor($r('app.color.input_bg'))
.fontColor($r('app.color.font_pri'))
.placeholderColor($r('app.color.font_ter'))
.width('100%')
.onChange((v: string) => {
DownloadDraft.onUrlChanged(this.urlInput.trim());
DownloadDraft.customTitle = v;
this.titleInput = v;
})
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%')
.alignItems(HorizontalAlign.Start)
}
if (this.urlInput.trim().length > 0 && this.src() === '') {
Row({ space: 6 }) {
SymIcon({
sym: $r('sys.symbol.exclamationmark_triangle'),
iconSize: 15,
colorRes: $r('app.color.warn')
})
Text('无法识别的链接,目前支持 ESJZone 与 轻之国度(lightnovel.fun)')
.fontSize(FontSize.cap)
.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()) {
Row({ space: 6 }) {
SymIcon({
sym: $r('sys.symbol.exclamationmark_triangle'),
iconSize: 15,
colorRes: $r('app.color.warn')
})
Text(`链接域名(${this.urlHost()})与站点域名(${this.siteHost})不一致`)
.fontSize(FontSize.cap)
.fontColor($r('app.color.warn'))
.layoutWeight(1)
Text('切换')
.fontSize(FontSize.cap)
.fontColor($r('app.color.brand'))
.onClick(() => {
this.switchSiteTo(this.urlHost());
})
}
} else if (this.isEsjUrl() && this.domainMatch()) {
Row({ space: 6 }) {
SymIcon({
sym: $r('sys.symbol.checkmark_circle'),
iconSize: 15,
colorRes: $r('app.color.ok')
})
Text(`域名一致:${this.siteHost}`)
.fontSize(FontSize.cap)
.fontColor($r('app.color.ok'))
}
}
Row({ space: 8 }) {
Text(this.src() === 'lk'
? `LK Cookie ${this.lkCookieReady ? '已配置' : '未配置'}`
: `Cookie ${this.cookieReady ? '已配置' : '未配置'}`)
.fontSize(FontSize.cap)
.fontColor(this.src() === 'lk'
? (this.lkCookieReady ? $r('app.color.ok') : $r('app.color.warn'))
: (this.cookieReady ? $r('app.color.ok') : $r('app.color.warn')))
Text('·')
.fontColor($r('app.color.font_ter'))
Text(`并发 ${this.threadCount}`)
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_sec'))
Text('·')
.fontColor($r('app.color.font_ter'))
Text(this.convertLabel)
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_sec'))
Blank()
Text('设置')
.fontSize(FontSize.cap)
.fontColor($r('app.color.brand'))
.onClick(() => {
this.gotoSettings();
})
}
.width('100%')
PrimaryButton({
label: this.startLabel(),
isEnabled: this.canStart(),
onTap: (): void => {
this.startTask();
}
})
}
.width('100%')
.padding(Dim.cardPad)
.borderRadius(Dim.cardRadius)
.backgroundColor($r('app.color.card_bg'))
.alignItems(HorizontalAlign.Start)
// 任务列表
Text(this.tasks.length > 0 ? `任务 (${this.tasks.length})` : '任务')
.fontSize(FontSize.sub)
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.font_sec'))
.width('100%')
.padding({ left: 12, top: 8 })
if (this.tasks.length === 0) {
Column() {
EmptyView({
sym: $r('sys.symbol.arrow_down_circle'),
title: '暂无下载任务',
sub: '粘贴书籍链接开始下载'
})
}
.width('100%')
.borderRadius(Dim.cardRadius)
.backgroundColor($r('app.color.card_bg'))
} else {
ForEach(this.tasks, (t: TaskInfo) => {
this.taskCard(t)
}, (t: TaskInfo) => t.id + t.status + t.doneChapters + t.failedChapters + t.progressPercent())
}
}
.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%')
.backgroundColor($r('app.color.page_bg'))
}
}
+242
View File
@@ -0,0 +1,242 @@
import { systemShare } from '@kit.ShareKit';
import { uniformTypeDescriptor as utd } from '@kit.ArkData';
import { picker, fileIo as fs, fileUri } from '@kit.CoreFileKit';
import { promptAction } from '@kit.ArkUI';
import { AppHub } from '../common/AppHub';
import { Dim, FontSize, InsetKey, Insets } from '../common/Theme';
import { LibraryStore, BookRecord, ensureLibraryDir } from '../model/LibraryStore';
import { EmptyView, SymIcon } from './Widgets';
/**
* 书库:已生成书籍的展示、系统分享、导出到用户目录、删除。
*/
@Component
export struct LibraryView {
scroller: Scroller = new Scroller();
@StorageProp(InsetKey.TOP) topInset: number = 0;
@StorageProp(InsetKey.BOTTOM) bottomInset: number = 0;
@State records: BookRecord[] = [];
@State showPath: boolean = false;
private tasksListener: (data?: string) => void = (_d?: string): void => {
this.records = LibraryStore.list();
};
aboutToAppear(): void {
ensureLibraryDir();
this.records = LibraryStore.list();
AppHub.on('tasks', this.tasksListener);
}
aboutToDisappear(): void {
AppHub.off('tasks', this.tasksListener);
}
shareBook(r: BookRecord): void {
const path = r.epubPath.length > 0 ? r.epubPath : r.txtPath;
if (path.length === 0) {
promptAction.showToast({ message: '没有可分享的文件' });
return;
}
try {
const record: systemShare.SharedRecord = {
utd: utd.UniformDataType.FILE,
uri: fileUri.getUriFromPath(path),
title: `《${r.name}》${r.author}`
};
const data = new systemShare.SharedData(record);
const controller = new systemShare.ShareController(data);
controller.show(AppHub.uiContext(), { previewMode: systemShare.SharePreviewMode.DEFAULT }).catch((e: Error): void => {
promptAction.showToast({ message: '分享失败: ' + e.message });
});
} catch (e) {
promptAction.showToast({ message: '分享失败: ' + (e as Error).message });
}
}
async exportBook(r: BookRecord, isEpub: boolean): Promise<void> {
const srcPath = isEpub ? r.epubPath : r.txtPath;
if (srcPath.length === 0) {
promptAction.showToast({ message: '该格式未生成' });
return;
}
try {
const docPicker = new picker.DocumentViewPicker();
const opts = new picker.DocumentSaveOptions();
opts.newFileNames = [`《${r.name}》${r.author}.${isEpub ? 'epub' : 'txt'}`];
const uris = await docPicker.save(opts);
if (uris === undefined || uris.length === 0) {
return; // 用户取消
}
const st = fs.statSync(srcPath);
const buf = new ArrayBuffer(st.size);
const src = fs.openSync(srcPath, fs.OpenMode.READ_ONLY);
let off = 0;
while (off < st.size) {
const n = fs.readSync(src.fd, buf, { offset: off, length: st.size - off });
if (n <= 0) {
break;
}
off += n;
}
fs.closeSync(src);
const dst = fs.openSync(uris[0], fs.OpenMode.READ_WRITE | fs.OpenMode.TRUNC);
fs.writeSync(dst.fd, buf);
fs.closeSync(dst);
promptAction.showToast({ message: '已导出' });
} catch (e) {
promptAction.showToast({ message: '导出失败: ' + (e as Error).message });
}
}
confirmDelete(r: BookRecord): void {
AlertDialog.show({
title: '删除书籍',
message: `将从书库中删除《${r.name}》及其文件。`,
autoCancel: true,
alignment: DialogAlignment.Center,
primaryButton: {
value: '取消',
action: () => {}
},
secondaryButton: {
value: '删除',
fontColor: $r('app.color.err'),
action: () => {
LibraryStore.remove(r.id);
this.records = LibraryStore.list();
promptAction.showToast({ message: '已删除' });
}
}
});
}
@Builder
miniAction(label: string, color: ResourceColor, action: () => void) {
Button(label, { type: ButtonType.Capsule })
.fontSize(FontSize.cap)
.fontColor(color)
.height(28)
.padding({ left: 12, right: 12 })
.backgroundColor($r('app.color.chip_bg'))
.onClick(action)
}
@Builder
formatTag(label: string) {
Text(label)
.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)
}
@Builder
bookCard(r: BookRecord) {
Column({ space: 12 }) {
Row({ space: 12 }) {
Column() {
SymIcon({
sym: $r('sys.symbol.book_pages_fill'),
iconSize: 22,
colorRes: $r('app.color.brand')
})
}
.width(44)
.height(44)
.justifyContent(FlexAlign.Center)
.borderRadius(12)
.backgroundColor($r('app.color.brand_soft'))
Column({ space: 4 }) {
Text(`《${r.name}》`)
.fontSize(FontSize.body)
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.font_pri'))
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
Text(`${r.author.length > 0 ? r.author + ' · ' : ''}${r.chapters} 章${r.date.length > 0 ? ' · 更新 ' + r.date : ''}`)
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
}
.alignItems(HorizontalAlign.Start)
.layoutWeight(1)
}
.width('100%')
Row({ space: 6 }) {
if (r.epubPath.length > 0) {
this.formatTag('EPUB')
}
if (r.txtPath.length > 0) {
this.formatTag('TXT')
}
Blank()
this.miniAction('分享', $r('app.color.brand'), (): void => {
this.shareBook(r);
})
if (r.epubPath.length > 0) {
this.miniAction('导出EPUB', $r('app.color.font_pri'), (): void => {
this.exportBook(r, true);
})
}
if (r.txtPath.length > 0) {
this.miniAction('导出TXT', $r('app.color.font_pri'), (): void => {
this.exportBook(r, false);
})
}
Button({ type: ButtonType.Circle }) {
SymIcon({ sym: $r('sys.symbol.trash'), iconSize: 16, colorRes: $r('app.color.err') })
}
.width(28)
.height(28)
.backgroundColor($r('app.color.chip_bg'))
.accessibilityText('删除')
.onClick(() => {
this.confirmDelete(r);
})
}
.width('100%')
}
.width('100%')
.padding(Dim.cardPad)
.borderRadius(Dim.cardRadius)
.backgroundColor($r('app.color.card_bg'))
}
build() {
Stack() {
if (this.records.length === 0) {
Column() {
EmptyView({
sym: $r('sys.symbol.book_pages_fill'),
title: '书库还是空的',
sub: '完成下载后,书籍会自动保存在这里'
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
} else {
List({ space: Dim.cardGap, scroller: this.scroller }) {
ForEach(this.records, (r: BookRecord) => {
ListItem() {
this.bookCard(r)
}
}, (r: BookRecord) => r.id + r.date)
}
.width('100%')
.height('100%')
.scrollBar(BarState.Off)
.padding({ left: Dim.pagePad, right: Dim.pagePad })
.contentStartOffset(Insets.contentTop(this.topInset))
.contentEndOffset(Insets.contentBottom(this.bottomInset))
.clipContent(ContentClipMode.SAFE_AREA)
}
}
.width('100%')
.height('100%')
.backgroundColor($r('app.color.page_bg'))
}
}
+457
View File
@@ -0,0 +1,457 @@
import { pasteboard } from '@kit.BasicServicesKit';
import { promptAction } from '@kit.ArkUI';
import { AppHub } from '../common/AppHub';
import { Dim, FontSize, InsetKey, Insets } from '../common/Theme';
import { ConfigStore, AppSettings, CONVERT_T2S, CONVERT_S2T, CONVERT_NONE } from '../model/Config';
import { hostOf } from '../core/EsjCore';
import { SectionCard, SettingRow, SegmentedControl, SymIcon } from './Widgets';
/** 设置页:站点、Cookie、下载参数、繁简转换与输出设置,修改即持久化。 */
@Component
export struct SettingsView {
scroller: Scroller = new Scroller();
@StorageProp(InsetKey.TOP) topInset: number = 0;
@StorageProp(InsetKey.BOTTOM) bottomInset: number = 0;
@State siteUrl: string = '';
@State cookie: string = '';
@State lkCookie: string = '';
@State convertMode: string = CONVERT_T2S;
@State threadCount: number = 2;
@State retryCount: number = 3;
@State timeoutSec: number = 25;
@State downloadImages: boolean = true;
@State downloadCover: boolean = true;
@State outputEpub: boolean = true;
@State outputTxt: boolean = true;
@State showCookieHelp: boolean = false;
@State showLkCookieHelp: boolean = false;
private configListener: (data?: string) => void = (_d?: string): void => {
this.loadFromStore();
};
aboutToAppear(): void {
this.loadFromStore();
AppHub.on('config', this.configListener);
}
aboutToDisappear(): void {
AppHub.off('config', this.configListener);
}
loadFromStore(): void {
const s = ConfigStore.get();
this.siteUrl = s.siteUrl;
this.cookie = s.cookie;
this.lkCookie = s.lkCookie;
this.convertMode = s.convertMode;
this.threadCount = s.threadCount;
this.retryCount = s.retryCount;
this.timeoutSec = s.timeoutSec;
this.downloadImages = s.downloadImages;
this.downloadCover = s.downloadCover;
this.outputEpub = s.outputEpub;
this.outputTxt = s.outputTxt;
}
private persist(): void {
const s: AppSettings = {
siteUrl: this.siteUrl,
cookie: this.cookie,
lkCookie: this.lkCookie,
convertMode: this.convertMode,
threadCount: this.threadCount,
retryCount: this.retryCount,
timeoutSec: this.timeoutSec,
downloadImages: this.downloadImages,
downloadCover: this.downloadCover,
outputEpub: this.outputEpub,
outputTxt: this.outputTxt
};
ConfigStore.save(s).then((): void => {
AppHub.emit('config', '');
});
}
cookieOk(): boolean {
return ConfigStore.cookieOk(ConfigStore.cleanCookie(this.cookie));
}
lkCookieOk(): boolean {
return ConfigStore.lkCookieOk(ConfigStore.cleanCookie(this.lkCookie));
}
async pasteCookie(): Promise<void> {
try {
const data = await pasteboard.getSystemPasteboard().getData();
const txt = data.getPrimaryText() ?? '';
if (txt.length > 0) {
this.cookie = ConfigStore.cleanCookie(txt);
this.persist();
promptAction.showToast({ message: this.cookieOk() ? 'Cookie 已粘贴并识别到登录字段' : '已粘贴,但未检测到 ews_key/ews_token' });
} else {
promptAction.showToast({ message: '剪贴板为空' });
}
} catch (e) {
promptAction.showToast({ message: '读取剪贴板失败' });
}
}
async pasteLkCookie(): Promise<void> {
try {
const data = await pasteboard.getSystemPasteboard().getData();
const txt = data.getPrimaryText() ?? '';
if (txt.length > 0) {
this.lkCookie = ConfigStore.cleanCookie(txt);
this.persist();
promptAction.showToast({ message: this.lkCookieOk() ? 'LK Cookie 已粘贴并识别到 lk_security_key' : '已粘贴,但未检测到 lk_security_key' });
} else {
promptAction.showToast({ message: '剪贴板为空' });
}
} catch (e) {
promptAction.showToast({ message: '读取剪贴板失败' });
}
}
build() {
Scroll(this.scroller) {
Column({ space: Dim.cardGap + 4 }) {
// ---------- 站点与账号 ----------
SectionCard({ title: '站点与账号' }) {
Column({ space: 4 }) {
SettingRow({
title: '站点域名'
})
Row({ space: 8 }) {
TextInput({ text: this.siteUrl, placeholder: 'https://www.esjzone.cc/' })
.fontSize(FontSize.sub)
.height(40)
.borderRadius(10)
.backgroundColor($r('app.color.input_bg'))
.fontColor($r('app.color.font_pri'))
.layoutWeight(1)
.onChange((v: string) => {
this.siteUrl = v;
})
.onSubmit((): void => {
if (hostOf(this.siteUrl).length > 0) {
this.persist();
} else {
promptAction.showToast({ message: '域名格式不正确' });
}
})
Text('.cc')
.fontSize(FontSize.cap)
.fontColor(this.siteUrl.indexOf('esjzone.cc') >= 0 ? $r('app.color.on_brand') : $r('app.color.font_sec'))
.padding({ left: 10, right: 10, top: 6, bottom: 6 })
.borderRadius(8)
.backgroundColor(this.siteUrl.indexOf('esjzone.cc') >= 0 ? $r('app.color.brand') : $r('app.color.chip_bg'))
.onClick(() => {
this.siteUrl = 'https://www.esjzone.cc/';
this.persist();
})
Text('.one')
.fontSize(FontSize.cap)
.fontColor(this.siteUrl.indexOf('esjzone.one') >= 0 ? $r('app.color.on_brand') : $r('app.color.font_sec'))
.padding({ left: 10, right: 10, top: 6, bottom: 6 })
.borderRadius(8)
.backgroundColor(this.siteUrl.indexOf('esjzone.one') >= 0 ? $r('app.color.brand') : $r('app.color.chip_bg'))
.onClick(() => {
this.siteUrl = 'https://www.esjzone.one/';
this.persist();
})
}
.width('100%')
Divider().strokeWidth(0.5).color($r('app.color.divider'))
SettingRow({
title: 'Cookie',
desc: this.cookieOk() ? '已检测到 ews_key / ews_token' : ''
})
TextArea({ text: this.cookie, placeholder: 'ews_key=…;ews_token=…;' })
.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.cookie = v;
this.persist();
})
Row({ space: 12 }) {
Text('粘贴')
.fontSize(FontSize.sub)
.fontColor($r('app.color.brand'))
.padding(6)
.onClick(() => {
this.pasteCookie();
})
Text('清空')
.fontSize(FontSize.sub)
.fontColor($r('app.color.err'))
.padding(6)
.onClick(() => {
this.cookie = '';
this.persist();
})
Text('使用说明')
.fontSize(FontSize.sub)
.fontColor($r('app.color.font_sec'))
.padding(6)
.onClick(() => {
this.showCookieHelp = !this.showCookieHelp;
})
Blank()
if (this.cookieOk()) {
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.showCookieHelp) {
Text('1. 在浏览器登录 esjzone\n2. 打开开发者工具(F12)→ Application/存储 → Cookies\n3. 复制包含 ews_key 与 ews_token 的整行 Cookie\n4. 粘贴到上方输入框\n\n注意:esjzone.cc 与 esjzone.one 的 Cookie 不通用;手机浏览器可先切换桌面版网页获取。')
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_sec'))
.width('100%')
.padding(10)
.borderRadius(10)
.backgroundColor($r('app.color.input_bg'))
}
}
.width('100%')
.padding({ left: Dim.cardPad, right: Dim.cardPad })
}
// ---------- 轻之国度 ----------
SectionCard({ title: '轻之国度(lightnovel.fun)' }) {
Column({ space: 4 }) {
SettingRow({
title: 'LK Cookie',
desc: this.lkCookieOk() ? '已检测到 lk_security_key' : ''
})
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. 粘贴到上方输入框')
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_sec'))
.width('100%')
.padding(10)
.borderRadius(10)
.backgroundColor($r('app.color.input_bg'))
}
}
.width('100%')
.padding({ left: Dim.cardPad, right: Dim.cardPad })
}
// ---------- 下载 ----------
SectionCard({ title: '下载' }) {
Column({ space: 4 }) {
SettingRow({
title: '并发数',
valueText: `${this.threadCount}`
})
Slider({ value: this.threadCount, min: 1, max: 6, step: 1, style: SliderStyle.OutSet })
.width('100%')
.selectedColor($r('app.color.brand'))
.onChange((v: number) => {
this.threadCount = Math.round(v);
this.persist();
})
Divider().strokeWidth(0.5).color($r('app.color.divider'))
SettingRow({
title: '失败重试次数',
valueText: `${this.retryCount}`
})
Slider({ value: this.retryCount, min: 0, max: 5, step: 1, style: SliderStyle.OutSet })
.width('100%')
.selectedColor($r('app.color.brand'))
.onChange((v: number) => {
this.retryCount = Math.round(v);
this.persist();
})
Divider().strokeWidth(0.5).color($r('app.color.divider'))
SettingRow({
title: '请求超时',
valueText: `${this.timeoutSec}s`
})
Slider({ value: this.timeoutSec, min: 10, max: 60, step: 5, style: SliderStyle.OutSet })
.width('100%')
.selectedColor($r('app.color.brand'))
.onChange((v: number) => {
this.timeoutSec = Math.round(v);
this.persist();
})
Divider().strokeWidth(0.5).color($r('app.color.divider'))
SettingRow({
title: '下载章节插图',
showToggle: true,
isOn: this.downloadImages,
onToggle: (v: boolean): void => {
this.downloadImages = v;
this.persist();
}
})
SettingRow({
title: '下载封面',
showToggle: true,
isOn: this.downloadCover,
onToggle: (v: boolean): void => {
this.downloadCover = v;
this.persist();
}
})
}
.width('100%')
.padding({ left: Dim.cardPad, right: Dim.cardPad })
}
// ---------- 内容转换 ----------
SectionCard({ title: '内容转换' }) {
Column({ space: 10 }) {
SettingRow({
title: '繁简转换'
})
SegmentedControl({
options: ['繁→简', '简→繁', '不转换'],
activeIndex: this.convertMode === CONVERT_T2S ? 0 : (this.convertMode === CONVERT_S2T ? 1 : 2),
onSelect: (idx: number): void => {
this.convertMode = idx === 0 ? CONVERT_T2S : (idx === 1 ? CONVERT_S2T : CONVERT_NONE);
this.persist();
}
})
}
.width('100%')
.padding({ left: Dim.cardPad, right: Dim.cardPad })
}
// ---------- 输出 ----------
SectionCard({ title: '输出' }) {
Column({ space: 4 }) {
SettingRow({
title: '生成 EPUB',
showToggle: true,
isOn: this.outputEpub,
onToggle: (v: boolean): void => {
if (!v && !this.outputTxt) {
promptAction.showToast({ message: '至少保留一种输出格式' });
return;
}
this.outputEpub = v;
this.persist();
}
})
Divider().strokeWidth(0.5).color($r('app.color.divider'))
SettingRow({
title: '生成 TXT',
showToggle: true,
isOn: this.outputTxt,
onToggle: (v: boolean): void => {
if (!v && !this.outputEpub) {
promptAction.showToast({ message: '至少保留一种输出格式' });
return;
}
this.outputTxt = v;
this.persist();
}
})
}
.width('100%')
.padding({ left: Dim.cardPad, right: Dim.cardPad })
}
// ---------- 关于 ----------
SectionCard({ title: '关于' }) {
Column({ space: 6 }) {
Text('ESJ / LK 下载器 v1.1.0')
.fontSize(FontSize.sub)
.fontColor($r('app.color.font_pri'))
Text('请仅将本工具用于个人备份与学习,尊重原作者版权。')
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
}
.width('100%')
.padding({ left: Dim.cardPad, right: Dim.cardPad })
}
}
.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%')
.backgroundColor($r('app.color.page_bg'))
}
}
+544
View File
@@ -0,0 +1,544 @@
import { HdsNavDestination, HdsNavDestinationTitleMode, ScrollEffectType } from '@kit.UIDesignKit';
import { TaskManager } from '../model/TaskManager';
import { TaskInfo, ChapterNode, NodeDataSource, LogLine } from '../model/TaskModel';
import { NodeStatus, TaskStatus, Dim, FontSize, HDS_MATERIAL, InsetKey, Insets } from '../common/Theme';
import { EmptyView, SymIcon, FloatingToolbar, ToolbarAction } from './Widgets';
/** 任务详情:单书模式展示章节树,批量模式展示书籍进度,可展开运行日志。 */
@Component
export struct TaskDetailPage {
@Consume pathStack: NavPathStack;
@StorageProp(InsetKey.TOP) topInset: number = 0;
@StorageProp(InsetKey.BOTTOM) bottomInset: number = 0;
@State taskId: string = '';
@State taskFound: boolean = false;
@State tick: number = 0;
@State showLog: boolean = false;
@State mode: string = 'book';
@State bookName: string = '';
@State status: string = '';
@State phase: string = '';
@State doneCh: number = 0;
@State totalCh: number = 0;
@State failedCh: number = 0;
@State doneImg: number = 0;
@State totalImg: number = 0;
@State currentTitle: string = '';
@State errorMessage: string = '';
@State percent: number = 0;
@State booksDone: number = 0;
@State booksTotal: number = 0;
nodeDs: NodeDataSource = new NodeDataSource();
private timerId: number = -1;
private scroller: Scroller = new Scroller();
private listScroller: Scroller = new Scroller();
aboutToAppear(): void {
this.timerId = setInterval((): void => {
this.refresh();
}, 500);
}
aboutToDisappear(): void {
if (this.timerId >= 0) {
clearInterval(this.timerId);
this.timerId = -1;
}
}
private resolveTask(): TaskInfo | null {
if (this.taskId === '') {
// 从导航参数兜底获取
try {
const params = this.pathStack.getParamByName('taskDetail') as Array<Object>;
if (params !== undefined && params.length > 0) {
this.taskId = params[params.length - 1] as string;
}
} catch (e) {
// 忽略
}
}
return TaskManager.instance.findTask(this.taskId);
}
refresh(): void {
const t = this.resolveTask();
if (t === null) {
this.taskFound = false;
return;
}
this.taskFound = true;
this.mode = t.mode;
this.bookName = t.bookName;
this.status = t.status;
this.phase = t.phase;
this.doneCh = t.doneChapters;
this.totalCh = t.totalChapters;
this.failedCh = t.failedChapters;
this.doneImg = t.doneImages;
this.totalImg = t.totalImages;
this.currentTitle = t.currentTitle;
this.errorMessage = t.errorMessage;
this.percent = t.progressPercent();
this.booksDone = t.activeBooksDone;
this.booksTotal = t.activeBooksTotal;
this.nodeDs.setItems(t.nodes);
this.tick++;
}
statusLabel(): string {
switch (this.status) {
case TaskStatus.QUEUED:
return '排队中…';
case TaskStatus.RUNNING:
return this.phase === 'list' ? '收集书籍列表…' : (this.phase === 'build' ? '正在打包…' : '下载中…');
case TaskStatus.DONE:
return '下载完成';
case TaskStatus.DONE_WITH_FAIL:
return `下载完成,${this.failedCh} 章失败`;
case TaskStatus.FAILED:
return '任务失败';
case TaskStatus.CANCELLED:
return '已取消';
default:
return '';
}
}
nodeIcon(n: ChapterNode): Resource {
switch (n.status) {
case NodeStatus.DONE:
return $r('sys.symbol.checkmark');
case NodeStatus.DOWNLOADING:
return $r('sys.symbol.arrow_down_circle');
case NodeStatus.FAILED:
return $r('sys.symbol.xmark');
case NodeStatus.LOCKED:
return $r('sys.symbol.lock');
default:
return $r('sys.symbol.circle');
}
}
nodeColor(n: ChapterNode): Resource {
switch (n.status) {
case NodeStatus.DONE:
return $r('app.color.ok');
case NodeStatus.DOWNLOADING:
return $r('app.color.brand');
case NodeStatus.FAILED:
return $r('app.color.err');
case NodeStatus.LOCKED:
return $r('app.color.warn');
default:
return $r('app.color.font_ter');
}
}
@Builder
nodeRow(n: ChapterNode) {
Row({ space: 8 }) {
SymIcon({
sym: this.nodeIcon(n),
iconSize: 16,
colorRes: this.nodeColor(n)
})
.width(20)
Text(n.node.title)
.fontSize(n.node.isVolume ? FontSize.sub : FontSize.cap)
.fontWeight(n.node.isVolume ? FontWeight.Medium : FontWeight.Normal)
.fontColor(n.node.isVolume ? $r('app.color.font_pri') : $r('app.color.font_sec'))
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.layoutWeight(1)
if (n.status === NodeStatus.FAILED && n.error.length > 0) {
Text(n.error)
.fontSize(FontSize.cap)
.fontColor($r('app.color.err'))
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.constraintSize({ maxWidth: '45%' })
}
}
.width('100%')
.height(36)
.padding({ left: 12 + n.node.level * 16, right: 12 })
}
build() {
HdsNavDestination() {
Stack({ alignContent: Alignment.Bottom }) {
if (!this.taskFound) {
Column() {
EmptyView({
sym: $r('sys.symbol.exclamationmark_triangle'),
title: '任务不存在',
sub: '可能已被删除'
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
} else {
Scroll(this.scroller) {
Column({ space: Dim.cardGap }) {
Column({ space: 12 }) {
Row({ space: 16 }) {
Stack() {
Progress({ value: this.percent, total: 100, type: ProgressType.Ring })
.width(72)
.height(72)
.color(this.status === TaskStatus.FAILED ? $r('app.color.err') : $r('app.color.brand'))
.style({ strokeWidth: 8 })
Text(`${this.percent}%`)
.fontSize(FontSize.sub)
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.font_pri'))
}
Column({ space: 4 }) {
Text(this.statusLabel())
.fontSize(FontSize.body)
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.font_pri'))
if (this.mode === 'book') {
Text(`章节 ${this.doneCh}/${this.totalCh}${this.failedCh > 0 ? ` · 失败 ${this.failedCh}` : ''}`)
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_sec'))
if (this.totalImg > 0) {
Text(`图片 ${this.doneImg}/${this.totalImg}`)
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_sec'))
}
if (this.currentTitle.length > 0 && this.status === TaskStatus.RUNNING) {
Text(`当前:${this.currentTitle}`)
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
}
} else {
Text(`书籍 ${this.booksDone}/${this.booksTotal}`)
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_sec'))
}
}
.alignItems(HorizontalAlign.Start)
.layoutWeight(1)
}
.width('100%')
if (this.errorMessage.length > 0) {
Text(this.errorMessage)
.fontSize(FontSize.cap)
.fontColor($r('app.color.err'))
.width('100%')
}
}
.width('100%')
.padding(Dim.cardPad)
.borderRadius(Dim.cardRadius)
.backgroundColor($r('app.color.card_bg'))
if (this.mode === 'book') {
Column() {
Text(`章节 (${this.totalCh})`)
.fontSize(FontSize.sub)
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.font_sec'))
.width('100%')
.padding({ left: 12, top: 12, bottom: 6 })
List({ scroller: this.listScroller, space: 0 }) {
LazyForEach(this.nodeDs, (n: ChapterNode) => {
ListItem() {
this.nodeRow(n)
}
}, (n: ChapterNode) => `${n.node.value}_${n.status}_${n.doneTick}`)
}
.layoutWeight(1)
.scrollBar(BarState.Auto)
.nestedScroll({ scrollForward: NestedScrollMode.PARENT_FIRST, scrollBackward: NestedScrollMode.SELF_FIRST })
.divider({ strokeWidth: 0.5, color: $r('app.color.divider'), startMargin: 40, endMargin: 12 })
}
.height(420)
.borderRadius(Dim.cardRadius)
.backgroundColor($r('app.color.card_bg'))
.clip(true)
} else {
this.bookListCard()
}
if (this.showLog) {
Column({ space: 8 }) {
Text('运行日志')
.fontSize(FontSize.sub)
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.font_sec'))
.width('100%')
.padding({ left: 4 })
this.logList()
}
.width('100%')
.padding(Dim.cardPad)
.borderRadius(Dim.cardRadius)
.backgroundColor($r('app.color.card_bg'))
}
}
.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: this.showLog ? '收起日志' : '运行日志',
sym: $r('sys.symbol.doc_plaintext'),
onTap: (): void => {
this.toggleLog();
}
})
if (this.status === TaskStatus.RUNNING || this.status === TaskStatus.QUEUED) {
ToolbarAction({
label: '取消任务',
sym: $r('sys.symbol.xmark'),
danger: true,
onTap: (): void => {
TaskManager.instance.requestCancel(this.taskId);
}
})
} else if (this.status === TaskStatus.DONE_WITH_FAIL && this.mode === 'book') {
ToolbarAction({
label: '重试失败章节',
primary: true,
onTap: (): void => {
TaskManager.instance.retryFailed(this.taskId);
}
})
} else {
ToolbarAction({
label: '删除任务',
sym: $r('sys.symbol.trash'),
danger: true,
onTap: (): void => {
TaskManager.instance.removeTask(this.taskId);
this.pathStack.pop();
}
})
}
}
}
}
.width('100%')
.height('100%')
.backgroundColor($r('app.color.page_bg'))
}
.titleMode(HdsNavDestinationTitleMode.MINI)
.titleBar({
content: {
title: {
mainTitle: this.bookName.length > 0 ? `《${this.bookName}》` : '任务详情',
subTitle: this.taskFound ? this.statusLabel() : undefined
}
},
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.taskId = p;
this.refresh();
}
})
}
private toggleLog(): void {
this.showLog = !this.showLog;
if (this.showLog) {
// 等待日志卡片完成布局后滚动到底部
setTimeout((): void => {
this.scroller.scrollEdge(Edge.Bottom);
}, 50);
}
}
@Builder
bookListCard() {
Column() {
Text(`书籍列表 (${this.booksDone}/${this.booksTotal})`)
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
.width('100%')
.padding({ left: 4, top: 10, bottom: 6 })
BookRowsView({ taskId: this.taskId, tick: this.tick })
}
.width('100%')
.padding({ bottom: 8 })
.borderRadius(Dim.cardRadius)
.backgroundColor($r('app.color.card_bg'))
}
@Builder
logList() {
LogView({ taskId: this.taskId, tick: this.tick })
}
}
/** 批量模式书籍行(子组件:随 tick 刷新) */
@Component
struct BookRowsView {
taskId: string = '';
@Prop tick: number = 0;
build() {
Column() {
ForEach(this.rows(), (b: BookRowItem) => {
Row({ space: 8 }) {
SymIcon({
sym: this.iconOf(b.status),
iconSize: 16,
colorRes: this.colorOf(b.status)
})
.width(20)
Column({ space: 2 }) {
Text(b.name.length > 0 ? `《${b.name}》` : b.url)
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_pri'))
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
if (b.message.length > 0 || b.doneCh > 0) {
Text(b.message.length > 0 ? b.message : `${b.doneCh}/${b.totalCh} 章`)
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
}
}
.alignItems(HorizontalAlign.Start)
.layoutWeight(1)
}
.width('100%')
.height(40)
.padding({ left: 8, right: 8 })
}, (b: BookRowItem) => b.url + b.status + b.doneCh)
}
.width('100%')
}
private rows(): BookRowItem[] {
const t = TaskManager.instance.findTask(this.taskId);
const out: BookRowItem[] = [];
if (t === null) {
return out;
}
for (const b of t.books) {
out.push({ url: b.url, name: b.name, status: b.status, doneCh: b.doneCh, totalCh: b.totalCh, message: b.message });
}
return out;
}
private iconOf(status: string): Resource {
if (status === 'done') {
return $r('sys.symbol.checkmark');
}
if (status === 'failed') {
return $r('sys.symbol.xmark');
}
if (status === 'skipped') {
return $r('sys.symbol.arrow_right');
}
if (status === 'running') {
return $r('sys.symbol.arrow_down_circle');
}
return $r('sys.symbol.circle');
}
private colorOf(status: string): Resource {
if (status === 'done') {
return $r('app.color.ok');
}
if (status === 'failed') {
return $r('app.color.err');
}
if (status === 'skipped') {
return $r('app.color.warn');
}
if (status === 'running') {
return $r('app.color.brand');
}
return $r('app.color.font_ter');
}
}
interface BookRowItem {
url: string;
name: string;
status: string;
doneCh: number;
totalCh: number;
message: string;
}
/** 日志视图(子组件:随 tick 刷新) */
@Component
struct LogView {
taskId: string = '';
@Prop tick: number = 0;
private scroller: Scroller = new Scroller();
build() {
Column() {
List({ scroller: this.scroller, space: 2 }) {
ForEach(this.lines(), (l: LogLine) => {
ListItem() {
Text(`${l.time} ${l.msg}`)
.fontSize(11)
.fontColor(this.colorOf(l.level))
.width('100%')
.padding({ left: 4, right: 4, top: 1, bottom: 1 })
}
}, (l: LogLine, idx: number) => `${idx}_${l.msg}`)
}
.height(220)
.scrollBar(BarState.Auto)
.onAppear(() => {
this.scroller.scrollEdge(Edge.Bottom);
})
}
.width('100%')
.borderRadius(Dim.innerRadius)
.backgroundColor($r('app.color.log_bg'))
.padding(8)
}
private lines(): LogLine[] {
const t = TaskManager.instance.findTask(this.taskId);
return t !== null ? t.logs.slice(-120) : [];
}
private colorOf(level: string): Resource {
if (level === 'error') {
return $r('app.color.err');
}
if (level === 'warn') {
return $r('app.color.warn');
}
if (level === 'ok') {
return $r('app.color.ok');
}
return $r('app.color.font_sec');
}
}
+273
View File
@@ -0,0 +1,273 @@
import { Dim, FontSize, InsetKey, Insets, floatingBarMaterial } from '../common/Theme';
/**
* 通用小组件:官方符号图标、分段选择器、设置行、空状态、主按钮、悬浮工具栏。
* 需要随父组件状态刷新的数据一律使用 @Prop 传递。
*/
/** 官方 HarmonyOS Symbol 图标(sys.symbol.*),单色渲染 */
@Component
export struct SymIcon {
@Prop sym: Resource = $r('sys.symbol.circle');
@Prop iconSize: number = 18;
@Prop colorRes: ResourceColor = $r('app.color.font_ter');
build() {
SymbolGlyph(this.sym)
.fontSize(this.iconSize)
.fontColor([this.colorRes])
}
}
@Component
export struct SegmentedControl {
options: string[] = [];
@Prop activeIndex: number = 0;
onSelect: (index: number) => void = (_: number) => {};
build() {
Row({ space: 4 }) {
ForEach(this.options, (opt: string, idx: number) => {
Text(opt)
.fontSize(this.activeIndex === idx ? FontSize.sub : FontSize.cap)
.fontWeight(this.activeIndex === idx ? FontWeight.Medium : FontWeight.Normal)
.fontColor(this.activeIndex === idx ? $r('app.color.on_brand') : $r('app.color.font_sec'))
.textAlign(TextAlign.Center)
.layoutWeight(1)
.height(32)
.borderRadius(8)
.backgroundColor(this.activeIndex === idx ? $r('app.color.brand') : Color.Transparent)
.onClick(() => {
if (this.activeIndex !== idx) {
this.onSelect(idx);
}
})
}, (opt: string) => opt)
}
.padding(4)
.borderRadius(12)
.backgroundColor($r('app.color.chip_bg'))
.width('100%')
}
}
@Component
export struct SectionCard {
@Prop title: string = '';
@BuilderParam content: () => void = emptyBuilder;
build() {
Column({ space: 8 }) {
if (this.title.length > 0) {
Text(this.title)
.fontSize(FontSize.sub)
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.font_sec'))
.width('100%')
.padding({ left: 12 })
}
Column() {
this.content()
}
.width('100%')
.padding({ top: 4, bottom: 8 })
.borderRadius(Dim.cardRadius)
.backgroundColor($r('app.color.card_bg'))
}
.width('100%')
.alignItems(HorizontalAlign.Start)
}
}
@Component
export struct SettingRow {
@Prop title: string = '';
@Prop desc: string = '';
@Prop valueText: string = '';
@Prop showToggle: boolean = false;
@Prop isOn: boolean = false;
onToggle: (v: boolean) => void = (_: boolean) => {};
build() {
Row() {
Column({ space: 2 }) {
Text(this.title)
.fontSize(FontSize.body)
.fontColor($r('app.color.font_pri'))
.maxLines(2)
if (this.desc.length > 0) {
Text(this.desc)
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
}
}
.layoutWeight(1)
.alignItems(HorizontalAlign.Start)
Blank()
if (this.showToggle) {
Toggle({ type: ToggleType.Switch, isOn: this.isOn })
.selectedColor($r('app.color.brand'))
.onChange((v: boolean) => {
this.onToggle(v);
})
} else if (this.valueText.length > 0) {
Text(this.valueText)
.fontSize(FontSize.body)
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.brand'))
}
}
.width('100%')
.constraintSize({ minHeight: 48 })
.padding({ top: 10, bottom: 10 })
}
}
@Component
export struct EmptyView {
@Prop sym: Resource = $r('sys.symbol.circle');
@Prop title: string = '暂无内容';
@Prop sub: string = '';
build() {
Column({ space: 10 }) {
SymIcon({
sym: this.sym,
iconSize: 44,
colorRes: $r('app.color.font_ter')
})
Text(this.title)
.fontSize(FontSize.sub)
.fontColor($r('app.color.font_sec'))
if (this.sub.length > 0) {
Text(this.sub)
.fontSize(FontSize.cap)
.fontColor($r('app.color.font_ter'))
.textAlign(TextAlign.Center)
}
}
.width('100%')
.padding({ top: 56, bottom: 56 })
}
}
@Component
export struct PrimaryButton {
@Prop label: string = '';
@Prop isEnabled: boolean = true;
onTap: () => void = () => {};
build() {
Button(this.label)
.fontSize(FontSize.body)
.fontWeight(FontWeight.Medium)
.fontColor(this.isEnabled ? $r('app.color.on_brand') : $r('app.color.font_ter'))
.backgroundColor(this.isEnabled ? $r('app.color.brand') : $r('app.color.chip_bg'))
.height(Dim.btnHeight)
.borderRadius(Dim.btnRadius)
.width('100%')
.enabled(this.isEnabled)
.onClick(() => {
if (this.isEnabled) {
this.onTap();
}
})
}
}
@Builder
function emptyBuilder() {
}
/**
* 悬浮工具栏(HarmonyOS 6.1+ 悬浮工具栏样式):胶囊容器悬浮于页面底部,
* 容器使用沉浸光感 THIN 材质,并在其下方铺一层与页面背景同色的渐变蒙层(高出栏顶 16vp)。
* 需放在页面根 Stack 的底部对齐位置,内容区自行预留 Insets.contentBottom() 的底部空间。
*/
@Component
export struct FloatingToolbar {
@StorageProp(InsetKey.BOTTOM) bottomInset: number = 0;
@BuilderParam content: () => void = emptyBuilder;
build() {
Stack({ alignContent: Alignment.Bottom }) {
// 渐变颜色蒙层:不拦截触摸,内容滚动至栏下时自然衰减
Column()
.width('100%')
.height(Insets.contentBottom(this.bottomInset))
.linearGradient({
direction: GradientDirection.Bottom,
colors: [[$r('app.color.page_bg_clear'), 0], [$r('app.color.page_bg_mask'), 0.7]]
})
.hitTestBehavior(HitTestMode.None)
Column() {
Row({ space: 4 }) {
this.content()
}
.width('100%')
.height(Dim.floatBarH)
.constraintSize({ maxWidth: 480 })
.padding({ left: 8, right: 8 })
.borderRadius(Dim.floatBarH / 2)
.systemMaterial(floatingBarMaterial())
}
.width('100%')
.padding({ left: Dim.pagePad, right: Dim.pagePad, bottom: Insets.floatBarBottom(this.bottomInset) })
}
.width('100%')
.hitTestBehavior(HitTestMode.Transparent)
}
}
/** 悬浮工具栏中的操作项:普通项为文本 + 图标,primary 为品牌色胶囊主操作 */
@Component
export struct ToolbarAction {
@Prop label: string = '';
@Prop sym: Resource | undefined = undefined;
@Prop primary: boolean = false;
@Prop danger: boolean = false;
@Prop isEnabled: boolean = true;
onTap: () => void = () => {};
private fg(): ResourceColor {
if (!this.isEnabled) {
return $r('app.color.font_ter');
}
if (this.primary) {
return $r('app.color.on_brand');
}
return this.danger ? $r('app.color.err') : $r('app.color.font_pri');
}
build() {
Button({ type: ButtonType.Capsule, stateEffect: this.isEnabled }) {
Row({ space: 6 }) {
if (this.sym !== undefined) {
SymbolGlyph(this.sym)
.fontSize(18)
.fontColor([this.fg()])
}
Text(this.label)
.fontSize(FontSize.sub)
.fontWeight(this.primary ? FontWeight.Medium : FontWeight.Normal)
.fontColor(this.fg())
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
}
.padding({ left: 14, right: 14 })
}
.height(40)
.layoutWeight(this.primary ? 1.4 : 1)
.backgroundColor(this.primary
? (this.isEnabled ? $r('app.color.brand') : $r('app.color.chip_bg'))
: Color.Transparent)
.enabled(this.isEnabled)
.onClick(() => {
if (this.isEnabled) {
this.onTap();
}
})
}
}
+47
View File
@@ -0,0 +1,47 @@
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
/**
* 内容哈希:优先 SHA-256(cryptoFramework),失败时回退 64 位 FNV-1a。
* 供 TaskPool 并发任务导入使用。
*/
export async function sha256Hash32(data: ArrayBuffer): Promise<string> {
try {
const md = cryptoFramework.createMd('SHA-256');
await md.update({ data: new Uint8Array(data) });
const digest = await md.digest();
const u8 = digest.data;
let s = '';
const limit = Math.min(16, u8.length);
for (let i = 0; i < limit; i++) {
let hx = u8[i].toString(16);
if (hx.length < 2) {
hx = '0' + hx;
}
s += hx;
}
return s;
} catch (e) {
return fnvHashHex(data);
}
}
export function fnvHashHex(data: ArrayBuffer): string {
const u8 = new Uint8Array(data);
let h1: number = 0x811c9dc5;
let h2: number = 0x01000193;
for (let i = 0; i < u8.length; i++) {
h1 = (h1 ^ u8[i]) >>> 0;
h1 = (h1 * 0x01000193) >>> 0;
h2 = (h2 + u8[i] + i) >>> 0;
h2 = (h2 ^ (h2 << 7)) >>> 0;
h2 = (h2 ^ (h2 >>> 3)) >>> 0;
}
const hex = (v: number): string => {
let s = (v >>> 0).toString(16);
while (s.length < 8) {
s = '0' + s;
}
return s;
};
return hex(h1) + hex(h2);
}
+107
View File
@@ -0,0 +1,107 @@
import { httpGetText, httpGetBinary, sniffImageExt } from '../net/HttpUtil';
import { parseChapterContent } from '../core/EsjCore';
import { fetchChapterLines, LkApiCfg } from '../core/LkCore';
import { sha256Hash32 } from './HashUtil';
/**
* TaskPool 并发任务:章节抓取 + 图片抓取。
* 返回纯数据对象(可跨线程序列化),转换与落盘由主线程完成。
*/
export interface FetchChapterArgs {
url: string;
cookie: string;
timeoutMs: number;
retry: number;
}
export interface FetchChapterResult {
ok: boolean;
status: string; // ok | locked | error
lines: string[];
error: string;
}
export interface FetchImageArgs {
url: string;
cookie: string;
timeoutMs: number;
retry: number;
}
export interface FetchImageResult {
ok: boolean;
ext: string;
hash: string;
data: ArrayBuffer;
error: string;
}
@Concurrent
export async function fetchChapterJob(args: FetchChapterArgs): Promise<FetchChapterResult> {
const resp = await httpGetText(args.url, args.cookie, args.timeoutMs, args.retry);
if (!resp.ok) {
const r: FetchChapterResult = { ok: false, status: 'error', lines: [], error: resp.error };
return r;
}
try {
const content = parseChapterContent(resp.text);
const r2: FetchChapterResult =
{ ok: true, status: content.status, lines: content.lines, error: content.error };
return r2;
} catch (e) {
const r3: FetchChapterResult = { ok: false, status: 'error', lines: [], error: '解析失败: ' + (e as Error).message };
return r3;
}
}
@Concurrent
export async function fetchImageJob(args: FetchImageArgs): Promise<FetchImageResult> {
const resp = await httpGetBinary(args.url, args.cookie, args.timeoutMs, args.retry);
if (!resp.ok) {
const r: FetchImageResult = { ok: false, ext: '', hash: '', data: new ArrayBuffer(0), error: resp.error };
return r;
}
const ext = sniffImageExt(resp.data, resp.contentType);
if (ext.length === 0 || resp.data.byteLength === 0) {
const r2: FetchImageResult = { ok: false, ext: '', hash: '', data: new ArrayBuffer(0), error: '无法识别的图片类型: ' + resp.contentType };
return r2;
}
const hash = await sha256Hash32(resp.data);
const r3: FetchImageResult = { ok: true, ext: ext, hash: hash, data: resp.data, error: '' };
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-h6 标题(长文拆分用)
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, error: parsed.error };
return r;
} catch (e) {
const r2: FetchLkChapterResult = { ok: false, status: 'error', lines: [], heads: [], error: (e as Error).message };
return r2;
}
}
+30 -2
View File
@@ -11,6 +11,18 @@
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:main_pages",
"metadata": [
{
// 沉浸光感:Dialog、Toast、Toggle、Slider 等组件默认启用沉浸式系统材质(需 targetAPIVersion >= 26)
"name": "ohos.arkui.UIMaterial.state",
"value": "enable"
}
],
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
],
"abilities": [
{
"name": "EntryAbility",
@@ -29,6 +41,22 @@
"actions": [
"ohos.want.action.home"
]
},
{
"entities": [
"entity.system.view"
],
"actions": [
"ohos.want.action.viewData"
],
"uris": [
{ "scheme": "https", "host": "www.esjzone.cc" },
{ "scheme": "https", "host": "www.esjzone.one" },
{ "scheme": "https", "host": "esjzone.cc" },
{ "scheme": "https", "host": "esjzone.one" },
{ "scheme": "https", "host": "www.lightnovel.fun" },
{ "scheme": "https", "host": "lightnovel.fun" }
]
}
]
}
@@ -44,8 +72,8 @@
"name": "ohos.extension.backup",
"resource": "$profile:backup_config"
}
],
]
}
]
}
}
}
@@ -2,7 +2,79 @@
"color": [
{
"name": "start_window_background",
"value": "#F1F3F5"
},
{
"name": "page_bg",
"value": "#F1F3F5"
},
{
"name": "page_bg_clear",
"value": "#00F1F3F5"
},
{
"name": "page_bg_mask",
"value": "#CCF1F3F5"
},
{
"name": "card_bg",
"value": "#FFFFFF"
},
{
"name": "input_bg",
"value": "#F1F3F5"
},
{
"name": "chip_bg",
"value": "#0D182431"
},
{
"name": "brand",
"value": "#0A59F7"
},
{
"name": "brand_soft",
"value": "#140A59F7"
},
{
"name": "on_brand",
"value": "#FFFFFF"
},
{
"name": "font_pri",
"value": "#E5000000"
},
{
"name": "font_sec",
"value": "#99000000"
},
{
"name": "font_ter",
"value": "#66000000"
},
{
"name": "ok",
"value": "#3EA230"
},
{
"name": "warn",
"value": "#D97E00"
},
{
"name": "err",
"value": "#E84026"
},
{
"name": "divider",
"value": "#14000000"
},
{
"name": "btn_secondary_bg",
"value": "#0D182431"
},
{
"name": "log_bg",
"value": "#F7F8FA"
}
]
}
}
@@ -2,15 +2,15 @@
"string": [
{
"name": "module_desc",
"value": "module description"
"value": "ESJZone novel downloader"
},
{
"name": "EntryAbility_desc",
"value": "description"
"value": "ESJZone novel downloader"
},
{
"name": "EntryAbility_label",
"value": "label"
"value": "ESJ下载器"
}
]
}
@@ -3,6 +3,78 @@
{
"name": "start_window_background",
"value": "#000000"
},
{
"name": "page_bg",
"value": "#000000"
},
{
"name": "page_bg_clear",
"value": "#00000000"
},
{
"name": "page_bg_mask",
"value": "#99000000"
},
{
"name": "card_bg",
"value": "#1C1C1E"
},
{
"name": "input_bg",
"value": "#141416"
},
{
"name": "chip_bg",
"value": "#1F1F22"
},
{
"name": "brand",
"value": "#317AF7"
},
{
"name": "brand_soft",
"value": "#33317AF7"
},
{
"name": "on_brand",
"value": "#FFFFFF"
},
{
"name": "font_pri",
"value": "#E6FFFFFF"
},
{
"name": "font_sec",
"value": "#99FFFFFF"
},
{
"name": "font_ter",
"value": "#66FFFFFF"
},
{
"name": "ok",
"value": "#64BB5C"
},
{
"name": "warn",
"value": "#F7BA1E"
},
{
"name": "err",
"value": "#F55A45"
},
{
"name": "divider",
"value": "#1FFFFFFF"
},
{
"name": "btn_secondary_bg",
"value": "#1F1F22"
},
{
"name": "log_bg",
"value": "#141416"
}
]
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,482 @@
# Open Chinese Convert (OpenCC) Dictionary
# File: TSPhrases.txt
# License: Apache-2.0 (see LICENSE)
# Source: https://github.com/BYVoid/OpenCC
一坏 一坯
一目瞭然 一目了然
七逕 七迳
上逕 上迳
上鍊 上链
不可貲計 不可赀計
不瞭解 不了解
么麼 幺麽
么麽 幺麽
九逕山 九迳山
乾乾淨淨 干干净净
乾乾脆脆 干干脆脆
乾佑縣 乾佑县
乾元 乾元
乾卦 乾卦
乾嘉 乾嘉
乾圖 乾图
乾坤 乾坤
乾坤一擲 乾坤一掷
乾坤再造 乾坤再造
乾坤大挪移 乾坤大挪移
乾宅 乾宅
乾安縣 乾安县
乾安鎮 乾安镇
乾州 乾州
乾斷 乾断
乾斷食 干断食
乾旦 乾旦
乾曜 乾曜
乾清宮 乾清宫
乾盛世 乾盛世
乾紅 干红 乾红
乾綱 乾纲
乾縣 乾县
乾象 乾象
乾造 乾造
乾道 乾道
乾闥婆 乾闼婆
乾陵 乾陵
乾隆 乾隆
乾隆年間 乾隆年间
乾隆皇帝 乾隆皇帝
二噁英 二𫫇英
仇讎 仇雠
以免藉口 以免借口
以功覆過 以功覆过
任筆沈詩 任笔沈诗
侔德覆載 侔德覆载
傢俱 家具
傷亡枕藉 伤亡枕藉
允祕 允祕
八濛山 八濛山
其陰多蒐 其阴多蒐
凌藉 凌借
出醜狼藉 出丑狼藉
函覆 函复
剋架 剋架
剋毒 剋毒
千鍾粟 千锺粟
南氾 南氾
南逕 南迳
反反覆覆 反反复复
反覆 反复
反覆思維 反复思维
反覆思量 反复思量
反覆性 反复性
名覆金甌 名复金瓯
吳祕 吴祕
吳育昇 吴育昇
哪吒 哪吒
回覆 回复
土坏 土坯
坏土 坯土
坏子 坯子
坏布 坯布
坏戶 坯户
墨沈沈 墨沉沉
壺裏乾坤 壶里乾坤
大目乾連冥間救母變文 大目乾连冥间救母变文
宫商角徵羽 宫商角徵羽
射覆 射覆
尼乾子 尼乾子
尼乾陀 尼乾陀
年釐 年釐
幺麼 幺麽
幺麼小丑 幺麽小丑
幺麼小醜 幺麽小丑
康乾 康乾
張昇 张昇
張法乾 张法乾
彷彿 仿佛
彷徨 彷徨
徐胤昇 徐胤昇
復甦 复苏
徵弦 徵弦
徵絃 徵弦
徵羽摩柯 徵羽摩柯
徵聲 徵声
徵調 徵调
徵音 徵音
情有獨鍾 情有独钟 情有独锺
想像 想像 想象
意志消沈 意志消沉
慰藉 慰藉
慰藉着 慰藉着
憑藉 凭借
憑藉着 凭借着
懷釐 怀釐
成甦 成甦
所費不貲 所费不赀
手鍊 手链
打坏 打坯
扞格 扞格
扭轉乾坤 扭转乾坤
批覆 批复
找藉口 找借口
折戟沈沙 折戟沉沙
折戟沈河 折戟沉河
拉坏 拉坯
拉鍊 拉链
拉鍊工程 拉链工程
拜覆 拜复
挨剋 挨剋
捏坏 捏坯
擊沈 击沉
據瞭解 据了解
文錦覆阱 文锦覆阱
於世成 於世成
於乎 於乎
於仲完 於仲完
於倫 於伦
於其一 於其一
於則 於则
於勇明 於勇明
於呼哀哉 於呼哀哉
於單 於单
於坦 於坦
於崇文 於崇文
於忠祥 於忠祥
於惟一 於惟一
於戲 於戏
於敖 於敖
於梨華 於梨华
於清言 於清言
於潛 於潜
於琳 於琳
於穆 於穆
於竹屋 於竹屋
於菟 於菟
於邑 於邑
於陵子 於陵子
旋乾轉坤 旋乾转坤
旋轉乾坤 旋转乾坤
旋轉乾坤之力 旋转乾坤之力
明瞭 明了
明覆 明复
昏沈 昏沉
春蒐 春蒐
春釐 春釐
暗沈沈 暗沉沉
書中自有千鍾粟 书中自有千锺粟
有序 有序
朝乾夕惕 朝乾夕惕
木吒 木吒
李乾德 李乾德
李昇 李昇
李昇勳 李昇勋
李澤鉅 李泽钜
李祕 李祕
李鍊福 李链福
李鍾郁 李锺郁
束脩 束脩 束修
東氾 东氾
林甦 林甦
校讎 校雠
梁昇卿 梁昇卿 梁升卿
梁章鉅 梁章钜
楊甦棣 杨甦棣
楊聯陞 杨联陞
樊於期 樊於期
橡椀 橡椀
死氣沈沈 死气沉沉
段脩 段脩
毛坏 毛坯
水逕 水迳
氾勝之 氾胜之
氾南 氾南
氾國 氾国
氾水 氾水
沈下 沉下
沈不住氣 沉不住气
沈住氣 沉住气
沈冤 沉冤
沈厚 沉厚
沈吟 沉吟
沈寂 沉寂
沈得住氣 沉得住气
沈思 沉思
沈思往事 沉思往事
沈悶 沉闷
沈沒 沉没
沈沒成本 沉没成本
沈浮 沉浮
沈浸 沉浸
沈浸於 沉浸于
沈淪 沉沦
沈湎 沉湎
沈湎酒色 沉湎酒色
沈溺 沉溺
沈滯 沉滞
沈滯性 沉滞性
沈澱 沉淀
沈澱出來 沉淀出来
沈澱劑 沉淀剂
沈澱法 沉淀法
沈澱物 沉淀物
沈濁 沉浊
沈甸甸 沉甸甸
沈痛 沉痛
沈痼 沉痼
沈痾 沉疴
沈睡 沉睡
沈睡不醒 沉睡不醒
沈砂池 沉砂池
沈積 沉积
沈積岩 沉积岩
沈積石 沉积石
沈筒 沉筒
沈船 沉船
沈落 沉落
沈詩任筆 沈诗任笔
沈迷 沉迷
沈迷不醒 沉迷不醒
沈醉 沉醉
沈重 沉重
沈降 沉降
沈陷 沉陷
沈靜 沉静
沈靜下來 沉静下来
沈香 沉香
沈鬱 沉郁
沈魚落雁 沉鱼落雁
沈默 沉默
沈默不語 沉默不语
沈默寡言 沉默寡言
沙逕 沙迳
河逕 河迳
流徵 流徵
浪蕩乾坤 浪荡乾坤
浮沈 浮沉
海哩 海里
深沈 深沉
深沈不露 深沉不露
溫昇豪 温昇豪
滑藉 滑借
烏昇 乌昇
烏沈沈 乌沉沉
烏逕 乌迳
無序 无序
狐藉虎威 狐借虎威
王彥昇 王彦昇
珍珠項鍊 珍珠项链
甚鉅 甚钜
甦生 苏生
甦醒 苏醒
申昇勳 申昇勋
申覆 申复
畢昇 毕昇
發覆 发覆
盧象昇 卢象昇
目劄 目劄
瞭哨 瞭哨
瞭如 了如
瞭如指掌 了如指掌
瞭望 瞭望
瞭然 了然
瞭然於心 了然于心
瞭若指掌 了若指掌
瞭解 了解
瞭解到 了解到
破釜沈舟 破釜沉舟
磚坏 砖坯
示覆 示复
社逕 社迳
祕丕笈 祕丕笈
祕彭祖 祕彭祖
祕瓊 祕琼
祝釐 祝釐
神祇 神祇
稟覆 禀复
竺乾 竺乾
答覆 答复
篤麼 笃麽
簡單明瞭 简单明了
籌畫 筹划
素藉 素借
老態龍鍾 老态龙钟 老态龙锺
耳沈 耳沉
肉脩 肉脩
肘手鍊足 肘手链足
胤祕 胤祕
脩敬 脩敬
脩炳 脩炳
脩脡 脩脡
脩脯 脩脯
脩金 脩金
脫坏 脱坯
腶脩 腶脩
英哩 英里
茅蒐 茅蒐
茵藉 茵借
萬鍾 万锺
落雁沈魚 落雁沉鱼
蒐于紅 蒐于红
蒐於紅 蒐于红
蒐狩 蒐狩
蒐獮 蒐狝
蒐獵 蒐猎
蒐田 蒐田
蒐畋 蒐畋
蒐苗 蒐苗
蒜薹 蒜薹
蔣昇 蒋昇
蕓薹 芸薹
蕩覆 荡覆
蕭乾 萧乾
藉代 借代
藉以 借以
藉助 借助
藉助於 借助于
藉卉 借卉
藉口 借口
藉喻 借喻
藉寇兵 借寇兵
藉寇兵齎盜糧 借寇兵赍盗粮
藉手 借手
藉據 借据
藉故 借故
藉故推辭 借故推辞
藉方 借方
藉條 借条
藉槁 借槁
藉機 借机
藉此 借此
藉此機會 借此机会
藉甚 借甚
藉由 借由
藉着 借着
藉端 借端
藉端生事 借端生事
藉箸代籌 借箸代筹
藉草枕塊 借草枕块
藉藉 藉藉
藉藉无名 藉藉无名
藉詞 借词
藉讀 借读
藉資 借资
衹得 只得
衹見樹木 只见树木
衹見樹木不見森林 只见树木不见森林
袁祕 袁祕
袖裏乾坤 袖里乾坤
袷袢 袷袢
製坏 制坯
覆上 覆上
覆住 覆住
覆信 复信
覆冒 覆冒
覆呈 复呈
覆命 复命
覆墓 复墓
覆宗 覆宗
覆帳 复帐
覆幬 覆帱
覆成 覆成
覆按 复按
覆文 复文
覆杯 覆杯
覆校 复校
覆瓿 覆瓿
覆盂 覆盂
覆盆 覆盆
覆盆子 覆盆子
覆盤 覆盘
覆育 覆育
覆蕉尋鹿 覆蕉寻鹿
覆逆 覆逆
覆醢 覆醢
覆醬瓿 覆酱瓿
覆電 复电
覆露 覆露
覆鹿尋蕉 覆鹿寻蕉
覆鹿遺蕉 覆鹿遗蕉
覆鼎 覆鼎
見覆 见复
角徵 角徵
角徵羽 角徵羽
計畫 计划
許甦魂 许甦魂
變徵 变徵
變徵之聲 变徵之声
變徵之音 变徵之音
讎定 雠定
谿工 谿工
貂覆額 貂覆额
買臣覆水 买臣覆水
赤石逕 赤石迳
踅門瞭戶 踅门了户
躪藉 躏借
載沈載浮 载沉载浮
載浮載沈 载浮载沉
辛祕 辛祕
逆釐 逆釐
逕口 迳口
逕聯 迳联
逕頭 迳头
郭子乾 郭子乾
酒逢知己千鍾少 酒逢知己千锺少
醞藉 酝借
重覆 重复
金吒 金吒
金昇玟 金昇玟
金鍊 金链
鈞覆 钧复
鉅子 钜子
鉅萬 钜万
鉅防 钜防
鉸鍊 铰链
銀鍊 银链
鋼坏 钢坯
錢鍾書 钱锺书
鍊墜 链坠
鍊子 链子
鍊形 链形
鍊條 链条
鍊錘 链锤
鍊鎖 链锁
鍛鍾 锻锺
鍾繇 锺繇 钟繇
鍾萬梅 锺万梅
鍾重發 锺重发
鍾鍛 锺锻
鍾馗 锺馗
鎖鍊 锁链
鐵鍊 铁链
鑽石項鍊 钻石项链
鑿坏 凿坯
閻鶴昇 阎鹤昇
陰沈 阴沉
陰沈沈 阴沉沉
陰陰沈沈 阴阴沉沉
陳志昇 陈志昇
陳昇 陈昇
陳甦 陈甦
陶坏 陶坯
雁杳魚沈 雁杳鱼沉
雖覆能復 虽覆能复
電覆 电复
露覆 露覆
韓昇延 韩昇延
韓甦 韩甦
項鍊 项链
頗覆 颇覆
頸鍊 颈链
顛乾倒坤 颠乾倒坤
顛倒乾坤 颠倒乾坤
顧藉 顾借
馮甦 冯甦
魏徵 魏徵 魏征
魚沈雁杳 鱼沉雁杳
麪坏兒 面坯儿
麼些族 麽些族
黃甦 黄甦
黃鍾公 黄锺公
黑沈沈 黑沉沉
龍鍾 龙钟 龙锺
龔昇 龚昇
+4 -3
View File
@@ -1,6 +1,7 @@
// @ts-nocheck – Template file, only used when copied into a project directory
import { appTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins: [] /* Custom plugin to extend the functionality of Hvigor. */
}
system: appTasks /* Built-in plugin of Hvigor. It cannot be modified. */,
plugins: [] /* Custom plugin to extend the functionality of Hvigor. */,
};