Files
crawler-plugin/frontend-vue/src/shared/utils/download-progress.ts
T
huangzd1997 3987b8d7fe 用户端(四面9分批次): 三条全局错误出口、URL 白名单收口、令牌键单点、uid 短路进门禁
- 此前全树 0 处全局错误处理器:装 app.config.errorHandler + window error + unhandledrejection,
  每条都留可诊断记录、界面只出中文、处理器自身异常不重抛也不白屏(9 例判据)。
- safeHttpUrl 未覆盖的 3 处(两个品牌 Tab 与 useVersionUpdate 直装服务端 file_url)收口;
  令牌键 aiimage_auth_token 由 4 处各自定义 + 2 处内联收成唯一定义点。
- 「localStorage 有 uid 就免校验」改走 auth-gate 单点,剩余例外台账化且同口径必须能抓到
  评审点名的原写法(6 例);卸载配对 3 处补齐 + 全树判据(7 例)。
- task-status-text 把 CANCELLED 显示成"执行中"改对,CANCELED/CANCELLED 两拼写都映射(4 例)。
- 主审计补的四处修复:新判据里两处拿数组和 0 比(怎么写都红);静默 catch 的"用户可见出口"
  符号表认不出本仓 userNotice 与注入式 notify,把真报了用户的 catch 判成静默;
  新错误出口带来的 2 个 try/catch 按棘轮合同写理由进基线(296→298,silent 一格没涨)。
- 验收:node --test 820 例 0 红、npx vue-tsc --noEmit rc=0。
2026-10-09 23:09:37 +08:00

