dsh-reading-inbox 0.4.0 → 0.5.1
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.en.md +10 -5
- package/README.md +10 -5
- package/VERIFY.md +9 -1
- package/package.json +1 -1
- package/src/config.js +3 -0
- package/src/fetch.js +67 -5
- package/src/routes.js +30 -0
- package/src/store.js +160 -11
- package/src/tools.js +6 -0
- package/web/app.js +13 -1
- package/web/index.html +1 -0
- package/web/style.css +15 -0
package/README.en.md
CHANGED
|
@@ -28,6 +28,7 @@ This plugin is the small implementation of those three things. Everything stays
|
|
|
28
28
|
- **One-step clipping** — paste a URL; Readability extracts the article; Markdown + original HTML + title/author/date/source/excerpt are saved.
|
|
29
29
|
- **Text/selection capture** — when there is no fetchable URL, paste text, Markdown or HTML into the same inbox.
|
|
30
30
|
- **Import/export** — download all clips as JSON (optionally with original HTML) or one Markdown file; import JSON to restore clips, annotations and saved views.
|
|
31
|
+
- **Offline images** — optionally download article images into `clips/<id>/assets/` and serve them through a local asset route; `meta.json` records charset, HTTP status, byte count and other provenance.
|
|
31
32
|
- **Inbox UI** — unread / reading / read / archived, search, tag filters, reading view, copy link, export Markdown.
|
|
32
33
|
- **Highlights and notes** — select text to highlight it (yellow / green / blue / red) and add a note. Anchors use quote + surrounding context, so a re-clip re-locates them automatically; missing text becomes stale instead of landing on the wrong sentence. Markdown export includes active annotations.
|
|
33
34
|
- **Local full-text search** — CJK is indexed as unigrams + bigrams, Latin as words; title and tags are boosted. No model call.
|
|
@@ -49,7 +50,7 @@ From npm:
|
|
|
49
50
|
dsh plugin --profile web add dsh-reading-inbox
|
|
50
51
|
```
|
|
51
52
|
|
|
52
|
-
> pnpm's supply-chain policy waits before adopting a freshly published version. If an install right after a release picks the previous version, pin it: `dsh plugin --profile web add dsh-reading-inbox@0.
|
|
53
|
+
> pnpm's supply-chain policy waits before adopting a freshly published version. If an install right after a release picks the previous version, pin it: `dsh plugin --profile web add dsh-reading-inbox@0.5.1`.
|
|
53
54
|
|
|
54
55
|
From GitHub:
|
|
55
56
|
|
|
@@ -106,7 +107,7 @@ Command output is shown in the UI only; the full article is not pushed into mode
|
|
|
106
107
|
|
|
107
108
|
| Tool | What it does |
|
|
108
109
|
| --- | --- |
|
|
109
|
-
| `reading_clip` | Fetch a URL, extract the article, save Markdown + original HTML, update the index. Duplicate URLs return the existing clip; `force: true` re-fetches. |
|
|
110
|
+
| `reading_clip` | Fetch a URL, extract the article, save Markdown + original HTML, update the index. Duplicate URLs return the existing clip; `force: true` re-fetches; `assets: 'local'` downloads article images. |
|
|
110
111
|
| `reading_search` | Full-text search with `tag:` / `is:` / `site:` / `after:` / `before:` / `has:highlight` grammar, status/tag filters and pagination; returns metadata plus a matched snippet, not the body. |
|
|
111
112
|
| `reading_list` | List by date, filtered by status/tag. |
|
|
112
113
|
| `reading_read` | Read a Markdown slice by id; use `offset` / `nextOffset` for long articles and `hasMore` to know whether it is complete. |
|
|
@@ -125,6 +126,9 @@ Set these in the shell that starts DSH, or in the profile's `.env`, then restart
|
|
|
125
126
|
| `DSH_READING_INBOX_MAX_BYTES` | `5242880` | Max page size (5 MB) |
|
|
126
127
|
| `DSH_READING_INBOX_MAX_MARKDOWN_CHARS` | `400000` | Max Markdown chars per article; longer content is truncated and flagged |
|
|
127
128
|
| `DSH_READING_INBOX_MAX_REDIRECTS` | `5` | Max redirects |
|
|
129
|
+
| `DSH_READING_INBOX_ASSETS` | `remote` | Set to `local` to download article images into the clip `assets/`; can also be set per clip with the `assets` tool argument or the UI checkbox |
|
|
130
|
+
| `DSH_READING_INBOX_ASSET_MAX_BYTES` | `5242880` | Max bytes per image |
|
|
131
|
+
| `DSH_READING_INBOX_ASSET_MAX_COUNT` | `50` | Max images localized per clip |
|
|
128
132
|
| `DSH_READING_INBOX_ALLOW_PRIVATE` | `0` | Set to `1` to allow localhost/private targets; for local tests only |
|
|
129
133
|
| `DSH_READING_INBOX_USER_AGENT` | `dsh-reading-inbox/0.1 ...` | User-Agent for fetches |
|
|
130
134
|
| `DSH_READING_INBOX_PROXY` | falls back to `HTTPS_PROXY` / `HTTP_PROXY` | HTTP proxy URL, e.g. `http://127.0.0.1:7890`; the proxy resolves the destination |
|
|
@@ -141,6 +145,7 @@ Set these in the shell that starts DSH, or in the profile's `.env`, then restart
|
|
|
141
145
|
└── <id>/
|
|
142
146
|
├── article.md # clean Markdown body
|
|
143
147
|
├── original.html # original HTML snapshot (archive only, never rendered)
|
|
148
|
+
├── assets/ # optional localized article images
|
|
144
149
|
├── annotations.json # highlights/notes (created on the first annotation)
|
|
145
150
|
└── meta.json # title, URL, author, date, tags, status, annotation count
|
|
146
151
|
```
|
|
@@ -183,7 +188,7 @@ See [VERIFY.md](VERIFY.md) for the end-to-end check inside a real DSH.
|
|
|
183
188
|
|
|
184
189
|
```sh
|
|
185
190
|
npm run build:client # rebuild client/client.js with esbuild
|
|
186
|
-
npm test #
|
|
191
|
+
npm test # 41 tests: extraction, rendering, SSRF, DNS checks, annotation anchoring, store races, search, routes, assets, client bundle
|
|
187
192
|
npm run verify # end-to-end self-check
|
|
188
193
|
```
|
|
189
194
|
|
|
@@ -200,10 +205,10 @@ Layout:
|
|
|
200
205
|
|
|
201
206
|
## Limits and roadmap
|
|
202
207
|
|
|
203
|
-
0.
|
|
208
|
+
0.5.0 is deliberately small:
|
|
204
209
|
|
|
205
210
|
- [ ] SPA / login / anti-bot pages may yield no article; add a Playwright fallback.
|
|
206
|
-
- [
|
|
211
|
+
- [x] Images can be downloaded into `clips/<id>/assets/` with provenance; full CSS/font page mirroring is still out of scope.
|
|
207
212
|
- [ ] No PDF support; use `dsh-pdf-mineru` or a document reader for PDFs.
|
|
208
213
|
- [ ] No browser extension or RSS import yet; URL, paste-text, JSON import/export and agent tools are covered.
|
|
209
214
|
- [ ] No sync/backup yet; the directory is portable.
|
package/README.md
CHANGED
|
@@ -28,6 +28,7 @@ DSH 已经有 `web_fetch`、`read_url` 这类“读一次”的工具,但它
|
|
|
28
28
|
- **一键剪藏**:粘贴 URL → Readability 提取正文 → Markdown + 原文 HTML + 标题/作者/日期/来源/摘要。
|
|
29
29
|
- **文本/选区采集**:没有可抓取 URL 时,可以直接粘贴正文、Markdown 或 HTML,保存成同一收件箱条目。
|
|
30
30
|
- **导入/导出**:一键导出全部 JSON(可选原始 HTML)或全部 Markdown;导入 JSON 恢复文章、批注和保存视图。
|
|
31
|
+
- **离线图片**:可选把正文图片下载到 `clips/<id>/assets/`,详情通过本地资源路由加载;`meta.json` 记录 charset、HTTP 状态、字节数等 provenance。
|
|
31
32
|
- **收件箱界面**:未读 / 在读 / 已读 / 归档,搜索、标签筛选、详情阅读、复制链接、导出 Markdown。
|
|
32
33
|
- **划线与批注**:选中正文文字即可高亮(黄 / 绿 / 蓝 / 红),写笔记;批注按“引文 + 前后文”锚定,文章重新抓取后自动重定位,失败会标为失效而不是错贴。导出 Markdown 时带上有效批注。
|
|
33
34
|
- **全文检索**:中文按单字 + 二元组切分,英文按词切分;标题和标签权重更高。纯本地,不调用模型。
|
|
@@ -49,7 +50,7 @@ DSH 已经有 `web_fetch`、`read_url` 这类“读一次”的工具,但它
|
|
|
49
50
|
dsh plugin --profile web add dsh-reading-inbox
|
|
50
51
|
```
|
|
51
52
|
|
|
52
|
-
> pnpm 的 supply-chain 策略会等新版本发布一段时间才默认采用它。刚发布后如果装到上一版,可显式指定版本:`dsh plugin --profile web add dsh-reading-inbox@0.
|
|
53
|
+
> pnpm 的 supply-chain 策略会等新版本发布一段时间才默认采用它。刚发布后如果装到上一版,可显式指定版本:`dsh plugin --profile web add dsh-reading-inbox@0.5.1`。
|
|
53
54
|
|
|
54
55
|
直接从 GitHub 安装:
|
|
55
56
|
|
|
@@ -106,7 +107,7 @@ dsh plugin --profile web add file:C:/path/to/dsh-reading-inbox
|
|
|
106
107
|
|
|
107
108
|
| 工具 | 作用 |
|
|
108
109
|
| --- | --- |
|
|
109
|
-
| `reading_clip` | 抓取 URL,提取正文,保存 Markdown + 原文 HTML,写入索引。重复 URL 默认返回已有条目;`force: true`
|
|
110
|
+
| `reading_clip` | 抓取 URL,提取正文,保存 Markdown + 原文 HTML,写入索引。重复 URL 默认返回已有条目;`force: true` 重新抓取;`assets: 'local'` 下载正文图片。 |
|
|
110
111
|
| `reading_search` | 全文搜索,支持 `tag:` / `is:` / `site:` / `after:` / `before:` / `has:highlight` 查询语法、状态/标签过滤和分页;返回元数据 + 命中 snippet,不返回全文。 |
|
|
111
112
|
| `reading_list` | 按时间列出,支持状态/标签过滤。 |
|
|
112
113
|
| `reading_read` | 按 id 读取 Markdown 切片;用 `offset` / `nextOffset` 翻长文,`hasMore` 判断是否读完。 |
|
|
@@ -125,6 +126,9 @@ dsh plugin --profile web add file:C:/path/to/dsh-reading-inbox
|
|
|
125
126
|
| `DSH_READING_INBOX_MAX_BYTES` | `5242880` | 单页最大字节数(5 MB) |
|
|
126
127
|
| `DSH_READING_INBOX_MAX_MARKDOWN_CHARS` | `400000` | 单篇 Markdown 最大字符数,超出截断并标记 |
|
|
127
128
|
| `DSH_READING_INBOX_MAX_REDIRECTS` | `5` | 最大重定向次数 |
|
|
129
|
+
| `DSH_READING_INBOX_ASSETS` | `remote` | 设为 `local` 时默认下载正文图片到 clip 的 `assets/`;也可以单次用 `reading_clip` 的 `assets` 参数或界面“本地图片”勾选 |
|
|
130
|
+
| `DSH_READING_INBOX_ASSET_MAX_BYTES` | `5242880` | 单张图片最大字节数 |
|
|
131
|
+
| `DSH_READING_INBOX_ASSET_MAX_COUNT` | `50` | 单篇最多本地化图片数 |
|
|
128
132
|
| `DSH_READING_INBOX_ALLOW_PRIVATE` | `0` | 设为 `1` 才允许抓取本机/内网;只用于本地测试 |
|
|
129
133
|
| `DSH_READING_INBOX_USER_AGENT` | `dsh-reading-inbox/0.1 ...` | 抓取时的 User-Agent |
|
|
130
134
|
| `DSH_READING_INBOX_PROXY` | 读 `HTTPS_PROXY` / `HTTP_PROXY` | HTTP 代理地址,例如 `http://127.0.0.1:7890`;走代理时目标由代理解析 |
|
|
@@ -141,6 +145,7 @@ dsh plugin --profile web add file:C:/path/to/dsh-reading-inbox
|
|
|
141
145
|
└── <id>/
|
|
142
146
|
├── article.md # 干净正文(Markdown)
|
|
143
147
|
├── original.html # 原始 HTML 快照(只存档,不渲染)
|
|
148
|
+
├── assets/ # 可选:本地化后的正文图片
|
|
144
149
|
├── annotations.json # 划线/批注(首次批注时生成)
|
|
145
150
|
└── meta.json # 标题、URL、作者、日期、标签、状态、批注数
|
|
146
151
|
```
|
|
@@ -183,7 +188,7 @@ npm run dev # http://127.0.0.1:4173/dsh-reading-inbox/
|
|
|
183
188
|
|
|
184
189
|
```sh
|
|
185
190
|
npm run build:client # 重新构建 client/client.js(esbuild)
|
|
186
|
-
npm test #
|
|
191
|
+
npm test # 41 个测试:提取、渲染、SSRF、DNS 校验、批注锚定、存储竞态、检索、路由、图片本地化、客户端 bundle
|
|
187
192
|
npm run verify # 端到端自检
|
|
188
193
|
```
|
|
189
194
|
|
|
@@ -200,10 +205,10 @@ npm run verify # 端到端自检
|
|
|
200
205
|
|
|
201
206
|
## 限制与 Roadmap
|
|
202
207
|
|
|
203
|
-
当前版本是 0.
|
|
208
|
+
当前版本是 0.5.0,刻意不做大而全:
|
|
204
209
|
|
|
205
210
|
- [ ] SPA / 登录页 / 反爬页可能提取不到正文;下一步加 Playwright fallback。
|
|
206
|
-
- [
|
|
211
|
+
- [x] 图片可下载到 `clips/<id>/assets/`,记录 provenance;仍不做整页 CSS/字体资源的完整离线镜像。
|
|
207
212
|
- [ ] 暂不支持 PDF;PDF 请用 `dsh-pdf-mineru` 或文档阅读插件。
|
|
208
213
|
- [ ] 暂无浏览器扩展 / RSS 导入;已有 URL、粘贴文本、JSON 导入/导出和 Agent 工具。
|
|
209
214
|
- [ ] 暂无同步/备份;先保证本地目录可复制。
|
package/VERIFY.md
CHANGED
|
@@ -62,7 +62,15 @@ dsh --profile inbox-web --no-open --port 4191
|
|
|
62
62
|
3. 点搜索框下方的“+ 视图”,输入名称并保存;应出现视图 chip。
|
|
63
63
|
4. 清空搜索后点该 chip,搜索框应恢复保存的查询,列表回到同一组结果;点 chip 上的 × 可删除视图。
|
|
64
64
|
|
|
65
|
-
### 3.3
|
|
65
|
+
### 3.3 离线图片与 provenance
|
|
66
|
+
|
|
67
|
+
1. 勾选顶部“本地图片”,剪藏一篇带正文图片的文章(或先不勾选剪藏一篇,再对同一 URL 用 `reading_clip` 的 `force: true, assets: 'local'` 重新抓取)。
|
|
68
|
+
2. 期望:`clips/<id>/assets/` 下出现以内容哈希命名的图片,`article.md` 里的图片地址变成 `assets/<hash>.<ext>`。
|
|
69
|
+
3. 详情页里图片仍应正常显示;直接访问 `http://127.0.0.1:4191/dsh-reading-inbox/asset/<id>/<hash>.png` 应返回图片,非 `127.0.0.1` 来源应被 403 拒绝。
|
|
70
|
+
4. 打开 `clips/<id>/meta.json`,`assets` 应列出图片,`provenance` 应包含 `finalUrl`、`status`、`contentType`、`charset`、`bytes`、`extractor`。
|
|
71
|
+
5. 图片超过 `DSH_READING_INBOX_ASSET_MAX_BYTES`、或超过 `DSH_READING_INBOX_ASSET_MAX_COUNT` 时,不应整篇失败:图片被跳过并在 `provenance.warnings` 里记录。
|
|
72
|
+
|
|
73
|
+
### 3.4 粘贴文本、导入与导出
|
|
66
74
|
|
|
67
75
|
1. 点顶部“粘贴文本”,填标题和正文(不填 URL)后保存;左侧应出现来源为“手动保存”的条目,详情里不显示“打开原文”。
|
|
68
76
|
2. 点顶部“导出”,应下载 `dsh-reading-inbox.json`;换一个空数据目录后点“导入”选择该文件,文章、批注和视图应恢复。
|
package/package.json
CHANGED
package/src/config.js
CHANGED
|
@@ -23,6 +23,9 @@ export function loadConfig(env = process.env) {
|
|
|
23
23
|
maxBytes: positiveInt(env.DSH_READING_INBOX_MAX_BYTES, 5 * 1024 * 1024),
|
|
24
24
|
maxMarkdownChars: positiveInt(env.DSH_READING_INBOX_MAX_MARKDOWN_CHARS, 400_000),
|
|
25
25
|
maxRedirects: positiveInt(env.DSH_READING_INBOX_MAX_REDIRECTS, 5),
|
|
26
|
+
assets: env.DSH_READING_INBOX_ASSETS === 'local' ? 'local' : 'remote',
|
|
27
|
+
assetMaxBytes: positiveInt(env.DSH_READING_INBOX_ASSET_MAX_BYTES, 5 * 1024 * 1024),
|
|
28
|
+
assetMaxCount: positiveInt(env.DSH_READING_INBOX_ASSET_MAX_COUNT, 50),
|
|
26
29
|
allowPrivate: env.DSH_READING_INBOX_ALLOW_PRIVATE === '1' || env.DSH_READING_INBOX_ALLOW_PRIVATE === 'true',
|
|
27
30
|
blockFakeIp:
|
|
28
31
|
env.DSH_READING_INBOX_BLOCK_FAKE_IP === '1' || env.DSH_READING_INBOX_BLOCK_FAKE_IP === 'true',
|
package/src/fetch.js
CHANGED
|
@@ -79,9 +79,9 @@ function charsetFromHtml(buffer) {
|
|
|
79
79
|
function decodeBody(buffer, contentType) {
|
|
80
80
|
const charset = charsetFromContentType(contentType) || charsetFromHtml(buffer) || 'utf-8'
|
|
81
81
|
try {
|
|
82
|
-
return iconv.decode(buffer, charset)
|
|
82
|
+
return { text: iconv.decode(buffer, charset), charset }
|
|
83
83
|
} catch {
|
|
84
|
-
return buffer.toString('utf8')
|
|
84
|
+
return { text: buffer.toString('utf8'), charset: 'utf-8' }
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
87
|
|
|
@@ -156,14 +156,25 @@ export async function fetchHtml(rawUrl, config, options = {}) {
|
|
|
156
156
|
const finalUrl = response.url || url.toString()
|
|
157
157
|
|
|
158
158
|
if (HTML_TYPES.some(type => contentType.includes(type)) || contentType === '') {
|
|
159
|
-
|
|
159
|
+
const decoded = decodeBody(buffer, contentType)
|
|
160
|
+
return {
|
|
161
|
+
html: decoded.text,
|
|
162
|
+
finalUrl,
|
|
163
|
+
contentType,
|
|
164
|
+
charset: decoded.charset,
|
|
165
|
+
status: response.status,
|
|
166
|
+
bytes: buffer.length,
|
|
167
|
+
}
|
|
160
168
|
}
|
|
161
169
|
if (contentType.includes('text/plain')) {
|
|
162
|
-
const
|
|
170
|
+
const decoded = decodeBody(buffer, contentType)
|
|
163
171
|
return {
|
|
164
|
-
html: `<!doctype html><html><head><meta charset="utf-8"></head><body><pre>${escapeHtml(text)}</pre></body></html>`,
|
|
172
|
+
html: `<!doctype html><html><head><meta charset="utf-8"></head><body><pre>${escapeHtml(decoded.text)}</pre></body></html>`,
|
|
165
173
|
finalUrl,
|
|
166
174
|
contentType,
|
|
175
|
+
charset: decoded.charset,
|
|
176
|
+
status: response.status,
|
|
177
|
+
bytes: buffer.length,
|
|
167
178
|
}
|
|
168
179
|
}
|
|
169
180
|
throw new Error(`不支持的内容类型:${contentType.split(';')[0]};目前只支持 HTML/纯文本`)
|
|
@@ -171,3 +182,54 @@ export async function fetchHtml(rawUrl, config, options = {}) {
|
|
|
171
182
|
|
|
172
183
|
throw new Error('重定向次数过多')
|
|
173
184
|
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Fetch an image with the same SSRF, redirect, timeout and byte-cap policy as
|
|
188
|
+
* article fetches. Used only when local asset archiving is enabled.
|
|
189
|
+
*/
|
|
190
|
+
export async function fetchBinary(rawUrl, config, options = {}) {
|
|
191
|
+
const dispatcher = dispatcherFor(config, options.fetchImpl !== undefined)
|
|
192
|
+
const fetchImpl = options.fetchImpl ?? undiciFetch
|
|
193
|
+
const signal = signalWithTimeout(options.signal, config.timeoutMs)
|
|
194
|
+
const maxBytes = Math.min(config.assetMaxBytes ?? config.maxBytes, config.maxBytes)
|
|
195
|
+
let current = rawUrl
|
|
196
|
+
|
|
197
|
+
for (let hop = 0; hop <= config.maxRedirects; hop += 1) {
|
|
198
|
+
const url = await assertPublicUrl(current, config)
|
|
199
|
+
const response = await fetchImpl(url, {
|
|
200
|
+
redirect: 'manual',
|
|
201
|
+
signal,
|
|
202
|
+
...(dispatcher === undefined ? {} : { dispatcher }),
|
|
203
|
+
headers: {
|
|
204
|
+
'user-agent': config.userAgent,
|
|
205
|
+
accept: 'image/*,*/*;q=0.8',
|
|
206
|
+
},
|
|
207
|
+
})
|
|
208
|
+
|
|
209
|
+
if (REDIRECT_STATUS.has(response.status)) {
|
|
210
|
+
const location = response.headers.get('location')
|
|
211
|
+
if (location === null) throw new Error(`HTTP ${response.status} 重定向缺少 Location`)
|
|
212
|
+
current = new URL(location, url).toString()
|
|
213
|
+
if (hop === config.maxRedirects) throw new Error('重定向次数过多')
|
|
214
|
+
continue
|
|
215
|
+
}
|
|
216
|
+
if (!response.ok) {
|
|
217
|
+
throw new Error(`图片抓取失败:HTTP ${response.status} ${response.statusText}`.trim())
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const contentType = (response.headers.get('content-type') || '').toLowerCase()
|
|
221
|
+
if (!contentType.startsWith('image/')) {
|
|
222
|
+
throw new Error(`不是图片内容:${contentType.split(';')[0] || 'unknown'}`)
|
|
223
|
+
}
|
|
224
|
+
const buffer = await readCapped(response, maxBytes)
|
|
225
|
+
return {
|
|
226
|
+
buffer,
|
|
227
|
+
contentType,
|
|
228
|
+
finalUrl: response.url || url.toString(),
|
|
229
|
+
status: response.status,
|
|
230
|
+
bytes: buffer.length,
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
throw new Error('重定向次数过多')
|
|
235
|
+
}
|
package/src/routes.js
CHANGED
|
@@ -200,6 +200,7 @@ async function handleApi(req, res, url, inbox) {
|
|
|
200
200
|
const result = await inbox.clip(body.url, {
|
|
201
201
|
tags,
|
|
202
202
|
force: body.force === true,
|
|
203
|
+
assets: body.assets,
|
|
203
204
|
})
|
|
204
205
|
return writeJson(res, 200, { ok: true, clip: result })
|
|
205
206
|
}
|
|
@@ -298,6 +299,35 @@ export function createRoutes({ inbox, webDir }) {
|
|
|
298
299
|
return
|
|
299
300
|
}
|
|
300
301
|
|
|
302
|
+
if (url.pathname.startsWith(`${PREFIX}/asset/`)) {
|
|
303
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
304
|
+
writeError(res, 405, 'method not allowed')
|
|
305
|
+
return
|
|
306
|
+
}
|
|
307
|
+
const assetPath = url.pathname.slice(`${PREFIX}/asset/`.length)
|
|
308
|
+
const segments = assetPath.split('/').filter(Boolean)
|
|
309
|
+
if (segments.length !== 2) {
|
|
310
|
+
writeError(res, 404, 'not found')
|
|
311
|
+
return
|
|
312
|
+
}
|
|
313
|
+
try {
|
|
314
|
+
const asset = await inbox.readAsset(decodeSegment(segments[0]), decodeSegment(segments[1]))
|
|
315
|
+
res.writeHead(200, {
|
|
316
|
+
'content-type': asset.contentType,
|
|
317
|
+
'cache-control': 'private, max-age=3600',
|
|
318
|
+
'x-content-type-options': 'nosniff',
|
|
319
|
+
// SVG is active content. Sandboxing the response blocks scripts
|
|
320
|
+
// and same-origin access if a hostile SVG is opened directly;
|
|
321
|
+
// loading it through <img> is unaffected.
|
|
322
|
+
'content-security-policy': "default-src 'none'; sandbox",
|
|
323
|
+
})
|
|
324
|
+
res.end(asset.buffer)
|
|
325
|
+
} catch {
|
|
326
|
+
writeError(res, 404, 'not found')
|
|
327
|
+
}
|
|
328
|
+
return
|
|
329
|
+
}
|
|
330
|
+
|
|
301
331
|
// Relative assets and API calls in web/index.html assume the trailing
|
|
302
332
|
// slash. Redirect the bare prefix instead of serving a page that would
|
|
303
333
|
// resolve ./style.css and ./api against the DSH root.
|
package/src/store.js
CHANGED
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
normalizeQuote,
|
|
10
10
|
resolveAnnotations,
|
|
11
11
|
} from './annotations.js'
|
|
12
|
-
import { fetchHtml } from './fetch.js'
|
|
12
|
+
import { fetchBinary, fetchHtml } from './fetch.js'
|
|
13
13
|
import { countWords, exportMarkdown, htmlToMarkdown, parseArticle, renderMarkdown, renderedText } from './markdown.js'
|
|
14
14
|
import { makeSnippet, parseQuery, queryTerms } from './search.js'
|
|
15
15
|
|
|
@@ -18,6 +18,20 @@ const STATUSES = new Set(['unread', 'reading', 'read', 'archived'])
|
|
|
18
18
|
const MAX_TAGS = 20
|
|
19
19
|
const MAX_TAG_LENGTH = 40
|
|
20
20
|
const MAX_ANNOTATIONS = 500
|
|
21
|
+
const ASSET_EXTENSIONS = {
|
|
22
|
+
'image/png': 'png',
|
|
23
|
+
'image/jpeg': 'jpg',
|
|
24
|
+
'image/gif': 'gif',
|
|
25
|
+
'image/webp': 'webp',
|
|
26
|
+
'image/svg+xml': 'svg',
|
|
27
|
+
'image/avif': 'avif',
|
|
28
|
+
'image/bmp': 'bmp',
|
|
29
|
+
'image/x-icon': 'ico',
|
|
30
|
+
'image/vnd.microsoft.icon': 'ico',
|
|
31
|
+
'image/tiff': 'tiff',
|
|
32
|
+
}
|
|
33
|
+
const ASSET_TYPES = new Map(Object.entries(ASSET_EXTENSIONS).map(([type, ext]) => [ext, type]))
|
|
34
|
+
const ASSET_FILE_RE = /^[a-f0-9]{64}\.(png|jpg|gif|webp|svg|avif|bmp|ico|tiff|bin)$/
|
|
21
35
|
|
|
22
36
|
function nowIso() {
|
|
23
37
|
return new Date().toISOString()
|
|
@@ -241,6 +255,85 @@ export class ReadingInbox {
|
|
|
241
255
|
return text
|
|
242
256
|
}
|
|
243
257
|
|
|
258
|
+
async localizeAssets(id, markdown, options = {}) {
|
|
259
|
+
const urls = []
|
|
260
|
+
const matcher = /!\[[^\]]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g
|
|
261
|
+
let match
|
|
262
|
+
while ((match = matcher.exec(markdown)) !== null) {
|
|
263
|
+
const url = match[1]
|
|
264
|
+
if (/^https?:\/\//i.test(url) && !urls.includes(url)) urls.push(url)
|
|
265
|
+
}
|
|
266
|
+
const warnings = []
|
|
267
|
+
if (urls.length === 0) return { markdown, assets: [], warnings }
|
|
268
|
+
const limited = urls.slice(0, this.config.assetMaxCount)
|
|
269
|
+
if (urls.length > limited.length) {
|
|
270
|
+
warnings.push({ url: '', message: `图片数量超过 ${limited.length},其余保留远程地址` })
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const assetsDir = join(this.clipsDir, id, 'assets')
|
|
274
|
+
await mkdir(assetsDir, { recursive: true })
|
|
275
|
+
const byHash = new Map()
|
|
276
|
+
const results = new Array(limited.length)
|
|
277
|
+
let cursor = 0
|
|
278
|
+
|
|
279
|
+
const fetchOne = async url => {
|
|
280
|
+
try {
|
|
281
|
+
const fetched = await fetchBinary(url, this.config, { signal: options.signal })
|
|
282
|
+
const sha256 = createHash('sha256').update(fetched.buffer).digest('hex')
|
|
283
|
+
const type = fetched.contentType.split(';')[0].trim().toLowerCase()
|
|
284
|
+
const extension = ASSET_EXTENSIONS[type] ?? 'bin'
|
|
285
|
+
const file = `${sha256}.${extension}`
|
|
286
|
+
if (!byHash.has(sha256)) {
|
|
287
|
+
await writeFile(join(assetsDir, file), fetched.buffer)
|
|
288
|
+
byHash.set(sha256, file)
|
|
289
|
+
}
|
|
290
|
+
return {
|
|
291
|
+
url,
|
|
292
|
+
path: `assets/${file}`,
|
|
293
|
+
bytes: fetched.bytes,
|
|
294
|
+
contentType: fetched.contentType,
|
|
295
|
+
sha256,
|
|
296
|
+
}
|
|
297
|
+
} catch (error) {
|
|
298
|
+
warnings.push({
|
|
299
|
+
url,
|
|
300
|
+
message: error instanceof Error ? error.message : String(error),
|
|
301
|
+
})
|
|
302
|
+
return null
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const workers = Array.from({ length: Math.min(4, limited.length) }, async () => {
|
|
307
|
+
for (;;) {
|
|
308
|
+
const index = cursor
|
|
309
|
+
cursor += 1
|
|
310
|
+
if (index >= limited.length) break
|
|
311
|
+
results[index] = await fetchOne(limited[index])
|
|
312
|
+
}
|
|
313
|
+
})
|
|
314
|
+
await Promise.all(workers)
|
|
315
|
+
const assets = results.filter(Boolean)
|
|
316
|
+
let localized = markdown
|
|
317
|
+
for (const asset of assets) {
|
|
318
|
+
localized = localized.split(asset.url).join(asset.path)
|
|
319
|
+
}
|
|
320
|
+
return { markdown: localized, assets, warnings }
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
async readAsset(id, file) {
|
|
324
|
+
await this.ready()
|
|
325
|
+
const meta = this._byId.get(String(id))
|
|
326
|
+
if (meta === undefined) throw new Error(`找不到文章:${id}`)
|
|
327
|
+
if (!ASSET_FILE_RE.test(String(file))) throw new Error('找不到资源')
|
|
328
|
+
const asset = (meta.assets ?? []).find(item => item.path === `assets/${file}`)
|
|
329
|
+
if (asset === undefined) throw new Error('找不到资源')
|
|
330
|
+
const buffer = await readFile(join(this.clipsDir, meta.id, 'assets', file))
|
|
331
|
+
return {
|
|
332
|
+
buffer,
|
|
333
|
+
contentType: asset.contentType || ASSET_TYPES.get(file.split('.').pop()) || 'application/octet-stream',
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
244
337
|
async readAnnotations(meta) {
|
|
245
338
|
try {
|
|
246
339
|
const raw = await readFile(this.annotationPath(meta), 'utf8')
|
|
@@ -505,6 +598,13 @@ export class ReadingInbox {
|
|
|
505
598
|
images: (markdown.match(/!\[[^\]]*\]\([^)]*\)/g) ?? []).length,
|
|
506
599
|
truncated,
|
|
507
600
|
annotationCount: 0,
|
|
601
|
+
assets: [],
|
|
602
|
+
provenance: {
|
|
603
|
+
source: 'manual',
|
|
604
|
+
requestedUrl: url,
|
|
605
|
+
fetchedAt: nowIso(),
|
|
606
|
+
extractor: 'manual',
|
|
607
|
+
},
|
|
508
608
|
contentHash: digest(markdown, 16),
|
|
509
609
|
manual: true,
|
|
510
610
|
articlePath: `clips/${id}/article.md`,
|
|
@@ -574,6 +674,18 @@ export class ReadingInbox {
|
|
|
574
674
|
const tags = explicitTags.length > 0
|
|
575
675
|
? explicitTags
|
|
576
676
|
: normalizeTags((parsed.keywords ?? []).slice(0, 3))
|
|
677
|
+
const useAssets = options.assets === 'local'
|
|
678
|
+
|| (options.assets === undefined && this.config.assets === 'local')
|
|
679
|
+
let markdown = parsed.markdown
|
|
680
|
+
let assets = []
|
|
681
|
+
let assetWarnings = []
|
|
682
|
+
if (useAssets) {
|
|
683
|
+
const localized = await this.localizeAssets(id, markdown, { signal: options.signal })
|
|
684
|
+
markdown = localized.markdown
|
|
685
|
+
assets = localized.assets
|
|
686
|
+
assetWarnings = localized.warnings
|
|
687
|
+
}
|
|
688
|
+
const now = nowIso()
|
|
577
689
|
const meta = {
|
|
578
690
|
id,
|
|
579
691
|
url: fetched.finalUrl,
|
|
@@ -582,7 +694,7 @@ export class ReadingInbox {
|
|
|
582
694
|
site: parsed.siteName,
|
|
583
695
|
author: parsed.byline,
|
|
584
696
|
published: parsed.published,
|
|
585
|
-
clippedAt:
|
|
697
|
+
clippedAt: now,
|
|
586
698
|
tags,
|
|
587
699
|
status: 'unread',
|
|
588
700
|
excerpt: parsed.excerpt,
|
|
@@ -592,7 +704,19 @@ export class ReadingInbox {
|
|
|
592
704
|
images: parsed.images,
|
|
593
705
|
truncated: parsed.truncated === true,
|
|
594
706
|
annotationCount: 0,
|
|
595
|
-
|
|
707
|
+
assets,
|
|
708
|
+
provenance: {
|
|
709
|
+
requestedUrl: url,
|
|
710
|
+
finalUrl: fetched.finalUrl,
|
|
711
|
+
status: fetched.status,
|
|
712
|
+
contentType: fetched.contentType,
|
|
713
|
+
charset: fetched.charset,
|
|
714
|
+
bytes: fetched.bytes,
|
|
715
|
+
fetchedAt: now,
|
|
716
|
+
extractor: 'readability+turndown',
|
|
717
|
+
warnings: assetWarnings,
|
|
718
|
+
},
|
|
719
|
+
contentHash: digest(markdown, 16),
|
|
596
720
|
articlePath: `clips/${id}/article.md`,
|
|
597
721
|
htmlPath: `clips/${id}/original.html`,
|
|
598
722
|
metaPath: `clips/${id}/meta.json`,
|
|
@@ -600,7 +724,7 @@ export class ReadingInbox {
|
|
|
600
724
|
|
|
601
725
|
const clipDir = join(this.clipsDir, id)
|
|
602
726
|
await mkdir(clipDir, { recursive: true })
|
|
603
|
-
await writeFile(join(this.dir, meta.articlePath), `${
|
|
727
|
+
await writeFile(join(this.dir, meta.articlePath), `${markdown.trim()}\n`, 'utf8')
|
|
604
728
|
await writeFile(join(this.dir, meta.htmlPath), fetched.html, 'utf8')
|
|
605
729
|
await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
|
|
606
730
|
|
|
@@ -608,19 +732,32 @@ export class ReadingInbox {
|
|
|
608
732
|
this._byId.set(meta.id, meta)
|
|
609
733
|
this._byUrl.set(meta.url, meta)
|
|
610
734
|
this._byUrl.set(meta.canonicalUrl, meta)
|
|
611
|
-
this._search.add(toSearchDoc(meta,
|
|
735
|
+
this._search.add(toSearchDoc(meta, markdown))
|
|
612
736
|
await this.persist()
|
|
613
737
|
|
|
614
738
|
return {
|
|
615
739
|
...publicMeta(meta),
|
|
616
740
|
duplicate: false,
|
|
617
|
-
preview:
|
|
741
|
+
preview: markdown.slice(0, 1_500),
|
|
618
742
|
}
|
|
619
743
|
})
|
|
620
744
|
}
|
|
621
745
|
|
|
622
746
|
async refreshClip(meta, parsed, fetched, options = {}) {
|
|
747
|
+
const requestedUrl = meta.url
|
|
623
748
|
const canonicalUrl = parsed.canonicalUrl || fetched.finalUrl
|
|
749
|
+
const useAssets = options.assets === 'local'
|
|
750
|
+
|| (options.assets === undefined && this.config.assets === 'local')
|
|
751
|
+
let markdown = parsed.markdown
|
|
752
|
+
let assets = []
|
|
753
|
+
let assetWarnings = []
|
|
754
|
+
if (useAssets) {
|
|
755
|
+
const localized = await this.localizeAssets(meta.id, markdown, { signal: options.signal })
|
|
756
|
+
markdown = localized.markdown
|
|
757
|
+
assets = localized.assets
|
|
758
|
+
assetWarnings = localized.warnings
|
|
759
|
+
}
|
|
760
|
+
const now = nowIso()
|
|
624
761
|
meta.url = fetched.finalUrl
|
|
625
762
|
meta.canonicalUrl = canonicalUrl
|
|
626
763
|
meta.title = parsed.title
|
|
@@ -634,13 +771,25 @@ export class ReadingInbox {
|
|
|
634
771
|
meta.images = parsed.images
|
|
635
772
|
meta.truncated = parsed.truncated === true
|
|
636
773
|
meta.annotationCount = (await this.readAnnotations(meta)).length
|
|
637
|
-
meta.updatedAt =
|
|
638
|
-
meta.
|
|
774
|
+
meta.updatedAt = now
|
|
775
|
+
meta.assets = assets
|
|
776
|
+
meta.provenance = {
|
|
777
|
+
requestedUrl,
|
|
778
|
+
finalUrl: fetched.finalUrl,
|
|
779
|
+
status: fetched.status,
|
|
780
|
+
contentType: fetched.contentType,
|
|
781
|
+
charset: fetched.charset,
|
|
782
|
+
bytes: fetched.bytes,
|
|
783
|
+
fetchedAt: now,
|
|
784
|
+
extractor: 'readability+turndown',
|
|
785
|
+
warnings: assetWarnings,
|
|
786
|
+
}
|
|
787
|
+
meta.contentHash = digest(markdown, 16)
|
|
639
788
|
if (Array.isArray(options.tags) && options.tags.length > 0) {
|
|
640
789
|
meta.tags = normalizeTags(options.tags)
|
|
641
790
|
}
|
|
642
791
|
|
|
643
|
-
await writeFile(join(this.dir, meta.articlePath), `${
|
|
792
|
+
await writeFile(join(this.dir, meta.articlePath), `${markdown.trim()}\n`, 'utf8')
|
|
644
793
|
await writeFile(join(this.dir, meta.htmlPath), fetched.html, 'utf8')
|
|
645
794
|
await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
|
|
646
795
|
|
|
@@ -651,13 +800,13 @@ export class ReadingInbox {
|
|
|
651
800
|
} catch {
|
|
652
801
|
// The id may be absent after a manual index edit; adding it back is enough.
|
|
653
802
|
}
|
|
654
|
-
this._search.add(toSearchDoc(meta,
|
|
803
|
+
this._search.add(toSearchDoc(meta, markdown))
|
|
655
804
|
await this.persist()
|
|
656
805
|
|
|
657
806
|
return {
|
|
658
807
|
...publicMeta(meta),
|
|
659
808
|
duplicate: false,
|
|
660
|
-
preview:
|
|
809
|
+
preview: markdown.slice(0, 1_500),
|
|
661
810
|
}
|
|
662
811
|
}
|
|
663
812
|
|
package/src/tools.js
CHANGED
|
@@ -133,6 +133,11 @@ export function registerTools(ctx, { inbox }) {
|
|
|
133
133
|
type: 'boolean',
|
|
134
134
|
description: 'Re-clip and refresh an existing URL instead of returning the existing clip.',
|
|
135
135
|
},
|
|
136
|
+
assets: {
|
|
137
|
+
type: 'string',
|
|
138
|
+
enum: ['remote', 'local'],
|
|
139
|
+
description: 'Image policy for this clip: local downloads images into the clip assets directory; remote keeps original URLs.',
|
|
140
|
+
},
|
|
136
141
|
},
|
|
137
142
|
required: ['url'],
|
|
138
143
|
},
|
|
@@ -159,6 +164,7 @@ export function registerTools(ctx, { inbox }) {
|
|
|
159
164
|
return inbox.clip(args.url, {
|
|
160
165
|
tags: Array.isArray(args.tags) ? args.tags : [],
|
|
161
166
|
force: args.force === true,
|
|
167
|
+
assets: args.assets,
|
|
162
168
|
signal: exec.signal,
|
|
163
169
|
})
|
|
164
170
|
},
|
package/web/app.js
CHANGED
|
@@ -26,6 +26,7 @@ const els = {
|
|
|
26
26
|
clipForm: $('#clip-form'),
|
|
27
27
|
clipUrl: $('#clip-url'),
|
|
28
28
|
clipTags: $('#clip-tags'),
|
|
29
|
+
clipAssets: $('#clip-assets'),
|
|
29
30
|
clipSubmit: $('#clip-submit'),
|
|
30
31
|
saveTextToggle: $('#save-text-toggle'),
|
|
31
32
|
textPanel: $('#text-panel'),
|
|
@@ -603,6 +604,13 @@ function renderDetail() {
|
|
|
603
604
|
${renderAnnotationSection(annotations)}
|
|
604
605
|
`
|
|
605
606
|
|
|
607
|
+
for (const image of els.detail.querySelectorAll('.article img')) {
|
|
608
|
+
const source = image.getAttribute('src') ?? ''
|
|
609
|
+
if (source.startsWith('assets/')) {
|
|
610
|
+
image.src = `./asset/${encodeURIComponent(item.id)}/${source.slice('assets/'.length)}`
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
606
614
|
applyHighlights(els.detail.querySelector('.article'), annotations)
|
|
607
615
|
}
|
|
608
616
|
|
|
@@ -675,7 +683,11 @@ els.clipForm.addEventListener('submit', async event => {
|
|
|
675
683
|
try {
|
|
676
684
|
const data = await api('/clip', {
|
|
677
685
|
method: 'POST',
|
|
678
|
-
body: JSON.stringify({
|
|
686
|
+
body: JSON.stringify({
|
|
687
|
+
url,
|
|
688
|
+
tags,
|
|
689
|
+
assets: els.clipAssets?.checked ? 'local' : undefined,
|
|
690
|
+
}),
|
|
679
691
|
})
|
|
680
692
|
const clip = data.clip
|
|
681
693
|
toast(clip.duplicate ? '这个链接已经在收件箱里了' : '已保存到阅读收件箱')
|
package/web/index.html
CHANGED
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
<div class="clip-inputs">
|
|
23
23
|
<input id="clip-url" type="text" inputmode="url" placeholder="粘贴网页链接,回车保存" autocomplete="off" required>
|
|
24
24
|
<input id="clip-tags" type="text" placeholder="标签,逗号分隔(可选)" autocomplete="off">
|
|
25
|
+
<label class="clip-assets"><input id="clip-assets" type="checkbox"> 本地图片</label>
|
|
25
26
|
</div>
|
|
26
27
|
<button type="submit" class="primary" id="clip-submit">保存</button>
|
|
27
28
|
</form>
|
package/web/style.css
CHANGED
|
@@ -863,3 +863,18 @@ mark.hl.pulse {
|
|
|
863
863
|
.text-panel { padding: 10px 12px; }
|
|
864
864
|
.text-form-row input { flex-basis: 100%; }
|
|
865
865
|
}
|
|
866
|
+
|
|
867
|
+
.clip-assets {
|
|
868
|
+
display: inline-flex;
|
|
869
|
+
align-items: center;
|
|
870
|
+
gap: 4px;
|
|
871
|
+
color: var(--muted);
|
|
872
|
+
font-size: 12px;
|
|
873
|
+
white-space: nowrap;
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
.clip-assets input {
|
|
877
|
+
width: auto;
|
|
878
|
+
height: auto;
|
|
879
|
+
accent-color: var(--accent);
|
|
880
|
+
}
|