feat: 书籍链接解析下载
This commit is contained in:
+20
@@ -0,0 +1,20 @@
|
|||||||
|
/node_modules
|
||||||
|
/oh_modules
|
||||||
|
/local.properties
|
||||||
|
/.idea
|
||||||
|
**/build
|
||||||
|
/.hvigor
|
||||||
|
.cxx
|
||||||
|
/.clangd
|
||||||
|
/.clang-format
|
||||||
|
/.clang-tidy
|
||||||
|
**/.test
|
||||||
|
/.appanalyzer
|
||||||
|
/.work
|
||||||
|
oh-package-lock.json5
|
||||||
|
*.hap
|
||||||
|
*.hsp
|
||||||
|
*.har
|
||||||
|
/build-profile.json5
|
||||||
|
.DS_Store
|
||||||
|
.npmrc
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"app": {
|
||||||
|
"bundleName": "com.esj.downloader",
|
||||||
|
"vendor": "example",
|
||||||
|
"versionCode": 1000000,
|
||||||
|
"versionName": "1.0.0",
|
||||||
|
"icon": "$media:layered_image",
|
||||||
|
"label": "$string:app_name"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"string": [
|
||||||
|
{
|
||||||
|
"name": "app_name",
|
||||||
|
"value": "ESJ下载器"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 6.3 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 160 KiB |
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"layered-image":
|
||||||
|
{
|
||||||
|
"background" : "$media:background",
|
||||||
|
"foreground" : "$media:foreground"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
{
|
||||||
|
"files": [
|
||||||
|
"**/*.ets"
|
||||||
|
],
|
||||||
|
"ignore": [
|
||||||
|
"**/src/ohosTest/**/*",
|
||||||
|
"**/src/test/**/*",
|
||||||
|
"**/src/mock/**/*",
|
||||||
|
"**/node_modules/**/*",
|
||||||
|
"**/oh_modules/**/*",
|
||||||
|
"**/build/**/*",
|
||||||
|
"**/.preview/**/*"
|
||||||
|
],
|
||||||
|
"ruleSet": [
|
||||||
|
"plugin:@performance/recommended",
|
||||||
|
"plugin:@typescript-eslint/recommended"
|
||||||
|
],
|
||||||
|
"rules": {
|
||||||
|
"@security/no-unsafe-aes": "error",
|
||||||
|
"@security/no-unsafe-hash": "error",
|
||||||
|
"@security/no-unsafe-mac": "warn",
|
||||||
|
"@security/no-unsafe-dh": "error",
|
||||||
|
"@security/no-unsafe-dsa": "error",
|
||||||
|
"@security/no-unsafe-ecdsa": "error",
|
||||||
|
"@security/no-unsafe-rsa-encrypt": "error",
|
||||||
|
"@security/no-unsafe-rsa-sign": "error",
|
||||||
|
"@security/no-unsafe-rsa-key": "error",
|
||||||
|
"@security/no-unsafe-dsa-key": "error",
|
||||||
|
"@security/no-unsafe-dh-key": "error",
|
||||||
|
"@security/no-unsafe-3des": "error"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
/node_modules
|
||||||
|
/oh_modules
|
||||||
|
/.preview
|
||||||
|
/build
|
||||||
|
/.cxx
|
||||||
|
/.test
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
{
|
||||||
|
"apiType": "stageMode",
|
||||||
|
"buildOption": {
|
||||||
|
"resOptions": {
|
||||||
|
"copyCodeResource": {
|
||||||
|
"enable": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"buildOptionSet": [
|
||||||
|
{
|
||||||
|
"name": "release",
|
||||||
|
"arkOptions": {
|
||||||
|
"obfuscation": {
|
||||||
|
"ruleOptions": {
|
||||||
|
"enable": false,
|
||||||
|
"files": [
|
||||||
|
"./obfuscation-rules.txt"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"name": "default"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "ohosTest",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +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. */,
|
||||||
|
};
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# Define project specific obfuscation rules here.
|
||||||
|
# You can include the obfuscation configuration files in the current module's build-profile.json5.
|
||||||
|
|
||||||
|
# Obfuscation options:
|
||||||
|
# -disable-obfuscation: disable all obfuscations
|
||||||
|
# -enable-property-obfuscation: obfuscate the property names
|
||||||
|
# -enable-toplevel-obfuscation: obfuscate the names in the global scope
|
||||||
|
# -compact: remove unnecessary blank spaces and all line feeds
|
||||||
|
# -remove-log: remove all console.* statements
|
||||||
|
# -print-namecache: print the name cache that contains the mapping from the old names to new names
|
||||||
|
# -apply-namecache: reuse the given cache file
|
||||||
|
|
||||||
|
# Keep options:
|
||||||
|
# -keep-property-name: specifies property names that you want to keep
|
||||||
|
# -keep-global-name: specifies names that you want to keep in the global scope
|
||||||
|
|
||||||
|
-enable-property-obfuscation
|
||||||
|
-enable-toplevel-obfuscation
|
||||||
|
-enable-filename-obfuscation
|
||||||
|
-enable-export-obfuscation
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"name": "entry",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "Please describe the basic information.",
|
||||||
|
"main": "",
|
||||||
|
"author": "",
|
||||||
|
"license": "",
|
||||||
|
"dependencies": {}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
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.indexOf('esjzone') >= 0 && v.startsWith('http')) {
|
||||||
|
url = v;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (url !== '' && url.indexOf('esjzone') >= 0) {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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';
|
||||||
|
}
|
||||||
@@ -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, '&');
|
||||||
|
out = out.replace(/</g, '<');
|
||||||
|
out = out.replace(/>/g, '>');
|
||||||
|
out = out.replace(/"/g, '"');
|
||||||
|
out = out.replace(/'/g, ''');
|
||||||
|
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);
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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(/ /g, '\u00A0');
|
||||||
|
out = out.replace(/</g, '<');
|
||||||
|
out = out.replace(/>/g, '>');
|
||||||
|
out = out.replace(/"/g, '"');
|
||||||
|
out = out.replace(/'/g, '\'');
|
||||||
|
out = out.replace(/'/g, '\'');
|
||||||
|
out = out.replace(/&/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);
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
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 {
|
||||||
|
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
|
||||||
|
|
||||||
|
windowStage.loadContent('pages/Index', (err) => {
|
||||||
|
if (err.code) {
|
||||||
|
hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
|
||||||
|
this.trackAvoidArea(windowStage);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 页面内容沉浸到状态栏与导航条下方,记录两者高度(vp)供标题栏 / 悬浮栏避让 */
|
||||||
|
private trackAvoidArea(windowStage: window.WindowStage): void {
|
||||||
|
try {
|
||||||
|
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 {
|
||||||
|
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
|
||||||
|
}
|
||||||
|
|
||||||
|
onForeground(): void {
|
||||||
|
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
|
||||||
|
}
|
||||||
|
|
||||||
|
onBackground(): void {
|
||||||
|
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
/*
|
||||||
|
* 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';
|
||||||
|
|
||||||
|
const DOMAIN = 0x0000;
|
||||||
|
|
||||||
|
export default class EntryBackupAbility extends BackupExtensionAbility {
|
||||||
|
async onBackup() {
|
||||||
|
hilog.info(DOMAIN, 'testTag', 'onBackup ok');
|
||||||
|
await Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
async onRestore(bundleVersion: BundleVersion) {
|
||||||
|
hilog.info(DOMAIN, 'testTag', 'onRestore ok %{public}s', JSON.stringify(bundleVersion));
|
||||||
|
await Promise.resolve();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import { preferences } from '@kit.ArkData';
|
||||||
|
import { common } from '@kit.AbilityKit';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 应用配置:对应原脚本开头全部参数,全部页面可配置并持久化。
|
||||||
|
* - siteUrl -> base_url
|
||||||
|
* - cookie -> esj.txt 第一行(含 ews_key / ews_token)
|
||||||
|
* - convertMode -> opencc t2s / s2t / none
|
||||||
|
* - threadCount -> threadNum(并发数)
|
||||||
|
* - retryCount -> retrying stop_max_attempt_number
|
||||||
|
* - timeoutSec -> requests timeout
|
||||||
|
* - downloadImages / downloadCover / outputEpub / outputTxt -> 输出控制
|
||||||
|
*/
|
||||||
|
export const CONVERT_T2S: string = 't2s';
|
||||||
|
export const CONVERT_S2T: string = 's2t';
|
||||||
|
export const CONVERT_NONE: string = 'none';
|
||||||
|
|
||||||
|
export interface AppSettings {
|
||||||
|
siteUrl: string;
|
||||||
|
cookie: string;
|
||||||
|
convertMode: string;
|
||||||
|
threadCount: number;
|
||||||
|
retryCount: number;
|
||||||
|
timeoutSec: number;
|
||||||
|
downloadImages: boolean;
|
||||||
|
downloadCover: boolean;
|
||||||
|
outputEpub: boolean;
|
||||||
|
outputTxt: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function defaultSettings(): AppSettings {
|
||||||
|
const s: AppSettings = {
|
||||||
|
siteUrl: 'https://www.esjzone.cc/',
|
||||||
|
cookie: '',
|
||||||
|
convertMode: CONVERT_T2S,
|
||||||
|
threadCount: 2,
|
||||||
|
retryCount: 3,
|
||||||
|
timeoutSec: 25,
|
||||||
|
downloadImages: true,
|
||||||
|
downloadCover: true,
|
||||||
|
outputEpub: true,
|
||||||
|
outputTxt: true
|
||||||
|
};
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ConfigStore {
|
||||||
|
private static prefs: preferences.Preferences | null = null;
|
||||||
|
private static cache: AppSettings | null = null;
|
||||||
|
|
||||||
|
static async init(ctx: common.Context): Promise<void> {
|
||||||
|
ConfigStore.prefs = await preferences.getPreferences(ctx, 'esj_config');
|
||||||
|
const raw = ConfigStore.prefs.getSync('settings_json', '') as string;
|
||||||
|
const base = defaultSettings();
|
||||||
|
if (raw.length > 0) {
|
||||||
|
try {
|
||||||
|
const obj = JSON.parse(raw) as Record<string, Object>;
|
||||||
|
base.siteUrl = strOf(obj, 'siteUrl', base.siteUrl);
|
||||||
|
base.cookie = strOf(obj, 'cookie', base.cookie);
|
||||||
|
base.convertMode = strOf(obj, 'convertMode', base.convertMode);
|
||||||
|
base.threadCount = numOf(obj, 'threadCount', base.threadCount);
|
||||||
|
base.retryCount = numOf(obj, 'retryCount', base.retryCount);
|
||||||
|
base.timeoutSec = numOf(obj, 'timeoutSec', base.timeoutSec);
|
||||||
|
base.downloadImages = boolOf(obj, 'downloadImages', base.downloadImages);
|
||||||
|
base.downloadCover = boolOf(obj, 'downloadCover', base.downloadCover);
|
||||||
|
base.outputEpub = boolOf(obj, 'outputEpub', base.outputEpub);
|
||||||
|
base.outputTxt = boolOf(obj, 'outputTxt', base.outputTxt);
|
||||||
|
} catch (e) {
|
||||||
|
// 配置损坏时使用默认值
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ConfigStore.cache = base;
|
||||||
|
}
|
||||||
|
|
||||||
|
static get(): AppSettings {
|
||||||
|
if (ConfigStore.cache === null) {
|
||||||
|
ConfigStore.cache = defaultSettings();
|
||||||
|
}
|
||||||
|
return ConfigStore.cache;
|
||||||
|
}
|
||||||
|
|
||||||
|
static async save(s: AppSettings): Promise<void> {
|
||||||
|
ConfigStore.cache = s;
|
||||||
|
if (ConfigStore.prefs === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ConfigStore.prefs.putSync('settings_json', JSON.stringify(s));
|
||||||
|
await ConfigStore.prefs.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** cookie 是否包含关键登录字段 */
|
||||||
|
static cookieOk(cookie: string): boolean {
|
||||||
|
return cookie.indexOf('ews_key') >= 0 && cookie.indexOf('ews_token') >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 清理 cookie 字符串:去掉换行、首尾空格 */
|
||||||
|
static cleanCookie(cookie: string): string {
|
||||||
|
return cookie.replace(/\r?\n/g, '').trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function strOf(obj: Record<string, Object>, key: string, def: string): string {
|
||||||
|
const v = obj[key];
|
||||||
|
return typeof v === 'string' ? v : def;
|
||||||
|
}
|
||||||
|
|
||||||
|
function numOf(obj: Record<string, Object>, key: string, def: number): number {
|
||||||
|
const v = obj[key];
|
||||||
|
return typeof v === 'number' ? v : def;
|
||||||
|
}
|
||||||
|
|
||||||
|
function boolOf(obj: Record<string, Object>, key: string, def: boolean): boolean {
|
||||||
|
const v = obj[key];
|
||||||
|
return typeof v === 'boolean' ? v : def;
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { TocPreviewNode } from './TaskModel';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单本下载的"选章 + 自定义标题"草稿。
|
||||||
|
* 与目标 URL 绑定;URL 变化时自动清空,避免串书。
|
||||||
|
*/
|
||||||
|
export class DownloadDraft {
|
||||||
|
static url: string = '';
|
||||||
|
static customTitle: string = '';
|
||||||
|
static chapterFilter: number[] = []; // 空 = 全部章节
|
||||||
|
static nodes: TocPreviewNode[] = []; // 已抓取的目录缓存
|
||||||
|
static bookName: string = '';
|
||||||
|
static author: string = '';
|
||||||
|
|
||||||
|
static reset(): void {
|
||||||
|
DownloadDraft.url = '';
|
||||||
|
DownloadDraft.customTitle = '';
|
||||||
|
DownloadDraft.chapterFilter = [];
|
||||||
|
DownloadDraft.nodes = [];
|
||||||
|
DownloadDraft.bookName = '';
|
||||||
|
DownloadDraft.author = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 目标 URL 变化时清空草稿(避免不同书籍沿用旧的选章/标题) */
|
||||||
|
static onUrlChanged(newUrl: string): void {
|
||||||
|
if (DownloadDraft.url === newUrl) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
DownloadDraft.reset();
|
||||||
|
DownloadDraft.url = newUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
static hasCacheFor(url: string): boolean {
|
||||||
|
return DownloadDraft.url === url && DownloadDraft.nodes.length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static filterActiveFor(url: string): boolean {
|
||||||
|
return DownloadDraft.url === url && DownloadDraft.chapterFilter.length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static chapterTotal(): number {
|
||||||
|
let n = 0;
|
||||||
|
for (const nd of DownloadDraft.nodes) {
|
||||||
|
if (nd.isChapter) {
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import { preferences } from '@kit.ArkData';
|
||||||
|
import { fileIo as fs } from '@kit.CoreFileKit';
|
||||||
|
import { AppHub } from '../common/AppHub';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 书库记录:已生成书籍的持久化索引。
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface BookRecord {
|
||||||
|
id: string; // 原书下载 = 详情页链接;选章/自定义标题下载 = 链接#《自定义名》作者
|
||||||
|
url: string; // 详情页链接
|
||||||
|
name: string;
|
||||||
|
author: string;
|
||||||
|
date: string; // 更新日期
|
||||||
|
baseName: string; // 不含扩展名的文件名(《书名》作者)
|
||||||
|
epubPath: string;
|
||||||
|
txtPath: string;
|
||||||
|
chapters: number;
|
||||||
|
createdAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class LibraryStore {
|
||||||
|
private static prefs: preferences.Preferences | null = null;
|
||||||
|
private static records: BookRecord[] = [];
|
||||||
|
|
||||||
|
static async init(): Promise<void> {
|
||||||
|
LibraryStore.prefs = await preferences.getPreferences(AppHub.uiContext(), 'esj_library');
|
||||||
|
const raw = LibraryStore.prefs.getSync('library_json', '') as string;
|
||||||
|
LibraryStore.records = [];
|
||||||
|
if (raw.length > 0) {
|
||||||
|
try {
|
||||||
|
const arr = JSON.parse(raw) as BookRecord[];
|
||||||
|
for (const r of arr) {
|
||||||
|
LibraryStore.records.push(r);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
LibraryStore.records = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ensureLibraryDir();
|
||||||
|
}
|
||||||
|
|
||||||
|
static list(): BookRecord[] {
|
||||||
|
return LibraryStore.records.slice().sort((a: BookRecord, b: BookRecord): number => b.createdAt - a.createdAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
static save(): void {
|
||||||
|
if (LibraryStore.prefs === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
LibraryStore.prefs.putSync('library_json', JSON.stringify(LibraryStore.records));
|
||||||
|
LibraryStore.prefs.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
static findByUrl(url: string): BookRecord | null {
|
||||||
|
// 仅匹配"原书下载"记录(id === 链接),批量模式的日期去重使用
|
||||||
|
for (const r of LibraryStore.records) {
|
||||||
|
if (r.id === url) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
static findById(id: string): BookRecord | null {
|
||||||
|
for (const r of LibraryStore.records) {
|
||||||
|
if (r.id === id) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 同一 id 重新下载时替换记录并清理旧文件;不同 id(如选章自定义名)各自独立保留 */
|
||||||
|
static upsert(record: BookRecord): void {
|
||||||
|
const idx = LibraryStore.records.findIndex((r: BookRecord): boolean => r.id === record.id);
|
||||||
|
if (idx >= 0) {
|
||||||
|
const old = LibraryStore.records[idx];
|
||||||
|
if (old.baseName !== record.baseName) {
|
||||||
|
// 文件名变了:清理旧文件,避免残留
|
||||||
|
deleteQuietly(old.epubPath);
|
||||||
|
deleteQuietly(old.txtPath);
|
||||||
|
}
|
||||||
|
LibraryStore.records.splice(idx, 1);
|
||||||
|
}
|
||||||
|
LibraryStore.records.push(record);
|
||||||
|
LibraryStore.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
static remove(id: string): void {
|
||||||
|
const idx = LibraryStore.records.findIndex((r: BookRecord): boolean => r.id === id);
|
||||||
|
if (idx >= 0) {
|
||||||
|
const old = LibraryStore.records[idx];
|
||||||
|
deleteQuietly(old.epubPath);
|
||||||
|
deleteQuietly(old.txtPath);
|
||||||
|
LibraryStore.records.splice(idx, 1);
|
||||||
|
LibraryStore.save();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为书籍生成不冲突的基础文件名。
|
||||||
|
* 同一 id(原书刷新 / 同名选章重下)复用旧文件名以便覆盖;
|
||||||
|
* 不同内容若与磁盘文件重名则追加序号。
|
||||||
|
*/
|
||||||
|
static uniqueName(base: string, id: string): string {
|
||||||
|
const exist = LibraryStore.findById(id);
|
||||||
|
if (exist !== null && exist.baseName.length > 0) {
|
||||||
|
return exist.baseName;
|
||||||
|
}
|
||||||
|
const dir = AppHub.uiContext().filesDir + '/library';
|
||||||
|
let name = base;
|
||||||
|
let n = 2;
|
||||||
|
while (LibraryStore.existsFile(dir + '/' + name + '.epub') || LibraryStore.existsFile(dir + '/' + name + '.txt')) {
|
||||||
|
name = base + `(${n})`;
|
||||||
|
n++;
|
||||||
|
if (n > 50) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
static existsFile(path: string): boolean {
|
||||||
|
try {
|
||||||
|
return fs.accessSync(path);
|
||||||
|
} catch (e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteQuietly(path: string): void {
|
||||||
|
if (path.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (fs.accessSync(path)) {
|
||||||
|
fs.unlinkSync(path);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// 忽略
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ensureLibraryDir(): void {
|
||||||
|
const dir = AppHub.uiContext().filesDir + '/library';
|
||||||
|
try {
|
||||||
|
if (!fs.accessSync(dir)) {
|
||||||
|
fs.mkdirSync(dir, true);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(dir, true);
|
||||||
|
} catch (e2) {
|
||||||
|
// 忽略
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,837 @@
|
|||||||
|
import { taskpool } from '@kit.ArkTS';
|
||||||
|
import { fileIo as fs } from '@kit.CoreFileKit';
|
||||||
|
import { util } from '@kit.ArkTS';
|
||||||
|
import { ConfigStore, AppSettings } from './Config';
|
||||||
|
import { TaskInfo, ChapterNode, BookProgress, TocPreviewNode, TocPreviewResult } from './TaskModel';
|
||||||
|
import { NodeStatus, TaskStatus } from '../common/Theme';
|
||||||
|
import { AppHub } from '../common/AppHub';
|
||||||
|
import { OpenCC } from '../core/OpenCC';
|
||||||
|
import { analyzeDetail, parseListPage, urlHandler, isImgPlaceholder, imgPlaceholderUrl, hostOf, VolumeChapterNode } from '../core/EsjCore';
|
||||||
|
import { buildEpub, EpubBuildInput, EpubImageItem, EpubNodeItem, escapeXml } from '../core/EpubWriter';
|
||||||
|
import { fetchChapterJob, fetchImageJob, FetchChapterArgs, FetchImageArgs, FetchChapterResult, FetchImageResult } from '../worker/Jobs';
|
||||||
|
import { httpGetText } from '../net/HttpUtil';
|
||||||
|
import { LibraryStore, BookRecord } from './LibraryStore';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 任务编排:等价原脚本的 downloadOneBook / 批量列表下载流程。
|
||||||
|
* 单任务串行运行,任务内部按配置的并发数抓取章节;图片随章节内联抓取并按内容去重。
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface ImageState {
|
||||||
|
status: string; // inflight | done | failed
|
||||||
|
fileName: string;
|
||||||
|
filePath: string;
|
||||||
|
contentType: string;
|
||||||
|
error: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Cursor {
|
||||||
|
i: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TaskManager {
|
||||||
|
static instance: TaskManager = new TaskManager();
|
||||||
|
tasks: TaskInfo[] = [];
|
||||||
|
activeTaskId: string = '';
|
||||||
|
|
||||||
|
private imgMap: Map<string, ImageState> = new Map();
|
||||||
|
private lastEmit: number = 0;
|
||||||
|
|
||||||
|
tasksSnapshot(): TaskInfo[] {
|
||||||
|
return this.tasks.slice();
|
||||||
|
}
|
||||||
|
|
||||||
|
findTask(id: string): TaskInfo | null {
|
||||||
|
for (const t of this.tasks) {
|
||||||
|
if (t.id === id) {
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
createTask(mode: string, url: string, customTitle: string = '', chapterFilter: number[] = []): TaskInfo {
|
||||||
|
const t = new TaskInfo();
|
||||||
|
t.id = 'task_' + Date.now().toString(36) + '_' + Math.floor(Math.random() * 1000);
|
||||||
|
t.mode = mode;
|
||||||
|
t.url = url;
|
||||||
|
t.customTitle = customTitle;
|
||||||
|
for (const v of chapterFilter) {
|
||||||
|
t.chapterFilter.push(v);
|
||||||
|
}
|
||||||
|
t.createdAt = Date.now();
|
||||||
|
this.tasks.unshift(t);
|
||||||
|
t.addLog('info', mode === 'list' ? '创建批量下载任务' : '创建下载任务');
|
||||||
|
this.emit(true);
|
||||||
|
if (this.activeTaskId === '') {
|
||||||
|
this.startTask(t);
|
||||||
|
}
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 拉取目录预览(选章下载用)。返回纯数据,不改任务状态。 */
|
||||||
|
async fetchTocPreview(url: string): Promise<TocPreviewResult> {
|
||||||
|
const s = ConfigStore.get();
|
||||||
|
const empty: TocPreviewNode[] = [];
|
||||||
|
const resp = await httpGetText(url, s.cookie, s.timeoutSec * 1000, s.retryCount);
|
||||||
|
if (!resp.ok) {
|
||||||
|
const r: TocPreviewResult = { ok: false, error: resp.error, nodes: empty, bookName: '', author: '' };
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
const cc = await OpenCC.getConverter(s.convertMode, AppHub.uiContext());
|
||||||
|
const detail = analyzeDetail(resp.text, s.siteUrl, cc !== null ? (x: string): string => cc.convert(x) : null);
|
||||||
|
if (!detail.ok) {
|
||||||
|
const r2: TocPreviewResult = { ok: false, error: detail.error, nodes: empty, bookName: '', author: '' };
|
||||||
|
return r2;
|
||||||
|
}
|
||||||
|
const nodes: TocPreviewNode[] = [];
|
||||||
|
for (const n of detail.nodes) {
|
||||||
|
nodes.push({ value: n.value, level: n.level, fatherValue: n.fatherValue, isVolume: n.isVolume, isChapter: n.isChapter, title: n.title });
|
||||||
|
}
|
||||||
|
const r3: TocPreviewResult = { ok: true, error: '', nodes: nodes, bookName: detail.bookName, author: detail.author };
|
||||||
|
return r3;
|
||||||
|
}
|
||||||
|
|
||||||
|
requestCancel(id: string): void {
|
||||||
|
const t = this.findTask(id);
|
||||||
|
if (t === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
t.cancelRequested = true;
|
||||||
|
t.addLog('warn', '已请求取消,等待进行中的请求结束…');
|
||||||
|
this.emit(true);
|
||||||
|
if (t.status === TaskStatus.QUEUED) {
|
||||||
|
t.status = TaskStatus.CANCELLED;
|
||||||
|
t.addLog('warn', '任务已取消');
|
||||||
|
this.emit(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
removeTask(id: string): void {
|
||||||
|
const idx = this.tasks.findIndex((t: TaskInfo): boolean => t.id === id);
|
||||||
|
if (idx >= 0) {
|
||||||
|
if (this.tasks[idx].status === TaskStatus.RUNNING) {
|
||||||
|
this.requestCancel(id);
|
||||||
|
}
|
||||||
|
this.tasks.splice(idx, 1);
|
||||||
|
this.emit(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 重试失败章节(仅单书模式;复用仍存在的缓存与已下载图片做增量重建) */
|
||||||
|
retryFailed(id: string): void {
|
||||||
|
if (this.activeTaskId !== '') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const t = this.findTask(id);
|
||||||
|
if (t === null || t.status !== TaskStatus.DONE_WITH_FAIL || t.mode !== 'book') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const n of t.nodes) {
|
||||||
|
if (n.status === NodeStatus.FAILED) {
|
||||||
|
n.status = NodeStatus.PENDING;
|
||||||
|
n.error = '';
|
||||||
|
n.lines = [];
|
||||||
|
n.fragmentPath = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 重置失败的图片,允许重新抓取
|
||||||
|
const removeUrls: string[] = [];
|
||||||
|
this.imgMap.forEach((v: ImageState, k: string): void => {
|
||||||
|
if (v.status === 'failed') {
|
||||||
|
removeUrls.push(k);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
for (const u of removeUrls) {
|
||||||
|
this.imgMap.delete(u);
|
||||||
|
}
|
||||||
|
t.failedChapters = 0;
|
||||||
|
t.errorMessage = '';
|
||||||
|
t.cancelRequested = false;
|
||||||
|
t.addLog('info', '重试失败章节');
|
||||||
|
this.emit(true);
|
||||||
|
this.startTask(t, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private startTask(t: TaskInfo, retryOnly: boolean = false): void {
|
||||||
|
if (this.activeTaskId !== '') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.activeTaskId = t.id;
|
||||||
|
t.status = TaskStatus.RUNNING;
|
||||||
|
this.emit(true);
|
||||||
|
this.run(t, retryOnly).then((): void => {
|
||||||
|
/* 由 run 内部收尾 */
|
||||||
|
}).catch((e: Error): void => {
|
||||||
|
t.status = TaskStatus.FAILED;
|
||||||
|
t.errorMessage = e.message;
|
||||||
|
t.addLog('error', '任务异常: ' + e.message);
|
||||||
|
this.finishActive(t);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private finishActive(t: TaskInfo): void {
|
||||||
|
this.activeTaskId = '';
|
||||||
|
this.emit(true);
|
||||||
|
// 启动队列中的下一个任务
|
||||||
|
for (const nt of this.tasks) {
|
||||||
|
if (nt.status === TaskStatus.QUEUED) {
|
||||||
|
this.startTask(nt);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private emit(force: boolean): void {
|
||||||
|
const now = Date.now();
|
||||||
|
if (!force && now - this.lastEmit < 400) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.lastEmit = now;
|
||||||
|
AppHub.emit('tasks', '');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------- 主流程 ----------------
|
||||||
|
|
||||||
|
private async run(t: TaskInfo, retryOnly: boolean = false): Promise<void> {
|
||||||
|
const s = ConfigStore.get();
|
||||||
|
try {
|
||||||
|
if (t.mode === 'list') {
|
||||||
|
await this.runList(t, s);
|
||||||
|
} else {
|
||||||
|
await this.runBook(t, s, t.url, null, retryOnly);
|
||||||
|
}
|
||||||
|
if (t.cancelRequested) {
|
||||||
|
t.status = TaskStatus.CANCELLED;
|
||||||
|
t.addLog('warn', '任务已取消');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (!t.cancelRequested) {
|
||||||
|
t.status = TaskStatus.FAILED;
|
||||||
|
t.errorMessage = (e as Error).message;
|
||||||
|
t.addLog('error', (e as Error).message);
|
||||||
|
} else {
|
||||||
|
t.status = TaskStatus.CANCELLED;
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
// 存在失败章节的任务保留缓存与图片映射以便重试,其余清理
|
||||||
|
if (t.status !== TaskStatus.DONE_WITH_FAIL) {
|
||||||
|
this.cleanupCache(t);
|
||||||
|
this.imgMap.clear();
|
||||||
|
}
|
||||||
|
this.finishActive(t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async runList(t: TaskInfo, s: AppSettings): Promise<void> {
|
||||||
|
const mismatch = checkDomain(t.url, s.siteUrl);
|
||||||
|
if (mismatch.length > 0) {
|
||||||
|
throw new Error(mismatch);
|
||||||
|
}
|
||||||
|
t.phase = 'list';
|
||||||
|
t.addLog('info', '开始收集书籍列表…');
|
||||||
|
this.emit(true);
|
||||||
|
const firstPage = await httpGetText(t.url, s.cookie, s.timeoutSec * 1000, s.retryCount);
|
||||||
|
if (!firstPage.ok) {
|
||||||
|
throw new Error('列表页下载失败: ' + firstPage.error);
|
||||||
|
}
|
||||||
|
const firstInfo = parseListPage(firstPage.text, s.siteUrl);
|
||||||
|
const total = firstInfo.totalCount > 0 ? firstInfo.totalCount : 1;
|
||||||
|
t.addLog('info', `列表「${firstInfo.title}」共 ${total} 页`);
|
||||||
|
const bookUrls: string[] = [];
|
||||||
|
const seen: Set<string> = new Set();
|
||||||
|
for (const u of firstInfo.bookUrls) {
|
||||||
|
if (!seen.has(u)) {
|
||||||
|
seen.add(u);
|
||||||
|
bookUrls.push(u);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (let p = 2; p <= total; p++) {
|
||||||
|
if (t.cancelRequested) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const pageUrl = t.url + p + '.html';
|
||||||
|
const resp = await httpGetText(pageUrl, s.cookie, s.timeoutSec * 1000, s.retryCount);
|
||||||
|
if (!resp.ok) {
|
||||||
|
t.addLog('warn', `第 ${p} 页下载失败: ${resp.error}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const info = parseListPage(resp.text, s.siteUrl);
|
||||||
|
for (const u of info.bookUrls) {
|
||||||
|
if (!seen.has(u)) {
|
||||||
|
seen.add(u);
|
||||||
|
bookUrls.push(u);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.currentTitle = `收集列表 ${p}/${total}`;
|
||||||
|
this.emit(false);
|
||||||
|
}
|
||||||
|
t.addLog('info', `共发现 ${bookUrls.length} 本小说`);
|
||||||
|
t.activeBooksTotal = bookUrls.length;
|
||||||
|
t.phase = 'chapters';
|
||||||
|
for (let i = 0; i < bookUrls.length; i++) {
|
||||||
|
if (t.cancelRequested) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const bp: BookProgress = {
|
||||||
|
url: bookUrls[i], name: '', author: '', date: '', status: 'running',
|
||||||
|
doneCh: 0, totalCh: 0, message: ''
|
||||||
|
};
|
||||||
|
t.books.push(bp);
|
||||||
|
try {
|
||||||
|
const ok = await this.runBook(t, s, bookUrls[i], bp);
|
||||||
|
bp.status = t.cancelRequested ? 'cancelled' : (ok ? 'done' : 'skipped');
|
||||||
|
} catch (e) {
|
||||||
|
bp.status = 'failed';
|
||||||
|
bp.message = (e as Error).message;
|
||||||
|
t.addLog('error', `书籍下载失败: ${(e as Error).message}`);
|
||||||
|
}
|
||||||
|
t.activeBooksDone++;
|
||||||
|
this.emit(true);
|
||||||
|
}
|
||||||
|
if (t.cancelRequested) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const failedCount = t.books.filter((b: BookProgress): boolean => b.status === 'failed').length;
|
||||||
|
t.status = failedCount > 0 ? TaskStatus.DONE_WITH_FAIL : TaskStatus.DONE;
|
||||||
|
t.addLog('ok', `批量任务完成:成功 ${t.activeBooksDone - failedCount},失败 ${failedCount}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 下载单本书。bp 非空表示处于批量模式;retryOnly 表示失败章节增量重试
|
||||||
|
* (复用现存缓存目录、已完成章节与图片)。
|
||||||
|
* 返回 true=完成;抛出异常=失败;返回 false=已存在跳过。
|
||||||
|
*/
|
||||||
|
private async runBook(t: TaskInfo, s: AppSettings, bookUrl: string, bp: BookProgress | null,
|
||||||
|
retryOnly: boolean = false): Promise<boolean> {
|
||||||
|
const cacheDir = AppHub.uiContext().cacheDir + '/task_' + t.id;
|
||||||
|
const chDir = cacheDir + '/chapters';
|
||||||
|
const imgDir = cacheDir + '/images';
|
||||||
|
|
||||||
|
let bookName = t.bookName;
|
||||||
|
let author = t.author;
|
||||||
|
let changeDate = t.changeDate;
|
||||||
|
let coverUrl = t.coverUrl;
|
||||||
|
let descLines: string[] = t.descLines;
|
||||||
|
let descFragmentPath = '';
|
||||||
|
let unique = '';
|
||||||
|
let recordId = bookUrl;
|
||||||
|
|
||||||
|
if (!retryOnly) {
|
||||||
|
const mismatch = checkDomain(bookUrl, s.siteUrl);
|
||||||
|
if (mismatch.length > 0) {
|
||||||
|
throw new Error(mismatch);
|
||||||
|
}
|
||||||
|
t.phase = 'detail';
|
||||||
|
t.currentTitle = '获取书籍信息';
|
||||||
|
this.emit(true);
|
||||||
|
|
||||||
|
const resp = await httpGetText(bookUrl, s.cookie, s.timeoutSec * 1000, s.retryCount);
|
||||||
|
if (!resp.ok) {
|
||||||
|
throw new Error('详情页下载失败: ' + resp.error);
|
||||||
|
}
|
||||||
|
const cc = await OpenCC.getConverter(s.convertMode, AppHub.uiContext());
|
||||||
|
const convertFn = cc !== null ? (x: string): string => cc.convert(x) : null;
|
||||||
|
const detail = analyzeDetail(resp.text, s.siteUrl, convertFn);
|
||||||
|
if (!detail.ok) {
|
||||||
|
throw new Error(detail.error);
|
||||||
|
}
|
||||||
|
if (detail.nodes.length === 0 && detail.descLines.length === 0) {
|
||||||
|
throw new Error('未解析到章节列表,页面结构可能已变化');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 批量模式日期去重(等价脚本的已存在判断)
|
||||||
|
if (bp !== null) {
|
||||||
|
const exist = LibraryStore.findByUrl(bookUrl);
|
||||||
|
if (exist !== null && exist.date.length > 0 && detail.changeDate.length > 0 && exist.date === detail.changeDate) {
|
||||||
|
bp.name = exist.name;
|
||||||
|
bp.author = exist.author;
|
||||||
|
bp.date = exist.date;
|
||||||
|
bp.status = 'skipped';
|
||||||
|
bp.message = `更新日期 ${exist.date} 已存在,跳过`;
|
||||||
|
t.addLog('info', `《${exist.name}》更新日期 ${exist.date} 已存在,跳过`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bookName = detail.bookName;
|
||||||
|
author = detail.author;
|
||||||
|
changeDate = detail.changeDate;
|
||||||
|
coverUrl = detail.coverUrl;
|
||||||
|
// 自定义 EPUB 标题(选章下载/改名场景)
|
||||||
|
if (t.customTitle.length > 0) {
|
||||||
|
bookName = t.customTitle;
|
||||||
|
}
|
||||||
|
t.bookName = bookName;
|
||||||
|
t.author = author;
|
||||||
|
t.changeDate = changeDate;
|
||||||
|
t.coverUrl = coverUrl;
|
||||||
|
if (bp !== null) {
|
||||||
|
bp.name = bookName;
|
||||||
|
bp.author = author;
|
||||||
|
bp.date = changeDate;
|
||||||
|
}
|
||||||
|
if (bookName !== detail.bookName) {
|
||||||
|
t.addLog('info', `《${detail.bookName}》${author} 开始下载(标题:${bookName})`);
|
||||||
|
} else {
|
||||||
|
t.addLog('info', `《${bookName}》${author} 开始下载`);
|
||||||
|
}
|
||||||
|
|
||||||
|
ensureDir(cacheDir);
|
||||||
|
ensureDir(chDir);
|
||||||
|
ensureDir(imgDir);
|
||||||
|
t.nodes = detail.nodes.map((n): ChapterNode => new ChapterNode(n));
|
||||||
|
// 选章下载:仅保留选中章节及其所属卷
|
||||||
|
if (t.chapterFilter.length > 0) {
|
||||||
|
t.nodes = filterSelectedNodes(t.nodes, t.chapterFilter);
|
||||||
|
const selCount = t.nodes.filter((n: ChapterNode): boolean => n.node.isChapter).length;
|
||||||
|
if (selCount === 0) {
|
||||||
|
throw new Error('未选中任何章节');
|
||||||
|
}
|
||||||
|
t.addLog('info', `选章下载:${selCount}/${detail.nodes.filter((n: VolumeChapterNode): boolean => n.isChapter).length} 章`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 简介片段
|
||||||
|
descLines = detail.descLines;
|
||||||
|
t.descLines = descLines;
|
||||||
|
if (descLines.length > 0) {
|
||||||
|
if (allBlankLines(descLines)) {
|
||||||
|
descLines = ['【空】'];
|
||||||
|
t.descLines = descLines;
|
||||||
|
}
|
||||||
|
descFragmentPath = chDir + '/desc.xhtml';
|
||||||
|
writeFragment(descFragmentPath, descLines);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 文件名(同一 id 复用旧名覆盖;选章/自定义名与原书互不影响)
|
||||||
|
const baseName = `《${bookName}》${author}`;
|
||||||
|
recordId = t.customTitle.length > 0 ? bookUrl + '#' + baseName : bookUrl;
|
||||||
|
unique = LibraryStore.uniqueName(baseName, recordId);
|
||||||
|
} else {
|
||||||
|
// 增量重试:缓存必须仍存在
|
||||||
|
if (!fs.accessSync(cacheDir)) {
|
||||||
|
throw new Error('任务缓存已被清理,请重新下载这本书');
|
||||||
|
}
|
||||||
|
ensureDir(chDir);
|
||||||
|
ensureDir(imgDir);
|
||||||
|
if (t.nodes.length === 0) {
|
||||||
|
throw new Error('没有可重试的章节');
|
||||||
|
}
|
||||||
|
if (descLines.length > 0) {
|
||||||
|
descFragmentPath = chDir + '/desc.xhtml';
|
||||||
|
if (!fs.accessSync(descFragmentPath)) {
|
||||||
|
writeFragment(descFragmentPath, descLines);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
recordId = t.customTitle.length > 0 ? bookUrl + '#' + `《${bookName}》${author}` : bookUrl;
|
||||||
|
const exist = LibraryStore.findById(recordId);
|
||||||
|
unique = exist !== null && exist.baseName.length > 0 ? exist.baseName : `《${bookName}》${author}`;
|
||||||
|
}
|
||||||
|
const epubPath = AppHub.uiContext().filesDir + '/library/' + unique + '.epub';
|
||||||
|
const txtPath = AppHub.uiContext().filesDir + '/library/' + unique + '.txt';
|
||||||
|
|
||||||
|
// 封面
|
||||||
|
if (s.downloadCover && coverUrl.length > 0) {
|
||||||
|
await this.ensureImage(t, s, coverUrl, imgDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 章节并发下载
|
||||||
|
t.phase = 'chapters';
|
||||||
|
const chapterNodes = t.nodes.filter((n: ChapterNode): boolean => n.node.isChapter);
|
||||||
|
t.totalChapters = chapterNodes.length;
|
||||||
|
t.doneChapters = chapterNodes.filter((n: ChapterNode): boolean =>
|
||||||
|
n.status === NodeStatus.DONE || n.status === NodeStatus.LOCKED).length;
|
||||||
|
if (!retryOnly) {
|
||||||
|
this.imgMap.clear();
|
||||||
|
}
|
||||||
|
const cursor: Cursor = { i: 0 };
|
||||||
|
const workers: Promise<void>[] = [];
|
||||||
|
for (let w = 0; w < Math.max(1, s.threadCount); w++) {
|
||||||
|
workers.push(this.chapterWorker(t, s, chapterNodes, cursor, chDir, imgDir));
|
||||||
|
}
|
||||||
|
await Promise.all(workers);
|
||||||
|
if (t.cancelRequested) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
t.currentTitle = '正在打包';
|
||||||
|
|
||||||
|
// 组装 TXT
|
||||||
|
if (s.outputTxt) {
|
||||||
|
let txt = '';
|
||||||
|
if (descLines.length > 0) {
|
||||||
|
txt += '简介\n' + txtOfLines(descLines, this.imgMap);
|
||||||
|
}
|
||||||
|
for (const n of t.nodes) {
|
||||||
|
if (n.node.isChapter && n.status === NodeStatus.FAILED) {
|
||||||
|
txt += n.node.title + '章节下载失败\n' + n.node.url + '\n';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
txt += n.node.title + '\n';
|
||||||
|
if (n.node.isChapter) {
|
||||||
|
txt += txtOfLines(n.lines, this.imgMap);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeTextFileSync(txtPath, txt);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 打包 EPUB
|
||||||
|
if (s.outputEpub) {
|
||||||
|
t.phase = 'build';
|
||||||
|
this.emit(true);
|
||||||
|
const nodeItems: EpubNodeItem[] = [];
|
||||||
|
for (const n of t.nodes) {
|
||||||
|
const fileName = n.node.isChapter
|
||||||
|
? (n.status === NodeStatus.FAILED ? `error_novel_${n.node.value}.xhtml` : `novel_${n.node.value}.xhtml`)
|
||||||
|
: `volume_${n.node.value}.xhtml`;
|
||||||
|
if (n.node.isChapter && n.fragmentPath === '') {
|
||||||
|
// 失败章节写入错误占位(等价脚本 error_novel)
|
||||||
|
const failPath = chDir + '/' + fileName;
|
||||||
|
const failLines = ['章节下载失败', n.node.url, n.error];
|
||||||
|
writeFragment(failPath, failLines);
|
||||||
|
n.fragmentPath = failPath;
|
||||||
|
}
|
||||||
|
nodeItems.push({ node: n.node, fileName: fileName, fragmentPath: n.node.isChapter ? n.fragmentPath : '' });
|
||||||
|
}
|
||||||
|
const images: EpubImageItem[] = [];
|
||||||
|
this.imgMap.forEach((v: ImageState, k: string): void => {
|
||||||
|
if (v.status === 'done' && k !== coverUrl) {
|
||||||
|
images.push({ url: k, fileName: v.fileName, contentType: v.contentType, filePath: v.filePath });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let cover: EpubImageItem | undefined = undefined;
|
||||||
|
if (s.downloadCover && coverUrl.length > 0) {
|
||||||
|
const cv = this.imgMap.get(coverUrl);
|
||||||
|
if (cv !== undefined && cv.status === 'done') {
|
||||||
|
cover = { url: coverUrl, fileName: 'cover' + cv.fileName.substring(cv.fileName.lastIndexOf('.')), contentType: cv.contentType, filePath: cv.filePath };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const buildInput: EpubBuildInput = {
|
||||||
|
outPath: epubPath, bookName: bookName, author: author, changeDate: changeDate,
|
||||||
|
cover: cover, descFragmentPath: descFragmentPath !== '' ? descFragmentPath : undefined,
|
||||||
|
nodes: nodeItems, images: images
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
buildEpub(buildInput);
|
||||||
|
t.epubPath = epubPath;
|
||||||
|
} catch (e) {
|
||||||
|
t.addLog('error', 'EPUB 打包失败: ' + (e as Error).message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.txtPath = s.outputTxt ? txtPath : '';
|
||||||
|
|
||||||
|
// 入库
|
||||||
|
const record: BookRecord = {
|
||||||
|
id: recordId, url: bookUrl, name: bookName, author: author, date: changeDate,
|
||||||
|
baseName: unique,
|
||||||
|
epubPath: t.epubPath, txtPath: t.txtPath,
|
||||||
|
chapters: chapterNodes.length, createdAt: Date.now()
|
||||||
|
};
|
||||||
|
LibraryStore.upsert(record);
|
||||||
|
|
||||||
|
t.phase = 'done';
|
||||||
|
const failedNow = t.failedChapters;
|
||||||
|
if (bp !== null) {
|
||||||
|
// 批量模式:单本结果记入 bp,任务状态由 runList 统一收尾
|
||||||
|
if (failedNow > 0) {
|
||||||
|
bp.message = `完成,${failedNow} 章失败`;
|
||||||
|
t.addLog('warn', `《${bookName}》完成,${failedNow} 章失败(批量模式不做单章重试)`);
|
||||||
|
}
|
||||||
|
t.failedChapters = 0;
|
||||||
|
// 批量模式不保留已完成书籍的章节文本
|
||||||
|
for (const n of t.nodes) {
|
||||||
|
n.lines = [];
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (failedNow > 0) {
|
||||||
|
t.status = TaskStatus.DONE_WITH_FAIL;
|
||||||
|
t.addLog('ok', `《${bookName}》下载完成,${failedNow} 章失败可重试`);
|
||||||
|
} else {
|
||||||
|
t.status = TaskStatus.DONE;
|
||||||
|
t.addLog('ok', `《${bookName}》${changeDate} 下载完成`);
|
||||||
|
// 无失败章节,释放章节文本内存
|
||||||
|
for (const n of t.nodes) {
|
||||||
|
n.lines = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async chapterWorker(t: TaskInfo, s: AppSettings, list: ChapterNode[], cursor: Cursor,
|
||||||
|
chDir: string, imgDir: string): Promise<void> {
|
||||||
|
while (!t.cancelRequested) {
|
||||||
|
const idx = cursor.i;
|
||||||
|
if (idx >= list.length) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cursor.i++;
|
||||||
|
const node = list[idx];
|
||||||
|
if (node.status !== NodeStatus.PENDING) {
|
||||||
|
// 增量重试时跳过已完成的章节
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
node.status = NodeStatus.DOWNLOADING;
|
||||||
|
t.currentTitle = node.node.title;
|
||||||
|
this.emit(false);
|
||||||
|
const fullUrl = urlHandler(node.node.url, s.siteUrl);
|
||||||
|
const args: FetchChapterArgs = { url: fullUrl, cookie: s.cookie, timeoutMs: s.timeoutSec * 1000, retry: s.retryCount };
|
||||||
|
const job = new taskpool.Task(fetchChapterJob, args);
|
||||||
|
let result: FetchChapterResult | null = null;
|
||||||
|
try {
|
||||||
|
result = await taskpool.execute(job) as FetchChapterResult;
|
||||||
|
} catch (e) {
|
||||||
|
result = { ok: false, status: 'error', lines: [], error: '任务执行失败: ' + (e as Error).message };
|
||||||
|
}
|
||||||
|
if (t.cancelRequested) {
|
||||||
|
node.status = NodeStatus.PENDING;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (result === null || !result.ok || result.status === 'error') {
|
||||||
|
node.status = NodeStatus.FAILED;
|
||||||
|
node.error = result !== null ? result.error : '未知错误';
|
||||||
|
t.failedChapters++;
|
||||||
|
t.doneChapters++;
|
||||||
|
t.addLog('error', `章节下载失败「${node.node.title}」: ${node.error}`);
|
||||||
|
node.touch();
|
||||||
|
this.emit(false);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// 转换文本(图片占位行不转换)
|
||||||
|
let lines = result.lines;
|
||||||
|
const cc = await OpenCC.getConverter(s.convertMode, AppHub.uiContext());
|
||||||
|
if (cc !== null) {
|
||||||
|
lines = lines.map((l: string): string => isImgPlaceholder(l) ? l : cc.convert(l));
|
||||||
|
}
|
||||||
|
if (result.status === 'locked') {
|
||||||
|
node.status = NodeStatus.LOCKED;
|
||||||
|
node.lines = ['本章节需要密码,已跳过'];
|
||||||
|
} else if (lines.length === 0) {
|
||||||
|
node.status = NodeStatus.DONE;
|
||||||
|
node.lines = ['【空】'];
|
||||||
|
} else {
|
||||||
|
node.status = NodeStatus.DONE;
|
||||||
|
node.lines = lines;
|
||||||
|
}
|
||||||
|
if (node.node.isChapter) {
|
||||||
|
const fragPath = `${chDir}/novel_${node.node.value}.xhtml`;
|
||||||
|
writeFragment(fragPath, node.lines);
|
||||||
|
node.fragmentPath = fragPath;
|
||||||
|
}
|
||||||
|
// 内联下载本章图片
|
||||||
|
for (const line of node.lines) {
|
||||||
|
if (isImgPlaceholder(line) && s.downloadImages) {
|
||||||
|
await this.ensureImage(t, s, imgPlaceholderUrl(line), imgDir);
|
||||||
|
if (t.cancelRequested) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.doneChapters++;
|
||||||
|
node.touch();
|
||||||
|
this.emit(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async ensureImage(t: TaskInfo, s: AppSettings, url: string, imgDir: string): Promise<void> {
|
||||||
|
if (this.imgMap.has(url)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const st: ImageState = { status: 'inflight', fileName: '', filePath: '', contentType: '', error: '' };
|
||||||
|
this.imgMap.set(url, st);
|
||||||
|
t.totalImages = this.imgMap.size;
|
||||||
|
const fullUrl = urlHandler(url, s.siteUrl);
|
||||||
|
const args: FetchImageArgs = { url: fullUrl, cookie: s.cookie, timeoutMs: s.timeoutSec * 1000, retry: s.retryCount };
|
||||||
|
const job = new taskpool.Task(fetchImageJob, args);
|
||||||
|
let result: FetchImageResult | null = null;
|
||||||
|
try {
|
||||||
|
result = await taskpool.execute(job) as FetchImageResult;
|
||||||
|
} catch (e) {
|
||||||
|
result = { ok: false, ext: '', hash: '', data: new ArrayBuffer(0), error: (e as Error).message };
|
||||||
|
}
|
||||||
|
if (result !== null && result.ok) {
|
||||||
|
const fileName = `Image_${result.hash}${result.ext}`;
|
||||||
|
const filePath = imgDir + '/' + fileName;
|
||||||
|
try {
|
||||||
|
const f = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE | fs.OpenMode.TRUNC);
|
||||||
|
fs.writeSync(f.fd, result.data);
|
||||||
|
fs.closeSync(f);
|
||||||
|
st.status = 'done';
|
||||||
|
st.fileName = fileName;
|
||||||
|
st.filePath = filePath;
|
||||||
|
st.contentType = 'image/' + result.ext.substring(1);
|
||||||
|
} catch (e) {
|
||||||
|
st.status = 'failed';
|
||||||
|
st.error = '写入失败: ' + (e as Error).message;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
st.status = 'failed';
|
||||||
|
st.error = result !== null ? result.error : '未知错误';
|
||||||
|
t.addLog('warn', `图片下载失败: ${url} ${st.error}`);
|
||||||
|
}
|
||||||
|
t.doneImages++;
|
||||||
|
this.emit(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private cleanupCache(t: TaskInfo): void {
|
||||||
|
try {
|
||||||
|
const cacheDir = AppHub.uiContext().cacheDir + '/task_' + t.id;
|
||||||
|
deleteDirRecursive(cacheDir);
|
||||||
|
} catch (e) {
|
||||||
|
// 目录不存在或删除失败,忽略
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------- 辅助函数 ----------------
|
||||||
|
|
||||||
|
function checkDomain(url: string, siteUrl: string): string {
|
||||||
|
const h1 = hostOf(url);
|
||||||
|
const h2 = hostOf(siteUrl);
|
||||||
|
if (h1.length === 0 || h2.length === 0) {
|
||||||
|
return '链接或站点域名无法解析';
|
||||||
|
}
|
||||||
|
if (h1 !== h2) {
|
||||||
|
return `链接域名(${h1}) 与设置中的站点域名(${h2}) 不一致。请修改设置中的站点域名,或使用对应域名的 Cookie。`;
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureDir(path: string): void {
|
||||||
|
try {
|
||||||
|
if (!fs.accessSync(path)) {
|
||||||
|
fs.mkdirSync(path, true);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(path, true);
|
||||||
|
} catch (e2) {
|
||||||
|
// 忽略
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteDirRecursive(path: string): void {
|
||||||
|
try {
|
||||||
|
if (!fs.accessSync(path)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const children = fs.listFileSync(path);
|
||||||
|
for (const name of children) {
|
||||||
|
const full = path + '/' + name;
|
||||||
|
if (fs.statSync(full).isDirectory()) {
|
||||||
|
deleteDirRecursive(full);
|
||||||
|
} else {
|
||||||
|
fs.unlinkSync(full);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fs.rmdirSync(path);
|
||||||
|
} catch (e) {
|
||||||
|
// 尽力清理
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 将文本行写入片段文件:文本行转 <p>,占位行原样保留(打包时替换) */
|
||||||
|
function writeFragment(path: string, lines: string[]): void {
|
||||||
|
const out: string[] = [];
|
||||||
|
for (const line of lines) {
|
||||||
|
if (isImgPlaceholder(line)) {
|
||||||
|
out.push(line);
|
||||||
|
} else {
|
||||||
|
out.push('<p>' + escapeXml(line) + '</p>');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeTextFileSync(path, out.join('\n'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeTextFileSync(path: string, text: string): void {
|
||||||
|
const bytes = util.TextEncoder.create().encodeInto(text);
|
||||||
|
const f = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE | fs.OpenMode.TRUNC);
|
||||||
|
try {
|
||||||
|
fs.writeSync(f.fd, bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
|
||||||
|
} finally {
|
||||||
|
fs.closeSync(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 文本行 → TXT 内容(占位行替换为 URL,等价脚本 imgTagConvert) */
|
||||||
|
function txtOfLines(lines: string[], imgMap: Map<string, ImageState>): string {
|
||||||
|
const out: string[] = [];
|
||||||
|
for (const line of lines) {
|
||||||
|
if (isImgPlaceholder(line)) {
|
||||||
|
const url = imgPlaceholderUrl(line);
|
||||||
|
const st = imgMap.get(url);
|
||||||
|
if (st !== undefined && st.status === 'done') {
|
||||||
|
out.push(url);
|
||||||
|
} else {
|
||||||
|
out.push('下载失败:' + url);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
out.push(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.join('\n') + '\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
function allBlankLines(lines: string[]): boolean {
|
||||||
|
for (const l of lines) {
|
||||||
|
if (isImgPlaceholder(l)) {
|
||||||
|
return false; // 图片占位也算有效内容
|
||||||
|
}
|
||||||
|
if (l.replace(/\s/g, '').length > 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 选章过滤:保留选中章节与其所属各级卷,并重排 value/fatherValue,
|
||||||
|
* 使剩余节点仍构成一棵合法目录树(等价于脚本对 node 列表的裁剪)。
|
||||||
|
*/
|
||||||
|
function filterSelectedNodes(nodes: ChapterNode[], filter: number[]): ChapterNode[] {
|
||||||
|
const selected: Set<number> = new Set();
|
||||||
|
for (const v of filter) {
|
||||||
|
selected.add(v);
|
||||||
|
}
|
||||||
|
const keep: boolean[] = new Array(nodes.length);
|
||||||
|
keep.fill(false);
|
||||||
|
// 自底向上:章节按选中集,卷按"含被保留子节点"保留
|
||||||
|
for (let i = nodes.length - 1; i >= 0; i--) {
|
||||||
|
const nd = nodes[i].node;
|
||||||
|
if (nd.isChapter) {
|
||||||
|
keep[i] = selected.has(nd.value);
|
||||||
|
} else {
|
||||||
|
let any = false;
|
||||||
|
for (let j = i + 1; j < nodes.length; j++) {
|
||||||
|
if (keep[j] && nodes[j].node.fatherValue === nd.value) {
|
||||||
|
any = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
keep[i] = any;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const out: ChapterNode[] = [];
|
||||||
|
const idMap: Map<number, number> = new Map();
|
||||||
|
for (let i = 0; i < nodes.length; i++) {
|
||||||
|
if (!keep[i]) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const src = nodes[i].node;
|
||||||
|
const copy: VolumeChapterNode = {
|
||||||
|
value: src.value, level: src.level, fatherValue: src.fatherValue,
|
||||||
|
isVolume: src.isVolume, isChapter: src.isChapter, title: src.title, url: src.url
|
||||||
|
};
|
||||||
|
idMap.set(src.value, out.length);
|
||||||
|
out.push(new ChapterNode(copy));
|
||||||
|
}
|
||||||
|
for (const cn of out) {
|
||||||
|
cn.node.value = idMap.get(cn.node.value) ?? cn.node.value;
|
||||||
|
}
|
||||||
|
for (const cn of out) {
|
||||||
|
if (cn.node.fatherValue >= 0) {
|
||||||
|
cn.node.fatherValue = idMap.get(cn.node.fatherValue) ?? -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
import { VolumeChapterNode } from '../core/EsjCore';
|
||||||
|
import { NodeStatus, TaskStatus } from '../common/Theme';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 任务数据模型 + UI 数据源。
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface LogLine {
|
||||||
|
time: string;
|
||||||
|
level: string; // info | warn | error | ok
|
||||||
|
msg: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ChapterNode {
|
||||||
|
node: VolumeChapterNode;
|
||||||
|
status: string = NodeStatus.PENDING;
|
||||||
|
lines: string[] = []; // 转换后的文本行(含图片占位行)
|
||||||
|
error: string = '';
|
||||||
|
fragmentPath: string = '';
|
||||||
|
doneTick: number = 0; // 用于驱动 UI 刷新
|
||||||
|
|
||||||
|
constructor(node: VolumeChapterNode) {
|
||||||
|
this.node = node;
|
||||||
|
}
|
||||||
|
|
||||||
|
touch(): void {
|
||||||
|
this.doneTick++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookProgress {
|
||||||
|
url: string;
|
||||||
|
name: string;
|
||||||
|
author: string;
|
||||||
|
date: string;
|
||||||
|
status: string;
|
||||||
|
doneCh: number;
|
||||||
|
totalCh: number;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 章节选择页用的目录预览节点(纯数据,可跨线程返回) */
|
||||||
|
export interface TocPreviewNode {
|
||||||
|
value: number;
|
||||||
|
level: number;
|
||||||
|
fatherValue: number;
|
||||||
|
isVolume: boolean;
|
||||||
|
isChapter: boolean;
|
||||||
|
title: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TocPreviewResult {
|
||||||
|
ok: boolean;
|
||||||
|
error: string;
|
||||||
|
nodes: TocPreviewNode[];
|
||||||
|
bookName: string;
|
||||||
|
author: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TaskInfo {
|
||||||
|
id: string = '';
|
||||||
|
mode: string = 'book'; // book | list
|
||||||
|
url: string = '';
|
||||||
|
status: string = TaskStatus.QUEUED;
|
||||||
|
bookName: string = '';
|
||||||
|
author: string = '';
|
||||||
|
changeDate: string = '';
|
||||||
|
coverUrl: string = '';
|
||||||
|
descLines: string[] = []; // 转换后的简介行(含图片占位)
|
||||||
|
phase: string = ''; // detail | list | chapters | images | build
|
||||||
|
totalChapters: number = 0;
|
||||||
|
doneChapters: number = 0;
|
||||||
|
failedChapters: number = 0;
|
||||||
|
totalImages: number = 0;
|
||||||
|
doneImages: number = 0;
|
||||||
|
currentTitle: string = '';
|
||||||
|
nodes: ChapterNode[] = [];
|
||||||
|
books: BookProgress[] = []; // 批量模式
|
||||||
|
logs: LogLine[] = [];
|
||||||
|
errorMessage: string = '';
|
||||||
|
epubPath: string = '';
|
||||||
|
txtPath: string = '';
|
||||||
|
createdAt: number = 0;
|
||||||
|
cancelRequested: boolean = false;
|
||||||
|
customTitle: string = ''; // 用户自定义 EPUB 标题(空=用原书名)
|
||||||
|
chapterFilter: number[] = []; // 选中的章节节点 value(空=全部)
|
||||||
|
activeBooksDone: number = 0;
|
||||||
|
activeBooksTotal: number = 0;
|
||||||
|
versionTick: number = 0; // 每次有变化自增,驱动界面刷新
|
||||||
|
|
||||||
|
touch(): void {
|
||||||
|
this.versionTick++;
|
||||||
|
}
|
||||||
|
|
||||||
|
addLog(level: string, msg: string): void {
|
||||||
|
const d = new Date();
|
||||||
|
const time = `${d.getHours() < 10 ? '0' : ''}${d.getHours()}:${d.getMinutes() < 10 ? '0' : ''}${d.getMinutes()}:${d.getSeconds() < 10 ? '0' : ''}${d.getSeconds()}`;
|
||||||
|
this.logs.push({ time: time, level: level, msg: msg });
|
||||||
|
if (this.logs.length > 400) {
|
||||||
|
this.logs.splice(0, this.logs.length - 400);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
progressPercent(): number {
|
||||||
|
if (this.mode === 'list') {
|
||||||
|
if (this.activeBooksTotal === 0) {
|
||||||
|
return this.phase === 'list' ? 5 : 0;
|
||||||
|
}
|
||||||
|
return Math.floor(this.activeBooksDone * 100 / this.activeBooksTotal);
|
||||||
|
}
|
||||||
|
if (this.totalChapters === 0) {
|
||||||
|
return this.status === TaskStatus.DONE || this.status === TaskStatus.DONE_WITH_FAIL ? 100 : 0;
|
||||||
|
}
|
||||||
|
return Math.floor(this.doneChapters * 100 / this.totalChapters);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** LazyForEach 数据源 */
|
||||||
|
export class NodeDataSource implements IDataSource {
|
||||||
|
private listeners: DataChangeListener[] = [];
|
||||||
|
items: ChapterNode[] = [];
|
||||||
|
|
||||||
|
setItems(items: ChapterNode[]): void {
|
||||||
|
this.items = items;
|
||||||
|
this.notifyDataReload();
|
||||||
|
}
|
||||||
|
|
||||||
|
totalCount(): number {
|
||||||
|
return this.items.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
getData(index: number): ChapterNode {
|
||||||
|
return this.items[index];
|
||||||
|
}
|
||||||
|
|
||||||
|
idxOf(node: ChapterNode): number {
|
||||||
|
return this.items.indexOf(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
registerDataChangeListener(listener: DataChangeListener): void {
|
||||||
|
this.listeners.push(listener);
|
||||||
|
}
|
||||||
|
|
||||||
|
unregisterDataChangeListener(listener: DataChangeListener): void {
|
||||||
|
const idx = this.listeners.indexOf(listener);
|
||||||
|
if (idx >= 0) {
|
||||||
|
this.listeners.splice(idx, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
notifyDataReload(): void {
|
||||||
|
for (const l of this.listeners) {
|
||||||
|
l.onDataReloaded();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
notifyChangedAt(index: number): void {
|
||||||
|
for (const l of this.listeners) {
|
||||||
|
l.onDataChange(index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TaskDataSource implements IDataSource {
|
||||||
|
private listeners: DataChangeListener[] = [];
|
||||||
|
items: TaskInfo[] = [];
|
||||||
|
|
||||||
|
setItems(items: TaskInfo[]): void {
|
||||||
|
this.items = items;
|
||||||
|
this.notifyDataReload();
|
||||||
|
}
|
||||||
|
|
||||||
|
totalCount(): number {
|
||||||
|
return this.items.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
getData(index: number): TaskInfo {
|
||||||
|
return this.items[index];
|
||||||
|
}
|
||||||
|
|
||||||
|
registerDataChangeListener(listener: DataChangeListener): void {
|
||||||
|
this.listeners.push(listener);
|
||||||
|
}
|
||||||
|
|
||||||
|
unregisterDataChangeListener(listener: DataChangeListener): void {
|
||||||
|
const idx = this.listeners.indexOf(listener);
|
||||||
|
if (idx >= 0) {
|
||||||
|
this.listeners.splice(idx, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
notifyDataReload(): void {
|
||||||
|
for (const l of this.listeners) {
|
||||||
|
l.onDataReloaded();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 '';
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
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[] = ['下载', '书库', '设置'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 应用入口:HdsNavigation(沉浸光感标题栏 + 渐变模糊)+ HdsTabs 悬浮底部页签(沉浸光感材质),
|
||||||
|
* 子页面(任务详情 / 选章)通过 HdsNavDestination 路由。
|
||||||
|
*/
|
||||||
|
@Entry
|
||||||
|
@Component
|
||||||
|
struct Index {
|
||||||
|
@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() {
|
||||||
|
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;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
.navDestination(this.pagesMap)
|
||||||
|
.mode(NavigationMode.Stack)
|
||||||
|
.titleMode(HdsNavigationTitleMode.MINI)
|
||||||
|
.hideBackButton(true)
|
||||||
|
.titleBar({
|
||||||
|
content: {
|
||||||
|
title: { mainTitle: TAB_TITLES[this.currentTab] }
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
// 非沉浸式列表类页面推荐 GRADIENT_BLUR + 沉浸光感材质
|
||||||
|
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,367 @@
|
|||||||
|
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';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 选章下载页:抓取目录 → 勾选章节(点卷名整卷切换)→ 确认后回填草稿。
|
||||||
|
* 保存的草稿在首页用于「开始下载(已选 N 章)」。操作集中在底部悬浮工具栏。
|
||||||
|
*/
|
||||||
|
@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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,562 @@
|
|||||||
|
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 { PrimaryButton, EmptyView, SymIcon, SegmentedControl } from './Widgets';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 下载页:新建任务(粘贴链接、模式识别、选章与自定义标题、域名/Cookie 检查)+ 任务进度列表。
|
||||||
|
* 页面标题由根 HdsNavigation 标题栏承载,内容区延伸至标题栏与悬浮页签下方。
|
||||||
|
*/
|
||||||
|
@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 siteHost: string = '';
|
||||||
|
@State threadCount: number = 2;
|
||||||
|
@State convertLabel: string = '繁→简';
|
||||||
|
@State autoDetected: boolean = false;
|
||||||
|
@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.threadCount = s.threadCount;
|
||||||
|
this.convertLabel = s.convertMode === 't2s' ? '繁→简' : (s.convertMode === 's2t' ? '简→繁' : '不转换');
|
||||||
|
}
|
||||||
|
|
||||||
|
urlHost(): string {
|
||||||
|
return hostOf(this.urlInput.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
isEsjUrl(): boolean {
|
||||||
|
return this.urlHost().indexOf('esjzone') >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
domainMatch(): boolean {
|
||||||
|
return this.isEsjUrl() && this.urlHost() === this.siteHost;
|
||||||
|
}
|
||||||
|
|
||||||
|
detectMode(): void {
|
||||||
|
const u = this.urlInput.trim();
|
||||||
|
if (u.indexOf('/detail/') >= 0 || /\/\d+\.html/.test(u)) {
|
||||||
|
this.modeIdx = 0;
|
||||||
|
this.autoDetected = true;
|
||||||
|
} else if (u.indexOf('/list-') >= 0 || u.indexOf('/tags/') >= 0) {
|
||||||
|
this.modeIdx = 1;
|
||||||
|
this.autoDetected = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 (url.length === 0 || !this.isEsjUrl() || !this.domainMatch()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
} else {
|
||||||
|
TaskManager.instance.createTask('list', url);
|
||||||
|
}
|
||||||
|
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.domainMatch()) {
|
||||||
|
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' ? '批量' : '单本')
|
||||||
|
.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 }) {
|
||||||
|
Column({ space: 2 }) {
|
||||||
|
Text('新建任务')
|
||||||
|
.fontSize(FontSize.body)
|
||||||
|
.fontWeight(FontWeight.Medium)
|
||||||
|
.fontColor($r('app.color.font_pri'))
|
||||||
|
Text('粘贴 ESJZone 链接,自动抓取章节并打包 EPUB / TXT')
|
||||||
|
.fontSize(FontSize.cap)
|
||||||
|
.fontColor($r('app.color.font_ter'))
|
||||||
|
}
|
||||||
|
.width('100%')
|
||||||
|
.alignItems(HorizontalAlign.Start)
|
||||||
|
|
||||||
|
Row({ space: 8 }) {
|
||||||
|
TextInput({ text: this.urlInput, placeholder: 'https://www.esjzone.cc/detail/…' })
|
||||||
|
.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%')
|
||||||
|
|
||||||
|
Column({ space: 6 }) {
|
||||||
|
SegmentedControl({
|
||||||
|
options: ['单本书籍', '批量列表'],
|
||||||
|
activeIndex: this.modeIdx,
|
||||||
|
onSelect: (idx: number): void => {
|
||||||
|
this.modeIdx = idx;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if (this.autoDetected) {
|
||||||
|
Text('已根据链接自动识别下载模式,可手动修改')
|
||||||
|
.fontSize(FontSize.cap)
|
||||||
|
.fontColor($r('app.color.font_ter'))
|
||||||
|
.padding({ left: 4 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.width('100%')
|
||||||
|
.alignItems(HorizontalAlign.Start)
|
||||||
|
|
||||||
|
// 单本模式:自定义标题 + 选章
|
||||||
|
if (this.modeIdx === 0 && this.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.isEsjUrl()) {
|
||||||
|
Row({ space: 6 }) {
|
||||||
|
SymIcon({
|
||||||
|
sym: $r('sys.symbol.exclamationmark_triangle'),
|
||||||
|
iconSize: 15,
|
||||||
|
colorRes: $r('app.color.warn')
|
||||||
|
})
|
||||||
|
Text('不是 esjzone 链接,请检查')
|
||||||
|
.fontSize(FontSize.cap)
|
||||||
|
.fontColor($r('app.color.warn'))
|
||||||
|
}
|
||||||
|
} 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(`Cookie ${this.cookieReady ? '已配置' : '未配置'}`)
|
||||||
|
.fontSize(FontSize.cap)
|
||||||
|
.fontColor(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.isEsjUrl() && this.domainMatch(),
|
||||||
|
onTap: (): void => {
|
||||||
|
this.startTask();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!this.cookieReady) {
|
||||||
|
Text('提示:未配置 Cookie 时,部分书籍(如 R18 区)将无法访问。可在「设置 → Cookie」中粘贴。')
|
||||||
|
.fontSize(FontSize.cap)
|
||||||
|
.fontColor($r('app.color.font_ter'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.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: '粘贴书籍详情页链接开始\n批量模式支持 /list-/ 与 /tags/ 列表链接'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
.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())
|
||||||
|
}
|
||||||
|
|
||||||
|
Text('下载期间请保持应用在前台;书籍完成后可在「书库」中导出或分享。')
|
||||||
|
.fontSize(FontSize.cap)
|
||||||
|
.fontColor($r('app.color.font_ter'))
|
||||||
|
.width('100%')
|
||||||
|
.padding({ left: 12, right: 12 })
|
||||||
|
}
|
||||||
|
.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'))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
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: '完成下载后,书籍会自动保存在这里\n支持系统分享给阅读器或导出到本地'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
.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)
|
||||||
|
|
||||||
|
ListItem() {
|
||||||
|
Text('文件保存在应用沙箱 library 目录;「导出」可保存到用户选择的位置。')
|
||||||
|
.fontSize(FontSize.cap)
|
||||||
|
.fontColor($r('app.color.font_ter'))
|
||||||
|
.width('100%')
|
||||||
|
.padding({ left: 12, right: 12, top: 4 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.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'))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,411 @@
|
|||||||
|
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 { OpenCC } from '../core/OpenCC';
|
||||||
|
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 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 dictLoaded: boolean = false;
|
||||||
|
@State dictSize: number = 0;
|
||||||
|
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.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;
|
||||||
|
this.dictLoaded = OpenCC.loadedMode === this.convertMode;
|
||||||
|
}
|
||||||
|
|
||||||
|
private persist(): void {
|
||||||
|
const s: AppSettings = {
|
||||||
|
siteUrl: this.siteUrl,
|
||||||
|
cookie: this.cookie,
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
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 warmDict(): Promise<void> {
|
||||||
|
try {
|
||||||
|
const cc = await OpenCC.getConverter(this.convertMode, AppHub.uiContext());
|
||||||
|
if (cc !== null) {
|
||||||
|
this.dictLoaded = true;
|
||||||
|
this.dictSize = cc.dictSize();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
this.dictLoaded = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
build() {
|
||||||
|
Scroll(this.scroller) {
|
||||||
|
Column({ space: Dim.cardGap + 4 }) {
|
||||||
|
Text('所有配置修改后立即生效并自动保存')
|
||||||
|
.fontSize(FontSize.cap)
|
||||||
|
.fontColor($r('app.color.font_ter'))
|
||||||
|
.width('100%')
|
||||||
|
.padding({ left: 12 })
|
||||||
|
|
||||||
|
// ---------- 站点与账号 ----------
|
||||||
|
SectionCard({ title: '站点与账号' }) {
|
||||||
|
Column({ space: 4 }) {
|
||||||
|
SettingRow({
|
||||||
|
title: '站点域名',
|
||||||
|
desc: '脚本中的 base_url,需与下载链接、Cookie 的域名一致'
|
||||||
|
})
|
||||||
|
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' : '原脚本 esj.txt 第一行内容,可直接粘贴'
|
||||||
|
})
|
||||||
|
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: '下载' }) {
|
||||||
|
Column({ space: 4 }) {
|
||||||
|
SettingRow({
|
||||||
|
title: '并发数',
|
||||||
|
desc: `同时下载 ${this.threadCount} 个章节(原脚本 threadNum,站点有反爬,不建议过大)`,
|
||||||
|
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: '失败重试次数',
|
||||||
|
desc: '每个请求失败后的重试次数',
|
||||||
|
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: '请求超时',
|
||||||
|
desc: `读取超时 ${this.timeoutSec} 秒`,
|
||||||
|
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: '下载章节插图',
|
||||||
|
desc: '关闭后插图在正文中保留为文字链接',
|
||||||
|
showToggle: true,
|
||||||
|
isOn: this.downloadImages,
|
||||||
|
onToggle: (v: boolean): void => {
|
||||||
|
this.downloadImages = v;
|
||||||
|
this.persist();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
SettingRow({
|
||||||
|
title: '下载封面',
|
||||||
|
desc: '生成 EPUB 封面页',
|
||||||
|
showToggle: true,
|
||||||
|
isOn: this.downloadCover,
|
||||||
|
onToggle: (v: boolean): void => {
|
||||||
|
this.downloadCover = v;
|
||||||
|
this.persist();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
.width('100%')
|
||||||
|
.padding({ left: Dim.cardPad, right: Dim.cardPad })
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 内容转换 ----------
|
||||||
|
SectionCard({ title: '内容转换' }) {
|
||||||
|
Column({ space: 10 }) {
|
||||||
|
SettingRow({
|
||||||
|
title: '繁简转换',
|
||||||
|
desc: '原脚本 opencc t2s(繁→简)/ s2t(简→繁)'
|
||||||
|
})
|
||||||
|
SegmentedControl({
|
||||||
|
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();
|
||||||
|
this.dictLoaded = false;
|
||||||
|
if (this.convertMode !== CONVERT_NONE) {
|
||||||
|
this.warmDict();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
Text(this.convertMode === CONVERT_NONE
|
||||||
|
? '保持原文,不做转换'
|
||||||
|
: (this.dictLoaded ? `词典已就绪(${this.dictSize} 条词条,OpenCC 数据)` : '词典将在首次转换时自动加载'))
|
||||||
|
.fontSize(FontSize.cap)
|
||||||
|
.fontColor($r('app.color.font_ter'))
|
||||||
|
}
|
||||||
|
.width('100%')
|
||||||
|
.padding({ left: Dim.cardPad, right: Dim.cardPad })
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 输出 ----------
|
||||||
|
SectionCard({ title: '输出' }) {
|
||||||
|
Column({ space: 4 }) {
|
||||||
|
SettingRow({
|
||||||
|
title: '生成 EPUB',
|
||||||
|
desc: '含封面、插图、嵌套目录',
|
||||||
|
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',
|
||||||
|
desc: '插图以原始链接形式保留',
|
||||||
|
showToggle: true,
|
||||||
|
isOn: this.outputTxt,
|
||||||
|
onToggle: (v: boolean): void => {
|
||||||
|
if (!v && !this.outputEpub) {
|
||||||
|
promptAction.showToast({ message: '至少保留一种输出格式' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.outputTxt = v;
|
||||||
|
this.persist();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
Text('文件命名:《书名》作者.epub / .txt')
|
||||||
|
.fontSize(FontSize.cap)
|
||||||
|
.fontColor($r('app.color.font_ter'))
|
||||||
|
}
|
||||||
|
.width('100%')
|
||||||
|
.padding({ left: Dim.cardPad, right: Dim.cardPad })
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 关于 ----------
|
||||||
|
SectionCard({ title: '关于' }) {
|
||||||
|
Column({ space: 6 }) {
|
||||||
|
Text('ESJ下载器 v1.0.0')
|
||||||
|
.fontSize(FontSize.sub)
|
||||||
|
.fontColor($r('app.color.font_pri'))
|
||||||
|
Text('由 esj.py(ESJZone 小说抓取脚本)移植:目录结构分析、章节净化、繁简转换、EPUB/TXT 打包逻辑与原脚本保持一致。繁简词典来自 OpenCC(Apache-2.0 / opencc-data)。')
|
||||||
|
.fontSize(FontSize.cap)
|
||||||
|
.fontColor($r('app.color.font_ter'))
|
||||||
|
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'))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,551 @@
|
|||||||
|
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';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 任务详情:单书模式展示章节树状态,批量模式展示每本书进度;含实时日志。
|
||||||
|
* HdsNavDestination 沉浸光感标题栏 + 底部悬浮工具栏承载页面操作。
|
||||||
|
*/
|
||||||
|
@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');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { httpGetText, httpGetBinary, sniffImageExt } from '../net/HttpUtil';
|
||||||
|
import { parseChapterContent } from '../core/EsjCore';
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
{
|
||||||
|
"module": {
|
||||||
|
"name": "entry",
|
||||||
|
"type": "entry",
|
||||||
|
"description": "$string:module_desc",
|
||||||
|
"mainElement": "EntryAbility",
|
||||||
|
"deviceTypes": [
|
||||||
|
"phone",
|
||||||
|
"tablet"
|
||||||
|
],
|
||||||
|
"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",
|
||||||
|
"srcEntry": "./ets/entryability/EntryAbility.ets",
|
||||||
|
"description": "$string:EntryAbility_desc",
|
||||||
|
"icon": "$media:layered_image",
|
||||||
|
"label": "$string:EntryAbility_label",
|
||||||
|
"startWindowIcon": "$media:startIcon",
|
||||||
|
"startWindowBackground": "$color:start_window_background",
|
||||||
|
"exported": true,
|
||||||
|
"skills": [
|
||||||
|
{
|
||||||
|
"entities": [
|
||||||
|
"entity.system.home"
|
||||||
|
],
|
||||||
|
"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" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"extensionAbilities": [
|
||||||
|
{
|
||||||
|
"name": "EntryBackupAbility",
|
||||||
|
"srcEntry": "./ets/entrybackupability/EntryBackupAbility.ets",
|
||||||
|
"type": "backup",
|
||||||
|
"exported": false,
|
||||||
|
"metadata": [
|
||||||
|
{
|
||||||
|
"name": "ohos.extension.backup",
|
||||||
|
"resource": "$profile:backup_config"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"float": [
|
||||||
|
{
|
||||||
|
"name": "page_text_font_size",
|
||||||
|
"value": "50fp"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"string": [
|
||||||
|
{
|
||||||
|
"name": "module_desc",
|
||||||
|
"value": "ESJZone novel downloader"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "EntryAbility_desc",
|
||||||
|
"value": "ESJZone novel downloader"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "EntryAbility_label",
|
||||||
|
"value": "ESJ下载器"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 6.3 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 160 KiB |
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"layered-image":
|
||||||
|
{
|
||||||
|
"background" : "$media:background",
|
||||||
|
"foreground" : "$media:foreground"
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 130 KiB |
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"allowToBackupRestore": true
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"src": [
|
||||||
|
"pages/Index"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
{
|
||||||
|
"color": [
|
||||||
|
{
|
||||||
|
"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
|
||||||
|
|
||||||
|
一坏 一坯
|
||||||
|
一目瞭然 一目了然
|
||||||
|
七逕 七迳
|
||||||
|
上逕 上迳
|
||||||
|
上鍊 上链
|
||||||
|
不可貲計 不可赀計
|
||||||
|
不瞭解 不了解
|
||||||
|
么麼 幺麽
|
||||||
|
么麽 幺麽
|
||||||
|
九逕山 九迳山
|
||||||
|
乾乾淨淨 干干净净
|
||||||
|
乾乾脆脆 干干脆脆
|
||||||
|
乾佑縣 乾佑县
|
||||||
|
乾元 乾元
|
||||||
|
乾卦 乾卦
|
||||||
|
乾嘉 乾嘉
|
||||||
|
乾圖 乾图
|
||||||
|
乾坤 乾坤
|
||||||
|
乾坤一擲 乾坤一掷
|
||||||
|
乾坤再造 乾坤再造
|
||||||
|
乾坤大挪移 乾坤大挪移
|
||||||
|
乾宅 乾宅
|
||||||
|
乾安縣 乾安县
|
||||||
|
乾安鎮 乾安镇
|
||||||
|
乾州 乾州
|
||||||
|
乾斷 乾断
|
||||||
|
乾斷食 干断食
|
||||||
|
乾旦 乾旦
|
||||||
|
乾曜 乾曜
|
||||||
|
乾清宮 乾清宫
|
||||||
|
乾盛世 乾盛世
|
||||||
|
乾紅 干红 乾红
|
||||||
|
乾綱 乾纲
|
||||||
|
乾縣 乾县
|
||||||
|
乾象 乾象
|
||||||
|
乾造 乾造
|
||||||
|
乾道 乾道
|
||||||
|
乾闥婆 乾闼婆
|
||||||
|
乾陵 乾陵
|
||||||
|
乾隆 乾隆
|
||||||
|
乾隆年間 乾隆年间
|
||||||
|
乾隆皇帝 乾隆皇帝
|
||||||
|
二噁英 二𫫇英
|
||||||
|
仇讎 仇雠
|
||||||
|
以免藉口 以免借口
|
||||||
|
以功覆過 以功覆过
|
||||||
|
任筆沈詩 任笔沈诗
|
||||||
|
侔德覆載 侔德覆载
|
||||||
|
傢俱 家具
|
||||||
|
傷亡枕藉 伤亡枕藉
|
||||||
|
允祕 允祕
|
||||||
|
八濛山 八濛山
|
||||||
|
其陰多蒐 其阴多蒐
|
||||||
|
凌藉 凌借
|
||||||
|
出醜狼藉 出丑狼藉
|
||||||
|
函覆 函复
|
||||||
|
剋架 剋架
|
||||||
|
剋毒 剋毒
|
||||||
|
千鍾粟 千锺粟
|
||||||
|
南氾 南氾
|
||||||
|
南逕 南迳
|
||||||
|
反反覆覆 反反复复
|
||||||
|
反覆 反复
|
||||||
|
反覆思維 反复思维
|
||||||
|
反覆思量 反复思量
|
||||||
|
反覆性 反复性
|
||||||
|
名覆金甌 名复金瓯
|
||||||
|
吳祕 吴祕
|
||||||
|
吳育昇 吴育昇
|
||||||
|
哪吒 哪吒
|
||||||
|
回覆 回复
|
||||||
|
土坏 土坯
|
||||||
|
坏土 坯土
|
||||||
|
坏子 坯子
|
||||||
|
坏布 坯布
|
||||||
|
坏戶 坯户
|
||||||
|
墨沈沈 墨沉沉
|
||||||
|
壺裏乾坤 壶里乾坤
|
||||||
|
大目乾連冥間救母變文 大目乾连冥间救母变文
|
||||||
|
宫商角徵羽 宫商角徵羽
|
||||||
|
射覆 射覆
|
||||||
|
尼乾子 尼乾子
|
||||||
|
尼乾陀 尼乾陀
|
||||||
|
年釐 年釐
|
||||||
|
幺麼 幺麽
|
||||||
|
幺麼小丑 幺麽小丑
|
||||||
|
幺麼小醜 幺麽小丑
|
||||||
|
康乾 康乾
|
||||||
|
張昇 张昇
|
||||||
|
張法乾 张法乾
|
||||||
|
彷彿 仿佛
|
||||||
|
彷徨 彷徨
|
||||||
|
徐胤昇 徐胤昇
|
||||||
|
復甦 复苏
|
||||||
|
徵弦 徵弦
|
||||||
|
徵絃 徵弦
|
||||||
|
徵羽摩柯 徵羽摩柯
|
||||||
|
徵聲 徵声
|
||||||
|
徵調 徵调
|
||||||
|
徵音 徵音
|
||||||
|
情有獨鍾 情有独钟 情有独锺
|
||||||
|
想像 想像 想象
|
||||||
|
意志消沈 意志消沉
|
||||||
|
慰藉 慰藉
|
||||||
|
慰藉着 慰藉着
|
||||||
|
憑藉 凭借
|
||||||
|
憑藉着 凭借着
|
||||||
|
懷釐 怀釐
|
||||||
|
成甦 成甦
|
||||||
|
所費不貲 所费不赀
|
||||||
|
手鍊 手链
|
||||||
|
打坏 打坯
|
||||||
|
扞格 扞格
|
||||||
|
扭轉乾坤 扭转乾坤
|
||||||
|
批覆 批复
|
||||||
|
找藉口 找借口
|
||||||
|
折戟沈沙 折戟沉沙
|
||||||
|
折戟沈河 折戟沉河
|
||||||
|
拉坏 拉坯
|
||||||
|
拉鍊 拉链
|
||||||
|
拉鍊工程 拉链工程
|
||||||
|
拜覆 拜复
|
||||||
|
挨剋 挨剋
|
||||||
|
捏坏 捏坯
|
||||||
|
擊沈 击沉
|
||||||
|
據瞭解 据了解
|
||||||
|
文錦覆阱 文锦覆阱
|
||||||
|
於世成 於世成
|
||||||
|
於乎 於乎
|
||||||
|
於仲完 於仲完
|
||||||
|
於倫 於伦
|
||||||
|
於其一 於其一
|
||||||
|
於則 於则
|
||||||
|
於勇明 於勇明
|
||||||
|
於呼哀哉 於呼哀哉
|
||||||
|
於單 於单
|
||||||
|
於坦 於坦
|
||||||
|
於崇文 於崇文
|
||||||
|
於忠祥 於忠祥
|
||||||
|
於惟一 於惟一
|
||||||
|
於戲 於戏
|
||||||
|
於敖 於敖
|
||||||
|
於梨華 於梨华
|
||||||
|
於清言 於清言
|
||||||
|
於潛 於潜
|
||||||
|
於琳 於琳
|
||||||
|
於穆 於穆
|
||||||
|
於竹屋 於竹屋
|
||||||
|
於菟 於菟
|
||||||
|
於邑 於邑
|
||||||
|
於陵子 於陵子
|
||||||
|
旋乾轉坤 旋乾转坤
|
||||||
|
旋轉乾坤 旋转乾坤
|
||||||
|
旋轉乾坤之力 旋转乾坤之力
|
||||||
|
明瞭 明了
|
||||||
|
明覆 明复
|
||||||
|
昏沈 昏沉
|
||||||
|
春蒐 春蒐
|
||||||
|
春釐 春釐
|
||||||
|
暗沈沈 暗沉沉
|
||||||
|
書中自有千鍾粟 书中自有千锺粟
|
||||||
|
有序 有序
|
||||||
|
朝乾夕惕 朝乾夕惕
|
||||||
|
木吒 木吒
|
||||||
|
李乾德 李乾德
|
||||||
|
李昇 李昇
|
||||||
|
李昇勳 李昇勋
|
||||||
|
李澤鉅 李泽钜
|
||||||
|
李祕 李祕
|
||||||
|
李鍊福 李链福
|
||||||
|
李鍾郁 李锺郁
|
||||||
|
束脩 束脩 束修
|
||||||
|
東氾 东氾
|
||||||
|
林甦 林甦
|
||||||
|
校讎 校雠
|
||||||
|
梁昇卿 梁昇卿 梁升卿
|
||||||
|
梁章鉅 梁章钜
|
||||||
|
楊甦棣 杨甦棣
|
||||||
|
楊聯陞 杨联陞
|
||||||
|
樊於期 樊於期
|
||||||
|
橡椀 橡椀
|
||||||
|
死氣沈沈 死气沉沉
|
||||||
|
段脩 段脩
|
||||||
|
毛坏 毛坯
|
||||||
|
水逕 水迳
|
||||||
|
氾勝之 氾胜之
|
||||||
|
氾南 氾南
|
||||||
|
氾國 氾国
|
||||||
|
氾水 氾水
|
||||||
|
沈下 沉下
|
||||||
|
沈不住氣 沉不住气
|
||||||
|
沈住氣 沉住气
|
||||||
|
沈冤 沉冤
|
||||||
|
沈厚 沉厚
|
||||||
|
沈吟 沉吟
|
||||||
|
沈寂 沉寂
|
||||||
|
沈得住氣 沉得住气
|
||||||
|
沈思 沉思
|
||||||
|
沈思往事 沉思往事
|
||||||
|
沈悶 沉闷
|
||||||
|
沈沒 沉没
|
||||||
|
沈沒成本 沉没成本
|
||||||
|
沈浮 沉浮
|
||||||
|
沈浸 沉浸
|
||||||
|
沈浸於 沉浸于
|
||||||
|
沈淪 沉沦
|
||||||
|
沈湎 沉湎
|
||||||
|
沈湎酒色 沉湎酒色
|
||||||
|
沈溺 沉溺
|
||||||
|
沈滯 沉滞
|
||||||
|
沈滯性 沉滞性
|
||||||
|
沈澱 沉淀
|
||||||
|
沈澱出來 沉淀出来
|
||||||
|
沈澱劑 沉淀剂
|
||||||
|
沈澱法 沉淀法
|
||||||
|
沈澱物 沉淀物
|
||||||
|
沈濁 沉浊
|
||||||
|
沈甸甸 沉甸甸
|
||||||
|
沈痛 沉痛
|
||||||
|
沈痼 沉痼
|
||||||
|
沈痾 沉疴
|
||||||
|
沈睡 沉睡
|
||||||
|
沈睡不醒 沉睡不醒
|
||||||
|
沈砂池 沉砂池
|
||||||
|
沈積 沉积
|
||||||
|
沈積岩 沉积岩
|
||||||
|
沈積石 沉积石
|
||||||
|
沈筒 沉筒
|
||||||
|
沈船 沉船
|
||||||
|
沈落 沉落
|
||||||
|
沈詩任筆 沈诗任笔
|
||||||
|
沈迷 沉迷
|
||||||
|
沈迷不醒 沉迷不醒
|
||||||
|
沈醉 沉醉
|
||||||
|
沈重 沉重
|
||||||
|
沈降 沉降
|
||||||
|
沈陷 沉陷
|
||||||
|
沈靜 沉静
|
||||||
|
沈靜下來 沉静下来
|
||||||
|
沈香 沉香
|
||||||
|
沈鬱 沉郁
|
||||||
|
沈魚落雁 沉鱼落雁
|
||||||
|
沈默 沉默
|
||||||
|
沈默不語 沉默不语
|
||||||
|
沈默寡言 沉默寡言
|
||||||
|
沙逕 沙迳
|
||||||
|
河逕 河迳
|
||||||
|
流徵 流徵
|
||||||
|
浪蕩乾坤 浪荡乾坤
|
||||||
|
浮沈 浮沉
|
||||||
|
海哩 海里
|
||||||
|
深沈 深沉
|
||||||
|
深沈不露 深沉不露
|
||||||
|
溫昇豪 温昇豪
|
||||||
|
滑藉 滑借
|
||||||
|
烏昇 乌昇
|
||||||
|
烏沈沈 乌沉沉
|
||||||
|
烏逕 乌迳
|
||||||
|
無序 无序
|
||||||
|
狐藉虎威 狐借虎威
|
||||||
|
王彥昇 王彦昇
|
||||||
|
珍珠項鍊 珍珠项链
|
||||||
|
甚鉅 甚钜
|
||||||
|
甦生 苏生
|
||||||
|
甦醒 苏醒
|
||||||
|
申昇勳 申昇勋
|
||||||
|
申覆 申复
|
||||||
|
畢昇 毕昇
|
||||||
|
發覆 发覆
|
||||||
|
盧象昇 卢象昇
|
||||||
|
目劄 目劄
|
||||||
|
瞭哨 瞭哨
|
||||||
|
瞭如 了如
|
||||||
|
瞭如指掌 了如指掌
|
||||||
|
瞭望 瞭望
|
||||||
|
瞭然 了然
|
||||||
|
瞭然於心 了然于心
|
||||||
|
瞭若指掌 了若指掌
|
||||||
|
瞭解 了解
|
||||||
|
瞭解到 了解到
|
||||||
|
破釜沈舟 破釜沉舟
|
||||||
|
磚坏 砖坯
|
||||||
|
示覆 示复
|
||||||
|
社逕 社迳
|
||||||
|
祕丕笈 祕丕笈
|
||||||
|
祕彭祖 祕彭祖
|
||||||
|
祕瓊 祕琼
|
||||||
|
祝釐 祝釐
|
||||||
|
神祇 神祇
|
||||||
|
稟覆 禀复
|
||||||
|
竺乾 竺乾
|
||||||
|
答覆 答复
|
||||||
|
篤麼 笃麽
|
||||||
|
簡單明瞭 简单明了
|
||||||
|
籌畫 筹划
|
||||||
|
素藉 素借
|
||||||
|
老態龍鍾 老态龙钟 老态龙锺
|
||||||
|
耳沈 耳沉
|
||||||
|
肉脩 肉脩
|
||||||
|
肘手鍊足 肘手链足
|
||||||
|
胤祕 胤祕
|
||||||
|
脩敬 脩敬
|
||||||
|
脩炳 脩炳
|
||||||
|
脩脡 脩脡
|
||||||
|
脩脯 脩脯
|
||||||
|
脩金 脩金
|
||||||
|
脫坏 脱坯
|
||||||
|
腶脩 腶脩
|
||||||
|
英哩 英里
|
||||||
|
茅蒐 茅蒐
|
||||||
|
茵藉 茵借
|
||||||
|
萬鍾 万锺
|
||||||
|
落雁沈魚 落雁沉鱼
|
||||||
|
蒐于紅 蒐于红
|
||||||
|
蒐於紅 蒐于红
|
||||||
|
蒐狩 蒐狩
|
||||||
|
蒐獮 蒐狝
|
||||||
|
蒐獵 蒐猎
|
||||||
|
蒐田 蒐田
|
||||||
|
蒐畋 蒐畋
|
||||||
|
蒐苗 蒐苗
|
||||||
|
蒜薹 蒜薹
|
||||||
|
蔣昇 蒋昇
|
||||||
|
蕓薹 芸薹
|
||||||
|
蕩覆 荡覆
|
||||||
|
蕭乾 萧乾
|
||||||
|
藉代 借代
|
||||||
|
藉以 借以
|
||||||
|
藉助 借助
|
||||||
|
藉助於 借助于
|
||||||
|
藉卉 借卉
|
||||||
|
藉口 借口
|
||||||
|
藉喻 借喻
|
||||||
|
藉寇兵 借寇兵
|
||||||
|
藉寇兵齎盜糧 借寇兵赍盗粮
|
||||||
|
藉手 借手
|
||||||
|
藉據 借据
|
||||||
|
藉故 借故
|
||||||
|
藉故推辭 借故推辞
|
||||||
|
藉方 借方
|
||||||
|
藉條 借条
|
||||||
|
藉槁 借槁
|
||||||
|
藉機 借机
|
||||||
|
藉此 借此
|
||||||
|
藉此機會 借此机会
|
||||||
|
藉甚 借甚
|
||||||
|
藉由 借由
|
||||||
|
藉着 借着
|
||||||
|
藉端 借端
|
||||||
|
藉端生事 借端生事
|
||||||
|
藉箸代籌 借箸代筹
|
||||||
|
藉草枕塊 借草枕块
|
||||||
|
藉藉 藉藉
|
||||||
|
藉藉无名 藉藉无名
|
||||||
|
藉詞 借词
|
||||||
|
藉讀 借读
|
||||||
|
藉資 借资
|
||||||
|
衹得 只得
|
||||||
|
衹見樹木 只见树木
|
||||||
|
衹見樹木不見森林 只见树木不见森林
|
||||||
|
袁祕 袁祕
|
||||||
|
袖裏乾坤 袖里乾坤
|
||||||
|
袷袢 袷袢
|
||||||
|
製坏 制坯
|
||||||
|
覆上 覆上
|
||||||
|
覆住 覆住
|
||||||
|
覆信 复信
|
||||||
|
覆冒 覆冒
|
||||||
|
覆呈 复呈
|
||||||
|
覆命 复命
|
||||||
|
覆墓 复墓
|
||||||
|
覆宗 覆宗
|
||||||
|
覆帳 复帐
|
||||||
|
覆幬 覆帱
|
||||||
|
覆成 覆成
|
||||||
|
覆按 复按
|
||||||
|
覆文 复文
|
||||||
|
覆杯 覆杯
|
||||||
|
覆校 复校
|
||||||
|
覆瓿 覆瓿
|
||||||
|
覆盂 覆盂
|
||||||
|
覆盆 覆盆
|
||||||
|
覆盆子 覆盆子
|
||||||
|
覆盤 覆盘
|
||||||
|
覆育 覆育
|
||||||
|
覆蕉尋鹿 覆蕉寻鹿
|
||||||
|
覆逆 覆逆
|
||||||
|
覆醢 覆醢
|
||||||
|
覆醬瓿 覆酱瓿
|
||||||
|
覆電 复电
|
||||||
|
覆露 覆露
|
||||||
|
覆鹿尋蕉 覆鹿寻蕉
|
||||||
|
覆鹿遺蕉 覆鹿遗蕉
|
||||||
|
覆鼎 覆鼎
|
||||||
|
見覆 见复
|
||||||
|
角徵 角徵
|
||||||
|
角徵羽 角徵羽
|
||||||
|
計畫 计划
|
||||||
|
許甦魂 许甦魂
|
||||||
|
變徵 变徵
|
||||||
|
變徵之聲 变徵之声
|
||||||
|
變徵之音 变徵之音
|
||||||
|
讎定 雠定
|
||||||
|
谿工 谿工
|
||||||
|
貂覆額 貂覆额
|
||||||
|
買臣覆水 买臣覆水
|
||||||
|
赤石逕 赤石迳
|
||||||
|
踅門瞭戶 踅门了户
|
||||||
|
躪藉 躏借
|
||||||
|
載沈載浮 载沉载浮
|
||||||
|
載浮載沈 载浮载沉
|
||||||
|
辛祕 辛祕
|
||||||
|
逆釐 逆釐
|
||||||
|
逕口 迳口
|
||||||
|
逕聯 迳联
|
||||||
|
逕頭 迳头
|
||||||
|
郭子乾 郭子乾
|
||||||
|
酒逢知己千鍾少 酒逢知己千锺少
|
||||||
|
醞藉 酝借
|
||||||
|
重覆 重复
|
||||||
|
金吒 金吒
|
||||||
|
金昇玟 金昇玟
|
||||||
|
金鍊 金链
|
||||||
|
鈞覆 钧复
|
||||||
|
鉅子 钜子
|
||||||
|
鉅萬 钜万
|
||||||
|
鉅防 钜防
|
||||||
|
鉸鍊 铰链
|
||||||
|
銀鍊 银链
|
||||||
|
鋼坏 钢坯
|
||||||
|
錢鍾書 钱锺书
|
||||||
|
鍊墜 链坠
|
||||||
|
鍊子 链子
|
||||||
|
鍊形 链形
|
||||||
|
鍊條 链条
|
||||||
|
鍊錘 链锤
|
||||||
|
鍊鎖 链锁
|
||||||
|
鍛鍾 锻锺
|
||||||
|
鍾繇 锺繇 钟繇
|
||||||
|
鍾萬梅 锺万梅
|
||||||
|
鍾重發 锺重发
|
||||||
|
鍾鍛 锺锻
|
||||||
|
鍾馗 锺馗
|
||||||
|
鎖鍊 锁链
|
||||||
|
鐵鍊 铁链
|
||||||
|
鑽石項鍊 钻石项链
|
||||||
|
鑿坏 凿坯
|
||||||
|
閻鶴昇 阎鹤昇
|
||||||
|
陰沈 阴沉
|
||||||
|
陰沈沈 阴沉沉
|
||||||
|
陰陰沈沈 阴阴沉沉
|
||||||
|
陳志昇 陈志昇
|
||||||
|
陳昇 陈昇
|
||||||
|
陳甦 陈甦
|
||||||
|
陶坏 陶坯
|
||||||
|
雁杳魚沈 雁杳鱼沉
|
||||||
|
雖覆能復 虽覆能复
|
||||||
|
電覆 电复
|
||||||
|
露覆 露覆
|
||||||
|
韓昇延 韩昇延
|
||||||
|
韓甦 韩甦
|
||||||
|
項鍊 项链
|
||||||
|
頗覆 颇覆
|
||||||
|
頸鍊 颈链
|
||||||
|
顛乾倒坤 颠乾倒坤
|
||||||
|
顛倒乾坤 颠倒乾坤
|
||||||
|
顧藉 顾借
|
||||||
|
馮甦 冯甦
|
||||||
|
魏徵 魏徵 魏征
|
||||||
|
魚沈雁杳 鱼沉雁杳
|
||||||
|
麪坏兒 面坯儿
|
||||||
|
麼些族 麽些族
|
||||||
|
黃甦 黄甦
|
||||||
|
黃鍾公 黄锺公
|
||||||
|
黑沈沈 黑沉沉
|
||||||
|
龍鍾 龙钟 龙锺
|
||||||
|
龔昇 龚昇
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"modelVersion": "26.0.0",
|
||||||
|
"dependencies": {
|
||||||
|
},
|
||||||
|
"execution": {
|
||||||
|
// "analyze": "normal", /* Define the build analyze mode. Value: [ "normal" | "advanced" | "ultrafine" | false ]. Default: "normal" */
|
||||||
|
// "daemon": true, /* Enable daemon compilation. Value: [ true | false ]. Default: true */
|
||||||
|
// "incremental": true, /* Enable incremental compilation. Value: [ true | false ]. Default: true */
|
||||||
|
// "parallel": true, /* Enable parallel compilation. Value: [ true | false ]. Default: true */
|
||||||
|
// "typeCheck": false, /* Enable typeCheck. Value: [ true | false ]. Default: false */
|
||||||
|
// "optimizationStrategy": "memory" /* Define the optimization strategy. Value: [ "memory" | "performance" ]. Default: "memory" */
|
||||||
|
},
|
||||||
|
"logging": {
|
||||||
|
// "level": "info" /* Define the log level. Value: [ "debug" | "info" | "warn" | "error" ]. Default: "info" */
|
||||||
|
},
|
||||||
|
"debugging": {
|
||||||
|
// "stacktrace": false /* Disable stacktrace compilation. Value: [ true | false ]. Default: false */
|
||||||
|
},
|
||||||
|
"nodeOptions": {
|
||||||
|
// "maxOldSpaceSize": 8192 /* Enable nodeOptions maxOldSpaceSize compilation. Unit M. Used for the daemon process. Default: 8192*/
|
||||||
|
// "exposeGC": true /* Enable to trigger garbage collection explicitly. Default: true*/
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +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. */,
|
||||||
|
};
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"modelVersion": "26.0.0",
|
||||||
|
"description": "Please describe the basic information.",
|
||||||
|
"dependencies": {
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@ohos/hypium": "1.0.25",
|
||||||
|
"@ohos/hamock": "1.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user