dsh-reading-inbox 0.2.1 → 0.3.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.en.md +211 -208
- package/README.md +211 -208
- package/VERIFY.md +133 -126
- package/index.js +80 -80
- package/package.json +83 -83
- package/src/config.js +44 -44
- package/src/fetch.js +173 -173
- package/src/markdown.js +309 -309
- package/src/routes.js +276 -254
- package/src/search.js +109 -0
- package/src/store.js +741 -647
- package/src/tools.js +441 -438
- package/web/app.js +912 -785
- package/web/index.html +83 -74
- package/web/style.css +814 -739
package/src/config.js
CHANGED
|
@@ -1,44 +1,44 @@
|
|
|
1
|
-
import { homedir } from 'node:os'
|
|
2
|
-
import { join, resolve } from 'node:path'
|
|
3
|
-
|
|
4
|
-
export const DEFAULT_DIR = join(homedir(), '.dsh-reading-inbox')
|
|
5
|
-
|
|
6
|
-
function positiveInt(value, fallback) {
|
|
7
|
-
if (value === undefined || value === null || value === '') return fallback
|
|
8
|
-
const parsed = Number(value)
|
|
9
|
-
return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
function expandHome(path) {
|
|
13
|
-
if (path === '~') return homedir()
|
|
14
|
-
if (path.startsWith('~/') || path.startsWith('~\\')) return join(homedir(), path.slice(2))
|
|
15
|
-
return path
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export function loadConfig(env = process.env) {
|
|
19
|
-
const dir = resolve(expandHome(env.DSH_READING_INBOX_DIR || DEFAULT_DIR))
|
|
20
|
-
return {
|
|
21
|
-
dir,
|
|
22
|
-
timeoutMs: positiveInt(env.DSH_READING_INBOX_TIMEOUT_MS, 20_000),
|
|
23
|
-
maxBytes: positiveInt(env.DSH_READING_INBOX_MAX_BYTES, 5 * 1024 * 1024),
|
|
24
|
-
maxMarkdownChars: positiveInt(env.DSH_READING_INBOX_MAX_MARKDOWN_CHARS, 400_000),
|
|
25
|
-
maxRedirects: positiveInt(env.DSH_READING_INBOX_MAX_REDIRECTS, 5),
|
|
26
|
-
allowPrivate: env.DSH_READING_INBOX_ALLOW_PRIVATE === '1' || env.DSH_READING_INBOX_ALLOW_PRIVATE === 'true',
|
|
27
|
-
blockFakeIp:
|
|
28
|
-
env.DSH_READING_INBOX_BLOCK_FAKE_IP === '1' || env.DSH_READING_INBOX_BLOCK_FAKE_IP === 'true',
|
|
29
|
-
userAgent:
|
|
30
|
-
env.DSH_READING_INBOX_USER_AGENT ||
|
|
31
|
-
'dsh-reading-inbox/0.1 (+https://github.com/Bit0620/dsh-reading-inbox)',
|
|
32
|
-
proxy:
|
|
33
|
-
env.DSH_READING_INBOX_PROXY ||
|
|
34
|
-
env.HTTPS_PROXY ||
|
|
35
|
-
env.https_proxy ||
|
|
36
|
-
env.HTTP_PROXY ||
|
|
37
|
-
env.http_proxy ||
|
|
38
|
-
'',
|
|
39
|
-
defaultTags: (env.DSH_READING_INBOX_DEFAULT_TAGS || '')
|
|
40
|
-
.split(',')
|
|
41
|
-
.map(tag => tag.trim())
|
|
42
|
-
.filter(Boolean),
|
|
43
|
-
}
|
|
44
|
-
}
|
|
1
|
+
import { homedir } from 'node:os'
|
|
2
|
+
import { join, resolve } from 'node:path'
|
|
3
|
+
|
|
4
|
+
export const DEFAULT_DIR = join(homedir(), '.dsh-reading-inbox')
|
|
5
|
+
|
|
6
|
+
function positiveInt(value, fallback) {
|
|
7
|
+
if (value === undefined || value === null || value === '') return fallback
|
|
8
|
+
const parsed = Number(value)
|
|
9
|
+
return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function expandHome(path) {
|
|
13
|
+
if (path === '~') return homedir()
|
|
14
|
+
if (path.startsWith('~/') || path.startsWith('~\\')) return join(homedir(), path.slice(2))
|
|
15
|
+
return path
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function loadConfig(env = process.env) {
|
|
19
|
+
const dir = resolve(expandHome(env.DSH_READING_INBOX_DIR || DEFAULT_DIR))
|
|
20
|
+
return {
|
|
21
|
+
dir,
|
|
22
|
+
timeoutMs: positiveInt(env.DSH_READING_INBOX_TIMEOUT_MS, 20_000),
|
|
23
|
+
maxBytes: positiveInt(env.DSH_READING_INBOX_MAX_BYTES, 5 * 1024 * 1024),
|
|
24
|
+
maxMarkdownChars: positiveInt(env.DSH_READING_INBOX_MAX_MARKDOWN_CHARS, 400_000),
|
|
25
|
+
maxRedirects: positiveInt(env.DSH_READING_INBOX_MAX_REDIRECTS, 5),
|
|
26
|
+
allowPrivate: env.DSH_READING_INBOX_ALLOW_PRIVATE === '1' || env.DSH_READING_INBOX_ALLOW_PRIVATE === 'true',
|
|
27
|
+
blockFakeIp:
|
|
28
|
+
env.DSH_READING_INBOX_BLOCK_FAKE_IP === '1' || env.DSH_READING_INBOX_BLOCK_FAKE_IP === 'true',
|
|
29
|
+
userAgent:
|
|
30
|
+
env.DSH_READING_INBOX_USER_AGENT ||
|
|
31
|
+
'dsh-reading-inbox/0.1 (+https://github.com/Bit0620/dsh-reading-inbox)',
|
|
32
|
+
proxy:
|
|
33
|
+
env.DSH_READING_INBOX_PROXY ||
|
|
34
|
+
env.HTTPS_PROXY ||
|
|
35
|
+
env.https_proxy ||
|
|
36
|
+
env.HTTP_PROXY ||
|
|
37
|
+
env.http_proxy ||
|
|
38
|
+
'',
|
|
39
|
+
defaultTags: (env.DSH_READING_INBOX_DEFAULT_TAGS || '')
|
|
40
|
+
.split(',')
|
|
41
|
+
.map(tag => tag.trim())
|
|
42
|
+
.filter(Boolean),
|
|
43
|
+
}
|
|
44
|
+
}
|
package/src/fetch.js
CHANGED
|
@@ -1,173 +1,173 @@
|
|
|
1
|
-
import dns from 'node:dns'
|
|
2
|
-
import iconv from 'iconv-lite'
|
|
3
|
-
import { Agent, ProxyAgent, fetch as undiciFetch } from 'undici'
|
|
4
|
-
import { assertPublicUrl, isPrivateIp } from './security.js'
|
|
5
|
-
|
|
6
|
-
const proxyAgents = new Map()
|
|
7
|
-
const validatingAgents = new Map()
|
|
8
|
-
|
|
9
|
-
function proxyDispatcher(proxyUrl) {
|
|
10
|
-
if (!proxyUrl) return undefined
|
|
11
|
-
let agent = proxyAgents.get(proxyUrl)
|
|
12
|
-
if (agent === undefined) {
|
|
13
|
-
agent = new ProxyAgent(proxyUrl)
|
|
14
|
-
proxyAgents.set(proxyUrl, agent)
|
|
15
|
-
}
|
|
16
|
-
return agent
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
function validatingAgent(blockFakeIp) {
|
|
20
|
-
const key = blockFakeIp ? 'block-fake-ip' : 'allow-fake-ip'
|
|
21
|
-
let agent = validatingAgents.get(key)
|
|
22
|
-
if (agent !== undefined) return agent
|
|
23
|
-
agent = new Agent({
|
|
24
|
-
connect: {
|
|
25
|
-
// assertPublicUrl checks the hostname once, but the socket resolves it
|
|
26
|
-
// again. This lookup is the enforcement point that closes the DNS
|
|
27
|
-
// rebinding window: a second answer pointing at a private address is
|
|
28
|
-
// rejected here, not just at URL validation time.
|
|
29
|
-
lookup(hostname, options, callback) {
|
|
30
|
-
dns.lookup(hostname, { all: true, verbatim: true }, (error, addresses) => {
|
|
31
|
-
if (error) {
|
|
32
|
-
callback(error)
|
|
33
|
-
return
|
|
34
|
-
}
|
|
35
|
-
const allowed = addresses.filter(({ address }) => !isPrivateIp(address, { blockFakeIp }))
|
|
36
|
-
if (allowed.length === 0) {
|
|
37
|
-
callback(new Error(`拒绝连接:${hostname} 解析到内网地址`))
|
|
38
|
-
return
|
|
39
|
-
}
|
|
40
|
-
if (options?.all === true) callback(null, allowed)
|
|
41
|
-
else callback(null, allowed[0].address, allowed[0].family)
|
|
42
|
-
})
|
|
43
|
-
},
|
|
44
|
-
},
|
|
45
|
-
})
|
|
46
|
-
validatingAgents.set(key, agent)
|
|
47
|
-
return agent
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
function dispatcherFor(config, hasInjectedFetch) {
|
|
51
|
-
if (hasInjectedFetch) return undefined
|
|
52
|
-
if (config.allowPrivate === true) return undefined
|
|
53
|
-
if (config.proxy) return proxyDispatcher(config.proxy)
|
|
54
|
-
return validatingAgent(config.blockFakeIp === true)
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
const REDIRECT_STATUS = new Set([301, 302, 303, 307, 308])
|
|
58
|
-
const HTML_TYPES = ['text/html', 'application/xhtml+xml']
|
|
59
|
-
|
|
60
|
-
function signalWithTimeout(signal, timeoutMs) {
|
|
61
|
-
const timeout = AbortSignal.timeout(timeoutMs)
|
|
62
|
-
if (signal === undefined || signal === null) return timeout
|
|
63
|
-
return AbortSignal.any([signal, timeout])
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
function charsetFromContentType(contentType) {
|
|
67
|
-
const match = /charset\s*=\s*["']?([^;"'\s]+)/i.exec(contentType || '')
|
|
68
|
-
return match ? match[1].toLowerCase() : undefined
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
function charsetFromHtml(buffer) {
|
|
72
|
-
const head = buffer.subarray(0, 4096).toString('latin1')
|
|
73
|
-
const meta = /<meta[^>]+charset\s*=\s*["']?([^"'\s/>]+)/i.exec(head)
|
|
74
|
-
if (meta !== null) return meta[1].toLowerCase()
|
|
75
|
-
const httpEquiv = /<meta[^>]+http-equiv\s*=\s*["']?content-type["']?[^>]+content\s*=\s*["'][^"']*charset=([^"'\s;]+)/i.exec(head)
|
|
76
|
-
return httpEquiv !== null ? httpEquiv[1].toLowerCase() : undefined
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
function decodeBody(buffer, contentType) {
|
|
80
|
-
const charset = charsetFromContentType(contentType) || charsetFromHtml(buffer) || 'utf-8'
|
|
81
|
-
try {
|
|
82
|
-
return iconv.decode(buffer, charset)
|
|
83
|
-
} catch {
|
|
84
|
-
return buffer.toString('utf8')
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
async function readCapped(response, maxBytes) {
|
|
89
|
-
if (response.body === null) return Buffer.alloc(0)
|
|
90
|
-
const reader = response.body.getReader()
|
|
91
|
-
const chunks = []
|
|
92
|
-
let total = 0
|
|
93
|
-
try {
|
|
94
|
-
for (;;) {
|
|
95
|
-
const { done, value } = await reader.read()
|
|
96
|
-
if (done) break
|
|
97
|
-
total += value.byteLength
|
|
98
|
-
if (total > maxBytes) {
|
|
99
|
-
await reader.cancel().catch(() => {})
|
|
100
|
-
throw new Error(`页面超过大小上限(${Math.floor(maxBytes / 1024)} KB)`)
|
|
101
|
-
}
|
|
102
|
-
chunks.push(Buffer.from(value))
|
|
103
|
-
}
|
|
104
|
-
} finally {
|
|
105
|
-
reader.releaseLock?.()
|
|
106
|
-
}
|
|
107
|
-
return Buffer.concat(chunks, total)
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
function escapeHtml(text) {
|
|
111
|
-
return text
|
|
112
|
-
.replaceAll('&', '&')
|
|
113
|
-
.replaceAll('<', '<')
|
|
114
|
-
.replaceAll('>', '>')
|
|
115
|
-
.replaceAll('"', '"')
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
/**
|
|
119
|
-
* Fetch an article with a manual redirect loop, per-hop SSRF validation, a
|
|
120
|
-
* byte cap, and charset detection (GBK/Big5 pages are common in the Chinese
|
|
121
|
-
* web). Returns HTML plus the final URL after redirects.
|
|
122
|
-
*/
|
|
123
|
-
export async function fetchHtml(rawUrl, config, options = {}) {
|
|
124
|
-
const dispatcher = dispatcherFor(config, options.fetchImpl !== undefined)
|
|
125
|
-
const fetchImpl = options.fetchImpl ?? undiciFetch
|
|
126
|
-
const signal = signalWithTimeout(options.signal, config.timeoutMs)
|
|
127
|
-
let current = rawUrl
|
|
128
|
-
|
|
129
|
-
for (let hop = 0; hop <= config.maxRedirects; hop += 1) {
|
|
130
|
-
const url = await assertPublicUrl(current, config)
|
|
131
|
-
const response = await fetchImpl(url, {
|
|
132
|
-
redirect: 'manual',
|
|
133
|
-
signal,
|
|
134
|
-
...(dispatcher === undefined ? {} : { dispatcher }),
|
|
135
|
-
headers: {
|
|
136
|
-
'user-agent': config.userAgent,
|
|
137
|
-
accept: 'text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.1',
|
|
138
|
-
'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
|
|
139
|
-
},
|
|
140
|
-
})
|
|
141
|
-
|
|
142
|
-
if (REDIRECT_STATUS.has(response.status)) {
|
|
143
|
-
const location = response.headers.get('location')
|
|
144
|
-
if (location === null) throw new Error(`HTTP ${response.status} 重定向缺少 Location`)
|
|
145
|
-
current = new URL(location, url).toString()
|
|
146
|
-
if (hop === config.maxRedirects) throw new Error('重定向次数过多')
|
|
147
|
-
continue
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
if (!response.ok) {
|
|
151
|
-
throw new Error(`抓取失败:HTTP ${response.status} ${response.statusText}`.trim())
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
const contentType = (response.headers.get('content-type') || '').toLowerCase()
|
|
155
|
-
const buffer = await readCapped(response, config.maxBytes)
|
|
156
|
-
const finalUrl = response.url || url.toString()
|
|
157
|
-
|
|
158
|
-
if (HTML_TYPES.some(type => contentType.includes(type)) || contentType === '') {
|
|
159
|
-
return { html: decodeBody(buffer, contentType), finalUrl, contentType }
|
|
160
|
-
}
|
|
161
|
-
if (contentType.includes('text/plain')) {
|
|
162
|
-
const text = decodeBody(buffer, contentType)
|
|
163
|
-
return {
|
|
164
|
-
html: `<!doctype html><html><head><meta charset="utf-8"></head><body><pre>${escapeHtml(text)}</pre></body></html>`,
|
|
165
|
-
finalUrl,
|
|
166
|
-
contentType,
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
throw new Error(`不支持的内容类型:${contentType.split(';')[0]};目前只支持 HTML/纯文本`)
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
throw new Error('重定向次数过多')
|
|
173
|
-
}
|
|
1
|
+
import dns from 'node:dns'
|
|
2
|
+
import iconv from 'iconv-lite'
|
|
3
|
+
import { Agent, ProxyAgent, fetch as undiciFetch } from 'undici'
|
|
4
|
+
import { assertPublicUrl, isPrivateIp } from './security.js'
|
|
5
|
+
|
|
6
|
+
const proxyAgents = new Map()
|
|
7
|
+
const validatingAgents = new Map()
|
|
8
|
+
|
|
9
|
+
function proxyDispatcher(proxyUrl) {
|
|
10
|
+
if (!proxyUrl) return undefined
|
|
11
|
+
let agent = proxyAgents.get(proxyUrl)
|
|
12
|
+
if (agent === undefined) {
|
|
13
|
+
agent = new ProxyAgent(proxyUrl)
|
|
14
|
+
proxyAgents.set(proxyUrl, agent)
|
|
15
|
+
}
|
|
16
|
+
return agent
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function validatingAgent(blockFakeIp) {
|
|
20
|
+
const key = blockFakeIp ? 'block-fake-ip' : 'allow-fake-ip'
|
|
21
|
+
let agent = validatingAgents.get(key)
|
|
22
|
+
if (agent !== undefined) return agent
|
|
23
|
+
agent = new Agent({
|
|
24
|
+
connect: {
|
|
25
|
+
// assertPublicUrl checks the hostname once, but the socket resolves it
|
|
26
|
+
// again. This lookup is the enforcement point that closes the DNS
|
|
27
|
+
// rebinding window: a second answer pointing at a private address is
|
|
28
|
+
// rejected here, not just at URL validation time.
|
|
29
|
+
lookup(hostname, options, callback) {
|
|
30
|
+
dns.lookup(hostname, { all: true, verbatim: true }, (error, addresses) => {
|
|
31
|
+
if (error) {
|
|
32
|
+
callback(error)
|
|
33
|
+
return
|
|
34
|
+
}
|
|
35
|
+
const allowed = addresses.filter(({ address }) => !isPrivateIp(address, { blockFakeIp }))
|
|
36
|
+
if (allowed.length === 0) {
|
|
37
|
+
callback(new Error(`拒绝连接:${hostname} 解析到内网地址`))
|
|
38
|
+
return
|
|
39
|
+
}
|
|
40
|
+
if (options?.all === true) callback(null, allowed)
|
|
41
|
+
else callback(null, allowed[0].address, allowed[0].family)
|
|
42
|
+
})
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
})
|
|
46
|
+
validatingAgents.set(key, agent)
|
|
47
|
+
return agent
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function dispatcherFor(config, hasInjectedFetch) {
|
|
51
|
+
if (hasInjectedFetch) return undefined
|
|
52
|
+
if (config.allowPrivate === true) return undefined
|
|
53
|
+
if (config.proxy) return proxyDispatcher(config.proxy)
|
|
54
|
+
return validatingAgent(config.blockFakeIp === true)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const REDIRECT_STATUS = new Set([301, 302, 303, 307, 308])
|
|
58
|
+
const HTML_TYPES = ['text/html', 'application/xhtml+xml']
|
|
59
|
+
|
|
60
|
+
function signalWithTimeout(signal, timeoutMs) {
|
|
61
|
+
const timeout = AbortSignal.timeout(timeoutMs)
|
|
62
|
+
if (signal === undefined || signal === null) return timeout
|
|
63
|
+
return AbortSignal.any([signal, timeout])
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function charsetFromContentType(contentType) {
|
|
67
|
+
const match = /charset\s*=\s*["']?([^;"'\s]+)/i.exec(contentType || '')
|
|
68
|
+
return match ? match[1].toLowerCase() : undefined
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function charsetFromHtml(buffer) {
|
|
72
|
+
const head = buffer.subarray(0, 4096).toString('latin1')
|
|
73
|
+
const meta = /<meta[^>]+charset\s*=\s*["']?([^"'\s/>]+)/i.exec(head)
|
|
74
|
+
if (meta !== null) return meta[1].toLowerCase()
|
|
75
|
+
const httpEquiv = /<meta[^>]+http-equiv\s*=\s*["']?content-type["']?[^>]+content\s*=\s*["'][^"']*charset=([^"'\s;]+)/i.exec(head)
|
|
76
|
+
return httpEquiv !== null ? httpEquiv[1].toLowerCase() : undefined
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function decodeBody(buffer, contentType) {
|
|
80
|
+
const charset = charsetFromContentType(contentType) || charsetFromHtml(buffer) || 'utf-8'
|
|
81
|
+
try {
|
|
82
|
+
return iconv.decode(buffer, charset)
|
|
83
|
+
} catch {
|
|
84
|
+
return buffer.toString('utf8')
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function readCapped(response, maxBytes) {
|
|
89
|
+
if (response.body === null) return Buffer.alloc(0)
|
|
90
|
+
const reader = response.body.getReader()
|
|
91
|
+
const chunks = []
|
|
92
|
+
let total = 0
|
|
93
|
+
try {
|
|
94
|
+
for (;;) {
|
|
95
|
+
const { done, value } = await reader.read()
|
|
96
|
+
if (done) break
|
|
97
|
+
total += value.byteLength
|
|
98
|
+
if (total > maxBytes) {
|
|
99
|
+
await reader.cancel().catch(() => {})
|
|
100
|
+
throw new Error(`页面超过大小上限(${Math.floor(maxBytes / 1024)} KB)`)
|
|
101
|
+
}
|
|
102
|
+
chunks.push(Buffer.from(value))
|
|
103
|
+
}
|
|
104
|
+
} finally {
|
|
105
|
+
reader.releaseLock?.()
|
|
106
|
+
}
|
|
107
|
+
return Buffer.concat(chunks, total)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function escapeHtml(text) {
|
|
111
|
+
return text
|
|
112
|
+
.replaceAll('&', '&')
|
|
113
|
+
.replaceAll('<', '<')
|
|
114
|
+
.replaceAll('>', '>')
|
|
115
|
+
.replaceAll('"', '"')
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Fetch an article with a manual redirect loop, per-hop SSRF validation, a
|
|
120
|
+
* byte cap, and charset detection (GBK/Big5 pages are common in the Chinese
|
|
121
|
+
* web). Returns HTML plus the final URL after redirects.
|
|
122
|
+
*/
|
|
123
|
+
export async function fetchHtml(rawUrl, config, options = {}) {
|
|
124
|
+
const dispatcher = dispatcherFor(config, options.fetchImpl !== undefined)
|
|
125
|
+
const fetchImpl = options.fetchImpl ?? undiciFetch
|
|
126
|
+
const signal = signalWithTimeout(options.signal, config.timeoutMs)
|
|
127
|
+
let current = rawUrl
|
|
128
|
+
|
|
129
|
+
for (let hop = 0; hop <= config.maxRedirects; hop += 1) {
|
|
130
|
+
const url = await assertPublicUrl(current, config)
|
|
131
|
+
const response = await fetchImpl(url, {
|
|
132
|
+
redirect: 'manual',
|
|
133
|
+
signal,
|
|
134
|
+
...(dispatcher === undefined ? {} : { dispatcher }),
|
|
135
|
+
headers: {
|
|
136
|
+
'user-agent': config.userAgent,
|
|
137
|
+
accept: 'text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.1',
|
|
138
|
+
'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
|
|
139
|
+
},
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
if (REDIRECT_STATUS.has(response.status)) {
|
|
143
|
+
const location = response.headers.get('location')
|
|
144
|
+
if (location === null) throw new Error(`HTTP ${response.status} 重定向缺少 Location`)
|
|
145
|
+
current = new URL(location, url).toString()
|
|
146
|
+
if (hop === config.maxRedirects) throw new Error('重定向次数过多')
|
|
147
|
+
continue
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (!response.ok) {
|
|
151
|
+
throw new Error(`抓取失败:HTTP ${response.status} ${response.statusText}`.trim())
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const contentType = (response.headers.get('content-type') || '').toLowerCase()
|
|
155
|
+
const buffer = await readCapped(response, config.maxBytes)
|
|
156
|
+
const finalUrl = response.url || url.toString()
|
|
157
|
+
|
|
158
|
+
if (HTML_TYPES.some(type => contentType.includes(type)) || contentType === '') {
|
|
159
|
+
return { html: decodeBody(buffer, contentType), finalUrl, contentType }
|
|
160
|
+
}
|
|
161
|
+
if (contentType.includes('text/plain')) {
|
|
162
|
+
const text = decodeBody(buffer, contentType)
|
|
163
|
+
return {
|
|
164
|
+
html: `<!doctype html><html><head><meta charset="utf-8"></head><body><pre>${escapeHtml(text)}</pre></body></html>`,
|
|
165
|
+
finalUrl,
|
|
166
|
+
contentType,
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
throw new Error(`不支持的内容类型:${contentType.split(';')[0]};目前只支持 HTML/纯文本`)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
throw new Error('重定向次数过多')
|
|
173
|
+
}
|