交付 Windows 与 Web 端到端加密附件预览
This commit is contained in:
1 parent
d1efdedc57
commit
c24960d22a
19 files changed
+421
-58
No files matched your search
+23
-4
@@ -6,20 +6,39 @@ export class APIError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export async function request<T>(path: string, method = 'GET', token = '', body?: object): Promise<T> {
|
||||
export async function request<T>(path: string, method = 'GET', token = '', body?: object, binary = false): Promise<T> {
|
||||
const headers: Record<string, string> = { Accept: 'application/json' }
|
||||
if (token) headers.Authorization = 'Bearer ' + token
|
||||
if (body) headers['Content-Type'] = 'application/json'
|
||||
const bytes = body instanceof ArrayBuffer
|
||||
if (body) headers['Content-Type'] = bytes ? 'application/octet-stream' : 'application/json'
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(base + '/api/v1' + path, {
|
||||
method, headers, body: body ? JSON.stringify(body) : undefined,
|
||||
credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(12000),
|
||||
method, headers, body: bytes ? body : body ? JSON.stringify(body) : undefined,
|
||||
credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(binary || bytes ? 60_000 : 12_000),
|
||||
})
|
||||
} catch {
|
||||
throw new Error('无法连接 XHChat 服务,请检查网络后重试')
|
||||
}
|
||||
if (response.status === 204) return undefined as T
|
||||
if (binary && response.ok) {
|
||||
if (Number(response.headers.get('Content-Length')) > 8 * 1024 * 1024 + 16) throw new Error('附件超过大小限制')
|
||||
const reader = response.body?.getReader()
|
||||
if (!reader) throw new Error('附件下载失败')
|
||||
const chunks: Uint8Array<ArrayBuffer>[] = []
|
||||
let length = 0
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read()
|
||||
if (done) break
|
||||
length += value.byteLength
|
||||
if (length > 8 * 1024 * 1024 + 16) {
|
||||
await reader.cancel()
|
||||
throw new Error('附件超过大小限制')
|
||||
}
|
||||
chunks.push(value)
|
||||
}
|
||||
return await new Blob(chunks).arrayBuffer() as T
|
||||
}
|
||||
const data = await response.json().catch(() => null)
|
||||
if (!response.ok) throw new APIError(response.status, data?.error?.message ?? '请求失败,请稍后重试')
|
||||
return data as T
|
||||
|
||||
Reference in new issue
Block a user