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>({}) let progressListenerBound = false /** 终态条目自动清理延迟:success/failed 未手动关闭也只保留 2 分钟,防长驻累积 */ const TERMINAL_RETENTION_MS = 2 * 60 * 1000 let sweepTimer: ReturnType | 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, '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).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 ? '正在下载,请等待完成后再打开' : '正在下载,正在获取文件大小' }