239 lines
7.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { computed, reactive } from 'vue'
import { getPywebviewApi } from '@/shared/bridges/pywebview'
import { isHttpUrl } from './safe-url'
export type DownloadProgressStatus = 'selecting' | 'running' | 'success' | 'failed' | 'cancelled'
export type DownloadProgressItem = {
id: string
filename: string
status: DownloadProgressStatus
path?: string
downloaded: number
total: number
percent: number
error?: string
createdAt: number
updatedAt: number
}
type PywebviewDownloadProgressEvent = {
id: string
status: 'running' | 'success' | 'failed'
path?: string
downloaded: number
total: number
percent: number
error?: string
}
const progressItems = reactive<Record<string, DownloadProgressItem>>({})
let progressListenerBound = false
/** 终态条目自动清理延迟:success/failed 未手动关闭也只保留 2 分钟,防长驻累积 */
const TERMINAL_RETENTION_MS = 2 * 60 * 1000
let sweepTimer: ReturnType<typeof setInterval> | null = null
function sweepTerminalItems() {
const cutoff = now() - TERMINAL_RETENTION_MS
for (const id of Object.keys(progressItems)) {
const item = progressItems[id]
if ((item.status === 'success' || item.status === 'failed') && item.updatedAt <= cutoff) {
delete progressItems[id]
}
}
if (Object.keys(progressItems).length === 0 && sweepTimer) {
clearInterval(sweepTimer)
sweepTimer = null
}
}
function ensureSweepTimer() {
if (sweepTimer || typeof window === 'undefined') return
sweepTimer = setInterval(sweepTerminalItems, 30 * 1000)
}
function normalizePercent(value: number) {
if (!Number.isFinite(value)) return 0
return Math.max(0, Math.min(100, Math.round(value)))
}
function now() {
return Date.now()
}
function upsertProgress(partial: Omit<Partial<DownloadProgressItem>, 'id'> & { id: string }) {
ensureSweepTimer()
const existing = progressItems[partial.id]
const timestamp = now()
progressItems[partial.id] = {
id: partial.id,
filename: partial.filename || existing?.filename || '下载文件',
status: partial.status || existing?.status || 'running',
path: partial.path ?? existing?.path,
downloaded: Number(partial.downloaded ?? existing?.downloaded ?? 0),
total: Number(partial.total ?? existing?.total ?? 0),
percent: normalizePercent(Number(partial.percent ?? existing?.percent ?? 0)),
error: partial.error ?? existing?.error,
createdAt: existing?.createdAt || timestamp,
updatedAt: timestamp,
}
}
function handlePywebviewProgress(event: Event) {
const detail = (event as CustomEvent<PywebviewDownloadProgressEvent>).detail
if (!detail?.id) return
upsertProgress({
id: detail.id,
status: detail.status,
path: detail.path,
downloaded: detail.downloaded,
total: detail.total,
percent: detail.percent,
error: detail.error,
})
}
export function ensureDownloadProgressListener() {
if (progressListenerBound || typeof window === 'undefined') return
progressListenerBound = true
window.addEventListener('pywebview-download-progress', handlePywebviewProgress)
}
/**
* 与 ensureDownloadProgressListener 配对的卸载出口:摘掉桥事件监听并停掉清扫定时器。
* 由根组件 App.vue 的 onBeforeUnmount 调用(判据见 tests/listener-timer-pairing.test.ts)。
*/
export function disposeDownloadProgressListener() {
if (typeof window !== 'undefined' && progressListenerBound) {
window.removeEventListener('pywebview-download-progress', handlePywebviewProgress)
progressListenerBound = false
}
if (sweepTimer !== null) {
clearInterval(sweepTimer)
sweepTimer = null
}
}
export function useDownloadProgress() {
ensureDownloadProgressListener()
const items = computed(() =>
Object.values(progressItems)
.filter((item) => item.status !== 'cancelled')
.sort((a, b) => b.createdAt - a.createdAt),
)
return {
items,
clearDownloadProgress,
}
}
export function clearDownloadProgress(id: string) {
delete progressItems[id]
}
function buildDownloadId(filename: string) {
const safeName = filename.replace(/[^a-zA-Z0-9._-]+/g, '-').slice(0, 60) || 'download'
return `download:${Date.now()}:${Math.random().toString(16).slice(2)}:${safeName}`
}
/** 白名单不通过时的统一说法:进度条目与返回值都用这一句(中文,用户读得懂)。 */
const UNSAFE_DOWNLOAD_URL_TEXT = '下载地址不可用,请稍后重试或在本机客户端中打开'
export async function saveUrlWithProgress(url: string, filename: string, id = buildDownloadId(filename)) {
ensureDownloadProgressListener()
// 服务端/客户端透传的 file_url、downloadUrl 是开放字段,进桥之前先过白名单:
// 校验不过就不发起下载,原因既落进度条目也进控制台留一行可查的记录(判据:tests/url-outlet-guard.test.ts)
if (!isHttpUrl(url)) {
console.warn('[safe-url] 下载地址未通过白名单校验,已取消下载:', String(url).slice(0, 200))
upsertProgress({
id,
filename,
status: 'failed',
downloaded: 0,
total: 0,
percent: 0,
error: UNSAFE_DOWNLOAD_URL_TEXT,
})
return { success: false, error: UNSAFE_DOWNLOAD_URL_TEXT }
}
const api = getPywebviewApi()
if (!api?.save_file_from_url_new) {
upsertProgress({
id,
filename,
status: 'failed',
downloaded: 0,
total: 0,
percent: 0,
error: '当前客户端未提供下载能力',
})
return { success: false, error: '当前客户端未提供下载能力' }
}
upsertProgress({
id,
filename,
status: 'selecting',
downloaded: 0,
total: 0,
percent: 0,
})
const result = api.save_file_from_url_with_progress
? await api.save_file_from_url_with_progress(url, filename, id)
: await api.save_file_from_url_new(url, filename)
if (result.success) {
const existing = progressItems[id]
upsertProgress({
id,
filename,
status: 'success',
path: result.path,
downloaded: existing?.downloaded || existing?.total || 0,
total: existing?.total || existing?.downloaded || 0,
percent: 100,
})
} else if (result.error === '用户取消') {
upsertProgress({
id,
filename,
status: 'cancelled',
downloaded: 0,
total: 0,
percent: 0,
})
clearDownloadProgress(id)
} else {
upsertProgress({
id,
filename,
status: 'failed',
downloaded: 0,
total: 0,
percent: 0,
error: result.error || '下载失败',
})
}
return result
}
export function formatDownloadBytes(value: number) {
const size = Number(value || 0)
if (!Number.isFinite(size) || size <= 0) return '未知大小'
if (size < 1024) return `${size} B`
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`
if (size < 1024 * 1024 * 1024) return `${(size / 1024 / 1024).toFixed(1)} MB`
return `${(size / 1024 / 1024 / 1024).toFixed(2)} GB`
}
export function downloadProgressText(item: DownloadProgressItem) {
if (item.status === 'selecting') return '等待选择保存位置'
if (item.status === 'success') return '下载完成'
if (item.status === 'failed') return item.error || '下载失败'
return item.total > 0 ? '正在下载,请等待完成后再打开' : '正在下载,正在获取文件大小'
}