@yyds-dudu/dsh-novel-reader 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +73 -8
- package/client.js +1023 -111
- package/docs/SOURCES.md +90 -0
- package/docs/screenshot-online-reading.png +0 -0
- package/docs/screenshot-online-search.png +0 -0
- package/docs/screenshot-online-shelf.png +0 -0
- package/docs/screenshot-sources.png +0 -0
- package/index.js +197 -2
- package/lib/community-sources.js +2090 -0
- package/lib/html.js +52 -0
- package/lib/http.js +62 -0
- package/lib/legado.js +345 -0
- package/lib/sources/custom.js +76 -0
- package/lib/sources/daizhige.js +68 -0
- package/lib/sources/index.js +34 -0
- package/lib/sources/wikisource.js +244 -0
- package/locale/en.json +118 -33
- package/locale/zh.json +114 -29
- package/package.json +11 -2
package/lib/html.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
const NAMED_ENTITIES = {
|
|
2
|
+
amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: '\u00a0',
|
|
3
|
+
middot: '·', hellip: '…', mdash: '—', ldquo: '“', rdquo: '”',
|
|
4
|
+
lsquo: '‘', rsquo: '’', times: '×', copy: '©', reg: '®', deg: '°',
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
/** 解码 HTML 实体:命名实体 + 十进制/十六进制数字实体。 */
|
|
8
|
+
export function decodeEntities(text) {
|
|
9
|
+
return String(text).replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g, (whole, body) => {
|
|
10
|
+
if (body[0] === '#') {
|
|
11
|
+
const hex = body[1] === 'x' || body[1] === 'X';
|
|
12
|
+
const code = Number.parseInt(hex ? body.slice(2) : body.slice(1), hex ? 16 : 10);
|
|
13
|
+
return code > 0 && code < 0x110000 ? String.fromCodePoint(code) : whole;
|
|
14
|
+
}
|
|
15
|
+
const value = NAMED_ENTITIES[body.toLowerCase()];
|
|
16
|
+
return value == null ? whole : value;
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 用一条正则从 HTML 里截取目标片段。优先取命名组 body,
|
|
22
|
+
* 没有命名组时取整个匹配,便于用户直接抄站点原来的一段正则。
|
|
23
|
+
*/
|
|
24
|
+
export function sliceByRegex(html, source) {
|
|
25
|
+
const re = new RegExp(source, 's');
|
|
26
|
+
const match = re.exec(html);
|
|
27
|
+
if (!match) return null;
|
|
28
|
+
return match.groups && match.groups.body != null ? match.groups.body : match[0];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 片段 → 段落文本:去脚本样式、块级标签转换行、剥标签、解实体。段落之间空一行。 */
|
|
32
|
+
export function htmlToText(fragment) {
|
|
33
|
+
const plain = decodeEntities(
|
|
34
|
+
String(fragment)
|
|
35
|
+
.replace(/<(script|style|noscript)[\s\S]*?<\/\1>/gi, '')
|
|
36
|
+
.replace(/<br\s*\/?>/gi, '\n')
|
|
37
|
+
.replace(/<\/(p|div|h[1-6]|li|tr|section|article|blockquote|dd|dt)>/gi, '\n')
|
|
38
|
+
.replace(/<[^>]+>/g, ''),
|
|
39
|
+
);
|
|
40
|
+
const lines = plain
|
|
41
|
+
.replace(/\r\n?/g, '\n')
|
|
42
|
+
.split('\n')
|
|
43
|
+
.map((line) => line.replace(/^[\s\u3000]+|[\s\u3000]+$/g, ''))
|
|
44
|
+
.filter(Boolean);
|
|
45
|
+
return lines.join('\n\n');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 从 <title> 或 og:title 取书名,兜底返回空串。 */
|
|
49
|
+
export function pageTitle(html) {
|
|
50
|
+
const m = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(String(html));
|
|
51
|
+
return m ? decodeEntities(m[1]).replace(/\s+/g, ' ').trim().slice(0, 80) : '';
|
|
52
|
+
}
|
package/lib/http.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
const MAX_BYTES = 8 * 1024 * 1024;
|
|
2
|
+
const TIMEOUT_MS = 20_000;
|
|
3
|
+
// 只跑在本机,但仍然拒绝内网/回环地址:书源 spec 来自用户粘贴的 JSON,
|
|
4
|
+
// 别让它变成内网探测工具(也避免访问路由器、本机服务)。
|
|
5
|
+
const PRIVATE_HOST = /^(localhost|127\.|0\.0\.0\.0|10\.|192\.168\.|169\.254\.|172\.(1[6-9]|2\d|3[01])\.|\[::1\]|::1)/i;
|
|
6
|
+
|
|
7
|
+
/** 校验地址必须是公网 http(s),返回 URL 对象。 */
|
|
8
|
+
export function assertPublicUrl(raw) {
|
|
9
|
+
let url;
|
|
10
|
+
try { url = new URL(raw); } catch { throw new Error('地址不合法:' + raw); }
|
|
11
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new Error('只支持 http/https 地址');
|
|
12
|
+
if (PRIVATE_HOST.test(url.hostname)) throw new Error('不允许访问内网地址');
|
|
13
|
+
return url;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** 按 charset 解码;未声明时先严格 UTF-8,失败再按 GBK。 */
|
|
17
|
+
export function decodeBytes(bytes, encoding) {
|
|
18
|
+
const tryDecode = (label) => {
|
|
19
|
+
try { return new TextDecoder(label).decode(bytes); } catch { return null; }
|
|
20
|
+
};
|
|
21
|
+
const declared = encoding ? tryDecode(String(encoding).toLowerCase()) : null;
|
|
22
|
+
if (declared != null) return declared;
|
|
23
|
+
try {
|
|
24
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
25
|
+
} catch {
|
|
26
|
+
const gbk = tryDecode('gbk');
|
|
27
|
+
if (gbk != null) return gbk;
|
|
28
|
+
throw new Error('无法解码页面内容');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function charsetOf(contentType) {
|
|
33
|
+
const m = /charset=([\w-]+)/i.exec(contentType || '');
|
|
34
|
+
return m ? m[1].toLowerCase() : '';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 取一个公网页面并解码为文本。
|
|
39
|
+
* @param {string} raw 目标地址
|
|
40
|
+
* @param {{ encoding?: string, timeoutMs?: number, headers?: Record<string,string> }} options
|
|
41
|
+
*/
|
|
42
|
+
export async function fetchText(raw, options = {}) {
|
|
43
|
+
const target = assertPublicUrl(raw);
|
|
44
|
+
const response = await fetch(target, {
|
|
45
|
+
headers: {
|
|
46
|
+
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36',
|
|
47
|
+
accept: 'text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8',
|
|
48
|
+
'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
|
|
49
|
+
...(options.headers || {}),
|
|
50
|
+
},
|
|
51
|
+
redirect: 'follow',
|
|
52
|
+
signal: AbortSignal.timeout(options.timeoutMs || TIMEOUT_MS),
|
|
53
|
+
});
|
|
54
|
+
// 跟随重定向后确认落点仍是公网,避免用 302 绕开上面的校验
|
|
55
|
+
assertPublicUrl(response.url || String(target));
|
|
56
|
+
if (!response.ok) throw new Error('页面请求失败:HTTP ' + response.status);
|
|
57
|
+
const declaredLength = Number(response.headers.get('content-length') || 0);
|
|
58
|
+
if (declaredLength > MAX_BYTES) throw new Error('页面过大,已放弃');
|
|
59
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
60
|
+
if (bytes.byteLength > MAX_BYTES) throw new Error('页面过大,已放弃');
|
|
61
|
+
return decodeBytes(bytes, options.encoding || charsetOf(response.headers.get('content-type')));
|
|
62
|
+
}
|
package/lib/legado.js
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 阅读3 / Legado 书源兼容层(纯规则子集)。
|
|
3
|
+
* 支持 jsoup 默认规则、CSS、JSONPath、正则;JS/WebView 规则明确拒绝。
|
|
4
|
+
*/
|
|
5
|
+
import { parseDocument, DomUtils } from 'htmlparser2';
|
|
6
|
+
import { render } from 'dom-serializer';
|
|
7
|
+
import { fetchText } from './http.js';
|
|
8
|
+
import { htmlToText, decodeEntities } from './html.js';
|
|
9
|
+
|
|
10
|
+
const ACCESSOR = /^(text|textNodes|ownText|html|all|href|src|content|value|title|alt|class|id|attr\([^)]+\))$/;
|
|
11
|
+
|
|
12
|
+
export function isLegadoSource(spec) {
|
|
13
|
+
return !!(spec && typeof spec === 'object' && !Array.isArray(spec)
|
|
14
|
+
&& (spec.bookSourceUrl || spec.bookSourceName)
|
|
15
|
+
&& (spec.ruleSearch || spec.ruleToc || spec.ruleContent));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** 校验书源,把不支持的规则明确指出来。 */
|
|
19
|
+
export function validateLegado(spec) {
|
|
20
|
+
if (!isLegadoSource(spec)) throw new Error('不是 Legado 书源 JSON');
|
|
21
|
+
const name = String(spec.bookSourceName || spec.bookSourceUrl || '').trim();
|
|
22
|
+
if (!name) throw new Error('缺少 bookSourceName');
|
|
23
|
+
const search = spec.ruleSearch || {}, toc = spec.ruleToc || {}, content = spec.ruleContent || {};
|
|
24
|
+
if (!spec.searchUrl || !search.bookList) throw new Error('缺少 searchUrl 或 ruleSearch.bookList');
|
|
25
|
+
if (!toc.chapterList) throw new Error('缺少 ruleToc.chapterList');
|
|
26
|
+
if (!content.content) throw new Error('缺少 ruleContent.content');
|
|
27
|
+
const rules = [spec.searchUrl, search.bookList, search.name, search.bookUrl,
|
|
28
|
+
toc.chapterList, toc.chapterName, toc.chapterUrl, content.content].filter(Boolean).join(' ');
|
|
29
|
+
if (/@js:|<js[\s>]/i.test(rules)) throw new Error('这个书源使用了 JS 规则,当前版本只支持纯规则书源');
|
|
30
|
+
if (/^\s*\/\//.test(String(toc.chapterList))) throw new Error('ruleToc.chapterList 使用了 XPath,暂不支持');
|
|
31
|
+
const header = String(spec.header || '');
|
|
32
|
+
const charset = /"charset"\s*:\s*"([^"]+)"/.exec(header)?.[1] || '';
|
|
33
|
+
return { name: name.slice(0, 60), base: String(spec.bookSourceUrl || '').trim(),
|
|
34
|
+
searchUrl: spec.searchUrl, search, toc, content, info: spec.ruleBookInfo || {}, charset, header };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function collect(nodes) {
|
|
38
|
+
const out = [];
|
|
39
|
+
for (const n of nodes || []) {
|
|
40
|
+
if (!n) continue;
|
|
41
|
+
if (n.type === 'tag' || n.type === 'text') out.push(n);
|
|
42
|
+
if (n.children) out.push(...collect(n.children));
|
|
43
|
+
}
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function absolute(raw, base) {
|
|
48
|
+
try { return new URL(String(raw), base).href; } catch { return ''; }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 解析单段选择器:class.x / id.x / tag.x / 带 .N 索引或 !N:M 排除、CSS 片段。 */
|
|
52
|
+
function applyStep(nodes, raw) {
|
|
53
|
+
const str = String(raw || '').trim();
|
|
54
|
+
if (!str) return nodes;
|
|
55
|
+
if (str.startsWith('@css:')) return cssSelect(nodes, str.slice(5));
|
|
56
|
+
// 注意:jsoup 默认规则形如 class.x / id.x / tag.x,不能被误判成 CSS 选择器。
|
|
57
|
+
if (!/^(class|id|tag|text|attr)\./.test(str) && /^[a-zA-Z][\w-]*[.#]/.test(str)) return cssSelect(nodes, str);
|
|
58
|
+
const m = /^(class|id|tag|text|attr)\.([\s\S]+)$/.exec(str);
|
|
59
|
+
if (!m) {
|
|
60
|
+
if (/^-?\d+$/.test(str)) { const i = Number(str); return [nodes[i < 0 ? nodes.length + i : i]].filter(Boolean); }
|
|
61
|
+
return collect(nodes).filter(n => n.type === 'text' && n.data.includes(str));
|
|
62
|
+
}
|
|
63
|
+
const kind = m[1];
|
|
64
|
+
let name = m[2], index = null, exclude = null;
|
|
65
|
+
const bang = name.indexOf('!');
|
|
66
|
+
if (bang >= 0) {
|
|
67
|
+
exclude = name.slice(bang + 1).split(':').filter(Boolean).map(Number);
|
|
68
|
+
name = name.slice(0, bang);
|
|
69
|
+
} else {
|
|
70
|
+
const dot = name.lastIndexOf('.');
|
|
71
|
+
if (dot > 0 && /^\d+$/.test(name.slice(dot + 1))) { index = Number(name.slice(dot + 1)); name = name.slice(0, dot); }
|
|
72
|
+
}
|
|
73
|
+
let found;
|
|
74
|
+
if (kind === 'class') found = collect(nodes).filter(n => n.type === 'tag' && (DomUtils.getAttributeValue(n, 'class') || '').split(/\s+/).includes(name));
|
|
75
|
+
else if (kind === 'id') found = collect(nodes).filter(n => n.type === 'tag' && DomUtils.getAttributeValue(n, 'id') === name);
|
|
76
|
+
else if (kind === 'tag') found = DomUtils.getElementsByTagName(name, nodes, true);
|
|
77
|
+
else if (kind === 'text') found = collect(nodes).filter(n => n.type === 'tag' && DomUtils.textContent(n).includes(name));
|
|
78
|
+
else found = collect(nodes).filter(n => n.type === 'tag' && DomUtils.getAttributeValue(n, name) != null);
|
|
79
|
+
if (exclude) found = found.filter((_, i) => !exclude.includes(i));
|
|
80
|
+
if (index != null) found = [found[index]].filter(Boolean);
|
|
81
|
+
return found;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 简易 CSS:tag / .class / #id / 空格后代 / > 子元素 / :nth-child(N)。 */
|
|
85
|
+
function cssSelect(nodes, selector) {
|
|
86
|
+
let cur = nodes;
|
|
87
|
+
for (const part of String(selector).split(/\s+|>/).filter(Boolean)) {
|
|
88
|
+
const mm = /^([a-zA-Z][\w-]*)?((?:[.#][\w-]+)*)(?::(?:nth-child|eq)\((\d+)\))?$/.exec(part);
|
|
89
|
+
if (!mm) continue;
|
|
90
|
+
const tag = mm[1], mods = mm[2], nth = mm[3];
|
|
91
|
+
cur = tag ? DomUtils.getElementsByTagName(tag, cur, true) : collect(cur);
|
|
92
|
+
for (const mod of mods.match(/[.#][\w-]+/g) || []) {
|
|
93
|
+
cur = cur.filter(n => n.type === 'tag' && (mod[0] === '.'
|
|
94
|
+
? (DomUtils.getAttributeValue(n, 'class') || '').split(/\s+/).includes(mod.slice(1))
|
|
95
|
+
: DomUtils.getAttributeValue(n, 'id') === mod.slice(1)));
|
|
96
|
+
}
|
|
97
|
+
if (nth) { const i = Number(nth) - 1; cur = [cur[i]].filter(Boolean); }
|
|
98
|
+
}
|
|
99
|
+
return cur;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function access(node, key, base) {
|
|
103
|
+
if (key === 'text' || key === 'textNodes') return DomUtils.textContent(node).replace(/\s+/g, ' ').trim();
|
|
104
|
+
if (key === 'ownText') return (node.children || []).filter(c => c.type === 'text').map(c => c.data).join('').replace(/\s+/g, ' ').trim();
|
|
105
|
+
if (key === 'html') return render(node.children || [], { decodeEntities: false });
|
|
106
|
+
if (key === 'all') return render(node, { decodeEntities: false });
|
|
107
|
+
const attr = key.startsWith('attr(') ? key.slice(5, -1) : key;
|
|
108
|
+
const value = DomUtils.getAttributeValue(node, attr);
|
|
109
|
+
if (value == null) return '';
|
|
110
|
+
return (attr === 'href' || attr === 'src') ? absolute(value, base) : String(value).trim();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** JSONPath:$ 开头按路径取,否则对当前对象直取字段。 */
|
|
114
|
+
function jsonPath(data, path) {
|
|
115
|
+
if (!path || path === '$') return [data];
|
|
116
|
+
const p = String(path).trim();
|
|
117
|
+
if (!p.startsWith('$') && !p.includes('.') && !p.includes('[')) {
|
|
118
|
+
return data && typeof data === 'object' && p in data ? [data[p]] : [];
|
|
119
|
+
}
|
|
120
|
+
if (p.includes('..')) {
|
|
121
|
+
const key = p.split('..').pop();
|
|
122
|
+
const out = [];
|
|
123
|
+
const walk = (v) => {
|
|
124
|
+
if (v && typeof v === 'object') {
|
|
125
|
+
for (const [k, val] of Object.entries(v)) { if (k === key) out.push(val); walk(val); }
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
walk(data);
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
let cur = [data];
|
|
132
|
+
for (const token of p.replace(/^\$\.?/, '').split(/\.(?![^\[]*\])/).filter(Boolean)) {
|
|
133
|
+
const mm = /^([^\[]*)((?:\[[^\]]*\])*)$/.exec(token);
|
|
134
|
+
const key = mm && mm[1];
|
|
135
|
+
const idx = mm && mm[2] ? [...mm[2].matchAll(/\[([^\]]*)\]/g)].map(x => x[1]) : [];
|
|
136
|
+
const next = [];
|
|
137
|
+
for (const item of cur) {
|
|
138
|
+
let v = item;
|
|
139
|
+
if (key) v = v && typeof v === 'object' ? v[key] : undefined;
|
|
140
|
+
for (const one of idx) {
|
|
141
|
+
if (v == null) break;
|
|
142
|
+
if (one === '' || one === '*') continue;
|
|
143
|
+
if (/^-?\d+$/.test(one)) v = v[Number(one)];
|
|
144
|
+
else if (one.startsWith("'") || one.startsWith('"')) v = v[one.slice(1, -1)];
|
|
145
|
+
else v = v[one];
|
|
146
|
+
}
|
|
147
|
+
if (v != null) next.push(v);
|
|
148
|
+
}
|
|
149
|
+
cur = next;
|
|
150
|
+
}
|
|
151
|
+
return cur.flatMap(v => Array.isArray(v) ? v : [v]).filter(v => v != null);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function splitClean(rule) {
|
|
155
|
+
const str = String(rule);
|
|
156
|
+
const i = str.indexOf('##');
|
|
157
|
+
if (i < 0) return { expr: str.trim(), cleans: [] };
|
|
158
|
+
const expr = str.slice(0, i).trim();
|
|
159
|
+
const rest = str.slice(i + 2).replace(/###$/, '');
|
|
160
|
+
const parts = rest.split('##');
|
|
161
|
+
const cleans = [];
|
|
162
|
+
for (let j = 0; j + 1 < parts.length; j += 2) cleans.push([parts[j], parts[j + 1]]);
|
|
163
|
+
return { expr, cleans };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function cleanValues(values, cleans) {
|
|
167
|
+
let out = values;
|
|
168
|
+
for (const [pattern, replacement] of cleans) {
|
|
169
|
+
let re; try { re = new RegExp(pattern, 'g'); } catch { continue; }
|
|
170
|
+
out = out.map(v => String(v).replace(re, replacement || ''));
|
|
171
|
+
}
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** 模板插值:{{key}} / {{page}} / {{$.field}} / {{baseUrl}}。 */
|
|
176
|
+
function interpolate(tpl, vars, row) {
|
|
177
|
+
return String(tpl).replace(/\{\{([^}]+)\}\}/g, (_, expr) => {
|
|
178
|
+
const e = expr.trim();
|
|
179
|
+
if (e === 'key' || e === 'searchKey') return encodeURIComponent(vars.query || '');
|
|
180
|
+
if (/^java\.encodeURI\(\s*key/i.test(e)) return encodeURIComponent(vars.query || '');
|
|
181
|
+
if (e === 'page') return String(vars.page || 1);
|
|
182
|
+
if (e === 'page-1') return String((vars.page || 1) - 1);
|
|
183
|
+
if (e === 'baseUrl') return vars.base || '';
|
|
184
|
+
if (e.startsWith('$.')) {
|
|
185
|
+
const v = jsonPath(row, e.replace(/^\$\.?/, '')).flat()[0];
|
|
186
|
+
return v == null ? '' : String(v);
|
|
187
|
+
}
|
|
188
|
+
return '';
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** 规则求值:返回字符串数组。opts.json=JSON 数据,opts.body=正文优先保留换行。 */
|
|
193
|
+
function evalRule(source, rule, base, opts = {}) {
|
|
194
|
+
const parsed = splitClean(rule);
|
|
195
|
+
const expr = parsed.expr, cleans = parsed.cleans;
|
|
196
|
+
if (opts.json || expr.startsWith('@json:') || expr.trim().startsWith('$.')) {
|
|
197
|
+
const data = typeof source === 'string' ? JSON.parse(source) : source;
|
|
198
|
+
return cleanValues(jsonPath(data, expr.replace(/^@json:/, '')).map(v => typeof v === 'object' ? render(v, { decodeEntities: false }) : String(v)), cleans);
|
|
199
|
+
}
|
|
200
|
+
if (expr.startsWith(':')) {
|
|
201
|
+
let re; try { re = new RegExp(expr.slice(1), 'g'); } catch { return []; }
|
|
202
|
+
const out = []; let m;
|
|
203
|
+
while ((m = re.exec(String(source))) !== null) {
|
|
204
|
+
if (!m[0]) { re.lastIndex++; continue; }
|
|
205
|
+
out.push(m[1] || m[0]);
|
|
206
|
+
}
|
|
207
|
+
return cleanValues(out, cleans);
|
|
208
|
+
}
|
|
209
|
+
const parts = expr.split('@').map(x => x.trim()).filter(Boolean);
|
|
210
|
+
let accessor = 'text';
|
|
211
|
+
if (parts.length && ACCESSOR.test(parts[parts.length - 1])) accessor = parts.pop();
|
|
212
|
+
const doc = parseDocument(String(source));
|
|
213
|
+
let nodes = doc.children || [doc];
|
|
214
|
+
for (const part of parts) {
|
|
215
|
+
nodes = nodes.flatMap(n => applyStep([n], part));
|
|
216
|
+
if (!nodes.length) break;
|
|
217
|
+
}
|
|
218
|
+
if (!parts.length) nodes = collect([doc]);
|
|
219
|
+
if (opts.body && (accessor === 'text' || accessor === 'textNodes')) accessor = 'html';
|
|
220
|
+
return cleanValues(nodes.map(n => access(n, accessor, base)).filter(v => v !== ''), cleans);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** 规则组合:|| 取第一个非空,&& 合并。 */
|
|
224
|
+
function ruleValues(source, rule, base, opts) {
|
|
225
|
+
for (const alt of String(rule).split('||').filter(Boolean)) {
|
|
226
|
+
const merged = alt.split('&&').filter(Boolean);
|
|
227
|
+
let values = [];
|
|
228
|
+
for (const part of merged) {
|
|
229
|
+
const v = evalRule(source, part, base, opts).filter(x => x != null && String(x).trim() !== '');
|
|
230
|
+
values = merged.length > 1 ? values.concat(v) : v;
|
|
231
|
+
}
|
|
232
|
+
if (values.length) return values;
|
|
233
|
+
}
|
|
234
|
+
return [];
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const first = (source, rule, base, opts) => ruleValues(source, rule, base, opts)[0] || '';
|
|
238
|
+
|
|
239
|
+
/** 只做选择器,返回节点(用于列表提取)。 */
|
|
240
|
+
function selectNodes(html, rule) {
|
|
241
|
+
let expr = String(rule).replace(/^@css:/, '');
|
|
242
|
+
const i = expr.indexOf('##'); if (i >= 0) expr = expr.slice(0, i).trim();
|
|
243
|
+
const parts = expr.split('@').map(x => x.trim()).filter(Boolean);
|
|
244
|
+
const doc = parseDocument(String(html));
|
|
245
|
+
let nodes = doc.children || [doc];
|
|
246
|
+
for (const part of parts) {
|
|
247
|
+
nodes = nodes.flatMap(n => applyStep([n], part));
|
|
248
|
+
if (!nodes.length) break;
|
|
249
|
+
}
|
|
250
|
+
return nodes;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function fieldFrom(row, rule, base, isJson) {
|
|
254
|
+
if (isJson) {
|
|
255
|
+
const t = String(rule);
|
|
256
|
+
if (t.includes('{{')) return interpolate(t, {}, row);
|
|
257
|
+
const v = jsonPath(row, t.replace(/^@json:/, '').replace(/^\$\.?/, '')).flat()[0];
|
|
258
|
+
return v == null ? '' : String(v).trim();
|
|
259
|
+
}
|
|
260
|
+
const frag = typeof row === 'string' ? row : render(row, { decodeEntities: false });
|
|
261
|
+
return first(frag, rule, base);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function buildUrl(template, query, page, base) {
|
|
265
|
+
let str = String(template);
|
|
266
|
+
const mm = /,\s*(\{[\s\S]*\})\s*$/.exec(str);
|
|
267
|
+
let options = {};
|
|
268
|
+
if (mm) { try { options = JSON.parse(mm[1]); str = str.slice(0, mm.index); } catch { /* 保留原样 */ } }
|
|
269
|
+
str = str.replace(/<([^,<>]*),([^,<>]*)>/g, (_, a, b) => (page || 1) <= 1 ? a : b);
|
|
270
|
+
const vars = { query, page: page || 1, base };
|
|
271
|
+
const url = interpolate(str, vars, null);
|
|
272
|
+
if (options.body) options.body = interpolate(options.body, vars, null);
|
|
273
|
+
return { url: absolute(url, base) || url, options };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
export function createLegadoSource(spec) {
|
|
277
|
+
const src = validateLegado(spec);
|
|
278
|
+
const base = src.base || src.searchUrl;
|
|
279
|
+
const fetchOpts = { encoding: src.charset || undefined };
|
|
280
|
+
|
|
281
|
+
return {
|
|
282
|
+
id: 'legado:' + src.name,
|
|
283
|
+
name: src.name,
|
|
284
|
+
homepage: src.base,
|
|
285
|
+
isLegado: true,
|
|
286
|
+
|
|
287
|
+
async search(query, page) {
|
|
288
|
+
const built = buildUrl(src.searchUrl, query, page, base);
|
|
289
|
+
const raw = await fetchText(built.url, { ...fetchOpts, ...built.options });
|
|
290
|
+
const isJson = /^\s*[\[{]/.test(raw);
|
|
291
|
+
let rows;
|
|
292
|
+
if (isJson) rows = jsonPath(JSON.parse(raw), String(src.search.bookList).replace(/^@json:/, '').replace(/^\$\.?/, ''));
|
|
293
|
+
else rows = selectNodes(raw, src.search.bookList);
|
|
294
|
+
const items = [];
|
|
295
|
+
for (const row of rows) {
|
|
296
|
+
const name = fieldFrom(row, src.search.name || '@text', built.url, isJson);
|
|
297
|
+
const href = fieldFrom(row, src.search.bookUrl || 'a@href', built.url, isJson);
|
|
298
|
+
if (!name || !href) continue;
|
|
299
|
+
items.push({ title: decodeEntities(name).slice(0, 80), url: absolute(href, built.url) || href,
|
|
300
|
+
author: src.search.author ? fieldFrom(row, src.search.author, built.url, isJson) : '',
|
|
301
|
+
note: src.name, snippet: '' });
|
|
302
|
+
}
|
|
303
|
+
if (!items.length) throw new Error('搜索没有匹配到结果:检查书源规则,或站点需要登录/JS 渲染');
|
|
304
|
+
return { total: items.length, page: Number(page) || 0, items };
|
|
305
|
+
},
|
|
306
|
+
|
|
307
|
+
async chapters(url, hint) {
|
|
308
|
+
const html = await fetchText(url, fetchOpts);
|
|
309
|
+
const title = first(html, src.info.name || '', url) || (hint && hint.title) || '';
|
|
310
|
+
const author = first(html, src.info.author || '', url) || (hint && hint.author) || '';
|
|
311
|
+
let tocUrl = url;
|
|
312
|
+
if (src.info.tocUrl && !src.info.tocUrl.startsWith('@js:')) {
|
|
313
|
+
const t = first(html, src.info.tocUrl, url);
|
|
314
|
+
if (t) tocUrl = absolute(t, url) || url;
|
|
315
|
+
}
|
|
316
|
+
const doc = tocUrl === url ? html : await fetchText(tocUrl, fetchOpts);
|
|
317
|
+
const isJson = /^\s*[\[{]/.test(doc);
|
|
318
|
+
const rows = isJson
|
|
319
|
+
? jsonPath(JSON.parse(doc), String(src.toc.chapterList).replace(/^@json:/, '').replace(/^\$\.?/, ''))
|
|
320
|
+
: selectNodes(doc, src.toc.chapterList);
|
|
321
|
+
const chapters = [];
|
|
322
|
+
for (const row of rows) {
|
|
323
|
+
const name = fieldFrom(row, src.toc.chapterName || 'text', tocUrl, isJson);
|
|
324
|
+
let href = fieldFrom(row, src.toc.chapterUrl || 'a@href', tocUrl, isJson);
|
|
325
|
+
if (href.includes('{{')) href = interpolate(href, {}, row);
|
|
326
|
+
if (!name) continue;
|
|
327
|
+
chapters.push({ title: decodeEntities(name).slice(0, 80), url: absolute(href, tocUrl) || href });
|
|
328
|
+
}
|
|
329
|
+
if (!chapters.length) throw new Error('目录没有匹配到章节:检查 ruleToc 规则');
|
|
330
|
+
return { title, author, chapters };
|
|
331
|
+
},
|
|
332
|
+
|
|
333
|
+
async content(url) {
|
|
334
|
+
const raw = await fetchText(url, fetchOpts);
|
|
335
|
+
const isJson = /^\s*[\[{]/.test(raw);
|
|
336
|
+
const rules = String(src.content.content).split('&&').filter(Boolean);
|
|
337
|
+
const parts = rules.map(rule => isJson
|
|
338
|
+
? ruleValues(raw, rule, url, { json: true }).join('\n\n')
|
|
339
|
+
: ruleValues(raw, rule, url, { body: true }).join('\n\n')).filter(Boolean);
|
|
340
|
+
const plain = htmlToText(parts.join('\n\n'));
|
|
341
|
+
if (plain.length < 20) throw new Error('正文为空或过短:检查 ruleContent.content 规则');
|
|
342
|
+
return { title: src.content.title ? first(raw, src.content.title, url) : '', text: plain };
|
|
343
|
+
},
|
|
344
|
+
};
|
|
345
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { fetchText } from '../http.js';
|
|
2
|
+
import { htmlToText, sliceByRegex, pageTitle, decodeEntities } from '../html.js';
|
|
3
|
+
|
|
4
|
+
/** 校验并规范化用户书源 spec,失败时抛出可以直接展示给用户的中文原因。 */
|
|
5
|
+
export function validateSpec(spec) {
|
|
6
|
+
if (!spec || typeof spec !== 'object' || Array.isArray(spec)) throw new Error('书源必须是一个 JSON 对象');
|
|
7
|
+
const name = String(spec.name || '').trim();
|
|
8
|
+
if (!name) throw new Error('缺少 name');
|
|
9
|
+
const search = spec.search || {};
|
|
10
|
+
const book = spec.book || {};
|
|
11
|
+
if (typeof search.url !== 'string' || !search.url.includes('{q}')) throw new Error('search.url 必须包含 {q} 占位符');
|
|
12
|
+
if (typeof search.item !== 'string' || !search.item.trim()) throw new Error('search.item 必须是正则字符串');
|
|
13
|
+
if (typeof book.content !== 'string' || !book.content.trim()) throw new Error('book.content 必须是正则字符串');
|
|
14
|
+
assertRegex(search.item, 'search.item');
|
|
15
|
+
assertRegex(book.content, 'book.content');
|
|
16
|
+
return {
|
|
17
|
+
name: name.slice(0, 40),
|
|
18
|
+
homepage: String(spec.homepage || ''),
|
|
19
|
+
encoding: String(spec.encoding || '').trim(),
|
|
20
|
+
search: { url: search.url, item: search.item },
|
|
21
|
+
book: { content: book.content },
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function assertRegex(source, field) {
|
|
26
|
+
try { new RegExp(source, 's'); } catch (error) {
|
|
27
|
+
throw new Error(field + ' 不是合法正则:' + (error && error.message ? error.message : error));
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function plainTitle(value) {
|
|
32
|
+
return decodeEntities(String(value || '')).replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim();
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 把一份用户 spec 变成可用书源。
|
|
37
|
+
* 约定:search.item 必须带命名组 (?<url>…) 与 (?<title>…);book.content 可带 (?<body>…)。
|
|
38
|
+
*/
|
|
39
|
+
export function createCustomSource(spec) {
|
|
40
|
+
return {
|
|
41
|
+
id: 'custom',
|
|
42
|
+
name: spec.name,
|
|
43
|
+
homepage: spec.homepage,
|
|
44
|
+
|
|
45
|
+
async search(query, page) {
|
|
46
|
+
const pageUrl = spec.search.url
|
|
47
|
+
.replace('{q}', encodeURIComponent(query))
|
|
48
|
+
.replace('{page}', String(page || 0));
|
|
49
|
+
const html = await fetchText(pageUrl, { encoding: spec.encoding });
|
|
50
|
+
const re = new RegExp(spec.search.item, 'gs');
|
|
51
|
+
const items = [];
|
|
52
|
+
let match;
|
|
53
|
+
while ((match = re.exec(html)) !== null) {
|
|
54
|
+
if (!match[0]) { re.lastIndex++; continue; }
|
|
55
|
+
const groups = match.groups || {};
|
|
56
|
+
const title = plainTitle(groups.title);
|
|
57
|
+
const href = String(groups.url || '').trim();
|
|
58
|
+
if (!title || !href) continue;
|
|
59
|
+
let absolute;
|
|
60
|
+
try { absolute = new URL(href, pageUrl).href; } catch { continue; }
|
|
61
|
+
items.push({ title: title.slice(0, 80), url: absolute, note: spec.name, snippet: '' });
|
|
62
|
+
}
|
|
63
|
+
if (!items.length) throw new Error('搜索页没有匹配到结果:检查 search.item 正则,或站点需要登录/JS 渲染');
|
|
64
|
+
return { total: items.length, page: Number(page) || 0, items };
|
|
65
|
+
},
|
|
66
|
+
|
|
67
|
+
async book(url) {
|
|
68
|
+
const html = await fetchText(url, { encoding: spec.encoding });
|
|
69
|
+
const fragment = sliceByRegex(html, spec.book.content);
|
|
70
|
+
if (fragment == null) throw new Error('正文正则没有匹配到内容:检查 book.content');
|
|
71
|
+
const text = htmlToText(fragment);
|
|
72
|
+
if (text.length < 50) throw new Error('正文内容过短,放弃导入');
|
|
73
|
+
return { title: pageTitle(html) || '未命名', author: '', text, truncated: false };
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { fetchText } from '../http.js';
|
|
2
|
+
import { htmlToText, decodeEntities } from '../html.js';
|
|
3
|
+
|
|
4
|
+
const BASE = 'https://daizhige.org';
|
|
5
|
+
const MAX_TEXT = 1_500_000; // 单本上限:红楼梦约 87 万字,留足余量又避免把超大页面塞给浏览器
|
|
6
|
+
|
|
7
|
+
/** 把搜索高亮片段(可能带 <em>)压成一行纯文本。 */
|
|
8
|
+
function snippetOf(highlight) {
|
|
9
|
+
const parts = Array.isArray(highlight && highlight.content) ? highlight.content : [];
|
|
10
|
+
const plain = parts.map((part) => decodeEntities(String(part)).replace(/<[^>]+>/g, '')).join(' … ');
|
|
11
|
+
return plain.replace(/\s+/g, ' ').trim().slice(0, 120);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** 殆知阁把章节标题拆成『第 一 回』『第四 十 回』,这里把标题内的空格还原。 */
|
|
15
|
+
function collapseChapterHeadings(text) {
|
|
16
|
+
return text.split('\n').map((line) => line.replace(
|
|
17
|
+
/^第\s*((?:[零一二三四五六七八九十百千两0-9]\s*)+)\s*([章节回卷部篇集])/,
|
|
18
|
+
(whole, digits, unit) => '第' + digits.replace(/\s+/g, '') + unit,
|
|
19
|
+
)).join('\n');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function splitHeading(text) {
|
|
23
|
+
const firstLine = String(text).split('\n')[0] || '';
|
|
24
|
+
const m = /^《([^》]+)》\s*(?:作者[::]\s*(.+))?$/.exec(firstLine);
|
|
25
|
+
if (!m) return { title: '', author: '' };
|
|
26
|
+
return { title: m[1].trim().slice(0, 80), author: (m[2] || '').trim().slice(0, 40) };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const daizhige = {
|
|
30
|
+
id: 'daizhige',
|
|
31
|
+
name: '殆知阁(古典公版)',
|
|
32
|
+
homepage: BASE,
|
|
33
|
+
|
|
34
|
+
/** @param {string} query @param {number} page 0 起 */
|
|
35
|
+
async search(query, page) {
|
|
36
|
+
const url = BASE + '/api/search?q=' + encodeURIComponent(query) + '&page=' + String(page || 0) + '&size=20';
|
|
37
|
+
let payload;
|
|
38
|
+
try { payload = JSON.parse(await fetchText(url, { headers: { accept: 'application/json' } })); }
|
|
39
|
+
catch (error) { throw new Error('书源返回的不是合法 JSON:' + (error && error.message ? error.message : error)); }
|
|
40
|
+
if (!payload || payload.success !== true || !payload.data) throw new Error('书源返回格式异常');
|
|
41
|
+
const items = (payload.data.results || [])
|
|
42
|
+
.map((row) => {
|
|
43
|
+
const source = row.source || {};
|
|
44
|
+
const href = source.url || source.filepath;
|
|
45
|
+
if (!source.title || !href) return null;
|
|
46
|
+
const absolute = new URL(String(href).replace(/^\//, '/'), BASE + '/').href;
|
|
47
|
+
const words = Number(source.char_count || 0);
|
|
48
|
+
const note = [String(source.book_category || '').replace(/^\//, ''), words > 0 ? (words / 10000).toFixed(1) + ' 万字' : '']
|
|
49
|
+
.filter(Boolean).join(' · ');
|
|
50
|
+
return { title: String(source.title).trim().slice(0, 80), url: absolute, note, snippet: snippetOf(row.highlight) };
|
|
51
|
+
})
|
|
52
|
+
.filter(Boolean);
|
|
53
|
+
return { total: Number(payload.data.total || items.length), page: Number(page) || 0, items };
|
|
54
|
+
},
|
|
55
|
+
|
|
56
|
+
async book(url) {
|
|
57
|
+
const html = await fetchText(url);
|
|
58
|
+
const start = html.indexOf('<div class="text-content">');
|
|
59
|
+
const end = start >= 0 ? html.indexOf('<div class="document-meta">', start) : -1;
|
|
60
|
+
if (start < 0 || end <= start) throw new Error('这个页面里没有找到正文,可能是站点改版了');
|
|
61
|
+
const full = collapseChapterHeadings(htmlToText(html.slice(start, end)));
|
|
62
|
+
if (full.length < 50) throw new Error('正文内容过短,放弃导入');
|
|
63
|
+
const heading = splitHeading(full);
|
|
64
|
+
const text = full.length > MAX_TEXT ? full.slice(0, MAX_TEXT) : full;
|
|
65
|
+
// 标题抓不到时留空,由客户端回退到搜索结果里的书名,避免书架出现一堆「未命名」
|
|
66
|
+
return { title: heading.title, author: heading.author, text, truncated: full.length > MAX_TEXT };
|
|
67
|
+
},
|
|
68
|
+
};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { daizhige } from './daizhige.js';
|
|
2
|
+
import { wikisource } from './wikisource.js';
|
|
3
|
+
import { createCustomSource, validateSpec } from './custom.js';
|
|
4
|
+
import { createLegadoSource, isLegadoSource } from '../legado.js';
|
|
5
|
+
import { COMMUNITY_SOURCES } from '../community-sources.js';
|
|
6
|
+
|
|
7
|
+
const BUILTIN = { daizhige, wikisource };
|
|
8
|
+
// 社区书源:按 id 索引,供 { id: 'src:xxx' } 或 { spec } 解析
|
|
9
|
+
const COMMUNITY = new Map(COMMUNITY_SOURCES.map((s) => [s.id, s]));
|
|
10
|
+
|
|
11
|
+
/** 内置源清单(殆知阁 / 维基文库),客户端下拉框用。 */
|
|
12
|
+
export const BUILTIN_SOURCES = Object.values(BUILTIN).map((s) => ({ id: s.id, name: s.name, homepage: s.homepage }));
|
|
13
|
+
|
|
14
|
+
/** 社区书源清单(不含规则本体,避免每次传输几十 KB)。 */
|
|
15
|
+
export function communityList() {
|
|
16
|
+
return COMMUNITY_SOURCES.map((s) => ({
|
|
17
|
+
id: s.id, name: s.name, host: s.host, group: s.group, status: s.status, enabled: s.enabled, stats: s.stats,
|
|
18
|
+
}));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** 路由里的 source 形态:{ id } 内置/社区,或 { spec } 用户自填(含阅读3/Legado)。 */
|
|
22
|
+
export function resolveSource(source) {
|
|
23
|
+
if (!source || typeof source !== 'object') throw new Error('缺少书源参数');
|
|
24
|
+
if (source.spec) {
|
|
25
|
+
if (isLegadoSource(source.spec)) return createLegadoSource(source.spec);
|
|
26
|
+
return createCustomSource(validateSpec(source.spec));
|
|
27
|
+
}
|
|
28
|
+
const id = String(source.id || '');
|
|
29
|
+
const builtin = BUILTIN[id];
|
|
30
|
+
if (builtin) return builtin;
|
|
31
|
+
const community = COMMUNITY.get(id);
|
|
32
|
+
if (community) return createLegadoSource(community.spec);
|
|
33
|
+
throw new Error('未知书源:' + id);
|
|
34
|
+
}
|